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 machine_cause_resolved_with_admission(task, cfg, home, |paths| {
408 crate::retention::OutputLease::admit(home, paths, cfg.disk.min_free_bytes).is_ok()
409 })
410}
411
412fn machine_cause_resolved_with_admission(
413 task: &Task,
414 cfg: &Config,
415 home: &Path,
416 admission_available: impl Fn(&[PathBuf]) -> bool,
417) -> Option<bool> {
418 if task
419 .hold_reason
420 .as_deref()
421 .is_some_and(|r| r.starts_with(crate::cache::RESOURCE_HOLD))
422 {
423 let id = task.runs.last()?;
425 let state = crate::run::RunState::load_under(id, home).ok()?;
426 let block = state.resource_block.as_ref()?;
427 if state.id != *id {
428 return None;
429 }
430 if block.kind == "disk admission"
431 && matches!(block.cause, crate::run::ResourceBlockCause::Other)
432 {
433 let mut paths = vec![repo_for(task), state.repo.clone(), state.worktree_root()];
437 paths.extend(state.candidates.iter().map(|c| c.worktree.clone()));
438 paths.extend(state.config.cache_dir());
439 paths.extend(cfg.cache_dir());
440 return Some(admission_available(&paths));
441 }
442 if block.kind != "shared build cache"
445 || !matches!(block.cause, crate::run::ResourceBlockCause::Timeout { .. })
446 {
447 return None;
448 }
449 return Some(
450 cfg.cache_dir()
451 .is_none_or(|dir| !crate::cache::in_use(home, &dir)),
452 );
453 }
454 if !is_disk_hold(task) {
455 return None;
456 }
457 let min = cfg.disk.min_free_bytes;
458 if min == 0 {
459 return Some(true);
462 }
463 Some(crate::daemon::disk_gate(&repo_for(task), cfg).is_none())
464}
465
466fn manual_is_stale(task: &Task, now: Timestamp) -> bool {
470 now.as_second() - task.updated_at.as_second() > MANUAL_STALE_AFTER.as_secs() as i64
471}
472
473fn marker_for(q: &Question) -> String {
476 format!("[triage:{}]", q.short())
477}
478
479fn already_applied(task: &Task, q: &Question) -> bool {
482 if task.triage_applied(&q.id) {
483 return true;
484 }
485 let marker = marker_for(q);
488 task.hold_reason
489 .as_deref()
490 .is_some_and(|r| r.contains(marker.as_str()))
491}
492
493fn latest_triage_question(questions: &Questions, task_id: &str) -> Option<Question> {
498 latest_question(questions, NODE, task_id)
499}
500
501fn latest_question(questions: &Questions, node: &str, task_id: &str) -> Option<Question> {
503 questions
504 .list()
505 .into_iter()
506 .filter(|q| q.node == node && q.run == task_id)
507 .max_by(|a, b| a.asked_at.cmp(&b.asked_at).then_with(|| a.id.cmp(&b.id)))
510}
511
512#[derive(Debug, Clone, Copy, PartialEq, Eq)]
515enum AnswerAction {
516 Resume,
520 Discard,
523 KeepHeld,
528}
529
530fn interpret_answer(q: &Question) -> AnswerAction {
543 let resolution = q.resolution().unwrap_or_default();
544 match q.choices.iter().position(|c| *c == resolution) {
545 Some(0) => AnswerAction::Resume,
546 Some(2) => AnswerAction::Discard,
547 _ => AnswerAction::KeepHeld,
548 }
549}
550
551pub(crate) fn contextual_keep_held(q: &Question, label: &str) -> bool {
554 q.node == NODE
555 && q.seat == SEAT
556 && q.actions.is_empty()
557 && q.choices.get(1).is_some_and(|c| c == label)
558}
559
560fn keep_held_note(task: &Task, q: &Question, resolution: &str) -> String {
565 let marker = format!("{} operator: {resolution}", marker_for(q));
566 match task.hold_reason.as_deref() {
567 Some(existing) if !existing.is_empty() => format!("{existing}\n{marker}"),
568 _ => marker,
569 }
570}
571
572fn file_question(
576 questions: &Questions,
577 task: &Task,
578 bucket: Bucket,
579 w: &Wording,
580 now: Timestamp,
581) -> Option<Question> {
582 let (summary, why, choices) = match bucket {
583 Bucket::MachineUnknown => (
584 w.summary_machine_unknown(task),
585 w.why_machine().to_owned(),
586 w.choices3(),
587 ),
588 Bucket::ConductorOverride => (
589 w.summary_conductor_override(task),
590 task.resume_override
591 .as_ref()
592 .map(|o| w.why_conductor_override(o))
593 .unwrap_or_default(),
594 w.choices_conductor_override(),
595 ),
596 Bucket::Legacy => (
597 w.summary_legacy(task),
598 w.why_legacy().to_owned(),
599 w.choices3(),
600 ),
601 Bucket::ManualStale => {
602 let days = (now.as_second() - task.updated_at.as_second()) / (24 * 60 * 60);
603 (
604 w.summary_manual_stale(task, days),
605 w.why_manual().to_owned(),
606 w.choices2(),
607 )
608 }
609 };
610 let mut q = Question::new(
611 task.id.clone(),
612 NODE.to_owned(),
613 SEAT.to_owned(),
614 summary,
615 w.detail(task, &why),
616 choices,
617 );
618 q.triage_generation = Some(task.resumption.as_ref().map_or(0, |r| r.generation));
619 questions.put_executable(&mut q).ok()?;
620 Some(q)
621}
622
623pub(crate) fn deputy_brief(q: &Question, queue: &Queue) -> String {
628 let task = queue.get(&q.run).ok();
629 let mut s = match &task {
630 Some(t) => format!(
631 "Task {} (`magi task show {}`), \"{}\", is {}. Hold source: {}. Reason: {}.",
632 t.id,
633 t.id,
634 t.title,
635 t.status.as_str(),
636 match t.hold_source {
637 Some(HoldSource::Machine) => "machine (an automatic hold)",
638 Some(HoldSource::Manual) => "manual (an operator held it)",
639 None => "unknown (an old record, treated as the operator's)",
640 },
641 t.hold_reason
642 .as_deref()
643 .or(t.last_error.as_deref())
644 .unwrap_or("(none recorded)")
645 ),
646 None => format!("Task {} no longer exists (its record is gone).", q.run),
647 };
648 s.push_str("\n\nWhat each option does, by position:");
649 let n = q.choices.len();
650 for (i, c) in q.choices.iter().enumerate() {
651 let effect = if q.node == DEPS_NODE {
652 match i {
653 0 => "the dependency is released so the loop runs it",
654 1 => {
655 "the dependants are detached and the dependency task is DELETED; this cannot be undone"
656 }
657 2 => "the dependants are detached; the dependency stays as it is",
658 _ => "nothing is applied",
659 }
660 } else {
661 match i {
662 0 => "the task is released and requeued",
663 2 if n > 2 => "the task is DELETED; this cannot be undone",
664 _ => "the task stays held, with the answer noted",
665 }
666 };
667 s.push_str(&format!("\n- `{c}`: {effect}"));
668 }
669 s.push_str(
670 "\n\nThe daemon applies the answer on its next pass; you apply nothing. When \
671 the owner's words pick an option - including releasing a task they held \
672 themselves, or deleting it - settle it.",
673 );
674 s
675}
676
677fn quarantine_orphaned_blocked(queue: &Queue, questions: &Questions) -> Vec<String> {
695 let mut quarantined = Vec::new();
696 for listed in queue.list() {
697 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
698 continue;
699 }
700 let Ok(_claim) = queue.claim(&listed.id) else {
701 continue;
702 };
703 let Ok(mut task) = queue.get(&listed.id) else {
704 continue;
705 };
706 if task.status != TaskStatus::Blocked {
707 continue;
708 }
709 let deleted = queue.apply_deleted_blockers(&mut task, questions);
710 if !deleted.is_empty() && queue.put(&mut task).is_ok() {
711 for id in &deleted {
712 queue.note_dependency_deleted(&task, id);
713 }
714 }
715 if task.status != TaskStatus::Blocked {
716 continue;
717 }
718 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
719 if missing.is_empty() {
720 continue;
721 }
722 let language = crate::lang::of_repo(&repo_for(&task));
723 let mut cause = missing.clone();
724 cause.sort();
725 cause.dedup();
726 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
727 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
728 &task.blocked_by,
729 &missing,
730 &language,
731 )));
732 if queue.put(&mut task).is_ok() {
733 quarantined.push(task.id.clone());
734 }
735 }
736 quarantined
737}
738
739#[derive(Debug, Clone, Copy, PartialEq, Eq)]
742enum DepsAction {
743 Release,
744 Discard,
745 Detach,
746 Nothing,
748}
749
750fn interpret_deps_answer(q: &Question) -> DepsAction {
751 let resolution = q.resolution().unwrap_or_default();
752 match q.choices.iter().position(|c| *c == resolution) {
753 Some(0) => DepsAction::Release,
754 Some(1) => DepsAction::Discard,
755 Some(2) => DepsAction::Detach,
756 _ => DepsAction::Nothing,
757 }
758}
759
760fn deps_texts(w: &Wording, root: &Task, dependants: &[&Task]) -> (String, String, Vec<String>) {
762 let ja = w.lang == "ja";
763 let reason = root
764 .hold_reason
765 .as_deref()
766 .or(root.last_error.as_deref())
767 .unwrap_or(if ja {
768 "(記録なし)"
769 } else {
770 "(none recorded)"
771 });
772 let list: String = dependants
773 .iter()
774 .map(|t| format!("- {} {}\n", t.short(), t.title))
775 .collect();
776 if ja {
777 (
778 format!(
779 "{} ({}) が {} 件のタスクを止めています",
780 root.short(),
781 root.status.as_str(),
782 dependants.len()
783 ),
784 format!(
785 "task: {} ({})\ntitle: {}\n状態: {}\n理由: {reason}\n\n\
786 このタスクは自動では実行されないため、依存している次のタスクは永遠に待ち続けます:\n{list}",
787 root.id,
788 root.short(),
789 root.title,
790 root.status.as_str()
791 ),
792 vec![
793 "依存先を再開する".to_owned(),
794 "依存先を捨てる(依存タスクは切り離して実行)".to_owned(),
795 "依存タスクを切り離す(依存先はそのまま)".to_owned(),
796 ],
797 )
798 } else {
799 (
800 format!(
801 "{} ({}) is freezing {} blocked task(s)",
802 root.short(),
803 root.status.as_str(),
804 dependants.len()
805 ),
806 format!(
807 "task: {} ({})\ntitle: {}\nstatus: {}\nreason: {reason}\n\n\
808 Nothing in the loop will ever run this task, so these dependants wait \
809 forever:\n{list}",
810 root.id,
811 root.short(),
812 root.title,
813 root.status.as_str()
814 ),
815 vec![
816 "release the dependency".to_owned(),
817 "discard the dependency (dependants are detached and run)".to_owned(),
818 "detach the dependants (the dependency stays as it is)".to_owned(),
819 ],
820 )
821 }
822}
823
824fn detach_dependants(queue: &Queue, questions: &Questions, root: &str) {
828 for listed in queue.list() {
829 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)) {
830 continue;
831 }
832 let Ok(_claim) = queue.claim(&listed.id) else {
833 continue;
834 };
835 let Ok(mut t) = queue.get(&listed.id) else {
836 continue;
837 };
838 if t.status != TaskStatus::Blocked {
839 continue;
840 }
841 for id in t.blocked_by.clone() {
842 if matches!(crate::queue::dependency(queue, questions, &id), crate::queue::Dependency::Task(full) if full == root)
843 {
844 t.unblock(&id);
845 }
846 }
847 let _ = queue.put(&mut t);
848 }
849}
850
851fn apply_deps_answer(queue: &Queue, questions: &Questions, q: &Question, now: Timestamp) -> bool {
855 let Ok(_claim) = queue.claim(&q.run) else {
856 return false;
857 };
858 let Ok(mut root) = queue.get(&q.run) else {
859 return false;
860 };
861 if root.triage_applied(&q.id) {
862 return false;
863 }
864 if root.operator_decided_at.is_some_and(|at| at > q.asked_at)
865 || q.triage_generation
866 .is_some_and(|g| g != root.resumption.as_ref().map_or(0, |r| r.generation))
867 {
868 root.mark_triage_applied(&q.id);
869 return queue.put(&mut root).is_ok();
870 }
871 match interpret_deps_answer(q) {
872 DepsAction::Release => {
873 if root.status == TaskStatus::Running {
874 return false;
875 }
876 root.answers.push(crate::queue::AnsweredQuestion {
877 question: q.summary.clone(),
878 answer: q.resolution().unwrap_or_default(),
879 });
880 if crate::base_sync_recovery::held_task(queue, &root) {
881 root.mark_triage_applied(&q.id);
882 return queue.put(&mut root).is_ok();
883 }
884 root.release_operator("triage-dependencies", Some(&q.id));
885 root.resume_override = Some(OperatorResume {
886 question_id: q.id.clone(),
887 at: now,
888 conductor_rehold: None,
889 forced: false,
890 pinned_run: None,
891 });
892 }
893 DepsAction::Discard => {
894 detach_dependants(queue, questions, &root.id);
895 return queue.remove(&root.id, false, questions).is_ok();
896 }
897 DepsAction::Detach => detach_dependants(queue, questions, &root.id),
898 DepsAction::Nothing => return false,
903 }
904 root.mark_triage_applied(&q.id);
905 queue.put(&mut root).is_ok()
906}
907
908fn ask_about_stuck_roots(
917 queue: &Queue,
918 questions: &Questions,
919 config_override: Option<&Path>,
920 report: &mut Report,
921) {
922 let all = questions.list();
923 let inv = crate::blockers::Inventory::load(queue, questions);
924 let mut frozen: std::collections::BTreeMap<String, Vec<String>> = Default::default();
925 for (id, roots) in inv.stuck() {
926 for root in roots {
927 if root != id {
928 frozen.entry(root).or_default().push(id.clone());
929 }
930 }
931 }
932 for mut q in all
936 .iter()
937 .filter(|q| q.node == DEPS_NODE && q.status.open())
938 .cloned()
939 {
940 if !frozen.contains_key(&q.run) {
941 q.abandon("nothing waits on this task anymore");
942 let _ = questions.put_executable(&mut q);
943 }
944 }
945
946 for (root_id, dependant_ids) in &frozen {
947 let Ok(_claim) = queue.claim(root_id) else {
948 continue;
949 };
950 let current = crate::blockers::Inventory::load(queue, questions);
953 let Some(root) = current.task(root_id) else {
954 continue;
955 };
956 if crate::base_sync_recovery::held_task(queue, root) {
957 continue;
958 }
959 let dependants: Vec<&Task> = dependant_ids
960 .iter()
961 .filter_map(|d| current.task(d))
962 .filter(|t| current.stuck_roots(t).contains(root_id))
963 .collect();
964 if dependants.is_empty() {
965 continue;
966 }
967 let latest = all
968 .iter()
969 .filter(|q| q.node == DEPS_NODE && q.run == *root_id)
970 .max_by(|a, b| a.asked_at.cmp(&b.asked_at).then_with(|| a.id.cmp(&b.id)));
971 match latest {
972 Some(q) if q.status.open() || awaiting_task_chat(q, root) => continue,
973 Some(q) if q.status == QuestionStatus::Answered && !root.triage_applied(&q.id) => {
974 continue;
975 }
976 Some(q) if q.status == QuestionStatus::Abandoned => {
977 let changed = root.updated_at > q.asked_at
978 || dependants.iter().any(|t| t.updated_at > q.asked_at);
979 if !changed {
980 continue;
981 }
982 }
983 _ => {}
984 }
985 if pending_for(questions, root) {
986 continue;
987 }
988 let cfg = Config::discover(&repo_for(root), config_override)
989 .ok()
990 .map(|(c, _)| c);
991 let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
992 let (summary, detail, choices) = deps_texts(w, root, &dependants);
993 let mut question = Question::new(
994 root.id.clone(),
995 DEPS_NODE.to_owned(),
996 SEAT.to_owned(),
997 summary,
998 detail,
999 choices,
1000 );
1001 question.triage_generation = Some(root.resumption.as_ref().map_or(0, |r| r.generation));
1002 if questions.put_executable(&mut question).is_ok() {
1003 report.asked.push(root.id.clone());
1004 }
1005 }
1006}
1007
1008pub fn apply_answers(queue: &Queue, questions: &Questions) -> Vec<String> {
1011 let mut applied = Vec::new();
1012 for q in questions.list() {
1013 if q.node == DEPS_NODE
1014 && q.status == QuestionStatus::Answered
1015 && apply_deps_answer(queue, questions, &q, Timestamp::now())
1016 {
1017 applied.push(q.run.clone());
1018 }
1019 }
1020 for listed in queue.list() {
1021 let Some(q) = latest_triage_question(questions, &listed.id) else {
1022 continue;
1023 };
1024 if q.status != QuestionStatus::Answered || already_applied(&listed, &q) {
1025 continue;
1026 }
1027 let Ok(_claim) = queue.claim(&listed.id) else {
1028 continue;
1029 };
1030 let Ok(mut task) = queue.get(&listed.id) else {
1031 continue;
1032 };
1033 if already_applied(&task, &q)
1034 || !matches!(task.status, TaskStatus::Held | TaskStatus::Queued)
1035 {
1036 continue;
1037 }
1038 let generation = task.resumption.as_ref().map_or(0, |r| r.generation);
1039 let action = interpret_answer(&q);
1040 let mut newer_decision = q.triage_generation.is_some_and(|g| g != generation)
1041 || task.resumption.as_ref().is_some_and(|r| r.at > q.asked_at)
1042 || task.held_at.is_some_and(|at| at > q.asked_at)
1043 || task.operator_decided_at.is_some_and(|at| at > q.asked_at);
1044 if matches!(action, AnswerAction::KeepHeld)
1048 && q.answered_at.is_some_and(|at| {
1049 task.operator_decided_at
1050 .is_none_or(|decision| at > decision)
1051 && task.resumption.as_ref().is_none_or(|r| at > r.at)
1052 })
1053 {
1054 newer_decision = false;
1055 }
1056 let resolution = q.resolution().unwrap_or_default();
1058 task.answers.push(crate::queue::AnsweredQuestion {
1059 question: q.summary.clone(),
1060 answer: if newer_decision {
1061 format!("{resolution} (superseded by a later operator decision)")
1062 } else {
1063 resolution
1064 },
1065 });
1066 if !newer_decision {
1067 match action {
1068 AnswerAction::Resume if crate::base_sync_recovery::held_task(queue, &task) => {
1069 }
1072 AnswerAction::Resume => {
1073 task.release_operator("triage", Some(&q.id));
1074 task.resume_override = Some(OperatorResume {
1075 question_id: q.id.clone(),
1076 at: Timestamp::now(),
1077 conductor_rehold: None,
1078 forced: true,
1079 pinned_run: None,
1080 });
1081 }
1082 AnswerAction::KeepHeld => {
1083 let note = keep_held_note(&task, &q, &q.resolution().unwrap_or_default());
1084 task.hold_manual(Some(note));
1085 }
1086 AnswerAction::Discard => {
1087 if queue.remove(&task.id, false, questions).is_ok() {
1088 applied.push(task.id);
1089 }
1090 continue;
1091 }
1092 }
1093 }
1094 task.mark_triage_applied(&q.id);
1095 if queue.put(&mut task).is_ok() {
1096 applied.push(task.id);
1097 }
1098 }
1099 applied
1100}
1101
1102pub fn run_once(
1120 queue: &Queue,
1121 questions: &Questions,
1122 config_override: Option<&Path>,
1123 now: Timestamp,
1124) -> Report {
1125 let mut report = Report {
1126 answered: apply_answers(queue, questions),
1127 quarantined: quarantine_orphaned_blocked(queue, questions),
1128 ..Report::default()
1129 };
1130 ask_about_stuck_roots(queue, questions, config_override, &mut report);
1131 for listed in queue.list() {
1132 if listed.status != TaskStatus::Held {
1133 continue;
1134 }
1135 let Ok(_claim) = queue.claim(&listed.id) else {
1136 continue;
1137 };
1138 let Ok(mut task) = queue.get(&listed.id) else {
1139 continue;
1140 };
1141 if task.status != TaskStatus::Held {
1145 continue;
1146 }
1147 if crate::base_sync_recovery::held_task(queue, &task) {
1148 continue;
1149 }
1150 if deps_pending(questions, &task) {
1154 continue;
1155 }
1156
1157 let cfg = Config::discover(&repo_for(&task), config_override)
1158 .ok()
1159 .map(|(c, _)| c);
1160 let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
1161
1162 if let Some(q) = latest_triage_question(questions, &task.id) {
1163 if q.status.open() || awaiting_task_chat(&q, &task) {
1164 continue;
1166 }
1167 }
1173
1174 match task.hold_source {
1175 Some(HoldSource::Machine) => {
1176 let overridden = task
1177 .resume_override
1178 .as_ref()
1179 .is_some_and(|o| o.conductor_rehold.is_some() && !o.forced);
1180 if overridden {
1181 if file_question(questions, &task, Bucket::ConductorOverride, w, now).is_some()
1182 {
1183 report.asked.push(task.id.clone());
1184 }
1185 } else if cfg.as_ref().and_then(|c| machine_cause_resolved(&task, c)) == Some(true)
1186 {
1187 task.release();
1188 if queue.put(&mut task).is_ok() {
1189 report.resumed.push(task.id.clone());
1190 }
1191 } else if file_question(questions, &task, Bucket::MachineUnknown, w, now).is_some()
1192 {
1193 report.asked.push(task.id.clone());
1194 }
1195 }
1196 None => {
1197 if file_question(questions, &task, Bucket::Legacy, w, now).is_some() {
1198 report.asked.push(task.id.clone());
1199 }
1200 }
1201 Some(HoldSource::Manual) => {
1202 if manual_is_stale(&task, now)
1203 && file_question(questions, &task, Bucket::ManualStale, w, now).is_some()
1204 {
1205 report.asked.push(task.id.clone());
1206 }
1207 }
1208 }
1209 }
1210 report
1211}
1212
1213pub fn open_question_for(questions: &Questions, task_id: &str) -> Option<Question> {
1218 latest_triage_question(questions, task_id).filter(|q| q.status.open())
1219}
1220
1221pub fn pending_for(questions: &Questions, task: &Task) -> bool {
1235 !pending_recovery_questions(questions, task).is_empty()
1236}
1237
1238pub(crate) fn pending_recovery_questions(questions: &Questions, task: &Task) -> Vec<Question> {
1241 [NODE, DEPS_NODE]
1242 .into_iter()
1243 .filter_map(|node| {
1244 latest_question(questions, node, &task.id).filter(|q| {
1245 q.status.open()
1246 || awaiting_task_chat(q, task)
1247 || (q.status == QuestionStatus::Answered
1248 && if node == NODE {
1249 !already_applied(task, q)
1250 } else {
1251 !task.triage_applied(&q.id)
1252 })
1253 })
1254 })
1255 .collect()
1256}
1257
1258fn awaiting_task_chat(q: &Question, task: &Task) -> bool {
1259 q.status != QuestionStatus::Abandoned
1260 && q.routed_chat.is_some()
1261 && !already_applied(task, q)
1262 && task.resumption.as_ref().map_or(0, |r| r.generation) == q.triage_generation.unwrap_or(0)
1263 && task.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1264}
1265
1266fn deps_pending(questions: &Questions, task: &Task) -> bool {
1270 match latest_question(questions, DEPS_NODE, &task.id) {
1271 Some(q) if q.status.open() || awaiting_task_chat(&q, task) => true,
1272 Some(q) if q.status == QuestionStatus::Answered => !task.triage_applied(&q.id),
1273 _ => false,
1274 }
1275}
1276
1277pub fn open_task_ids(questions: &Questions) -> std::collections::BTreeSet<String> {
1282 questions
1283 .list()
1284 .into_iter()
1285 .filter(|q| (q.node == NODE || q.node == DEPS_NODE) && q.status.open())
1286 .map(|q| q.run)
1287 .collect()
1288}
1289
1290#[cfg(test)]
1291mod tests {
1292 use super::*;
1293 use crate::ask::Answer;
1294 use crate::queue::Source;
1295 use jiff::SignedDuration;
1296
1297 fn store() -> (tempfile::TempDir, Queue, Questions) {
1298 let dir = tempfile::tempdir().unwrap();
1299 let q = Queue::at(dir.path().join("queue"));
1300 let s = Questions::at(dir.path().join("questions"));
1301 (dir, q, s)
1302 }
1303
1304 fn task(title: &str, repo: PathBuf) -> Task {
1305 Task::new(title.to_owned(), format!("do {title}"), repo, Source::Human)
1306 }
1307
1308 #[test]
1309 fn base_recovery_stops_suppress_generic_and_dependency_resume_offers() {
1310 let (dir, queue, questions) = store();
1311 let mut root = task("base stop", dir.path().to_path_buf());
1312 let mut run = crate::run::RunState::new(
1313 dir.path().to_path_buf(),
1314 "main".into(),
1315 "base".into(),
1316 "retained implementation".into(),
1317 Config::default(),
1318 );
1319 run.status = crate::run::RunStatus::Voting;
1320 run.base_sync = Some(crate::run::BaseSync {
1321 tip: "tip".into(),
1322 behind: 3,
1323 attempts: 4,
1324 conflict: Some("persisted exhaustion".into()),
1325 already_in: None,
1326 });
1327 run.save_under(dir.path()).unwrap();
1328 root.link_run(&run.id);
1329 root.hold_machine(Some("base stop".into()));
1330 queue.put(&mut root).unwrap();
1331 let mut dependent = task("dependent", dir.path().to_path_buf());
1332 dependent.blocked_by = vec![root.id.clone()];
1333 dependent.status = TaskStatus::Blocked;
1334 queue.put(&mut dependent).unwrap();
1335 for _ in 0..2 {
1336 let report = run_once(&queue, &questions, None, Timestamp::now());
1337 assert!(report.asked.is_empty());
1338 assert!(report.resumed.is_empty());
1339 }
1340 let q = file_question(
1343 &questions,
1344 &root,
1345 Bucket::MachineUnknown,
1346 &EN,
1347 Timestamp::now(),
1348 )
1349 .unwrap();
1350 let mut q = q;
1351 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
1352 questions.put_executable(&mut q).unwrap();
1353 apply_answers(&queue, &questions);
1354 let saved = queue.get(&root.id).unwrap();
1355 assert_eq!(saved.status, TaskStatus::Held);
1356 assert!(saved.triage_applied(&q.id));
1357 assert_eq!(saved.runs, vec![run.id]);
1358 }
1359
1360 #[test]
1361 fn resource_holds_only_auto_release_a_proven_cache_wait_timeout() {
1362 use crate::run::{ResourceBlock, ResourceBlockCause, RunState};
1363 let dir = tempfile::tempdir().unwrap();
1364 let cfg = Config::default(); assert!(cfg.cache_dir().is_none());
1366 let mut state = RunState::new(
1367 dir.path().into(),
1368 "main".into(),
1369 "base".into(),
1370 "verify".into(),
1371 cfg.clone(),
1372 );
1373 let mut task = task("verify", dir.path().into());
1374 task.runs = vec![state.id.clone()];
1375 task.hold_machine(Some("[resource] cache operation stopped".into()));
1376 for cause in [
1377 ResourceBlockCause::Other,
1378 ResourceBlockCause::Unrecorded,
1379 ResourceBlockCause::Cancelled { park: None },
1380 ] {
1381 state.resource_block = Some(ResourceBlock {
1382 node: "gate".into(),
1383 kind: "shared build cache".into(),
1384 detail: "persistent metadata or manifest error".into(),
1385 cause,
1386 at: Timestamp::now(),
1387 });
1388 state.save_under(dir.path()).unwrap();
1389 for _ in 0..3 {
1391 assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
1392 }
1393 }
1394 let block = state.resource_block.as_mut().unwrap();
1395 block.cause = ResourceBlockCause::Timeout {
1396 waited_secs: 10,
1397 limit_secs: 10,
1398 };
1399 state.save_under(dir.path()).unwrap();
1400 assert_eq!(
1401 machine_cause_resolved_under(&task, &cfg, dir.path()),
1402 Some(true)
1403 );
1404 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
1405 state.save_under(dir.path()).unwrap();
1406 assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
1407 task.runs = vec!["unreadable-run".into()];
1408 assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
1409 }
1410
1411 #[cfg(unix)]
1412 #[test]
1413 fn disk_admission_holds_recheck_live_reservations_and_the_floor() {
1414 use crate::retention::OutputLease;
1415 use crate::run::{ResourceBlock, ResourceBlockCause, RunState};
1416 let temp = tempfile::tempdir().unwrap();
1417 let home = temp.path().canonicalize().unwrap();
1418 let mut cfg = Config::default();
1419 cfg.graph.worktree_root = Some(home.join("worktrees"));
1420 cfg.disk.min_free_bytes = 100;
1421 let cache = home.join("cache");
1422 cfg.verify.gate = vec![format!(
1423 "CARGO_TARGET_DIR='{}' cargo build",
1424 cache.display()
1425 )];
1426 let mut state = RunState::new(
1427 home.clone(),
1428 "main".into(),
1429 "base".into(),
1430 "verify".into(),
1431 cfg.clone(),
1432 );
1433 state.resource_block = Some(ResourceBlock {
1434 node: "gate".into(),
1435 kind: "disk admission".into(),
1436 detail: "writer headroom unavailable".into(),
1437 cause: ResourceBlockCause::Other,
1438 at: Timestamp::now(),
1439 });
1440 state.save_under(&home).unwrap();
1441 let mut task = task("verify", home.clone());
1442 task.runs = vec![state.id.clone()];
1443 task.hold_machine(Some("[resource] gate: disk admission: blocked".into()));
1444 let gib = 1024 * 1024 * 1024;
1445 let free = std::cell::Cell::new(100 + gib - 1);
1446 let check = || {
1447 machine_cause_resolved_with_admission(&task, &cfg, &home, |paths| {
1448 assert!(
1449 paths.contains(&cache),
1450 "the cache volume must also be checked"
1451 );
1452 assert!(paths.contains(&state.worktree_root()));
1453 OutputLease::admit_with(&home, paths, cfg.disk.min_free_bytes, |_| Ok(free.get()))
1454 .is_ok()
1455 })
1456 };
1457 assert_eq!(check(), Some(false), "the unchanged floor still applies");
1458 free.set(100 + gib);
1459 let writer = OutputLease::admit_with(
1460 &home,
1461 std::slice::from_ref(&home),
1462 cfg.disk.min_free_bytes,
1463 |_| Ok(free.get()),
1464 )
1465 .unwrap();
1466 assert_eq!(
1467 check(),
1468 Some(false),
1469 "df alone cannot resolve a live reservation"
1470 );
1471 drop(writer);
1472 assert_eq!(
1473 check(),
1474 Some(true),
1475 "releasing headroom resolves the machine hold"
1476 );
1477 assert_eq!(
1478 check(),
1479 Some(true),
1480 "the probe must release its temporary reservation"
1481 );
1482
1483 let namespace = home.join("disk-admission");
1485 let saved = home.join("saved-admission");
1486 std::fs::rename(&namespace, &saved).unwrap();
1487 std::os::unix::fs::symlink(&saved, &namespace).unwrap();
1488 assert_eq!(check(), Some(false));
1489 std::fs::remove_file(&namespace).unwrap();
1490 std::fs::rename(saved, namespace).unwrap();
1491 assert_eq!(check(), Some(true));
1492
1493 state.resource_block.as_mut().unwrap().cause = ResourceBlockCause::Cancelled { park: None };
1494 state.save_under(&home).unwrap();
1495 assert_eq!(
1496 machine_cause_resolved_with_admission(&task, &cfg, &home, |_| panic!(
1497 "a cancelled operation must remain held"
1498 )),
1499 None
1500 );
1501 state.resource_block.as_mut().unwrap().kind = "incremental cache admission".into();
1502 state.resource_block.as_mut().unwrap().cause = ResourceBlockCause::Other;
1503 state.save_under(&home).unwrap();
1504 assert_eq!(
1505 machine_cause_resolved_with_admission(&task, &cfg, &home, |_| panic!(
1506 "unproven incremental caches must remain held"
1507 )),
1508 None
1509 );
1510 task.runs.push("unreadable-run".into());
1511 assert_eq!(
1512 machine_cause_resolved_with_admission(&task, &cfg, &home, |_| panic!(
1513 "missing evidence must not release a hold"
1514 )),
1515 None
1516 );
1517 }
1518
1519 fn gate_disabled_config(dir: &std::path::Path) -> PathBuf {
1523 let config = dir.join("magi.toml");
1524 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
1525 config
1526 }
1527
1528 #[test]
1529 fn resumption_later_keep_held_answer_wins_but_an_older_answer_cannot_undo_release() {
1530 for source in ["cli", "web"] {
1531 for answer_after_release in [true, false] {
1532 let (dir, queue, questions) = store();
1533 let mut t = task("recovery", dir.path().join("repo"));
1534 t.hold_machine(Some("inspect remote first".into()));
1535 queue.put(&mut t).unwrap();
1536 let mut q = file_question(
1537 &questions,
1538 &t,
1539 Bucket::MachineUnknown,
1540 &JA,
1541 Timestamp::now(),
1542 )
1543 .unwrap();
1544 if !answer_after_release {
1545 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
1546 questions.put(&mut q).unwrap();
1547 }
1548 t.release_operator(source, None);
1549 queue.put(&mut t).unwrap();
1550 if answer_after_release {
1551 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
1552 questions.put(&mut q).unwrap();
1553 }
1554 apply_answers(&queue, &questions);
1555 let after = queue.get(&t.id).unwrap();
1556 assert!(after.triage_applied(&q.id));
1557 assert_eq!(after.operator_held(), answer_after_release);
1558 assert_eq!(
1559 after.status,
1560 if answer_after_release {
1561 TaskStatus::Held
1562 } else {
1563 TaskStatus::Queued
1564 }
1565 );
1566 assert!(apply_answers(&queue, &questions).is_empty());
1567 }
1568 }
1569 }
1570
1571 #[test]
1572 fn explicit_resumption_applies_legacy_queued_triage_once_and_preserves_later_holds() {
1573 let (dir, queue, questions) = store();
1574 let mut t = task("recover", dir.path().join("repo"));
1575 t.hold_machine(Some("inspect first".into()));
1576 queue.put(&mut t).unwrap();
1577 let mut q = file_question(
1578 &questions,
1579 &t,
1580 Bucket::MachineUnknown,
1581 &JA,
1582 Timestamp::now(),
1583 )
1584 .unwrap();
1585 assert!(q.actions.is_empty());
1586 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
1587 questions.put(&mut q).unwrap();
1588 t.release();
1590 t.instruction = "Reuse approved PR head".into();
1591 queue.put(&mut t).unwrap();
1592 assert_eq!(apply_answers(&queue, &questions), [t.id.clone()]);
1593 let mut after = queue.get(&t.id).unwrap();
1594 assert_eq!(
1595 after.resumption.as_ref().unwrap().question_id.as_deref(),
1596 Some(q.id.as_str())
1597 );
1598 assert_eq!(
1599 after.resumption.as_ref().unwrap().instruction,
1600 t.instruction
1601 );
1602 assert_eq!(after.answers[0].answer, JA.resume);
1603 assert!(after.triage_applied(&q.id));
1604 assert!(apply_answers(&Queue::at(dir.path().join("queue")), &questions).is_empty());
1605 after.hold_machine(Some("new blocker".into()));
1606 queue.put(&mut after).unwrap();
1607 let mut late = file_question(
1608 &questions,
1609 &after,
1610 Bucket::MachineUnknown,
1611 &EN,
1612 Timestamp::now(),
1613 )
1614 .unwrap();
1615 after.hold_manual(Some("keep held now".into()));
1616 queue.put(&mut after).unwrap();
1617 late.answer(Answer::Choice(late.choices[0].clone()))
1618 .unwrap();
1619 questions.put(&mut late).unwrap();
1620 apply_answers(&queue, &questions);
1621 let held = queue.get(&t.id).unwrap();
1622 assert!(held.operator_held());
1623 assert_eq!(held.hold_reason.as_deref(), Some("keep held now"));
1624 assert_eq!(held.resumption.as_ref().unwrap().generation, 1);
1625 }
1626
1627 #[test]
1628 fn a_resolved_machine_hold_is_requeued_automatically() {
1629 let (dir, q, questions) = store();
1630 let config = gate_disabled_config(dir.path());
1631 let mut t = task("disk pressure", dir.path().join("repo"));
1632 t.hold_machine(Some(
1633 "not enough free space to start a run: 10 bytes free, 100 required by \
1634 `[disk] min_free_bytes`"
1635 .to_owned(),
1636 ));
1637 q.put(&mut t).unwrap();
1638
1639 let report = run_once(&q, &questions, Some(&config), Timestamp::now());
1640 assert_eq!(report.resumed, [t.id.clone()]);
1641 assert!(report.asked.is_empty());
1642
1643 let back = q.get(&t.id).unwrap();
1644 assert_eq!(back.status, TaskStatus::Queued);
1645 assert!(back.hold_source.is_none());
1646 assert!(questions.list().is_empty(), "nothing needed asking");
1647 }
1648
1649 #[test]
1650 fn a_machine_hold_with_no_recognised_cause_gets_one_question_not_two() {
1651 let (dir, q, questions) = store();
1652 let mut t = task("gate went red", dir.path().join("repo"));
1653 t.hold_machine(Some("gate red".to_owned()));
1654 q.put(&mut t).unwrap();
1655
1656 let first = run_once(&q, &questions, None, Timestamp::now());
1657 assert_eq!(first.asked, [t.id.clone()]);
1658 assert!(first.resumed.is_empty());
1659
1660 let open: Vec<_> = questions
1661 .list()
1662 .into_iter()
1663 .filter(|q| q.status.open())
1664 .collect();
1665 assert_eq!(open.len(), 1);
1666 assert_eq!(open[0].run, t.id);
1667 assert_eq!(open[0].node, NODE);
1668 assert_eq!(open[0].choices.len(), 3);
1669
1670 let second = run_once(&q, &questions, None, Timestamp::now());
1672 assert!(second.asked.is_empty());
1673 assert_eq!(
1674 questions
1675 .list()
1676 .into_iter()
1677 .filter(|q| q.status.open())
1678 .count(),
1679 1
1680 );
1681 }
1682
1683 #[test]
1684 fn a_legacy_hold_with_no_recorded_source_gets_exactly_one_question() {
1685 let (dir, q, questions) = store();
1686 let mut t = task("schema 1 record", dir.path().join("repo"));
1687 t.status = TaskStatus::Held;
1688 assert!(t.hold_source.is_none(), "the case this test is about");
1689 q.put(&mut t).unwrap();
1690
1691 let first = run_once(&q, &questions, None, Timestamp::now());
1692 assert_eq!(first.asked, [t.id.clone()]);
1693
1694 let second = run_once(&q, &questions, None, Timestamp::now());
1695 assert!(
1696 second.asked.is_empty(),
1697 "the same legacy hold must not be asked about twice"
1698 );
1699 assert_eq!(
1700 questions
1701 .list()
1702 .into_iter()
1703 .filter(|q| q.status.open())
1704 .count(),
1705 1
1706 );
1707 }
1708
1709 #[test]
1710 fn dependency_resolution_detaches_legacy_short_refs_without_dropping_other_waits() {
1711 let (dir, queue, questions) = store();
1712 let mut root = task("root", dir.path().join("repo"));
1713 root.id = "20261013-193611-ca5b".into();
1714 root.hold_machine(Some("needs owner decision".into()));
1715 queue.put(&mut root).unwrap();
1716 let mut other = task("other", dir.path().join("repo"));
1717 other.id = "20261013-192213-feb2".into();
1718 queue.put(&mut other).unwrap();
1719 let mut waiting = task("waiting", dir.path().join("repo"));
1720 waiting.block(vec!["ca5b".into(), other.id.clone()], None);
1721 queue.put(&mut waiting).unwrap();
1722 detach_dependants(&queue, &questions, &root.id);
1723 let after = queue.get(&waiting.id).unwrap();
1724 assert_eq!(after.status, TaskStatus::Blocked);
1725 assert_eq!(after.blocked_by, [other.id]);
1726 }
1727
1728 #[test]
1729 fn a_manual_hold_is_never_auto_resumed() {
1730 let (dir, q, questions) = store();
1731 let mut t = task("operator stopped this", dir.path().join("repo"));
1732 t.hold_manual(Some("waiting on a decision".to_owned()));
1733 q.put(&mut t).unwrap();
1734
1735 let report = run_once(&q, &questions, None, Timestamp::now());
1736 assert!(report.resumed.is_empty());
1737 assert!(report.asked.is_empty());
1739
1740 let back = q.get(&t.id).unwrap();
1741 assert_eq!(back.status, TaskStatus::Held);
1742 assert_eq!(back.hold_source, Some(HoldSource::Manual));
1743 assert!(questions.list().is_empty());
1744 }
1745
1746 #[test]
1747 fn a_blocked_task_on_a_deleted_dependency_is_held_and_asked_about_in_one_pass() {
1748 let (dir, q, questions) = store();
1753 let mut still_going = task("still valid", dir.path().join("repo"));
1754 q.put(&mut still_going).unwrap();
1755
1756 let mut t = task("orphaned", dir.path().join("repo"));
1757 t.block(
1758 vec!["20260101-000000-gone".to_owned(), still_going.id.clone()],
1759 Some("waits on both".to_owned()),
1760 );
1761 q.put(&mut t).unwrap();
1762
1763 let report = run_once(&q, &questions, None, Timestamp::now());
1764 assert_eq!(report.quarantined, [t.id.clone()]);
1765 assert_eq!(
1766 report.asked,
1767 [t.id.clone()],
1768 "the fresh machine hold must earn a question in the same pass"
1769 );
1770
1771 let after = q.get(&t.id).unwrap();
1772 assert_eq!(after.status, TaskStatus::Held);
1773 assert_eq!(after.hold_source, Some(HoldSource::Machine));
1774 assert!(after.blocked_by.is_empty());
1775
1776 assert!(!is_disk_hold(&after));
1779
1780 let open: Vec<_> = questions
1781 .list()
1782 .into_iter()
1783 .filter(|q| q.status.open())
1784 .collect();
1785 assert_eq!(open.len(), 1);
1786 assert_eq!(open[0].run, t.id);
1787
1788 let second = run_once(&q, &questions, None, Timestamp::now());
1790 assert!(second.quarantined.is_empty());
1791 assert!(second.asked.is_empty());
1792 }
1793
1794 fn stuck_chain(q: &Queue, dir: &std::path::Path) -> (Task, Task, Task) {
1797 let mut root = task("root", dir.join("repo"));
1798 root.hold_manual(Some("waiting".to_owned()));
1799 q.put(&mut root).unwrap();
1800 let mut mid = task("mid", dir.join("repo"));
1801 mid.block(vec![root.id.clone()], None);
1802 q.put(&mut mid).unwrap();
1803 let mut leaf = task("leaf", dir.join("repo"));
1804 leaf.block(vec![mid.id.clone()], None);
1805 q.put(&mut leaf).unwrap();
1806 (root, mid, leaf)
1807 }
1808
1809 fn deps_questions(questions: &Questions) -> Vec<Question> {
1810 questions
1811 .list()
1812 .into_iter()
1813 .filter(|q| q.node == DEPS_NODE)
1814 .collect()
1815 }
1816
1817 fn answer_deps(questions: &Questions, choice: usize) {
1818 let mut asked = deps_questions(questions).remove(0);
1819 let c = asked.choices[choice].clone();
1820 asked.answer(Answer::Choice(c)).unwrap();
1821 questions.put(&mut asked).unwrap();
1822 }
1823
1824 #[test]
1825 fn a_stuck_chain_earns_one_question_naming_every_dependant_and_is_not_reasked() {
1826 let (dir, q, questions) = store();
1827 let (root, mid, leaf) = stuck_chain(&q, dir.path());
1828
1829 let first = run_once(&q, &questions, None, Timestamp::now());
1830 assert_eq!(first.asked, std::slice::from_ref(&root.id));
1831 let asked = deps_questions(&questions);
1832 assert_eq!(asked.len(), 1, "one question per root, not per dependant");
1833 assert_eq!(asked[0].run, root.id);
1834 assert_eq!(asked[0].choices.len(), 3);
1835 assert!(asked[0].detail.contains(mid.short()), "{}", asked[0].detail);
1836 assert!(
1837 asked[0].detail.contains(leaf.short()),
1838 "{}",
1839 asked[0].detail
1840 );
1841
1842 let second = run_once(&q, &questions, None, Timestamp::now());
1843 assert!(second.asked.is_empty());
1844 assert_eq!(deps_questions(&questions).len(), 1);
1845 assert!(pending_for(&questions, &q.get(&root.id).unwrap()));
1846 }
1847
1848 #[test]
1849 fn a_stuck_root_with_a_machine_hold_gets_only_the_dependency_question() {
1850 let (dir, q, questions) = store();
1851 let mut root = task("root", dir.path().join("repo"));
1852 root.hold_machine(Some("gate red".to_owned()));
1853 q.put(&mut root).unwrap();
1854 let mut dep = task("dep", dir.path().join("repo"));
1855 dep.block(vec![root.id.clone()], None);
1856 q.put(&mut dep).unwrap();
1857
1858 run_once(&q, &questions, None, Timestamp::now());
1859 run_once(&q, &questions, None, Timestamp::now());
1860 assert_eq!(deps_questions(&questions).len(), 1);
1861 assert_eq!(
1862 questions.list().len(),
1863 1,
1864 "no second question about the hold"
1865 );
1866 }
1867
1868 #[test]
1869 fn a_dependency_that_can_still_run_asks_nothing() {
1870 let (dir, q, questions) = store();
1871 let mut live = task("live", dir.path().join("repo"));
1872 q.put(&mut live).unwrap();
1873 let mut dep = task("dep", dir.path().join("repo"));
1874 dep.block(vec![live.id.clone()], None);
1875 q.put(&mut dep).unwrap();
1876 let report = run_once(&q, &questions, None, Timestamp::now());
1877 assert!(report.asked.is_empty());
1878 assert!(questions.list().is_empty());
1879 }
1880
1881 #[test]
1882 fn answering_release_requeues_the_root_and_is_not_reasked() {
1883 let (dir, q, questions) = store();
1884 let (root, _mid, _leaf) = stuck_chain(&q, dir.path());
1885 run_once(&q, &questions, None, Timestamp::now());
1886 answer_deps(&questions, 0);
1887
1888 let report = run_once(&q, &questions, None, Timestamp::now());
1889 assert_eq!(report.answered, std::slice::from_ref(&root.id));
1890 assert!(report.asked.is_empty(), "applying must not re-ask");
1891 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Queued);
1892 let again = run_once(&q, &questions, None, Timestamp::now());
1893 assert!(again.asked.is_empty() && again.answered.is_empty());
1894 assert_eq!(deps_questions(&questions).len(), 1);
1895 }
1896
1897 #[test]
1898 fn answering_detach_frees_the_direct_dependant_and_keeps_the_root() {
1899 let (dir, q, questions) = store();
1900 let (root, mid, leaf) = stuck_chain(&q, dir.path());
1901 run_once(&q, &questions, None, Timestamp::now());
1902 answer_deps(&questions, 2);
1903
1904 let report = run_once(&q, &questions, None, Timestamp::now());
1905 assert!(report.asked.is_empty());
1906 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
1907 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
1908 let leaf = q.get(&leaf.id).unwrap();
1909 assert_eq!(leaf.status, TaskStatus::Blocked, "still waits on mid");
1910 assert_eq!(leaf.blocked_by, std::slice::from_ref(&mid.id));
1911 }
1912
1913 #[test]
1914 fn a_dependant_that_can_progress_through_another_blocker_is_not_stuck() {
1915 let (dir, q, questions) = store();
1916 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
1917 let mut live = task("live", dir.path().join("repo"));
1918 q.put(&mut live).unwrap();
1919 let mut both = q.get(&mid.id).unwrap();
1920 both.block(vec![root.id.clone(), live.id.clone()], None);
1921 q.put(&mut both).unwrap();
1922 assert!(
1924 run_once(&q, &questions, None, Timestamp::now())
1925 .asked
1926 .is_empty()
1927 );
1928 }
1929
1930 #[test]
1931 fn answering_discard_detaches_then_removes_the_root() {
1932 let (dir, q, questions) = store();
1933 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
1934 run_once(&q, &questions, None, Timestamp::now());
1935 answer_deps(&questions, 1);
1936
1937 let report = run_once(&q, &questions, None, Timestamp::now());
1938 assert!(q.get(&root.id).is_err());
1939 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
1940 assert!(
1941 report.asked.is_empty(),
1942 "no per-dependant quarantine question"
1943 );
1944 assert!(report.quarantined.is_empty());
1945 }
1946
1947 #[test]
1948 fn an_unmatched_deps_answer_changes_nothing_and_is_not_reasked() {
1949 let (dir, q, questions) = store();
1950 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
1951 run_once(&q, &questions, None, Timestamp::now());
1952 let mut asked = deps_questions(&questions).remove(0);
1953 asked.choices.clear();
1954 asked.answer(Answer::Text("dunno".to_owned())).unwrap();
1955 questions.put(&mut asked).unwrap();
1956
1957 for _ in 0..2 {
1958 let report = run_once(&q, &questions, None, Timestamp::now());
1959 assert!(report.asked.is_empty() && report.answered.is_empty());
1960 }
1961 assert_eq!(deps_questions(&questions).len(), 1);
1962 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
1963 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Blocked);
1964 }
1965
1966 #[test]
1967 fn a_dependency_cycle_terminates_and_is_asked_about_once() {
1968 let (dir, q, questions) = store();
1969 let mut a = task("a", dir.path().join("repo"));
1970 let mut b = task("b", dir.path().join("repo"));
1971 a.block(vec![b.id.clone()], None);
1972 b.block(vec![a.id.clone()], None);
1973 q.put(&mut a).unwrap();
1974 q.put(&mut b).unwrap();
1975
1976 let first = run_once(&q, &questions, None, Timestamp::now());
1977 assert_eq!(first.asked.len(), 1);
1978 let second = run_once(&q, &questions, None, Timestamp::now());
1979 assert!(second.asked.is_empty());
1980 assert_eq!(deps_questions(&questions).len(), 1);
1981 }
1982
1983 #[test]
1984 fn a_missing_dependency_is_still_quarantined_not_asked_about_as_stuck() {
1985 let (dir, q, questions) = store();
1986 let mut t = task("orphan", dir.path().join("repo"));
1987 t.block(vec!["20260101-000000-gone".to_owned()], None);
1988 q.put(&mut t).unwrap();
1989 let report = run_once(&q, &questions, None, Timestamp::now());
1990 assert_eq!(report.quarantined, [t.id.clone()]);
1991 assert!(deps_questions(&questions).is_empty());
1992 }
1993
1994 #[test]
1995 fn a_stale_manual_hold_earns_a_two_choice_question() {
1996 let (dir, q, questions) = store();
1997 let mut t = task("been sitting a while", dir.path().join("repo"));
1998 t.hold_manual(Some("waiting on a decision".to_owned()));
1999 q.put(&mut t).unwrap();
2000 let mut back = q.get(&t.id).unwrap();
2002 back.updated_at = Timestamp::now() - SignedDuration::new(8 * 24 * 60 * 60, 0);
2003 std::fs::write(
2004 q.path_of(&back.id),
2005 serde_json::to_string_pretty(&back).unwrap(),
2006 )
2007 .unwrap();
2008
2009 let report = run_once(&q, &questions, None, Timestamp::now());
2010 assert_eq!(report.asked, [t.id.clone()]);
2011 let open: Vec<_> = questions
2012 .list()
2013 .into_iter()
2014 .filter(|q| q.status.open())
2015 .collect();
2016 assert_eq!(open.len(), 1);
2017 assert_eq!(open[0].choices.len(), 2);
2018 }
2019
2020 #[test]
2021 fn answering_resume_releases_the_task() {
2022 let (dir, q, questions) = store();
2023 let mut t = task("gate went red", dir.path().join("repo"));
2024 t.hold_machine(Some("gate red".to_owned()));
2025 q.put(&mut t).unwrap();
2026 run_once(&q, &questions, None, Timestamp::now());
2027
2028 let mut asked = questions
2029 .list()
2030 .into_iter()
2031 .find(|q| q.run == t.id)
2032 .unwrap();
2033 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
2034 questions.put(&mut asked).unwrap();
2035
2036 let report = run_once(&q, &questions, None, Timestamp::now());
2037 assert_eq!(report.answered, [t.id.clone()]);
2038 let back = q.get(&t.id).unwrap();
2039 assert_eq!(back.status, TaskStatus::Queued);
2040 assert!(back.hold_source.is_none());
2041 }
2042
2043 fn resumed_then_failed(q: &Queue, questions: &Questions, dir: &std::path::Path) -> Task {
2045 let mut t = task("gate went red", dir.join("repo"));
2046 t.hold_machine(Some("gate red".to_owned()));
2047 q.put(&mut t).unwrap();
2048 run_once(q, questions, None, Timestamp::now());
2049 let mut asked = questions
2050 .list()
2051 .into_iter()
2052 .find(|q| q.run == t.id)
2053 .unwrap();
2054 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
2055 questions.put(&mut asked).unwrap();
2056
2057 let report = run_once(q, questions, None, Timestamp::now());
2058 assert_eq!(report.answered, [t.id.clone()]);
2059 let mut back = q.get(&t.id).unwrap();
2060 assert_eq!(back.status, TaskStatus::Queued);
2061 assert_eq!(back.attempts, 0);
2062
2063 back.start("run-1".to_owned());
2064 back.fail("rebase conflict", 1);
2065 assert_eq!(back.status, TaskStatus::Held);
2066 q.put(&mut back).unwrap();
2067 back
2068 }
2069
2070 #[test]
2071 fn a_resume_answer_is_applied_once_and_a_new_machine_hold_is_asked_about() {
2072 let (dir, q, questions) = store();
2073 let t = resumed_then_failed(&q, &questions, dir.path());
2074
2075 let report = run_once(&q, &questions, None, Timestamp::now());
2076 assert!(report.answered.is_empty(), "the old answer must not replay");
2077 assert_eq!(report.asked, std::slice::from_ref(&t.id));
2078 let back = q.get(&t.id).unwrap();
2079 assert_eq!(back.status, TaskStatus::Held);
2080 assert_eq!(
2081 questions
2082 .list()
2083 .into_iter()
2084 .filter(|q| q.status.open())
2085 .count(),
2086 1
2087 );
2088 }
2089
2090 #[test]
2091 fn a_manual_hold_placed_after_a_resume_is_not_undone_by_the_old_answer() {
2092 let (dir, q, questions) = store();
2093 let mut t = resumed_then_failed(&q, &questions, dir.path());
2094 t.hold_manual(Some("operator stopped this".to_owned()));
2095 q.put(&mut t).unwrap();
2096 let before = questions.list().len();
2097
2098 let report = run_once(&q, &questions, None, Timestamp::now());
2099 assert!(report.answered.is_empty());
2100 assert!(report.asked.is_empty());
2101 let back = q.get(&t.id).unwrap();
2102 assert_eq!(back.status, TaskStatus::Held);
2103 assert_eq!(back.hold_source, Some(HoldSource::Manual));
2104 assert_eq!(questions.list().len(), before);
2105 }
2106
2107 #[test]
2108 fn answering_not_yet_keeps_it_held_as_a_manual_hold_and_does_not_reapply() {
2109 let (dir, q, questions) = store();
2110 let mut t = task("gate went red", dir.path().join("repo"));
2111 t.hold_machine(Some("gate red".to_owned()));
2112 q.put(&mut t).unwrap();
2113 run_once(&q, &questions, None, Timestamp::now());
2114
2115 let mut asked = questions
2116 .list()
2117 .into_iter()
2118 .find(|q| q.run == t.id)
2119 .unwrap();
2120 asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
2121 questions.put(&mut asked).unwrap();
2122
2123 let report = run_once(&q, &questions, None, Timestamp::now());
2124 assert_eq!(report.answered, [t.id.clone()]);
2125 let back = q.get(&t.id).unwrap();
2126 assert_eq!(back.status, TaskStatus::Held);
2127 assert_eq!(back.hold_source, Some(HoldSource::Manual));
2128 assert!(
2129 back.hold_reason
2130 .as_deref()
2131 .is_some_and(|r| r.contains("gate red")),
2132 "the original cause must survive a \"not yet\" answer, not just the \
2133 triage marker: {:?}",
2134 back.hold_reason
2135 );
2136
2137 let third = run_once(&q, &questions, None, Timestamp::now());
2141 assert!(third.answered.is_empty());
2142 assert!(third.asked.is_empty());
2143 }
2144
2145 #[test]
2146 fn answering_discard_removes_the_task_entirely() {
2147 let (dir, q, questions) = store();
2148 let mut t = task("gate went red", dir.path().join("repo"));
2149 t.hold_machine(Some("gate red".to_owned()));
2150 q.put(&mut t).unwrap();
2151 run_once(&q, &questions, None, Timestamp::now());
2152
2153 let mut asked = questions
2154 .list()
2155 .into_iter()
2156 .find(|q| q.run == t.id)
2157 .unwrap();
2158 asked.answer(Answer::Choice(EN.discard.to_owned())).unwrap();
2159 questions.put(&mut asked).unwrap();
2160
2161 let report = run_once(&q, &questions, None, Timestamp::now());
2162 assert_eq!(report.answered, [t.id.clone()]);
2163 assert!(
2164 q.get(&t.id).is_err(),
2165 "\"discard it\" (捨ててよい) must actually discard the task, not \
2166 just leave it sitting held forever"
2167 );
2168 }
2169
2170 #[test]
2171 fn an_answer_is_read_by_its_position_in_choices_not_by_the_callers_current_language() {
2172 let (dir, q, questions) = store();
2174 let ja_config = dir.path().join("ja.toml");
2175 std::fs::write(&ja_config, "[graph]\nlanguage = \"ja\"\n").unwrap();
2176 let mut t = task("gate went red", dir.path().join("repo"));
2177 t.hold_machine(Some("gate red".to_owned()));
2178 q.put(&mut t).unwrap();
2179 run_once(&q, &questions, Some(&ja_config), Timestamp::now());
2180
2181 let mut asked = questions
2182 .list()
2183 .into_iter()
2184 .find(|q| q.run == t.id)
2185 .unwrap();
2186 assert_eq!(asked.choices[0], JA.resume, "filed in Japanese");
2187 asked.answer(Answer::Choice(JA.resume.to_owned())).unwrap();
2188 questions.put(&mut asked).unwrap();
2189
2190 let en_config = dir.path().join("en.toml");
2195 std::fs::write(&en_config, "[graph]\nlanguage = \"en\"\n").unwrap();
2196 let report = run_once(&q, &questions, Some(&en_config), Timestamp::now());
2197 assert_eq!(report.answered, [t.id.clone()]);
2198 let back = q.get(&t.id).unwrap();
2199 assert_eq!(
2200 back.status,
2201 TaskStatus::Queued,
2202 "a resume answer must resume the task regardless of which \
2203 language it is read back in"
2204 );
2205 }
2206
2207 #[test]
2208 fn a_question_falls_back_to_last_error_when_hold_reason_was_never_set() {
2209 let (dir, q, questions) = store();
2214 let mut t = task("kept failing the gate", dir.path().join("repo"));
2215 t.start("run-1".to_owned());
2216 t.fail("gate red three times running", 1);
2217 assert_eq!(t.status, TaskStatus::Held);
2218 t.hold_reason = None; q.put(&mut t).unwrap();
2220
2221 run_once(&q, &questions, None, Timestamp::now());
2222 let asked = questions
2223 .list()
2224 .into_iter()
2225 .find(|q| q.run == t.id)
2226 .unwrap();
2227 assert!(
2228 asked.detail.contains("gate red three times running"),
2229 "the question must surface `last_error` when there is no \
2230 `hold_reason` to show instead: {}",
2231 asked.detail
2232 );
2233 }
2234
2235 #[test]
2236 fn open_question_for_and_open_task_ids_reflect_only_what_is_still_waiting() {
2237 let (dir, q, questions) = store();
2238 let mut t = task("gate went red", dir.path().join("repo"));
2239 t.hold_machine(Some("gate red".to_owned()));
2240 q.put(&mut t).unwrap();
2241
2242 assert!(open_question_for(&questions, &t.id).is_none());
2243 assert!(!open_task_ids(&questions).contains(&t.id));
2244
2245 run_once(&q, &questions, None, Timestamp::now());
2246 assert!(open_question_for(&questions, &t.id).is_some());
2247 assert!(open_task_ids(&questions).contains(&t.id));
2248
2249 let mut asked = questions
2250 .list()
2251 .into_iter()
2252 .find(|q| q.run == t.id)
2253 .unwrap();
2254 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
2255 questions.put(&mut asked).unwrap();
2256
2257 assert!(
2258 open_question_for(&questions, &t.id).is_none(),
2259 "an answered question is no longer open"
2260 );
2261 assert!(!open_task_ids(&questions).contains(&t.id));
2262 }
2263
2264 #[test]
2265 fn pending_for_stays_true_between_an_answer_and_the_next_run_once_pass() {
2266 let (dir, q, questions) = store();
2272 let mut t = task("gate went red", dir.path().join("repo"));
2273 t.hold_machine(Some("gate red".to_owned()));
2274 q.put(&mut t).unwrap();
2275
2276 assert!(!pending_for(&questions, &t));
2277
2278 run_once(&q, &questions, None, Timestamp::now());
2279 let held = q.get(&t.id).unwrap();
2280 assert!(pending_for(&questions, &held), "still waiting on an answer");
2281
2282 let mut asked = questions
2283 .list()
2284 .into_iter()
2285 .find(|q| q.run == t.id)
2286 .unwrap();
2287 asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
2288 questions.put(&mut asked).unwrap();
2289 assert!(!asked.status.open());
2290
2291 let still_held = q.get(&t.id).unwrap();
2293 assert!(
2294 pending_for(&questions, &still_held),
2295 "answered but not yet applied is still pending"
2296 );
2297
2298 run_once(&q, &questions, None, Timestamp::now());
2299 let after = q.get(&t.id).unwrap();
2300 assert!(
2301 !pending_for(&questions, &after),
2302 "the answer is applied now, nothing left pending"
2303 );
2304 }
2305}