1use std::path::{Path, PathBuf};
84use std::time::Duration;
85
86use jiff::Timestamp;
87
88use crate::ask::{Question, QuestionStatus, Questions};
89use crate::config::Config;
90use crate::disk;
91use crate::queue::{HoldSource, OperatorResume, Queue, Task, TaskStatus};
92
93pub const NODE: &str = "triage";
96
97pub const DEPS_NODE: &str = "triage-deps";
101
102const SEAT: &str = "triage";
107
108const MANUAL_STALE_AFTER: Duration = Duration::from_secs(7 * 24 * 60 * 60);
120
121struct Wording {
125 lang: &'static str,
126 resume: &'static str,
127 wait: &'static str,
128 discard: &'static str,
129 resume_now: &'static str,
130 keep_held: &'static str,
131}
132
133const EN: Wording = Wording {
134 lang: "en",
135 resume: "resume it",
136 wait: "not yet",
137 discard: "discard it",
138 resume_now: "resume it",
139 keep_held: "keep it held",
140};
141
142const JA: Wording = Wording {
143 lang: "ja",
144 resume: "再開してよい",
145 wait: "まだ待って",
146 discard: "捨ててよい",
147 resume_now: "再開する",
148 keep_held: "まだ止めておく",
149};
150
151fn wording(language: &str) -> &'static Wording {
154 if crate::lang::is_japanese(language) {
155 &JA
156 } else {
157 &EN
158 }
159}
160
161impl Wording {
162 fn choices3(&self) -> Vec<String> {
163 vec![
164 self.resume.to_owned(),
165 self.wait.to_owned(),
166 self.discard.to_owned(),
167 ]
168 }
169
170 fn choices2(&self) -> Vec<String> {
171 vec![self.resume_now.to_owned(), self.keep_held.to_owned()]
172 }
173
174 fn source_label(&self, source: Option<HoldSource>) -> &'static str {
175 match (self.lang, source) {
176 ("ja", Some(HoldSource::Machine)) => "machine(機械による自動保留)",
177 ("ja", Some(HoldSource::Manual)) => "manual(操作者による手動保留)",
178 ("ja", None) => "unknown(schema 3 未満の旧レコード、または理由未記録)",
179 (_, Some(HoldSource::Machine)) => "machine (automatic recovery hold)",
180 (_, Some(HoldSource::Manual)) => "manual (an operator held this)",
181 (_, None) => "unknown (pre-schema-3 record, or never recorded)",
182 }
183 }
184
185 fn detail(&self, task: &Task, why: &str) -> String {
194 let none = if self.lang == "ja" {
195 "(記録なし)"
196 } else {
197 "(none recorded)"
198 };
199 let reason = task
200 .hold_reason
201 .as_deref()
202 .or(task.last_error.as_deref())
203 .unwrap_or(none);
204 format!(
205 "task: {} ({})\ntitle: {}\nhold source: {}\nhold reason: {reason}\n\n{why}",
206 task.id,
207 task.short(),
208 task.title,
209 self.source_label(task.hold_source),
210 )
211 }
212
213 fn summary_machine_unknown(&self, task: &Task) -> String {
214 if self.lang == "ja" {
215 format!("保留タスク {} の再開可否を判断してください", task.short())
216 } else {
217 format!("decide whether to resume held task {}", task.short())
218 }
219 }
220
221 fn why_machine(&self) -> &'static str {
222 if self.lang == "ja" {
223 "機械的な保留(machine hold)ですが、原因がすでに解消しているかを自動では判断できませんでした。"
224 } else {
225 "This is a machine hold, but whether its cause has resolved could not be \
226 checked automatically."
227 }
228 }
229
230 fn summary_conductor_override(&self, task: &Task) -> String {
231 if self.lang == "ja" {
232 format!(
233 "再開と回答済みのタスク {} を conductor が再び保留しました",
234 task.short()
235 )
236 } else {
237 format!(
238 "task {} was resumed at your word, but the conductor held it again",
239 task.short()
240 )
241 }
242 }
243
244 fn why_conductor_override(&self, o: &OperatorResume) -> String {
245 let reason = o.conductor_rehold.as_deref().unwrap_or_default();
246 if self.lang == "ja" {
247 format!(
248 "{} に再開と回答済みですが、conductor が再び hold しました。conductor の理由: \
249 {reason}\n\n強制再キューを選ぶと、以後 conductor はこのタスクを hold できません。",
250 o.at
251 )
252 } else {
253 format!(
254 "You answered \"resume\" at {}, but the conductor held the task again. \
255 Its reason: {reason}\n\nForcing a requeue stops the conductor from \
256 holding this task again.",
257 o.at
258 )
259 }
260 }
261
262 fn choices_conductor_override(&self) -> Vec<String> {
264 if self.lang == "ja" {
265 vec![
266 "強制再キュー(conductor は再 hold 不可)".to_owned(),
267 "手動 hold のまま".to_owned(),
268 "捨ててよい".to_owned(),
269 ]
270 } else {
271 vec![
272 "force requeue (conductor must not hold again)".to_owned(),
273 "keep held (manual)".to_owned(),
274 "discard".to_owned(),
275 ]
276 }
277 }
278
279 fn summary_legacy(&self, task: &Task) -> String {
280 if self.lang == "ja" {
281 format!(
282 "hold_source が不明な保留タスク {} を確認してください",
283 task.short()
284 )
285 } else {
286 format!(
287 "held task {} has no recorded hold source - please take a look",
288 task.short()
289 )
290 }
291 }
292
293 fn why_legacy(&self) -> &'static str {
294 if self.lang == "ja" {
295 "hold_source が記録されていません。schema 3 より前のレコードか、理由が記録されなかった \
296 holdです。人が意図して止めたのか、クラッシュや強制再起動で宙に浮いただけなのか、\
297 このデータからは区別できません。"
298 } else {
299 "No hold_source was recorded - either a pre-schema-3 record, or a hold whose \
300 reason was never written down. Whether this was a deliberate hold or the \
301 leftover of a crash cannot be told from the data alone."
302 }
303 }
304
305 fn summary_manual_stale(&self, task: &Task, days: i64) -> String {
306 if self.lang == "ja" {
307 format!(
308 "{days}日間 保留されたままの手動保留タスク {} を確認してください",
309 task.short()
310 )
311 } else {
312 format!(
313 "held task {} has been on a manual hold for {days} day(s)",
314 task.short()
315 )
316 }
317 }
318
319 fn why_manual(&self) -> &'static str {
320 if self.lang == "ja" {
321 "操作者が明示的に止めた保留ですが、長期間そのままになっています。まだ止めておくか、\
322 再開するか教えてください。"
323 } else {
324 "An operator held this on purpose, but it has sat untouched for a while. Say \
325 whether to keep holding it or resume it."
326 }
327 }
328}
329
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
332enum Bucket {
333 MachineUnknown,
335 ConductorOverride,
338 Legacy,
340 ManualStale,
342}
343
344#[derive(Debug, Clone, Default)]
346pub struct Report {
347 pub resumed: Vec<String>,
350 pub asked: Vec<String>,
352 pub answered: Vec<String>,
354 pub quarantined: Vec<String>,
359}
360
361impl Report {
362 pub fn is_empty(&self) -> bool {
365 self.resumed.is_empty()
366 && self.asked.is_empty()
367 && self.answered.is_empty()
368 && self.quarantined.is_empty()
369 }
370}
371
372fn repo_for(task: &Task) -> PathBuf {
376 if task.repo.as_os_str().is_empty() {
377 PathBuf::from(".")
378 } else {
379 task.repo.clone()
380 }
381}
382
383fn is_disk_hold(task: &Task) -> bool {
394 task.hold_reason
395 .as_deref()
396 .is_some_and(crate::disk::is_gate_reason)
397}
398
399fn machine_cause_resolved(task: &Task, cfg: &Config) -> Option<bool> {
404 if task
405 .hold_reason
406 .as_deref()
407 .is_some_and(|r| r.starts_with(crate::cache::RESOURCE_HOLD))
408 {
409 return Some(
412 cfg.cache_dir()
413 .is_none_or(|dir| !crate::cache::in_use(&crate::run::home(), &dir)),
414 );
415 }
416 if !is_disk_hold(task) {
417 return None;
418 }
419 let min = cfg.disk.min_free_bytes;
420 if min == 0 {
421 return Some(true);
424 }
425 let free = disk::free_bytes(&repo_for(task)).ok()?;
426 Some(disk::gate(free, min).is_none())
427}
428
429fn manual_is_stale(task: &Task, now: Timestamp) -> bool {
433 now.as_second() - task.updated_at.as_second() > MANUAL_STALE_AFTER.as_secs() as i64
434}
435
436fn marker_for(q: &Question) -> String {
439 format!("[triage:{}]", q.short())
440}
441
442fn already_applied(task: &Task, q: &Question) -> bool {
445 if task.triage_applied(&q.id) {
446 return true;
447 }
448 let marker = marker_for(q);
451 task.hold_reason
452 .as_deref()
453 .is_some_and(|r| r.contains(marker.as_str()))
454}
455
456fn latest_triage_question(questions: &Questions, task_id: &str) -> Option<Question> {
461 latest_question(questions, NODE, task_id)
462}
463
464fn latest_question(questions: &Questions, node: &str, task_id: &str) -> Option<Question> {
466 questions
467 .list()
468 .into_iter()
469 .filter(|q| q.node == node && q.run == task_id)
470 .max_by(|a, b| a.asked_at.cmp(&b.asked_at).then_with(|| a.id.cmp(&b.id)))
473}
474
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
478enum AnswerAction {
479 Resume,
483 Discard,
486 KeepHeld,
491}
492
493fn interpret_answer(q: &Question) -> AnswerAction {
506 let resolution = q.resolution().unwrap_or_default();
507 match q.choices.iter().position(|c| *c == resolution) {
508 Some(0) => AnswerAction::Resume,
509 Some(2) => AnswerAction::Discard,
510 _ => AnswerAction::KeepHeld,
511 }
512}
513
514fn keep_held_note(task: &Task, q: &Question, resolution: &str) -> String {
519 let marker = format!("{} operator: {resolution}", marker_for(q));
520 match task.hold_reason.as_deref() {
521 Some(existing) if !existing.is_empty() => format!("{existing}\n{marker}"),
522 _ => marker,
523 }
524}
525
526fn file_question(
530 questions: &Questions,
531 task: &Task,
532 bucket: Bucket,
533 w: &Wording,
534 now: Timestamp,
535) -> Option<Question> {
536 let (summary, why, choices) = match bucket {
537 Bucket::MachineUnknown => (
538 w.summary_machine_unknown(task),
539 w.why_machine().to_owned(),
540 w.choices3(),
541 ),
542 Bucket::ConductorOverride => (
543 w.summary_conductor_override(task),
544 task.resume_override
545 .as_ref()
546 .map(|o| w.why_conductor_override(o))
547 .unwrap_or_default(),
548 w.choices_conductor_override(),
549 ),
550 Bucket::Legacy => (
551 w.summary_legacy(task),
552 w.why_legacy().to_owned(),
553 w.choices3(),
554 ),
555 Bucket::ManualStale => {
556 let days = (now.as_second() - task.updated_at.as_second()) / (24 * 60 * 60);
557 (
558 w.summary_manual_stale(task, days),
559 w.why_manual().to_owned(),
560 w.choices2(),
561 )
562 }
563 };
564 let mut q = Question::new(
565 task.id.clone(),
566 NODE.to_owned(),
567 SEAT.to_owned(),
568 summary,
569 w.detail(task, &why),
570 choices,
571 );
572 q.triage_generation = Some(task.resumption.as_ref().map_or(0, |r| r.generation));
573 questions.put(&mut q).ok()?;
574 Some(q)
575}
576
577pub(crate) fn deputy_brief(q: &Question, queue: &Queue) -> String {
582 let task = queue.get(&q.run).ok();
583 let mut s = match &task {
584 Some(t) => format!(
585 "Task {} (`magi task show {}`), \"{}\", is {}. Hold source: {}. Reason: {}.",
586 t.id,
587 t.id,
588 t.title,
589 t.status.as_str(),
590 match t.hold_source {
591 Some(HoldSource::Machine) => "machine (an automatic hold)",
592 Some(HoldSource::Manual) => "manual (an operator held it)",
593 None => "unknown (an old record, treated as the operator's)",
594 },
595 t.hold_reason
596 .as_deref()
597 .or(t.last_error.as_deref())
598 .unwrap_or("(none recorded)")
599 ),
600 None => format!("Task {} no longer exists (its record is gone).", q.run),
601 };
602 s.push_str("\n\nWhat each option does, by position (the owner taps a button; you only read their words):");
603 let n = q.choices.len();
604 for (i, c) in q.choices.iter().enumerate() {
605 let effect = if q.node == DEPS_NODE {
606 match i {
607 0 => "the dependency is released so the loop runs it",
608 1 => {
609 "the dependants are detached and the dependency task is DELETED; this cannot be undone"
610 }
611 2 => "the dependants are detached; the dependency stays as it is",
612 _ => "nothing is applied",
613 }
614 } else {
615 match i {
616 0 => "the task is released and requeued",
617 2 if n > 2 => "the task is DELETED; this cannot be undone",
618 _ => "the task stays held, with the answer noted",
619 }
620 };
621 s.push_str(&format!("\n- `{c}`: {effect}"));
622 }
623 s.push_str(
624 "\n\nThe daemon applies the answer on its next pass; you apply nothing. \
625 `magi ask --settle` is refused while the task is held by the operator (a \
626 manual hold, or an old record): an answer must not release or delete \
627 something a person parked. In that case do not retry it - ask the owner \
628 with `--thread` to tap the button themselves. The destructive option is \
629 accepted only for an unhedged, verbatim instruction.",
630 );
631 s
632}
633
634fn quarantine_orphaned_blocked(queue: &Queue, questions: &Questions) -> Vec<String> {
652 let mut quarantined = Vec::new();
653 for listed in queue.list() {
654 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
655 continue;
656 }
657 let Ok(_claim) = queue.claim(&listed.id) else {
658 continue;
659 };
660 let Ok(mut task) = queue.get(&listed.id) else {
661 continue;
662 };
663 if task.status != TaskStatus::Blocked {
664 continue;
665 }
666 let deleted = queue.apply_deleted_blockers(&mut task, questions);
667 if !deleted.is_empty() && queue.put(&mut task).is_ok() {
668 for id in &deleted {
669 queue.note_dependency_deleted(&task, id);
670 }
671 }
672 if task.status != TaskStatus::Blocked {
673 continue;
674 }
675 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
676 if missing.is_empty() {
677 continue;
678 }
679 let language = crate::lang::of_repo(&repo_for(&task));
680 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
681 &task.blocked_by,
682 &missing,
683 &language,
684 )));
685 if queue.put(&mut task).is_ok() {
686 quarantined.push(task.id.clone());
687 }
688 }
689 quarantined
690}
691
692#[derive(Debug, Clone, Copy, PartialEq, Eq)]
695enum DepsAction {
696 Release,
697 Discard,
698 Detach,
699 Nothing,
701}
702
703fn interpret_deps_answer(q: &Question) -> DepsAction {
704 let resolution = q.resolution().unwrap_or_default();
705 match q.choices.iter().position(|c| *c == resolution) {
706 Some(0) => DepsAction::Release,
707 Some(1) => DepsAction::Discard,
708 Some(2) => DepsAction::Detach,
709 _ => DepsAction::Nothing,
710 }
711}
712
713fn deps_texts(w: &Wording, root: &Task, dependants: &[&Task]) -> (String, String, Vec<String>) {
715 let ja = w.lang == "ja";
716 let reason = root
717 .hold_reason
718 .as_deref()
719 .or(root.last_error.as_deref())
720 .unwrap_or(if ja {
721 "(記録なし)"
722 } else {
723 "(none recorded)"
724 });
725 let list: String = dependants
726 .iter()
727 .map(|t| format!("- {} {}\n", t.short(), t.title))
728 .collect();
729 if ja {
730 (
731 format!(
732 "{} ({}) が {} 件のタスクを止めています",
733 root.short(),
734 root.status.as_str(),
735 dependants.len()
736 ),
737 format!(
738 "task: {} ({})\ntitle: {}\n状態: {}\n理由: {reason}\n\n\
739 このタスクは自動では実行されないため、依存している次のタスクは永遠に待ち続けます:\n{list}",
740 root.id,
741 root.short(),
742 root.title,
743 root.status.as_str()
744 ),
745 vec![
746 "依存先を再開する".to_owned(),
747 "依存先を捨てる(依存タスクは切り離して実行)".to_owned(),
748 "依存タスクを切り離す(依存先はそのまま)".to_owned(),
749 ],
750 )
751 } else {
752 (
753 format!(
754 "{} ({}) is freezing {} blocked task(s)",
755 root.short(),
756 root.status.as_str(),
757 dependants.len()
758 ),
759 format!(
760 "task: {} ({})\ntitle: {}\nstatus: {}\nreason: {reason}\n\n\
761 Nothing in the loop will ever run this task, so these dependants wait \
762 forever:\n{list}",
763 root.id,
764 root.short(),
765 root.title,
766 root.status.as_str()
767 ),
768 vec![
769 "release the dependency".to_owned(),
770 "discard the dependency (dependants are detached and run)".to_owned(),
771 "detach the dependants (the dependency stays as it is)".to_owned(),
772 ],
773 )
774 }
775}
776
777fn detach_dependants(queue: &Queue, questions: &Questions, root: &str) {
781 for listed in queue.list() {
782 if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| matches!(crate::queue::dependency(queue, questions, b), crate::queue::Dependency::Task(id) if id == root)) {
783 continue;
784 }
785 let Ok(_claim) = queue.claim(&listed.id) else {
786 continue;
787 };
788 let Ok(mut t) = queue.get(&listed.id) else {
789 continue;
790 };
791 if t.status != TaskStatus::Blocked {
792 continue;
793 }
794 for id in t.blocked_by.clone() {
795 if matches!(crate::queue::dependency(queue, questions, &id), crate::queue::Dependency::Task(full) if full == root)
796 {
797 t.unblock(&id);
798 }
799 }
800 let _ = queue.put(&mut t);
801 }
802}
803
804fn apply_deps_answer(queue: &Queue, questions: &Questions, q: &Question, now: Timestamp) -> bool {
808 let Ok(_claim) = queue.claim(&q.run) else {
809 return false;
810 };
811 let Ok(mut root) = queue.get(&q.run) else {
812 return false;
813 };
814 if root.triage_applied(&q.id) {
815 return false;
816 }
817 if root.operator_decided_at.is_some_and(|at| at > q.asked_at)
818 || q.triage_generation
819 .is_some_and(|g| g != root.resumption.as_ref().map_or(0, |r| r.generation))
820 {
821 root.mark_triage_applied(&q.id);
822 return queue.put(&mut root).is_ok();
823 }
824 match interpret_deps_answer(q) {
825 DepsAction::Release => {
826 if root.status == TaskStatus::Running {
827 return false;
828 }
829 root.answers.push(crate::queue::AnsweredQuestion {
830 question: q.summary.clone(),
831 answer: q.resolution().unwrap_or_default(),
832 });
833 root.release_operator("triage-dependencies", Some(&q.id));
834 root.resume_override = Some(OperatorResume {
835 question_id: q.id.clone(),
836 at: now,
837 conductor_rehold: None,
838 forced: false,
839 pinned_run: None,
840 });
841 }
842 DepsAction::Discard => {
843 detach_dependants(queue, questions, &root.id);
844 return queue.remove(&root.id, false, questions).is_ok();
845 }
846 DepsAction::Detach => detach_dependants(queue, questions, &root.id),
847 DepsAction::Nothing => return false,
852 }
853 root.mark_triage_applied(&q.id);
854 queue.put(&mut root).is_ok()
855}
856
857fn ask_about_stuck_roots(
866 queue: &Queue,
867 questions: &Questions,
868 config_override: Option<&Path>,
869 report: &mut Report,
870) {
871 let all = questions.list();
872 let inv = crate::blockers::Inventory::load(queue, questions);
873 let mut frozen: std::collections::BTreeMap<String, Vec<String>> = Default::default();
874 for (id, roots) in inv.stuck() {
875 for root in roots {
876 if root != id {
877 frozen.entry(root).or_default().push(id.clone());
878 }
879 }
880 }
881 for mut q in all
885 .iter()
886 .filter(|q| q.node == DEPS_NODE && q.status.open())
887 .cloned()
888 {
889 if !frozen.contains_key(&q.run) {
890 q.abandon("nothing waits on this task anymore");
891 let _ = questions.put(&mut q);
892 }
893 }
894
895 for (root_id, dependant_ids) in &frozen {
896 let Ok(_claim) = queue.claim(root_id) else {
897 continue;
898 };
899 let current = crate::blockers::Inventory::load(queue, questions);
902 let Some(root) = current.task(root_id) else {
903 continue;
904 };
905 let dependants: Vec<&Task> = dependant_ids
906 .iter()
907 .filter_map(|d| current.task(d))
908 .filter(|t| current.stuck_roots(t).contains(root_id))
909 .collect();
910 if dependants.is_empty() {
911 continue;
912 }
913 let latest = all
914 .iter()
915 .filter(|q| q.node == DEPS_NODE && q.run == *root_id)
916 .max_by(|a, b| a.asked_at.cmp(&b.asked_at).then_with(|| a.id.cmp(&b.id)));
917 match latest {
918 Some(q) if q.status.open() => continue,
919 Some(q) if q.status == QuestionStatus::Answered && !root.triage_applied(&q.id) => {
920 continue;
921 }
922 Some(q) if q.status == QuestionStatus::Abandoned => {
923 let changed = root.updated_at > q.asked_at
924 || dependants.iter().any(|t| t.updated_at > q.asked_at);
925 if !changed {
926 continue;
927 }
928 }
929 _ => {}
930 }
931 if pending_for(questions, root) {
932 continue;
933 }
934 let cfg = Config::discover(&repo_for(root), config_override)
935 .ok()
936 .map(|(c, _)| c);
937 let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
938 let (summary, detail, choices) = deps_texts(w, root, &dependants);
939 let mut question = Question::new(
940 root.id.clone(),
941 DEPS_NODE.to_owned(),
942 SEAT.to_owned(),
943 summary,
944 detail,
945 choices,
946 );
947 question.triage_generation = Some(root.resumption.as_ref().map_or(0, |r| r.generation));
948 if questions.put(&mut question).is_ok() {
949 report.asked.push(root.id.clone());
950 }
951 }
952}
953
954pub fn apply_answers(queue: &Queue, questions: &Questions) -> Vec<String> {
957 let mut applied = Vec::new();
958 for q in questions.list() {
959 if q.node == DEPS_NODE
960 && q.status == QuestionStatus::Answered
961 && apply_deps_answer(queue, questions, &q, Timestamp::now())
962 {
963 applied.push(q.run.clone());
964 }
965 }
966 for listed in queue.list() {
967 let Some(q) = latest_triage_question(questions, &listed.id) else {
968 continue;
969 };
970 if q.status != QuestionStatus::Answered || already_applied(&listed, &q) {
971 continue;
972 }
973 let Ok(_claim) = queue.claim(&listed.id) else {
974 continue;
975 };
976 let Ok(mut task) = queue.get(&listed.id) else {
977 continue;
978 };
979 if already_applied(&task, &q)
980 || !matches!(task.status, TaskStatus::Held | TaskStatus::Queued)
981 {
982 continue;
983 }
984 let generation = task.resumption.as_ref().map_or(0, |r| r.generation);
985 let action = interpret_answer(&q);
986 let mut newer_decision = q.triage_generation.is_some_and(|g| g != generation)
987 || task.resumption.as_ref().is_some_and(|r| r.at > q.asked_at)
988 || task.held_at.is_some_and(|at| at > q.asked_at)
989 || task.operator_decided_at.is_some_and(|at| at > q.asked_at);
990 if matches!(action, AnswerAction::KeepHeld)
994 && q.answered_at.is_some_and(|at| {
995 task.operator_decided_at
996 .is_none_or(|decision| at > decision)
997 && task.resumption.as_ref().is_none_or(|r| at > r.at)
998 })
999 {
1000 newer_decision = false;
1001 }
1002 let resolution = q.resolution().unwrap_or_default();
1004 task.answers.push(crate::queue::AnsweredQuestion {
1005 question: q.summary.clone(),
1006 answer: if newer_decision {
1007 format!("{resolution} (superseded by a later operator decision)")
1008 } else {
1009 resolution
1010 },
1011 });
1012 if !newer_decision {
1013 match action {
1014 AnswerAction::Resume => {
1015 task.release_operator("triage", Some(&q.id));
1016 task.resume_override = Some(OperatorResume {
1017 question_id: q.id.clone(),
1018 at: Timestamp::now(),
1019 conductor_rehold: None,
1020 forced: true,
1021 pinned_run: None,
1022 });
1023 }
1024 AnswerAction::KeepHeld => {
1025 let note = keep_held_note(&task, &q, &q.resolution().unwrap_or_default());
1026 task.hold_manual(Some(note));
1027 }
1028 AnswerAction::Discard => {
1029 if queue.remove(&task.id, false, questions).is_ok() {
1030 applied.push(task.id);
1031 }
1032 continue;
1033 }
1034 }
1035 }
1036 task.mark_triage_applied(&q.id);
1037 if queue.put(&mut task).is_ok() {
1038 applied.push(task.id);
1039 }
1040 }
1041 applied
1042}
1043
1044pub fn run_once(
1062 queue: &Queue,
1063 questions: &Questions,
1064 config_override: Option<&Path>,
1065 now: Timestamp,
1066) -> Report {
1067 let mut report = Report {
1068 answered: apply_answers(queue, questions),
1069 quarantined: quarantine_orphaned_blocked(queue, questions),
1070 ..Report::default()
1071 };
1072 ask_about_stuck_roots(queue, questions, config_override, &mut report);
1073 for listed in queue.list() {
1074 if listed.status != TaskStatus::Held {
1075 continue;
1076 }
1077 let Ok(_claim) = queue.claim(&listed.id) else {
1078 continue;
1079 };
1080 let Ok(mut task) = queue.get(&listed.id) else {
1081 continue;
1082 };
1083 if task.status != TaskStatus::Held {
1087 continue;
1088 }
1089 if deps_pending(questions, &task) {
1093 continue;
1094 }
1095
1096 let cfg = Config::discover(&repo_for(&task), config_override)
1097 .ok()
1098 .map(|(c, _)| c);
1099 let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
1100
1101 if let Some(q) = latest_triage_question(questions, &task.id) {
1102 if q.status.open() {
1103 continue;
1105 }
1106 }
1112
1113 match task.hold_source {
1114 Some(HoldSource::Machine) => {
1115 let overridden = task
1116 .resume_override
1117 .as_ref()
1118 .is_some_and(|o| o.conductor_rehold.is_some() && !o.forced);
1119 if overridden {
1120 if file_question(questions, &task, Bucket::ConductorOverride, w, now).is_some()
1121 {
1122 report.asked.push(task.id.clone());
1123 }
1124 } else if cfg.as_ref().and_then(|c| machine_cause_resolved(&task, c)) == Some(true)
1125 {
1126 task.release();
1127 if queue.put(&mut task).is_ok() {
1128 report.resumed.push(task.id.clone());
1129 }
1130 } else if file_question(questions, &task, Bucket::MachineUnknown, w, now).is_some()
1131 {
1132 report.asked.push(task.id.clone());
1133 }
1134 }
1135 None => {
1136 if file_question(questions, &task, Bucket::Legacy, w, now).is_some() {
1137 report.asked.push(task.id.clone());
1138 }
1139 }
1140 Some(HoldSource::Manual) => {
1141 if manual_is_stale(&task, now)
1142 && file_question(questions, &task, Bucket::ManualStale, w, now).is_some()
1143 {
1144 report.asked.push(task.id.clone());
1145 }
1146 }
1147 }
1148 }
1149 report
1150}
1151
1152pub fn open_question_for(questions: &Questions, task_id: &str) -> Option<Question> {
1157 latest_triage_question(questions, task_id).filter(|q| q.status.open())
1158}
1159
1160pub fn pending_for(questions: &Questions, task: &Task) -> bool {
1174 let own = match latest_triage_question(questions, &task.id) {
1175 Some(q) if q.status.open() => true,
1176 Some(q) if q.status == QuestionStatus::Answered => !already_applied(task, &q),
1177 _ => false,
1178 };
1179 own || deps_pending(questions, task)
1180}
1181
1182fn deps_pending(questions: &Questions, task: &Task) -> bool {
1186 match latest_question(questions, DEPS_NODE, &task.id) {
1187 Some(q) if q.status.open() => true,
1188 Some(q) if q.status == QuestionStatus::Answered => !task.triage_applied(&q.id),
1189 _ => false,
1190 }
1191}
1192
1193pub fn open_task_ids(questions: &Questions) -> std::collections::BTreeSet<String> {
1198 questions
1199 .list()
1200 .into_iter()
1201 .filter(|q| (q.node == NODE || q.node == DEPS_NODE) && q.status.open())
1202 .map(|q| q.run)
1203 .collect()
1204}
1205
1206#[cfg(test)]
1207mod tests {
1208 use super::*;
1209 use crate::ask::Answer;
1210 use crate::queue::Source;
1211 use jiff::SignedDuration;
1212
1213 fn store() -> (tempfile::TempDir, Queue, Questions) {
1214 let dir = tempfile::tempdir().unwrap();
1215 let q = Queue::at(dir.path().join("queue"));
1216 let s = Questions::at(dir.path().join("questions"));
1217 (dir, q, s)
1218 }
1219
1220 fn task(title: &str, repo: PathBuf) -> Task {
1221 Task::new(title.to_owned(), format!("do {title}"), repo, Source::Human)
1222 }
1223
1224 fn gate_disabled_config(dir: &std::path::Path) -> PathBuf {
1228 let config = dir.join("magi.toml");
1229 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
1230 config
1231 }
1232
1233 #[test]
1234 fn resumption_later_keep_held_answer_wins_but_an_older_answer_cannot_undo_release() {
1235 for source in ["cli", "web"] {
1236 for answer_after_release in [true, false] {
1237 let (dir, queue, questions) = store();
1238 let mut t = task("recovery", dir.path().join("repo"));
1239 t.hold_machine(Some("inspect remote first".into()));
1240 queue.put(&mut t).unwrap();
1241 let mut q = file_question(
1242 &questions,
1243 &t,
1244 Bucket::MachineUnknown,
1245 &JA,
1246 Timestamp::now(),
1247 )
1248 .unwrap();
1249 if !answer_after_release {
1250 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
1251 questions.put(&mut q).unwrap();
1252 }
1253 t.release_operator(source, None);
1254 queue.put(&mut t).unwrap();
1255 if answer_after_release {
1256 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
1257 questions.put(&mut q).unwrap();
1258 }
1259 apply_answers(&queue, &questions);
1260 let after = queue.get(&t.id).unwrap();
1261 assert!(after.triage_applied(&q.id));
1262 assert_eq!(after.operator_held(), answer_after_release);
1263 assert_eq!(
1264 after.status,
1265 if answer_after_release {
1266 TaskStatus::Held
1267 } else {
1268 TaskStatus::Queued
1269 }
1270 );
1271 assert!(apply_answers(&queue, &questions).is_empty());
1272 }
1273 }
1274 }
1275
1276 #[test]
1277 fn explicit_resumption_applies_legacy_queued_triage_once_and_preserves_later_holds() {
1278 let (dir, queue, questions) = store();
1279 let mut t = task("recover", dir.path().join("repo"));
1280 t.hold_machine(Some("inspect first".into()));
1281 queue.put(&mut t).unwrap();
1282 let mut q = file_question(
1283 &questions,
1284 &t,
1285 Bucket::MachineUnknown,
1286 &JA,
1287 Timestamp::now(),
1288 )
1289 .unwrap();
1290 assert!(q.actions.is_empty());
1291 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
1292 questions.put(&mut q).unwrap();
1293 t.release();
1295 t.instruction = "Reuse approved PR head".into();
1296 queue.put(&mut t).unwrap();
1297 assert_eq!(apply_answers(&queue, &questions), [t.id.clone()]);
1298 let mut after = queue.get(&t.id).unwrap();
1299 assert_eq!(
1300 after.resumption.as_ref().unwrap().question_id.as_deref(),
1301 Some(q.id.as_str())
1302 );
1303 assert_eq!(
1304 after.resumption.as_ref().unwrap().instruction,
1305 t.instruction
1306 );
1307 assert_eq!(after.answers[0].answer, JA.resume);
1308 assert!(after.triage_applied(&q.id));
1309 assert!(apply_answers(&Queue::at(dir.path().join("queue")), &questions).is_empty());
1310 after.hold_machine(Some("new blocker".into()));
1311 queue.put(&mut after).unwrap();
1312 let mut late = file_question(
1313 &questions,
1314 &after,
1315 Bucket::MachineUnknown,
1316 &EN,
1317 Timestamp::now(),
1318 )
1319 .unwrap();
1320 after.hold_manual(Some("keep held now".into()));
1321 queue.put(&mut after).unwrap();
1322 late.answer(Answer::Choice(late.choices[0].clone()))
1323 .unwrap();
1324 questions.put(&mut late).unwrap();
1325 apply_answers(&queue, &questions);
1326 let held = queue.get(&t.id).unwrap();
1327 assert!(held.operator_held());
1328 assert_eq!(held.hold_reason.as_deref(), Some("keep held now"));
1329 assert_eq!(held.resumption.as_ref().unwrap().generation, 1);
1330 }
1331
1332 #[test]
1333 fn a_resolved_machine_hold_is_requeued_automatically() {
1334 let (dir, q, questions) = store();
1335 let config = gate_disabled_config(dir.path());
1336 let mut t = task("disk pressure", dir.path().join("repo"));
1337 t.hold_machine(Some(
1338 "not enough free space to start a run: 10 bytes free, 100 required by \
1339 `[disk] min_free_bytes`"
1340 .to_owned(),
1341 ));
1342 q.put(&mut t).unwrap();
1343
1344 let report = run_once(&q, &questions, Some(&config), Timestamp::now());
1345 assert_eq!(report.resumed, [t.id.clone()]);
1346 assert!(report.asked.is_empty());
1347
1348 let back = q.get(&t.id).unwrap();
1349 assert_eq!(back.status, TaskStatus::Queued);
1350 assert!(back.hold_source.is_none());
1351 assert!(questions.list().is_empty(), "nothing needed asking");
1352 }
1353
1354 #[test]
1355 fn a_machine_hold_with_no_recognised_cause_gets_one_question_not_two() {
1356 let (dir, q, questions) = store();
1357 let mut t = task("gate went red", dir.path().join("repo"));
1358 t.hold_machine(Some("gate red".to_owned()));
1359 q.put(&mut t).unwrap();
1360
1361 let first = run_once(&q, &questions, None, Timestamp::now());
1362 assert_eq!(first.asked, [t.id.clone()]);
1363 assert!(first.resumed.is_empty());
1364
1365 let open: Vec<_> = questions
1366 .list()
1367 .into_iter()
1368 .filter(|q| q.status.open())
1369 .collect();
1370 assert_eq!(open.len(), 1);
1371 assert_eq!(open[0].run, t.id);
1372 assert_eq!(open[0].node, NODE);
1373 assert_eq!(open[0].choices.len(), 3);
1374
1375 let second = run_once(&q, &questions, None, Timestamp::now());
1377 assert!(second.asked.is_empty());
1378 assert_eq!(
1379 questions
1380 .list()
1381 .into_iter()
1382 .filter(|q| q.status.open())
1383 .count(),
1384 1
1385 );
1386 }
1387
1388 #[test]
1389 fn a_legacy_hold_with_no_recorded_source_gets_exactly_one_question() {
1390 let (dir, q, questions) = store();
1391 let mut t = task("schema 1 record", dir.path().join("repo"));
1392 t.status = TaskStatus::Held;
1393 assert!(t.hold_source.is_none(), "the case this test is about");
1394 q.put(&mut t).unwrap();
1395
1396 let first = run_once(&q, &questions, None, Timestamp::now());
1397 assert_eq!(first.asked, [t.id.clone()]);
1398
1399 let second = run_once(&q, &questions, None, Timestamp::now());
1400 assert!(
1401 second.asked.is_empty(),
1402 "the same legacy hold must not be asked about twice"
1403 );
1404 assert_eq!(
1405 questions
1406 .list()
1407 .into_iter()
1408 .filter(|q| q.status.open())
1409 .count(),
1410 1
1411 );
1412 }
1413
1414 #[test]
1415 fn dependency_resolution_detaches_legacy_short_refs_without_dropping_other_waits() {
1416 let (dir, queue, questions) = store();
1417 let mut root = task("root", dir.path().join("repo"));
1418 root.id = "20261013-193611-ca5b".into();
1419 root.hold_machine(Some("needs owner decision".into()));
1420 queue.put(&mut root).unwrap();
1421 let mut other = task("other", dir.path().join("repo"));
1422 other.id = "20261013-192213-feb2".into();
1423 queue.put(&mut other).unwrap();
1424 let mut waiting = task("waiting", dir.path().join("repo"));
1425 waiting.block(vec!["ca5b".into(), other.id.clone()], None);
1426 queue.put(&mut waiting).unwrap();
1427 detach_dependants(&queue, &questions, &root.id);
1428 let after = queue.get(&waiting.id).unwrap();
1429 assert_eq!(after.status, TaskStatus::Blocked);
1430 assert_eq!(after.blocked_by, [other.id]);
1431 }
1432
1433 #[test]
1434 fn a_manual_hold_is_never_auto_resumed() {
1435 let (dir, q, questions) = store();
1436 let mut t = task("operator stopped this", dir.path().join("repo"));
1437 t.hold_manual(Some("waiting on a decision".to_owned()));
1438 q.put(&mut t).unwrap();
1439
1440 let report = run_once(&q, &questions, None, Timestamp::now());
1441 assert!(report.resumed.is_empty());
1442 assert!(report.asked.is_empty());
1444
1445 let back = q.get(&t.id).unwrap();
1446 assert_eq!(back.status, TaskStatus::Held);
1447 assert_eq!(back.hold_source, Some(HoldSource::Manual));
1448 assert!(questions.list().is_empty());
1449 }
1450
1451 #[test]
1452 fn a_blocked_task_on_a_deleted_dependency_is_held_and_asked_about_in_one_pass() {
1453 let (dir, q, questions) = store();
1458 let mut still_going = task("still valid", dir.path().join("repo"));
1459 q.put(&mut still_going).unwrap();
1460
1461 let mut t = task("orphaned", dir.path().join("repo"));
1462 t.block(
1463 vec!["20260101-000000-gone".to_owned(), still_going.id.clone()],
1464 Some("waits on both".to_owned()),
1465 );
1466 q.put(&mut t).unwrap();
1467
1468 let report = run_once(&q, &questions, None, Timestamp::now());
1469 assert_eq!(report.quarantined, [t.id.clone()]);
1470 assert_eq!(
1471 report.asked,
1472 [t.id.clone()],
1473 "the fresh machine hold must earn a question in the same pass"
1474 );
1475
1476 let after = q.get(&t.id).unwrap();
1477 assert_eq!(after.status, TaskStatus::Held);
1478 assert_eq!(after.hold_source, Some(HoldSource::Machine));
1479 assert!(after.blocked_by.is_empty());
1480
1481 assert!(!is_disk_hold(&after));
1484
1485 let open: Vec<_> = questions
1486 .list()
1487 .into_iter()
1488 .filter(|q| q.status.open())
1489 .collect();
1490 assert_eq!(open.len(), 1);
1491 assert_eq!(open[0].run, t.id);
1492
1493 let second = run_once(&q, &questions, None, Timestamp::now());
1495 assert!(second.quarantined.is_empty());
1496 assert!(second.asked.is_empty());
1497 }
1498
1499 fn stuck_chain(q: &Queue, dir: &std::path::Path) -> (Task, Task, Task) {
1502 let mut root = task("root", dir.join("repo"));
1503 root.hold_manual(Some("waiting".to_owned()));
1504 q.put(&mut root).unwrap();
1505 let mut mid = task("mid", dir.join("repo"));
1506 mid.block(vec![root.id.clone()], None);
1507 q.put(&mut mid).unwrap();
1508 let mut leaf = task("leaf", dir.join("repo"));
1509 leaf.block(vec![mid.id.clone()], None);
1510 q.put(&mut leaf).unwrap();
1511 (root, mid, leaf)
1512 }
1513
1514 fn deps_questions(questions: &Questions) -> Vec<Question> {
1515 questions
1516 .list()
1517 .into_iter()
1518 .filter(|q| q.node == DEPS_NODE)
1519 .collect()
1520 }
1521
1522 fn answer_deps(questions: &Questions, choice: usize) {
1523 let mut asked = deps_questions(questions).remove(0);
1524 let c = asked.choices[choice].clone();
1525 asked.answer(Answer::Choice(c)).unwrap();
1526 questions.put(&mut asked).unwrap();
1527 }
1528
1529 #[test]
1530 fn a_stuck_chain_earns_one_question_naming_every_dependant_and_is_not_reasked() {
1531 let (dir, q, questions) = store();
1532 let (root, mid, leaf) = stuck_chain(&q, dir.path());
1533
1534 let first = run_once(&q, &questions, None, Timestamp::now());
1535 assert_eq!(first.asked, std::slice::from_ref(&root.id));
1536 let asked = deps_questions(&questions);
1537 assert_eq!(asked.len(), 1, "one question per root, not per dependant");
1538 assert_eq!(asked[0].run, root.id);
1539 assert_eq!(asked[0].choices.len(), 3);
1540 assert!(asked[0].detail.contains(mid.short()), "{}", asked[0].detail);
1541 assert!(
1542 asked[0].detail.contains(leaf.short()),
1543 "{}",
1544 asked[0].detail
1545 );
1546
1547 let second = run_once(&q, &questions, None, Timestamp::now());
1548 assert!(second.asked.is_empty());
1549 assert_eq!(deps_questions(&questions).len(), 1);
1550 assert!(pending_for(&questions, &q.get(&root.id).unwrap()));
1551 }
1552
1553 #[test]
1554 fn a_stuck_root_with_a_machine_hold_gets_only_the_dependency_question() {
1555 let (dir, q, questions) = store();
1556 let mut root = task("root", dir.path().join("repo"));
1557 root.hold_machine(Some("gate red".to_owned()));
1558 q.put(&mut root).unwrap();
1559 let mut dep = task("dep", dir.path().join("repo"));
1560 dep.block(vec![root.id.clone()], None);
1561 q.put(&mut dep).unwrap();
1562
1563 run_once(&q, &questions, None, Timestamp::now());
1564 run_once(&q, &questions, None, Timestamp::now());
1565 assert_eq!(deps_questions(&questions).len(), 1);
1566 assert_eq!(
1567 questions.list().len(),
1568 1,
1569 "no second question about the hold"
1570 );
1571 }
1572
1573 #[test]
1574 fn a_dependency_that_can_still_run_asks_nothing() {
1575 let (dir, q, questions) = store();
1576 let mut live = task("live", dir.path().join("repo"));
1577 q.put(&mut live).unwrap();
1578 let mut dep = task("dep", dir.path().join("repo"));
1579 dep.block(vec![live.id.clone()], None);
1580 q.put(&mut dep).unwrap();
1581 let report = run_once(&q, &questions, None, Timestamp::now());
1582 assert!(report.asked.is_empty());
1583 assert!(questions.list().is_empty());
1584 }
1585
1586 #[test]
1587 fn answering_release_requeues_the_root_and_is_not_reasked() {
1588 let (dir, q, questions) = store();
1589 let (root, _mid, _leaf) = stuck_chain(&q, dir.path());
1590 run_once(&q, &questions, None, Timestamp::now());
1591 answer_deps(&questions, 0);
1592
1593 let report = run_once(&q, &questions, None, Timestamp::now());
1594 assert_eq!(report.answered, std::slice::from_ref(&root.id));
1595 assert!(report.asked.is_empty(), "applying must not re-ask");
1596 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Queued);
1597 let again = run_once(&q, &questions, None, Timestamp::now());
1598 assert!(again.asked.is_empty() && again.answered.is_empty());
1599 assert_eq!(deps_questions(&questions).len(), 1);
1600 }
1601
1602 #[test]
1603 fn answering_detach_frees_the_direct_dependant_and_keeps_the_root() {
1604 let (dir, q, questions) = store();
1605 let (root, mid, leaf) = stuck_chain(&q, dir.path());
1606 run_once(&q, &questions, None, Timestamp::now());
1607 answer_deps(&questions, 2);
1608
1609 let report = run_once(&q, &questions, None, Timestamp::now());
1610 assert!(report.asked.is_empty());
1611 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
1612 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
1613 let leaf = q.get(&leaf.id).unwrap();
1614 assert_eq!(leaf.status, TaskStatus::Blocked, "still waits on mid");
1615 assert_eq!(leaf.blocked_by, std::slice::from_ref(&mid.id));
1616 }
1617
1618 #[test]
1619 fn a_dependant_that_can_progress_through_another_blocker_is_not_stuck() {
1620 let (dir, q, questions) = store();
1621 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
1622 let mut live = task("live", dir.path().join("repo"));
1623 q.put(&mut live).unwrap();
1624 let mut both = q.get(&mid.id).unwrap();
1625 both.block(vec![root.id.clone(), live.id.clone()], None);
1626 q.put(&mut both).unwrap();
1627 assert!(
1629 run_once(&q, &questions, None, Timestamp::now())
1630 .asked
1631 .is_empty()
1632 );
1633 }
1634
1635 #[test]
1636 fn answering_discard_detaches_then_removes_the_root() {
1637 let (dir, q, questions) = store();
1638 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
1639 run_once(&q, &questions, None, Timestamp::now());
1640 answer_deps(&questions, 1);
1641
1642 let report = run_once(&q, &questions, None, Timestamp::now());
1643 assert!(q.get(&root.id).is_err());
1644 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
1645 assert!(
1646 report.asked.is_empty(),
1647 "no per-dependant quarantine question"
1648 );
1649 assert!(report.quarantined.is_empty());
1650 }
1651
1652 #[test]
1653 fn an_unmatched_deps_answer_changes_nothing_and_is_not_reasked() {
1654 let (dir, q, questions) = store();
1655 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
1656 run_once(&q, &questions, None, Timestamp::now());
1657 let mut asked = deps_questions(&questions).remove(0);
1658 asked.choices.clear();
1659 asked.answer(Answer::Text("dunno".to_owned())).unwrap();
1660 questions.put(&mut asked).unwrap();
1661
1662 for _ in 0..2 {
1663 let report = run_once(&q, &questions, None, Timestamp::now());
1664 assert!(report.asked.is_empty() && report.answered.is_empty());
1665 }
1666 assert_eq!(deps_questions(&questions).len(), 1);
1667 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
1668 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Blocked);
1669 }
1670
1671 #[test]
1672 fn a_dependency_cycle_terminates_and_is_asked_about_once() {
1673 let (dir, q, questions) = store();
1674 let mut a = task("a", dir.path().join("repo"));
1675 let mut b = task("b", dir.path().join("repo"));
1676 a.block(vec![b.id.clone()], None);
1677 b.block(vec![a.id.clone()], None);
1678 q.put(&mut a).unwrap();
1679 q.put(&mut b).unwrap();
1680
1681 let first = run_once(&q, &questions, None, Timestamp::now());
1682 assert_eq!(first.asked.len(), 1);
1683 let second = run_once(&q, &questions, None, Timestamp::now());
1684 assert!(second.asked.is_empty());
1685 assert_eq!(deps_questions(&questions).len(), 1);
1686 }
1687
1688 #[test]
1689 fn a_missing_dependency_is_still_quarantined_not_asked_about_as_stuck() {
1690 let (dir, q, questions) = store();
1691 let mut t = task("orphan", dir.path().join("repo"));
1692 t.block(vec!["20260101-000000-gone".to_owned()], None);
1693 q.put(&mut t).unwrap();
1694 let report = run_once(&q, &questions, None, Timestamp::now());
1695 assert_eq!(report.quarantined, [t.id.clone()]);
1696 assert!(deps_questions(&questions).is_empty());
1697 }
1698
1699 #[test]
1700 fn a_stale_manual_hold_earns_a_two_choice_question() {
1701 let (dir, q, questions) = store();
1702 let mut t = task("been sitting a while", dir.path().join("repo"));
1703 t.hold_manual(Some("waiting on a decision".to_owned()));
1704 q.put(&mut t).unwrap();
1705 let mut back = q.get(&t.id).unwrap();
1707 back.updated_at = Timestamp::now() - SignedDuration::new(8 * 24 * 60 * 60, 0);
1708 std::fs::write(
1709 q.path_of(&back.id),
1710 serde_json::to_string_pretty(&back).unwrap(),
1711 )
1712 .unwrap();
1713
1714 let report = run_once(&q, &questions, None, Timestamp::now());
1715 assert_eq!(report.asked, [t.id.clone()]);
1716 let open: Vec<_> = questions
1717 .list()
1718 .into_iter()
1719 .filter(|q| q.status.open())
1720 .collect();
1721 assert_eq!(open.len(), 1);
1722 assert_eq!(open[0].choices.len(), 2);
1723 }
1724
1725 #[test]
1726 fn answering_resume_releases_the_task() {
1727 let (dir, q, questions) = store();
1728 let mut t = task("gate went red", dir.path().join("repo"));
1729 t.hold_machine(Some("gate red".to_owned()));
1730 q.put(&mut t).unwrap();
1731 run_once(&q, &questions, None, Timestamp::now());
1732
1733 let mut asked = questions
1734 .list()
1735 .into_iter()
1736 .find(|q| q.run == t.id)
1737 .unwrap();
1738 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
1739 questions.put(&mut asked).unwrap();
1740
1741 let report = run_once(&q, &questions, None, Timestamp::now());
1742 assert_eq!(report.answered, [t.id.clone()]);
1743 let back = q.get(&t.id).unwrap();
1744 assert_eq!(back.status, TaskStatus::Queued);
1745 assert!(back.hold_source.is_none());
1746 }
1747
1748 fn resumed_then_failed(q: &Queue, questions: &Questions, dir: &std::path::Path) -> Task {
1750 let mut t = task("gate went red", dir.join("repo"));
1751 t.hold_machine(Some("gate red".to_owned()));
1752 q.put(&mut t).unwrap();
1753 run_once(q, questions, None, Timestamp::now());
1754 let mut asked = questions
1755 .list()
1756 .into_iter()
1757 .find(|q| q.run == t.id)
1758 .unwrap();
1759 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
1760 questions.put(&mut asked).unwrap();
1761
1762 let report = run_once(q, questions, None, Timestamp::now());
1763 assert_eq!(report.answered, [t.id.clone()]);
1764 let mut back = q.get(&t.id).unwrap();
1765 assert_eq!(back.status, TaskStatus::Queued);
1766 assert_eq!(back.attempts, 0);
1767
1768 back.start("run-1".to_owned());
1769 back.fail("rebase conflict", 1);
1770 assert_eq!(back.status, TaskStatus::Held);
1771 q.put(&mut back).unwrap();
1772 back
1773 }
1774
1775 #[test]
1776 fn a_resume_answer_is_applied_once_and_a_new_machine_hold_is_asked_about() {
1777 let (dir, q, questions) = store();
1778 let t = resumed_then_failed(&q, &questions, dir.path());
1779
1780 let report = run_once(&q, &questions, None, Timestamp::now());
1781 assert!(report.answered.is_empty(), "the old answer must not replay");
1782 assert_eq!(report.asked, std::slice::from_ref(&t.id));
1783 let back = q.get(&t.id).unwrap();
1784 assert_eq!(back.status, TaskStatus::Held);
1785 assert_eq!(
1786 questions
1787 .list()
1788 .into_iter()
1789 .filter(|q| q.status.open())
1790 .count(),
1791 1
1792 );
1793 }
1794
1795 #[test]
1796 fn a_manual_hold_placed_after_a_resume_is_not_undone_by_the_old_answer() {
1797 let (dir, q, questions) = store();
1798 let mut t = resumed_then_failed(&q, &questions, dir.path());
1799 t.hold_manual(Some("operator stopped this".to_owned()));
1800 q.put(&mut t).unwrap();
1801 let before = questions.list().len();
1802
1803 let report = run_once(&q, &questions, None, Timestamp::now());
1804 assert!(report.answered.is_empty());
1805 assert!(report.asked.is_empty());
1806 let back = q.get(&t.id).unwrap();
1807 assert_eq!(back.status, TaskStatus::Held);
1808 assert_eq!(back.hold_source, Some(HoldSource::Manual));
1809 assert_eq!(questions.list().len(), before);
1810 }
1811
1812 #[test]
1813 fn answering_not_yet_keeps_it_held_as_a_manual_hold_and_does_not_reapply() {
1814 let (dir, q, questions) = store();
1815 let mut t = task("gate went red", dir.path().join("repo"));
1816 t.hold_machine(Some("gate red".to_owned()));
1817 q.put(&mut t).unwrap();
1818 run_once(&q, &questions, None, Timestamp::now());
1819
1820 let mut asked = questions
1821 .list()
1822 .into_iter()
1823 .find(|q| q.run == t.id)
1824 .unwrap();
1825 asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
1826 questions.put(&mut asked).unwrap();
1827
1828 let report = run_once(&q, &questions, None, Timestamp::now());
1829 assert_eq!(report.answered, [t.id.clone()]);
1830 let back = q.get(&t.id).unwrap();
1831 assert_eq!(back.status, TaskStatus::Held);
1832 assert_eq!(back.hold_source, Some(HoldSource::Manual));
1833 assert!(
1834 back.hold_reason
1835 .as_deref()
1836 .is_some_and(|r| r.contains("gate red")),
1837 "the original cause must survive a \"not yet\" answer, not just the \
1838 triage marker: {:?}",
1839 back.hold_reason
1840 );
1841
1842 let third = run_once(&q, &questions, None, Timestamp::now());
1846 assert!(third.answered.is_empty());
1847 assert!(third.asked.is_empty());
1848 }
1849
1850 #[test]
1851 fn answering_discard_removes_the_task_entirely() {
1852 let (dir, q, questions) = store();
1853 let mut t = task("gate went red", dir.path().join("repo"));
1854 t.hold_machine(Some("gate red".to_owned()));
1855 q.put(&mut t).unwrap();
1856 run_once(&q, &questions, None, Timestamp::now());
1857
1858 let mut asked = questions
1859 .list()
1860 .into_iter()
1861 .find(|q| q.run == t.id)
1862 .unwrap();
1863 asked.answer(Answer::Choice(EN.discard.to_owned())).unwrap();
1864 questions.put(&mut asked).unwrap();
1865
1866 let report = run_once(&q, &questions, None, Timestamp::now());
1867 assert_eq!(report.answered, [t.id.clone()]);
1868 assert!(
1869 q.get(&t.id).is_err(),
1870 "\"discard it\" (捨ててよい) must actually discard the task, not \
1871 just leave it sitting held forever"
1872 );
1873 }
1874
1875 #[test]
1876 fn an_answer_is_read_by_its_position_in_choices_not_by_the_callers_current_language() {
1877 let (dir, q, questions) = store();
1879 let ja_config = dir.path().join("ja.toml");
1880 std::fs::write(&ja_config, "[graph]\nlanguage = \"ja\"\n").unwrap();
1881 let mut t = task("gate went red", dir.path().join("repo"));
1882 t.hold_machine(Some("gate red".to_owned()));
1883 q.put(&mut t).unwrap();
1884 run_once(&q, &questions, Some(&ja_config), Timestamp::now());
1885
1886 let mut asked = questions
1887 .list()
1888 .into_iter()
1889 .find(|q| q.run == t.id)
1890 .unwrap();
1891 assert_eq!(asked.choices[0], JA.resume, "filed in Japanese");
1892 asked.answer(Answer::Choice(JA.resume.to_owned())).unwrap();
1893 questions.put(&mut asked).unwrap();
1894
1895 let en_config = dir.path().join("en.toml");
1900 std::fs::write(&en_config, "[graph]\nlanguage = \"en\"\n").unwrap();
1901 let report = run_once(&q, &questions, Some(&en_config), Timestamp::now());
1902 assert_eq!(report.answered, [t.id.clone()]);
1903 let back = q.get(&t.id).unwrap();
1904 assert_eq!(
1905 back.status,
1906 TaskStatus::Queued,
1907 "a resume answer must resume the task regardless of which \
1908 language it is read back in"
1909 );
1910 }
1911
1912 #[test]
1913 fn a_question_falls_back_to_last_error_when_hold_reason_was_never_set() {
1914 let (dir, q, questions) = store();
1919 let mut t = task("kept failing the gate", dir.path().join("repo"));
1920 t.start("run-1".to_owned());
1921 t.fail("gate red three times running", 1);
1922 assert_eq!(t.status, TaskStatus::Held);
1923 t.hold_reason = None; q.put(&mut t).unwrap();
1925
1926 run_once(&q, &questions, None, Timestamp::now());
1927 let asked = questions
1928 .list()
1929 .into_iter()
1930 .find(|q| q.run == t.id)
1931 .unwrap();
1932 assert!(
1933 asked.detail.contains("gate red three times running"),
1934 "the question must surface `last_error` when there is no \
1935 `hold_reason` to show instead: {}",
1936 asked.detail
1937 );
1938 }
1939
1940 #[test]
1941 fn open_question_for_and_open_task_ids_reflect_only_what_is_still_waiting() {
1942 let (dir, q, questions) = store();
1943 let mut t = task("gate went red", dir.path().join("repo"));
1944 t.hold_machine(Some("gate red".to_owned()));
1945 q.put(&mut t).unwrap();
1946
1947 assert!(open_question_for(&questions, &t.id).is_none());
1948 assert!(!open_task_ids(&questions).contains(&t.id));
1949
1950 run_once(&q, &questions, None, Timestamp::now());
1951 assert!(open_question_for(&questions, &t.id).is_some());
1952 assert!(open_task_ids(&questions).contains(&t.id));
1953
1954 let mut asked = questions
1955 .list()
1956 .into_iter()
1957 .find(|q| q.run == t.id)
1958 .unwrap();
1959 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
1960 questions.put(&mut asked).unwrap();
1961
1962 assert!(
1963 open_question_for(&questions, &t.id).is_none(),
1964 "an answered question is no longer open"
1965 );
1966 assert!(!open_task_ids(&questions).contains(&t.id));
1967 }
1968
1969 #[test]
1970 fn pending_for_stays_true_between_an_answer_and_the_next_run_once_pass() {
1971 let (dir, q, questions) = store();
1977 let mut t = task("gate went red", dir.path().join("repo"));
1978 t.hold_machine(Some("gate red".to_owned()));
1979 q.put(&mut t).unwrap();
1980
1981 assert!(!pending_for(&questions, &t));
1982
1983 run_once(&q, &questions, None, Timestamp::now());
1984 let held = q.get(&t.id).unwrap();
1985 assert!(pending_for(&questions, &held), "still waiting on an answer");
1986
1987 let mut asked = questions
1988 .list()
1989 .into_iter()
1990 .find(|q| q.run == t.id)
1991 .unwrap();
1992 asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
1993 questions.put(&mut asked).unwrap();
1994 assert!(!asked.status.open());
1995
1996 let still_held = q.get(&t.id).unwrap();
1998 assert!(
1999 pending_for(&questions, &still_held),
2000 "answered but not yet applied is still pending"
2001 );
2002
2003 run_once(&q, &questions, None, Timestamp::now());
2004 let after = q.get(&t.id).unwrap();
2005 assert!(
2006 !pending_for(&questions, &after),
2007 "the answer is applied now, nothing left pending"
2008 );
2009 }
2010}