1use std::path::{Path, PathBuf};
86use std::time::Duration;
87
88use jiff::Timestamp;
89
90use crate::ask::{Question, QuestionStatus, Questions};
91use crate::config::Config;
92use crate::queue::{HoldSource, OperatorResume, Queue, Task, TaskStatus};
93
94pub const NODE: &str = "triage";
97
98pub const DEPS_NODE: &str = "triage-deps";
102
103const SEAT: &str = "triage";
108
109const MANUAL_STALE_AFTER: Duration = Duration::from_secs(7 * 24 * 60 * 60);
121
122struct Wording {
126 lang: &'static str,
127 resume: &'static str,
128 wait: &'static str,
129 discard: &'static str,
130}
131
132const EN: Wording = Wording {
133 lang: "en",
134 resume: "resume it",
135 wait: "not yet",
136 discard: "discard it",
137};
138
139const JA: Wording = Wording {
140 lang: "ja",
141 resume: "再開してよい",
142 wait: "まだ待って",
143 discard: "捨ててよい",
144};
145
146fn wording(language: &str) -> &'static Wording {
149 if crate::lang::is_japanese(language) {
150 &JA
151 } else {
152 &EN
153 }
154}
155
156impl Wording {
157 fn choices3(&self) -> Vec<String> {
158 vec![
159 self.resume.to_owned(),
160 self.wait.to_owned(),
161 self.discard.to_owned(),
162 ]
163 }
164
165 fn choices_manual(&self) -> Vec<String> {
166 let (resume, wait) = if self.lang == "ja" {
167 ("再開する", "まだ止めておく")
168 } else {
169 ("resume it", "keep it held")
170 };
171 vec![resume.to_owned(), wait.to_owned(), self.discard.to_owned()]
172 }
173
174 fn source_label(&self, source: Option<HoldSource>) -> &'static str {
175 match (self.lang, source) {
176 ("ja", Some(HoldSource::Machine)) => "machine(機械による自動保留)",
177 ("ja", Some(HoldSource::Manual)) => "manual(操作者による手動保留)",
178 ("ja", None) => "unknown(schema 3 未満の旧レコード、または理由未記録)",
179 (_, Some(HoldSource::Machine)) => "machine (automatic recovery hold)",
180 (_, Some(HoldSource::Manual)) => "manual (an operator held this)",
181 (_, None) => "unknown (pre-schema-3 record, or never recorded)",
182 }
183 }
184
185 fn detail(&self, task: &Task, why: &str) -> String {
194 let none = if self.lang == "ja" {
195 "(記録なし)"
196 } else {
197 "(none recorded)"
198 };
199 let reason = task
200 .hold_reason
201 .as_deref()
202 .or(task.last_error.as_deref())
203 .unwrap_or(none);
204 format!(
205 "task: {} ({})\ntitle: {}\nhold source: {}\nhold reason: {reason}\n\n{why}",
206 task.id,
207 task.short(),
208 task.title,
209 self.source_label(task.hold_source),
210 )
211 }
212
213 fn summary_machine_unknown(&self, task: &Task) -> String {
214 if self.lang == "ja" {
215 format!("保留タスク {} の再開可否を判断してください", task.short())
216 } else {
217 format!("decide whether to resume held task {}", task.short())
218 }
219 }
220
221 fn why_machine(&self) -> &'static str {
222 if self.lang == "ja" {
223 "機械的な保留(machine hold)ですが、原因がすでに解消しているかを自動では判断できませんでした。"
224 } else {
225 "This is a machine hold, but whether its cause has resolved could not be \
226 checked automatically."
227 }
228 }
229
230 fn summary_conductor_override(&self, task: &Task) -> String {
231 if self.lang == "ja" {
232 format!(
233 "再開と回答済みのタスク {} を conductor が再び保留しました",
234 task.short()
235 )
236 } else {
237 format!(
238 "task {} was resumed at your word, but the conductor held it again",
239 task.short()
240 )
241 }
242 }
243
244 fn why_conductor_override(&self, o: &OperatorResume) -> String {
245 let reason = o.conductor_rehold.as_deref().unwrap_or_default();
246 if self.lang == "ja" {
247 format!(
248 "{} に再開と回答済みですが、conductor が再び hold しました。conductor の理由: \
249 {reason}\n\n強制再キューを選ぶと、以後 conductor はこのタスクを hold できません。",
250 o.at
251 )
252 } else {
253 format!(
254 "You answered \"resume\" at {}, but the conductor held the task again. \
255 Its reason: {reason}\n\nForcing a requeue stops the conductor from \
256 holding this task again.",
257 o.at
258 )
259 }
260 }
261
262 fn choices_conductor_override(&self) -> Vec<String> {
264 if self.lang == "ja" {
265 vec![
266 "強制再キュー(conductor は再 hold 不可)".to_owned(),
267 "手動 hold のまま".to_owned(),
268 "捨ててよい".to_owned(),
269 ]
270 } else {
271 vec![
272 "force requeue (conductor must not hold again)".to_owned(),
273 "keep held (manual)".to_owned(),
274 "discard".to_owned(),
275 ]
276 }
277 }
278
279 fn summary_legacy(&self, task: &Task) -> String {
280 if self.lang == "ja" {
281 format!(
282 "hold_source が不明な保留タスク {} を確認してください",
283 task.short()
284 )
285 } else {
286 format!(
287 "held task {} has no recorded hold source - please take a look",
288 task.short()
289 )
290 }
291 }
292
293 fn why_legacy(&self) -> &'static str {
294 if self.lang == "ja" {
295 "hold_source が記録されていません。schema 3 より前のレコードか、理由が記録されなかった \
296 holdです。人が意図して止めたのか、クラッシュや強制再起動で宙に浮いただけなのか、\
297 このデータからは区別できません。"
298 } else {
299 "No hold_source was recorded - either a pre-schema-3 record, or a hold whose \
300 reason was never written down. Whether this was a deliberate hold or the \
301 leftover of a crash cannot be told from the data alone."
302 }
303 }
304
305 fn summary_manual_stale(&self, task: &Task, days: i64) -> String {
306 if self.lang == "ja" {
307 format!(
308 "{days}日間 保留されたままの手動保留タスク {} を確認してください",
309 task.short()
310 )
311 } else {
312 format!(
313 "held task {} has been on a manual hold for {days} day(s)",
314 task.short()
315 )
316 }
317 }
318
319 fn why_manual(&self) -> &'static str {
320 if self.lang == "ja" {
321 "操作者が明示的に止めた保留ですが、長期間そのままになっています。まだ止めておくか、\
322 再開するか教えてください。"
323 } else {
324 "An operator held this on purpose, but it has sat untouched for a while. Say \
325 whether to keep holding it or resume it."
326 }
327 }
328}
329
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
332enum Bucket {
333 MachineUnknown,
335 ConductorOverride,
338 Legacy,
340 ManualStale,
342}
343
344#[derive(Debug, Clone, Default)]
346pub struct Report {
347 pub resumed: Vec<String>,
350 pub asked: Vec<String>,
352 pub answered: Vec<String>,
354 pub quarantined: Vec<String>,
359 pub superseded: Vec<String>,
362 pub needs_owner: Vec<String>,
365}
366
367impl Report {
368 pub fn is_empty(&self) -> bool {
371 self.resumed.is_empty()
372 && self.asked.is_empty()
373 && self.answered.is_empty()
374 && self.quarantined.is_empty()
375 && self.superseded.is_empty()
376 && self.needs_owner.is_empty()
377 }
378}
379
380fn repo_for(task: &Task) -> PathBuf {
384 if task.repo.as_os_str().is_empty() {
385 PathBuf::from(".")
386 } else {
387 task.repo.clone()
388 }
389}
390
391fn is_disk_hold(task: &Task) -> bool {
393 task.has_disk_capacity_cause()
394 || (task.schema < 22
395 && task
396 .hold_reason
397 .as_deref()
398 .is_some_and(crate::disk::is_gate_reason))
399}
400
401pub(crate) fn disk_wait_eligible(task: &Task) -> bool {
402 disk_wait_known(task, &crate::run::home())
403}
404
405fn disk_wait_known(task: &Task, home: &Path) -> bool {
407 if task.status != TaskStatus::Held
408 || task.hold_source != Some(HoldSource::Machine)
409 || task
410 .resume_override
411 .as_ref()
412 .is_some_and(|o| o.conductor_rehold.is_some())
413 {
414 return false;
415 }
416 if task.has_disk_capacity_cause() {
417 return true;
418 }
419 if task.resume_override.is_some() {
421 return false;
422 }
423 if is_disk_hold(task) {
424 return true;
425 }
426 if task.schema >= 22 {
427 return false;
428 }
429 if !task.hold_reason.as_deref().is_some_and(|r| {
430 r.starts_with(crate::disk::RUNNING_PRESSURE) || r.starts_with(crate::cache::RESOURCE_HOLD)
431 }) {
432 return false;
433 }
434 let Some(id) = task.execution_runs().last() else {
435 return false;
436 };
437 let Ok(state) = crate::run::RunState::load_under(id, home) else {
438 return false;
439 };
440 state.id == *id
441 && state.resource_block.as_ref().is_some_and(|b| {
442 let expected = match b.kind.as_str() {
443 "disk pressure" => format!("{}{}", crate::disk::RUNNING_PRESSURE, b.detail),
444 "disk admission" => format!(
445 "{}{}; no attempt was spent; resume to retry the affected operation",
446 crate::cache::RESOURCE_HOLD,
447 b.description()
448 ),
449 _ => return false,
450 };
451 matches!(b.cause, crate::run::ResourceBlockCause::Other)
452 && task.hold_reason.as_deref() == Some(expected.as_str())
453 })
454}
455
456fn machine_cause_resolved(task: &Task, cfg: &Config) -> Option<bool> {
461 machine_cause_resolved_under(task, cfg, &crate::run::home())
462}
463
464fn machine_cause_resolved_under(task: &Task, cfg: &Config, home: &Path) -> Option<bool> {
465 machine_cause_resolved_with_admission(task, cfg, home, |paths, floor| {
466 let admit = if paths.contains(&crate::build_target::root(home)) {
467 crate::retention::OutputLease::admit_isolated
468 } else {
469 crate::retention::OutputLease::admit
470 };
471 admit(home, paths, floor).is_ok()
472 })
473}
474
475fn cache_wait_run(task: &Task, home: &Path) -> Option<crate::run::RunState> {
476 if !task
477 .hold_reason
478 .as_deref()?
479 .starts_with(crate::cache::RESOURCE_HOLD)
480 {
481 return None;
482 }
483 let id = task.execution_runs().last()?;
484 let state = crate::run::RunState::load_under(id, home).ok()?;
485 (state.id == *id).then_some(state)
486}
487
488fn known_isolated_cache_wait(task: &Task, home: &Path) -> bool {
489 let Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout { target, .. }) =
490 cache_wait_run(task, home)
491 .and_then(|state| state.resource_block)
492 .map(|block| block.cause)
493 else {
494 return false;
495 };
496 crate::build_target::check_prune(home, &target).is_ok_and(|owned| owned)
497}
498
499fn machine_cause_resolved_with_admission(
500 task: &Task,
501 cfg: &Config,
502 home: &Path,
503 admission_available: impl Fn(&[PathBuf], u64) -> bool,
504) -> Option<bool> {
505 if disk_wait_known(task, home) {
506 let saved = if let Some(id) = task.disk_wait_run() {
507 let Ok(state) = crate::run::RunState::load_under(id, home) else {
508 return Some(false);
509 };
510 if state.id != *id || !state.status.resumable() {
511 return Some(false);
512 }
513 Some(state)
514 } else {
515 None
516 };
517 let override_config = task
518 .build_cache_override(cfg)
519 .map(|(mode, _)| mode)
520 .filter(|mode| saved.is_none() && *mode != cfg.verify.build_cache)
521 .map(|mode| {
522 let mut config = cfg.clone();
523 config.verify.build_cache = mode;
524 config
525 });
526 let (repo, config) = saved.as_ref().map_or_else(
527 || (repo_for(task), override_config.as_ref().unwrap_or(cfg)),
528 |state| (state.repo.clone(), &state.config),
529 );
530 if crate::daemon::disk_gate_at(&repo, config, || home.to_owned()).is_some() {
531 return Some(false);
532 }
533 let mut paths = vec![repo];
534 if let Some(state) = &saved {
535 paths.push(state.worktree_root());
536 paths.extend(state.candidates.iter().map(|c| c.worktree.clone()));
537 } else {
538 paths.push(
539 config
540 .graph
541 .worktree_root
542 .clone()
543 .unwrap_or_else(crate::run::default_worktree_root),
544 );
545 }
546 if crate::build_target::isolated(config) {
547 paths.push(crate::build_target::root(home));
548 } else {
549 paths.extend(config.cache_dir());
550 }
551 let mut floor = config.disk.min_free_bytes;
552 if saved.is_some()
553 && !crate::build_target::isolated(config)
554 && !crate::build_target::isolated(cfg)
555 {
556 let repo = repo_for(task);
557 if crate::daemon::disk_gate_at(&repo, cfg, || home.to_owned()).is_some() {
558 return Some(false);
559 }
560 paths.push(repo);
561 paths.extend(cfg.cache_dir());
562 paths.push(
563 cfg.graph
564 .worktree_root
565 .clone()
566 .unwrap_or_else(crate::run::default_worktree_root),
567 );
568 floor = floor.max(cfg.disk.min_free_bytes);
569 }
570 return Some(admission_available(&paths, floor));
571 }
572 if let Some(state) = cache_wait_run(task, home) {
573 let block = state.resource_block.as_ref()?;
574 if let crate::run::ResourceBlockCause::IsolatedCacheTimeout { target, .. } = &block.cause {
575 return Some(
576 crate::build_target::check_prune(home, target).is_ok_and(|owned| owned)
577 && !crate::cache::in_use(home, target),
578 );
579 }
580 if block.kind != "shared build cache"
583 || !matches!(block.cause, crate::run::ResourceBlockCause::Timeout { .. })
584 {
585 return None;
586 }
587 return Some(
588 state
589 .config
590 .cache_dir()
591 .is_none_or(|dir| !crate::cache::in_use(home, &dir)),
592 );
593 }
594 None
595}
596
597fn manual_is_stale(task: &Task, now: Timestamp) -> bool {
601 now.as_second() - task.updated_at.as_second() > MANUAL_STALE_AFTER.as_secs() as i64
602}
603
604fn marker_for(q: &Question) -> String {
607 format!("[triage:{}]", q.short())
608}
609
610fn already_applied(task: &Task, q: &Question) -> bool {
613 if task.triage_applied(&q.id) {
614 return true;
615 }
616 let marker = marker_for(q);
619 task.hold_reason
620 .as_deref()
621 .is_some_and(|r| r.contains(marker.as_str()))
622}
623
624fn consumed(task: &Task, q: &Question) -> bool {
626 if q.node == NODE {
627 already_applied(task, q)
628 } else {
629 task.triage_applied(&q.id)
630 }
631}
632
633pub(crate) struct RecoveryIndex {
636 latest: std::collections::HashMap<(String, String), Question>,
637}
638
639impl RecoveryIndex {
640 pub(crate) fn load(questions: &Questions) -> Self {
641 let queue = Queue::at(
642 questions
643 .root()
644 .parent()
645 .unwrap_or(Path::new(""))
646 .join("queue"),
647 );
648 let tasks = queue.list();
649 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
650 Self::from_scan(&queue, &tasks, questions.list_for_effects_in(&ownership))
651 }
652
653 fn from_scan(queue: &Queue, tasks: &[Task], all: Vec<Question>) -> Self {
654 let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
655 let by_id: std::collections::HashMap<_, _> =
656 tasks.iter().map(|task| (task.id.as_str(), task)).collect();
657 let exact: std::collections::HashSet<_> = ids.iter().map(String::as_str).collect();
658 let mut aliases: std::collections::HashMap<&str, Option<&str>> = Default::default();
659 for id in &ids {
660 for boundary in id
661 .char_indices()
662 .map(|(i, _)| i)
663 .chain(std::iter::once(id.len()))
664 {
665 for alias in [&id[..boundary], &id[boundary..]] {
666 let entry = aliases.entry(alias).or_insert(Some(id));
667 if *entry != Some(id.as_str()) {
668 *entry = None;
669 }
670 }
671 }
672 }
673 let mut index = Self {
674 latest: Default::default(),
675 };
676 for q in all {
677 if q.node != NODE && q.node != DEPS_NODE {
678 continue;
679 }
680 let resolved = if exact.contains(q.run.as_str()) {
681 Some(q.run.as_str())
682 } else {
683 aliases.get(q.run.as_str()).copied().flatten()
684 };
685 if let Some(id) = resolved
686 && by_id.get(id).is_some_and(|task| {
687 crate::repair_budget::reconcile::superseded_question(task, &q)
688 })
689 {
690 continue;
691 }
692 let key = (q.node.clone(), q.run.clone());
693 let entry = index.latest.entry(key).or_insert_with(|| q.clone());
694 if (q.asked_at, &q.id) > (entry.asked_at, &entry.id) {
695 *entry = q;
696 }
697 }
698 index
699 }
700
701 fn latest(&self, node: &str, task_id: &str) -> Option<Question> {
702 self.latest
703 .get(&(node.to_owned(), task_id.to_owned()))
704 .cloned()
705 }
706
707 pub(crate) fn pending(&self, task: &Task) -> Vec<Question> {
708 [NODE, DEPS_NODE]
709 .into_iter()
710 .filter_map(|node| {
711 self.latest(node, &task.id).filter(|q| {
712 !consumed(task, q)
713 && (q.status.open()
714 || awaiting_task_chat(q, task)
715 || q.status == QuestionStatus::Answered)
716 })
717 })
718 .collect()
719 }
720
721 fn displayed_open(&self, task: &Task) -> Option<Question> {
722 [NODE, DEPS_NODE]
723 .into_iter()
724 .filter(|node| {
725 task.status == TaskStatus::Held
726 || (*node == DEPS_NODE && task.status == TaskStatus::Blocked)
727 })
728 .filter_map(|node| self.latest(node, &task.id))
729 .find(|q| q.status.open() && !consumed(task, q))
730 }
731}
732
733#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736enum AnswerAction {
737 Resume,
741 Discard,
744 KeepHeld,
749}
750
751fn interpret_answer(q: &Question) -> AnswerAction {
764 let resolution = q.resolution().unwrap_or_default();
765 match q.choices.iter().position(|c| *c == resolution) {
766 Some(0) => AnswerAction::Resume,
767 Some(2) => AnswerAction::Discard,
768 _ => AnswerAction::KeepHeld,
769 }
770}
771
772pub(crate) fn contextual_keep_held(q: &Question, label: &str) -> bool {
775 q.node == NODE
776 && q.seat == SEAT
777 && q.actions.is_empty()
778 && q.choices.get(1).is_some_and(|c| c == label)
779}
780
781fn keep_held_note(task: &Task, q: &Question, resolution: &str) -> String {
786 let marker = format!("{} operator: {resolution}", marker_for(q));
787 match task.hold_reason.as_deref() {
788 Some(existing) if !existing.is_empty() => format!("{existing}\n{marker}"),
789 _ => marker,
790 }
791}
792
793fn file_question(
797 questions: &Questions,
798 ownership: &crate::task_chat::InquiryOwnership,
799 task: &Task,
800 bucket: Bucket,
801 w: &Wording,
802 now: Timestamp,
803) -> Option<Question> {
804 let (summary, why, choices) = match bucket {
805 Bucket::MachineUnknown => (
806 w.summary_machine_unknown(task),
807 w.why_machine().to_owned(),
808 w.choices3(),
809 ),
810 Bucket::ConductorOverride => (
811 w.summary_conductor_override(task),
812 task.resume_override
813 .as_ref()
814 .map(|o| w.why_conductor_override(o))
815 .unwrap_or_default(),
816 w.choices_conductor_override(),
817 ),
818 Bucket::Legacy => (
819 w.summary_legacy(task),
820 w.why_legacy().to_owned(),
821 w.choices3(),
822 ),
823 Bucket::ManualStale => {
824 let days = (now.as_second() - task.updated_at.as_second()) / (24 * 60 * 60);
825 (
826 w.summary_manual_stale(task, days),
827 w.why_manual().to_owned(),
828 w.choices_manual(),
829 )
830 }
831 };
832 let mut q = Question::new(
833 task.id.clone(),
834 NODE.to_owned(),
835 SEAT.to_owned(),
836 summary,
837 w.detail(task, &why),
838 choices,
839 );
840 q.triage_generation = Some(task.resumption.as_ref().map_or(0, |r| r.generation));
841 questions.put_executable_in(&mut q, ownership).ok()?;
842 Some(q)
843}
844
845pub(crate) fn deputy_brief(q: &Question, queue: &Queue) -> String {
850 let task = queue.get(&q.run).ok();
851 let mut s = match &task {
852 Some(t) => format!(
853 "Task {} (`magi task show {}`), \"{}\", is {}. Hold source: {}. Reason: {}.",
854 t.id,
855 t.id,
856 t.title,
857 t.status.as_str(),
858 match t.hold_source {
859 Some(HoldSource::Machine) => "machine (an automatic hold)",
860 Some(HoldSource::Manual) => "manual (an operator held it)",
861 None => "unknown (an old record, treated as the operator's)",
862 },
863 t.hold_reason
864 .as_deref()
865 .or(t.last_error.as_deref())
866 .unwrap_or("(none recorded)")
867 ),
868 None => format!("Task {} no longer exists (its record is gone).", q.run),
869 };
870 if task.as_ref().is_some_and(disk_wait_eligible) {
871 s.push_str("\n\nDisk capacity waits are monitored automatically. No owner answer is needed for an untouched automatic disk triage question. Explicit holds, discussion and other approvals still require owner resolution.");
872 }
873 s.push_str("\n\nWhat each option does, by position:");
874 let n = q.choices.len();
875 for (i, c) in q.choices.iter().enumerate() {
876 let effect = if q.node == DEPS_NODE {
877 match i {
878 0 => "the dependency is released so the loop runs it",
879 1 => {
880 "the dependants are detached and the dependency task is DELETED; this cannot be undone"
881 }
882 2 => "the dependants are detached; the dependency stays as it is",
883 _ => "nothing is applied",
884 }
885 } else {
886 match i {
887 0 => "the task is released and requeued",
888 2 if n > 2 => "the task is DELETED; this cannot be undone",
889 _ => "the task stays held, with the answer noted",
890 }
891 };
892 s.push_str(&format!("\n- `{c}`: {effect}"));
893 }
894 s.push_str(
895 "\n\nThe daemon applies the answer on its next pass; you apply nothing. When \
896 the owner's words pick an option - including releasing a task they held \
897 themselves, or deleting it - settle it.",
898 );
899 s
900}
901
902fn quarantine_orphaned_blocked(queue: &Queue, questions: &Questions) -> Vec<String> {
920 let mut quarantined = Vec::new();
921 for listed in queue.list() {
922 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
923 continue;
924 }
925 let Ok(_claim) = queue.claim(&listed.id) else {
926 continue;
927 };
928 let Ok(mut task) = queue.get(&listed.id) else {
929 continue;
930 };
931 if task.status != TaskStatus::Blocked {
932 continue;
933 }
934 let deleted = queue.apply_deleted_blockers(&mut task, questions);
935 if !deleted.is_empty() && queue.put(&mut task).is_ok() {
936 for id in &deleted {
937 queue.note_dependency_deleted(&task, id);
938 }
939 }
940 if task.status != TaskStatus::Blocked {
941 continue;
942 }
943 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
944 if missing.is_empty() {
945 continue;
946 }
947 let language = crate::lang::of_repo(&repo_for(&task));
948 let mut cause = missing.clone();
949 cause.sort();
950 cause.dedup();
951 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
952 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
953 &task.blocked_by,
954 &missing,
955 &language,
956 )));
957 if queue.put(&mut task).is_ok() {
958 quarantined.push(task.id.clone());
959 }
960 }
961 quarantined
962}
963
964#[derive(Debug, Clone, Copy, PartialEq, Eq)]
967enum DepsAction {
968 Release,
969 Discard,
970 Detach,
971 Nothing,
973}
974
975fn interpret_deps_answer(q: &Question) -> DepsAction {
976 let resolution = q.resolution().unwrap_or_default();
977 match q.choices.iter().position(|c| *c == resolution) {
978 Some(0) => DepsAction::Release,
979 Some(1) => DepsAction::Discard,
980 Some(2) => DepsAction::Detach,
981 _ => DepsAction::Nothing,
982 }
983}
984
985fn deps_texts(w: &Wording, root: &Task, dependants: &[&Task]) -> (String, String, Vec<String>) {
987 let ja = w.lang == "ja";
988 let reason = root
989 .hold_reason
990 .as_deref()
991 .or(root.last_error.as_deref())
992 .unwrap_or(if ja {
993 "(記録なし)"
994 } else {
995 "(none recorded)"
996 });
997 let list: String = dependants
998 .iter()
999 .map(|t| format!("- {} {}\n", t.short(), t.title))
1000 .collect();
1001 if ja {
1002 (
1003 format!(
1004 "{} ({}) が {} 件のタスクを止めています",
1005 root.short(),
1006 root.status.as_str(),
1007 dependants.len()
1008 ),
1009 format!(
1010 "task: {} ({})\ntitle: {}\n状態: {}\n理由: {reason}\n\n\
1011 このタスクは自動では実行されないため、依存している次のタスクは永遠に待ち続けます:\n{list}",
1012 root.id,
1013 root.short(),
1014 root.title,
1015 root.status.as_str()
1016 ),
1017 vec![
1018 "依存先を再開する".to_owned(),
1019 "依存先を捨てる(依存タスクは切り離して実行)".to_owned(),
1020 "依存タスクを切り離す(依存先はそのまま)".to_owned(),
1021 ],
1022 )
1023 } else {
1024 (
1025 format!(
1026 "{} ({}) is freezing {} blocked task(s)",
1027 root.short(),
1028 root.status.as_str(),
1029 dependants.len()
1030 ),
1031 format!(
1032 "task: {} ({})\ntitle: {}\nstatus: {}\nreason: {reason}\n\n\
1033 Nothing in the loop will ever run this task, so these dependants wait \
1034 forever:\n{list}",
1035 root.id,
1036 root.short(),
1037 root.title,
1038 root.status.as_str()
1039 ),
1040 vec![
1041 "release the dependency".to_owned(),
1042 "discard the dependency (dependants are detached and run)".to_owned(),
1043 "detach the dependants (the dependency stays as it is)".to_owned(),
1044 ],
1045 )
1046 }
1047}
1048
1049fn detach_dependants(queue: &Queue, questions: &Questions, root: &str) {
1053 for listed in queue.list() {
1054 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)) {
1055 continue;
1056 }
1057 let Ok(_claim) = queue.claim(&listed.id) else {
1058 continue;
1059 };
1060 let Ok(mut t) = queue.get(&listed.id) else {
1061 continue;
1062 };
1063 if t.status != TaskStatus::Blocked {
1064 continue;
1065 }
1066 for id in t.blocked_by.clone() {
1067 if matches!(crate::queue::dependency(queue, questions, &id), crate::queue::Dependency::Task(full) if full == root)
1068 {
1069 t.unblock(&id);
1070 }
1071 }
1072 let _ = queue.put(&mut t);
1073 }
1074}
1075
1076fn apply_deps_answer(
1080 queue: &Queue,
1081 questions: &Questions,
1082 q: &Question,
1083 now: Timestamp,
1084 ownership: &crate::task_chat::InquiryOwnership,
1085) -> bool {
1086 let Ok(_claim) = queue.claim(&q.run) else {
1087 return false;
1088 };
1089 let Ok(current) = questions.get_for_effects_in(&q.id, ownership) else {
1090 return false;
1091 };
1092 if current.status != QuestionStatus::Answered {
1093 return false;
1094 }
1095 let q = ¤t;
1096 let Ok(mut root) = queue.get(&q.run) else {
1097 return false;
1098 };
1099 if root.triage_applied(&q.id) {
1100 return false;
1101 }
1102 if root.operator_decided_at.is_some_and(|at| at > q.asked_at)
1103 || q.triage_generation
1104 .is_some_and(|g| g != root.resumption.as_ref().map_or(0, |r| r.generation))
1105 {
1106 root.mark_triage_applied(&q.id);
1107 return queue.put(&mut root).is_ok();
1108 }
1109 match interpret_deps_answer(q) {
1110 DepsAction::Release => {
1111 if root.status == TaskStatus::Running {
1112 return false;
1113 }
1114 if crate::repair_budget::reconcile::blocker(queue, &root).is_some() {
1115 let Ok(receipt) = crate::repair_budget::reconcile::blocked_resume(q) else {
1116 return false;
1117 };
1118 root.decision_effects.insert(q.id.clone(), receipt);
1119 root.mark_triage_applied(&q.id);
1120 return queue.put(&mut root).is_ok();
1121 }
1122 root.answers.push(crate::queue::AnsweredQuestion {
1123 question: q.summary.clone(),
1124 answer: q.resolution().unwrap_or_default(),
1125 });
1126 if crate::base_sync_recovery::held_task(queue, &root)
1127 || crate::land_sync_recovery::held_task(queue, &root)
1128 {
1129 root.mark_triage_applied(&q.id);
1130 return queue.put(&mut root).is_ok();
1131 }
1132 let before = root.operator_decided_at;
1133 let contract =
1134 crate::repair_budget::contract(&root, crate::repair_budget::Kind::Review).ok();
1135 root.release_operator("triage-dependencies", Some(&q.id));
1136 if let Some(contract) = contract
1137 && let Ok(evidence) = crate::repair_budget::reconcile::effect_evidence(
1138 q,
1139 before,
1140 &contract,
1141 root.resumption.as_ref().expect("release"),
1142 )
1143 {
1144 root.decision_effects.insert(q.id.clone(), evidence);
1145 }
1146 root.resume_override = Some(OperatorResume {
1147 question_id: q.id.clone(),
1148 at: now,
1149 conductor_rehold: None,
1150 forced: false,
1151 pinned_run: None,
1152 });
1153 }
1154 DepsAction::Discard => {
1155 detach_dependants(queue, questions, &root.id);
1156 return queue.discard_triage(&root.id, questions, &q.id).is_ok();
1157 }
1158 DepsAction::Detach => detach_dependants(queue, questions, &root.id),
1159 DepsAction::Nothing => return false,
1164 }
1165 root.mark_triage_applied(&q.id);
1166 queue.put(&mut root).is_ok()
1167}
1168
1169fn repair_receipt_notice(queue: &Queue, task: &Task) -> bool {
1170 let Some(detail) = crate::repair_budget::reconcile::blocker(queue, task) else {
1171 return false;
1172 };
1173 if let Some(home) = queue.root().parent() {
1174 let _ = crate::task_inquiry::Outbox::at(home).file_for_occurrence(
1175 task,
1176 task.runs.last().cloned(),
1177 "repair-receipt-recovery".into(),
1178 &task
1179 .repair_grants
1180 .last()
1181 .expect("diagnosed receipt")
1182 .request
1183 .request,
1184 "Retained repair receipt needs reconciliation",
1185 &detail,
1186 );
1187 }
1188 true
1189}
1190
1191fn ask_about_stuck_roots(
1200 queue: &Queue,
1201 questions: &Questions,
1202 config_override: Option<&Path>,
1203 report: &mut Report,
1204) {
1205 let all = questions.list_for_effects();
1206 let tasks = queue.list();
1207 let recovery = RecoveryIndex::from_scan(queue, &tasks, all.clone());
1208 let inv = crate::blockers::Inventory::load_with_tasks(queue, questions, tasks);
1209 let mut frozen: std::collections::BTreeMap<String, Vec<String>> = Default::default();
1210 for (id, roots) in inv.stuck() {
1211 for root in roots {
1212 if root != id {
1213 frozen.entry(root).or_default().push(id.clone());
1214 }
1215 }
1216 }
1217 let ownership = crate::task_chat::InquiryOwnership::default();
1221 for mut q in all
1222 .iter()
1223 .filter(|q| q.node == DEPS_NODE && q.status.open())
1224 .cloned()
1225 {
1226 if inv.task(&q.run).is_some_and(|task| consumed(task, &q)) {
1227 continue;
1228 }
1229 if !frozen.contains_key(&q.run) {
1230 q.abandon("nothing waits on this task anymore");
1231 let _ = questions.put_executable_in(&mut q, &ownership);
1232 }
1233 }
1234
1235 for (root_id, dependant_ids) in &frozen {
1236 let Ok(_claim) = queue.claim(root_id) else {
1237 continue;
1238 };
1239 let seeds: Vec<_> = std::iter::once(root_id)
1242 .chain(dependant_ids.iter())
1243 .filter_map(|id| queue.get(id).ok())
1244 .collect();
1245 let current = crate::blockers::Inventory::load_for_tasks(queue, questions, &seeds);
1246 let Some(root) = current.task(root_id) else {
1247 continue;
1248 };
1249 if crate::base_sync_recovery::held_task(queue, root)
1250 || crate::land_sync_recovery::held_task(queue, root)
1251 {
1252 continue;
1253 }
1254 if disk_wait_known(root, questions.root().parent().unwrap_or(Path::new(""))) {
1257 continue;
1258 }
1259 let dependants: Vec<&Task> = dependant_ids
1260 .iter()
1261 .filter_map(|d| current.task(d))
1262 .filter(|t| current.stuck_roots(t).contains(root_id))
1263 .collect();
1264 if dependants.is_empty() {
1265 continue;
1266 }
1267 if repair_receipt_notice(queue, root) {
1268 continue;
1269 }
1270 let latest = recovery.latest(DEPS_NODE, root_id);
1271 match latest.as_ref() {
1272 Some(q) if !consumed(root, q) && (q.status.open() || awaiting_task_chat(q, root)) => {
1273 continue;
1274 }
1275 Some(q) if q.status == QuestionStatus::Answered && !consumed(root, q) => {
1276 continue;
1277 }
1278 Some(q) if q.status == QuestionStatus::Abandoned => {
1279 let changed = root.updated_at > q.asked_at
1280 || dependants.iter().any(|t| t.updated_at > q.asked_at);
1281 if !changed {
1282 continue;
1283 }
1284 }
1285 _ => {}
1286 }
1287 if !recovery.pending(root).is_empty() {
1288 continue;
1289 }
1290 let cfg = Config::discover(&repo_for(root), config_override)
1291 .ok()
1292 .map(|(c, _)| c);
1293 let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
1294 let (summary, detail, choices) = deps_texts(w, root, &dependants);
1295 let mut question = Question::new(
1296 root.id.clone(),
1297 DEPS_NODE.to_owned(),
1298 SEAT.to_owned(),
1299 summary,
1300 detail,
1301 choices,
1302 );
1303 question.triage_generation = Some(root.resumption.as_ref().map_or(0, |r| r.generation));
1304 if questions
1305 .put_executable_in(&mut question, &ownership)
1306 .is_ok()
1307 {
1308 report.asked.push(root.id.clone());
1309 }
1310 }
1311}
1312
1313pub fn apply_answers(queue: &Queue, questions: &Questions) -> Vec<String> {
1316 let mut applied = Vec::new();
1317 let ownership = crate::task_chat::InquiryOwnership::default();
1318 for q in questions.list_for_effects_in(&ownership) {
1319 if q.node == DEPS_NODE
1320 && q.status == QuestionStatus::Answered
1321 && apply_deps_answer(queue, questions, &q, Timestamp::now(), &ownership)
1322 {
1323 applied.push(q.run.clone());
1324 }
1325 }
1326 let tasks = queue.list();
1328 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1329 let recovery =
1330 RecoveryIndex::from_scan(queue, &tasks, questions.list_for_effects_in(&ownership));
1331 for listed in tasks {
1332 let Some(q) = recovery.latest(NODE, &listed.id) else {
1333 continue;
1334 };
1335 if q.status != QuestionStatus::Answered || already_applied(&listed, &q) {
1336 continue;
1337 }
1338 let Ok(_claim) = queue.claim(&listed.id) else {
1339 continue;
1340 };
1341 let Ok(mut task) = queue.get(&listed.id) else {
1342 continue;
1343 };
1344 let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1347 continue;
1348 };
1349 if q.status != QuestionStatus::Answered {
1350 continue;
1351 }
1352 if already_applied(&task, &q)
1353 || !matches!(task.status, TaskStatus::Held | TaskStatus::Queued)
1354 {
1355 continue;
1356 }
1357 let generation = task.resumption.as_ref().map_or(0, |r| r.generation);
1358 let action = interpret_answer(&q);
1359 let mut newer_decision = q.triage_generation.is_some_and(|g| g != generation)
1360 || task.resumption.as_ref().is_some_and(|r| r.at > q.asked_at)
1361 || task.held_at.is_some_and(|at| at > q.asked_at)
1362 || task.operator_decided_at.is_some_and(|at| at > q.asked_at);
1363 if matches!(action, AnswerAction::KeepHeld)
1367 && q.answered_at.is_some_and(|at| {
1368 task.operator_decided_at
1369 .is_none_or(|decision| at > decision)
1370 && task.resumption.as_ref().is_none_or(|r| at > r.at)
1371 })
1372 {
1373 newer_decision = false;
1374 }
1375 let resolution = q.resolution().unwrap_or_default();
1377 task.answers.push(crate::queue::AnsweredQuestion {
1378 question: q.summary.clone(),
1379 answer: if newer_decision {
1380 format!("{resolution} (superseded by a later operator decision)")
1381 } else {
1382 resolution
1383 },
1384 });
1385 if !newer_decision {
1386 match action {
1387 AnswerAction::Resume
1388 if crate::base_sync_recovery::held_task(queue, &task)
1389 || crate::land_sync_recovery::held_task(queue, &task) =>
1390 {
1391 }
1394 AnswerAction::Resume
1395 if crate::repair_budget::reconcile::blocker(queue, &task).is_some() =>
1396 {
1397 let Ok(receipt) = crate::repair_budget::reconcile::blocked_resume(&q) else {
1398 continue;
1399 };
1400 task.decision_effects.insert(q.id.clone(), receipt);
1401 }
1402 AnswerAction::Resume => {
1403 let before = task.operator_decided_at;
1404 let contract =
1405 crate::repair_budget::contract(&task, crate::repair_budget::Kind::Review)
1406 .ok();
1407 task.release_operator("triage", Some(&q.id));
1408 if let Some(contract) = contract
1409 && let Ok(evidence) = crate::repair_budget::reconcile::effect_evidence(
1410 &q,
1411 before,
1412 &contract,
1413 task.resumption.as_ref().expect("release"),
1414 )
1415 {
1416 task.decision_effects.insert(q.id.clone(), evidence);
1417 }
1418 task.resume_override = Some(OperatorResume {
1419 question_id: q.id.clone(),
1420 at: Timestamp::now(),
1421 conductor_rehold: None,
1422 forced: true,
1423 pinned_run: None,
1424 });
1425 }
1426 AnswerAction::KeepHeld => {
1427 let note = keep_held_note(&task, &q, &q.resolution().unwrap_or_default());
1428 task.hold_manual(Some(note));
1429 }
1430 AnswerAction::Discard => {
1431 if queue.discard_triage(&task.id, questions, &q.id).is_ok() {
1432 applied.push(task.id);
1433 }
1434 continue;
1435 }
1436 }
1437 }
1438 task.mark_triage_applied(&q.id);
1439 if queue.put(&mut task).is_ok() {
1440 applied.push(task.id);
1441 }
1442 }
1443 applied
1444}
1445const DISK_SUPERSEDED: &str =
1446 "Automatic disk wait superseded unanswered triage; no owner answer or approval was created";
1447
1448fn untouched_disk_question(q: &Question, task: &Task) -> bool {
1449 q.status.open()
1450 && q.node == NODE
1451 && q.seat == SEAT
1452 && q.run == task.id
1453 && q.routed_task.as_deref().is_none_or(|id| id == task.id)
1454 && q.triage_generation == Some(task.resumption.as_ref().map_or(0, |r| r.generation))
1455 && task.held_at.is_some_and(|at| q.asked_at >= at)
1456 && task.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1457 && q.answer.is_none()
1458 && q.answered_at.is_none()
1459 && q.accepted_answer_at.is_none()
1460 && q.thread.is_empty()
1461 && q.actions.is_empty()
1462 && q.merge_target.is_none()
1463 && [&EN, &JA].iter().any(|w| {
1464 q.summary == w.summary_machine_unknown(task)
1465 && q.choices == w.choices3()
1466 && q.detail == w.detail(task, w.why_machine())
1467 })
1468}
1469
1470fn refresh_disk_notices(home: &Path, task: &Task) {
1472 let notices = crate::notices::Notices::at(home.join("notifications"));
1473 let Some(task_notice) = crate::notices::task_held(task) else {
1474 return;
1475 };
1476 for (key, message) in [
1477 (task_notice.key, task_notice.message),
1478 (
1479 format!("disk:{}", repo_for(task).display()),
1480 format!(
1481 "Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.",
1482 task.id
1483 ),
1484 ),
1485 ] {
1486 let id = crate::notices::id_of(&key);
1487 if notices
1488 .get(&id)
1489 .is_ok_and(|n| n.key == key && n.message != message)
1490 {
1491 let _ = notices.update(&id, |n| {
1492 if n.key == key {
1493 n.message = message;
1494 }
1495 });
1496 }
1497 }
1498}
1499
1500fn resume_disk_task(
1504 queue: &Queue,
1505 questions: &Questions,
1506 task: &mut Task,
1507 ownership: &crate::task_chat::InquiryOwnership,
1508) -> anyhow::Result<bool> {
1509 let expected = task.clone();
1510 let home = questions
1511 .root()
1512 .parent()
1513 .ok_or_else(|| anyhow::anyhow!("missing question home"))?;
1514 let _lease = if let Some(id) = task.disk_wait_run() {
1515 anyhow::ensure!(
1516 task.resume_override
1517 .as_ref()
1518 .and_then(|o| o.pinned_run.as_ref())
1519 .is_none_or(|pin| pin == id),
1520 "selected recovery run differs from disk wait evidence"
1521 );
1522 let state = crate::run::RunState::load_under(id, home)?;
1523 anyhow::ensure!(
1524 state.id == *id && state.status.resumable() && !task.fresh_start,
1525 "retained execution cannot resume"
1526 );
1527 anyhow::ensure!(
1528 state.liveness_under(
1529 home,
1530 crate::daemon::is_working_on(home, id, Timestamp::now())
1531 ) == crate::run::Liveness::Dead,
1532 "retained execution is not proven idle"
1533 );
1534 Some(crate::driver::maintenance(home, id)?)
1535 } else {
1536 None
1537 };
1538 let outbox = crate::task_inquiry::Outbox::at(home);
1539 let all = questions.list_for_effects_in(ownership);
1540 let pending: Vec<_> = all
1541 .iter()
1542 .filter(|q| {
1543 (!q.run.is_empty()
1545 && std::iter::once(task.id.as_str())
1546 .chain(task.execution_runs().iter().map(String::as_str))
1547 .any(|id| id == q.run || id.starts_with(&q.run) || id.ends_with(&q.run)))
1548 && (q.status.open()
1549 || ((q.node == NODE || q.node == DEPS_NODE)
1550 && (awaiting_task_chat(q, task)
1551 || (q.status == QuestionStatus::Answered
1552 && !already_applied(task, q)))))
1553 })
1554 .collect();
1555 anyhow::ensure!(pending.len() <= 1, "multiple decisions remain");
1557 let candidate = pending.first().copied();
1558 if let Some(q) = candidate {
1559 anyhow::ensure!(untouched_disk_question(q, task), "owner decision remains");
1560 }
1561 for inquiry in outbox.pending()? {
1562 if inquiry.task == task.id && inquiry.decision.is_some() {
1563 anyhow::ensure!(
1564 candidate.is_some_and(|q| q.id == inquiry.id),
1565 "unrelated decision remains"
1566 );
1567 }
1568 }
1569 if let Some(q) = candidate {
1570 let _execution = outbox.execution_claim(&q.id)?;
1571 questions.update_in(&q.id, ownership, |current| {
1572 anyhow::ensure!(untouched_disk_question(current, task), "question changed");
1573 let inquiry = match outbox.get(&q.id) {
1574 Ok(inquiry) => inquiry,
1575 Err(error)
1576 if error
1577 .downcast_ref::<std::io::Error>()
1578 .is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) =>
1579 {
1580 anyhow::ensure!(
1581 current.routed_chat.is_none(),
1582 "delivered inquiry is missing; owner reconciliation required"
1583 );
1584 outbox.enqueue(crate::task_chat::live_record(home, task, current))?
1587 }
1588 Err(error) => return Err(error),
1589 };
1590 anyhow::ensure!(
1591 inquiry.task == task.id
1592 && inquiry.repo == task.repo
1593 && inquiry.source == format!("{}:{}:{}", NODE, SEAT, task.id)
1594 && current
1595 .routed_chat
1596 .as_ref()
1597 .is_none_or(|chat| inquiry.delivered_to.as_ref() == Some(chat)),
1598 "inquiry binding changed"
1599 );
1600 outbox.update_decision(&q.id, |d| {
1601 if d.status == crate::task_decision::Status::Resolved {
1602 anyhow::ensure!(
1603 d.request.is_none()
1604 && d.history
1605 .last()
1606 .is_some_and(|e| e.evidence == DISK_SUPERSEDED),
1607 "decision already settled by owner"
1608 );
1609 return Ok(false);
1610 }
1611 anyhow::ensure!(
1612 d.status == crate::task_decision::Status::AwaitingOwner
1613 && d.request.is_none()
1614 && d.source_answer_at.is_none(),
1615 "owner request remains"
1616 );
1617 d.settle(DISK_SUPERSEDED)
1618 })?;
1619 current.abandon(DISK_SUPERSEDED);
1620 Ok(())
1621 })?;
1622 }
1623 if let Some(q) = candidate {
1624 task.mark_triage_applied(&q.id);
1625 }
1626 task.resume_disk_wait();
1627 queue.commit_disk_wait(task, &expected)?;
1628 let notices = crate::notices::Notices::at(home.join("notifications"));
1629 let keys = [
1630 format!("disk-recovered:{}", task.id),
1631 format!("disk:{}", repo_for(task).display()),
1632 format!("task:{}", task.id),
1633 ];
1634 let repo_waiting = queue
1635 .list()
1636 .iter()
1637 .any(|other| other.repo == task.repo && disk_wait_eligible(other));
1638 for notice in notices.list() {
1639 if notice.key == keys[0]
1640 || notice.key == keys[2]
1641 || (!repo_waiting && notice.key == keys[1])
1642 {
1643 let _ = notices.dismiss(¬ice.id);
1644 }
1645 }
1646 Ok(candidate.is_some())
1647}
1648
1649pub fn run_once(
1668 queue: &Queue,
1669 questions: &Questions,
1670 config_override: Option<&Path>,
1671 now: Timestamp,
1672) -> Report {
1673 run_once_inner(queue, questions, config_override, now, false)
1674}
1675
1676pub(crate) fn monitor_disk_waits(
1678 queue: &Queue,
1679 questions: &Questions,
1680 config: Option<&Path>,
1681 now: Timestamp,
1682) -> Report {
1683 run_once_inner(queue, questions, config, now, true)
1684}
1685
1686fn run_once_inner(
1687 queue: &Queue,
1688 questions: &Questions,
1689 config_override: Option<&Path>,
1690 now: Timestamp,
1691 disk_only: bool,
1692) -> Report {
1693 run_once_with_probe(
1694 queue,
1695 questions,
1696 config_override,
1697 now,
1698 disk_only,
1699 machine_cause_resolved,
1700 )
1701}
1702
1703fn run_once_with_probe(
1704 queue: &Queue,
1705 questions: &Questions,
1706 config_override: Option<&Path>,
1707 now: Timestamp,
1708 disk_only: bool,
1709 resolved: impl Fn(&Task, &Config) -> Option<bool>,
1710) -> Report {
1711 let mut report = Report {
1712 answered: if disk_only {
1713 Vec::new()
1714 } else {
1715 apply_answers(queue, questions)
1716 },
1717 quarantined: if disk_only {
1718 Vec::new()
1719 } else {
1720 quarantine_orphaned_blocked(queue, questions)
1721 },
1722 ..Report::default()
1723 };
1724 if !disk_only {
1725 ask_about_stuck_roots(queue, questions, config_override, &mut report);
1726 }
1727 let recovery = RecoveryIndex::load(questions);
1728 let ownership = crate::task_chat::InquiryOwnership::default();
1729 for listed in queue.list() {
1730 if listed.status != TaskStatus::Held {
1731 continue;
1732 }
1733 let Ok(_claim) = queue.claim(&listed.id) else {
1734 continue;
1735 };
1736 let Ok(mut task) = queue.get(&listed.id) else {
1737 continue;
1738 };
1739 if task.status != TaskStatus::Held {
1743 continue;
1744 }
1745 if crate::base_sync_recovery::held_task(queue, &task)
1746 || crate::land_sync_recovery::held_task(queue, &task)
1747 {
1748 continue;
1749 }
1750 if task.has_awaiting_landing_cause() {
1751 continue;
1752 }
1753 if !disk_only {
1754 match crate::head_e2e_stop::triage_status(queue, &task) {
1755 crate::head_e2e_stop::TriageStatus::NotHeadE2e => {}
1756 crate::head_e2e_stop::TriageStatus::HoldStillActive => continue,
1757 crate::head_e2e_stop::TriageStatus::ResolvedChanged => {
1758 task.resume_head_e2e_wait();
1759 if queue.put(&mut task).is_ok() {
1760 report.resumed.push(task.id.clone());
1761 }
1762 continue;
1763 }
1764 }
1765 }
1766 if repair_receipt_notice(queue, &task) {
1767 continue;
1768 }
1769 if !disk_wait_known(&task, questions.root().parent().unwrap_or(Path::new("")))
1776 && deps_pending_in(&recovery, &task)
1777 {
1778 continue;
1779 }
1780
1781 let explicit = match &task.overrides {
1782 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
1783 _ => config_override,
1784 };
1785 let cfg = Config::discover(&repo_for(&task), explicit)
1786 .ok()
1787 .map(|(c, _)| c);
1788 let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
1789
1790 if disk_wait_known(&task, questions.root().parent().unwrap_or(Path::new(""))) {
1791 if task
1792 .disk_checked_at
1793 .is_some_and(|at| now.as_second() - at.as_second() < 60)
1794 {
1795 continue;
1796 }
1797 let expected = task.clone();
1798 task.disk_checked_at = Some(now);
1799 if !task.has_disk_capacity_cause() {
1800 task.mark_disk_capacity();
1802 }
1803 if queue.commit_disk_wait(&mut task, &expected).is_err() {
1804 continue;
1805 }
1806 refresh_disk_notices(questions.root().parent().unwrap_or(Path::new("")), &task);
1807 if cfg.as_ref().and_then(|c| resolved(&task, c)) == Some(true) {
1810 match resume_disk_task(queue, questions, &mut task, &ownership) {
1811 Ok(superseded) => {
1812 if superseded {
1813 report.superseded.push(task.id.clone());
1814 }
1815 report.resumed.push(task.id.clone());
1816 }
1817 Err(error) => {
1818 if !report.needs_owner.contains(&task.id) {
1819 report.needs_owner.push(task.id.clone());
1820 }
1821 crate::notices::raise_in(
1822 questions.root().parent().unwrap_or(Path::new("")),
1823 crate::notices::Notice::warn(
1824 &format!("disk-recovered:{}", task.id),
1825 format!(
1826 "Task {}: disk capacity recovered; automatic recovery is still blocked ({error}). Existing owner decisions and unrelated approvals require explicit resolution. Disk monitoring continues.",
1827 task.id
1828 ),
1829 ).link(crate::notices::Link::Task { id: task.id.clone() }).about([task.id.clone()]),
1830 );
1831 }
1832 }
1833 }
1834 continue;
1835 }
1836 if disk_only {
1837 continue;
1838 }
1839
1840 if let Some(q) = recovery.latest(NODE, &task.id) {
1841 if !consumed(&task, &q) && (q.status.open() || awaiting_task_chat(&q, &task)) {
1842 continue;
1844 }
1845 }
1851
1852 match task.hold_source {
1853 Some(HoldSource::Machine) => {
1854 let overridden = task
1855 .resume_override
1856 .as_ref()
1857 .is_some_and(|o| o.conductor_rehold.is_some() && !o.forced);
1858 if overridden {
1859 if file_question(
1860 questions,
1861 &ownership,
1862 &task,
1863 Bucket::ConductorOverride,
1864 w,
1865 now,
1866 )
1867 .is_some()
1868 {
1869 report.asked.push(task.id.clone());
1870 }
1871 } else if cfg.as_ref().and_then(|c| resolved(&task, c)) == Some(true) {
1872 task.release();
1873 if queue.put(&mut task).is_ok() {
1874 report.resumed.push(task.id.clone());
1875 }
1876 } else if !known_isolated_cache_wait(&task, &crate::run::home())
1877 && file_question(questions, &ownership, &task, Bucket::MachineUnknown, w, now)
1878 .is_some()
1879 {
1880 report.asked.push(task.id.clone());
1881 }
1882 }
1883 None => {
1884 if file_question(questions, &ownership, &task, Bucket::Legacy, w, now).is_some() {
1885 report.asked.push(task.id.clone());
1886 }
1887 }
1888 Some(HoldSource::Manual) => {
1889 if manual_is_stale(&task, now)
1890 && file_question(questions, &ownership, &task, Bucket::ManualStale, w, now)
1891 .is_some()
1892 {
1893 report.asked.push(task.id.clone());
1894 }
1895 }
1896 }
1897 }
1898 report
1899}
1900
1901pub fn open_question_for(questions: &Questions, task_id: &str) -> Option<Question> {
1906 let queue = question_queue(questions);
1907 let task = queue.get(task_id).ok()?;
1908 display_index(questions, &queue, std::slice::from_ref(&task)).displayed_open(&task)
1909}
1910
1911pub fn pending_for(questions: &Questions, task: &Task) -> bool {
1925 !pending_recovery_questions(questions, task).is_empty()
1926}
1927
1928pub(crate) fn pending_recovery_questions(questions: &Questions, task: &Task) -> Vec<Question> {
1931 RecoveryIndex::load(questions).pending(task)
1932}
1933
1934fn awaiting_task_chat(q: &Question, task: &Task) -> bool {
1935 q.status != QuestionStatus::Abandoned
1936 && q.routed_chat.is_some()
1937 && !already_applied(task, q)
1938 && task.resumption.as_ref().map_or(0, |r| r.generation) == q.triage_generation.unwrap_or(0)
1939 && task.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1940}
1941
1942fn deps_pending_in(recovery: &RecoveryIndex, task: &Task) -> bool {
1946 match recovery.latest(DEPS_NODE, &task.id) {
1947 Some(q) if consumed(task, &q) => false,
1948 Some(q) if q.status.open() || awaiting_task_chat(&q, task) => true,
1949 Some(q) if q.status == QuestionStatus::Answered => true,
1950 _ => false,
1951 }
1952}
1953
1954pub fn open_task_ids(questions: &Questions) -> std::collections::BTreeSet<String> {
1959 let queue = question_queue(questions);
1960 let tasks = queue.list();
1961 let index = display_index(questions, &queue, &tasks);
1962 tasks
1963 .iter()
1964 .filter(|task| index.displayed_open(task).is_some())
1965 .map(|task| task.id.clone())
1966 .collect()
1967}
1968
1969fn question_queue(questions: &Questions) -> Queue {
1970 Queue::at(
1971 questions
1972 .root()
1973 .parent()
1974 .unwrap_or(Path::new(""))
1975 .join("queue"),
1976 )
1977}
1978
1979fn display_index(questions: &Questions, queue: &Queue, tasks: &[Task]) -> RecoveryIndex {
1981 RecoveryIndex::from_scan(queue, tasks, questions.list())
1982}
1983
1984#[cfg(test)]
1985mod tests {
1986 use super::*;
1987 use crate::ask::Answer;
1988 use crate::queue::Source;
1989 use jiff::SignedDuration;
1990
1991 fn store() -> (tempfile::TempDir, Queue, Questions) {
1992 let dir = tempfile::tempdir().unwrap();
1993 let q = Queue::at(dir.path().join("queue"));
1994 let s = Questions::at(dir.path().join("questions"));
1995 (dir, q, s)
1996 }
1997
1998 fn task(title: &str, repo: PathBuf) -> Task {
1999 Task::new(title.to_owned(), format!("do {title}"), repo, Source::Human)
2000 }
2001
2002 fn disk_task(repo: PathBuf) -> Task {
2003 let mut t = task("capacity", repo);
2004 t.hold_machine(crate::disk::gate_in(1_477_050_368, 3_221_225_472, "ja"));
2005 t.mark_disk_capacity();
2006 t.attempts = 3;
2007 t
2008 }
2009
2010 #[test]
2011 fn disk_wait_repeated_pressure_measurement_failure_and_recovery_cost_nothing() {
2012 let (dir, queue, questions) = store();
2013 let cfg = gate_disabled_config(dir.path());
2014 let mut t = disk_task(dir.path().to_owned());
2015 queue.put(&mut t).unwrap();
2016 let notices = crate::notices::Notices::at(dir.path().join("notifications"));
2017 let before = serde_json::to_value(notices.list()).unwrap();
2018 let start = Timestamp::now();
2019 let probes = std::cell::Cell::new(0);
2020 for seconds in [0, 1, 10, 60, 61, 120] {
2021 let report = run_once_with_probe(
2022 &queue,
2023 &questions,
2024 Some(&cfg),
2025 start + SignedDuration::from_secs(seconds),
2026 true,
2027 |_, _| {
2028 probes.set(probes.get() + 1);
2029 Some(false) },
2031 );
2032 assert!(report.is_empty());
2033 assert_eq!(queue.get(&t.id).unwrap().attempts, 3);
2034 }
2035 assert_eq!(
2036 probes.get(),
2037 3,
2038 "resource probes are bounded to one per minute"
2039 );
2040 assert!(questions.list().is_empty());
2041 assert_eq!(serde_json::to_value(notices.list()).unwrap(), before);
2042 let recovered = run_once_with_probe(
2043 &queue,
2044 &questions,
2045 Some(&cfg),
2046 start + SignedDuration::from_secs(180),
2047 true,
2048 |_, _| Some(true),
2049 );
2050 assert_eq!(recovered.resumed, [t.id.clone()]);
2051 let saved = queue.get(&t.id).unwrap();
2052 assert_eq!(saved.status, TaskStatus::Queued);
2053 assert_eq!(saved.attempts, 3);
2054 let again = run_once_with_probe(
2055 &queue,
2056 &questions,
2057 Some(&cfg),
2058 start + SignedDuration::from_secs(240),
2059 true,
2060 |_, _| panic!("queued tasks are not relaunched"),
2061 );
2062 assert!(again.is_empty());
2063 }
2064
2065 #[test]
2066 fn disk_wait_supersedes_only_untouched_automatic_questions_in_both_stores() {
2067 for routed in [false, true] {
2068 let (dir, queue, questions) = store();
2069 let cfg = gate_disabled_config(dir.path());
2070 let mut t = disk_task(dir.path().to_owned());
2071 queue.put(&mut t).unwrap();
2072 let q = file_question(
2073 &questions,
2074 &crate::task_chat::InquiryOwnership::default(),
2075 &t,
2076 Bucket::MachineUnknown,
2077 &JA,
2078 Timestamp::now(),
2079 )
2080 .unwrap();
2081 if routed {
2082 crate::task_chat::sweep(
2083 &queue,
2084 &crate::talk::Talks::at(dir.path().join("talks")),
2085 &questions,
2086 dir.path(),
2087 );
2088 assert!(
2089 crate::task_inquiry::Outbox::at(dir.path())
2090 .get(&q.id)
2091 .is_ok()
2092 );
2093 }
2094 let start = Timestamp::now();
2095 for seconds in [0, 60, 120] {
2096 assert!(
2097 run_once_with_probe(
2098 &queue,
2099 &questions,
2100 Some(&cfg),
2101 start + SignedDuration::from_secs(seconds),
2102 true,
2103 |_, _| Some(false)
2104 )
2105 .is_empty()
2106 );
2107 assert!(questions.read_history(&q.id).unwrap().status.open());
2108 assert_eq!(questions.list().len(), 1);
2109 }
2110 let report = monitor_disk_waits(
2111 &queue,
2112 &questions,
2113 Some(&cfg),
2114 start + SignedDuration::from_secs(180),
2115 );
2116 assert_eq!(report.resumed, [t.id.clone()], "routed={routed}");
2117 let source = questions.read_history(&q.id).unwrap();
2118 assert_eq!(source.status, QuestionStatus::Abandoned);
2119 assert!(source.answer.is_none());
2120 assert!(source.answered_at.is_none());
2121 assert!(!pending_for(&questions, &queue.get(&t.id).unwrap()));
2122 if routed {
2123 let d = crate::task_inquiry::Outbox::at(dir.path())
2124 .get(&q.id)
2125 .unwrap()
2126 .decision
2127 .unwrap();
2128 assert_eq!(d.status, crate::task_decision::Status::Resolved);
2129 assert!(
2130 d.request.is_none(),
2131 "system supersession fabricates no owner request"
2132 );
2133 }
2134 }
2135 }
2136
2137 #[test]
2138 fn disk_wait_respects_owner_hold_discussion_and_unrelated_approvals() {
2139 for kind in [
2140 "manual",
2141 "answered",
2142 "discussion",
2143 "unrelated",
2144 "override",
2145 "native-hold",
2146 "missing-native",
2147 ] {
2148 let (dir, queue, questions) = store();
2149 let cfg = gate_disabled_config(dir.path());
2150 let mut t = disk_task(dir.path().to_owned());
2151 queue.put(&mut t).unwrap();
2152 let q = file_question(
2153 &questions,
2154 &crate::task_chat::InquiryOwnership::default(),
2155 &t,
2156 Bucket::MachineUnknown,
2157 &EN,
2158 Timestamp::now(),
2159 )
2160 .unwrap();
2161 match kind {
2162 "manual" => {
2163 t.hold_manual(Some("owner hold".into()));
2164 queue.put(&mut t).unwrap();
2165 }
2166 "answered" => {
2167 questions
2168 .update(&q.id, |q| q.answer(Answer::Choice(q.choices[1].clone())))
2169 .unwrap();
2170 }
2171 "discussion" => {
2172 questions
2173 .update(&q.id, |q| q.say("please wait".to_owned()))
2174 .unwrap();
2175 }
2176 "unrelated" => {
2177 questions
2178 .update(&q.id, |q| {
2179 q.node = "land".into();
2180 Ok(())
2181 })
2182 .unwrap();
2183 }
2184 "override" => {
2185 t.resume_override = Some(OperatorResume {
2186 question_id: "owner".into(),
2187 at: Timestamp::now(),
2188 conductor_rehold: Some("pending conductor decision".into()),
2189 forced: true,
2190 pinned_run: None,
2191 });
2192 queue.put(&mut t).unwrap();
2193 }
2194 "native-hold" | "missing-native" => {
2195 crate::task_chat::sweep(
2196 &queue,
2197 &crate::talk::Talks::at(dir.path().join("talks")),
2198 &questions,
2199 dir.path(),
2200 );
2201 if kind == "native-hold" {
2202 crate::task_inquiry::Outbox::at(dir.path())
2203 .update_decision(&q.id, |d| d.accept("owner requested hold"))
2204 .unwrap();
2205 } else {
2206 questions
2210 .update(&q.id, |q| {
2211 q.routed_chat = Some("delivered-chat".into());
2212 Ok(())
2213 })
2214 .unwrap();
2215 std::fs::remove_file(
2216 dir.path()
2217 .join("notifications/task-inquiries")
2218 .join(format!("{}.json", q.id)),
2219 )
2220 .unwrap();
2221 }
2222 }
2223 _ => unreachable!(),
2224 }
2225 let report = run_once(&queue, &questions, Some(&cfg), Timestamp::now());
2226 assert!(report.resumed.is_empty(), "{kind}");
2227 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held, "{kind}");
2228 assert!(
2229 questions.read_history(&q.id).unwrap().status != QuestionStatus::Abandoned,
2230 "{kind}"
2231 );
2232 }
2233 }
2234
2235 #[test]
2236 fn startup_disk_wait_probes_the_task_override_and_does_not_pin_history() {
2237 use crate::config::BuildCache;
2238 crate::run::pin_test_home();
2241 let (dir, queue, questions) = store();
2242 let shared = dir.path().join("shared");
2243 let isolated = crate::build_target::root(dir.path());
2244 let mut config = Config::default();
2245 config.disk.min_free_bytes = 0;
2246 config.graph.worktree_root = Some(dir.path().to_owned());
2247 config.verify.gate = vec![format!(
2248 "CARGO_TARGET_DIR='{}' cargo check",
2249 shared.display()
2250 )];
2251 let mut task = disk_task(dir.path().to_owned());
2252 task.mark_startup_disk_capacity();
2253 task.overrides = Some(crate::queue::RunOverrides {
2254 build_cache: Some(BuildCache::Isolated),
2255 ..Default::default()
2256 });
2257 let check = |task: &Task, config: &Config, blocked: &Path| {
2258 machine_cause_resolved_with_admission(task, config, dir.path(), |paths, _| {
2259 !paths.iter().any(|path| path == blocked)
2260 })
2261 };
2262 assert_eq!(check(&task, &config, &isolated), Some(false));
2263 assert_eq!(check(&task, &config, &shared), Some(true));
2264 config.verify.build_cache = BuildCache::Isolated;
2265 task.overrides.as_mut().unwrap().build_cache = Some(BuildCache::Shared);
2266 assert_eq!(check(&task, &config, &shared), Some(false));
2267 assert_eq!(check(&task, &config, &isolated), Some(true));
2268 task.urgent = true;
2269 config.verify.build_cache = BuildCache::Shared;
2270 task.overrides.as_mut().unwrap().build_cache = None;
2271 assert_eq!(check(&task, &config, &isolated), Some(false));
2272 assert_eq!(check(&task, &config, &shared), Some(true));
2273 task.overrides.as_mut().unwrap().build_cache = Some(BuildCache::Shared);
2274
2275 task.runs.push("historical-execution".into());
2276 queue.put(&mut task).unwrap();
2277 let cfg = gate_disabled_config(dir.path());
2278 let report = run_once_with_probe(
2279 &queue,
2280 &questions,
2281 Some(&cfg),
2282 Timestamp::now(),
2283 true,
2284 |task, _| check(task, &config, &isolated),
2285 );
2286 assert_eq!(report.resumed, [task.id.clone()]);
2287 let saved = queue.get(&task.id).unwrap();
2288 assert_eq!(saved.attempts, task.attempts);
2289 assert_eq!(saved.runs, task.runs);
2290 assert!(saved.disk_resume_run.is_none());
2291 }
2292
2293 #[test]
2294 fn disk_wait_reuses_retained_execution_and_preserves_attempt_and_approval_evidence() {
2295 let (dir, queue, questions) = store();
2296 let cfg = gate_disabled_config(dir.path());
2297 let mut run = crate::run::RunState::new(
2298 dir.path().to_owned(),
2299 "main".into(),
2300 "base".into(),
2301 "capacity".into(),
2302 Config::default(),
2303 );
2304 run.status = crate::run::RunStatus::Blocked;
2305 run.driver_exited = true;
2306 run.save_under(dir.path()).unwrap();
2307 let mut t = disk_task(dir.path().to_owned());
2308 t.runs.push(run.id.clone());
2309 t.resume_override = Some(OperatorResume {
2310 question_id: "approved-recovery".into(),
2311 at: Timestamp::now(),
2312 conductor_rehold: None,
2313 forced: true,
2314 pinned_run: Some(run.id.clone()),
2315 });
2316 queue.put(&mut t).unwrap();
2317 let before = std::fs::read(dir.path().join("runs").join(&run.id).join("run.json")).unwrap();
2318 let report = run_once_with_probe(
2319 &queue,
2320 &questions,
2321 Some(&cfg),
2322 Timestamp::now(),
2323 true,
2324 |_, _| Some(true),
2325 );
2326 assert_eq!(report.resumed, [t.id.clone()]);
2327 let resumed = queue.get(&t.id).unwrap();
2328 assert_eq!(resumed.runs, t.runs);
2329 assert_eq!(resumed.disk_resume_run.as_deref(), Some(run.id.as_str()));
2330 assert_eq!(resumed.attempts, t.attempts);
2331 assert_eq!(resumed.resumption, t.resumption);
2332 assert_eq!(
2333 serde_json::to_value(&resumed.resume_override).unwrap(),
2334 serde_json::to_value(&t.resume_override).unwrap()
2335 );
2336 assert_eq!(
2337 std::fs::read(dir.path().join("runs").join(&run.id).join("run.json")).unwrap(),
2338 before
2339 );
2340 assert!(
2341 run_once_with_probe(
2342 &queue,
2343 &questions,
2344 Some(&cfg),
2345 Timestamp::now(),
2346 true,
2347 |_, _| panic!("no duplicate launch")
2348 )
2349 .is_empty()
2350 );
2351 }
2352
2353 #[test]
2354 fn disk_wait_interrupted_question_supersession_is_idempotent() {
2355 for abandoned in [false, true] {
2356 let (dir, queue, questions) = store();
2357 let cfg = gate_disabled_config(dir.path());
2358 let mut t = disk_task(dir.path().to_owned());
2359 queue.put(&mut t).unwrap();
2360 let q = file_question(
2361 &questions,
2362 &crate::task_chat::InquiryOwnership::default(),
2363 &t,
2364 Bucket::MachineUnknown,
2365 &EN,
2366 Timestamp::now(),
2367 )
2368 .unwrap();
2369 let outbox = crate::task_inquiry::Outbox::at(dir.path());
2370 outbox
2371 .enqueue(crate::task_chat::live_record(dir.path(), &t, &q))
2372 .unwrap();
2373 outbox
2374 .update_decision(&q.id, |d| d.settle(DISK_SUPERSEDED))
2375 .unwrap();
2376 if abandoned {
2377 questions
2378 .update(&q.id, |q| {
2379 q.abandon(DISK_SUPERSEDED);
2380 Ok(())
2381 })
2382 .unwrap();
2383 }
2384 let report = monitor_disk_waits(&queue, &questions, Some(&cfg), Timestamp::now());
2385 assert_eq!(report.resumed, [t.id.clone()]);
2386 assert_eq!(queue.get(&t.id).unwrap().attempts, 3);
2387 assert!(questions.read_history(&q.id).unwrap().answer.is_none());
2388 assert_eq!(
2389 outbox.get(&q.id).unwrap().decision.unwrap().history.len(),
2390 1
2391 );
2392 }
2393 }
2394
2395 #[test]
2396 fn disk_wait_legacy_migration_requires_machine_provenance_and_exact_localized_format() {
2397 let (dir, queue, _) = store();
2398 for (language, source, suffix, expected) in [
2399 ("en", Some(HoldSource::Machine), "", true),
2400 ("ja", Some(HoldSource::Machine), "", true),
2401 ("ja", Some(HoldSource::Manual), "", false),
2402 ("ja", None, "", false),
2403 ("ja", Some(HoldSource::Machine), " owner hold", false),
2404 ] {
2405 let mut t = task("legacy", dir.path().to_owned());
2406 t.hold_machine(Some(format!(
2407 "{}{suffix}",
2408 crate::disk::gate_in(1477050368, 3221225472, language).unwrap()
2409 )));
2410 t.schema = 21;
2411 t.hold_source = source;
2412 queue.put(&mut t).unwrap();
2413 let loaded = queue.get(&t.id).unwrap();
2414 assert_eq!(loaded.machine_hold_cause.is_some(), expected);
2415 assert_eq!(disk_wait_eligible(&loaded), expected);
2416 }
2417 }
2418
2419 #[test]
2420 fn disk_wait_refreshes_stale_notice_wording_without_redelivery() {
2421 let (dir, queue, questions) = store();
2422 let cfg = gate_disabled_config(dir.path());
2423 let mut t = disk_task(dir.path().to_owned());
2424 queue.put(&mut t).unwrap();
2425 let notices = crate::notices::Notices::at(dir.path().join("notifications"));
2426 let key = format!("disk:{}", t.repo.display());
2427 let n = notices
2428 .raise(crate::notices::Notice::warn(
2429 &key,
2430 "Free some, then release it from the queue.",
2431 ))
2432 .unwrap();
2433 notices.mark_read(&n.id).unwrap();
2434 let before = notices.get(&n.id).unwrap();
2435 let report = run_once_with_probe(
2436 &queue,
2437 &questions,
2438 Some(&cfg),
2439 Timestamp::now(),
2440 true,
2441 |_, _| Some(false),
2442 );
2443 assert!(report.is_empty());
2444 let after = notices.get(&n.id).unwrap();
2445 assert!(after.message.contains("automatically"));
2446 assert_eq!(before.generation, after.generation);
2447 assert_eq!(before.count, after.count);
2448 assert_eq!(before.read_at, after.read_at);
2449 }
2450
2451 #[test]
2452 fn disk_wait_owner_discard_is_applied_without_automatic_resumption() {
2453 let (dir, queue, questions) = store();
2454 let cfg = gate_disabled_config(dir.path());
2455 let mut t = disk_task(dir.path().to_owned());
2456 queue.put(&mut t).unwrap();
2457 let q = file_question(
2458 &questions,
2459 &crate::task_chat::InquiryOwnership::default(),
2460 &t,
2461 Bucket::MachineUnknown,
2462 &EN,
2463 Timestamp::now(),
2464 )
2465 .unwrap();
2466 questions
2467 .update(&q.id, |q| q.answer(Answer::Choice(q.choices[2].clone())))
2468 .unwrap();
2469 let report = run_once(&queue, &questions, Some(&cfg), Timestamp::now());
2470 assert!(report.resumed.is_empty());
2471 assert!(queue.get(&t.id).is_err());
2472 assert!(questions.read_history(&q.id).unwrap().answer.is_some());
2473 }
2474
2475 #[test]
2476 fn disk_wait_commit_cannot_overwrite_a_concurrent_owner_hold() {
2477 let (dir, queue, questions) = store();
2478 let mut stale = disk_task(dir.path().to_owned());
2479 queue.put(&mut stale).unwrap();
2480 let mut current = queue.get(&stale.id).unwrap();
2481 current.hold_manual(Some("wait for owner".into()));
2482 queue.put(&mut current).unwrap();
2483 assert!(
2484 resume_disk_task(
2485 &queue,
2486 &questions,
2487 &mut stale,
2488 &crate::task_chat::InquiryOwnership::default()
2489 )
2490 .is_err()
2491 );
2492 assert_eq!(
2493 queue.get(¤t.id).unwrap().hold_source,
2494 Some(HoldSource::Manual)
2495 );
2496 }
2497
2498 #[test]
2499 fn recovery_index_preserves_supersession_and_ambiguous_file_references() {
2500 let (dir, queue, questions) = store();
2501 let mut t = task("supersession", dir.path().join("repo"));
2502 t.id = "task-alpha-end".into();
2503 queue.put(&mut t).unwrap();
2504 let at: Timestamp = "2026-11-01T00:00:00Z".parse().unwrap();
2505 let mut all = Vec::new();
2506 for (i, run) in ["task-alpha-end", "task-alpha", "end"]
2507 .into_iter()
2508 .enumerate()
2509 {
2510 let mut q = Question::new(
2511 run.into(),
2512 NODE.into(),
2513 SEAT.into(),
2514 "superseded".into(),
2515 String::new(),
2516 EN.choices3(),
2517 );
2518 q.id = format!("superseded-{i}");
2519 q.asked_at = at;
2520 all.push(q);
2521 }
2522 let evidence: Vec<_> = all
2523 .iter()
2524 .map(|q| {
2525 (
2526 q.id.clone(),
2527 crate::repair_budget::reconcile::source(q).unwrap(),
2528 )
2529 })
2530 .collect();
2531 t.repair_reconciliations.push(
2532 serde_json::from_value(serde_json::json!({
2533 "request": {
2534 "task": t.id, "run": "run", "head": "head", "expect_pass": 0,
2535 "receipt": "grant", "question": "original", "answer_at": at,
2536 "request": "reconcile", "reason": "fixture"
2537 },
2538 "grant": {
2539 "request": {
2540 "task": t.id, "run": "run", "kind": "review", "rounds": 1,
2541 "head": "head", "expect_pass": 0, "request": "grant", "reason": "fixture"
2542 },
2543 "at": at, "decision": null, "contract": "fixture"
2544 },
2545 "source": "fixture", "application": "fixture", "decision": at,
2546 "superseded_questions": evidence
2547 }))
2548 .unwrap(),
2549 );
2550 queue.put(&mut t).unwrap();
2551 let index = RecoveryIndex::from_scan(&queue, &[t.clone()], all.clone());
2552 assert!(index.latest.is_empty());
2553 std::fs::write(queue.path_of("task-alphabet-other"), "{").unwrap();
2555 std::fs::write(queue.path_of("broken-end"), "{").unwrap();
2556 let index = RecoveryIndex::from_scan(&queue, &[t.clone()], all.clone());
2557 assert!(index.latest(NODE, "end").is_some());
2558 assert!(index.latest(NODE, "task-alpha").is_some());
2559 assert!(index.latest(NODE, &t.id).is_none());
2560 all[0].detail.push_str("changed evidence");
2561 let index = RecoveryIndex::from_scan(&queue, &[t], all);
2562 assert!(index.latest(NODE, "task-alpha-end").is_some());
2563 assert_eq!(questions.list().len(), 0);
2564 }
2565
2566 #[test]
2567 fn ownership_index_requires_positive_foreground_provenance() {
2568 let (dir, queue, _) = store();
2569 let mut run = crate::run::RunState::new(
2570 dir.path().join("repo"),
2571 "main".into(),
2572 "origin".into(),
2573 "fixture".into(),
2574 Config::default(),
2575 );
2576 run.origin = Some(crate::run::Origin::operator());
2577 run.save_under(dir.path()).unwrap();
2578 let foreground = run.id.clone();
2579 run.id = "owned-run".into();
2580 run.origin = Some(crate::run::Origin::queue("missing-task"));
2581 run.save_under(dir.path()).unwrap();
2582 let mut task = task("owner", dir.path().join("repo"));
2583 task.runs = vec!["linked-run".into()];
2584 queue.put(&mut task).unwrap();
2585 let ownership = crate::task_chat::InquiryOwnership::default();
2586 for (run, cwd, node, seat, expected) in [
2587 (foreground.as_str(), true, "node", "seat", true),
2588 (foreground.as_str(), false, "node", "seat", false),
2589 ("owned-run", true, "ask", "operator", false),
2590 ("linked-run", true, "ask", "operator", false),
2591 ("missing-run", true, "node", "seat", false),
2592 ("missing-run", false, "ask", "operator", true),
2593 ] {
2594 let mut q = Question::new(
2595 run.into(),
2596 node.into(),
2597 seat.into(),
2598 "provenance".into(),
2599 String::new(),
2600 Vec::new(),
2601 );
2602 q.cwd = cwd.then(|| dir.path().join("repo").display().to_string());
2603 assert_eq!(standalone_by_scanning(dir.path(), &q), expected);
2604 assert_eq!(
2605 crate::task_chat::standalone_inquiry_in(dir.path(), &q, &ownership),
2606 expected
2607 );
2608 }
2609 }
2610
2611 fn standalone_by_scanning(home: &Path, q: &Question) -> bool {
2613 if q.routed_task.is_some()
2614 || (q.node == crate::bump::NOTICE_NODE && q.seat == "release-watch")
2615 {
2616 return false;
2617 }
2618 if q.legacy_foreground || q.run.is_empty() {
2619 return true;
2620 }
2621 if Queue::at(home.join("queue"))
2622 .list()
2623 .iter()
2624 .any(|task| task.id == q.run || task.runs.contains(&q.run))
2625 {
2626 return false;
2627 }
2628 let run = crate::run::RunState::load_under(&q.run, home).ok();
2629 let origin = run.as_ref().and_then(|run| run.origin.as_ref());
2630 if origin.is_some_and(|origin| origin.task.is_some()) {
2631 return false;
2632 }
2633 (q.node == "ask" && q.seat == "operator")
2634 || (q.cwd.is_some() && origin.is_some_and(|origin| origin.task.is_none()))
2635 }
2636
2637 fn scan_counts() -> (usize, usize, usize) {
2638 (
2639 crate::queue::LIST_READS.with(|c| c.replace(0)),
2640 crate::queue::TASK_READS.with(|c| c.replace(0)),
2641 crate::ask::QUESTION_SCANS.with(|c| c.replace(0)),
2642 )
2643 }
2644
2645 #[test]
2646 fn creating_and_updating_questions_share_one_queue_read() {
2647 let (dir, queue, questions) = store();
2648 let size = 200;
2649 let mut ids = Vec::new();
2650 for i in 0..size {
2651 let mut t = task("scan fixture", dir.path().join("repo"));
2652 t.id = format!("task-{i:04}");
2653 t.runs = vec![format!("run-{i:04}")];
2654 t.hold_manual(Some("held for scan fixture".into()));
2655 queue.put(&mut t).unwrap();
2656 ids.push(t.id);
2657 }
2658 let ownership = crate::task_chat::InquiryOwnership::default();
2659 scan_counts();
2660 let mut created = Vec::new();
2661 for id in &ids {
2662 let mut q = Question::new(
2663 id.clone(),
2664 NODE.into(),
2665 SEAT.into(),
2666 "scan fixture".into(),
2667 String::new(),
2668 EN.choices3(),
2669 );
2670 questions.put_executable_in(&mut q, &ownership).unwrap();
2671 assert_eq!(q.routed_task.as_deref(), Some(id.as_str()));
2672 created.push(q.id);
2673 }
2674 for id in &created {
2675 questions
2676 .update_in(id, &ownership, |q| {
2677 q.answer_delivered = true;
2678 Ok(())
2679 })
2680 .unwrap();
2681 }
2682 let (lists, _, _) = scan_counts();
2683 assert_eq!(lists, 1, "one queue read for {size} creations and updates");
2684 }
2685
2686 #[test]
2687 fn recovery_scans_are_linear_and_match_legacy_decisions() {
2688 let mut previous = None;
2689 for size in [150, 300] {
2690 let (dir, queue, questions) = store();
2691 let at: Timestamp = "2026-11-01T00:00:00Z".parse().unwrap();
2692 let mut sources = Vec::new();
2693 let mut expected_applied = std::collections::BTreeSet::new();
2694 for i in 0..size {
2695 let mut t = task("scan fixture", dir.path().join("repo"));
2696 t.id = format!("task-{i:04}");
2697 t.runs = vec![format!("run-{i:04}")];
2698 t.hold_manual(Some("held for scan fixture".into()));
2699 queue.put(&mut t).unwrap();
2700 let mut q = Question::new(
2701 t.id.clone(),
2702 NODE.into(),
2703 SEAT.into(),
2704 "scan fixture".into(),
2705 String::new(),
2706 EN.choices3(),
2707 );
2708 q.id = format!("question-{i:04}");
2709 q.asked_at = at;
2710 match i % 10 {
2711 0 => {
2712 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
2713 q.accepted_answer_at = q.answered_at;
2714 expected_applied.insert(t.id.clone());
2715 }
2716 1 => q.node = DEPS_NODE.into(),
2717 2 => {
2718 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
2719 }
2720 3 => {
2721 q.run = format!("missing-{i}");
2722 q.legacy_foreground = true;
2723 }
2724 4 => {
2725 q.run.clear();
2726 q.node = crate::bump::NOTICE_NODE.into();
2727 q.seat = "release-watch".into();
2728 }
2729 5 => {
2730 q.run = format!("missing-{i}");
2731 q.node = "ask".into();
2732 q.seat = "operator".into();
2733 }
2734 6 => q.run = t.runs[0].clone(),
2735 7 => q.run = format!("missing-{i}"),
2736 8 => q.abandon("fixture"),
2737 _ => {}
2738 }
2739 questions.put(&mut q).unwrap();
2740 sources.push(q.id.clone());
2741 if i % 10 == 9 {
2742 q.id = format!("question-{i:04}-tie");
2743 questions.put(&mut q).unwrap();
2744 sources.push(q.id.clone());
2745 }
2746 }
2747 let migration = dir.path().join("notifications/task-chat-migration-v1");
2748 std::fs::create_dir_all(&migration).unwrap();
2749 std::fs::write(
2750 migration.join("state.json"),
2751 serde_json::to_vec(&serde_json::json!({
2752 "schema": 1, "classification_revision": 1, "pending": [], "sources": sources
2753 }))
2754 .unwrap(),
2755 )
2756 .unwrap();
2757
2758 scan_counts();
2759 let all = questions.list_for_effects();
2760 let (lists, reads, scans) = scan_counts();
2761 assert_eq!((lists, reads, scans), (1, size, 1));
2762 let tasks = queue.list();
2763 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
2764 for q in &all {
2765 assert_eq!(
2766 crate::task_chat::standalone_inquiry_in(dir.path(), q, &ownership),
2767 standalone_by_scanning(dir.path(), q),
2768 "{}",
2769 q.id,
2770 );
2771 if q.id.ends_with("0002") {
2772 assert!(q.answer.is_none(), "saved consent remains fenced");
2773 }
2774 }
2775 let recovery = RecoveryIndex::from_scan(&queue, &tasks, all.clone());
2776 for task in &tasks {
2777 for node in [NODE, DEPS_NODE] {
2778 let expected = all
2779 .iter()
2780 .filter(|q| {
2781 q.node == node
2782 && q.run == task.id
2783 && !queue.get(&q.run).ok().is_some_and(|t| {
2784 crate::repair_budget::reconcile::superseded_question(&t, q)
2785 })
2786 })
2787 .max_by(|a, b| a.asked_at.cmp(&b.asked_at).then_with(|| a.id.cmp(&b.id)));
2788 assert_eq!(
2789 recovery.latest(node, &task.id).map(|q| q.id),
2790 expected.map(|q| q.id.clone())
2791 );
2792 }
2793 }
2794
2795 scan_counts();
2796 crate::daemon::apply_task_choice_actions(&queue, &questions, dir.path());
2797 assert_eq!(
2798 scan_counts(),
2799 (1, size, 1),
2800 "choice-action rechecks share ownership"
2801 );
2802
2803 scan_counts();
2804 let applied: std::collections::BTreeSet<_> =
2805 apply_answers(&queue, &questions).into_iter().collect();
2806 let counts = scan_counts();
2807 assert_eq!(applied, expected_applied);
2808 assert!(counts.0 <= 3, "queue scans: {counts:?}");
2809 assert!(counts.1 <= 4 * size, "task reads: {counts:?}");
2810 assert_eq!(counts.2, 2, "question scans: {counts:?}");
2811 if let Some((_, reads, scans)) = previous {
2812 assert!(counts.1 <= 2 * reads);
2813 assert_eq!(counts.2, scans);
2814 }
2815 previous = Some(counts);
2816
2817 let config = gate_disabled_config(dir.path());
2818 scan_counts();
2819 run_once(&queue, &questions, Some(&config), Timestamp::now());
2820 let lap = scan_counts();
2821 assert!(lap.0 <= 12, "triage queue scans: {lap:?}");
2822 assert!(lap.1 <= 14 * size, "triage task reads: {lap:?}");
2823 assert!(lap.2 <= 6, "triage question scans: {lap:?}");
2824 }
2825 }
2826
2827 #[test]
2828 fn run_once_filing_many_new_questions_reads_the_queue_a_constant_number_of_times() {
2829 let (dir, queue, questions) = store();
2830 let size = 200;
2831 for i in 0..size {
2832 let mut t = task("scan fixture", dir.path().join("repo"));
2833 t.id = format!("task-{i:04}");
2834 t.hold_machine(Some("gate red".to_owned()));
2835 queue.put(&mut t).unwrap();
2836 }
2837 scan_counts();
2838 let report = run_once(&queue, &questions, None, Timestamp::now());
2839 let (lists, _, _) = scan_counts();
2840 assert_eq!(report.asked.len(), size, "every held task is asked about");
2841 assert!(
2842 lists <= 12,
2843 "queue scans while filing {size} questions: {lists}"
2844 );
2845 }
2846
2847 #[test]
2848 fn base_recovery_stops_suppress_generic_and_dependency_resume_offers() {
2849 let (dir, queue, questions) = store();
2850 let mut root = task("base stop", dir.path().to_path_buf());
2851 let mut run = crate::run::RunState::new(
2852 dir.path().to_path_buf(),
2853 "main".into(),
2854 "base".into(),
2855 "retained implementation".into(),
2856 Config::default(),
2857 );
2858 run.status = crate::run::RunStatus::Voting;
2859 run.base_sync = Some(crate::run::BaseSync {
2860 tip: "tip".into(),
2861 behind: 3,
2862 attempts: 4,
2863 conflict: Some("persisted exhaustion".into()),
2864 already_in: None,
2865 });
2866 run.save_under(dir.path()).unwrap();
2867 root.link_run(&run.id);
2868 root.hold_machine(Some("base stop".into()));
2869 queue.put(&mut root).unwrap();
2870 let mut dependent = task("dependent", dir.path().to_path_buf());
2871 dependent.blocked_by = vec![root.id.clone()];
2872 dependent.status = TaskStatus::Blocked;
2873 queue.put(&mut dependent).unwrap();
2874 for _ in 0..2 {
2875 let report = run_once(&queue, &questions, None, Timestamp::now());
2876 assert!(report.asked.is_empty());
2877 assert!(report.resumed.is_empty());
2878 }
2879 let q = file_question(
2882 &questions,
2883 &crate::task_chat::InquiryOwnership::default(),
2884 &root,
2885 Bucket::MachineUnknown,
2886 &EN,
2887 Timestamp::now(),
2888 )
2889 .unwrap();
2890 let mut q = q;
2891 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
2892 questions.put_executable(&mut q).unwrap();
2893 apply_answers(&queue, &questions);
2894 let saved = queue.get(&root.id).unwrap();
2895 assert_eq!(saved.status, TaskStatus::Held);
2896 assert!(saved.triage_applied(&q.id));
2897 assert_eq!(saved.runs, vec![run.id]);
2898 }
2899
2900 #[test]
2901 fn resource_holds_only_auto_release_a_proven_cache_wait_timeout() {
2902 use crate::run::{ResourceBlock, ResourceBlockCause, RunState};
2903 let dir = tempfile::tempdir().unwrap();
2904 let cfg = Config::default(); assert!(cfg.cache_dir().is_none());
2906 let mut state = RunState::new(
2907 dir.path().into(),
2908 "main".into(),
2909 "base".into(),
2910 "verify".into(),
2911 cfg.clone(),
2912 );
2913 let mut task = task("verify", dir.path().into());
2914 task.runs = vec![state.id.clone()];
2915 task.hold_machine(Some("[resource] cache operation stopped".into()));
2916 for cause in [
2917 ResourceBlockCause::Other,
2918 ResourceBlockCause::Unrecorded,
2919 ResourceBlockCause::Cancelled { park: None },
2920 ] {
2921 state.resource_block = Some(ResourceBlock {
2922 node: "gate".into(),
2923 kind: "shared build cache".into(),
2924 detail: "persistent metadata or manifest error".into(),
2925 cause,
2926 at: Timestamp::now(),
2927 });
2928 state.save_under(dir.path()).unwrap();
2929 for _ in 0..3 {
2931 assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
2932 }
2933 }
2934 let block = state.resource_block.as_mut().unwrap();
2935 block.cause = ResourceBlockCause::Timeout {
2936 waited_secs: 10,
2937 limit_secs: 10,
2938 };
2939 state.save_under(dir.path()).unwrap();
2940 assert_eq!(
2941 machine_cause_resolved_under(&task, &cfg, dir.path()),
2942 Some(true)
2943 );
2944 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
2945 state.save_under(dir.path()).unwrap();
2946 assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
2947 task.runs = vec!["unreadable-run".into()];
2948 assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
2949 }
2950
2951 #[cfg(unix)]
2952 #[test]
2953 fn disk_admission_holds_recheck_live_reservations_and_the_floor() {
2954 use crate::retention::OutputLease;
2955 use crate::run::{ResourceBlock, ResourceBlockCause, RunState};
2956 let temp = tempfile::tempdir().unwrap();
2957 let home = temp.path().canonicalize().unwrap();
2958 let mut cfg = Config::default();
2959 cfg.graph.worktree_root = Some(home.join("worktrees"));
2960 cfg.disk.min_free_bytes = 100;
2961 let cache = home.join("cache");
2962 cfg.verify.gate = vec![format!(
2963 "CARGO_TARGET_DIR='{}' cargo build",
2964 cache.display()
2965 )];
2966 let mut state = RunState::new(
2967 home.clone(),
2968 "main".into(),
2969 "base".into(),
2970 "verify".into(),
2971 cfg.clone(),
2972 );
2973 let saved_cache = home.join("saved-cache");
2974 state.config.verify.gate = vec![format!(
2975 "CARGO_TARGET_DIR='{}' cargo build",
2976 saved_cache.display()
2977 )];
2978 state.resource_block = Some(ResourceBlock {
2979 node: "gate".into(),
2980 kind: "disk admission".into(),
2981 detail: "writer headroom unavailable".into(),
2982 cause: ResourceBlockCause::Other,
2983 at: Timestamp::now(),
2984 });
2985 state.save_under(&home).unwrap();
2986 let mut task = task("verify", home.clone());
2987 task.runs = vec![state.id.clone()];
2988 task.hold_machine(Some(format!(
2989 "{}{}; no attempt was spent; resume to retry the affected operation",
2990 crate::cache::RESOURCE_HOLD,
2991 state.resource_block.as_ref().unwrap().description()
2992 )));
2993 task.schema = 21; let gib = 1024 * 1024 * 1024;
2995 let free = std::cell::Cell::new(100 + gib - 1);
2996 let check = || {
2997 machine_cause_resolved_with_admission(&task, &cfg, &home, |paths, floor| {
2998 assert!(
2999 paths.contains(&cache),
3000 "the cache volume must also be checked"
3001 );
3002 assert!(
3003 paths.contains(&saved_cache),
3004 "saved and current cache locations both matter"
3005 );
3006 assert!(paths.contains(&state.worktree_root()));
3007 OutputLease::admit_with(&home, paths, floor, |_| Ok(free.get())).is_ok()
3008 })
3009 };
3010 assert_eq!(check(), Some(false), "the unchanged floor still applies");
3011 assert_eq!(
3012 machine_cause_resolved_with_admission(&task, &cfg, &home, |paths, floor| {
3013 OutputLease::admit_with(&home, paths, floor, |_| {
3014 Err(anyhow::anyhow!("measurement unavailable"))
3015 })
3016 .is_ok()
3017 }),
3018 Some(false),
3019 "failed output-volume measurements must remain closed"
3020 );
3021 free.set(100 + gib);
3022 let writer = OutputLease::admit_with(
3023 &home,
3024 std::slice::from_ref(&home),
3025 cfg.disk.min_free_bytes,
3026 |_| Ok(free.get()),
3027 )
3028 .unwrap();
3029 assert_eq!(
3030 check(),
3031 Some(false),
3032 "df alone cannot resolve a live reservation"
3033 );
3034 drop(writer);
3035 assert_eq!(
3036 check(),
3037 Some(true),
3038 "releasing headroom resolves the machine hold"
3039 );
3040 assert_eq!(
3041 check(),
3042 Some(true),
3043 "the probe must release its temporary reservation"
3044 );
3045
3046 let namespace = home.join("disk-admission");
3048 let saved = home.join("saved-admission");
3049 std::fs::rename(&namespace, &saved).unwrap();
3050 std::os::unix::fs::symlink(&saved, &namespace).unwrap();
3051 assert_eq!(check(), Some(false));
3052 std::fs::remove_file(&namespace).unwrap();
3053 std::fs::rename(saved, namespace).unwrap();
3054 assert_eq!(check(), Some(true));
3055
3056 state.resource_block.as_mut().unwrap().cause = ResourceBlockCause::Cancelled { park: None };
3057 state.save_under(&home).unwrap();
3058 assert_eq!(
3059 machine_cause_resolved_with_admission(&task, &cfg, &home, |_, _| panic!(
3060 "a cancelled operation must remain held"
3061 )),
3062 None
3063 );
3064 state.resource_block.as_mut().unwrap().kind = "incremental cache admission".into();
3065 state.resource_block.as_mut().unwrap().cause = ResourceBlockCause::Other;
3066 state.save_under(&home).unwrap();
3067 assert_eq!(
3068 machine_cause_resolved_with_admission(&task, &cfg, &home, |_, _| panic!(
3069 "unproven incremental caches must remain held"
3070 )),
3071 None
3072 );
3073 task.runs.push("unreadable-run".into());
3074 assert_eq!(
3075 machine_cause_resolved_with_admission(&task, &cfg, &home, |_, _| panic!(
3076 "missing evidence must not release a hold"
3077 )),
3078 None
3079 );
3080 }
3081
3082 fn gate_disabled_config(dir: &std::path::Path) -> PathBuf {
3086 let config = dir.join("magi.toml");
3087 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
3088 config
3089 }
3090
3091 #[test]
3092 fn resumption_later_keep_held_answer_wins_but_an_older_answer_cannot_undo_release() {
3093 for source in ["cli", "web"] {
3094 for answer_after_release in [true, false] {
3095 let (dir, queue, questions) = store();
3096 let mut t = task("recovery", dir.path().join("repo"));
3097 t.hold_machine(Some("inspect remote first".into()));
3098 queue.put(&mut t).unwrap();
3099 let mut q = file_question(
3100 &questions,
3101 &crate::task_chat::InquiryOwnership::default(),
3102 &t,
3103 Bucket::MachineUnknown,
3104 &JA,
3105 Timestamp::now(),
3106 )
3107 .unwrap();
3108 if !answer_after_release {
3109 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
3110 questions.put(&mut q).unwrap();
3111 }
3112 t.release_operator(source, None);
3113 queue.put(&mut t).unwrap();
3114 if answer_after_release {
3115 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
3116 questions.put(&mut q).unwrap();
3117 }
3118 apply_answers(&queue, &questions);
3119 let after = queue.get(&t.id).unwrap();
3120 assert!(after.triage_applied(&q.id));
3121 assert_eq!(after.operator_held(), answer_after_release);
3122 assert_eq!(
3123 after.status,
3124 if answer_after_release {
3125 TaskStatus::Held
3126 } else {
3127 TaskStatus::Queued
3128 }
3129 );
3130 assert!(apply_answers(&queue, &questions).is_empty());
3131 }
3132 }
3133 }
3134
3135 #[test]
3136 fn explicit_resumption_applies_legacy_queued_triage_once_and_preserves_later_holds() {
3137 let (dir, queue, questions) = store();
3138 let mut t = task("recover", dir.path().join("repo"));
3139 t.hold_machine(Some("inspect first".into()));
3140 queue.put(&mut t).unwrap();
3141 let mut q = file_question(
3142 &questions,
3143 &crate::task_chat::InquiryOwnership::default(),
3144 &t,
3145 Bucket::MachineUnknown,
3146 &JA,
3147 Timestamp::now(),
3148 )
3149 .unwrap();
3150 assert!(q.actions.is_empty());
3151 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
3152 questions.put(&mut q).unwrap();
3153 t.release();
3155 t.instruction = "Reuse approved PR head".into();
3156 queue.put(&mut t).unwrap();
3157 assert_eq!(apply_answers(&queue, &questions), [t.id.clone()]);
3158 let mut after = queue.get(&t.id).unwrap();
3159 assert_eq!(
3160 after.resumption.as_ref().unwrap().question_id.as_deref(),
3161 Some(q.id.as_str())
3162 );
3163 assert_eq!(
3164 after.resumption.as_ref().unwrap().instruction,
3165 t.instruction
3166 );
3167 assert_eq!(after.answers[0].answer, JA.resume);
3168 assert!(after.triage_applied(&q.id));
3169 assert!(apply_answers(&Queue::at(dir.path().join("queue")), &questions).is_empty());
3170 after.hold_machine(Some("new blocker".into()));
3171 queue.put(&mut after).unwrap();
3172 let mut late = file_question(
3173 &questions,
3174 &crate::task_chat::InquiryOwnership::default(),
3175 &after,
3176 Bucket::MachineUnknown,
3177 &EN,
3178 Timestamp::now(),
3179 )
3180 .unwrap();
3181 after.hold_manual(Some("keep held now".into()));
3182 queue.put(&mut after).unwrap();
3183 late.answer(Answer::Choice(late.choices[0].clone()))
3184 .unwrap();
3185 questions.put(&mut late).unwrap();
3186 apply_answers(&queue, &questions);
3187 let held = queue.get(&t.id).unwrap();
3188 assert!(held.operator_held());
3189 assert_eq!(held.hold_reason.as_deref(), Some("keep held now"));
3190 assert_eq!(held.resumption.as_ref().unwrap().generation, 1);
3191 }
3192
3193 #[test]
3194 fn a_resolved_machine_hold_is_requeued_automatically() {
3195 let (dir, q, questions) = store();
3196 let config = gate_disabled_config(dir.path());
3197 let mut t = task("disk pressure", dir.path().join("repo"));
3198 t.hold_machine(Some(
3199 "not enough free space to start a run: 10 bytes free, 100 required by \
3200 `[disk] min_free_bytes`"
3201 .to_owned(),
3202 ));
3203 t.schema = 21; q.put(&mut t).unwrap();
3205
3206 let report = run_once(&q, &questions, Some(&config), Timestamp::now());
3207 assert_eq!(report.resumed, [t.id.clone()]);
3208 assert!(report.asked.is_empty());
3209
3210 let back = q.get(&t.id).unwrap();
3211 assert_eq!(back.status, TaskStatus::Queued);
3212 assert!(back.hold_source.is_none());
3213 assert!(questions.list().is_empty(), "nothing needed asking");
3214 }
3215
3216 #[test]
3217 fn a_machine_hold_with_no_recognised_cause_gets_one_question_not_two() {
3218 let (dir, q, questions) = store();
3219 let mut t = task("gate went red", dir.path().join("repo"));
3220 t.hold_machine(Some("gate red".to_owned()));
3221 q.put(&mut t).unwrap();
3222
3223 let first = run_once(&q, &questions, None, Timestamp::now());
3224 assert_eq!(first.asked, [t.id.clone()]);
3225 assert!(first.resumed.is_empty());
3226
3227 let open: Vec<_> = questions
3228 .list()
3229 .into_iter()
3230 .filter(|q| q.status.open())
3231 .collect();
3232 assert_eq!(open.len(), 1);
3233 assert_eq!(open[0].run, t.id);
3234 assert_eq!(open[0].node, NODE);
3235 assert_eq!(open[0].choices.len(), 3);
3236
3237 let second = run_once(&q, &questions, None, Timestamp::now());
3239 assert!(second.asked.is_empty());
3240 assert_eq!(
3241 questions
3242 .list()
3243 .into_iter()
3244 .filter(|q| q.status.open())
3245 .count(),
3246 1
3247 );
3248 }
3249
3250 #[test]
3251 fn a_legacy_hold_with_no_recorded_source_gets_exactly_one_question() {
3252 let (dir, q, questions) = store();
3253 let mut t = task("schema 1 record", dir.path().join("repo"));
3254 t.status = TaskStatus::Held;
3255 assert!(t.hold_source.is_none(), "the case this test is about");
3256 q.put(&mut t).unwrap();
3257
3258 let first = run_once(&q, &questions, None, Timestamp::now());
3259 assert_eq!(first.asked, [t.id.clone()]);
3260
3261 let second = run_once(&q, &questions, None, Timestamp::now());
3262 assert!(
3263 second.asked.is_empty(),
3264 "the same legacy hold must not be asked about twice"
3265 );
3266 assert_eq!(
3267 questions
3268 .list()
3269 .into_iter()
3270 .filter(|q| q.status.open())
3271 .count(),
3272 1
3273 );
3274 }
3275
3276 #[test]
3277 fn dependency_resolution_detaches_legacy_short_refs_without_dropping_other_waits() {
3278 let (dir, queue, questions) = store();
3279 let mut root = task("root", dir.path().join("repo"));
3280 root.id = "20261013-193611-ca5b".into();
3281 root.hold_machine(Some("needs owner decision".into()));
3282 queue.put(&mut root).unwrap();
3283 let mut other = task("other", dir.path().join("repo"));
3284 other.id = "20261013-192213-feb2".into();
3285 queue.put(&mut other).unwrap();
3286 let mut waiting = task("waiting", dir.path().join("repo"));
3287 waiting.block(vec!["ca5b".into(), other.id.clone()], None);
3288 queue.put(&mut waiting).unwrap();
3289 detach_dependants(&queue, &questions, &root.id);
3290 let after = queue.get(&waiting.id).unwrap();
3291 assert_eq!(after.status, TaskStatus::Blocked);
3292 assert_eq!(after.blocked_by, [other.id]);
3293 }
3294
3295 #[test]
3296 fn a_manual_hold_is_never_auto_resumed() {
3297 let (dir, q, questions) = store();
3298 let mut t = task("operator stopped this", dir.path().join("repo"));
3299 t.hold_manual(Some("waiting on a decision".to_owned()));
3300 q.put(&mut t).unwrap();
3301
3302 let report = run_once(&q, &questions, None, Timestamp::now());
3303 assert!(report.resumed.is_empty());
3304 assert!(report.asked.is_empty());
3306
3307 let back = q.get(&t.id).unwrap();
3308 assert_eq!(back.status, TaskStatus::Held);
3309 assert_eq!(back.hold_source, Some(HoldSource::Manual));
3310 assert!(questions.list().is_empty());
3311 }
3312
3313 #[test]
3314 fn a_blocked_task_on_a_deleted_dependency_is_held_and_asked_about_in_one_pass() {
3315 let (dir, q, questions) = store();
3320 let mut still_going = task("still valid", dir.path().join("repo"));
3321 q.put(&mut still_going).unwrap();
3322
3323 let mut t = task("orphaned", dir.path().join("repo"));
3324 t.block(
3325 vec!["20260101-000000-gone".to_owned(), still_going.id.clone()],
3326 Some("waits on both".to_owned()),
3327 );
3328 q.put(&mut t).unwrap();
3329
3330 let report = run_once(&q, &questions, None, Timestamp::now());
3331 assert_eq!(report.quarantined, [t.id.clone()]);
3332 assert_eq!(
3333 report.asked,
3334 [t.id.clone()],
3335 "the fresh machine hold must earn a question in the same pass"
3336 );
3337
3338 let after = q.get(&t.id).unwrap();
3339 assert_eq!(after.status, TaskStatus::Held);
3340 assert_eq!(after.hold_source, Some(HoldSource::Machine));
3341 assert!(after.blocked_by.is_empty());
3342
3343 assert!(!is_disk_hold(&after));
3346
3347 let open: Vec<_> = questions
3348 .list()
3349 .into_iter()
3350 .filter(|q| q.status.open())
3351 .collect();
3352 assert_eq!(open.len(), 1);
3353 assert_eq!(open[0].run, t.id);
3354
3355 let second = run_once(&q, &questions, None, Timestamp::now());
3357 assert!(second.quarantined.is_empty());
3358 assert!(second.asked.is_empty());
3359 }
3360
3361 fn stuck_chain(q: &Queue, dir: &std::path::Path) -> (Task, Task, Task) {
3364 let mut root = task("root", dir.join("repo"));
3365 root.hold_manual(Some("waiting".to_owned()));
3366 q.put(&mut root).unwrap();
3367 let mut mid = task("mid", dir.join("repo"));
3368 mid.block(vec![root.id.clone()], None);
3369 q.put(&mut mid).unwrap();
3370 let mut leaf = task("leaf", dir.join("repo"));
3371 leaf.block(vec![mid.id.clone()], None);
3372 q.put(&mut leaf).unwrap();
3373 (root, mid, leaf)
3374 }
3375
3376 fn deps_questions(questions: &Questions) -> Vec<Question> {
3377 questions
3378 .list()
3379 .into_iter()
3380 .filter(|q| q.node == DEPS_NODE)
3381 .collect()
3382 }
3383
3384 fn answer_deps(questions: &Questions, choice: usize) {
3385 let mut asked = deps_questions(questions).remove(0);
3386 let c = asked.choices[choice].clone();
3387 asked.answer(Answer::Choice(c)).unwrap();
3388 questions.put(&mut asked).unwrap();
3389 }
3390
3391 #[test]
3392 fn a_stuck_chain_earns_one_question_naming_every_dependant_and_is_not_reasked() {
3393 let (dir, q, questions) = store();
3394 let (root, mid, leaf) = stuck_chain(&q, dir.path());
3395
3396 let first = run_once(&q, &questions, None, Timestamp::now());
3397 assert_eq!(first.asked, std::slice::from_ref(&root.id));
3398 let asked = deps_questions(&questions);
3399 assert_eq!(asked.len(), 1, "one question per root, not per dependant");
3400 assert_eq!(asked[0].run, root.id);
3401 assert_eq!(asked[0].choices.len(), 3);
3402 assert!(asked[0].detail.contains(mid.short()), "{}", asked[0].detail);
3403 assert!(
3404 asked[0].detail.contains(leaf.short()),
3405 "{}",
3406 asked[0].detail
3407 );
3408
3409 let second = run_once(&q, &questions, None, Timestamp::now());
3410 assert!(second.asked.is_empty());
3411 assert_eq!(deps_questions(&questions).len(), 1);
3412 assert!(pending_for(&questions, &q.get(&root.id).unwrap()));
3413 }
3414
3415 #[test]
3416 fn a_stuck_root_with_a_machine_hold_gets_only_the_dependency_question() {
3417 let (dir, q, questions) = store();
3418 let mut root = task("root", dir.path().join("repo"));
3419 root.hold_machine(Some("gate red".to_owned()));
3420 q.put(&mut root).unwrap();
3421 let mut dep = task("dep", dir.path().join("repo"));
3422 dep.block(vec![root.id.clone()], None);
3423 q.put(&mut dep).unwrap();
3424
3425 run_once(&q, &questions, None, Timestamp::now());
3426 run_once(&q, &questions, None, Timestamp::now());
3427 assert_eq!(deps_questions(&questions).len(), 1);
3428 assert_eq!(
3429 questions.list().len(),
3430 1,
3431 "no second question about the hold"
3432 );
3433 }
3434
3435 #[test]
3436 fn a_dependency_that_can_still_run_asks_nothing() {
3437 let (dir, q, questions) = store();
3438 let mut live = task("live", dir.path().join("repo"));
3439 q.put(&mut live).unwrap();
3440 let mut dep = task("dep", dir.path().join("repo"));
3441 dep.block(vec![live.id.clone()], None);
3442 q.put(&mut dep).unwrap();
3443 let report = run_once(&q, &questions, None, Timestamp::now());
3444 assert!(report.asked.is_empty());
3445 assert!(questions.list().is_empty());
3446 }
3447
3448 #[test]
3449 fn answering_release_requeues_the_root_and_is_not_reasked() {
3450 let (dir, q, questions) = store();
3451 let (root, _mid, _leaf) = stuck_chain(&q, dir.path());
3452 run_once(&q, &questions, None, Timestamp::now());
3453 answer_deps(&questions, 0);
3454
3455 let report = run_once(&q, &questions, None, Timestamp::now());
3456 assert_eq!(report.answered, std::slice::from_ref(&root.id));
3457 assert!(report.asked.is_empty(), "applying must not re-ask");
3458 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Queued);
3459 let again = run_once(&q, &questions, None, Timestamp::now());
3460 assert!(again.asked.is_empty() && again.answered.is_empty());
3461 assert_eq!(deps_questions(&questions).len(), 1);
3462 }
3463
3464 #[test]
3465 fn answering_detach_frees_the_direct_dependant_and_keeps_the_root() {
3466 let (dir, q, questions) = store();
3467 let (root, mid, leaf) = stuck_chain(&q, dir.path());
3468 run_once(&q, &questions, None, Timestamp::now());
3469 answer_deps(&questions, 2);
3470
3471 let report = run_once(&q, &questions, None, Timestamp::now());
3472 assert!(report.asked.is_empty());
3473 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
3474 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
3475 let leaf = q.get(&leaf.id).unwrap();
3476 assert_eq!(leaf.status, TaskStatus::Blocked, "still waits on mid");
3477 assert_eq!(leaf.blocked_by, std::slice::from_ref(&mid.id));
3478 }
3479
3480 #[test]
3481 fn a_dependant_that_can_progress_through_another_blocker_is_not_stuck() {
3482 let (dir, q, questions) = store();
3483 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
3484 let mut live = task("live", dir.path().join("repo"));
3485 q.put(&mut live).unwrap();
3486 let mut both = q.get(&mid.id).unwrap();
3487 both.block(vec![root.id.clone(), live.id.clone()], None);
3488 q.put(&mut both).unwrap();
3489 assert!(
3491 run_once(&q, &questions, None, Timestamp::now())
3492 .asked
3493 .is_empty()
3494 );
3495 }
3496
3497 #[test]
3498 fn answering_discard_detaches_then_removes_the_root() {
3499 let (dir, q, questions) = store();
3500 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
3501 run_once(&q, &questions, None, Timestamp::now());
3502 answer_deps(&questions, 1);
3503
3504 let report = run_once(&q, &questions, None, Timestamp::now());
3505 assert!(q.get(&root.id).is_err());
3506 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
3507 assert!(
3508 report.asked.is_empty(),
3509 "no per-dependant quarantine question"
3510 );
3511 assert!(report.quarantined.is_empty());
3512 }
3513
3514 #[test]
3515 fn an_unmatched_deps_answer_changes_nothing_and_is_not_reasked() {
3516 let (dir, q, questions) = store();
3517 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
3518 run_once(&q, &questions, None, Timestamp::now());
3519 let mut asked = deps_questions(&questions).remove(0);
3520 asked.choices.clear();
3521 asked.answer(Answer::Text("dunno".to_owned())).unwrap();
3522 questions.put(&mut asked).unwrap();
3523
3524 for _ in 0..2 {
3525 let report = run_once(&q, &questions, None, Timestamp::now());
3526 assert!(report.asked.is_empty() && report.answered.is_empty());
3527 }
3528 assert_eq!(deps_questions(&questions).len(), 1);
3529 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
3530 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Blocked);
3531 }
3532
3533 #[test]
3534 fn a_dependency_cycle_terminates_and_is_asked_about_once() {
3535 let (dir, q, questions) = store();
3536 let mut a = task("a", dir.path().join("repo"));
3537 let mut b = task("b", dir.path().join("repo"));
3538 a.block(vec![b.id.clone()], None);
3539 b.block(vec![a.id.clone()], None);
3540 q.put(&mut a).unwrap();
3541 q.put(&mut b).unwrap();
3542
3543 let first = run_once(&q, &questions, None, Timestamp::now());
3544 assert_eq!(first.asked.len(), 1);
3545 let second = run_once(&q, &questions, None, Timestamp::now());
3546 assert!(second.asked.is_empty());
3547 assert_eq!(deps_questions(&questions).len(), 1);
3548 }
3549
3550 #[test]
3551 fn a_missing_dependency_is_still_quarantined_not_asked_about_as_stuck() {
3552 let (dir, q, questions) = store();
3553 let mut t = task("orphan", dir.path().join("repo"));
3554 t.block(vec!["20260101-000000-gone".to_owned()], None);
3555 q.put(&mut t).unwrap();
3556 let report = run_once(&q, &questions, None, Timestamp::now());
3557 assert_eq!(report.quarantined, [t.id.clone()]);
3558 assert!(deps_questions(&questions).is_empty());
3559 }
3560
3561 #[test]
3562 fn a_stale_manual_hold_can_be_discarded() {
3563 let (dir, q, questions) = store();
3564 let mut t = task("been sitting a while", dir.path().join("repo"));
3565 t.hold_manual(Some("waiting on a decision".to_owned()));
3566 q.put(&mut t).unwrap();
3567 let mut back = q.get(&t.id).unwrap();
3569 back.updated_at = Timestamp::now() - SignedDuration::new(8 * 24 * 60 * 60, 0);
3570 std::fs::write(
3571 q.path_of(&back.id),
3572 serde_json::to_string_pretty(&back).unwrap(),
3573 )
3574 .unwrap();
3575
3576 let report = run_once(&q, &questions, None, Timestamp::now());
3577 assert_eq!(report.asked, [t.id.clone()]);
3578 let open: Vec<_> = questions
3579 .list()
3580 .into_iter()
3581 .filter(|q| q.status.open())
3582 .collect();
3583 assert_eq!(open.len(), 1);
3584 let mut asked = open[0].clone();
3585 assert_eq!(asked.choices, ["resume it", "keep it held", "discard it"]);
3586 assert_eq!(
3587 JA.choices_manual(),
3588 ["再開する", "まだ止めておく", "捨ててよい"]
3589 );
3590 asked
3591 .answer(Answer::Choice(asked.choices[2].clone()))
3592 .unwrap();
3593 questions.put(&mut asked).unwrap();
3594 run_once(&q, &questions, None, Timestamp::now());
3595 assert!(q.get(&t.id).is_err());
3596 }
3597
3598 #[test]
3599 fn answering_resume_releases_the_task() {
3600 let (dir, q, questions) = store();
3601 let mut t = task("gate went red", dir.path().join("repo"));
3602 t.hold_machine(Some("gate red".to_owned()));
3603 q.put(&mut t).unwrap();
3604 run_once(&q, &questions, None, Timestamp::now());
3605
3606 let mut asked = questions
3607 .list()
3608 .into_iter()
3609 .find(|q| q.run == t.id)
3610 .unwrap();
3611 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
3612 questions.put(&mut asked).unwrap();
3613
3614 let report = run_once(&q, &questions, None, Timestamp::now());
3615 assert_eq!(report.answered, [t.id.clone()]);
3616 let back = q.get(&t.id).unwrap();
3617 assert_eq!(back.status, TaskStatus::Queued);
3618 assert!(back.hold_source.is_none());
3619 }
3620
3621 fn resumed_then_failed(q: &Queue, questions: &Questions, dir: &std::path::Path) -> Task {
3623 let mut t = task("gate went red", dir.join("repo"));
3624 t.hold_machine(Some("gate red".to_owned()));
3625 q.put(&mut t).unwrap();
3626 run_once(q, questions, None, Timestamp::now());
3627 let mut asked = questions
3628 .list()
3629 .into_iter()
3630 .find(|q| q.run == t.id)
3631 .unwrap();
3632 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
3633 questions.put(&mut asked).unwrap();
3634
3635 let report = run_once(q, questions, None, Timestamp::now());
3636 assert_eq!(report.answered, [t.id.clone()]);
3637 let mut back = q.get(&t.id).unwrap();
3638 assert_eq!(back.status, TaskStatus::Queued);
3639 assert_eq!(back.attempts, 0);
3640
3641 back.start("run-1".to_owned());
3642 back.fail("rebase conflict", 1);
3643 assert_eq!(back.status, TaskStatus::Held);
3644 q.put(&mut back).unwrap();
3645 back
3646 }
3647
3648 #[test]
3649 fn a_resume_answer_is_applied_once_and_a_new_machine_hold_is_asked_about() {
3650 let (dir, q, questions) = store();
3651 let t = resumed_then_failed(&q, &questions, dir.path());
3652
3653 let report = run_once(&q, &questions, None, Timestamp::now());
3654 assert!(report.answered.is_empty(), "the old answer must not replay");
3655 assert_eq!(report.asked, std::slice::from_ref(&t.id));
3656 let back = q.get(&t.id).unwrap();
3657 assert_eq!(back.status, TaskStatus::Held);
3658 assert_eq!(
3659 questions
3660 .list()
3661 .into_iter()
3662 .filter(|q| q.status.open())
3663 .count(),
3664 1
3665 );
3666 }
3667
3668 #[test]
3669 fn a_manual_hold_placed_after_a_resume_is_not_undone_by_the_old_answer() {
3670 let (dir, q, questions) = store();
3671 let mut t = resumed_then_failed(&q, &questions, dir.path());
3672 t.hold_manual(Some("operator stopped this".to_owned()));
3673 q.put(&mut t).unwrap();
3674 let before = questions.list().len();
3675
3676 let report = run_once(&q, &questions, None, Timestamp::now());
3677 assert!(report.answered.is_empty());
3678 assert!(report.asked.is_empty());
3679 let back = q.get(&t.id).unwrap();
3680 assert_eq!(back.status, TaskStatus::Held);
3681 assert_eq!(back.hold_source, Some(HoldSource::Manual));
3682 assert_eq!(questions.list().len(), before);
3683 }
3684
3685 #[test]
3686 fn answering_not_yet_keeps_it_held_as_a_manual_hold_and_does_not_reapply() {
3687 let (dir, q, questions) = store();
3688 let mut t = task("gate went red", dir.path().join("repo"));
3689 t.hold_machine(Some("gate red".to_owned()));
3690 q.put(&mut t).unwrap();
3691 run_once(&q, &questions, None, Timestamp::now());
3692
3693 let mut asked = questions
3694 .list()
3695 .into_iter()
3696 .find(|q| q.run == t.id)
3697 .unwrap();
3698 asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
3699 questions.put(&mut asked).unwrap();
3700
3701 let report = run_once(&q, &questions, None, Timestamp::now());
3702 assert_eq!(report.answered, [t.id.clone()]);
3703 let back = q.get(&t.id).unwrap();
3704 assert_eq!(back.status, TaskStatus::Held);
3705 assert_eq!(back.hold_source, Some(HoldSource::Manual));
3706 assert!(
3707 back.hold_reason
3708 .as_deref()
3709 .is_some_and(|r| r.contains("gate red")),
3710 "the original cause must survive a \"not yet\" answer, not just the \
3711 triage marker: {:?}",
3712 back.hold_reason
3713 );
3714
3715 let third = run_once(&q, &questions, None, Timestamp::now());
3719 assert!(third.answered.is_empty());
3720 assert!(third.asked.is_empty());
3721 }
3722
3723 #[test]
3724 fn answering_discard_removes_the_task_entirely() {
3725 let (dir, q, questions) = store();
3726 let mut t = task("gate went red", dir.path().join("repo"));
3727 t.hold_machine(Some("gate red".to_owned()));
3728 q.put(&mut t).unwrap();
3729 run_once(&q, &questions, None, Timestamp::now());
3730
3731 let mut asked = questions
3732 .list()
3733 .into_iter()
3734 .find(|q| q.run == t.id)
3735 .unwrap();
3736 asked.answer(Answer::Choice(EN.discard.to_owned())).unwrap();
3737 questions.put(&mut asked).unwrap();
3738
3739 let report = run_once(&q, &questions, None, Timestamp::now());
3740 assert_eq!(report.answered, [t.id.clone()]);
3741 assert!(
3742 q.get(&t.id).is_err(),
3743 "\"discard it\" (捨ててよい) must actually discard the task, not \
3744 just leave it sitting held forever"
3745 );
3746 }
3747
3748 #[test]
3749 fn an_answer_is_read_by_its_position_in_choices_not_by_the_callers_current_language() {
3750 let (dir, q, questions) = store();
3752 let ja_config = dir.path().join("ja.toml");
3753 std::fs::write(&ja_config, "[graph]\nlanguage = \"ja\"\n").unwrap();
3754 let mut t = task("gate went red", dir.path().join("repo"));
3755 t.hold_machine(Some("gate red".to_owned()));
3756 q.put(&mut t).unwrap();
3757 run_once(&q, &questions, Some(&ja_config), Timestamp::now());
3758
3759 let mut asked = questions
3760 .list()
3761 .into_iter()
3762 .find(|q| q.run == t.id)
3763 .unwrap();
3764 assert_eq!(asked.choices[0], JA.resume, "filed in Japanese");
3765 asked.answer(Answer::Choice(JA.resume.to_owned())).unwrap();
3766 questions.put(&mut asked).unwrap();
3767
3768 let en_config = dir.path().join("en.toml");
3773 std::fs::write(&en_config, "[graph]\nlanguage = \"en\"\n").unwrap();
3774 let report = run_once(&q, &questions, Some(&en_config), Timestamp::now());
3775 assert_eq!(report.answered, [t.id.clone()]);
3776 let back = q.get(&t.id).unwrap();
3777 assert_eq!(
3778 back.status,
3779 TaskStatus::Queued,
3780 "a resume answer must resume the task regardless of which \
3781 language it is read back in"
3782 );
3783 }
3784
3785 #[test]
3786 fn a_question_falls_back_to_last_error_when_hold_reason_was_never_set() {
3787 let (dir, q, questions) = store();
3792 let mut t = task("kept failing the gate", dir.path().join("repo"));
3793 t.start("run-1".to_owned());
3794 t.fail("gate red three times running", 1);
3795 assert_eq!(t.status, TaskStatus::Held);
3796 t.hold_reason = None; q.put(&mut t).unwrap();
3798
3799 run_once(&q, &questions, None, Timestamp::now());
3800 let asked = questions
3801 .list()
3802 .into_iter()
3803 .find(|q| q.run == t.id)
3804 .unwrap();
3805 assert!(
3806 asked.detail.contains("gate red three times running"),
3807 "the question must surface `last_error` when there is no \
3808 `hold_reason` to show instead: {}",
3809 asked.detail
3810 );
3811 }
3812
3813 #[test]
3814 fn open_question_for_and_open_task_ids_reflect_only_what_is_still_waiting() {
3815 let (dir, q, questions) = store();
3816 let mut t = task("gate went red", dir.path().join("repo"));
3817 t.hold_machine(Some("gate red".to_owned()));
3818 q.put(&mut t).unwrap();
3819
3820 assert!(open_question_for(&questions, &t.id).is_none());
3821 assert!(!open_task_ids(&questions).contains(&t.id));
3822
3823 run_once(&q, &questions, None, Timestamp::now());
3824 assert!(open_question_for(&questions, &t.id).is_some());
3825 assert!(open_task_ids(&questions).contains(&t.id));
3826
3827 let mut asked = questions
3828 .list()
3829 .into_iter()
3830 .find(|q| q.run == t.id)
3831 .unwrap();
3832 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
3833 questions.put(&mut asked).unwrap();
3834
3835 assert!(
3836 open_question_for(&questions, &t.id).is_none(),
3837 "an answered question is no longer open"
3838 );
3839 assert!(!open_task_ids(&questions).contains(&t.id));
3840 }
3841
3842 #[test]
3843 fn pending_for_stays_true_between_an_answer_and_the_next_run_once_pass() {
3844 let (dir, q, questions) = store();
3850 let mut t = task("gate went red", dir.path().join("repo"));
3851 t.hold_machine(Some("gate red".to_owned()));
3852 q.put(&mut t).unwrap();
3853
3854 assert!(!pending_for(&questions, &t));
3855
3856 run_once(&q, &questions, None, Timestamp::now());
3857 let held = q.get(&t.id).unwrap();
3858 assert!(pending_for(&questions, &held), "still waiting on an answer");
3859
3860 let mut asked = questions
3861 .list()
3862 .into_iter()
3863 .find(|q| q.run == t.id)
3864 .unwrap();
3865 asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
3866 questions.put(&mut asked).unwrap();
3867 assert!(!asked.status.open());
3868
3869 let still_held = q.get(&t.id).unwrap();
3871 assert!(
3872 pending_for(&questions, &still_held),
3873 "answered but not yet applied is still pending"
3874 );
3875
3876 run_once(&q, &questions, None, Timestamp::now());
3877 let after = q.get(&t.id).unwrap();
3878 assert!(
3879 !pending_for(&questions, &after),
3880 "the answer is applied now, nothing left pending"
3881 );
3882 }
3883
3884 #[test]
3885 fn migrated_keep_held_is_consumed_but_can_be_reviewed_and_discarded_again() {
3886 let (dir, queue, questions) = store();
3887 let mut t = task("keep held", dir.path().join("repo"));
3888 t.hold_machine(Some("unresolved cause".into()));
3889 queue.put(&mut t).unwrap();
3890 run_once(&queue, &questions, None, Timestamp::now());
3891 let mut old = questions.list().remove(0);
3892 old.answer(Answer::Choice(old.choices[1].clone())).unwrap();
3893 questions.put(&mut old).unwrap();
3894 run_once(&queue, &questions, None, Timestamp::now());
3895 let held = queue.get(&t.id).unwrap();
3896 assert!(held.triage_applied(&old.id));
3897
3898 let migration = dir.path().join("notifications/task-chat-migration-v1");
3899 std::fs::create_dir_all(&migration).unwrap();
3900 std::fs::write(
3901 migration.join("state.json"),
3902 serde_json::to_vec(&serde_json::json!({
3903 "schema": 1, "classification_revision": 1, "pending": [], "sources": [old.id]
3904 }))
3905 .unwrap(),
3906 )
3907 .unwrap();
3908 assert!(questions.list_for_effects()[0].status.open());
3909 assert!(!pending_for(&questions, &held));
3910 assert!(open_question_for(&questions, &t.id).is_none());
3911 assert!(!open_task_ids(&questions).contains(&t.id));
3912 assert!(old.answer(Answer::Choice(old.choices[2].clone())).is_err());
3913 assert!(
3914 run_once(&queue, &questions, None, Timestamp::now())
3915 .answered
3916 .is_empty()
3917 );
3918
3919 let later = held.updated_at + SignedDuration::from_hours(24 * 8);
3920 assert_eq!(
3921 run_once(&queue, &questions, None, later).asked,
3922 [t.id.clone()]
3923 );
3924 let mut fresh = open_question_for(&questions, &t.id).unwrap();
3925 assert_ne!(fresh.id, old.id);
3926 assert_eq!(fresh.choices[2], EN.discard);
3927 fresh
3928 .answer(Answer::Choice(fresh.choices[2].clone()))
3929 .unwrap();
3930 questions.put(&mut fresh).unwrap();
3931 assert_eq!(
3932 run_once(&queue, &questions, None, later).answered,
3933 [t.id.clone()]
3934 );
3935 assert!(queue.get(&t.id).is_err());
3936 assert_eq!(
3937 questions.read_history(&old.id).unwrap().resolution(),
3938 Some(EN.wait.into())
3939 );
3940 }
3941
3942 #[test]
3943 fn migrated_unapplied_answers_remain_fenced_but_are_not_displayed_open() {
3944 for node in [NODE, DEPS_NODE] {
3945 let (dir, queue, questions) = store();
3946 let mut t = task("unapplied", dir.path().join("repo"));
3947 t.hold_manual(Some("waiting".into()));
3948 queue.put(&mut t).unwrap();
3949 let mut q = Question::new(
3950 t.id.clone(),
3951 node.into(),
3952 SEAT.into(),
3953 "unapplied".into(),
3954 String::new(),
3955 EN.choices3(),
3956 );
3957 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
3958 questions.put(&mut q).unwrap();
3959 let migration = dir.path().join("notifications/task-chat-migration-v1");
3960 std::fs::create_dir_all(&migration).unwrap();
3961 std::fs::write(
3962 migration.join("state.json"),
3963 serde_json::to_vec(&serde_json::json!({
3964 "schema": 1, "classification_revision": 1, "pending": [], "sources": [q.id]
3965 }))
3966 .unwrap(),
3967 )
3968 .unwrap();
3969 assert!(pending_for(&questions, &t));
3970 assert!(open_question_for(&questions, &t.id).is_none());
3971 assert!(!open_task_ids(&questions).contains(&t.id));
3972 assert!(apply_answers(&queue, &questions).is_empty());
3973 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
3974 t.mark_triage_applied(&q.id);
3975 queue.put(&mut t).unwrap();
3976 assert!(!pending_for(&questions, &t));
3977 assert!(!deps_pending_in(&RecoveryIndex::load(&questions), &t));
3978 }
3979 }
3980}