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 !disk_only {
1751 match crate::head_e2e_stop::triage_status(queue, &task) {
1752 crate::head_e2e_stop::TriageStatus::NotHeadE2e => {}
1753 crate::head_e2e_stop::TriageStatus::HoldStillActive => continue,
1754 crate::head_e2e_stop::TriageStatus::ResolvedChanged => {
1755 task.resume_head_e2e_wait();
1756 if queue.put(&mut task).is_ok() {
1757 report.resumed.push(task.id.clone());
1758 }
1759 continue;
1760 }
1761 }
1762 }
1763 if repair_receipt_notice(queue, &task) {
1764 continue;
1765 }
1766 if !disk_wait_known(&task, questions.root().parent().unwrap_or(Path::new("")))
1773 && deps_pending_in(&recovery, &task)
1774 {
1775 continue;
1776 }
1777
1778 let explicit = match &task.overrides {
1779 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
1780 _ => config_override,
1781 };
1782 let cfg = Config::discover(&repo_for(&task), explicit)
1783 .ok()
1784 .map(|(c, _)| c);
1785 let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
1786
1787 if disk_wait_known(&task, questions.root().parent().unwrap_or(Path::new(""))) {
1788 if task
1789 .disk_checked_at
1790 .is_some_and(|at| now.as_second() - at.as_second() < 60)
1791 {
1792 continue;
1793 }
1794 let expected = task.clone();
1795 task.disk_checked_at = Some(now);
1796 if !task.has_disk_capacity_cause() {
1797 task.mark_disk_capacity();
1799 }
1800 if queue.commit_disk_wait(&mut task, &expected).is_err() {
1801 continue;
1802 }
1803 refresh_disk_notices(questions.root().parent().unwrap_or(Path::new("")), &task);
1804 if cfg.as_ref().and_then(|c| resolved(&task, c)) == Some(true) {
1807 match resume_disk_task(queue, questions, &mut task, &ownership) {
1808 Ok(superseded) => {
1809 if superseded {
1810 report.superseded.push(task.id.clone());
1811 }
1812 report.resumed.push(task.id.clone());
1813 }
1814 Err(error) => {
1815 if !report.needs_owner.contains(&task.id) {
1816 report.needs_owner.push(task.id.clone());
1817 }
1818 crate::notices::raise_in(
1819 questions.root().parent().unwrap_or(Path::new("")),
1820 crate::notices::Notice::warn(
1821 &format!("disk-recovered:{}", task.id),
1822 format!(
1823 "Task {}: disk capacity recovered; automatic recovery is still blocked ({error}). Existing owner decisions and unrelated approvals require explicit resolution. Disk monitoring continues.",
1824 task.id
1825 ),
1826 ).link(crate::notices::Link::Task { id: task.id.clone() }).about([task.id.clone()]),
1827 );
1828 }
1829 }
1830 }
1831 continue;
1832 }
1833 if disk_only {
1834 continue;
1835 }
1836
1837 if let Some(q) = recovery.latest(NODE, &task.id) {
1838 if !consumed(&task, &q) && (q.status.open() || awaiting_task_chat(&q, &task)) {
1839 continue;
1841 }
1842 }
1848
1849 match task.hold_source {
1850 Some(HoldSource::Machine) => {
1851 let overridden = task
1852 .resume_override
1853 .as_ref()
1854 .is_some_and(|o| o.conductor_rehold.is_some() && !o.forced);
1855 if overridden {
1856 if file_question(
1857 questions,
1858 &ownership,
1859 &task,
1860 Bucket::ConductorOverride,
1861 w,
1862 now,
1863 )
1864 .is_some()
1865 {
1866 report.asked.push(task.id.clone());
1867 }
1868 } else if cfg.as_ref().and_then(|c| resolved(&task, c)) == Some(true) {
1869 task.release();
1870 if queue.put(&mut task).is_ok() {
1871 report.resumed.push(task.id.clone());
1872 }
1873 } else if !known_isolated_cache_wait(&task, &crate::run::home())
1874 && file_question(questions, &ownership, &task, Bucket::MachineUnknown, w, now)
1875 .is_some()
1876 {
1877 report.asked.push(task.id.clone());
1878 }
1879 }
1880 None => {
1881 if file_question(questions, &ownership, &task, Bucket::Legacy, w, now).is_some() {
1882 report.asked.push(task.id.clone());
1883 }
1884 }
1885 Some(HoldSource::Manual) => {
1886 if manual_is_stale(&task, now)
1887 && file_question(questions, &ownership, &task, Bucket::ManualStale, w, now)
1888 .is_some()
1889 {
1890 report.asked.push(task.id.clone());
1891 }
1892 }
1893 }
1894 }
1895 report
1896}
1897
1898pub fn open_question_for(questions: &Questions, task_id: &str) -> Option<Question> {
1903 let queue = question_queue(questions);
1904 let task = queue.get(task_id).ok()?;
1905 display_index(questions, &queue, std::slice::from_ref(&task)).displayed_open(&task)
1906}
1907
1908pub fn pending_for(questions: &Questions, task: &Task) -> bool {
1922 !pending_recovery_questions(questions, task).is_empty()
1923}
1924
1925pub(crate) fn pending_recovery_questions(questions: &Questions, task: &Task) -> Vec<Question> {
1928 RecoveryIndex::load(questions).pending(task)
1929}
1930
1931fn awaiting_task_chat(q: &Question, task: &Task) -> bool {
1932 q.status != QuestionStatus::Abandoned
1933 && q.routed_chat.is_some()
1934 && !already_applied(task, q)
1935 && task.resumption.as_ref().map_or(0, |r| r.generation) == q.triage_generation.unwrap_or(0)
1936 && task.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1937}
1938
1939fn deps_pending_in(recovery: &RecoveryIndex, task: &Task) -> bool {
1943 match recovery.latest(DEPS_NODE, &task.id) {
1944 Some(q) if consumed(task, &q) => false,
1945 Some(q) if q.status.open() || awaiting_task_chat(&q, task) => true,
1946 Some(q) if q.status == QuestionStatus::Answered => true,
1947 _ => false,
1948 }
1949}
1950
1951pub fn open_task_ids(questions: &Questions) -> std::collections::BTreeSet<String> {
1956 let queue = question_queue(questions);
1957 let tasks = queue.list();
1958 let index = display_index(questions, &queue, &tasks);
1959 tasks
1960 .iter()
1961 .filter(|task| index.displayed_open(task).is_some())
1962 .map(|task| task.id.clone())
1963 .collect()
1964}
1965
1966fn question_queue(questions: &Questions) -> Queue {
1967 Queue::at(
1968 questions
1969 .root()
1970 .parent()
1971 .unwrap_or(Path::new(""))
1972 .join("queue"),
1973 )
1974}
1975
1976fn display_index(questions: &Questions, queue: &Queue, tasks: &[Task]) -> RecoveryIndex {
1978 RecoveryIndex::from_scan(queue, tasks, questions.list())
1979}
1980
1981#[cfg(test)]
1982mod tests {
1983 use super::*;
1984 use crate::ask::Answer;
1985 use crate::queue::Source;
1986 use jiff::SignedDuration;
1987
1988 fn store() -> (tempfile::TempDir, Queue, Questions) {
1989 let dir = tempfile::tempdir().unwrap();
1990 let q = Queue::at(dir.path().join("queue"));
1991 let s = Questions::at(dir.path().join("questions"));
1992 (dir, q, s)
1993 }
1994
1995 fn task(title: &str, repo: PathBuf) -> Task {
1996 Task::new(title.to_owned(), format!("do {title}"), repo, Source::Human)
1997 }
1998
1999 fn disk_task(repo: PathBuf) -> Task {
2000 let mut t = task("capacity", repo);
2001 t.hold_machine(crate::disk::gate_in(1_477_050_368, 3_221_225_472, "ja"));
2002 t.mark_disk_capacity();
2003 t.attempts = 3;
2004 t
2005 }
2006
2007 #[test]
2008 fn disk_wait_repeated_pressure_measurement_failure_and_recovery_cost_nothing() {
2009 let (dir, queue, questions) = store();
2010 let cfg = gate_disabled_config(dir.path());
2011 let mut t = disk_task(dir.path().to_owned());
2012 queue.put(&mut t).unwrap();
2013 let notices = crate::notices::Notices::at(dir.path().join("notifications"));
2014 let before = serde_json::to_value(notices.list()).unwrap();
2015 let start = Timestamp::now();
2016 let probes = std::cell::Cell::new(0);
2017 for seconds in [0, 1, 10, 60, 61, 120] {
2018 let report = run_once_with_probe(
2019 &queue,
2020 &questions,
2021 Some(&cfg),
2022 start + SignedDuration::from_secs(seconds),
2023 true,
2024 |_, _| {
2025 probes.set(probes.get() + 1);
2026 Some(false) },
2028 );
2029 assert!(report.is_empty());
2030 assert_eq!(queue.get(&t.id).unwrap().attempts, 3);
2031 }
2032 assert_eq!(
2033 probes.get(),
2034 3,
2035 "resource probes are bounded to one per minute"
2036 );
2037 assert!(questions.list().is_empty());
2038 assert_eq!(serde_json::to_value(notices.list()).unwrap(), before);
2039 let recovered = run_once_with_probe(
2040 &queue,
2041 &questions,
2042 Some(&cfg),
2043 start + SignedDuration::from_secs(180),
2044 true,
2045 |_, _| Some(true),
2046 );
2047 assert_eq!(recovered.resumed, [t.id.clone()]);
2048 let saved = queue.get(&t.id).unwrap();
2049 assert_eq!(saved.status, TaskStatus::Queued);
2050 assert_eq!(saved.attempts, 3);
2051 let again = run_once_with_probe(
2052 &queue,
2053 &questions,
2054 Some(&cfg),
2055 start + SignedDuration::from_secs(240),
2056 true,
2057 |_, _| panic!("queued tasks are not relaunched"),
2058 );
2059 assert!(again.is_empty());
2060 }
2061
2062 #[test]
2063 fn disk_wait_supersedes_only_untouched_automatic_questions_in_both_stores() {
2064 for routed in [false, true] {
2065 let (dir, queue, questions) = store();
2066 let cfg = gate_disabled_config(dir.path());
2067 let mut t = disk_task(dir.path().to_owned());
2068 queue.put(&mut t).unwrap();
2069 let q = file_question(
2070 &questions,
2071 &crate::task_chat::InquiryOwnership::default(),
2072 &t,
2073 Bucket::MachineUnknown,
2074 &JA,
2075 Timestamp::now(),
2076 )
2077 .unwrap();
2078 if routed {
2079 crate::task_chat::sweep(
2080 &queue,
2081 &crate::talk::Talks::at(dir.path().join("talks")),
2082 &questions,
2083 dir.path(),
2084 );
2085 assert!(
2086 crate::task_inquiry::Outbox::at(dir.path())
2087 .get(&q.id)
2088 .is_ok()
2089 );
2090 }
2091 let start = Timestamp::now();
2092 for seconds in [0, 60, 120] {
2093 assert!(
2094 run_once_with_probe(
2095 &queue,
2096 &questions,
2097 Some(&cfg),
2098 start + SignedDuration::from_secs(seconds),
2099 true,
2100 |_, _| Some(false)
2101 )
2102 .is_empty()
2103 );
2104 assert!(questions.read_history(&q.id).unwrap().status.open());
2105 assert_eq!(questions.list().len(), 1);
2106 }
2107 let report = monitor_disk_waits(
2108 &queue,
2109 &questions,
2110 Some(&cfg),
2111 start + SignedDuration::from_secs(180),
2112 );
2113 assert_eq!(report.resumed, [t.id.clone()], "routed={routed}");
2114 let source = questions.read_history(&q.id).unwrap();
2115 assert_eq!(source.status, QuestionStatus::Abandoned);
2116 assert!(source.answer.is_none());
2117 assert!(source.answered_at.is_none());
2118 assert!(!pending_for(&questions, &queue.get(&t.id).unwrap()));
2119 if routed {
2120 let d = crate::task_inquiry::Outbox::at(dir.path())
2121 .get(&q.id)
2122 .unwrap()
2123 .decision
2124 .unwrap();
2125 assert_eq!(d.status, crate::task_decision::Status::Resolved);
2126 assert!(
2127 d.request.is_none(),
2128 "system supersession fabricates no owner request"
2129 );
2130 }
2131 }
2132 }
2133
2134 #[test]
2135 fn disk_wait_respects_owner_hold_discussion_and_unrelated_approvals() {
2136 for kind in [
2137 "manual",
2138 "answered",
2139 "discussion",
2140 "unrelated",
2141 "override",
2142 "native-hold",
2143 "missing-native",
2144 ] {
2145 let (dir, queue, questions) = store();
2146 let cfg = gate_disabled_config(dir.path());
2147 let mut t = disk_task(dir.path().to_owned());
2148 queue.put(&mut t).unwrap();
2149 let q = file_question(
2150 &questions,
2151 &crate::task_chat::InquiryOwnership::default(),
2152 &t,
2153 Bucket::MachineUnknown,
2154 &EN,
2155 Timestamp::now(),
2156 )
2157 .unwrap();
2158 match kind {
2159 "manual" => {
2160 t.hold_manual(Some("owner hold".into()));
2161 queue.put(&mut t).unwrap();
2162 }
2163 "answered" => {
2164 questions
2165 .update(&q.id, |q| q.answer(Answer::Choice(q.choices[1].clone())))
2166 .unwrap();
2167 }
2168 "discussion" => {
2169 questions
2170 .update(&q.id, |q| q.say("please wait".to_owned()))
2171 .unwrap();
2172 }
2173 "unrelated" => {
2174 questions
2175 .update(&q.id, |q| {
2176 q.node = "land".into();
2177 Ok(())
2178 })
2179 .unwrap();
2180 }
2181 "override" => {
2182 t.resume_override = Some(OperatorResume {
2183 question_id: "owner".into(),
2184 at: Timestamp::now(),
2185 conductor_rehold: Some("pending conductor decision".into()),
2186 forced: true,
2187 pinned_run: None,
2188 });
2189 queue.put(&mut t).unwrap();
2190 }
2191 "native-hold" | "missing-native" => {
2192 crate::task_chat::sweep(
2193 &queue,
2194 &crate::talk::Talks::at(dir.path().join("talks")),
2195 &questions,
2196 dir.path(),
2197 );
2198 if kind == "native-hold" {
2199 crate::task_inquiry::Outbox::at(dir.path())
2200 .update_decision(&q.id, |d| d.accept("owner requested hold"))
2201 .unwrap();
2202 } else {
2203 questions
2207 .update(&q.id, |q| {
2208 q.routed_chat = Some("delivered-chat".into());
2209 Ok(())
2210 })
2211 .unwrap();
2212 std::fs::remove_file(
2213 dir.path()
2214 .join("notifications/task-inquiries")
2215 .join(format!("{}.json", q.id)),
2216 )
2217 .unwrap();
2218 }
2219 }
2220 _ => unreachable!(),
2221 }
2222 let report = run_once(&queue, &questions, Some(&cfg), Timestamp::now());
2223 assert!(report.resumed.is_empty(), "{kind}");
2224 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held, "{kind}");
2225 assert!(
2226 questions.read_history(&q.id).unwrap().status != QuestionStatus::Abandoned,
2227 "{kind}"
2228 );
2229 }
2230 }
2231
2232 #[test]
2233 fn startup_disk_wait_probes_the_task_override_and_does_not_pin_history() {
2234 use crate::config::BuildCache;
2235 crate::run::pin_test_home();
2238 let (dir, queue, questions) = store();
2239 let shared = dir.path().join("shared");
2240 let isolated = crate::build_target::root(dir.path());
2241 let mut config = Config::default();
2242 config.disk.min_free_bytes = 0;
2243 config.graph.worktree_root = Some(dir.path().to_owned());
2244 config.verify.gate = vec![format!(
2245 "CARGO_TARGET_DIR='{}' cargo check",
2246 shared.display()
2247 )];
2248 let mut task = disk_task(dir.path().to_owned());
2249 task.mark_startup_disk_capacity();
2250 task.overrides = Some(crate::queue::RunOverrides {
2251 build_cache: Some(BuildCache::Isolated),
2252 ..Default::default()
2253 });
2254 let check = |task: &Task, config: &Config, blocked: &Path| {
2255 machine_cause_resolved_with_admission(task, config, dir.path(), |paths, _| {
2256 !paths.iter().any(|path| path == blocked)
2257 })
2258 };
2259 assert_eq!(check(&task, &config, &isolated), Some(false));
2260 assert_eq!(check(&task, &config, &shared), Some(true));
2261 config.verify.build_cache = BuildCache::Isolated;
2262 task.overrides.as_mut().unwrap().build_cache = Some(BuildCache::Shared);
2263 assert_eq!(check(&task, &config, &shared), Some(false));
2264 assert_eq!(check(&task, &config, &isolated), Some(true));
2265 task.urgent = true;
2266 config.verify.build_cache = BuildCache::Shared;
2267 task.overrides.as_mut().unwrap().build_cache = None;
2268 assert_eq!(check(&task, &config, &isolated), Some(false));
2269 assert_eq!(check(&task, &config, &shared), Some(true));
2270 task.overrides.as_mut().unwrap().build_cache = Some(BuildCache::Shared);
2271
2272 task.runs.push("historical-execution".into());
2273 queue.put(&mut task).unwrap();
2274 let cfg = gate_disabled_config(dir.path());
2275 let report = run_once_with_probe(
2276 &queue,
2277 &questions,
2278 Some(&cfg),
2279 Timestamp::now(),
2280 true,
2281 |task, _| check(task, &config, &isolated),
2282 );
2283 assert_eq!(report.resumed, [task.id.clone()]);
2284 let saved = queue.get(&task.id).unwrap();
2285 assert_eq!(saved.attempts, task.attempts);
2286 assert_eq!(saved.runs, task.runs);
2287 assert!(saved.disk_resume_run.is_none());
2288 }
2289
2290 #[test]
2291 fn disk_wait_reuses_retained_execution_and_preserves_attempt_and_approval_evidence() {
2292 let (dir, queue, questions) = store();
2293 let cfg = gate_disabled_config(dir.path());
2294 let mut run = crate::run::RunState::new(
2295 dir.path().to_owned(),
2296 "main".into(),
2297 "base".into(),
2298 "capacity".into(),
2299 Config::default(),
2300 );
2301 run.status = crate::run::RunStatus::Blocked;
2302 run.driver_exited = true;
2303 run.save_under(dir.path()).unwrap();
2304 let mut t = disk_task(dir.path().to_owned());
2305 t.runs.push(run.id.clone());
2306 t.resume_override = Some(OperatorResume {
2307 question_id: "approved-recovery".into(),
2308 at: Timestamp::now(),
2309 conductor_rehold: None,
2310 forced: true,
2311 pinned_run: Some(run.id.clone()),
2312 });
2313 queue.put(&mut t).unwrap();
2314 let before = std::fs::read(dir.path().join("runs").join(&run.id).join("run.json")).unwrap();
2315 let report = run_once_with_probe(
2316 &queue,
2317 &questions,
2318 Some(&cfg),
2319 Timestamp::now(),
2320 true,
2321 |_, _| Some(true),
2322 );
2323 assert_eq!(report.resumed, [t.id.clone()]);
2324 let resumed = queue.get(&t.id).unwrap();
2325 assert_eq!(resumed.runs, t.runs);
2326 assert_eq!(resumed.disk_resume_run.as_deref(), Some(run.id.as_str()));
2327 assert_eq!(resumed.attempts, t.attempts);
2328 assert_eq!(resumed.resumption, t.resumption);
2329 assert_eq!(
2330 serde_json::to_value(&resumed.resume_override).unwrap(),
2331 serde_json::to_value(&t.resume_override).unwrap()
2332 );
2333 assert_eq!(
2334 std::fs::read(dir.path().join("runs").join(&run.id).join("run.json")).unwrap(),
2335 before
2336 );
2337 assert!(
2338 run_once_with_probe(
2339 &queue,
2340 &questions,
2341 Some(&cfg),
2342 Timestamp::now(),
2343 true,
2344 |_, _| panic!("no duplicate launch")
2345 )
2346 .is_empty()
2347 );
2348 }
2349
2350 #[test]
2351 fn disk_wait_interrupted_question_supersession_is_idempotent() {
2352 for abandoned in [false, true] {
2353 let (dir, queue, questions) = store();
2354 let cfg = gate_disabled_config(dir.path());
2355 let mut t = disk_task(dir.path().to_owned());
2356 queue.put(&mut t).unwrap();
2357 let q = file_question(
2358 &questions,
2359 &crate::task_chat::InquiryOwnership::default(),
2360 &t,
2361 Bucket::MachineUnknown,
2362 &EN,
2363 Timestamp::now(),
2364 )
2365 .unwrap();
2366 let outbox = crate::task_inquiry::Outbox::at(dir.path());
2367 outbox
2368 .enqueue(crate::task_chat::live_record(dir.path(), &t, &q))
2369 .unwrap();
2370 outbox
2371 .update_decision(&q.id, |d| d.settle(DISK_SUPERSEDED))
2372 .unwrap();
2373 if abandoned {
2374 questions
2375 .update(&q.id, |q| {
2376 q.abandon(DISK_SUPERSEDED);
2377 Ok(())
2378 })
2379 .unwrap();
2380 }
2381 let report = monitor_disk_waits(&queue, &questions, Some(&cfg), Timestamp::now());
2382 assert_eq!(report.resumed, [t.id.clone()]);
2383 assert_eq!(queue.get(&t.id).unwrap().attempts, 3);
2384 assert!(questions.read_history(&q.id).unwrap().answer.is_none());
2385 assert_eq!(
2386 outbox.get(&q.id).unwrap().decision.unwrap().history.len(),
2387 1
2388 );
2389 }
2390 }
2391
2392 #[test]
2393 fn disk_wait_legacy_migration_requires_machine_provenance_and_exact_localized_format() {
2394 let (dir, queue, _) = store();
2395 for (language, source, suffix, expected) in [
2396 ("en", Some(HoldSource::Machine), "", true),
2397 ("ja", Some(HoldSource::Machine), "", true),
2398 ("ja", Some(HoldSource::Manual), "", false),
2399 ("ja", None, "", false),
2400 ("ja", Some(HoldSource::Machine), " owner hold", false),
2401 ] {
2402 let mut t = task("legacy", dir.path().to_owned());
2403 t.hold_machine(Some(format!(
2404 "{}{suffix}",
2405 crate::disk::gate_in(1477050368, 3221225472, language).unwrap()
2406 )));
2407 t.schema = 21;
2408 t.hold_source = source;
2409 queue.put(&mut t).unwrap();
2410 let loaded = queue.get(&t.id).unwrap();
2411 assert_eq!(loaded.machine_hold_cause.is_some(), expected);
2412 assert_eq!(disk_wait_eligible(&loaded), expected);
2413 }
2414 }
2415
2416 #[test]
2417 fn disk_wait_refreshes_stale_notice_wording_without_redelivery() {
2418 let (dir, queue, questions) = store();
2419 let cfg = gate_disabled_config(dir.path());
2420 let mut t = disk_task(dir.path().to_owned());
2421 queue.put(&mut t).unwrap();
2422 let notices = crate::notices::Notices::at(dir.path().join("notifications"));
2423 let key = format!("disk:{}", t.repo.display());
2424 let n = notices
2425 .raise(crate::notices::Notice::warn(
2426 &key,
2427 "Free some, then release it from the queue.",
2428 ))
2429 .unwrap();
2430 notices.mark_read(&n.id).unwrap();
2431 let before = notices.get(&n.id).unwrap();
2432 let report = run_once_with_probe(
2433 &queue,
2434 &questions,
2435 Some(&cfg),
2436 Timestamp::now(),
2437 true,
2438 |_, _| Some(false),
2439 );
2440 assert!(report.is_empty());
2441 let after = notices.get(&n.id).unwrap();
2442 assert!(after.message.contains("automatically"));
2443 assert_eq!(before.generation, after.generation);
2444 assert_eq!(before.count, after.count);
2445 assert_eq!(before.read_at, after.read_at);
2446 }
2447
2448 #[test]
2449 fn disk_wait_owner_discard_is_applied_without_automatic_resumption() {
2450 let (dir, queue, questions) = store();
2451 let cfg = gate_disabled_config(dir.path());
2452 let mut t = disk_task(dir.path().to_owned());
2453 queue.put(&mut t).unwrap();
2454 let q = file_question(
2455 &questions,
2456 &crate::task_chat::InquiryOwnership::default(),
2457 &t,
2458 Bucket::MachineUnknown,
2459 &EN,
2460 Timestamp::now(),
2461 )
2462 .unwrap();
2463 questions
2464 .update(&q.id, |q| q.answer(Answer::Choice(q.choices[2].clone())))
2465 .unwrap();
2466 let report = run_once(&queue, &questions, Some(&cfg), Timestamp::now());
2467 assert!(report.resumed.is_empty());
2468 assert!(queue.get(&t.id).is_err());
2469 assert!(questions.read_history(&q.id).unwrap().answer.is_some());
2470 }
2471
2472 #[test]
2473 fn disk_wait_commit_cannot_overwrite_a_concurrent_owner_hold() {
2474 let (dir, queue, questions) = store();
2475 let mut stale = disk_task(dir.path().to_owned());
2476 queue.put(&mut stale).unwrap();
2477 let mut current = queue.get(&stale.id).unwrap();
2478 current.hold_manual(Some("wait for owner".into()));
2479 queue.put(&mut current).unwrap();
2480 assert!(
2481 resume_disk_task(
2482 &queue,
2483 &questions,
2484 &mut stale,
2485 &crate::task_chat::InquiryOwnership::default()
2486 )
2487 .is_err()
2488 );
2489 assert_eq!(
2490 queue.get(¤t.id).unwrap().hold_source,
2491 Some(HoldSource::Manual)
2492 );
2493 }
2494
2495 #[test]
2496 fn recovery_index_preserves_supersession_and_ambiguous_file_references() {
2497 let (dir, queue, questions) = store();
2498 let mut t = task("supersession", dir.path().join("repo"));
2499 t.id = "task-alpha-end".into();
2500 queue.put(&mut t).unwrap();
2501 let at: Timestamp = "2026-11-01T00:00:00Z".parse().unwrap();
2502 let mut all = Vec::new();
2503 for (i, run) in ["task-alpha-end", "task-alpha", "end"]
2504 .into_iter()
2505 .enumerate()
2506 {
2507 let mut q = Question::new(
2508 run.into(),
2509 NODE.into(),
2510 SEAT.into(),
2511 "superseded".into(),
2512 String::new(),
2513 EN.choices3(),
2514 );
2515 q.id = format!("superseded-{i}");
2516 q.asked_at = at;
2517 all.push(q);
2518 }
2519 let evidence: Vec<_> = all
2520 .iter()
2521 .map(|q| {
2522 (
2523 q.id.clone(),
2524 crate::repair_budget::reconcile::source(q).unwrap(),
2525 )
2526 })
2527 .collect();
2528 t.repair_reconciliations.push(
2529 serde_json::from_value(serde_json::json!({
2530 "request": {
2531 "task": t.id, "run": "run", "head": "head", "expect_pass": 0,
2532 "receipt": "grant", "question": "original", "answer_at": at,
2533 "request": "reconcile", "reason": "fixture"
2534 },
2535 "grant": {
2536 "request": {
2537 "task": t.id, "run": "run", "kind": "review", "rounds": 1,
2538 "head": "head", "expect_pass": 0, "request": "grant", "reason": "fixture"
2539 },
2540 "at": at, "decision": null, "contract": "fixture"
2541 },
2542 "source": "fixture", "application": "fixture", "decision": at,
2543 "superseded_questions": evidence
2544 }))
2545 .unwrap(),
2546 );
2547 queue.put(&mut t).unwrap();
2548 let index = RecoveryIndex::from_scan(&queue, &[t.clone()], all.clone());
2549 assert!(index.latest.is_empty());
2550 std::fs::write(queue.path_of("task-alphabet-other"), "{").unwrap();
2552 std::fs::write(queue.path_of("broken-end"), "{").unwrap();
2553 let index = RecoveryIndex::from_scan(&queue, &[t.clone()], all.clone());
2554 assert!(index.latest(NODE, "end").is_some());
2555 assert!(index.latest(NODE, "task-alpha").is_some());
2556 assert!(index.latest(NODE, &t.id).is_none());
2557 all[0].detail.push_str("changed evidence");
2558 let index = RecoveryIndex::from_scan(&queue, &[t], all);
2559 assert!(index.latest(NODE, "task-alpha-end").is_some());
2560 assert_eq!(questions.list().len(), 0);
2561 }
2562
2563 #[test]
2564 fn ownership_index_requires_positive_foreground_provenance() {
2565 let (dir, queue, _) = store();
2566 let mut run = crate::run::RunState::new(
2567 dir.path().join("repo"),
2568 "main".into(),
2569 "origin".into(),
2570 "fixture".into(),
2571 Config::default(),
2572 );
2573 run.origin = Some(crate::run::Origin::operator());
2574 run.save_under(dir.path()).unwrap();
2575 let foreground = run.id.clone();
2576 run.id = "owned-run".into();
2577 run.origin = Some(crate::run::Origin::queue("missing-task"));
2578 run.save_under(dir.path()).unwrap();
2579 let mut task = task("owner", dir.path().join("repo"));
2580 task.runs = vec!["linked-run".into()];
2581 queue.put(&mut task).unwrap();
2582 let ownership = crate::task_chat::InquiryOwnership::default();
2583 for (run, cwd, node, seat, expected) in [
2584 (foreground.as_str(), true, "node", "seat", true),
2585 (foreground.as_str(), false, "node", "seat", false),
2586 ("owned-run", true, "ask", "operator", false),
2587 ("linked-run", true, "ask", "operator", false),
2588 ("missing-run", true, "node", "seat", false),
2589 ("missing-run", false, "ask", "operator", true),
2590 ] {
2591 let mut q = Question::new(
2592 run.into(),
2593 node.into(),
2594 seat.into(),
2595 "provenance".into(),
2596 String::new(),
2597 Vec::new(),
2598 );
2599 q.cwd = cwd.then(|| dir.path().join("repo").display().to_string());
2600 assert_eq!(standalone_by_scanning(dir.path(), &q), expected);
2601 assert_eq!(
2602 crate::task_chat::standalone_inquiry_in(dir.path(), &q, &ownership),
2603 expected
2604 );
2605 }
2606 }
2607
2608 fn standalone_by_scanning(home: &Path, q: &Question) -> bool {
2610 if q.routed_task.is_some()
2611 || (q.node == crate::bump::NOTICE_NODE && q.seat == "release-watch")
2612 {
2613 return false;
2614 }
2615 if q.legacy_foreground || q.run.is_empty() {
2616 return true;
2617 }
2618 if Queue::at(home.join("queue"))
2619 .list()
2620 .iter()
2621 .any(|task| task.id == q.run || task.runs.contains(&q.run))
2622 {
2623 return false;
2624 }
2625 let run = crate::run::RunState::load_under(&q.run, home).ok();
2626 let origin = run.as_ref().and_then(|run| run.origin.as_ref());
2627 if origin.is_some_and(|origin| origin.task.is_some()) {
2628 return false;
2629 }
2630 (q.node == "ask" && q.seat == "operator")
2631 || (q.cwd.is_some() && origin.is_some_and(|origin| origin.task.is_none()))
2632 }
2633
2634 fn scan_counts() -> (usize, usize, usize) {
2635 (
2636 crate::queue::LIST_READS.with(|c| c.replace(0)),
2637 crate::queue::TASK_READS.with(|c| c.replace(0)),
2638 crate::ask::QUESTION_SCANS.with(|c| c.replace(0)),
2639 )
2640 }
2641
2642 #[test]
2643 fn creating_and_updating_questions_share_one_queue_read() {
2644 let (dir, queue, questions) = store();
2645 let size = 200;
2646 let mut ids = Vec::new();
2647 for i in 0..size {
2648 let mut t = task("scan fixture", dir.path().join("repo"));
2649 t.id = format!("task-{i:04}");
2650 t.runs = vec![format!("run-{i:04}")];
2651 t.hold_manual(Some("held for scan fixture".into()));
2652 queue.put(&mut t).unwrap();
2653 ids.push(t.id);
2654 }
2655 let ownership = crate::task_chat::InquiryOwnership::default();
2656 scan_counts();
2657 let mut created = Vec::new();
2658 for id in &ids {
2659 let mut q = Question::new(
2660 id.clone(),
2661 NODE.into(),
2662 SEAT.into(),
2663 "scan fixture".into(),
2664 String::new(),
2665 EN.choices3(),
2666 );
2667 questions.put_executable_in(&mut q, &ownership).unwrap();
2668 assert_eq!(q.routed_task.as_deref(), Some(id.as_str()));
2669 created.push(q.id);
2670 }
2671 for id in &created {
2672 questions
2673 .update_in(id, &ownership, |q| {
2674 q.answer_delivered = true;
2675 Ok(())
2676 })
2677 .unwrap();
2678 }
2679 let (lists, _, _) = scan_counts();
2680 assert_eq!(lists, 1, "one queue read for {size} creations and updates");
2681 }
2682
2683 #[test]
2684 fn recovery_scans_are_linear_and_match_legacy_decisions() {
2685 let mut previous = None;
2686 for size in [150, 300] {
2687 let (dir, queue, questions) = store();
2688 let at: Timestamp = "2026-11-01T00:00:00Z".parse().unwrap();
2689 let mut sources = Vec::new();
2690 let mut expected_applied = std::collections::BTreeSet::new();
2691 for i in 0..size {
2692 let mut t = task("scan fixture", dir.path().join("repo"));
2693 t.id = format!("task-{i:04}");
2694 t.runs = vec![format!("run-{i:04}")];
2695 t.hold_manual(Some("held for scan fixture".into()));
2696 queue.put(&mut t).unwrap();
2697 let mut q = Question::new(
2698 t.id.clone(),
2699 NODE.into(),
2700 SEAT.into(),
2701 "scan fixture".into(),
2702 String::new(),
2703 EN.choices3(),
2704 );
2705 q.id = format!("question-{i:04}");
2706 q.asked_at = at;
2707 match i % 10 {
2708 0 => {
2709 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
2710 q.accepted_answer_at = q.answered_at;
2711 expected_applied.insert(t.id.clone());
2712 }
2713 1 => q.node = DEPS_NODE.into(),
2714 2 => {
2715 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
2716 }
2717 3 => {
2718 q.run = format!("missing-{i}");
2719 q.legacy_foreground = true;
2720 }
2721 4 => {
2722 q.run.clear();
2723 q.node = crate::bump::NOTICE_NODE.into();
2724 q.seat = "release-watch".into();
2725 }
2726 5 => {
2727 q.run = format!("missing-{i}");
2728 q.node = "ask".into();
2729 q.seat = "operator".into();
2730 }
2731 6 => q.run = t.runs[0].clone(),
2732 7 => q.run = format!("missing-{i}"),
2733 8 => q.abandon("fixture"),
2734 _ => {}
2735 }
2736 questions.put(&mut q).unwrap();
2737 sources.push(q.id.clone());
2738 if i % 10 == 9 {
2739 q.id = format!("question-{i:04}-tie");
2740 questions.put(&mut q).unwrap();
2741 sources.push(q.id.clone());
2742 }
2743 }
2744 let migration = dir.path().join("notifications/task-chat-migration-v1");
2745 std::fs::create_dir_all(&migration).unwrap();
2746 std::fs::write(
2747 migration.join("state.json"),
2748 serde_json::to_vec(&serde_json::json!({
2749 "schema": 1, "classification_revision": 1, "pending": [], "sources": sources
2750 }))
2751 .unwrap(),
2752 )
2753 .unwrap();
2754
2755 scan_counts();
2756 let all = questions.list_for_effects();
2757 let (lists, reads, scans) = scan_counts();
2758 assert_eq!((lists, reads, scans), (1, size, 1));
2759 let tasks = queue.list();
2760 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
2761 for q in &all {
2762 assert_eq!(
2763 crate::task_chat::standalone_inquiry_in(dir.path(), q, &ownership),
2764 standalone_by_scanning(dir.path(), q),
2765 "{}",
2766 q.id,
2767 );
2768 if q.id.ends_with("0002") {
2769 assert!(q.answer.is_none(), "saved consent remains fenced");
2770 }
2771 }
2772 let recovery = RecoveryIndex::from_scan(&queue, &tasks, all.clone());
2773 for task in &tasks {
2774 for node in [NODE, DEPS_NODE] {
2775 let expected = all
2776 .iter()
2777 .filter(|q| {
2778 q.node == node
2779 && q.run == task.id
2780 && !queue.get(&q.run).ok().is_some_and(|t| {
2781 crate::repair_budget::reconcile::superseded_question(&t, q)
2782 })
2783 })
2784 .max_by(|a, b| a.asked_at.cmp(&b.asked_at).then_with(|| a.id.cmp(&b.id)));
2785 assert_eq!(
2786 recovery.latest(node, &task.id).map(|q| q.id),
2787 expected.map(|q| q.id.clone())
2788 );
2789 }
2790 }
2791
2792 scan_counts();
2793 crate::daemon::apply_task_choice_actions(&queue, &questions, dir.path());
2794 assert_eq!(
2795 scan_counts(),
2796 (1, size, 1),
2797 "choice-action rechecks share ownership"
2798 );
2799
2800 scan_counts();
2801 let applied: std::collections::BTreeSet<_> =
2802 apply_answers(&queue, &questions).into_iter().collect();
2803 let counts = scan_counts();
2804 assert_eq!(applied, expected_applied);
2805 assert!(counts.0 <= 3, "queue scans: {counts:?}");
2806 assert!(counts.1 <= 4 * size, "task reads: {counts:?}");
2807 assert_eq!(counts.2, 2, "question scans: {counts:?}");
2808 if let Some((_, reads, scans)) = previous {
2809 assert!(counts.1 <= 2 * reads);
2810 assert_eq!(counts.2, scans);
2811 }
2812 previous = Some(counts);
2813
2814 let config = gate_disabled_config(dir.path());
2815 scan_counts();
2816 run_once(&queue, &questions, Some(&config), Timestamp::now());
2817 let lap = scan_counts();
2818 assert!(lap.0 <= 12, "triage queue scans: {lap:?}");
2819 assert!(lap.1 <= 14 * size, "triage task reads: {lap:?}");
2820 assert!(lap.2 <= 6, "triage question scans: {lap:?}");
2821 }
2822 }
2823
2824 #[test]
2825 fn run_once_filing_many_new_questions_reads_the_queue_a_constant_number_of_times() {
2826 let (dir, queue, questions) = store();
2827 let size = 200;
2828 for i in 0..size {
2829 let mut t = task("scan fixture", dir.path().join("repo"));
2830 t.id = format!("task-{i:04}");
2831 t.hold_machine(Some("gate red".to_owned()));
2832 queue.put(&mut t).unwrap();
2833 }
2834 scan_counts();
2835 let report = run_once(&queue, &questions, None, Timestamp::now());
2836 let (lists, _, _) = scan_counts();
2837 assert_eq!(report.asked.len(), size, "every held task is asked about");
2838 assert!(
2839 lists <= 12,
2840 "queue scans while filing {size} questions: {lists}"
2841 );
2842 }
2843
2844 #[test]
2845 fn base_recovery_stops_suppress_generic_and_dependency_resume_offers() {
2846 let (dir, queue, questions) = store();
2847 let mut root = task("base stop", dir.path().to_path_buf());
2848 let mut run = crate::run::RunState::new(
2849 dir.path().to_path_buf(),
2850 "main".into(),
2851 "base".into(),
2852 "retained implementation".into(),
2853 Config::default(),
2854 );
2855 run.status = crate::run::RunStatus::Voting;
2856 run.base_sync = Some(crate::run::BaseSync {
2857 tip: "tip".into(),
2858 behind: 3,
2859 attempts: 4,
2860 conflict: Some("persisted exhaustion".into()),
2861 already_in: None,
2862 });
2863 run.save_under(dir.path()).unwrap();
2864 root.link_run(&run.id);
2865 root.hold_machine(Some("base stop".into()));
2866 queue.put(&mut root).unwrap();
2867 let mut dependent = task("dependent", dir.path().to_path_buf());
2868 dependent.blocked_by = vec![root.id.clone()];
2869 dependent.status = TaskStatus::Blocked;
2870 queue.put(&mut dependent).unwrap();
2871 for _ in 0..2 {
2872 let report = run_once(&queue, &questions, None, Timestamp::now());
2873 assert!(report.asked.is_empty());
2874 assert!(report.resumed.is_empty());
2875 }
2876 let q = file_question(
2879 &questions,
2880 &crate::task_chat::InquiryOwnership::default(),
2881 &root,
2882 Bucket::MachineUnknown,
2883 &EN,
2884 Timestamp::now(),
2885 )
2886 .unwrap();
2887 let mut q = q;
2888 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
2889 questions.put_executable(&mut q).unwrap();
2890 apply_answers(&queue, &questions);
2891 let saved = queue.get(&root.id).unwrap();
2892 assert_eq!(saved.status, TaskStatus::Held);
2893 assert!(saved.triage_applied(&q.id));
2894 assert_eq!(saved.runs, vec![run.id]);
2895 }
2896
2897 #[test]
2898 fn resource_holds_only_auto_release_a_proven_cache_wait_timeout() {
2899 use crate::run::{ResourceBlock, ResourceBlockCause, RunState};
2900 let dir = tempfile::tempdir().unwrap();
2901 let cfg = Config::default(); assert!(cfg.cache_dir().is_none());
2903 let mut state = RunState::new(
2904 dir.path().into(),
2905 "main".into(),
2906 "base".into(),
2907 "verify".into(),
2908 cfg.clone(),
2909 );
2910 let mut task = task("verify", dir.path().into());
2911 task.runs = vec![state.id.clone()];
2912 task.hold_machine(Some("[resource] cache operation stopped".into()));
2913 for cause in [
2914 ResourceBlockCause::Other,
2915 ResourceBlockCause::Unrecorded,
2916 ResourceBlockCause::Cancelled { park: None },
2917 ] {
2918 state.resource_block = Some(ResourceBlock {
2919 node: "gate".into(),
2920 kind: "shared build cache".into(),
2921 detail: "persistent metadata or manifest error".into(),
2922 cause,
2923 at: Timestamp::now(),
2924 });
2925 state.save_under(dir.path()).unwrap();
2926 for _ in 0..3 {
2928 assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
2929 }
2930 }
2931 let block = state.resource_block.as_mut().unwrap();
2932 block.cause = ResourceBlockCause::Timeout {
2933 waited_secs: 10,
2934 limit_secs: 10,
2935 };
2936 state.save_under(dir.path()).unwrap();
2937 assert_eq!(
2938 machine_cause_resolved_under(&task, &cfg, dir.path()),
2939 Some(true)
2940 );
2941 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
2942 state.save_under(dir.path()).unwrap();
2943 assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
2944 task.runs = vec!["unreadable-run".into()];
2945 assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
2946 }
2947
2948 #[cfg(unix)]
2949 #[test]
2950 fn disk_admission_holds_recheck_live_reservations_and_the_floor() {
2951 use crate::retention::OutputLease;
2952 use crate::run::{ResourceBlock, ResourceBlockCause, RunState};
2953 let temp = tempfile::tempdir().unwrap();
2954 let home = temp.path().canonicalize().unwrap();
2955 let mut cfg = Config::default();
2956 cfg.graph.worktree_root = Some(home.join("worktrees"));
2957 cfg.disk.min_free_bytes = 100;
2958 let cache = home.join("cache");
2959 cfg.verify.gate = vec![format!(
2960 "CARGO_TARGET_DIR='{}' cargo build",
2961 cache.display()
2962 )];
2963 let mut state = RunState::new(
2964 home.clone(),
2965 "main".into(),
2966 "base".into(),
2967 "verify".into(),
2968 cfg.clone(),
2969 );
2970 let saved_cache = home.join("saved-cache");
2971 state.config.verify.gate = vec![format!(
2972 "CARGO_TARGET_DIR='{}' cargo build",
2973 saved_cache.display()
2974 )];
2975 state.resource_block = Some(ResourceBlock {
2976 node: "gate".into(),
2977 kind: "disk admission".into(),
2978 detail: "writer headroom unavailable".into(),
2979 cause: ResourceBlockCause::Other,
2980 at: Timestamp::now(),
2981 });
2982 state.save_under(&home).unwrap();
2983 let mut task = task("verify", home.clone());
2984 task.runs = vec![state.id.clone()];
2985 task.hold_machine(Some(format!(
2986 "{}{}; no attempt was spent; resume to retry the affected operation",
2987 crate::cache::RESOURCE_HOLD,
2988 state.resource_block.as_ref().unwrap().description()
2989 )));
2990 task.schema = 21; let gib = 1024 * 1024 * 1024;
2992 let free = std::cell::Cell::new(100 + gib - 1);
2993 let check = || {
2994 machine_cause_resolved_with_admission(&task, &cfg, &home, |paths, floor| {
2995 assert!(
2996 paths.contains(&cache),
2997 "the cache volume must also be checked"
2998 );
2999 assert!(
3000 paths.contains(&saved_cache),
3001 "saved and current cache locations both matter"
3002 );
3003 assert!(paths.contains(&state.worktree_root()));
3004 OutputLease::admit_with(&home, paths, floor, |_| Ok(free.get())).is_ok()
3005 })
3006 };
3007 assert_eq!(check(), Some(false), "the unchanged floor still applies");
3008 assert_eq!(
3009 machine_cause_resolved_with_admission(&task, &cfg, &home, |paths, floor| {
3010 OutputLease::admit_with(&home, paths, floor, |_| {
3011 Err(anyhow::anyhow!("measurement unavailable"))
3012 })
3013 .is_ok()
3014 }),
3015 Some(false),
3016 "failed output-volume measurements must remain closed"
3017 );
3018 free.set(100 + gib);
3019 let writer = OutputLease::admit_with(
3020 &home,
3021 std::slice::from_ref(&home),
3022 cfg.disk.min_free_bytes,
3023 |_| Ok(free.get()),
3024 )
3025 .unwrap();
3026 assert_eq!(
3027 check(),
3028 Some(false),
3029 "df alone cannot resolve a live reservation"
3030 );
3031 drop(writer);
3032 assert_eq!(
3033 check(),
3034 Some(true),
3035 "releasing headroom resolves the machine hold"
3036 );
3037 assert_eq!(
3038 check(),
3039 Some(true),
3040 "the probe must release its temporary reservation"
3041 );
3042
3043 let namespace = home.join("disk-admission");
3045 let saved = home.join("saved-admission");
3046 std::fs::rename(&namespace, &saved).unwrap();
3047 std::os::unix::fs::symlink(&saved, &namespace).unwrap();
3048 assert_eq!(check(), Some(false));
3049 std::fs::remove_file(&namespace).unwrap();
3050 std::fs::rename(saved, namespace).unwrap();
3051 assert_eq!(check(), Some(true));
3052
3053 state.resource_block.as_mut().unwrap().cause = ResourceBlockCause::Cancelled { park: None };
3054 state.save_under(&home).unwrap();
3055 assert_eq!(
3056 machine_cause_resolved_with_admission(&task, &cfg, &home, |_, _| panic!(
3057 "a cancelled operation must remain held"
3058 )),
3059 None
3060 );
3061 state.resource_block.as_mut().unwrap().kind = "incremental cache admission".into();
3062 state.resource_block.as_mut().unwrap().cause = ResourceBlockCause::Other;
3063 state.save_under(&home).unwrap();
3064 assert_eq!(
3065 machine_cause_resolved_with_admission(&task, &cfg, &home, |_, _| panic!(
3066 "unproven incremental caches must remain held"
3067 )),
3068 None
3069 );
3070 task.runs.push("unreadable-run".into());
3071 assert_eq!(
3072 machine_cause_resolved_with_admission(&task, &cfg, &home, |_, _| panic!(
3073 "missing evidence must not release a hold"
3074 )),
3075 None
3076 );
3077 }
3078
3079 fn gate_disabled_config(dir: &std::path::Path) -> PathBuf {
3083 let config = dir.join("magi.toml");
3084 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
3085 config
3086 }
3087
3088 #[test]
3089 fn resumption_later_keep_held_answer_wins_but_an_older_answer_cannot_undo_release() {
3090 for source in ["cli", "web"] {
3091 for answer_after_release in [true, false] {
3092 let (dir, queue, questions) = store();
3093 let mut t = task("recovery", dir.path().join("repo"));
3094 t.hold_machine(Some("inspect remote first".into()));
3095 queue.put(&mut t).unwrap();
3096 let mut q = file_question(
3097 &questions,
3098 &crate::task_chat::InquiryOwnership::default(),
3099 &t,
3100 Bucket::MachineUnknown,
3101 &JA,
3102 Timestamp::now(),
3103 )
3104 .unwrap();
3105 if !answer_after_release {
3106 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
3107 questions.put(&mut q).unwrap();
3108 }
3109 t.release_operator(source, None);
3110 queue.put(&mut t).unwrap();
3111 if answer_after_release {
3112 q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
3113 questions.put(&mut q).unwrap();
3114 }
3115 apply_answers(&queue, &questions);
3116 let after = queue.get(&t.id).unwrap();
3117 assert!(after.triage_applied(&q.id));
3118 assert_eq!(after.operator_held(), answer_after_release);
3119 assert_eq!(
3120 after.status,
3121 if answer_after_release {
3122 TaskStatus::Held
3123 } else {
3124 TaskStatus::Queued
3125 }
3126 );
3127 assert!(apply_answers(&queue, &questions).is_empty());
3128 }
3129 }
3130 }
3131
3132 #[test]
3133 fn explicit_resumption_applies_legacy_queued_triage_once_and_preserves_later_holds() {
3134 let (dir, queue, questions) = store();
3135 let mut t = task("recover", dir.path().join("repo"));
3136 t.hold_machine(Some("inspect first".into()));
3137 queue.put(&mut t).unwrap();
3138 let mut q = file_question(
3139 &questions,
3140 &crate::task_chat::InquiryOwnership::default(),
3141 &t,
3142 Bucket::MachineUnknown,
3143 &JA,
3144 Timestamp::now(),
3145 )
3146 .unwrap();
3147 assert!(q.actions.is_empty());
3148 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
3149 questions.put(&mut q).unwrap();
3150 t.release();
3152 t.instruction = "Reuse approved PR head".into();
3153 queue.put(&mut t).unwrap();
3154 assert_eq!(apply_answers(&queue, &questions), [t.id.clone()]);
3155 let mut after = queue.get(&t.id).unwrap();
3156 assert_eq!(
3157 after.resumption.as_ref().unwrap().question_id.as_deref(),
3158 Some(q.id.as_str())
3159 );
3160 assert_eq!(
3161 after.resumption.as_ref().unwrap().instruction,
3162 t.instruction
3163 );
3164 assert_eq!(after.answers[0].answer, JA.resume);
3165 assert!(after.triage_applied(&q.id));
3166 assert!(apply_answers(&Queue::at(dir.path().join("queue")), &questions).is_empty());
3167 after.hold_machine(Some("new blocker".into()));
3168 queue.put(&mut after).unwrap();
3169 let mut late = file_question(
3170 &questions,
3171 &crate::task_chat::InquiryOwnership::default(),
3172 &after,
3173 Bucket::MachineUnknown,
3174 &EN,
3175 Timestamp::now(),
3176 )
3177 .unwrap();
3178 after.hold_manual(Some("keep held now".into()));
3179 queue.put(&mut after).unwrap();
3180 late.answer(Answer::Choice(late.choices[0].clone()))
3181 .unwrap();
3182 questions.put(&mut late).unwrap();
3183 apply_answers(&queue, &questions);
3184 let held = queue.get(&t.id).unwrap();
3185 assert!(held.operator_held());
3186 assert_eq!(held.hold_reason.as_deref(), Some("keep held now"));
3187 assert_eq!(held.resumption.as_ref().unwrap().generation, 1);
3188 }
3189
3190 #[test]
3191 fn a_resolved_machine_hold_is_requeued_automatically() {
3192 let (dir, q, questions) = store();
3193 let config = gate_disabled_config(dir.path());
3194 let mut t = task("disk pressure", dir.path().join("repo"));
3195 t.hold_machine(Some(
3196 "not enough free space to start a run: 10 bytes free, 100 required by \
3197 `[disk] min_free_bytes`"
3198 .to_owned(),
3199 ));
3200 t.schema = 21; q.put(&mut t).unwrap();
3202
3203 let report = run_once(&q, &questions, Some(&config), Timestamp::now());
3204 assert_eq!(report.resumed, [t.id.clone()]);
3205 assert!(report.asked.is_empty());
3206
3207 let back = q.get(&t.id).unwrap();
3208 assert_eq!(back.status, TaskStatus::Queued);
3209 assert!(back.hold_source.is_none());
3210 assert!(questions.list().is_empty(), "nothing needed asking");
3211 }
3212
3213 #[test]
3214 fn a_machine_hold_with_no_recognised_cause_gets_one_question_not_two() {
3215 let (dir, q, questions) = store();
3216 let mut t = task("gate went red", dir.path().join("repo"));
3217 t.hold_machine(Some("gate red".to_owned()));
3218 q.put(&mut t).unwrap();
3219
3220 let first = run_once(&q, &questions, None, Timestamp::now());
3221 assert_eq!(first.asked, [t.id.clone()]);
3222 assert!(first.resumed.is_empty());
3223
3224 let open: Vec<_> = questions
3225 .list()
3226 .into_iter()
3227 .filter(|q| q.status.open())
3228 .collect();
3229 assert_eq!(open.len(), 1);
3230 assert_eq!(open[0].run, t.id);
3231 assert_eq!(open[0].node, NODE);
3232 assert_eq!(open[0].choices.len(), 3);
3233
3234 let second = run_once(&q, &questions, None, Timestamp::now());
3236 assert!(second.asked.is_empty());
3237 assert_eq!(
3238 questions
3239 .list()
3240 .into_iter()
3241 .filter(|q| q.status.open())
3242 .count(),
3243 1
3244 );
3245 }
3246
3247 #[test]
3248 fn a_legacy_hold_with_no_recorded_source_gets_exactly_one_question() {
3249 let (dir, q, questions) = store();
3250 let mut t = task("schema 1 record", dir.path().join("repo"));
3251 t.status = TaskStatus::Held;
3252 assert!(t.hold_source.is_none(), "the case this test is about");
3253 q.put(&mut t).unwrap();
3254
3255 let first = run_once(&q, &questions, None, Timestamp::now());
3256 assert_eq!(first.asked, [t.id.clone()]);
3257
3258 let second = run_once(&q, &questions, None, Timestamp::now());
3259 assert!(
3260 second.asked.is_empty(),
3261 "the same legacy hold must not be asked about twice"
3262 );
3263 assert_eq!(
3264 questions
3265 .list()
3266 .into_iter()
3267 .filter(|q| q.status.open())
3268 .count(),
3269 1
3270 );
3271 }
3272
3273 #[test]
3274 fn dependency_resolution_detaches_legacy_short_refs_without_dropping_other_waits() {
3275 let (dir, queue, questions) = store();
3276 let mut root = task("root", dir.path().join("repo"));
3277 root.id = "20261013-193611-ca5b".into();
3278 root.hold_machine(Some("needs owner decision".into()));
3279 queue.put(&mut root).unwrap();
3280 let mut other = task("other", dir.path().join("repo"));
3281 other.id = "20261013-192213-feb2".into();
3282 queue.put(&mut other).unwrap();
3283 let mut waiting = task("waiting", dir.path().join("repo"));
3284 waiting.block(vec!["ca5b".into(), other.id.clone()], None);
3285 queue.put(&mut waiting).unwrap();
3286 detach_dependants(&queue, &questions, &root.id);
3287 let after = queue.get(&waiting.id).unwrap();
3288 assert_eq!(after.status, TaskStatus::Blocked);
3289 assert_eq!(after.blocked_by, [other.id]);
3290 }
3291
3292 #[test]
3293 fn a_manual_hold_is_never_auto_resumed() {
3294 let (dir, q, questions) = store();
3295 let mut t = task("operator stopped this", dir.path().join("repo"));
3296 t.hold_manual(Some("waiting on a decision".to_owned()));
3297 q.put(&mut t).unwrap();
3298
3299 let report = run_once(&q, &questions, None, Timestamp::now());
3300 assert!(report.resumed.is_empty());
3301 assert!(report.asked.is_empty());
3303
3304 let back = q.get(&t.id).unwrap();
3305 assert_eq!(back.status, TaskStatus::Held);
3306 assert_eq!(back.hold_source, Some(HoldSource::Manual));
3307 assert!(questions.list().is_empty());
3308 }
3309
3310 #[test]
3311 fn a_blocked_task_on_a_deleted_dependency_is_held_and_asked_about_in_one_pass() {
3312 let (dir, q, questions) = store();
3317 let mut still_going = task("still valid", dir.path().join("repo"));
3318 q.put(&mut still_going).unwrap();
3319
3320 let mut t = task("orphaned", dir.path().join("repo"));
3321 t.block(
3322 vec!["20260101-000000-gone".to_owned(), still_going.id.clone()],
3323 Some("waits on both".to_owned()),
3324 );
3325 q.put(&mut t).unwrap();
3326
3327 let report = run_once(&q, &questions, None, Timestamp::now());
3328 assert_eq!(report.quarantined, [t.id.clone()]);
3329 assert_eq!(
3330 report.asked,
3331 [t.id.clone()],
3332 "the fresh machine hold must earn a question in the same pass"
3333 );
3334
3335 let after = q.get(&t.id).unwrap();
3336 assert_eq!(after.status, TaskStatus::Held);
3337 assert_eq!(after.hold_source, Some(HoldSource::Machine));
3338 assert!(after.blocked_by.is_empty());
3339
3340 assert!(!is_disk_hold(&after));
3343
3344 let open: Vec<_> = questions
3345 .list()
3346 .into_iter()
3347 .filter(|q| q.status.open())
3348 .collect();
3349 assert_eq!(open.len(), 1);
3350 assert_eq!(open[0].run, t.id);
3351
3352 let second = run_once(&q, &questions, None, Timestamp::now());
3354 assert!(second.quarantined.is_empty());
3355 assert!(second.asked.is_empty());
3356 }
3357
3358 fn stuck_chain(q: &Queue, dir: &std::path::Path) -> (Task, Task, Task) {
3361 let mut root = task("root", dir.join("repo"));
3362 root.hold_manual(Some("waiting".to_owned()));
3363 q.put(&mut root).unwrap();
3364 let mut mid = task("mid", dir.join("repo"));
3365 mid.block(vec![root.id.clone()], None);
3366 q.put(&mut mid).unwrap();
3367 let mut leaf = task("leaf", dir.join("repo"));
3368 leaf.block(vec![mid.id.clone()], None);
3369 q.put(&mut leaf).unwrap();
3370 (root, mid, leaf)
3371 }
3372
3373 fn deps_questions(questions: &Questions) -> Vec<Question> {
3374 questions
3375 .list()
3376 .into_iter()
3377 .filter(|q| q.node == DEPS_NODE)
3378 .collect()
3379 }
3380
3381 fn answer_deps(questions: &Questions, choice: usize) {
3382 let mut asked = deps_questions(questions).remove(0);
3383 let c = asked.choices[choice].clone();
3384 asked.answer(Answer::Choice(c)).unwrap();
3385 questions.put(&mut asked).unwrap();
3386 }
3387
3388 #[test]
3389 fn a_stuck_chain_earns_one_question_naming_every_dependant_and_is_not_reasked() {
3390 let (dir, q, questions) = store();
3391 let (root, mid, leaf) = stuck_chain(&q, dir.path());
3392
3393 let first = run_once(&q, &questions, None, Timestamp::now());
3394 assert_eq!(first.asked, std::slice::from_ref(&root.id));
3395 let asked = deps_questions(&questions);
3396 assert_eq!(asked.len(), 1, "one question per root, not per dependant");
3397 assert_eq!(asked[0].run, root.id);
3398 assert_eq!(asked[0].choices.len(), 3);
3399 assert!(asked[0].detail.contains(mid.short()), "{}", asked[0].detail);
3400 assert!(
3401 asked[0].detail.contains(leaf.short()),
3402 "{}",
3403 asked[0].detail
3404 );
3405
3406 let second = run_once(&q, &questions, None, Timestamp::now());
3407 assert!(second.asked.is_empty());
3408 assert_eq!(deps_questions(&questions).len(), 1);
3409 assert!(pending_for(&questions, &q.get(&root.id).unwrap()));
3410 }
3411
3412 #[test]
3413 fn a_stuck_root_with_a_machine_hold_gets_only_the_dependency_question() {
3414 let (dir, q, questions) = store();
3415 let mut root = task("root", dir.path().join("repo"));
3416 root.hold_machine(Some("gate red".to_owned()));
3417 q.put(&mut root).unwrap();
3418 let mut dep = task("dep", dir.path().join("repo"));
3419 dep.block(vec![root.id.clone()], None);
3420 q.put(&mut dep).unwrap();
3421
3422 run_once(&q, &questions, None, Timestamp::now());
3423 run_once(&q, &questions, None, Timestamp::now());
3424 assert_eq!(deps_questions(&questions).len(), 1);
3425 assert_eq!(
3426 questions.list().len(),
3427 1,
3428 "no second question about the hold"
3429 );
3430 }
3431
3432 #[test]
3433 fn a_dependency_that_can_still_run_asks_nothing() {
3434 let (dir, q, questions) = store();
3435 let mut live = task("live", dir.path().join("repo"));
3436 q.put(&mut live).unwrap();
3437 let mut dep = task("dep", dir.path().join("repo"));
3438 dep.block(vec![live.id.clone()], None);
3439 q.put(&mut dep).unwrap();
3440 let report = run_once(&q, &questions, None, Timestamp::now());
3441 assert!(report.asked.is_empty());
3442 assert!(questions.list().is_empty());
3443 }
3444
3445 #[test]
3446 fn answering_release_requeues_the_root_and_is_not_reasked() {
3447 let (dir, q, questions) = store();
3448 let (root, _mid, _leaf) = stuck_chain(&q, dir.path());
3449 run_once(&q, &questions, None, Timestamp::now());
3450 answer_deps(&questions, 0);
3451
3452 let report = run_once(&q, &questions, None, Timestamp::now());
3453 assert_eq!(report.answered, std::slice::from_ref(&root.id));
3454 assert!(report.asked.is_empty(), "applying must not re-ask");
3455 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Queued);
3456 let again = run_once(&q, &questions, None, Timestamp::now());
3457 assert!(again.asked.is_empty() && again.answered.is_empty());
3458 assert_eq!(deps_questions(&questions).len(), 1);
3459 }
3460
3461 #[test]
3462 fn answering_detach_frees_the_direct_dependant_and_keeps_the_root() {
3463 let (dir, q, questions) = store();
3464 let (root, mid, leaf) = stuck_chain(&q, dir.path());
3465 run_once(&q, &questions, None, Timestamp::now());
3466 answer_deps(&questions, 2);
3467
3468 let report = run_once(&q, &questions, None, Timestamp::now());
3469 assert!(report.asked.is_empty());
3470 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
3471 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
3472 let leaf = q.get(&leaf.id).unwrap();
3473 assert_eq!(leaf.status, TaskStatus::Blocked, "still waits on mid");
3474 assert_eq!(leaf.blocked_by, std::slice::from_ref(&mid.id));
3475 }
3476
3477 #[test]
3478 fn a_dependant_that_can_progress_through_another_blocker_is_not_stuck() {
3479 let (dir, q, questions) = store();
3480 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
3481 let mut live = task("live", dir.path().join("repo"));
3482 q.put(&mut live).unwrap();
3483 let mut both = q.get(&mid.id).unwrap();
3484 both.block(vec![root.id.clone(), live.id.clone()], None);
3485 q.put(&mut both).unwrap();
3486 assert!(
3488 run_once(&q, &questions, None, Timestamp::now())
3489 .asked
3490 .is_empty()
3491 );
3492 }
3493
3494 #[test]
3495 fn answering_discard_detaches_then_removes_the_root() {
3496 let (dir, q, questions) = store();
3497 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
3498 run_once(&q, &questions, None, Timestamp::now());
3499 answer_deps(&questions, 1);
3500
3501 let report = run_once(&q, &questions, None, Timestamp::now());
3502 assert!(q.get(&root.id).is_err());
3503 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
3504 assert!(
3505 report.asked.is_empty(),
3506 "no per-dependant quarantine question"
3507 );
3508 assert!(report.quarantined.is_empty());
3509 }
3510
3511 #[test]
3512 fn an_unmatched_deps_answer_changes_nothing_and_is_not_reasked() {
3513 let (dir, q, questions) = store();
3514 let (root, mid, _leaf) = stuck_chain(&q, dir.path());
3515 run_once(&q, &questions, None, Timestamp::now());
3516 let mut asked = deps_questions(&questions).remove(0);
3517 asked.choices.clear();
3518 asked.answer(Answer::Text("dunno".to_owned())).unwrap();
3519 questions.put(&mut asked).unwrap();
3520
3521 for _ in 0..2 {
3522 let report = run_once(&q, &questions, None, Timestamp::now());
3523 assert!(report.asked.is_empty() && report.answered.is_empty());
3524 }
3525 assert_eq!(deps_questions(&questions).len(), 1);
3526 assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
3527 assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Blocked);
3528 }
3529
3530 #[test]
3531 fn a_dependency_cycle_terminates_and_is_asked_about_once() {
3532 let (dir, q, questions) = store();
3533 let mut a = task("a", dir.path().join("repo"));
3534 let mut b = task("b", dir.path().join("repo"));
3535 a.block(vec![b.id.clone()], None);
3536 b.block(vec![a.id.clone()], None);
3537 q.put(&mut a).unwrap();
3538 q.put(&mut b).unwrap();
3539
3540 let first = run_once(&q, &questions, None, Timestamp::now());
3541 assert_eq!(first.asked.len(), 1);
3542 let second = run_once(&q, &questions, None, Timestamp::now());
3543 assert!(second.asked.is_empty());
3544 assert_eq!(deps_questions(&questions).len(), 1);
3545 }
3546
3547 #[test]
3548 fn a_missing_dependency_is_still_quarantined_not_asked_about_as_stuck() {
3549 let (dir, q, questions) = store();
3550 let mut t = task("orphan", dir.path().join("repo"));
3551 t.block(vec!["20260101-000000-gone".to_owned()], None);
3552 q.put(&mut t).unwrap();
3553 let report = run_once(&q, &questions, None, Timestamp::now());
3554 assert_eq!(report.quarantined, [t.id.clone()]);
3555 assert!(deps_questions(&questions).is_empty());
3556 }
3557
3558 #[test]
3559 fn a_stale_manual_hold_can_be_discarded() {
3560 let (dir, q, questions) = store();
3561 let mut t = task("been sitting a while", dir.path().join("repo"));
3562 t.hold_manual(Some("waiting on a decision".to_owned()));
3563 q.put(&mut t).unwrap();
3564 let mut back = q.get(&t.id).unwrap();
3566 back.updated_at = Timestamp::now() - SignedDuration::new(8 * 24 * 60 * 60, 0);
3567 std::fs::write(
3568 q.path_of(&back.id),
3569 serde_json::to_string_pretty(&back).unwrap(),
3570 )
3571 .unwrap();
3572
3573 let report = run_once(&q, &questions, None, Timestamp::now());
3574 assert_eq!(report.asked, [t.id.clone()]);
3575 let open: Vec<_> = questions
3576 .list()
3577 .into_iter()
3578 .filter(|q| q.status.open())
3579 .collect();
3580 assert_eq!(open.len(), 1);
3581 let mut asked = open[0].clone();
3582 assert_eq!(asked.choices, ["resume it", "keep it held", "discard it"]);
3583 assert_eq!(
3584 JA.choices_manual(),
3585 ["再開する", "まだ止めておく", "捨ててよい"]
3586 );
3587 asked
3588 .answer(Answer::Choice(asked.choices[2].clone()))
3589 .unwrap();
3590 questions.put(&mut asked).unwrap();
3591 run_once(&q, &questions, None, Timestamp::now());
3592 assert!(q.get(&t.id).is_err());
3593 }
3594
3595 #[test]
3596 fn answering_resume_releases_the_task() {
3597 let (dir, q, questions) = store();
3598 let mut t = task("gate went red", dir.path().join("repo"));
3599 t.hold_machine(Some("gate red".to_owned()));
3600 q.put(&mut t).unwrap();
3601 run_once(&q, &questions, None, Timestamp::now());
3602
3603 let mut asked = questions
3604 .list()
3605 .into_iter()
3606 .find(|q| q.run == t.id)
3607 .unwrap();
3608 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
3609 questions.put(&mut asked).unwrap();
3610
3611 let report = run_once(&q, &questions, None, Timestamp::now());
3612 assert_eq!(report.answered, [t.id.clone()]);
3613 let back = q.get(&t.id).unwrap();
3614 assert_eq!(back.status, TaskStatus::Queued);
3615 assert!(back.hold_source.is_none());
3616 }
3617
3618 fn resumed_then_failed(q: &Queue, questions: &Questions, dir: &std::path::Path) -> Task {
3620 let mut t = task("gate went red", dir.join("repo"));
3621 t.hold_machine(Some("gate red".to_owned()));
3622 q.put(&mut t).unwrap();
3623 run_once(q, questions, None, Timestamp::now());
3624 let mut asked = questions
3625 .list()
3626 .into_iter()
3627 .find(|q| q.run == t.id)
3628 .unwrap();
3629 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
3630 questions.put(&mut asked).unwrap();
3631
3632 let report = run_once(q, questions, None, Timestamp::now());
3633 assert_eq!(report.answered, [t.id.clone()]);
3634 let mut back = q.get(&t.id).unwrap();
3635 assert_eq!(back.status, TaskStatus::Queued);
3636 assert_eq!(back.attempts, 0);
3637
3638 back.start("run-1".to_owned());
3639 back.fail("rebase conflict", 1);
3640 assert_eq!(back.status, TaskStatus::Held);
3641 q.put(&mut back).unwrap();
3642 back
3643 }
3644
3645 #[test]
3646 fn a_resume_answer_is_applied_once_and_a_new_machine_hold_is_asked_about() {
3647 let (dir, q, questions) = store();
3648 let t = resumed_then_failed(&q, &questions, dir.path());
3649
3650 let report = run_once(&q, &questions, None, Timestamp::now());
3651 assert!(report.answered.is_empty(), "the old answer must not replay");
3652 assert_eq!(report.asked, std::slice::from_ref(&t.id));
3653 let back = q.get(&t.id).unwrap();
3654 assert_eq!(back.status, TaskStatus::Held);
3655 assert_eq!(
3656 questions
3657 .list()
3658 .into_iter()
3659 .filter(|q| q.status.open())
3660 .count(),
3661 1
3662 );
3663 }
3664
3665 #[test]
3666 fn a_manual_hold_placed_after_a_resume_is_not_undone_by_the_old_answer() {
3667 let (dir, q, questions) = store();
3668 let mut t = resumed_then_failed(&q, &questions, dir.path());
3669 t.hold_manual(Some("operator stopped this".to_owned()));
3670 q.put(&mut t).unwrap();
3671 let before = questions.list().len();
3672
3673 let report = run_once(&q, &questions, None, Timestamp::now());
3674 assert!(report.answered.is_empty());
3675 assert!(report.asked.is_empty());
3676 let back = q.get(&t.id).unwrap();
3677 assert_eq!(back.status, TaskStatus::Held);
3678 assert_eq!(back.hold_source, Some(HoldSource::Manual));
3679 assert_eq!(questions.list().len(), before);
3680 }
3681
3682 #[test]
3683 fn answering_not_yet_keeps_it_held_as_a_manual_hold_and_does_not_reapply() {
3684 let (dir, q, questions) = store();
3685 let mut t = task("gate went red", dir.path().join("repo"));
3686 t.hold_machine(Some("gate red".to_owned()));
3687 q.put(&mut t).unwrap();
3688 run_once(&q, &questions, None, Timestamp::now());
3689
3690 let mut asked = questions
3691 .list()
3692 .into_iter()
3693 .find(|q| q.run == t.id)
3694 .unwrap();
3695 asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
3696 questions.put(&mut asked).unwrap();
3697
3698 let report = run_once(&q, &questions, None, Timestamp::now());
3699 assert_eq!(report.answered, [t.id.clone()]);
3700 let back = q.get(&t.id).unwrap();
3701 assert_eq!(back.status, TaskStatus::Held);
3702 assert_eq!(back.hold_source, Some(HoldSource::Manual));
3703 assert!(
3704 back.hold_reason
3705 .as_deref()
3706 .is_some_and(|r| r.contains("gate red")),
3707 "the original cause must survive a \"not yet\" answer, not just the \
3708 triage marker: {:?}",
3709 back.hold_reason
3710 );
3711
3712 let third = run_once(&q, &questions, None, Timestamp::now());
3716 assert!(third.answered.is_empty());
3717 assert!(third.asked.is_empty());
3718 }
3719
3720 #[test]
3721 fn answering_discard_removes_the_task_entirely() {
3722 let (dir, q, questions) = store();
3723 let mut t = task("gate went red", dir.path().join("repo"));
3724 t.hold_machine(Some("gate red".to_owned()));
3725 q.put(&mut t).unwrap();
3726 run_once(&q, &questions, None, Timestamp::now());
3727
3728 let mut asked = questions
3729 .list()
3730 .into_iter()
3731 .find(|q| q.run == t.id)
3732 .unwrap();
3733 asked.answer(Answer::Choice(EN.discard.to_owned())).unwrap();
3734 questions.put(&mut asked).unwrap();
3735
3736 let report = run_once(&q, &questions, None, Timestamp::now());
3737 assert_eq!(report.answered, [t.id.clone()]);
3738 assert!(
3739 q.get(&t.id).is_err(),
3740 "\"discard it\" (捨ててよい) must actually discard the task, not \
3741 just leave it sitting held forever"
3742 );
3743 }
3744
3745 #[test]
3746 fn an_answer_is_read_by_its_position_in_choices_not_by_the_callers_current_language() {
3747 let (dir, q, questions) = store();
3749 let ja_config = dir.path().join("ja.toml");
3750 std::fs::write(&ja_config, "[graph]\nlanguage = \"ja\"\n").unwrap();
3751 let mut t = task("gate went red", dir.path().join("repo"));
3752 t.hold_machine(Some("gate red".to_owned()));
3753 q.put(&mut t).unwrap();
3754 run_once(&q, &questions, Some(&ja_config), Timestamp::now());
3755
3756 let mut asked = questions
3757 .list()
3758 .into_iter()
3759 .find(|q| q.run == t.id)
3760 .unwrap();
3761 assert_eq!(asked.choices[0], JA.resume, "filed in Japanese");
3762 asked.answer(Answer::Choice(JA.resume.to_owned())).unwrap();
3763 questions.put(&mut asked).unwrap();
3764
3765 let en_config = dir.path().join("en.toml");
3770 std::fs::write(&en_config, "[graph]\nlanguage = \"en\"\n").unwrap();
3771 let report = run_once(&q, &questions, Some(&en_config), Timestamp::now());
3772 assert_eq!(report.answered, [t.id.clone()]);
3773 let back = q.get(&t.id).unwrap();
3774 assert_eq!(
3775 back.status,
3776 TaskStatus::Queued,
3777 "a resume answer must resume the task regardless of which \
3778 language it is read back in"
3779 );
3780 }
3781
3782 #[test]
3783 fn a_question_falls_back_to_last_error_when_hold_reason_was_never_set() {
3784 let (dir, q, questions) = store();
3789 let mut t = task("kept failing the gate", dir.path().join("repo"));
3790 t.start("run-1".to_owned());
3791 t.fail("gate red three times running", 1);
3792 assert_eq!(t.status, TaskStatus::Held);
3793 t.hold_reason = None; q.put(&mut t).unwrap();
3795
3796 run_once(&q, &questions, None, Timestamp::now());
3797 let asked = questions
3798 .list()
3799 .into_iter()
3800 .find(|q| q.run == t.id)
3801 .unwrap();
3802 assert!(
3803 asked.detail.contains("gate red three times running"),
3804 "the question must surface `last_error` when there is no \
3805 `hold_reason` to show instead: {}",
3806 asked.detail
3807 );
3808 }
3809
3810 #[test]
3811 fn open_question_for_and_open_task_ids_reflect_only_what_is_still_waiting() {
3812 let (dir, q, questions) = store();
3813 let mut t = task("gate went red", dir.path().join("repo"));
3814 t.hold_machine(Some("gate red".to_owned()));
3815 q.put(&mut t).unwrap();
3816
3817 assert!(open_question_for(&questions, &t.id).is_none());
3818 assert!(!open_task_ids(&questions).contains(&t.id));
3819
3820 run_once(&q, &questions, None, Timestamp::now());
3821 assert!(open_question_for(&questions, &t.id).is_some());
3822 assert!(open_task_ids(&questions).contains(&t.id));
3823
3824 let mut asked = questions
3825 .list()
3826 .into_iter()
3827 .find(|q| q.run == t.id)
3828 .unwrap();
3829 asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
3830 questions.put(&mut asked).unwrap();
3831
3832 assert!(
3833 open_question_for(&questions, &t.id).is_none(),
3834 "an answered question is no longer open"
3835 );
3836 assert!(!open_task_ids(&questions).contains(&t.id));
3837 }
3838
3839 #[test]
3840 fn pending_for_stays_true_between_an_answer_and_the_next_run_once_pass() {
3841 let (dir, q, questions) = store();
3847 let mut t = task("gate went red", dir.path().join("repo"));
3848 t.hold_machine(Some("gate red".to_owned()));
3849 q.put(&mut t).unwrap();
3850
3851 assert!(!pending_for(&questions, &t));
3852
3853 run_once(&q, &questions, None, Timestamp::now());
3854 let held = q.get(&t.id).unwrap();
3855 assert!(pending_for(&questions, &held), "still waiting on an answer");
3856
3857 let mut asked = questions
3858 .list()
3859 .into_iter()
3860 .find(|q| q.run == t.id)
3861 .unwrap();
3862 asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
3863 questions.put(&mut asked).unwrap();
3864 assert!(!asked.status.open());
3865
3866 let still_held = q.get(&t.id).unwrap();
3868 assert!(
3869 pending_for(&questions, &still_held),
3870 "answered but not yet applied is still pending"
3871 );
3872
3873 run_once(&q, &questions, None, Timestamp::now());
3874 let after = q.get(&t.id).unwrap();
3875 assert!(
3876 !pending_for(&questions, &after),
3877 "the answer is applied now, nothing left pending"
3878 );
3879 }
3880
3881 #[test]
3882 fn migrated_keep_held_is_consumed_but_can_be_reviewed_and_discarded_again() {
3883 let (dir, queue, questions) = store();
3884 let mut t = task("keep held", dir.path().join("repo"));
3885 t.hold_machine(Some("unresolved cause".into()));
3886 queue.put(&mut t).unwrap();
3887 run_once(&queue, &questions, None, Timestamp::now());
3888 let mut old = questions.list().remove(0);
3889 old.answer(Answer::Choice(old.choices[1].clone())).unwrap();
3890 questions.put(&mut old).unwrap();
3891 run_once(&queue, &questions, None, Timestamp::now());
3892 let held = queue.get(&t.id).unwrap();
3893 assert!(held.triage_applied(&old.id));
3894
3895 let migration = dir.path().join("notifications/task-chat-migration-v1");
3896 std::fs::create_dir_all(&migration).unwrap();
3897 std::fs::write(
3898 migration.join("state.json"),
3899 serde_json::to_vec(&serde_json::json!({
3900 "schema": 1, "classification_revision": 1, "pending": [], "sources": [old.id]
3901 }))
3902 .unwrap(),
3903 )
3904 .unwrap();
3905 assert!(questions.list_for_effects()[0].status.open());
3906 assert!(!pending_for(&questions, &held));
3907 assert!(open_question_for(&questions, &t.id).is_none());
3908 assert!(!open_task_ids(&questions).contains(&t.id));
3909 assert!(old.answer(Answer::Choice(old.choices[2].clone())).is_err());
3910 assert!(
3911 run_once(&queue, &questions, None, Timestamp::now())
3912 .answered
3913 .is_empty()
3914 );
3915
3916 let later = held.updated_at + SignedDuration::from_hours(24 * 8);
3917 assert_eq!(
3918 run_once(&queue, &questions, None, later).asked,
3919 [t.id.clone()]
3920 );
3921 let mut fresh = open_question_for(&questions, &t.id).unwrap();
3922 assert_ne!(fresh.id, old.id);
3923 assert_eq!(fresh.choices[2], EN.discard);
3924 fresh
3925 .answer(Answer::Choice(fresh.choices[2].clone()))
3926 .unwrap();
3927 questions.put(&mut fresh).unwrap();
3928 assert_eq!(
3929 run_once(&queue, &questions, None, later).answered,
3930 [t.id.clone()]
3931 );
3932 assert!(queue.get(&t.id).is_err());
3933 assert_eq!(
3934 questions.read_history(&old.id).unwrap().resolution(),
3935 Some(EN.wait.into())
3936 );
3937 }
3938
3939 #[test]
3940 fn migrated_unapplied_answers_remain_fenced_but_are_not_displayed_open() {
3941 for node in [NODE, DEPS_NODE] {
3942 let (dir, queue, questions) = store();
3943 let mut t = task("unapplied", dir.path().join("repo"));
3944 t.hold_manual(Some("waiting".into()));
3945 queue.put(&mut t).unwrap();
3946 let mut q = Question::new(
3947 t.id.clone(),
3948 node.into(),
3949 SEAT.into(),
3950 "unapplied".into(),
3951 String::new(),
3952 EN.choices3(),
3953 );
3954 q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
3955 questions.put(&mut q).unwrap();
3956 let migration = dir.path().join("notifications/task-chat-migration-v1");
3957 std::fs::create_dir_all(&migration).unwrap();
3958 std::fs::write(
3959 migration.join("state.json"),
3960 serde_json::to_vec(&serde_json::json!({
3961 "schema": 1, "classification_revision": 1, "pending": [], "sources": [q.id]
3962 }))
3963 .unwrap(),
3964 )
3965 .unwrap();
3966 assert!(pending_for(&questions, &t));
3967 assert!(open_question_for(&questions, &t.id).is_none());
3968 assert!(!open_task_ids(&questions).contains(&t.id));
3969 assert!(apply_answers(&queue, &questions).is_empty());
3970 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
3971 t.mark_triage_applied(&q.id);
3972 queue.put(&mut t).unwrap();
3973 assert!(!pending_for(&questions, &t));
3974 assert!(!deps_pending_in(&RecoveryIndex::load(&questions), &t));
3975 }
3976 }
3977}