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