1use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{BuildCache, Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{CompletionActor, CompletionContext, Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49pub const SCHEMA: u32 = 1;
51
52pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57pub const STALE_SECS: i64 = 30;
66
67pub const POLL: Duration = Duration::from_secs(5);
69
70pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub worker: Option<String>,
102 pub task: String,
104 pub run: String,
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116 pub schema: u32,
118 pub pid: u32,
120 pub started_at: Timestamp,
122 pub updated_at: Timestamp,
124 pub idle: bool,
126 pub current: Vec<Current>,
132 pub completed: usize,
134 pub polls: u64,
136 #[serde(default)]
138 pub dispatch_wait: Option<DispatchWait>,
139 #[serde(default)]
143 pub dispatch_skips: std::collections::BTreeMap<String, String>,
144 #[serde(default)]
146 pub question_recovery: Option<crate::question_delivery::Recovery>,
147 #[serde(default)]
149 pub worker_protocol: Option<u32>,
150}
151
152impl Status {
153 #[must_use]
155 pub fn new() -> Self {
156 let now = Timestamp::now();
157 Self {
158 schema: SCHEMA,
159 pid: std::process::id(),
160 started_at: now,
161 updated_at: now,
162 idle: true,
163 current: Vec::new(),
164 completed: 0,
165 polls: 0,
166 dispatch_wait: None,
167 dispatch_skips: std::collections::BTreeMap::new(),
168 question_recovery: None,
169 worker_protocol: Some(1),
170 }
171 }
172}
173
174impl Default for Status {
175 fn default() -> Self {
176 Self::new()
177 }
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize)]
182#[serde(default)]
183pub struct Opts {
184 pub repo: PathBuf,
186 pub config: Option<PathBuf>,
188 pub poll: Duration,
190 pub max_attempts: usize,
192 pub once: bool,
194 pub merge: Option<String>,
196 pub worktrees_root: Option<PathBuf>,
205}
206
207impl Default for Opts {
208 fn default() -> Self {
209 Self {
210 repo: PathBuf::from("."),
211 config: None,
212 poll: POLL,
213 max_attempts: 2,
214 once: false,
215 merge: None,
216 worktrees_root: None,
217 }
218 }
219}
220
221impl Opts {
222 fn absolute(&self) -> Result<Self> {
223 let mut opts = self.clone();
224 opts.repo = std::path::absolute(&opts.repo)?;
225 opts.config = opts
226 .config
227 .as_deref()
228 .map(std::path::absolute)
229 .transpose()?;
230 opts.worktrees_root = opts
231 .worktrees_root
232 .as_deref()
233 .map(std::path::absolute)
234 .transpose()?;
235 Ok(opts)
236 }
237}
238
239fn max_concurrent(n: usize) -> usize {
244 n.max(1)
245}
246
247#[must_use]
249pub fn status_path() -> PathBuf {
250 crate::run::home().join("daemon.json")
251}
252
253pub fn write_status(status: &Status) -> Result<()> {
255 write_status_to(&status_path(), status)
256}
257
258pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
263 if let Some(parent) = path.parent() {
264 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
265 }
266 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
267 let tmp = path.with_extension("json.tmp");
268 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
269 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
270 Ok(())
271}
272
273pub fn clear_status() {
276 clear_status_at(&status_path());
277}
278
279fn clear_status_at(path: &Path) {
283 let _ = std::fs::remove_file(path);
284}
285
286#[derive(Debug, Clone, Default)]
298pub struct Stop {
299 stopped: Arc<AtomicBool>,
303 busy: Arc<std::sync::atomic::AtomicUsize>,
305 wake: Arc<Notify>,
309 pause: crate::graph::Pause,
312}
313
314impl Stop {
315 #[must_use]
317 pub fn new() -> Self {
318 Self::default()
319 }
320
321 pub fn stop(&self) {
324 self.stopped.store(true, Ordering::SeqCst);
325 self.wake.notify_one();
329 }
330
331 #[must_use]
333 pub fn stopped(&self) -> bool {
334 self.stopped.load(Ordering::SeqCst)
335 }
336
337 #[must_use]
340 pub fn finishing(&self) -> bool {
341 self.stopped() && self.busy_now()
342 }
343
344 pub fn park(&self, cause: crate::run::ParkCause) {
350 self.pause.park_for(cause);
351 self.stop();
352 }
353
354 #[must_use]
356 pub fn parking(&self) -> bool {
357 self.pause.parked()
358 }
359
360 #[must_use]
362 pub fn pause(&self) -> crate::graph::Pause {
363 self.pause.clone()
364 }
365
366 #[must_use]
368 pub fn busy_now(&self) -> bool {
369 self.busy.load(Ordering::SeqCst) > 0
370 }
371
372 async fn idle(&self, poll: Duration) {
374 tokio::select! {
375 () = tokio::time::sleep(poll) => {}
376 () = self.wake.notified() => {}
377 }
378 }
379}
380
381#[derive(Debug, Clone, Default, Deserialize)]
388#[serde(default)]
389pub struct Reading {
390 pub schema: u32,
392 pub pid: Option<u32>,
394 pub started_at: Option<Timestamp>,
396 pub updated_at: Option<Timestamp>,
398 pub idle: bool,
400 #[serde(deserialize_with = "de_current")]
412 pub current: Vec<Current>,
413 pub completed: u64,
415 pub polls: u64,
417 pub dispatch_wait: Option<DispatchWait>,
419 #[serde(default)]
421 pub dispatch_skips: std::collections::BTreeMap<String, String>,
422 #[serde(default)]
424 pub question_recovery: Option<crate::question_delivery::Recovery>,
425 pub worker_protocol: Option<u32>,
427}
428
429fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
432where
433 D: serde::Deserializer<'de>,
434{
435 #[derive(Deserialize)]
436 #[serde(untagged)]
437 enum Shape {
438 Many(Vec<Current>),
439 One(Current),
440 }
441 Ok(
442 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
443 Shape::Many(v) => v,
444 Shape::One(c) => vec![c],
445 }),
446 )
447}
448
449impl Reading {
450 #[must_use]
453 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
454 self.updated_at
455 .map(|at| (now.as_second() - at.as_second()).max(0))
456 }
457
458 #[must_use]
462 pub fn running(&self, now: Timestamp) -> bool {
463 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
464 }
465}
466
467#[must_use]
474pub fn read_status(home: &Path) -> Option<Reading> {
475 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
476 serde_json::from_str(&body).ok()
477}
478
479struct ClaimObservation {
480 current: Current,
481 evidence: crate::run::LivenessEvidence,
482}
483
484fn observe_current_work(home: &Path, now: Timestamp) -> Vec<ClaimObservation> {
485 let mut observed: Vec<ClaimObservation> = Vec::new();
486 let reading = read_status(home).filter(|reading| reading.running(now));
487 let daemon_pid = reading.as_ref().and_then(|r| r.pid);
488 let heartbeat_age_secs = reading.as_ref().and_then(|r| r.age_secs(now));
489 if let Some(reading) = reading {
490 for claim in reading.current {
491 let task = (!claim.task.is_empty()).then(|| claim.task.clone());
492 let (worker_pid, worker_status, worker_lookup_error) = match claim.worker.as_deref() {
493 Some(worker_id) => match crate::worker::get(home, worker_id) {
494 Ok(job)
495 if matches!(
496 job.status,
497 crate::worker::Status::Finished | crate::worker::Status::Failed
498 ) =>
499 {
500 continue;
503 }
504 Ok(job) => (job.pid, Some(job.status), None),
505 Err(error) => (None, None, Some(format!("{error:#}"))),
506 },
507 None => (None, None, None),
508 };
509 let evidence = crate::run::LivenessEvidence::DaemonHeartbeat {
510 daemon_pid,
511 heartbeat_age_secs,
512 worker_id: claim.worker.clone(),
513 worker_pid,
514 worker_status,
515 worker_lookup_error,
516 task,
517 };
518 observed.push(ClaimObservation {
519 current: claim,
520 evidence,
521 });
522 }
523 }
524 let workers = crate::worker::observe_active_detailed(home).and_then(|jobs| {
525 jobs.into_iter()
526 .filter(|entry| entry.job.kind == "task")
527 .map(|entry| {
528 let job = entry.job;
529 let request: TaskWorker = serde_json::from_value(job.payload).map_err(|_| {
530 anyhow::anyhow!("invalid task worker payload metadata for worker {}", job.id)
531 })?;
532 let run = Queue::at(request.queue)
533 .get(&request.task)
534 .ok()
535 .and_then(|task| task.execution_runs().last().cloned())
536 .unwrap_or_default();
537 let task_label = (!request.task.is_empty()).then(|| request.task.clone());
538 let current = Current {
539 worker: Some(job.id.clone()),
540 task: request.task,
541 run,
542 };
543 let evidence = crate::run::LivenessEvidence::WorkerClaim {
544 worker_id: job.id,
545 pid: job.pid,
546 status: job.status,
547 reason: entry.reason,
548 task: task_label,
549 daemon_pid: None,
550 };
551 Ok(ClaimObservation { current, evidence })
552 })
553 .collect::<Result<Vec<_>>>()
554 });
555 match workers {
556 Ok(workers) => {
557 for mut worker in workers {
558 if let Some(existing) = observed.iter_mut().find(|claim| {
559 claim.current.task == worker.current.task
560 && claim.current.run == worker.current.run
561 && claim.current.worker == worker.current.worker
562 }) {
563 if let crate::run::LivenessEvidence::WorkerClaim {
564 daemon_pid: ref mut target_daemon_pid,
565 ..
566 } = worker.evidence
567 {
568 *target_daemon_pid = daemon_pid;
569 }
570 existing.evidence = worker.evidence;
571 } else {
572 observed.push(worker);
573 }
574 }
575 }
576 Err(error) => {
577 let detail = format!("{error:#}");
580 tracing::error!("cannot determine active workers: {detail}");
581 let evidence = crate::run::LivenessEvidence::WorkerStoreUnreadable { error: detail };
582 observed.extend(
583 Queue::at(home.join("queue"))
584 .list()
585 .into_iter()
586 .map(|task| ClaimObservation {
587 current: Current {
588 worker: None,
589 task: task.id.clone(),
590 run: task.execution_runs().last().cloned().unwrap_or_default(),
591 },
592 evidence: evidence.clone(),
593 }),
594 );
595 observed.extend(
596 crate::run::list_ids_in(&home.join("runs"))
597 .into_iter()
598 .map(|run| ClaimObservation {
599 current: Current {
600 worker: None,
601 task: String::new(),
602 run,
603 },
604 evidence: evidence.clone(),
605 }),
606 );
607 }
608 }
609 observed
610}
611
612#[must_use]
621pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
622 observe_current_work(home, now)
623 .into_iter()
624 .map(|entry| entry.current)
625 .collect()
626}
627
628#[must_use]
630pub fn claim_for_run(
631 home: &Path,
632 run: &str,
633 now: Timestamp,
634) -> Option<crate::run::LivenessEvidence> {
635 observe_current_work(home, now)
636 .into_iter()
637 .find(|entry| entry.current.run == run)
638 .map(|entry| entry.evidence)
639}
640
641#[must_use]
643pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
644 claim_for_run(home, run, now).is_some()
645}
646
647pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
652 Ok(other_claim_for_run(home, run, now)?.is_some())
653}
654
655pub(crate) fn other_claim_for_run(
658 home: &Path,
659 run: &str,
660 now: Timestamp,
661) -> Result<Option<crate::run::LivenessEvidence>> {
662 let same_home = std::env::var_os("MAGI_WORKER_HOME")
665 .is_some_and(|worker_home| Path::new(&worker_home) == home);
666 let caller = if same_home {
667 crate::worker::current_job(home)?
668 } else {
669 None
670 }
671 .filter(|job| {
672 job.kind == "task"
673 && job.status == crate::worker::Status::Running
674 && job.pid == Some(std::process::id())
675 });
676 let caller_id = caller.as_ref().map(|job| job.id.as_str());
677 Ok(observe_current_work(home, now)
678 .into_iter()
679 .find(|entry| {
680 entry.current.run == run
681 && !(caller_id.is_some() && entry.current.worker.as_deref() == caller_id)
682 })
683 .map(|entry| entry.evidence))
684}
685
686#[cfg(test)]
687fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
688 claims
689 .iter()
690 .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
691}
692
693#[must_use]
703pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
704 current_work(home, now)
705 .iter()
706 .any(|c| crate::run::short_of(&c.run) == short)
707}
708
709#[must_use]
711pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
712 current_work(home, now).iter().any(|c| c.task == task)
713}
714
715pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
755 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
756}
757
758fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
762where
763 F: Fn(u32) -> bool,
764{
765 let this_process = std::process::id();
766 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
767 .into_iter()
768 .flatten()
769 .flatten()
770 .map(|e| e.path())
771 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
772 .filter(|p| {
773 match std::fs::read_to_string(p)
774 .ok()
775 .and_then(|body| body.trim().parse::<u32>().ok())
776 {
777 Some(pid) if pid == this_process => false,
781 Some(pid) => !pid_alive(pid),
782 None => p
783 .metadata()
784 .and_then(|m| m.modified())
785 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
786 .is_ok_and(|age| age >= older_than),
787 }
788 })
789 .filter(|p| std::fs::remove_file(p).is_ok())
790 .filter_map(|p| {
791 p.file_stem()
792 .and_then(|s| s.to_str())
793 .map(std::borrow::ToOwned::to_owned)
794 })
795 .collect();
796 swept.sort_unstable();
797 swept
798}
799
800fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
805 task.status == TaskStatus::Running
806 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
807 && !is_working_on_task(home, &task.id, now)
808}
809
810fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
813 queue
814 .list()
815 .into_iter()
816 .filter(|t| is_stalled(t, home, now))
817 .collect()
818}
819
820fn queued_tasks(queue: &Queue) -> Vec<Task> {
826 queue
827 .list()
828 .into_iter()
829 .filter(|t| t.status == TaskStatus::Queued)
830 .collect()
831}
832
833fn finished_tasks(queue: &Queue) -> Vec<Task> {
836 queue
837 .list()
838 .into_iter()
839 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
840 .collect()
841}
842
843fn resolve_blockers(queue: &Queue, questions: &Questions) {
860 for listed in queue.list() {
861 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
862 continue;
863 }
864 let Ok(_claim) = queue.claim(&listed.id) else {
865 continue;
866 };
867 let Ok(mut task) = queue.get(&listed.id) else {
868 continue;
869 };
870 if task.status != TaskStatus::Blocked {
871 continue;
872 }
873 let deleted = queue.apply_deleted_blockers(&mut task, questions);
877 if !deleted.is_empty() {
878 record(queue, &mut task);
879 for id in &deleted {
880 queue.note_dependency_deleted(&task, id);
881 }
882 if task.status != TaskStatus::Blocked {
883 continue;
884 }
885 }
886 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
887 if !missing.is_empty() {
888 let language = language_of(&task, Path::new("."));
889 let mut cause = missing.clone();
890 cause.sort();
891 cause.dedup();
892 task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
893 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
894 &task.blocked_by,
895 &missing,
896 &language,
897 )));
898 record(queue, &mut task);
899 continue;
900 }
901 if let Some(q) = task.blocked_by.iter().find_map(|id| {
904 let crate::queue::Dependency::Question(full) =
905 crate::queue::dependency(queue, questions, id)
906 else {
907 return None;
908 };
909 questions.get_for_effects(&full).ok().filter(|q| {
910 q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
911 })
912 }) {
913 let language = language_of(&task, Path::new("."));
914 task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
915 task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
916 record(queue, &mut task);
917 continue;
918 }
919 let mut changed = false;
920 for id in task.blocked_by.clone() {
921 let resolved = crate::queue::dependency(queue, questions, &id);
922 if let crate::queue::Dependency::Task(full) = &resolved {
923 if queue
924 .get(full)
925 .is_ok_and(|dep| dep.status == TaskStatus::Done)
926 {
927 task.unblock(&id);
928 changed = true;
929 }
930 continue;
931 }
932 if let crate::queue::Dependency::Question(full) = resolved
933 && let Ok(q) = questions.get_for_effects(&full)
934 && q.status == ask::QuestionStatus::Answered
935 {
936 if q.node == crate::conduct::NODE
940 && q.chosen_action().is_some()
941 && !task.action_applied(&q.id)
942 {
943 continue;
944 }
945 let answer = match &q.answer {
946 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
947 None => String::new(),
948 };
949 task.record_answer(q.summary.clone(), answer);
950 task.unblock(&id);
951 changed = true;
952 }
953 }
954 if changed {
955 record(queue, &mut task);
956 }
957 }
958}
959
960fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
962 if crate::lang::is_japanese(language) {
963 format!(
964 "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
965 q.short(),
966 q.summary
967 )
968 } else {
969 format!(
970 "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
971 q.short(),
972 q.summary
973 )
974 }
975}
976
977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
980pub(crate) enum ActionStanding {
981 NoAction,
983 Pending,
985 Applied,
988 Stale,
990 Busy,
992}
993
994impl ActionStanding {
995 pub(crate) fn daemon_owns(self) -> bool {
997 matches!(self, Self::Pending | Self::Applied | Self::Stale)
998 }
999}
1000
1001pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
1005 if task.stale_question(q) {
1006 ActionStanding::Stale
1007 } else if q.chosen_action().is_none() {
1008 ActionStanding::NoAction
1009 } else if task.action_applied(&q.id) {
1010 ActionStanding::Applied
1011 } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1012 ActionStanding::Stale
1013 } else if matches!(
1014 task.status,
1015 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1016 ) {
1017 ActionStanding::Busy
1018 } else {
1019 ActionStanding::Pending
1020 }
1021}
1022
1023#[derive(Debug, Clone, PartialEq, Eq)]
1025enum ActionDecision {
1026 Skip,
1028 Resume(String),
1030 Requeue,
1032 Hold,
1034 Done,
1036 Stale,
1039 Refuse(String),
1042}
1043
1044fn decide_action<F>(
1053 home: &Path,
1054 task: &Task,
1055 q: &ask::Question,
1056 p: &Phrases,
1057 load: F,
1058) -> ActionDecision
1059where
1060 F: FnOnce(&str) -> Result<RunState>,
1061{
1062 if task.stale_question(q) {
1063 return ActionDecision::Stale;
1064 }
1065 let Some(action) = q.chosen_action() else {
1066 return ActionDecision::Skip;
1067 };
1068 if task.action_applied(&q.id)
1069 || matches!(
1070 task.status,
1071 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1072 )
1073 {
1074 return ActionDecision::Skip;
1075 }
1076 if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1079 return ActionDecision::Stale;
1080 }
1081 let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
1082 let stopping = q.node == land::APPROVAL_NODE
1083 && q.resolution()
1084 .as_deref()
1085 .is_some_and(crate::merge_decision::stops);
1086 let decision_at = q.answered_at.unwrap_or(q.asked_at);
1090 if task.operator_decided_at.is_some_and(|at| at > decision_at) {
1091 return if repair || stopping {
1092 ActionDecision::Refuse(format!(
1093 "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
1094 if repair { "repair" } else { "stop" },
1095 q.id,
1096 q.run,
1097 task.id
1098 ))
1099 } else {
1100 ActionDecision::Stale
1101 };
1102 }
1103 match action {
1104 a if a.maintenance() => ActionDecision::Skip,
1105 ask::ChoiceAction::RecoverBase { .. }
1106 | ask::ChoiceAction::ResumeRun { .. }
1107 | ask::ChoiceAction::ReleaseTask { .. }
1108 | ask::ChoiceAction::RerunChecks { .. }
1109 | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
1110 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
1111 ask::ChoiceAction::Hold => ActionDecision::Hold,
1112 ask::ChoiceAction::Done => ActionDecision::Done,
1113 ask::ChoiceAction::Resume { run } => {
1114 if task.execution_runs().last() != Some(run) {
1115 return ActionDecision::Refuse((p.resume_not_latest)(
1116 q.short(),
1117 ask::short_id(run),
1118 ));
1119 }
1120 match load(run) {
1121 Ok(s) if stopping => {
1122 if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1123 || !s
1124 .land_approval
1125 .as_ref()
1126 .is_some_and(|binding| binding.question == q.id)
1127 {
1128 ActionDecision::Stale
1129 } else if s.liveness_under(home, false) == Liveness::Live {
1130 ActionDecision::Skip
1131 } else if s.status == RunStatus::Landing
1132 && !s.released()
1133 && s.retired_to.is_none()
1134 {
1135 ActionDecision::Resume(run.clone())
1136 } else {
1137 ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1138 }
1139 }
1140 Ok(s)
1141 if q.node == land::APPROVAL_NODE
1142 && q.resolution().as_deref() == Some(land::REPAIR) =>
1143 {
1144 if s.merge_repairs.iter().any(|r| r.question == q.id)
1145 || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1146 {
1147 ActionDecision::Stale
1150 } else if s.liveness_under(home, false) == Liveness::Live {
1151 ActionDecision::Skip
1152 } else if s.status != RunStatus::Landing
1153 || s.released()
1154 || s.reviews.is_empty()
1155 || !implementers_match(task, &s)
1156 || !s
1157 .land_approval
1158 .as_ref()
1159 .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1160 {
1161 ActionDecision::Refuse(format!(
1162 "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
1163 q.id, run, run
1164 ))
1165 } else {
1166 ActionDecision::Resume(run.clone())
1167 }
1168 }
1169 Ok(s) => {
1170 let assessment = s.assess_liveness_under(home, None, Timestamp::now());
1171 if assessment.verdict == Liveness::Live {
1172 ActionDecision::Refuse(assessment.live_driver_refusal())
1173 } else {
1174 match crate::handover::resume_refusal_under(&s, Some(home)) {
1175 None => ActionDecision::Resume(run.clone()),
1176 Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1177 q.short(),
1178 ask::short_id(run),
1179 &reason.diagnostic(&s),
1180 )),
1181 }
1182 }
1183 }
1184 Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1185 q.short(),
1186 ask::short_id(run),
1187 &format!("{e:#}"),
1188 )),
1189 }
1190 }
1191 }
1192}
1193
1194struct Phrases {
1208 graph_stopped: fn(&str, &str) -> String,
1210 quorum_lost: &'static str,
1211 quota_took_out: &'static str,
1213 run_ended: &'static str,
1215 waiting_for_answer: &'static str,
1217 recovered_running: &'static str,
1218 no_run_to_recover: &'static str,
1219 could_not_start: &'static str,
1220 resume_not_latest: fn(&str, &str) -> String,
1221 resume_cannot_progress: fn(&str, &str, &str) -> String,
1222 resume_unreadable: fn(&str, &str, &str) -> String,
1223 handover_refused: fn(&crate::handover::Refused) -> String,
1226 handover_hint: &'static str,
1228 reviewers_never_answered: fn(usize, usize) -> String,
1231}
1232
1233const PHRASES_EN: Phrases = Phrases {
1234 graph_stopped: |status, detail| {
1235 format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1236 },
1237 quorum_lost: "the judging panel lost its quorum",
1238 quota_took_out: "; quota took out ",
1239 run_ended: "run ended ",
1240 waiting_for_answer: " - waiting for operator answer to question ",
1241 recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1242 no_run_to_recover: "task was `running` with no live daemon and no readable \
1243 run to recover; held for a human to check what happened",
1244 could_not_start: "could not start the run: ",
1245 resume_not_latest: |q, run| {
1246 format!("question {q} asked to resume run {run}, which is not this task's latest run")
1247 },
1248 resume_cannot_progress: |q, run, reason| {
1249 format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1250 },
1251 resume_unreadable: |q, run, e| {
1252 format!("question {q} asked to resume run {run}, which could not be read: {e}")
1253 },
1254 handover_refused: |r| r.to_string(),
1255 handover_hint: " (clean up the other worktree, then release the task from the queue)",
1256 reviewers_never_answered: |missing, rounds| {
1257 format!(
1258 "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1259 refusing to call it clean"
1260 )
1261 },
1262};
1263
1264const PHRASES_JA: Phrases = Phrases {
1265 graph_stopped: |status, detail| {
1266 format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1267 },
1268 quorum_lost: "審査パネルが定足数を失いました",
1269 quota_took_out: "。クォータで脱落: ",
1270 run_ended: "run 終了: ",
1271 waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1272 recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1273 no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1274 何が起きたか人が確認するため保留にしました",
1275 could_not_start: "run を開始できませんでした: ",
1276 resume_not_latest: |q, run| {
1277 format!(
1278 "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1279 )
1280 },
1281 resume_cannot_progress: |q, run, reason| {
1282 format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1283 },
1284 resume_unreadable: |q, run, e| {
1285 format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1286 },
1287 handover_refused: |r| {
1288 use crate::handover::Refused;
1289 match r {
1290 Refused::Foreign { branch, path, why } => format!(
1291 "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1292 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1293 から、やり直してください(詳細: {why})"
1294 ),
1295 Refused::Unsafe { branch, path, why } => format!(
1296 "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1297 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1298 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1299 ),
1300 Refused::ReleaseFailed { branch, path, run } => format!(
1301 "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1302 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1303 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1304 ),
1305 }
1306 },
1307 handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1308 reviewers_never_answered: |missing, rounds| {
1309 format!(
1310 "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1311 クリーンとは認めません"
1312 )
1313 },
1314};
1315
1316fn phrases(language: &str) -> &'static Phrases {
1317 if crate::lang::is_japanese(language) {
1318 &PHRASES_JA
1319 } else {
1320 &PHRASES_EN
1321 }
1322}
1323
1324fn language_of(task: &Task, fallback: &Path) -> String {
1328 crate::lang::of_repo(&repo_for(task, fallback))
1329}
1330
1331pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1335 if q.node == crate::conduct::NODE {
1336 return tasks.iter().find(|t| t.id == q.run);
1337 }
1338 tasks.iter().find(|t| t.runs.contains(&q.run))
1339}
1340
1341fn repair_choice_offers(questions: &Questions) {
1344 let ownership = crate::task_chat::InquiryOwnership::default();
1345 for q in questions
1346 .list_for_effects_in(&ownership)
1347 .into_iter()
1348 .filter(|q| {
1349 q.status.open()
1350 && q.node == crate::conduct::NODE
1351 && q.choices
1352 .iter()
1353 .any(|c| crate::choice_effect::describe(q, c).is_none())
1354 })
1355 {
1356 let _ = questions.update_in(&q.id, &ownership, |current| {
1357 if current.status.open() {
1358 crate::choice_effect::executable_conductor(current);
1359 if let Some(deputy) = &mut current.deputy {
1360 deputy.brief = crate::deputy::brief(
1361 ¤t.run,
1362 ¤t.detail,
1363 ¤t.choices,
1364 ¤t.actions,
1365 );
1366 }
1367 }
1368 Ok(())
1369 });
1370 }
1371}
1372
1373pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1376 apply_maintenance_choices(queue, questions, home).await;
1377 apply_task_choice_actions(queue, questions, home);
1378}
1379
1380async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1383 let ownership = crate::task_chat::InquiryOwnership::default();
1384 for q in questions.list_for_effects_in(&ownership) {
1385 let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1387 continue;
1388 };
1389 let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1390 continue;
1391 };
1392 let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1393 continue;
1394 };
1395 if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1398 continue;
1399 }
1400 if queue.list().iter().any(|task| {
1401 (task.id == q.run
1402 || task.runs.contains(&q.run)
1403 || q.routed_task.as_deref() == Some(&task.id))
1404 && task.stale_question(&q)
1405 }) {
1406 continue;
1407 }
1408 if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1409 let tasks = queue.list();
1410 let owner = crate::task_chat::task_of(&q, &tasks);
1411 if let Some(owner) = owner
1412 && q.routed_task
1413 .as_deref()
1414 .is_none_or(|routed| routed == owner)
1415 {
1416 let result = crate::base_recovery_control::recover(
1417 queue,
1418 home,
1419 crate::base_recovery_control::Request {
1420 run: run.clone(),
1421 head: stop.head.clone(),
1422 actor: "decisions".into(),
1423 request: q.id.clone(),
1424 decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1425 expected_stop: Some((stop.clone(), *episode)),
1426 evidence_digest: None,
1427 },
1428 )
1429 .await;
1430 if let Err(error) = result {
1431 tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1432 notices::raise_in(home, Notice::warn(
1433 &format!("base-recovery:{}", q.id),
1434 format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1435 ).link(Link::Run { id: run.clone() }));
1436 }
1437 }
1438 continue;
1439 }
1440 let dir = home.join("choice-actions");
1441 if std::fs::create_dir_all(&dir).is_err() {
1442 continue;
1443 }
1444 let Ok(lock) = std::fs::OpenOptions::new()
1445 .create(true)
1446 .truncate(false)
1447 .write(true)
1448 .open(dir.join(format!("{}.lock", q.id)))
1449 else {
1450 continue;
1451 };
1452 if crate::pr_head::try_lock_file(&lock).is_err() {
1453 continue;
1454 }
1455 let fresh = !home
1456 .join("choice-actions")
1457 .join(format!("{}.json", q.id))
1458 .exists();
1459 let result = async {
1460 let receipt = dir.join(format!("{}.json", q.id));
1461 if receipt.exists() {
1462 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1463 anyhow::ensure!(
1464 prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1465 "previous maintenance attempt did not confirm completion; inspect its receipt"
1466 );
1467 return Ok::<_, anyhow::Error>(());
1468 }
1469 let record = |status: &str| -> anyhow::Result<()> {
1472 let tmp = receipt.with_extension("tmp");
1473 std::fs::write(
1474 &tmp,
1475 serde_json::to_vec(&serde_json::json!({
1476 "action": action, "status": status,
1477 }))?,
1478 )?;
1479 std::fs::rename(tmp, &receipt)?;
1480 Ok(())
1481 };
1482 let applied = async {
1483 match action {
1484 ask::ChoiceAction::ResumeRun { run } => {
1485 crate::resume::validate(home, run)?;
1486 record("started")?;
1487 let decided = q.answered_at.unwrap_or(q.asked_at);
1488 if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1489 crate::resume::validate_unqueued(home, run)?;
1490 crate::resume::start(home, run.clone()).await?;
1491 }
1492 }
1493 ask::ChoiceAction::ReleaseTask {
1494 task,
1495 held_at,
1496 reason,
1497 } => {
1498 anyhow::ensure!(
1499 queue.resolve_id(task)? == *task,
1500 "task action requires an exact task ID"
1501 );
1502 let _claim = queue.claim(task)?;
1503 let mut task = queue.get(task)?;
1504 if task.action_applied(&q.id) {
1505 return Ok(());
1506 }
1507 if q.node == crate::conduct::NODE
1512 && q.run == task.id
1513 && task.status == TaskStatus::Blocked
1514 && task.blocked_from == Some(TaskStatus::Held)
1515 && task.blocked_by.as_slice() == [q.id.as_str()]
1516 {
1517 task.unblock(&q.id);
1518 }
1519 anyhow::ensure!(
1520 task.status == TaskStatus::Held
1521 && task.held_at == Some(*held_at)
1522 && task.hold_reason.as_deref() == reason.as_deref()
1523 && task
1524 .operator_decided_at
1525 .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1526 "task no longer has the hold this question names"
1527 );
1528 task.release_operator("choice", Some(&q.id));
1529 task.mark_action_applied(&q.id);
1530 queue.put(&mut task)?;
1531 }
1532 ask::ChoiceAction::AbandonRun { run } => {
1533 record("started")?;
1534 crate::driver::abandon_proven_dead(home, run)?;
1535 }
1536 ask::ChoiceAction::RerunChecks {
1537 repo,
1538 pr,
1539 head,
1540 runs,
1541 } => {
1542 rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1543 .await?;
1544 }
1545 _ => unreachable!(),
1546 }
1547 Ok::<_, anyhow::Error>(())
1548 }
1549 .await;
1550 match applied {
1551 Ok(()) => record("applied"),
1552 Err(e) => {
1553 record(&format!("refused or failed: {e:#}"))?;
1554 Err(e)
1555 }
1556 }
1557 }
1558 .await;
1559 if home
1564 .join("choice-actions")
1565 .join(format!("{}.json", q.id))
1566 .exists()
1567 && let Some(listed) = task_of_question(&queue.list(), &q)
1568 && !listed.action_applied(&q.id)
1569 && let Ok(_claim) = queue.claim(&listed.id)
1570 && let Ok(mut origin) = queue.get(&listed.id)
1571 {
1572 if !origin.operator_held()
1573 && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1574 && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1575 {
1576 if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1577 origin.hold_machine(Some(format!(
1578 "Maintenance choice {} settled; inspect its target before releasing this task",
1579 q.id
1580 )));
1581 } else {
1582 origin.unblock(&q.id);
1583 }
1584 }
1585 origin.mark_action_applied(&q.id);
1586 let _ = queue.put(&mut origin);
1587 }
1588 if let Err(e) = result
1589 && fresh
1590 {
1591 notices::raise_in(
1592 home,
1593 Notice::warn(
1594 &format!("action:{}", q.id),
1595 format!("Choice action {} was not completed: {e:#}", q.id),
1596 )
1597 .link(if q.run_names_task() {
1598 Link::Task { id: q.run.clone() }
1599 } else {
1600 Link::Run { id: q.run.clone() }
1601 }),
1602 );
1603 }
1604 }
1605}
1606
1607pub(crate) async fn rerun_checks_once(
1614 home: &Path,
1615 request: &str,
1616 repo: &Path,
1617 pr: &str,
1618 head: &str,
1619 runs: &[String],
1620 started: impl FnOnce() -> anyhow::Result<()>,
1621) -> anyhow::Result<()> {
1622 use crate::release_watch::{GhForge, ReleaseForge};
1623 anyhow::ensure!(
1624 !runs.is_empty()
1625 && runs.len() <= 20
1626 && runs
1627 .iter()
1628 .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1629 && !pr.starts_with('-'),
1630 "invalid rerun targets"
1631 );
1632 let snap = GhForge.snapshot(repo, pr).await?;
1633 anyhow::ensure!(
1634 snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1635 "pull request head or lifecycle changed"
1636 );
1637 anyhow::ensure!(
1638 runs.iter().all(|r| snap
1639 .checks
1640 .iter()
1641 .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1642 "named workflow is no longer failed on this pull request"
1643 );
1644 started()?;
1645 let dir = home.join("choice-actions");
1646 std::fs::create_dir_all(&dir)?;
1647 let rerun_lock = std::fs::OpenOptions::new()
1648 .create(true)
1649 .truncate(false)
1650 .write(true)
1651 .open(dir.join("reruns.lock"))?;
1652 crate::pr_head::try_lock_file(&rerun_lock)?;
1653 let ledger = dir.join("reruns.json");
1654 let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1655 serde_json::from_slice(&std::fs::read(&ledger)?)?
1656 } else {
1657 Default::default()
1658 };
1659 for run in runs {
1660 let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1661 if !recorded.insert(key) {
1662 continue;
1663 }
1664 let tmp = ledger.with_extension("tmp");
1665 std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1666 std::fs::rename(tmp, &ledger)?;
1667 GhForge.rerun(repo, run).await?;
1668 }
1669 Ok(())
1670}
1671
1672pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1681 let tasks = queue.list();
1682 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1683 for q in questions.list_for_effects_in(&ownership) {
1684 let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1686 continue;
1687 };
1688 let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1689 continue;
1690 };
1691 if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1693 continue;
1694 }
1695 if q.chosen_action().is_none_or(|a| a.maintenance()) {
1696 continue;
1697 }
1698 let Some(listed) = task_of_question(&tasks, &q) else {
1699 if q.node == land::APPROVAL_NODE
1700 && q.resolution().as_deref().is_some_and(|choice| {
1701 choice == land::REPAIR || crate::merge_decision::stops(choice)
1702 })
1703 {
1704 notices::raise_in(
1705 home,
1706 Notice::warn(
1707 &format!("repair-owner:{}", q.id),
1708 format!(
1709 "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1710 q.run, q.run
1711 ),
1712 ).link(Link::Run { id: q.run.clone() }),
1713 );
1714 }
1715 continue;
1716 };
1717 if listed.action_applied(&q.id) {
1718 continue;
1719 }
1720 let Ok(_claim) = queue.claim(&listed.id) else {
1721 continue;
1722 };
1723 let Ok(mut task) = queue.get(&listed.id) else {
1724 continue;
1725 };
1726 if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1729 let blockers: Vec<_> = task
1730 .blocked_by
1731 .iter()
1732 .filter(|id| {
1733 crate::queue::dependency(queue, questions, id)
1734 == crate::queue::Dependency::Question(q.id.clone())
1735 })
1736 .cloned()
1737 .collect();
1738 if !blockers.is_empty() {
1739 for id in blockers {
1740 task.unblock(&id);
1741 }
1742 let answer = match &q.answer {
1743 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1744 None => String::new(),
1745 };
1746 task.record_answer(q.summary.clone(), answer);
1747 }
1748 }
1749 let language = language_of(&task, Path::new("."));
1750 let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1751 RunState::load_under(id, home)
1752 });
1753 let completion = if matches!(decision, ActionDecision::Done) {
1754 match crate::task_completion::prepare_close(
1755 &task,
1756 home,
1757 CompletionActor::DaemonSettle,
1758 Some(format!(
1759 "Question {}: {} — {}",
1760 q.id,
1761 q.summary,
1762 q.resolution().unwrap_or_default()
1763 )),
1764 false,
1765 ) {
1766 Ok(context) => Some(context),
1767 Err(error) => {
1768 decision = ActionDecision::Refuse(error.to_string());
1769 None
1770 }
1771 }
1772 } else {
1773 None
1774 };
1775 let ran = matches!(
1776 decision,
1777 ActionDecision::Resume(_)
1778 | ActionDecision::Requeue
1779 | ActionDecision::Hold
1780 | ActionDecision::Done
1781 );
1782 if ran && asker_may_still_read(questions, &q, home) {
1783 continue;
1792 }
1793 let done = matches!(decision, ActionDecision::Done);
1794 let completed = matches!(
1797 decision,
1798 ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1799 );
1800 match decision {
1801 ActionDecision::Skip => continue,
1802 ActionDecision::Resume(run) => {
1803 task.release_operator("choice", Some(&q.id));
1804 task.resume_override = Some(crate::queue::OperatorResume {
1805 question_id: q.id.clone(),
1806 at: Timestamp::now(),
1807 conductor_rehold: None,
1808 forced: true,
1809 pinned_run: Some(run),
1810 });
1811 }
1812 ActionDecision::Stale => {}
1813 ActionDecision::Requeue => {
1814 task.release_operator("choice-requeue", Some(&q.id));
1815 task.requeue();
1816 }
1817 ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1818 ActionDecision::Done => {
1819 task.succeed(completion.expect("done passed completion admission"));
1820 }
1821 ActionDecision::Refuse(why) => {
1822 let _ =
1823 crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1824 if task.operator_held() {
1825 task.hold_reason = Some(match task.hold_reason.take() {
1828 Some(reason) => format!("{reason}\n\n{why}"),
1829 None => why,
1830 });
1831 } else {
1832 task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1833 task.hold_machine(Some(why));
1834 }
1835 notices::raise(
1836 Notice::warn(
1837 &format!("action:{}", q.id),
1838 "An answered task action could not be applied; the task stays held.",
1839 )
1840 .link(Link::Task {
1841 id: task.id.clone(),
1842 }),
1843 );
1844 }
1845 }
1846 task.mark_action_applied(&q.id);
1847 if completed {
1848 task.decision_effects.insert(
1849 q.id.clone(),
1850 format!("decision: {}", q.resolution().expect("answered action")),
1851 );
1852 }
1853 record(queue, &mut task);
1856 if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1857 supersede_prior_runs(&task, home);
1858 }
1859 let _ = questions.update_in(&q.id, &ownership, |r| {
1862 r.answer_delivered = true;
1863 Ok(())
1864 });
1865 }
1866}
1867
1868fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1872 let now = Timestamp::now();
1873 if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1874 return true;
1875 }
1876 q.node != crate::conduct::NODE
1877 && RunState::load_under(&q.run, home).is_ok_and(|s| {
1878 s.seats_active()
1879 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1880 })
1881}
1882
1883fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1894 let tasks = queue.list();
1895 let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1896 let by_id: std::collections::BTreeMap<&str, &Task> =
1897 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1898 let referenced: Vec<&str> = tasks
1899 .iter()
1900 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1901 .collect();
1902
1903 for mut question in questions.list_for_effects_in(&ownership) {
1904 if !question.status.open()
1905 || question.node != crate::conduct::NODE
1906 || questions.held_reply_in(&question.id, &ownership)
1907 {
1908 continue;
1909 }
1910 if referenced
1915 .iter()
1916 .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1917 {
1918 continue;
1919 }
1920 let Some(task) = by_id.get(question.run.as_str()) else {
1921 continue;
1922 };
1923 question.abandon(format!(
1924 "task {} no longer waits for this answer",
1925 task.short()
1926 ));
1927 if let Err(e) = questions.put_in(&mut question, &ownership) {
1928 tracing::warn!(
1929 "could not retire question {} for task {}: {e:#}",
1930 question.short(),
1931 task.short()
1932 );
1933 }
1934 }
1935}
1936
1937#[derive(Debug, Clone, Copy)]
1944pub struct Verdict {
1945 pub status: RunStatus,
1947 pub left_pr: bool,
1949 pub quota_hit: bool,
1951 pub parked: bool,
1953 pub no_viable_candidates: bool,
1960}
1961
1962pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
2021 settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
2022}
2023
2024fn settle_in(
2026 task: &mut Task,
2027 verdict: Verdict,
2028 detail: &str,
2029 max_attempts: usize,
2030 p: &Phrases,
2031 state: Option<&RunState>,
2032) {
2033 if verdict.parked {
2039 task.park(detail);
2040 return;
2041 }
2042 let completion = |task: &Task| match state {
2043 Some(state) => CompletionContext::from_run(
2044 CompletionActor::DaemonSettle,
2045 Some(detail.to_owned()),
2046 task,
2047 state,
2048 ),
2049 None => CompletionContext::new(
2050 CompletionActor::DaemonSettle,
2051 Some(detail.to_owned()),
2052 &crate::run::home(),
2053 task,
2054 ),
2055 };
2056 match verdict.status {
2057 RunStatus::Merged | RunStatus::Ready
2058 if task.pr_recovery.as_ref().is_some_and(|s| {
2059 s.disposition != Some(crate::pr_recovery::Disposition::Review)
2060 }) =>
2061 {
2062 task.hold_manual(Some("Public delivery is not confirmed. Inspect the selected PR and run, then use recover-pr --disposition land with the intended source and validation configuration.".into()));
2063 }
2064 RunStatus::Merged | RunStatus::Ready => task.succeed(completion(task)),
2065 RunStatus::AlreadyInBase => task.already_landed(detail, completion(task)),
2066 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
2067 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
2068 task.stall(detail)
2069 }
2070 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
2071 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
2072 RunStatus::Blocked => task.fail(detail, max_attempts),
2073 RunStatus::VerifiedNoop if state.is_none_or(RunState::all_candidates_verified_noop) => {
2074 task.handed_off(detail)
2075 }
2076 RunStatus::VerifiedNoop => task.fail(detail, max_attempts),
2077 other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
2078 }
2079}
2080
2081pub fn supersede_prior_runs(task: &Task, home: &Path) {
2130 if task
2131 .completion_history
2132 .last()
2133 .is_some_and(|event| event.discard)
2134 {
2135 return;
2136 }
2137 let now = Timestamp::now();
2138 let last_run_succeeded = task
2145 .runs
2146 .last()
2147 .and_then(|id| RunState::load_under(id, home).ok())
2148 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2149 for id in task.superseded_attempts(last_run_succeeded) {
2150 let mut state = match RunState::load_under(id, home) {
2151 Ok(s) => s,
2152 Err(e) => {
2153 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2154 continue;
2155 }
2156 };
2157 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2158 continue;
2159 }
2160 let daemon_claims = is_working_on(home, id, now);
2161 if state.liveness(daemon_claims) == Liveness::Live {
2162 continue;
2163 }
2164 state.status = RunStatus::Superseded;
2165 if let Err(e) = state.save_under(home) {
2166 tracing::warn!("could not mark run {id} superseded: {e:#}");
2167 }
2168 }
2169}
2170
2171fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2193 for task in queue.list() {
2194 if task.status != TaskStatus::Done || task.runs.len() < 2 {
2195 continue;
2196 }
2197 supersede_prior_runs(&task, home);
2198 }
2199}
2200
2201fn settle_and_diagnose(
2208 task: &mut Task,
2209 verdict: Verdict,
2210 detail: &str,
2211 max_attempts: usize,
2212 state: &RunState,
2213) {
2214 let mut verdict = verdict;
2215 let mut detail = detail;
2216 if verdict.status == RunStatus::VerifiedNoop && !state.all_candidates_verified_noop() {
2217 verdict.status = RunStatus::Failed;
2221 verdict.quota_hit = false;
2222 detail = "no-change result lacks verified evidence";
2223 }
2224 let p = phrases(&state.config.graph.language);
2225 if let Some(d) = &state.merge_decision {
2228 use crate::merge_decision as md;
2229 if task
2230 .execution_runs()
2231 .last()
2232 .is_some_and(|id| id != &state.id)
2233 {
2234 return;
2235 }
2236 if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2237 task.succeed(CompletionContext::from_run(
2238 CompletionActor::DaemonSettle,
2239 Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2240 task,
2241 state,
2242 ));
2243 } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2244 if state.liveness(false) != Liveness::Dead {
2245 task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2246 return;
2247 }
2248 let replacement = md::Replacement {
2249 question: d.question.clone(),
2250 run: state.id.clone(),
2251 pr: d.target.pr.clone(),
2252 agent: agent.to_owned(),
2253 context: format!(
2254 "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2255 d.target.pr,
2256 state.id,
2257 serde_json::to_string(&state.reviews).unwrap_or_default()
2258 ),
2259 };
2260 task.requeue();
2261 task.pr_recovery = None;
2262 task.review_of = None;
2263 task.replacement = Some(replacement);
2264 } else {
2265 task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2266 format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2267 } else { format!("PR closure was not confirmed. Task held; inspect the existing run before starting replacement work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str())) }));
2268 }
2269 task.mark_action_applied(&d.question);
2270 if d.choice.eq_ignore_ascii_case(land::HOLD) {
2271 task.decision_effects
2272 .insert(d.question.clone(), format!("decision: {}", d.choice));
2273 }
2274 if let Some(pass) = state.passes.last() {
2275 task.record_pass_at(
2276 &state.id,
2277 pass.index,
2278 Some(pass.started_at),
2279 task.attempts,
2280 None,
2281 );
2282 }
2283 return;
2284 }
2285 if let Some(replacement) = &task.replacement
2286 && !state.parked
2287 && state.resource_block.is_none()
2288 && (state.viable().is_empty()
2289 || (state.status == RunStatus::Blocked && state.tally.is_none()))
2290 {
2291 task.hold_manual(Some(format!("Selected implementer `{}` was unavailable, failed or hit quota before producing a viable implementation. No other implementer was dispatched. Inspect the run, restore availability, then explicitly release this task.", replacement.agent)));
2292 return;
2293 }
2294 if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2295 let mut agents: Vec<_> = state
2296 .quota
2297 .iter()
2298 .filter(|q| {
2299 q.cause == crate::agent::QuotaCause::Authentication
2300 && state
2301 .passes
2302 .last()
2303 .is_none_or(|pass| q.at >= pass.started_at)
2304 })
2305 .map(|q| q.agent.as_str())
2306 .collect();
2307 agents.sort_unstable();
2308 agents.dedup();
2309 if !agents.is_empty() {
2310 task.stall(detail);
2311 task.notice_cause("agent-authentication", None, None);
2312 task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2313 return;
2314 }
2315 }
2316 let attempts_before = task.attempts;
2317 if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2324 let disk_checked_at = task.disk_checked_at;
2325 task.notice_cause(
2326 &format!("resource:{}:{}", block.kind, block.node),
2327 None,
2328 None,
2329 );
2330 task.last_error = Some(detail.to_owned());
2331 task.diagnostic = None;
2332 task.attempts = task.attempts.saturating_sub(1);
2333 if block.kind == "agent authentication" {
2334 task.hold_machine(Some(format!(
2335 "[authentication] {}; no attempt was spent",
2336 block.detail
2337 )));
2338 } else if block.kind == "agent usage limit" {
2339 if let Some(agent) = &state.config.graph.selected_implementer {
2341 task.hold_machine(Some(format!("[agent usage limit] Selected implementer `{agent}` is unavailable. No other implementer was dispatched; resume after usage is available. No attempt was spent.")));
2342 } else {
2343 task.status = TaskStatus::Failed;
2344 task.last_error = Some(block.detail.clone());
2345 }
2346 } else if block.kind == "disk pressure" {
2347 task.hold_machine(Some(format!(
2348 "{}{}",
2349 crate::disk::RUNNING_PRESSURE,
2350 block.detail
2351 )));
2352 } else {
2353 task.hold_machine(Some(format!(
2354 "{}{}; no attempt was spent; resume to retry the affected operation",
2355 crate::cache::RESOURCE_HOLD,
2356 block.description()
2357 )));
2358 }
2359 if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2360 && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2361 {
2362 task.mark_disk_capacity();
2363 task.disk_checked_at = disk_checked_at;
2364 }
2365 if let Some(pass) = state.passes.last() {
2366 task.record_pass_at(
2367 &state.id,
2368 pass.index,
2369 Some(pass.started_at),
2370 attempts_before,
2371 None,
2372 );
2373 }
2374 return;
2375 }
2376 if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2377 state.parked
2378 && state.status == RunStatus::Landing
2379 && state
2380 .pr_pushed_head
2381 .as_ref()
2382 .is_none_or(|h| h == &hold.head)
2383 && task.execution_runs().last() == Some(&state.id)
2384 }) {
2385 let pass = state.passes.last().map_or(0, |p| p.index);
2388 if !task
2389 .passes
2390 .iter()
2391 .any(|p| p.run == state.id && p.pass_index == pass)
2392 {
2393 task.attempts = task.attempts.saturating_sub(1);
2394 }
2395 task.hold_machine(Some(format!(
2396 "[ci-unrelated] CI failure reproduced on base; owner question {}",
2397 hold.question
2398 )));
2399 task.last_error = Some(detail.to_owned());
2400 task.diagnostic = None;
2401 task.record_pass_at(
2402 &state.id,
2403 pass,
2404 state.passes.last().map(|p| p.started_at),
2405 attempts_before,
2406 Some(crate::run::ParkCause::Question),
2407 );
2408 return;
2409 }
2410 let unresolved = task.hold_notice_cause.clone();
2411 let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2412 .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2413 let mut reconsumed_head_e2e = false;
2414 if state.base_sync_blocked() {
2415 task.hold_machine(Some(detail.to_owned()));
2417 task.last_error = Some(detail.to_owned());
2418 } else if state.land_sync_exhausted() {
2419 task.hold_machine(Some(format!("{detail} {}", state.land_sync_next_action())));
2420 task.last_error = Some(detail.to_owned());
2421 } else if !verdict.parked
2422 && task
2423 .pr_recovery
2424 .as_ref()
2425 .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2426 && matches!(
2427 verdict.status,
2428 RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2429 )
2430 {
2431 if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2432 task.succeed(CompletionContext::from_run(
2433 CompletionActor::DaemonSettle,
2434 Some(detail.to_owned()),
2435 task,
2436 state,
2437 ));
2438 } else {
2439 task.hold_manual(Some("Selected PR delivery is incomplete: local review or publication is not a confirmed public merge. Inspect the run and PR; use recover-pr --disposition land with --source-head <reviewed-full-SHA> and the required verification configuration. No automatic new attempt will start.".into()));
2440 }
2441 } else if !verdict.parked
2442 && task.pr_recovery.is_some()
2443 && matches!(
2444 verdict.status,
2445 RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2446 )
2447 && !verdict.quota_hit
2448 {
2449 task.hold_unrequested_retry(Some(format!("Selected recovery stopped: {detail}. Inspect the retained source and run; correct the cause before explicitly releasing or selecting again. No automatic replacement will start.")));
2450 } else if let Some(stop) = head_e2e_stop.clone() {
2451 if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2456 reconsumed_head_e2e = true;
2457 let pass = state.passes.last().map_or(0, |p| p.index);
2458 if !task
2459 .passes
2460 .iter()
2461 .any(|p| p.run == state.id && p.pass_index == pass)
2462 {
2463 task.attempts = task.attempts.saturating_sub(1);
2464 }
2465 }
2466 let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2467 task.hold_head_e2e(stop, reason, detail.to_owned());
2468 } else {
2469 settle_in(task, verdict, detail, max_attempts, p, Some(state));
2470 }
2471 if !verdict.parked
2472 && !verdict.quota_hit
2473 && !reconsumed_head_e2e
2474 && matches!(
2475 verdict.status,
2476 RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2477 )
2478 {
2479 task.recovery_failed(state);
2480 }
2481 if state.prep_failure.is_some() {
2482 task.hold_notice_cause = unresolved;
2485 task.startup_notice_cause("startup-candidates");
2486 }
2487 if let Some(pass) = state.passes.last() {
2490 let parked = match &pass.end {
2491 Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2492 _ => None,
2493 };
2494 task.record_pass_at(
2495 &state.id,
2496 pass.index,
2497 Some(pass.started_at),
2498 attempts_before,
2499 parked,
2500 );
2501 }
2502 if task.status == TaskStatus::Held {
2503 if state.base_sync_blocked() {
2504 task.base_sync_notice(state);
2505 } else if state.land_sync_exhausted() {
2506 task.land_sync_notice(state);
2507 } else if let Some(stop) = &head_e2e_stop {
2508 task.head_e2e_notice(stop);
2509 } else if state.prep_failure.is_none() {
2510 task.notice_cause(
2511 label(verdict.status),
2512 Some(&state.id),
2513 state.passes.last().map(|p| p.index),
2514 );
2515 }
2516 task.diagnostic = diagnostic(state);
2517 note_open_question(task, &state.id, p);
2518 }
2519}
2520
2521fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2536 let Some(home) = crate::run::try_home() else {
2537 return;
2538 };
2539 let open = Questions::at(home.join("questions")).open_for(run);
2540 let Some(q) = open.first() else {
2541 return;
2542 };
2543 let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2544 decisions.sort_unstable();
2545 task.notice_cause(
2546 &format!("questions:{}", decisions.join(",")),
2547 Some(run),
2548 None,
2549 );
2550 let base = task.hold_reason.clone().unwrap_or_default();
2551 task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2552}
2553
2554fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2565 if let Some(request) = task.sync_only.clone() {
2566 crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2567 return;
2568 }
2569 match last_run {
2570 Some(state) => {
2571 let verdict = Verdict {
2572 status: state.status,
2573 left_pr: state.pr.is_some(),
2574 quota_hit: state.quota.iter().any(|loss| {
2575 state
2576 .passes
2577 .last()
2578 .is_none_or(|pass| loss.at >= pass.started_at)
2579 }),
2580 parked: state.parked,
2581 no_viable_candidates: state.viable().is_empty(),
2582 };
2583 let detail = format!(
2584 "{}{}",
2585 phrases(&state.config.graph.language).recovered_running,
2586 describe(&state)
2587 );
2588 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2589 }
2590 None => {
2591 let why = phrases(language).no_run_to_recover;
2594 task.last_error = Some(why.to_owned());
2595 task.notice_cause("missing-run", None, None);
2598 task.hold_machine(Some(why.to_owned()));
2599 }
2600 }
2601}
2602
2603fn reclaim_orphaned_running(
2625 queue: &Queue,
2626 max_attempts: usize,
2627 live_workers: &std::collections::BTreeSet<String>,
2628) -> Vec<String> {
2629 let mut reclaimed = Vec::new();
2630 for listed in queue.list() {
2631 if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2632 continue;
2633 }
2634 let Ok(_claim) = queue.claim(&listed.id) else {
2635 continue;
2636 };
2637 let Ok(mut task) = queue.get(&listed.id) else {
2641 continue;
2642 };
2643 if task.status != TaskStatus::Running {
2644 continue;
2645 }
2646 let last_run = task
2647 .execution_runs()
2648 .last()
2649 .and_then(|id| RunState::load(id).ok());
2650 if let Some(state) = &last_run
2660 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2661 {
2662 tracing::warn!("abandon questions for {}: {e:#}", state.id);
2663 }
2664 let language = if last_run.is_none() {
2665 language_of(&task, Path::new("."))
2666 } else {
2667 String::new()
2668 };
2669 reclaim(&mut task, last_run, max_attempts, &language);
2670 if task.status == TaskStatus::Done {
2671 supersede_prior_runs(&task, &crate::run::home());
2672 }
2673 record(queue, &mut task);
2674 reclaimed.push(task.id.clone());
2675 }
2676 reclaimed
2677}
2678
2679fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2711 reclaim_abandoned_runs_with(
2712 home,
2713 now,
2714 crate::proc::pid_status,
2715 crate::proc::process_started_at,
2716 )
2717}
2718
2719fn reclaim_abandoned_runs_with<F, G>(
2725 home: &Path,
2726 now: Timestamp,
2727 query: F,
2728 identity: G,
2729) -> Vec<String>
2730where
2731 F: Fn(u32) -> Option<bool>,
2732 G: Fn(u32) -> Option<String>,
2733{
2734 let mut abandoned = Vec::new();
2735 for entry in std::fs::read_dir(home.join("runs"))
2736 .into_iter()
2737 .flatten()
2738 .flatten()
2739 {
2740 let id = entry.file_name().to_string_lossy().into_owned();
2741 if !crate::run::is_run_id(&id) {
2742 continue;
2743 }
2744 let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2747 continue;
2748 };
2749 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2757 continue;
2758 };
2759 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2760 continue;
2761 };
2762 if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2763 continue;
2764 }
2765 let daemon_claims = is_working_on(home, &id, now);
2777 if state.liveness_under_with(home, daemon_claims, &query, &identity)
2778 != crate::run::Liveness::Dead
2779 {
2780 continue;
2781 }
2782 state.abandon("daemon");
2783 if let Err(e) = state.save_under(home) {
2784 tracing::warn!("could not persist abandoned run {id}: {e:#}");
2785 continue;
2786 }
2787 if let Some(notice) = notices::run_ended(&state) {
2790 notices::raise_in(home, notice);
2791 }
2792 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2800 tracing::warn!("abandon questions for {id}: {e:#}");
2801 }
2802 abandoned.push(id);
2803 }
2804 abandoned
2805}
2806
2807#[derive(Debug, Clone, Serialize, Deserialize)]
2808struct TaskWorker {
2809 opts: Opts,
2810 queue: PathBuf,
2811 task: String,
2812 #[serde(default)]
2813 lane: PermitKind,
2814 #[serde(default)]
2815 standalone: bool,
2816}
2817
2818#[doc(hidden)]
2819pub struct TaskWorkerLease {
2820 pub job: crate::worker::Job,
2821 dir: PathBuf,
2822 lease: Option<crate::worker::Lease>,
2823}
2824
2825impl TaskWorkerLease {
2826 pub fn release_lease(&mut self) {
2827 self.lease = None;
2828 }
2829}
2830
2831impl Drop for TaskWorkerLease {
2832 fn drop(&mut self) {
2833 self.release_lease();
2834 let _ = std::fs::remove_dir_all(&self.dir);
2835 }
2836}
2837
2838#[doc(hidden)]
2840pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2841 let request = TaskWorker {
2842 opts: Opts::default(),
2843 queue: home.join("queue"),
2844 task: task.to_owned(),
2845 lane: PermitKind::default(),
2846 standalone: true,
2847 };
2848 let (job, lease) = crate::worker::running_fixture(
2849 home,
2850 &format!("task:{task}"),
2851 serde_json::to_value(request)?,
2852 )?;
2853 Ok(TaskWorkerLease {
2854 dir: home.join("workers").join("jobs").join(&job.id),
2855 job,
2856 lease: Some(lease),
2857 })
2858}
2859
2860fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2861 Ok(crate::worker::active(home)?
2862 .into_iter()
2863 .filter(|job| job.kind == "task")
2864 .collect())
2865}
2866
2867fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2868 task_jobs(home)?
2869 .into_iter()
2870 .filter_map(
2871 |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2872 Ok(request) if !request.standalone => Some(Ok(job)),
2873 Ok(_) => None,
2874 Err(error) => Some(Err(error.into())),
2875 },
2876 )
2877 .collect()
2878}
2879
2880#[must_use]
2882pub fn managed(home: &Path) -> bool {
2883 match crate::worker::active(home) {
2884 Err(error) => {
2885 tracing::error!("cannot determine scheduler ownership: {error:#}");
2886 true
2887 }
2888 Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2889 Ok(_) => {
2890 read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2891 && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2892 }
2893 }
2894}
2895
2896pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2898 anyhow::ensure!(
2899 crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2900 "the scheduler is stopping; wait for retirement before starting it again"
2901 );
2902 crate::worker::spawn(
2903 home,
2904 "scheduler",
2905 "scheduler",
2906 serde_json::to_value(opts.absolute()?)?,
2907 )
2908 .await
2909}
2910
2911fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2912 home.join("worker-parks").join(format!("{}.json", job.id))
2913}
2914
2915fn request_task_park(
2916 home: &Path,
2917 job: &crate::worker::Job,
2918 cause: crate::run::ParkCause,
2919) -> Result<()> {
2920 let path = park_request_path(home, job);
2921 std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2922 std::fs::write(path, serde_json::to_vec(&cause)?)?;
2923 crate::worker::request(home, &job.key, crate::worker::Control::Park)
2924}
2925
2926pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2928 if control == crate::worker::Control::Park {
2929 for job in owned_task_jobs(home)? {
2930 request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2931 }
2932 }
2933 crate::worker::request(home, "scheduler", control)
2934}
2935
2936pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2938 if let Some(job) = crate::worker::active(home)?
2939 .into_iter()
2940 .find(|job| job.kind == "scheduler")
2941 {
2942 return serde_json::from_value(job.payload)
2943 .context("read detached scheduler options")
2944 .map(Some);
2945 }
2946 if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2947 && crate::worker::try_lease(home, "scheduler")?.is_none()
2948 {
2949 let path = home.join("scheduler-options.json");
2950 let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2951 return serde_json::from_slice(&body)
2952 .context("decode detached scheduler options")
2953 .map(Some);
2954 }
2955 Ok(None)
2956}
2957
2958pub async fn restart_detached(home: &Path) -> Result<()> {
2960 let Some(opts) = scheduler_restart_options(home)? else {
2961 return Ok(());
2962 };
2963 request_control(home, crate::worker::Control::Stop)?;
2964 loop {
2965 let reserved = crate::worker::active(home)?
2966 .iter()
2967 .any(|job| job.kind == "scheduler");
2968 if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2969 break;
2970 }
2971 tokio::time::sleep(Duration::from_millis(100)).await;
2972 }
2973 spawn_detached(home, &opts).await?;
2974 Ok(())
2975}
2976
2977pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2979 let opts: Opts = serde_json::from_value(payload)?;
2980 let _ = home;
2981 serve_until(opts, Stop::new()).await
2982}
2983
2984pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2986 let request: TaskWorker = serde_json::from_value(payload)?;
2987 let queue = Queue::at(request.queue);
2988 let key = format!("task:{}", request.task);
2989 let job = task_jobs(home)?
2990 .into_iter()
2991 .find(|job| job.key == key)
2992 .context("task worker reservation is missing")?;
2993 let park_path = park_request_path(home, &job);
2994 let _claim = loop {
2997 match queue.claim(&request.task) {
2998 Ok(claim) => break claim,
2999 Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
3002 return Err(e.context("claim the task for its worker"));
3003 }
3004 Err(_) => {
3005 sweep_stale_claims(&queue, STALE_CLAIM);
3006 tokio::time::sleep(Duration::from_millis(50)).await;
3007 }
3008 }
3009 };
3010 let mut task = queue.get(&request.task)?;
3011 if !task.status.runnable()
3012 || (!request.standalone
3013 && request.lane
3014 != permit_kind(
3015 land_resume_state(&task) == LandResume::Ready,
3016 task.immediate,
3017 task.urgent,
3018 ))
3019 {
3020 return Ok(());
3021 }
3022 let stop = Stop::new();
3023 let watcher = {
3024 let home = home.to_path_buf();
3025 let stop = stop.clone();
3026 let park_path = park_path.clone();
3027 tokio::spawn(async move {
3028 loop {
3029 if crate::worker::control(&home, &key).ok().flatten().is_some() {
3030 let cause = std::fs::read(&park_path)
3031 .ok()
3032 .and_then(|body| serde_json::from_slice(&body).ok())
3033 .unwrap_or(crate::run::ParkCause::Operator);
3034 stop.park(cause);
3035 return;
3036 }
3037 tokio::time::sleep(Duration::from_millis(200)).await;
3038 }
3039 })
3040 };
3041 let quota = if request.standalone {
3042 run_claimed_until(&request.opts, &queue, &mut task, &stop).await
3043 } else {
3044 let status = Arc::new(Mutex::new(Status::new()));
3045 Box::pin(attempt(
3046 &request.opts,
3047 &queue,
3048 &status,
3049 &stop,
3050 crate::graph::Pause::new(),
3051 &mut task,
3052 ))
3053 .await
3054 };
3055 watcher.abort();
3056 let _ = std::fs::remove_file(park_path);
3057 persist_cooldown(home, "a).await?;
3058 Ok(())
3059}
3060
3061pub async fn spawn_claimed(
3064 home: &Path,
3065 opts: &Opts,
3066 queue: &Queue,
3067 task: &Task,
3068 claim: crate::queue::Claim,
3069) -> Result<crate::worker::Job> {
3070 let request = TaskWorker {
3071 opts: opts.absolute()?,
3072 queue: std::path::absolute(queue.root())?,
3073 task: task.id.clone(),
3074 lane: permit_kind(
3075 land_resume_state(task) == LandResume::Ready,
3076 task.immediate,
3077 task.urgent,
3078 ),
3079 standalone: true,
3080 };
3081 let job = crate::worker::spawn(
3082 home,
3083 "task",
3084 &format!("task:{}", task.id),
3085 serde_json::to_value(request)?,
3086 )
3087 .await?;
3088 drop(claim);
3089 Ok(job)
3090}
3091
3092pub async fn run_detached_claimed(
3095 opts: &Opts,
3096 queue: &Queue,
3097 task: &mut Task,
3098 claim: crate::queue::Claim,
3099) -> Result<()> {
3100 let home = crate::run::home();
3101 let job = spawn_claimed(&home, opts, queue, task, claim).await?;
3102 loop {
3103 crate::worker::active(&home)?;
3106 let current = crate::worker::get(&home, &job.id)?;
3107 if matches!(
3108 current.status,
3109 crate::worker::Status::Finished | crate::worker::Status::Failed
3110 ) {
3111 *task = queue.get(&task.id)?;
3112 anyhow::ensure!(
3113 current.status != crate::worker::Status::Failed,
3114 "task worker failed: {}",
3115 current.result.as_deref().unwrap_or("unknown failure")
3116 );
3117 return Ok(());
3118 }
3119 tokio::time::sleep(Duration::from_millis(200)).await;
3120 }
3121}
3122
3123async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
3124 if let Some(until) = cooldown_until(quota, Timestamp::now()) {
3125 let _lease = loop {
3126 if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
3127 break lease;
3128 }
3129 tokio::time::sleep(Duration::from_millis(10)).await;
3130 };
3131 if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3132 let path = home.join("task-quota-cooldown.json");
3133 let temporary = path.with_extension("json.tmp");
3134 std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3135 std::fs::rename(temporary, path)?;
3136 }
3137 }
3138 Ok(())
3139}
3140
3141fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3142 match std::fs::read(home.join("task-quota-cooldown.json")) {
3143 Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3144 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3145 Err(error) => Err(error.into()),
3146 }
3147}
3148
3149pub async fn serve(opts: Opts) -> Result<()> {
3155 tracing::info!(
3156 "automatic update and restart requires magi web; standalone serve does not restart"
3157 );
3158 serve_until(opts, Stop::new()).await
3159}
3160
3161pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3172 let opts = opts.absolute()?;
3173 let home = crate::run::home();
3174 let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3175 .context("another scheduler already owns this home")?;
3176 if let Some(reading) = read_status(&home)
3177 && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3178 {
3179 bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3180 }
3181 if !crate::worker::active(&home)?
3182 .iter()
3183 .any(|job| job.kind == "scheduler")
3184 {
3185 crate::worker::clear_control(&home, "scheduler")?;
3186 }
3187 std::fs::write(
3188 home.join("scheduler-options.json"),
3189 serde_json::to_vec(&opts)?,
3190 )?;
3191 let control = {
3192 let home = home.clone();
3193 let stop = stop.clone();
3194 tokio::spawn(async move {
3195 loop {
3196 match crate::worker::control(&home, "scheduler").ok().flatten() {
3197 Some(crate::worker::Control::Park) => {
3198 let _ = request_control(&home, crate::worker::Control::Park);
3199 stop.park(crate::run::ParkCause::Operator);
3200 break;
3201 }
3202 Some(crate::worker::Control::Stop) => {
3203 stop.stop();
3204 break;
3205 }
3206 None => {}
3207 }
3208 tokio::time::sleep(Duration::from_millis(100)).await;
3209 }
3210 })
3211 };
3212 let signal = {
3213 let stop = stop.clone();
3214 tokio::spawn(async move {
3215 if tokio::signal::ctrl_c().await.is_ok() {
3216 stop.stop();
3217 tracing::info!("scheduler shutdown requested; independent workers continue");
3218 }
3219 })
3220 };
3221
3222 let worktrees_root = opts
3223 .worktrees_root
3224 .clone()
3225 .unwrap_or_else(crate::run::default_worktree_root);
3226 let outcome = drive(
3227 &opts,
3228 &Queue::open(),
3229 &status_path(),
3230 &crate::run::home(),
3231 &worktrees_root,
3232 &stop,
3233 )
3234 .await;
3235
3236 signal.abort();
3237 control.abort();
3238 outcome
3239}
3240
3241async fn drive(
3254 opts: &Opts,
3255 queue: &Queue,
3256 status_file: &Path,
3257 home: &Path,
3258 worktrees_root: &Path,
3259 stop: &Stop,
3260) -> Result<()> {
3261 let recovery_cfg = prepare(&opts.repo, opts).ok();
3269 let daemon_cfg = recovery_cfg
3270 .as_ref()
3271 .map(|c| c.daemon.clone())
3272 .unwrap_or_default();
3273 let reconciled = crate::driver::reconcile(home);
3274 if !reconciled.is_empty() {
3275 tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3276 }
3277 let mut initial_status = Status::new();
3278 let owned = owned_task_jobs(home)?;
3279 initial_status.current = current_work(home, Timestamp::now())
3280 .into_iter()
3281 .filter(|current| {
3282 owned
3283 .iter()
3284 .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3285 })
3286 .collect();
3287 initial_status.idle = initial_status.current.is_empty();
3288 initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3289 recovery_cfg.as_ref(),
3290 daemon_cfg.max_deputies,
3291 ));
3292 let status = Arc::new(Mutex::new(initial_status));
3293 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3294 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3295
3296 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3302
3303 tracing::info!(
3304 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3305 queue.root().display(),
3306 opts.poll.as_secs(),
3307 opts.max_attempts,
3308 concurrency,
3309 if daemon_cfg.pause_for_interrupts {
3310 ", interrupts enabled"
3311 } else {
3312 ""
3313 }
3314 );
3315
3316 let outcome = tokio::select! {
3317 outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3318 max_concurrent: concurrency,
3319 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3320 recovery_cfg,
3321 }) => outcome,
3322 () = async {
3323 while !stop.stopped() {
3324 tokio::time::sleep(Duration::from_millis(25)).await;
3325 }
3326 } => {
3327 if stop.parking() {
3328 request_control(home, crate::worker::Control::Park)?;
3329 }
3330 Ok(())
3331 }
3332 };
3333
3334 stop.busy.store(0, Ordering::SeqCst);
3335 beat.abort();
3336 clear_status_at(status_file);
3337 outcome
3338}
3339
3340pub(crate) fn release_watch_settings_from_config(
3343 home: &Path,
3344 repo: &Path,
3345 cfg: &Config,
3346) -> (Vec<PathBuf>, u64) {
3347 let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3348 .into_iter()
3349 .map(|r| r.path)
3350 .collect();
3351 let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3354 .list()
3355 .into_iter()
3356 .map(|t| t.repo)
3357 .collect();
3358 let runs = home.join("runs");
3359 for id in crate::run::list_ids_in(&runs) {
3360 let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3361 .ok()
3362 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3363 .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3364 known.extend(repo);
3365 }
3366 for k in known {
3367 let k = k.canonicalize().unwrap_or(k);
3368 if k.join(".git").exists() && !paths.contains(&k) {
3369 paths.push(k);
3370 }
3371 }
3372 let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3373 if !paths.contains(&own) {
3374 paths.push(own);
3375 }
3376 (paths, cfg.daemon.release_stall_minutes)
3377}
3378
3379const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3381
3382async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3388 loop {
3389 tokio::time::sleep(HEARTBEAT).await;
3390 let snapshot = {
3391 let mut guard = lock(&status);
3392 guard.updated_at = Timestamp::now();
3393 guard.clone()
3394 };
3395 if let Err(e) = write_status_to(&path, &snapshot) {
3396 tracing::warn!("could not refresh the daemon status file: {e:#}");
3399 }
3400 }
3401}
3402
3403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3406enum LandResume {
3407 NotLanding,
3410 StillWaiting,
3415 Ready,
3419}
3420
3421fn land_resume_state(task: &Task) -> LandResume {
3425 if task.sync_only.is_some() {
3426 return LandResume::NotLanding;
3427 }
3428 let Some(run_id) = task.execution_runs().last() else {
3429 return LandResume::NotLanding;
3430 };
3431 let Ok(state) = RunState::load(run_id) else {
3432 return LandResume::NotLanding;
3433 };
3434 if !state.parked {
3435 return LandResume::NotLanding;
3436 }
3437 if state.status == RunStatus::Landing
3438 && state.land_approval.as_ref().is_some_and(|binding| {
3439 ask::Questions::open()
3440 .get_for_effects(&binding.question)
3441 .is_ok_and(|q| {
3442 q.run == state.id
3443 && q.resolution()
3444 .as_deref()
3445 .is_some_and(crate::merge_decision::stops)
3446 })
3447 })
3448 {
3449 return LandResume::Ready;
3450 }
3451 if !implementers_match(task, &state) {
3452 return LandResume::NotLanding;
3453 }
3454 let node = if state.status == RunStatus::Landing {
3458 land::APPROVAL_NODE
3459 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3460 crate::github_text::ASK_NODE
3461 } else {
3462 return LandResume::NotLanding;
3463 };
3464 let store = ask::Questions::open();
3465 let waiting = store
3466 .list_for_effects()
3467 .into_iter()
3468 .filter(|q| &q.run == run_id && q.node == node)
3469 .max_by(|a, b| a.id.cmp(&b.id));
3470 let Some(mut q) = waiting else {
3471 return LandResume::Ready;
3472 };
3473 if !q.status.open() {
3474 if q.resolution().as_deref() == Some(land::REPAIR) {
3477 return if state.liveness(false) == Liveness::Live {
3478 LandResume::StillWaiting
3479 } else {
3480 LandResume::NotLanding
3481 };
3482 }
3483 return LandResume::Ready;
3484 }
3485 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3492 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3493 if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3494 q.abandon(format!(
3495 "no answer within {}s of asking",
3496 timeout.as_secs().max(1)
3497 ));
3498 if store.put(&mut q).is_ok() {
3501 return LandResume::Ready;
3502 }
3503 }
3504 LandResume::StillWaiting
3505}
3506
3507const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3515
3516const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3528
3529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3542enum Interrupt {
3543 Idle,
3545 Parking {
3557 parked: Vec<String>,
3558 interrupt_task: String,
3559 },
3560 Running {
3568 parked: Vec<String>,
3569 interrupt_task: String,
3570 },
3571 Resuming { parked: Vec<String> },
3578}
3579
3580fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3601 match state {
3602 Interrupt::Idle => {
3603 if in_flight.len() != 1 {
3615 return Interrupt::Idle;
3616 }
3617 match runnable.iter().find(|t| t.interrupt) {
3618 Some(t) => Interrupt::Parking {
3619 parked: in_flight.to_vec(),
3620 interrupt_task: t.id.clone(),
3621 },
3622 None => Interrupt::Idle,
3623 }
3624 }
3625 Interrupt::Parking {
3626 parked,
3627 interrupt_task,
3628 } => {
3629 if in_flight.iter().any(|id| parked.contains(id)) {
3630 Interrupt::Parking {
3632 parked,
3633 interrupt_task,
3634 }
3635 } else if in_flight.contains(&interrupt_task) {
3636 Interrupt::Running {
3637 parked,
3638 interrupt_task,
3639 }
3640 } else if runnable.iter().any(|t| t.id == interrupt_task) {
3641 Interrupt::Parking {
3645 parked,
3646 interrupt_task,
3647 }
3648 } else {
3649 Interrupt::Resuming { parked }
3654 }
3655 }
3656 Interrupt::Running {
3657 parked,
3658 interrupt_task,
3659 } => {
3660 if in_flight.contains(&interrupt_task) {
3661 Interrupt::Running {
3662 parked,
3663 interrupt_task,
3664 }
3665 } else {
3666 Interrupt::Resuming { parked }
3672 }
3673 }
3674 Interrupt::Resuming { parked } => {
3675 if in_flight.iter().any(|id| parked.contains(id)) {
3676 Interrupt::Idle
3682 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3683 Interrupt::Resuming { parked }
3684 } else {
3685 Interrupt::Idle
3688 }
3689 }
3690 }
3691}
3692
3693fn advance_interrupt_tick(
3699 enabled: bool,
3700 state: Interrupt,
3701 in_flight: &[String],
3702 runnable: &[Task],
3703) -> Interrupt {
3704 if !enabled {
3705 return Interrupt::Idle;
3706 }
3707 advance_interrupt(state, in_flight, runnable)
3708}
3709
3710fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3715 match state {
3716 Interrupt::Idle => candidates,
3717 Interrupt::Parking {
3718 parked,
3719 interrupt_task,
3720 } => {
3721 if in_flight.iter().any(|id| parked.contains(id)) {
3722 Vec::new()
3723 } else {
3724 candidates
3725 .into_iter()
3726 .filter(|t| &t.id == interrupt_task)
3727 .collect()
3728 }
3729 }
3730 Interrupt::Running { .. } => Vec::new(),
3731 Interrupt::Resuming { parked } => candidates
3739 .into_iter()
3740 .find(|t| parked.contains(&t.id))
3741 .into_iter()
3742 .collect(),
3743 }
3744}
3745
3746struct DispatchLimits {
3750 max_concurrent: usize,
3753 pause_for_interrupts: bool,
3755 recovery_cfg: Option<Config>,
3756}
3757
3758#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3766pub(crate) enum PermitKind {
3767 None,
3772 Immediate,
3779 Urgent,
3786 #[default]
3789 Ordinary,
3790}
3791
3792impl PermitKind {
3793 pub(crate) fn label(self) -> &'static str {
3794 match self {
3795 Self::None => "decision",
3796 Self::Immediate => "immediate",
3797 Self::Urgent => "urgent",
3798 Self::Ordinary => "ordinary",
3799 }
3800 }
3801}
3802
3803fn permit_kind(priority: bool, immediate: bool, urgent: bool) -> PermitKind {
3807 if priority {
3808 PermitKind::None
3809 } else if immediate {
3810 PermitKind::Immediate
3811 } else if urgent {
3812 PermitKind::Urgent
3813 } else {
3814 PermitKind::Ordinary
3815 }
3816}
3817
3818fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3819 let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3820 (0usize, 0usize),
3821 |(ordinary, urgent), request| match request.lane {
3822 PermitKind::Ordinary => (ordinary + 1, urgent),
3823 PermitKind::Urgent => (ordinary, urgent + 1),
3824 PermitKind::Immediate | PermitKind::None => (ordinary, urgent),
3825 },
3826 );
3827 (
3828 limit.saturating_sub(ordinary),
3829 1usize.saturating_sub(urgent),
3830 )
3831}
3832
3833#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3835enum SkipReason {
3836 ClaimUnavailable,
3837 RereadFailed,
3838 NoLongerRunnable,
3839 WaitingOnLanding,
3840 CoolingDown,
3841 OrdinaryCapacity,
3842 UrgentCapacity,
3843 InterruptGate,
3844}
3845
3846impl SkipReason {
3847 fn key(self) -> &'static str {
3848 match self {
3849 Self::ClaimUnavailable => "claim_unavailable",
3850 Self::RereadFailed => "reread_failed",
3851 Self::NoLongerRunnable => "no_longer_runnable",
3852 Self::WaitingOnLanding => "waiting_on_landing",
3853 Self::CoolingDown => "cooling_down",
3854 Self::OrdinaryCapacity => "ordinary_capacity",
3855 Self::UrgentCapacity => "urgent_capacity",
3856 Self::InterruptGate => "interrupt_gate",
3857 }
3858 }
3859
3860 fn describe(self) -> &'static str {
3861 match self {
3862 Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3863 Self::RereadFailed => "could not re-read it",
3864 Self::NoLongerRunnable => "no longer runnable",
3865 Self::WaitingOnLanding => "waiting on landing",
3866 Self::CoolingDown => "quota cooldown",
3867 Self::OrdinaryCapacity => "no free ordinary slot",
3868 Self::UrgentCapacity => "urgent slot busy",
3869 Self::InterruptGate => "withheld by the interrupt sequence",
3870 }
3871 }
3872}
3873
3874#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3876pub struct DispatchReasonCount {
3877 pub reason: String,
3879 pub count: usize,
3881}
3882
3883#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3885pub struct DispatchWait {
3886 pub runnable: usize,
3888 pub reasons: Vec<DispatchReasonCount>,
3890}
3891
3892type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3893
3894fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3895 if runnable == 0 {
3896 return None;
3897 }
3898 let mut counts = std::collections::BTreeMap::new();
3899 for (_, reason) in skips {
3900 *counts.entry(*reason).or_insert(0usize) += 1;
3901 }
3902 let mut counts: Vec<_> = counts.into_iter().collect();
3903 counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3904 Some(DispatchWait {
3905 runnable,
3906 reasons: counts
3907 .into_iter()
3908 .map(|(reason, count)| DispatchReasonCount {
3909 reason: reason.key().to_owned(),
3910 count,
3911 })
3912 .collect(),
3913 })
3914}
3915
3916fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3917 before
3918 .iter()
3919 .filter(|id| !after.iter().any(|task| &task.id == *id))
3920 .map(|id| (id.clone(), SkipReason::InterruptGate))
3921 .collect()
3922}
3923
3924fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3925 if *previous == current {
3926 return false;
3927 }
3928 *previous = current;
3929 true
3930}
3931
3932#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3936pub struct TaskAdmission {
3937 pub mode: &'static str,
3939 #[serde(default, skip_serializing_if = "Option::is_none")]
3942 pub reservation_lane: Option<&'static str>,
3943 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3945 pub standalone: bool,
3946 pub state: &'static str,
3948 pub label: String,
3951 #[serde(default, skip_serializing_if = "Option::is_none")]
3953 pub blocker: Option<String>,
3954}
3955
3956#[derive(Debug, Clone)]
3959pub struct AdmissionSnapshot {
3960 now: Timestamp,
3961 daemon: std::result::Result<Option<Reading>, String>,
3962 scheduler_running: bool,
3963 active_workers:
3964 std::result::Result<std::collections::BTreeMap<String, (PermitKind, bool)>, String>,
3965 owned_in_flight: Vec<String>,
3966 owned_ordinary_count: usize,
3967 urgent_busy: bool,
3968 cache_service_active: bool,
3969 cooldown_until: std::result::Result<Option<Timestamp>, String>,
3970 interrupt: std::result::Result<Interrupt, String>,
3971}
3972
3973fn read_status_checked(home: &Path) -> std::result::Result<Option<Reading>, String> {
3974 let path = home.join("daemon.json");
3975 match std::fs::read_to_string(&path) {
3976 Ok(body) => serde_json::from_str(&body)
3977 .map(Some)
3978 .map_err(|e| format!("parse {}: {e}", path.display())),
3979 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
3980 Err(e) => Err(format!("read {}: {e}", path.display())),
3981 }
3982}
3983
3984fn read_interrupt_checked(home: &Path) -> std::result::Result<Interrupt, String> {
3985 let path = home.join("scheduler-interrupt.json");
3986 match std::fs::read(&path) {
3987 Ok(body) => {
3988 serde_json::from_slice(&body).map_err(|e| format!("parse {}: {e}", path.display()))
3989 }
3990 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Interrupt::Idle),
3991 Err(e) => Err(format!("read {}: {e}", path.display())),
3992 }
3993}
3994
3995fn skip_reason_label(key: &str) -> String {
3996 match key {
3997 "claim_unavailable" => "claimed by another process".to_owned(),
3998 "reread_failed" => "could not re-read task".to_owned(),
3999 "no_longer_runnable" => "no longer runnable".to_owned(),
4000 "waiting_on_landing" => "waiting on merge/posting approval".to_owned(),
4001 "cooling_down" => "quota cooldown".to_owned(),
4002 "ordinary_capacity" => "no free ordinary slot".to_owned(),
4003 "urgent_capacity" => "urgent slot busy".to_owned(),
4004 "interrupt_gate" => "withheld by active interrupt sequence".to_owned(),
4005 other => other.replace('_', " "),
4006 }
4007}
4008
4009fn land_resume_state_readonly(task: &Task, home: &Path, now: Timestamp) -> LandResume {
4012 if task.sync_only.is_some() {
4013 return LandResume::NotLanding;
4014 }
4015 let Some(run_id) = task.execution_runs().last() else {
4016 return LandResume::NotLanding;
4017 };
4018 let Ok(state) = RunState::load_under(run_id, home) else {
4019 return LandResume::NotLanding;
4020 };
4021 if !state.parked {
4022 return LandResume::NotLanding;
4023 }
4024 let store = ask::Questions::at(home.join("questions"));
4025 if state.status == RunStatus::Landing
4026 && state.land_approval.as_ref().is_some_and(|binding| {
4027 store.get_for_effects(&binding.question).is_ok_and(|q| {
4028 q.run == state.id
4029 && q.resolution()
4030 .as_deref()
4031 .is_some_and(crate::merge_decision::stops)
4032 })
4033 })
4034 {
4035 return LandResume::Ready;
4036 }
4037 if !implementers_match(task, &state) {
4038 return LandResume::NotLanding;
4039 }
4040 let node = if state.status == RunStatus::Landing {
4041 land::APPROVAL_NODE
4042 } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
4043 crate::github_text::ASK_NODE
4044 } else {
4045 return LandResume::NotLanding;
4046 };
4047 let waiting = store
4048 .list_for_effects()
4049 .into_iter()
4050 .filter(|q| &q.run == run_id && q.node == node)
4051 .max_by(|a, b| a.id.cmp(&b.id));
4052 let Some(q) = waiting else {
4053 return LandResume::Ready;
4054 };
4055 if !q.status.open() {
4056 if q.resolution().as_deref() == Some(land::REPAIR) {
4057 return if is_working_on(home, &state.id, now) {
4058 LandResume::StillWaiting
4059 } else {
4060 LandResume::NotLanding
4061 };
4062 }
4063 return LandResume::Ready;
4064 }
4065 LandResume::StillWaiting
4066}
4067
4068impl AdmissionSnapshot {
4069 #[must_use]
4071 pub fn capture(home: &Path, now: Timestamp) -> Self {
4072 let daemon = read_status_checked(home);
4073 let scheduler_running = daemon
4074 .as_ref()
4075 .ok()
4076 .and_then(Option::as_ref)
4077 .is_some_and(|reading| reading.running(now));
4078 let mut cache_service_active = false;
4079 let mut owned_in_flight = Vec::new();
4080 let mut owned_ordinary_count = 0usize;
4081 let mut urgent_busy = false;
4082 let active_workers = match crate::worker::observe_active_detailed(home) {
4083 Ok(entries) => {
4084 let mut map = std::collections::BTreeMap::new();
4085 let mut parse_err = None;
4086 for entry in entries {
4087 if entry.job.key == "service:daemon-cache" {
4088 cache_service_active = true;
4089 continue;
4090 }
4091 if entry.job.kind != "task" {
4092 continue;
4093 }
4094 match serde_json::from_value::<TaskWorker>(entry.job.payload) {
4095 Ok(request) => {
4096 if !request.standalone {
4097 owned_in_flight.push(request.task.clone());
4098 match request.lane {
4099 PermitKind::Ordinary => owned_ordinary_count += 1,
4100 PermitKind::Urgent => urgent_busy = true,
4101 PermitKind::Immediate | PermitKind::None => {}
4102 }
4103 }
4104 map.entry(request.task)
4105 .and_modify(|existing: &mut (PermitKind, bool)| {
4106 if existing.1 && !request.standalone {
4107 *existing = (request.lane, request.standalone);
4108 }
4109 })
4110 .or_insert((request.lane, request.standalone));
4111 }
4112 Err(e) => {
4113 parse_err = Some(format!(
4114 "invalid task worker payload for {}: {e}",
4115 entry.job.id
4116 ));
4117 break;
4118 }
4119 }
4120 }
4121 match parse_err {
4122 Some(err) => Err(err),
4123 None => Ok(map),
4124 }
4125 }
4126 Err(e) => Err(format!("{e:#}")),
4127 };
4128 let cooldown_until = read_cooldown(home).map_err(|e| format!("{e:#}"));
4129 let interrupt = read_interrupt_checked(home);
4130 Self {
4131 now,
4132 daemon,
4133 scheduler_running,
4134 active_workers,
4135 owned_in_flight,
4136 owned_ordinary_count,
4137 urgent_busy,
4138 cache_service_active,
4139 cooldown_until,
4140 interrupt,
4141 }
4142 }
4143
4144 fn format_waiting(task: &Task, reason: &str) -> String {
4145 if task.immediate {
4146 format!("Immediate: waiting — {reason}")
4147 } else if task.urgent {
4148 format!("Urgent: waiting — {reason}")
4149 } else {
4150 format!("Waiting — {reason}")
4151 }
4152 }
4153
4154 #[must_use]
4157 pub fn evaluate(
4158 &self,
4159 task: &Task,
4160 queue: &Queue,
4161 inv: Option<&crate::blockers::Inventory>,
4162 home: &Path,
4163 ) -> TaskAdmission {
4164 let mode = if task.immediate {
4165 "immediate"
4166 } else if task.urgent {
4167 "urgent"
4168 } else {
4169 "ordinary"
4170 };
4171
4172 if task.status == TaskStatus::Done {
4173 return TaskAdmission {
4174 mode,
4175 reservation_lane: None,
4176 standalone: false,
4177 state: "completed",
4178 label: "Completed".to_owned(),
4179 blocker: None,
4180 };
4181 }
4182
4183 if let Ok(workers) = &self.active_workers
4184 && let Some(&(lane, standalone)) = workers.get(&task.id)
4185 {
4186 let lane_label = lane.label();
4187 let base = if standalone {
4188 format!("Running (standalone, {lane_label} lane)")
4189 } else {
4190 format!("Running ({lane_label} lane)")
4191 };
4192 let resource_blocker = task
4193 .execution_runs()
4194 .last()
4195 .and_then(|run_id| RunState::load_under(run_id, home).ok())
4196 .and_then(|state| state.resource_wait)
4197 .map(|wait| {
4198 if wait.holder.trim().is_empty() {
4199 format!("waiting for {}", wait.kind)
4200 } else {
4201 format!("waiting for {} ({})", wait.kind, wait.holder)
4202 }
4203 });
4204 let label = match &resource_blocker {
4205 Some(reason) => format!("{base} — {reason}"),
4206 None => base,
4207 };
4208 return TaskAdmission {
4209 mode,
4210 reservation_lane: Some(lane_label),
4211 standalone,
4212 state: "running",
4213 label,
4214 blocker: resource_blocker,
4215 };
4216 }
4217
4218 if task.status == TaskStatus::Running {
4219 if self.active_workers.is_err() {
4220 let reason = "worker state unreadable".to_owned();
4221 return TaskAdmission {
4222 mode,
4223 reservation_lane: None,
4224 standalone: false,
4225 state: "unknown",
4226 label: Self::format_waiting(task, &reason),
4227 blocker: Some(reason),
4228 };
4229 }
4230 return TaskAdmission {
4231 mode,
4232 reservation_lane: None,
4233 standalone: false,
4234 state: "running",
4235 label: "Running".to_owned(),
4236 blocker: None,
4237 };
4238 }
4239
4240 if task.status == TaskStatus::Blocked {
4241 let waits = inv.map(|i| i.waits_on(task)).unwrap_or_default();
4242 let reason = if !waits.is_empty() {
4243 format!("waiting on dependencies ({})", waits.join(", "))
4244 } else if let Some(block_reason) = &task.block_reason {
4245 format!("blocked ({block_reason})")
4246 } else if !task.blocked_by.is_empty() {
4247 let ids: Vec<_> = task
4248 .blocked_by
4249 .iter()
4250 .map(|id| crate::run::short_of(id))
4251 .collect();
4252 format!("waiting on dependencies ({})", ids.join(", "))
4253 } else {
4254 "blocked on unresolved dependencies".to_owned()
4255 };
4256 return TaskAdmission {
4257 mode,
4258 reservation_lane: None,
4259 standalone: false,
4260 state: "waiting",
4261 label: Self::format_waiting(task, &reason),
4262 blocker: Some(reason),
4263 };
4264 }
4265
4266 if task.status == TaskStatus::Held {
4267 let reason = match &task.machine_hold_cause {
4268 Some(crate::queue::MachineHoldCause::DiskCapacity { reason, .. }) => {
4269 format!("disk admission ({reason})")
4270 }
4271 Some(crate::queue::MachineHoldCause::HeadE2e { .. }) => {
4272 let detail = task
4273 .hold_reason
4274 .as_deref()
4275 .unwrap_or("current head verify.e2e failed");
4276 format!("head e2e hold ({detail})")
4277 }
4278 None if task.hold_source == Some(crate::queue::HoldSource::Machine) => {
4279 let detail = task.hold_reason.as_deref().unwrap_or("held by daemon");
4280 if let Some(rest) = detail.strip_prefix("[resource] ") {
4281 format!("resource hold ({rest})")
4282 } else if let Some(rest) = detail.strip_prefix("[config] ") {
4283 format!("config hold ({rest})")
4284 } else {
4285 format!("machine hold ({detail})")
4286 }
4287 }
4288 None => match task.hold_reason.as_deref() {
4289 Some(reason) if !reason.trim().is_empty() => format!("held ({reason})"),
4290 _ => "held (release required)".to_owned(),
4291 },
4292 };
4293 return TaskAdmission {
4294 mode,
4295 reservation_lane: None,
4296 standalone: false,
4297 state: "waiting",
4298 label: Self::format_waiting(task, &reason),
4299 blocker: Some(reason),
4300 };
4301 }
4302
4303 if self.active_workers.is_err() {
4307 let reason = "worker state unreadable".to_owned();
4308 return TaskAdmission {
4309 mode,
4310 reservation_lane: None,
4311 standalone: false,
4312 state: "unknown",
4313 label: Self::format_waiting(task, &reason),
4314 blocker: Some(reason),
4315 };
4316 }
4317
4318 if queue.is_claimed(&task.id) {
4319 let reason = "claimed by another process".to_owned();
4320 return TaskAdmission {
4321 mode,
4322 reservation_lane: None,
4323 standalone: false,
4324 state: "waiting",
4325 label: Self::format_waiting(task, &reason),
4326 blocker: Some(reason),
4327 };
4328 }
4329
4330 if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, task) {
4331 let reason = format!("head e2e stop ({})", hold.reason);
4332 return TaskAdmission {
4333 mode,
4334 reservation_lane: None,
4335 standalone: false,
4336 state: "waiting",
4337 label: Self::format_waiting(task, &reason),
4338 blocker: Some(reason),
4339 };
4340 }
4341
4342 let resume = land_resume_state_readonly(task, home, self.now);
4343 if resume == LandResume::StillWaiting {
4344 let reason = "waiting on merge/posting approval".to_owned();
4345 return TaskAdmission {
4346 mode,
4347 reservation_lane: None,
4348 standalone: false,
4349 state: "waiting",
4350 label: Self::format_waiting(task, &reason),
4351 blocker: Some(reason),
4352 };
4353 }
4354 let priority = resume == LandResume::Ready;
4355 let effective_lane = permit_kind(priority, task.immediate, task.urgent);
4356
4357 match &self.interrupt {
4358 Err(_) => {
4359 let reason = "interrupt state unreadable".to_owned();
4360 return TaskAdmission {
4361 mode,
4362 reservation_lane: None,
4363 standalone: false,
4364 state: "unknown",
4365 label: Self::format_waiting(task, &reason),
4366 blocker: Some(reason),
4367 };
4368 }
4369 Ok(interrupt)
4370 if *interrupt != Interrupt::Idle
4371 && interrupt_gate(interrupt, &self.owned_in_flight, vec![task.clone()])
4372 .is_empty() =>
4373 {
4374 let reason = "withheld by active interrupt sequence".to_owned();
4375 return TaskAdmission {
4376 mode,
4377 reservation_lane: None,
4378 standalone: false,
4379 state: "waiting",
4380 label: Self::format_waiting(task, &reason),
4381 blocker: Some(reason),
4382 };
4383 }
4384 Ok(_) => {}
4385 }
4386
4387 if effective_lane != PermitKind::None {
4388 match &self.cooldown_until {
4389 Err(_) => {
4390 let reason = "quota cooldown state unreadable".to_owned();
4391 return TaskAdmission {
4392 mode,
4393 reservation_lane: None,
4394 standalone: false,
4395 state: "unknown",
4396 label: Self::format_waiting(task, &reason),
4397 blocker: Some(reason),
4398 };
4399 }
4400 Ok(Some(until)) if self.now < *until => {
4401 let secs = (until.as_second() - self.now.as_second()).max(1);
4402 let reason = format!("quota cooldown ({secs}s remaining)");
4403 return TaskAdmission {
4404 mode,
4405 reservation_lane: None,
4406 standalone: false,
4407 state: "waiting",
4408 label: Self::format_waiting(task, &reason),
4409 blocker: Some(reason),
4410 };
4411 }
4412 Ok(_) => {}
4413 }
4414 }
4415
4416 if self.cache_service_active {
4417 let reason = "waiting for cache maintenance service".to_owned();
4418 return TaskAdmission {
4419 mode,
4420 reservation_lane: None,
4421 standalone: false,
4422 state: "waiting",
4423 label: Self::format_waiting(task, &reason),
4424 blocker: Some(reason),
4425 };
4426 }
4427
4428 if self.daemon.is_err() {
4429 let reason = "scheduler status unreadable".to_owned();
4430 return TaskAdmission {
4431 mode,
4432 reservation_lane: None,
4433 standalone: false,
4434 state: "unknown",
4435 label: Self::format_waiting(task, &reason),
4436 blocker: Some(reason),
4437 };
4438 }
4439
4440 if self.scheduler_running
4441 && let Ok(Some(reading)) = &self.daemon
4442 && let Some(skip_key) = reading.dispatch_skips.get(&task.id)
4443 {
4444 let stale_capacity_skip = match effective_lane {
4445 PermitKind::None | PermitKind::Immediate => {
4446 matches!(skip_key.as_str(), "ordinary_capacity" | "urgent_capacity")
4447 }
4448 PermitKind::Urgent => skip_key == "ordinary_capacity",
4449 PermitKind::Ordinary => skip_key == "urgent_capacity",
4450 };
4451 if !stale_capacity_skip {
4452 let reason = skip_reason_label(skip_key);
4453 return TaskAdmission {
4454 mode,
4455 reservation_lane: None,
4456 standalone: false,
4457 state: "waiting",
4458 label: Self::format_waiting(task, &reason),
4459 blocker: Some(reason),
4460 };
4461 }
4462 }
4463
4464 if !self.scheduler_running {
4465 let reason = "scheduler not running".to_owned();
4466 return TaskAdmission {
4467 mode,
4468 reservation_lane: None,
4469 standalone: false,
4470 state: "waiting",
4471 label: Self::format_waiting(task, &reason),
4472 blocker: Some(reason),
4473 };
4474 }
4475
4476 match effective_lane {
4477 PermitKind::Immediate => TaskAdmission {
4478 mode,
4479 reservation_lane: None,
4480 standalone: false,
4481 state: "next_poll",
4482 label: "Immediate: next poll".to_owned(),
4483 blocker: None,
4484 },
4485 PermitKind::None => TaskAdmission {
4486 mode,
4487 reservation_lane: None,
4488 standalone: false,
4489 state: "next_poll",
4490 label: if task.immediate {
4491 "Immediate: next poll".to_owned()
4492 } else {
4493 "Decision resume: next poll".to_owned()
4494 },
4495 blocker: None,
4496 },
4497 PermitKind::Urgent => {
4498 if self.urgent_busy {
4499 let reason = "urgent slot busy".to_owned();
4500 TaskAdmission {
4501 mode,
4502 reservation_lane: None,
4503 standalone: false,
4504 state: "waiting",
4505 label: Self::format_waiting(task, &reason),
4506 blocker: Some(reason),
4507 }
4508 } else {
4509 TaskAdmission {
4510 mode,
4511 reservation_lane: None,
4512 standalone: false,
4513 state: "next_poll",
4514 label: "Urgent: next poll".to_owned(),
4515 blocker: None,
4516 }
4517 }
4518 }
4519 PermitKind::Ordinary => {
4520 if self.owned_ordinary_count == 0 {
4521 TaskAdmission {
4522 mode,
4523 reservation_lane: None,
4524 standalone: false,
4525 state: "next_poll",
4526 label: "Ordinary: next poll".to_owned(),
4527 blocker: None,
4528 }
4529 } else {
4530 TaskAdmission {
4531 mode,
4532 reservation_lane: None,
4533 standalone: false,
4534 state: "waiting",
4535 label: "Queued (ordinary lane)".to_owned(),
4536 blocker: None,
4537 }
4538 }
4539 }
4540 }
4541 }
4542}
4543
4544struct DispatchClaim {
4545 task: Task,
4546 claim: crate::queue::Claim,
4547 lane: PermitKind,
4548 permit: Option<tokio::sync::OwnedSemaphorePermit>,
4549}
4550
4551fn claim_dispatch(
4555 queue: &Queue,
4556 candidate: &Task,
4557 cooling_down: bool,
4558 ordinary: &Arc<tokio::sync::Semaphore>,
4559 urgent: &Arc<tokio::sync::Semaphore>,
4560) -> std::result::Result<DispatchClaim, SkipReason> {
4561 let claim = queue
4562 .claim(&candidate.id)
4563 .map_err(|_| SkipReason::ClaimUnavailable)?;
4564 let task = match queue.get(&candidate.id) {
4565 Ok(t) if t.status.runnable() => t,
4566 Ok(_) => return Err(SkipReason::NoLongerRunnable),
4567 Err(e) => {
4568 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
4569 return Err(SkipReason::RereadFailed);
4570 }
4571 };
4572 if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
4573 let mut held = task;
4574 hold.apply(&mut held);
4575 record(queue, &mut held);
4576 return Err(SkipReason::NoLongerRunnable);
4577 }
4578 let resume = land_resume_state(&task);
4579 if resume == LandResume::StillWaiting {
4580 return Err(SkipReason::WaitingOnLanding);
4581 }
4582 let priority = resume == LandResume::Ready;
4583 if !priority && cooling_down {
4584 return Err(SkipReason::CoolingDown);
4585 }
4586 let lane = permit_kind(priority, task.immediate, task.urgent);
4590 let permit = match lane {
4591 PermitKind::None | PermitKind::Immediate => None,
4592 PermitKind::Urgent => Some(
4593 Arc::clone(urgent)
4594 .try_acquire_owned()
4595 .map_err(|_| SkipReason::UrgentCapacity)?,
4596 ),
4597 PermitKind::Ordinary => Some(
4598 Arc::clone(ordinary)
4599 .try_acquire_owned()
4600 .map_err(|_| SkipReason::OrdinaryCapacity)?,
4601 ),
4602 };
4603 let stamp = Timestamp::now();
4606 let mut task = task;
4607 task.dispatched_at = Some(stamp);
4608 if let Err(e) = queue.modify(&task.id, |t| {
4609 t.dispatched_at = Some(stamp);
4610 true
4611 }) {
4612 tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
4613 }
4614 Ok(DispatchClaim {
4615 task,
4616 claim,
4617 lane,
4618 permit,
4619 })
4620}
4621
4622#[derive(Serialize, Deserialize)]
4641struct ServiceWorker {
4642 opts: Opts,
4643 queue: PathBuf,
4644 worktrees_root: PathBuf,
4645 operation: String,
4646}
4647
4648fn load_conductor(home: &Path) -> Result<Conductor> {
4649 match std::fs::read(home.join("conductor-state.json")) {
4650 Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
4651 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
4652 Err(error) => Err(error.into()),
4653 }
4654}
4655
4656fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
4657 let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
4658 .into_iter()
4659 .map(|c| c.task)
4660 .collect();
4661 let stalled = stalled_tasks(queue, home, Timestamp::now());
4662 let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
4663 let finished = finished_tasks(queue)
4664 .into_iter()
4665 .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
4666 .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
4667 .collect();
4668 let queued = queued_tasks(queue)
4669 .into_iter()
4670 .filter(|t| !live.contains(&t.id))
4671 .collect();
4672 (queued, stalled, finished)
4673}
4674
4675fn retention_service_receipt(
4678 home: &Path,
4679 operation: &str,
4680 phase: &str,
4681 outcome: &str,
4682 detail: &str,
4683 cfg: Option<&Config>,
4684) {
4685 retention_service_receipt_with(
4686 home,
4687 operation,
4688 phase,
4689 outcome,
4690 detail,
4691 cfg,
4692 serde_json::Value::Null,
4693 );
4694}
4695
4696fn retention_service_receipt_with(
4700 home: &Path,
4701 operation: &str,
4702 phase: &str,
4703 outcome: &str,
4704 detail: &str,
4705 cfg: Option<&Config>,
4706 extra: serde_json::Value,
4707) {
4708 if !matches!(operation, "housekeeping" | "disk-pressure" | "fold") {
4709 return;
4710 }
4711 let mut receipt = serde_json::json!({"checked_at": Timestamp::now(),
4712 "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
4713 "operation": operation, "outcome": outcome, "detail": detail,
4714 "auto_fold": cfg.map(|c| c.disk.auto_fold),
4715 "reclaim_free_bytes": cfg.map(|c| c.disk.reclaim_threshold()),
4716 "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
4717 if let (Some(receipt), serde_json::Value::Object(extra)) = (receipt.as_object_mut(), extra) {
4718 receipt.extend(extra);
4719 }
4720 if let Err(error) = crate::fold_evidence::atomic_write(
4721 &home.join(format!("source-eviction-{operation}-{phase}.json")),
4722 &serde_json::to_vec(&receipt).expect("service receipt"),
4723 ) {
4724 tracing::warn!("retention service receipt failed: {error:#}");
4725 }
4726}
4727
4728fn retention_summary(report: &crate::retention::Report) -> serde_json::Value {
4732 let clip = |text: &String| text.chars().take(300).collect::<String>();
4733 serde_json::json!({"retention": {
4734 "checked_at": report.checked_at,
4735 "freed_bytes": report.freed_bytes,
4736 "retired": report.retired,
4737 "retained": report.retained.len(),
4738 "failure_count": report.failures.len(),
4739 "failures": report.failures.iter().take(8).map(clip).collect::<Vec<_>>(),
4740 }})
4741}
4742
4743const FOLD_TURN_INTERVAL_SECS: u64 = 120;
4763
4764fn housekeeping_eligible(busy: bool, runnable: bool) -> bool {
4766 !busy && !runnable
4767}
4768
4769fn fold_turn_eligible(busy: bool, runnable: bool, cfg: Option<&Config>) -> bool {
4774 !housekeeping_eligible(busy, runnable) && cfg.is_some_and(|cfg| cfg.disk.auto_fold)
4775}
4776
4777async fn start_service(
4778 home: &Path,
4779 opts: &Opts,
4780 queue: &Queue,
4781 worktrees_root: &Path,
4782 operation: &str,
4783 cfg: Option<&Config>,
4784 busy: bool,
4785) -> Result<()> {
4786 let fetch_cfg = if operation == "fetch" {
4789 match prepare(&opts.repo, opts) {
4790 Ok(cfg) => Some(cfg),
4791 Err(error) => {
4792 tracing::warn!("could not reload periodic fetch configuration: {error:#}");
4793 return Ok(());
4794 }
4795 }
4796 } else {
4797 None
4798 };
4799 let cfg = fetch_cfg.as_ref().or(cfg);
4800 let ticks = home.join("service-ticks");
4801 std::fs::create_dir_all(&ticks)?;
4802 let receipt = ticks.join(format!("daemon-{operation}"));
4803 let last = std::fs::read(&receipt)
4804 .ok()
4805 .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
4806 let interval = match operation {
4807 "disk-pressure" => 30,
4808 "fold" => FOLD_TURN_INTERVAL_SECS,
4809 "chat-goals" => 60,
4810 "cache" => CACHE_CHECK_INTERVAL_SECS,
4811 "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
4812 _ => opts.poll.as_secs().max(1),
4813 };
4814 let now = Timestamp::now();
4815 if !cache_check_due(last, now, interval) {
4816 retention_service_receipt(
4817 home,
4818 operation,
4819 "dispatch",
4820 "skipped",
4821 "cadence not due",
4822 cfg,
4823 );
4824 return Ok(());
4825 }
4826 let key = format!("service:daemon-{operation}");
4827 let active = crate::worker::active(home)?;
4828 if active.iter().any(|job| job.key == key) {
4829 retention_service_receipt(
4830 home,
4831 operation,
4832 "dispatch",
4833 "skipped",
4834 "service worker already active",
4835 cfg,
4836 );
4837 return Ok(());
4838 }
4839 let sibling = match operation {
4842 "housekeeping" => Some("service:daemon-fold"),
4843 "fold" => Some("service:daemon-housekeeping"),
4844 _ => None,
4845 };
4846 if sibling.is_some_and(|sibling| active.iter().any(|job| job.key == sibling)) {
4847 retention_service_receipt(
4848 home,
4849 operation,
4850 "dispatch",
4851 "skipped",
4852 "another finished-run folding service is active",
4853 cfg,
4854 );
4855 return Ok(());
4856 }
4857 let eligible = match operation {
4858 "conductor" => {
4859 let (queued, stalled, finished) = conductor_work(queue, home);
4860 !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4861 && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4862 }
4863 "maintenance" => {
4864 queue.list().iter().any(|task| {
4865 crate::triage::disk_wait_eligible(task)
4866 && task
4867 .disk_checked_at
4868 .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4869 }) || Questions::at(home.join("questions"))
4870 .list_for_effects()
4871 .iter()
4872 .any(|q| {
4873 q.chosen_action().is_some_and(|action| action.maintenance())
4874 && !home
4875 .join("choice-actions")
4876 .join(format!("{}.json", q.id))
4877 .exists()
4878 })
4879 }
4880 "housekeeping" => housekeeping_eligible(busy, !runnable(queue).is_empty()),
4881 "fold" => fold_turn_eligible(busy, !runnable(queue).is_empty(), cfg),
4882 "cache" => {
4883 !busy
4884 && !runnable(queue).is_empty()
4885 && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4886 }
4887 "disk-pressure" => busy,
4888 "fetch" => {
4889 cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4890 }
4891 "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4892 .list()
4893 .iter()
4894 .any(|talk| {
4895 talk.status.open()
4896 && talk.pending.is_empty()
4897 && talk.pending_attachments.is_empty()
4898 && talk.goals.iter().any(|goal| goal.active())
4899 }),
4900 _ => false,
4901 };
4902 if !eligible {
4903 retention_service_receipt(
4904 home,
4905 operation,
4906 "dispatch",
4907 "skipped",
4908 match operation {
4909 "housekeeping" => "active work or runnable task queue",
4910 "fold" if cfg.is_none() => "startup configuration unavailable",
4911 "fold" if cfg.is_some_and(|cfg| !cfg.disk.auto_fold) => "auto_fold disabled",
4912 "fold" => "idle machine; housekeeping owns finished-run folding",
4913 _ => "no active work; idle housekeeping owns scan",
4914 },
4915 cfg,
4916 );
4917 return Ok(());
4918 }
4919 retention_service_receipt(
4920 home,
4921 operation,
4922 "dispatch",
4923 "launching",
4924 "eligible and cadence due",
4925 cfg,
4926 );
4927 let request = ServiceWorker {
4928 opts: opts.absolute()?,
4929 queue: std::path::absolute(queue.root())?,
4930 worktrees_root: std::path::absolute(worktrees_root)?,
4931 operation: operation.to_owned(),
4932 };
4933 if let Err(error) = launch_service(home, &key, request).await {
4934 retention_service_receipt(
4935 home,
4936 operation,
4937 "dispatch",
4938 "error",
4939 &format!("worker launch: {error:#}"),
4940 cfg,
4941 );
4942 tracing::warn!(operation, "could not launch daemon service: {error:#}");
4943 }
4944 std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4945 Ok(())
4946}
4947
4948async fn launch_service(home: &Path, key: &str, request: ServiceWorker) -> Result<()> {
4954 #[cfg(test)]
4955 if INLINE_SERVICES.with(std::cell::Cell::get) {
4956 return run_service_worker(home, serde_json::to_value(request)?).await;
4957 }
4958 crate::worker::spawn(home, "daemon-service", key, serde_json::to_value(request)?).await?;
4959 Ok(())
4960}
4961
4962#[cfg(test)]
4963thread_local! {
4964 static INLINE_SERVICES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4965}
4966
4967async fn fold_service_turn(home: &Path, opts: &Opts) {
4971 let worker = |outcome: &str, detail: &str, cfg: Option<&Config>, extra| {
4972 retention_service_receipt_with(home, "fold", "worker", outcome, detail, cfg, extra);
4973 };
4974 let cfg = match prepare(&opts.repo, opts) {
4975 Ok(cfg) => cfg,
4976 Err(error) => {
4977 worker(
4978 "error",
4979 &format!("configuration: {error:#}"),
4980 None,
4981 serde_json::Value::Null,
4982 );
4983 return;
4984 }
4985 };
4986 if !cfg.disk.auto_fold {
4987 worker(
4988 "skipped",
4989 "auto_fold disabled",
4990 Some(&cfg),
4991 serde_json::Value::Null,
4992 );
4993 return;
4994 }
4995 worker(
4996 "running",
4997 "finished-run fold turn",
4998 Some(&cfg),
4999 serde_json::Value::Null,
5000 );
5001 let turn = clean::fold_turn(
5002 &home.join("runs"),
5003 home,
5004 &cfg.disk,
5005 Timestamp::now(),
5006 clean::BUSY_FOLD_BOUNDS,
5007 )
5008 .await;
5009 if turn.folded > 0 || turn.failed > 0 || turn.unreadable > 0 {
5010 tracing::info!(
5011 folded = turn.folded,
5012 failed = turn.failed,
5013 unreadable = turn.unreadable,
5014 "housekeep: finished-run fold turn"
5015 );
5016 }
5017 worker(
5018 "completed",
5019 "finished-run fold turn",
5020 Some(&cfg),
5021 serde_json::json!({ "fold": turn }),
5022 );
5023}
5024
5025pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
5028 let request: ServiceWorker = serde_json::from_value(payload)?;
5029 let opts = &request.opts;
5030 let queue = Queue::at(request.queue);
5031 let questions = Questions::at(home.join("questions"));
5032 match request.operation.as_str() {
5033 "chat-goals" => {
5034 let talks = crate::talk::Talks::at(home.join("talks"));
5035 crate::chat_goal_runtime::sweep(&talks, false).await;
5036 }
5037 "maintenance" => {
5038 apply_maintenance_choices(&queue, &questions, home).await;
5039 triage::monitor_disk_waits(
5040 &queue,
5041 &questions,
5042 opts.config.as_deref(),
5043 Timestamp::now(),
5044 );
5045 }
5046 "conductor" => {
5047 let path = home.join("conductor-state.json");
5048 let mut conductor = load_conductor(home)?;
5049 let (queued, stalled, finished) = conductor_work(&queue, home);
5050 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
5051 && conductor.worth_a_look(&queue, &stalled, &finished)
5052 {
5053 let cfg = prepare(&opts.repo, opts)?;
5054 conductor
5055 .maybe_run(
5056 &cfg,
5057 &opts.repo,
5058 &queue,
5059 &questions,
5060 home,
5061 &queued,
5062 &stalled,
5063 &finished,
5064 opts.max_attempts,
5065 )
5066 .await;
5067 let temporary = path.with_extension("json.tmp");
5068 std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
5069 std::fs::rename(temporary, path)?;
5070 }
5071 }
5072 "fetch" => {
5073 let cfg = prepare(&opts.repo, opts)?;
5074 if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
5075 let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
5076 tracing::debug!("fetch origins: {outcome:?}");
5077 }
5078 }
5079 "cache" => {
5080 if task_jobs(home)?.is_empty() {
5081 let mut checked = None;
5082 maybe_prune_cache_between_runs(
5083 &opts.repo,
5084 opts,
5085 home,
5086 &Stop::new(),
5087 &mut checked,
5088 Timestamp::now(),
5089 )
5090 .await;
5091 }
5092 }
5093 "disk-pressure" => {
5094 if let Ok(cfg) = prepare(&opts.repo, opts) {
5095 retention_service_receipt(
5096 home,
5097 "disk-pressure",
5098 "worker",
5099 "running",
5100 "retention sweep",
5101 Some(&cfg),
5102 );
5103 let report = crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5104 retention_service_receipt_with(
5105 home,
5106 "disk-pressure",
5107 "worker",
5108 "retention swept",
5109 "retention sweep finished; cache cleanup follows",
5110 Some(&cfg),
5111 retention_summary(&report),
5112 );
5113 if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
5114 tracing::warn!("disk pressure cache cleanup failed: {e:#}");
5115 }
5116 if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
5117 tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
5118 }
5119 for current in current_work(home, Timestamp::now()) {
5120 if let Ok(state) = RunState::load_under(¤t.run, home)
5121 && let Some(reason) = disk_gate(&state.repo, &state.config)
5122 {
5123 for job in owned_task_jobs(home)?.into_iter().filter(|job| {
5124 job.key.strip_prefix("task:") == Some(current.task.as_str())
5125 }) {
5126 request_task_park(
5127 home,
5128 &job,
5129 crate::run::ParkCause::Interrupt {
5130 reason: reason.clone(),
5131 },
5132 )?;
5133 }
5134 notices::raise_in(
5135 home,
5136 Notice::warn(
5137 "disk:pressure",
5138 "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
5139 ),
5140 );
5141 }
5142 }
5143 } else {
5144 retention_service_receipt(
5145 home,
5146 "disk-pressure",
5147 "worker",
5148 "error",
5149 "configuration could not be loaded",
5150 None,
5151 );
5152 }
5153 }
5154 "fold" => fold_service_turn(home, opts).await,
5155 "housekeeping" => {
5156 if task_jobs(home)?.is_empty() {
5157 match prepare(&opts.repo, opts) {
5158 Ok(cfg) => {
5159 retention_service_receipt(
5160 home,
5161 "housekeeping",
5162 "worker",
5163 "running",
5164 "retention sweep",
5165 Some(&cfg),
5166 );
5167 let report =
5168 crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5169 retention_service_receipt_with(
5170 home,
5171 "housekeeping",
5172 "worker",
5173 "retention swept",
5174 "retention sweep finished; janitor follows",
5175 Some(&cfg),
5176 retention_summary(&report),
5177 );
5178 }
5179 Err(error) => retention_service_receipt(
5180 home,
5181 "housekeeping",
5182 "worker",
5183 "error",
5184 &format!("configuration: {error:#}"),
5185 None,
5186 ),
5187 }
5188 janitor(&opts.repo, opts, home, &request.worktrees_root).await;
5189 resweep_superseded_attempts(&queue, home);
5190 triage_held(&queue, home, opts).await;
5191 } else {
5192 retention_service_receipt(
5193 home,
5194 "housekeeping",
5195 "worker",
5196 "skipped",
5197 "task worker became active",
5198 None,
5199 );
5200 }
5201 }
5202 operation => bail!("unknown daemon service {operation}"),
5203 }
5204 Ok(())
5205}
5206
5207fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
5211 let key = format!("task:{}", request.task);
5212 let payload = serde_json::to_value(request)?;
5213 if crate::worker::active(home)?
5214 .iter()
5215 .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
5216 {
5217 tracing::warn!(
5218 "task {} acquired a competing worker reservation: {error:#}",
5219 crate::run::short_of(&request.task)
5220 );
5221 return Ok(());
5222 }
5223 tracing::error!("task worker startup stopped dispatch: {error:#}");
5224 notices::raise_in(
5225 home,
5226 Notice::error(
5227 "loop:worker-startup",
5228 format!("Task {} worker could not be started or acknowledged. Scheduler dispatch stopped; already reserved workers may still complete. Inspect the local execution log and reservation worker.log for startup details.", request.task),
5231 ).link(Link::Task { id: request.task.clone() }),
5232 );
5233 Err(error).with_context(|| {
5234 format!(
5235 "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
5236 crate::run::short_of(&request.task)
5237 )
5238 })
5239}
5240
5241async fn poll(
5242 opts: &Opts,
5243 queue: &Queue,
5244 status: &Arc<Mutex<Status>>,
5245 home: &Path,
5246 worktrees_root: &Path,
5247 stop: &Stop,
5248 limits: DispatchLimits,
5249) -> Result<()> {
5250 let mut attempted = Vec::new();
5251 let mut settling_once_services = false;
5252 let interrupt_path = home.join("scheduler-interrupt.json");
5253 let mut interrupt = match std::fs::read(&interrupt_path) {
5254 Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
5255 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
5256 Err(error) => return Err(error.into()),
5257 };
5258 let mut previous = std::collections::BTreeSet::<String>::new();
5259 let mut previous_skips = DispatchSkips::new();
5260 while !stop.stopped() {
5261 let jobs: Vec<_> = crate::worker::active(home)?
5262 .into_iter()
5263 .filter(|job| job.kind == "task")
5264 .collect();
5265 let requests: Vec<_> = jobs
5266 .iter()
5267 .map(|job| {
5268 serde_json::from_value::<TaskWorker>(job.payload.clone())
5269 .with_context(|| format!("read live task worker {}", job.id))
5270 })
5271 .collect::<Result<_>>()?;
5272 let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
5273 let owned: std::collections::BTreeSet<_> = requests
5274 .iter()
5275 .filter(|r| !r.standalone)
5276 .map(|r| r.task.clone())
5277 .collect();
5278 let current: Vec<_> = requests
5279 .iter()
5280 .zip(&jobs)
5281 .filter(|(request, _)| !request.standalone)
5282 .map(|(request, job)| Current {
5283 worker: Some(job.id.clone()),
5284 task: request.task.clone(),
5285 run: queue
5286 .get(&request.task)
5287 .ok()
5288 .and_then(|task| task.execution_runs().last().cloned())
5289 .unwrap_or_default(),
5290 })
5291 .collect();
5292 {
5293 let mut snapshot = lock(status);
5294 snapshot.polls += 1;
5295 snapshot.completed += previous.difference(&owned).count();
5296 snapshot.current = current;
5297 snapshot.idle = owned.is_empty();
5298 snapshot.dispatch_wait = None;
5299 }
5300 previous = owned.clone();
5301 stop.busy.store(owned.len(), Ordering::SeqCst);
5302
5303 let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
5306 let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
5307 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
5308 let mut permits = Vec::new();
5309 sweep_stale_claims(queue, STALE_CLAIM);
5310 reclaim_orphaned_running(queue, opts.max_attempts, &live);
5311 reclaim_abandoned_runs(home, Timestamp::now());
5312 let questions = Questions::at(home.join("questions"));
5313
5314 crate::task_chat::sweep(
5317 queue,
5318 &crate::talk::Talks::at(home.join("talks")),
5319 &questions,
5320 home,
5321 );
5322 if let Err(error) = crate::task_inquiry::Outbox::at(home)
5323 .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
5324 {
5325 tracing::warn!("task inquiry delivery remains pending: {error:#}");
5326 }
5327 repair_choice_offers(&questions);
5328 resolve_blockers(queue, &questions);
5329 apply_task_choice_actions(queue, &questions, home);
5330 triage::apply_answers(queue, &questions);
5331 reconcile_task_questions(queue, &questions);
5332 let talks = crate::talk::Talks::at(home.join("talks"));
5333 crate::chat_notify::sweep(queue, &talks, home);
5334 crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
5335 crate::chat_watch::sweep(home, &talks);
5336 if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
5337 tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
5338 }
5339 let mut turns = tokio::task::JoinSet::new();
5340 crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
5341 while turns.join_next().await.is_some() {}
5343
5344 crate::consult::start_services(
5345 home,
5346 &opts.repo,
5347 limits.recovery_cfg.as_ref(),
5348 opts.config.as_deref(),
5349 )
5350 .await?;
5351 for operation in [
5352 "conductor",
5353 "maintenance",
5354 "housekeeping",
5355 "disk-pressure",
5356 "fold",
5357 "cache",
5358 "fetch",
5359 "chat-goals",
5360 ] {
5361 if settling_once_services {
5365 break;
5366 }
5367 if operation == "chat-goals" && stop.parking() {
5368 continue;
5369 }
5370 start_service(
5371 home,
5372 opts,
5373 queue,
5374 worktrees_root,
5375 operation,
5376 limits.recovery_cfg.as_ref(),
5377 !live.is_empty(),
5378 )
5379 .await?;
5380 }
5381 let latest = crate::worker::active(home)?;
5382 if latest.iter().any(|job| job.key == "service:daemon-cache")
5383 || latest
5384 .iter()
5385 .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
5386 {
5387 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5388 continue;
5389 }
5390 let candidates: Vec<Task> = runnable(queue)
5391 .into_iter()
5392 .filter(|task| !live.contains(&task.id))
5393 .filter(|task| !opts.once || !attempted.contains(&task.id))
5394 .collect();
5395 let in_flight: Vec<_> = owned.iter().cloned().collect();
5396 let prior_interrupt = std::mem::discriminant(&interrupt);
5397 interrupt = advance_interrupt_tick(
5398 limits.pause_for_interrupts,
5399 interrupt,
5400 &in_flight,
5401 &candidates,
5402 );
5403 if prior_interrupt != std::mem::discriminant(&interrupt) {
5406 let temporary = interrupt_path.with_extension("json.tmp");
5407 std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
5408 std::fs::rename(temporary, &interrupt_path)?;
5409 }
5410 if let Interrupt::Parking {
5411 parked,
5412 interrupt_task,
5413 } = &interrupt
5414 {
5415 for job in jobs.iter().filter(|job| {
5416 parked
5417 .iter()
5418 .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
5419 }) {
5420 if crate::worker::control(home, &job.key)?.is_none() {
5421 request_task_park(
5422 home,
5423 job,
5424 crate::run::ParkCause::Interrupt {
5425 reason: format!(
5426 "task {} asked to run first",
5427 crate::run::short_of(interrupt_task)
5428 ),
5429 },
5430 )?;
5431 }
5432 }
5433 }
5434 let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
5435 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
5436 let mut skips = interrupt_skips(&candidate_ids, &candidates);
5437 let (mut immediate_candidates, other_candidates): (Vec<Task>, Vec<Task>) =
5441 candidates.into_iter().partition(|task| task.immediate);
5442 immediate_candidates.extend(other_candidates);
5443 let candidates = immediate_candidates;
5444 let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
5445 let mut known_jobs: std::collections::BTreeSet<String> =
5446 jobs.iter().map(|job| job.id.clone()).collect();
5447 let mut started = false;
5448 let mut resync = false;
5449 for candidate in candidates {
5450 if stop.stopped() {
5451 break;
5452 }
5453 let DispatchClaim {
5454 task,
5455 claim,
5456 lane,
5457 permit,
5458 } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
5459 Ok(claim) => claim,
5460 Err(reason) => {
5461 skips.insert((candidate.id, reason));
5462 continue;
5463 }
5464 };
5465 if crate::worker::active(home)?
5466 .iter()
5467 .any(|job| job.kind == "task" && !known_jobs.contains(&job.id))
5468 {
5469 drop(claim);
5470 resync = true;
5471 break;
5472 }
5473 let request = TaskWorker {
5474 opts: opts.absolute()?,
5475 queue: std::path::absolute(queue.root())?,
5476 task: task.id.clone(),
5477 lane,
5478 standalone: false,
5479 };
5480 let job = match crate::worker::spawn(
5483 home,
5484 "task",
5485 &format!("task:{}", task.id),
5486 serde_json::to_value(&request)?,
5487 )
5488 .await
5489 {
5490 Ok(job) => job,
5491 Err(error) => {
5492 task_worker_spawn_error(home, &request, error)?;
5493 drop(claim);
5494 resync = true;
5495 break;
5496 }
5497 };
5498 known_jobs.insert(job.id);
5499 drop(claim);
5500 permits.extend(permit);
5501 attempted.push(task.id);
5502 started = true;
5503 if limits.pause_for_interrupts || lane != PermitKind::Immediate {
5507 break;
5508 }
5509 }
5510 if !resync && !stop.stopped() {
5511 let per_task_skips: std::collections::BTreeMap<String, String> = skips
5512 .iter()
5513 .map(|(id, reason)| (id.clone(), reason.key().to_owned()))
5514 .collect();
5515 {
5516 let mut snapshot = lock(status);
5517 snapshot.dispatch_skips = per_task_skips;
5518 if !started {
5519 snapshot.dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
5520 }
5521 }
5522 if changed_dispatch_skips(&mut previous_skips, skips) {
5523 if previous_skips.is_empty() {
5524 tracing::info!("dispatch skips cleared");
5525 }
5526 for (task, reason) in &previous_skips {
5527 tracing::info!(
5528 task,
5529 reason = reason.key(),
5530 "task {} skipped: {}",
5531 crate::run::short_of(task),
5532 reason.describe()
5533 );
5534 }
5535 }
5536 }
5537 if started || resync {
5538 continue;
5539 }
5540 if owned.is_empty() && opts.once {
5541 settling_once_services = true;
5542 if crate::worker::active(home)?.iter().any(|job| {
5546 job.kind == "daemon-service"
5547 && matches!(
5548 job.key.as_str(),
5549 "service:daemon-housekeeping"
5550 | "service:daemon-conductor"
5551 | "service:daemon-maintenance"
5552 )
5553 }) {
5554 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5555 continue;
5556 }
5557 break;
5558 }
5559 stop.idle(if live.is_empty() {
5560 opts.poll
5561 } else {
5562 RECHECK_WHILE_BUSY.min(opts.poll)
5563 })
5564 .await;
5565 }
5566 stop.busy.store(0, Ordering::SeqCst);
5569 {
5570 let mut snapshot = lock(status);
5571 snapshot.dispatch_wait = None;
5572 snapshot.dispatch_skips.clear();
5573 }
5574 Ok(())
5575}
5576
5577async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
5581 let busy = |error: &anyhow::Error| {
5582 error.downcast_ref::<std::io::Error>().is_some_and(|error| {
5583 error.kind() == std::io::ErrorKind::WouldBlock
5584 || cfg!(windows) && error.raw_os_error() == Some(33)
5585 })
5586 };
5587 match crate::pr_head::owner_lock(home, id) {
5588 Ok(lock) => return Ok(lock),
5589 Err(error) if busy(&error) => {}
5590 Err(error) => return Err(error),
5591 }
5592 let wait = RunState::load_under(id, home)?
5593 .config
5594 .graph
5595 .timeout_resource_wait;
5596 crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
5597}
5598
5599pub(crate) async fn public_resume_owner(
5603 home: &Path,
5604 runs: &[String],
5605 repo: &Path,
5606) -> Result<Option<RunState>> {
5607 let mut owner = None;
5608 for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
5609 let _lock = resume_owner_lock(home, id).await?;
5610 let state = RunState::load_under(id, home)?;
5611 if state.released()
5612 || state.retired_to.is_some()
5613 || state.pr_taken_over_by.is_some()
5614 || !crate::handover::landing_checkpoint(&state)
5615 {
5616 continue;
5617 }
5618 anyhow::ensure!(
5619 crate::git::toplevel(&state.repo).await?.canonicalize()?
5620 == crate::git::toplevel(repo).await?.canonicalize()?,
5621 "public owner repository differs; inspect run lineage"
5622 );
5623 anyhow::ensure!(
5624 owner.is_none(),
5625 "multiple retained public owners; inspect run lineage"
5626 );
5627 if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
5628 anyhow::bail!(reason.diagnostic(&state));
5629 }
5630 let claimed = is_working_on_other(home, id, Timestamp::now())?;
5631 anyhow::ensure!(
5632 state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
5633 "public owner's driver is live or unknown; wait before retrying"
5634 );
5635 owner = Some(state);
5636 }
5637 Ok(owner)
5638}
5639
5640async fn attempt(
5646 opts: &Opts,
5647 queue: &Queue,
5648 status: &Arc<Mutex<Status>>,
5649 stop: &Stop,
5650 interrupt_pause: crate::graph::Pause,
5651 task: &mut Task,
5652) -> Vec<QuotaLoss> {
5653 if let Some(request) = task.sync_only.clone() {
5654 Box::pin(attempt_sync_only(
5655 queue,
5656 status,
5657 stop,
5658 interrupt_pause,
5659 task,
5660 request,
5661 ))
5662 .await;
5663 return Vec::new();
5664 }
5665 let repo = repo_for(task, &opts.repo);
5666 tracing::info!(
5667 "task {} — {} (repo {})",
5668 task.short(),
5669 task.title,
5670 repo.display()
5671 );
5672
5673 let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
5674 Ok(owner) => owner,
5675 Err(e) => {
5676 task.hold_machine(Some(format!(
5677 "Cannot verify existing public owner: {e:#}; no attempt started."
5678 )));
5679 record(queue, task);
5680 return Vec::new();
5681 }
5682 };
5683 let resume_runs = public_owner
5684 .as_ref()
5685 .map(|s| vec![s.id.clone()])
5686 .unwrap_or_else(|| task.execution_runs().to_vec());
5687
5688 if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
5692 && previous
5693 .merge_decision
5694 .as_ref()
5695 .is_some_and(|decision| !decision.closed)
5696 && previous.status != RunStatus::Landing
5697 && !crate::merge_decision::resumable_hold(&previous)
5698 {
5699 task.hold_unrequested_retry(Some(format!("The existing owner stop decision remains held. Inspect run {} and its PR; request an explicit fresh review/decision before further work. No replacement or merge was started.", previous.id)));
5700 record(queue, task);
5701 return Vec::new();
5702 }
5703 let stop_owner = resume_runs
5704 .last()
5705 .and_then(|id| RunState::load(id).ok())
5706 .filter(|state| {
5707 crate::merge_decision::resumable_hold(state)
5708 || state.status == RunStatus::Landing
5709 && state.land_approval.as_ref().is_some_and(|binding| {
5710 Questions::open()
5711 .get_for_effects(&binding.question)
5712 .is_ok_and(|q| {
5713 q.run == state.id
5714 && q.resolution()
5715 .as_deref()
5716 .is_some_and(crate::merge_decision::stops)
5717 })
5718 })
5719 });
5720 if let Some(owner) = stop_owner {
5721 let mut runner = match Runner::resume(&owner.id) {
5722 Ok(runner) => runner,
5723 Err(e) => {
5724 task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
5725 record(queue, task);
5726 return Vec::new();
5727 }
5728 };
5729 runner.on_pause(stop.pause());
5730 runner.watch_interrupt(interrupt_pause);
5731 let quota_before = runner.state.quota.clone();
5732 let before_start = task.clone();
5733 task.start(owner.id.clone());
5734 if let Err(error) = queue.put(task) {
5735 *task = before_start;
5736 let error = runner.fail_startup("task-start", error);
5737 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5738 task.record_startup_failure(failure.clone());
5739 }
5740 task.hold_manual(Some(format!(
5741 "Could not persist task start; no agents dispatched: {error:#}"
5742 )));
5743 record(queue, task);
5744 return Vec::new();
5745 }
5746 lock(status).current.push(Current {
5747 worker: None,
5748 task: task.id.clone(),
5749 run: owner.id,
5750 });
5751 runner.state.carry_dispatched_resumes(task);
5752 runner.state.next_pass_task_entry = true;
5753 let result = runner.execute().await;
5754 return finish_attempt(
5755 opts.max_attempts,
5756 queue,
5757 task,
5758 &runner.state,
5759 "a_before,
5760 result,
5761 );
5762 }
5763
5764 if let Some(owner) = &public_owner
5765 && (task.fresh_start || !may_resume_run(owner, task))
5766 {
5767 task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. For a closed unmerged PR with a cancelled approval and selected replacement, use magi task recover-pr {} --retire-closed-run {} --cancelled-decision <inquiry-id>. No attempt started.", owner.id, task.id, owner.id)));
5768 record(queue, task);
5769 return Vec::new();
5770 }
5771
5772 if let Some(state) = task
5773 .execution_runs()
5774 .last()
5775 .and_then(|id| RunState::load(id).ok())
5776 && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
5777 {
5778 task.hold_machine(Some(reason));
5779 record(queue, task);
5780 return Vec::new();
5781 }
5782
5783 if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
5784 && !task.fresh_start
5785 && task.pr_recovery.is_none()
5786 {
5787 let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
5790 && task.review_branch.is_none()
5791 && task.assignment_accepts(&held)
5792 && compatible_run_instruction(&held, task)
5793 && task
5794 .resume_override
5795 .as_ref()
5796 .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
5797 let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
5800 {
5801 true
5802 } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
5803 let home = queue.root().parent().expect("queue has a home");
5804 match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
5805 Ok(()) => true,
5806 Err(error) => {
5807 tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
5808 false
5809 }
5810 }
5811 } else {
5812 false
5813 };
5814 if !authorized {
5815 task.hold_machine(Some(format!("Base synchronization remains stopped. {} A release without a new owner approval grants no additional synchronization budget and starts no replacement competition.", held.base_sync_next_action())));
5816 task.base_sync_notice(&held);
5818 task.resume_override = None;
5819 record(queue, task);
5820 return Vec::new();
5821 }
5822 }
5823 if !task.fresh_start && task.pr_recovery.is_none() {
5824 let home = queue.root().parent().expect("queue has a home");
5825 if let crate::land_sync_recovery::DispatchDecision::Hold { reason, state } =
5826 crate::land_sync_recovery::dispatch_check(queue, home, task).await
5827 {
5828 task.hold_machine(Some(reason));
5829 task.land_sync_notice(state.as_ref());
5830 task.resume_override = None;
5831 record(queue, task);
5832 return Vec::new();
5833 }
5834 }
5835 let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
5836 Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
5837 hold.apply(task);
5838 record(queue, task);
5839 return Vec::new();
5840 }
5841 Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
5842 run,
5843 stop_id,
5844 generation,
5845 approval_at,
5846 }) => Some((run, stop_id, generation, approval_at)),
5847 None => None,
5848 };
5849 let unfinished = (!task.fresh_start)
5850 .then(|| unfinished_run(&resume_runs, task.short()))
5851 .flatten()
5852 .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
5853 let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
5854 if task.repair_grants.last().is_some_and(|receipt| {
5855 task.execution_runs().last() == Some(&receipt.request.run)
5856 && task.operator_decided_at == receipt.decision
5857 && previous
5858 .as_ref()
5859 .is_none_or(|run| run.id != receipt.request.run)
5860 }) {
5861 task.hold_unrequested_retry(Some(
5862 "The retained repair run cannot be read or no longer owns this task's recovery. Inspect the saved grant and run; no replacement was started.".into(),
5863 ));
5864 record(queue, task);
5865 return Vec::new();
5866 }
5867 if let Some(id) = &task.disk_resume_run
5868 && unfinished.as_ref() != Some(id)
5869 {
5870 task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely. Inspect its state and recovery approvals; no replacement competition was started.".into()));
5871 record(queue, task);
5872 return Vec::new();
5873 }
5874
5875 if !task.fresh_start
5876 && task.pr_recovery.is_none()
5877 && task.review_branch.is_none()
5878 && task.resume_override.is_none()
5879 && previous
5880 .as_ref()
5881 .is_some_and(|run| run.retired_to.is_some())
5882 && unfinished.is_none()
5883 {
5884 task.hold_unrequested_retry(Some("Recorded recovery authority is unavailable, no longer resumable or no longer authorized for these instructions. Inspect the retained lineage and select a recovery source explicitly; no replacement competition was started.".into()));
5885 record(queue, task);
5886 return Vec::new();
5887 }
5888
5889 let saved_recovery = previous.as_ref().filter(|run| {
5890 task.replacement.is_none()
5891 && task.pr_recovery.as_ref().is_some_and(|selected| {
5892 selected
5893 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5894 .is_ok()
5895 && selected_starter(selected, Some(run), unfinished.as_deref())
5896 == Starter::Resume(run.id.clone())
5897 })
5898 });
5899
5900 let explicit = match &task.overrides {
5904 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5905 Some(_) => opts.config.as_deref(),
5906 None => opts.config.as_deref(),
5907 };
5908 let (mut config, layers) = if let Some(run) = saved_recovery {
5909 let mut saved = run.clone();
5912 if let Err(e) = saved.configure_recovery_resume() {
5913 task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
5914 record(queue, task);
5915 return Vec::new();
5916 }
5917 (saved.config, Vec::new())
5918 } else {
5919 let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
5920 Ok(loaded) => loaded,
5921 Err(e) => {
5922 let reason = format!("[config] {e:#}");
5923 record_config_failure(task, &e);
5924 task.last_error = Some(reason.clone());
5925 task.hold_machine(Some(reason));
5926 record(queue, task);
5927 return Vec::new();
5928 }
5929 };
5930 if let Err(e) = apply_options(&mut config, opts, task) {
5931 task.hold_manual(Some(format!(
5932 "[config] {e:#}; correct the merge override before releasing the task"
5933 )));
5934 record(queue, task);
5935 return Vec::new();
5936 }
5937 if let Some(selected) = &task.pr_recovery
5938 && let Err(e) = selected.configure(&mut config)
5939 {
5940 task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
5941 record(queue, task);
5942 return Vec::new();
5943 }
5944 (config, layers)
5945 };
5946 let config_evidence = crate::pr_recovery::ConfigEvidence {
5947 layers,
5948 overrides: task.overrides.clone(),
5949 daemon_merge: task
5950 .overrides
5951 .as_ref()
5952 .is_none_or(|o| o.inherit_daemon_options)
5953 .then(|| opts.merge.clone())
5954 .flatten(),
5955 };
5956 apply_task_implementers(&mut config, task);
5957 if let Some(replacement) = &task.replacement {
5958 let safe = RunState::load(&replacement.run).is_ok_and(|old| {
5959 old.liveness(false) == Liveness::Dead
5960 && old.merge_decision.as_ref().is_some_and(|d| {
5961 d.closed
5962 && d.question == replacement.question
5963 && d.replacement_run.as_ref().is_none_or(|run| {
5964 task.execution_runs().last() == Some(run)
5965 && RunState::load(run).is_ok_and(|current| {
5966 current.replaces.as_ref().is_some_and(|pin| {
5967 pin.question == replacement.question
5968 && pin.agent == replacement.agent
5969 })
5970 })
5971 })
5972 })
5973 });
5974 if !safe {
5975 task.hold_manual(Some("Replacement ownership cannot be confirmed, or a replacement run was already minted before a crash. Inspect the task and its linked runs; no second replacement was started.".into()));
5976 record(queue, task);
5977 return Vec::new();
5978 }
5979 match config.agent(&replacement.agent) {
5980 Ok(agent) if crate::agent::installed(agent) => {}
5981 _ => {
5982 task.hold_manual(Some(format!("Selected implementer `{}` is unavailable or no longer configured. No substitute was dispatched. Restore it and explicitly release the task.", replacement.agent)));
5983 record(queue, task);
5984 return Vec::new();
5985 }
5986 }
5987 config.graph.implementers = 1;
5988 config.graph.land_approval = true;
5989 config.merge.mode = MergeMode::Pr;
5990 config.graph.selected_implementer = Some(replacement.agent.clone());
5991 }
5992 let p = phrases(&config.graph.language);
5993 let start_failed = p.could_not_start;
5994 if let Ok(base) =
5999 crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
6000 .await
6001 && let Ok(head) =
6002 crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
6003 {
6004 let mut inputs = crate::queue::recovery_inputs(&task.sources);
6005 if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
6006 let source = crate::git::rev_parse(&repo, branch)
6007 .await
6008 .unwrap_or_default();
6009 inputs.push_str(&format!(";review:{branch}:{source}"));
6010 }
6011 if let Some(reason) = task
6012 .recovery_exhausted(
6013 &head,
6014 &inputs,
6015 task.attempt_limit
6016 .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
6017 )
6018 .filter(|_| {
6019 !task.repair_grants.last().is_some_and(|receipt| {
6020 RunState::load(&receipt.request.run)
6021 .is_ok_and(|run| crate::repair_budget::pending(task, &run))
6022 })
6023 })
6024 {
6025 task.hold_recovery_budget(
6026 reason,
6027 crate::queue::RecoveryAdmission { base: head, inputs },
6028 );
6029 record(queue, task);
6030 return Vec::new();
6031 }
6032 task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
6033 }
6034
6035 let consume_review = !previous
6056 .as_ref()
6057 .is_some_and(|state| crate::repair_budget::pending(task, state));
6058 let review_branch = consume_review
6059 .then(|| review_branch_for(task, previous.as_ref()))
6060 .flatten();
6061 let branch_exists = match review_branch {
6062 Some(branch) => crate::git::branch_exists(&repo, branch)
6063 .await
6064 .unwrap_or(false),
6065 None => false,
6066 };
6067 let proposed = review_retry_starter(
6071 task,
6072 previous.as_ref(),
6073 review_branch,
6074 branch_exists,
6075 unfinished.as_deref(),
6076 );
6077 let retry_selected = task.replacement.is_some()
6078 && task.resumption.is_some()
6079 && !task.fresh_start
6080 && previous.as_ref().is_some_and(|run| {
6081 run.replaces.is_some()
6082 && ((run.status == RunStatus::Failed && run.viable().is_empty())
6083 || (run.status == RunStatus::Blocked && run.tally.is_none()))
6084 });
6085 let stop_pin = task
6086 .resume_override
6087 .as_ref()
6088 .filter(|pin| {
6089 Questions::open()
6090 .get_for_effects(&pin.question_id)
6091 .is_ok_and(|q| {
6092 q.node == land::APPROVAL_NODE
6093 && q.resolution()
6094 .as_deref()
6095 .is_some_and(crate::merge_decision::stops)
6096 })
6097 })
6098 .and_then(|pin| pin.pinned_run.clone());
6099 let granted_run = task.repair_grants.last().and_then(|receipt| {
6100 let state = RunState::load(&receipt.request.run).ok()?;
6101 crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
6102 });
6103 let starter = if let Some(run) = granted_run {
6104 Starter::Resume(run)
6105 } else if let Some(owner) = &public_owner {
6106 Starter::Resume(owner.id.clone())
6107 } else if let Some(run) = stop_pin {
6108 Starter::Resume(run)
6111 } else if retry_selected {
6112 Starter::Resume(previous.as_ref().unwrap().id.clone())
6113 } else if let Some(selected) = &task.pr_recovery {
6114 if selected
6115 .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
6116 .is_ok()
6117 {
6118 selected_starter(selected, previous.as_ref(), unfinished.as_deref())
6119 } else {
6120 Starter::Review(selected.branch.clone())
6121 }
6122 } else {
6123 starter_with_implementers(task, previous.as_ref(), proposed)
6124 };
6125 let disk_reason = match &starter {
6128 Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
6129 || {
6130 RunState::load(id)
6131 .ok()
6132 .and_then(|run| disk_gate(&run.repo, &run.config))
6133 },
6134 |run| disk_gate(&run.repo, &run.config),
6135 ),
6136 _ => disk_gate(&repo, &config),
6137 };
6138 if let Some(reason) = disk_reason {
6139 task.notice_cause("disk-space", None, None);
6140 task.last_error = Some(reason.clone());
6141 let disk_checked_at = task.disk_checked_at;
6142 task.hold_machine(Some(reason.clone()));
6143 if matches!(starter, Starter::Resume(_)) {
6144 task.mark_disk_capacity();
6145 } else {
6146 task.mark_startup_disk_capacity();
6147 }
6148 task.disk_checked_at = disk_checked_at;
6149 record(queue, task);
6150 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
6151 notices::raise(
6152 Notice::warn(
6153 &format!("disk:{}", repo.display()),
6154 format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
6155 )
6156 .link(Link::Task {
6157 id: task.id.clone(),
6158 }),
6159 );
6160 return Vec::new();
6161 }
6162 let review_branch = if consume_review {
6163 let valid = review_branch.is_some();
6164 task.review_instruction = None;
6165 task.review_branch.take().filter(|_| valid)
6166 } else {
6167 None
6168 };
6169 if let Some(pin) = &task.resume_override
6172 && let Some(run) = &pin.pinned_run
6173 && starter != Starter::Resume(run.clone())
6174 {
6175 let run = run.clone();
6176 task.notice_cause("resume-owner", Some(&run), None);
6177 task.hold_machine(Some(format!(
6178 "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
6179 task.id
6180 )));
6181 record(queue, task);
6182 return Vec::new();
6183 }
6184 if let Some(run) = &task.disk_resume_run
6188 && starter != Starter::Resume(run.clone())
6189 {
6190 task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely: the task's current settings would start a different run. Inspect its state and recovery approvals; no replacement competition was started.".into()));
6191 record(queue, task);
6192 return Vec::new();
6193 }
6194 if task.replacement.is_some()
6195 && previous.as_ref().is_some_and(|run| run.replaces.is_some())
6196 && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
6197 {
6198 task.hold_manual(Some("The selected replacement already has an attempt. It cannot be resumed safely; inspect its saved pin and restore the existing run. No additional replacement was started.".into()));
6199 record(queue, task);
6200 return Vec::new();
6201 }
6202 if let Some((ref run, ..)) = head_e2e_approval
6203 && starter != Starter::Resume(run.clone())
6204 {
6205 task.hold_machine(Some(format!(
6206 "Conclusive head_e2e stop on run {run} cannot resume safely with current task settings; inspect `magi show {run}` before retrying. No replacement competition was started."
6207 )));
6208 record(queue, task);
6209 return Vec::new();
6210 }
6211 if let Some(reason) = retained_attempt_hold(
6212 task,
6213 &starter,
6214 config.disk.retained_attempt_limit,
6215 RunState::load,
6216 ) {
6217 if let Starter::Review(branch) = &starter {
6220 task.review_branch = Some(branch.clone());
6221 }
6222 task.hold_unrequested_retry(Some(reason));
6223 record(queue, task);
6224 return Vec::new();
6225 }
6226 let attachments = match task_attachments(queue, task) {
6231 Ok(a) => a,
6232 Err(e) => {
6233 task.attempts += 1;
6234 task.fail_startup_target(
6235 "startup-attachments",
6236 e.name.clone(),
6237 format!("{start_failed}{e:#}"),
6238 opts.max_attempts,
6239 );
6240 record(queue, task);
6241 return Vec::new();
6242 }
6243 };
6244 let startup_pause = stop.pause();
6245 let startup_interrupt = interrupt_pause.clone();
6246 let wait = crate::repo_lock::WaitPolicy::new(
6247 Duration::from_secs(config.graph.timeout_resource_wait),
6248 move || startup_pause.parked() || startup_interrupt.parked(),
6249 );
6250 let started = wait.scope(Box::pin(async { match &starter {
6253 Starter::Review(_) if task.pr_recovery.is_some() => {
6254 let selected = task.pr_recovery.clone().expect("selected recovery");
6255 match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
6256 Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
6257 .await
6258 .map(|mut r| {
6259 r.state.attachments = attachments.clone();
6260 r
6261 }),
6262 Err(e) => Err(e),
6263 }
6264 }
6265 Starter::Review(branch) => {
6266 tracing::info!(
6267 "task {} reopens `{branch}` as a review-only pass",
6268 task.short()
6269 );
6270 let takeover = crate::handover::Takeover {
6273 earlier: task.earlier_attempts().to_vec(),
6274 home: crate::run::home(),
6275 choice: take_divergence_answer(branch, &config.merge.remote, task),
6276 task_instruction: Some(instruction_for(task)),
6277 };
6278 Runner::review_taking_over(
6279 &repo,
6280 branch,
6281 config,
6282 Some(takeover),
6283 crate::run::Origin::queue(&task.id),
6284 )
6285 .await
6286 }
6287 Starter::Resume(id) => {
6288 tracing::info!("resuming run {id} rather than competing again");
6289 Runner::resume(id).and_then(|mut r| {
6290 if retry_selected {
6291 for candidate in &mut r.state.candidates {
6294 candidate.failed = None;
6295 candidate.empty = false;
6296 candidate.commits = 0;
6297 }
6298 r.state.status = RunStatus::Implementing;
6299 r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
6300 }
6301 if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
6302 r.state.sources = task.sources.clone();
6303 }
6304 if r.state.prep_failure.is_some() {
6305 let approval = task
6306 .resumption
6307 .as_ref()
6308 .context("preparation retry requires an explicit task release")?;
6309 r.retry_preparation(approval.at)?;
6310 }
6311 if let Some(instruction) =
6312 prepare_instruction(&starter, Some(&r.state.instruction), task)
6313 {
6314 r.state.instruction = instruction;
6315 }
6316 r.state.attachments = attachments.clone();
6317 if task.replacement.is_some() {
6318 r.state.config.merge.mode = MergeMode::Pr;
6319 r.state.config.graph.land_approval = true;
6320 }
6321 if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
6325 .overrides
6326 .as_ref()
6327 .and_then(|o| o.merge.as_deref())
6328 .and_then(|m| merge_mode(m).ok())
6329 {
6330 r.state.config.merge.mode = mode;
6331 }
6332 Ok(r)
6333 })
6334 }
6335 Starter::Start => {
6336 if let Some(branch) = &review_branch {
6337 tracing::warn!(
6338 "conductor chose review for task {} but branch `{branch}` no longer \
6339 exists; requeuing as a fresh competition instead",
6340 task.short()
6341 );
6342 }
6343 let instruction = prepare_instruction(&starter, None, task)
6344 .unwrap_or_else(|| task.instruction.clone());
6345 Runner::start_naming(
6346 &repo,
6347 instruction,
6348 &task.title,
6349 config,
6350 crate::run::Origin::queue(&task.id),
6351 )
6352 .await
6353 .map(|mut r| {
6354 r.state.attachments = attachments.clone();
6355 r.state.sources = task.sources.clone();
6356 r
6357 })
6358 }
6359 }})).await;
6360 if let Err(error) = &started
6361 && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
6362 {
6363 task.record_startup_failure(failure.clone());
6364 }
6365 let mut runner = match started {
6366 Ok(r) => r,
6367 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6368 let detail = format!("{e:#}");
6369 task.last_error = Some(detail.clone());
6370 if e.is::<crate::build_target::AdmissionDiskWait>()
6371 && let Starter::Review(branch) = &starter
6372 && review_branch.is_some()
6373 {
6374 task.review_branch = Some(branch.clone());
6375 task.review_instruction = Some(task.instruction.clone());
6376 }
6377 if stop.parking() || interrupt_pause.parked() {
6378 let attempts = task.attempts;
6379 task.park(e.to_string());
6380 task.attempts = attempts;
6382 } else if e.is::<crate::build_target::AdmissionDiskWait>() {
6383 let disk_checked_at = task.disk_checked_at;
6384 task.hold_machine(Some(detail));
6385 task.mark_startup_disk_capacity();
6386 task.disk_checked_at = disk_checked_at;
6387 } else {
6388 task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
6389 }
6390 record(queue, task);
6391 return Vec::new();
6392 }
6393 Err(e) if task.pr_recovery.is_some() => {
6397 task.startup_notice_cause("startup-public-head");
6398 task.attempts += 1;
6399 task.last_error = Some(format!("{start_failed}{e:#}"));
6400 task.hold_unrequested_retry(Some(format!(
6401 "Selected public-head recovery could not start: {e:#}. Correct the cause and use `magi task recover-pr` with the approved public head; automatic recovery is stopped."
6402 )));
6403 record(queue, task);
6404 return Vec::new();
6405 }
6406 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
6407 let detail = match e.downcast_ref::<crate::handover::Refused>() {
6408 Some(r) => (p.handover_refused)(r),
6409 None => format!("{e:#}"),
6410 };
6411 task.startup_notice_cause("startup-handover");
6412 let reason = format!("{start_failed}{detail}");
6413 task.last_error = Some(reason.clone());
6414 let branch = match &starter {
6417 Starter::Review(branch) => Some(branch.clone()),
6418 _ => None,
6419 };
6420 task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
6424 record(queue, task);
6425 tracing::warn!(
6426 "holding {} for a branch it cannot take over: {e:#}",
6427 task.short()
6428 );
6429 return Vec::new();
6430 }
6431 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
6436 let d = e
6437 .downcast_ref::<crate::reconcile::Diverged>()
6438 .expect("checked by the guard");
6439 let mut q = ask::Question::new(
6440 task.id.clone(),
6441 crate::reconcile::NODE.to_owned(),
6442 crate::reconcile::SEAT.to_owned(),
6443 d.summary(),
6444 d.detail(),
6445 d.choices(),
6446 );
6447 match Questions::open().put(&mut q) {
6448 Ok(()) => {
6449 task.last_error = Some(format!("{e:#}"));
6450 task.review_branch = Some(d.branch.clone());
6453 task.review_instruction = Some(task.instruction.clone());
6454 task.block(vec![q.id.clone()], Some(d.summary()));
6455 }
6456 Err(put) => {
6457 tracing::warn!("could not file the divergence question: {put:#}");
6458 task.attempts += 1;
6459 task.fail_startup(
6460 "startup-question-store",
6461 format!("{start_failed}{e:#}"),
6462 opts.max_attempts,
6463 );
6464 }
6465 }
6466 record(queue, task);
6467 return Vec::new();
6468 }
6469 Err(e) => {
6470 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
6476 && let Starter::Review(branch) = &starter
6477 {
6478 task.review_branch = Some(branch.clone());
6479 task.review_instruction = Some(task.instruction.clone());
6480 task.last_error = Some(format!("{start_failed}{e:#}"));
6481 task.status = crate::queue::TaskStatus::Failed;
6482 record(queue, task);
6483 return Vec::new();
6484 }
6485 task.attempts += 1;
6486 task.last_error = Some(format!("{start_failed}{e:#}"));
6487 task.startup_notice_cause("startup-source");
6488 task.hold_unrequested_retry(Some(format!(
6489 "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
6490 )));
6491 record(queue, task);
6492 return Vec::new();
6493 }
6494 };
6495 if !matches!(starter, Starter::Resume(_))
6496 && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
6497 {
6498 runner
6499 .state
6500 .event("build-cache", format!("{mode} selected by {source}"));
6501 }
6502 if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
6503 runner.state.recovery_config = Some(config_evidence);
6504 }
6505 if let Some(replacement) = &task.replacement {
6506 if matches!(starter, Starter::Start) {
6507 runner.state.instruction.push_str(&format!(
6508 "\n\n# Replacement review context\n{}",
6509 replacement.context
6510 ));
6511 }
6512 runner.state.replaces = Some(replacement.clone());
6513 runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
6514 if let Ok(mut old) = RunState::load(&replacement.run)
6515 && let Some(d) = &mut old.merge_decision
6516 {
6517 d.replacement_run = Some(runner.state.id.clone());
6518 old.event(
6519 "replacement",
6520 format!(
6521 "replacement run {} owns the next attempt; old PR remains closed",
6522 runner.state.id
6523 ),
6524 );
6525 if let Err(e) = old.save() {
6526 let error = runner.fail_startup("replacement-history", e);
6527 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6528 task.record_startup_failure(failure.clone());
6529 }
6530 task.hold_manual(Some(format!(
6531 "Could not link replacement history: {error:#}; no agents dispatched"
6532 )));
6533 record(queue, task);
6534 return Vec::new();
6535 }
6536 }
6537 }
6538 runner.state.task_instruction = Some(task.instruction.clone());
6539 runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
6542 if runner.state.origin_chat.is_none() {
6543 runner.state.origin_chat = task.chat_talk().map(str::to_owned);
6544 }
6545 runner.on_pause(stop.pause());
6547 runner.watch_interrupt(interrupt_pause);
6551
6552 let run = runner.state.id.clone();
6555 let before_start = task.clone();
6556 task.start(run.clone());
6557 if let Err(error) = queue.put(task) {
6558 *task = before_start;
6559 let error = runner.fail_startup("task-start", error);
6560 if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6561 task.record_startup_failure(failure.clone());
6562 }
6563 task.hold_manual(Some(format!(
6564 "Could not persist task start; no agents dispatched: {error:#}"
6565 )));
6566 record(queue, task);
6567 return Vec::new();
6568 }
6569 if task.status != TaskStatus::Running {
6570 return Vec::new();
6572 }
6573 lock(status).current.push(Current {
6574 worker: None,
6575 task: task.id.clone(),
6576 run,
6577 });
6578
6579 let quota_before = runner.state.quota.clone();
6582 runner.state.carry_dispatched_resumes(task);
6583 runner.state.entry_resumption_generation =
6584 Some(task.resumption.as_ref().map_or(0, |r| r.generation));
6585 if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
6586 && runner.state.id == run
6587 {
6588 crate::head_e2e_stop::record_consumed_approval(
6589 &mut runner.state,
6590 &task.id,
6591 &stop_id,
6592 generation,
6593 approval_at,
6594 );
6595 }
6596 runner.state.next_pass_task_entry = true;
6597 let result = runner.execute().await;
6598 finish_attempt(
6599 opts.max_attempts,
6600 queue,
6601 task,
6602 &runner.state,
6603 "a_before,
6604 result,
6605 )
6606}
6607
6608async fn attempt_sync_only(
6609 queue: &Queue,
6610 status: &Arc<Mutex<Status>>,
6611 stop: &Stop,
6612 interrupt: crate::graph::Pause,
6613 task: &mut Task,
6614 request: crate::base_sync_only::Request,
6615) {
6616 let result = async {
6617 anyhow::ensure!(
6618 task.status == TaskStatus::Queued
6619 && task.execution_runs().last() == Some(&request.run)
6620 && task.resume_override.as_ref().is_some_and(
6621 |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
6622 ),
6623 "sync-base-only request no longer owns the exact queued run"
6624 );
6625 let mut runner = Runner::resume(&request.run)?;
6626 anyhow::ensure!(
6627 public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
6628 .await?
6629 .is_none(),
6630 "the task still has a public execution owner"
6631 );
6632 anyhow::ensure!(
6633 !stop.parking() && !interrupt.parked(),
6634 "paused before base synchronization"
6635 );
6636 let original = task.clone();
6637 task.start(request.run.clone());
6638 task.attempts = original.attempts;
6639 if let Err(error) = queue.put(task) {
6640 *task = original;
6641 return Err(error);
6642 }
6643 if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
6644 return Ok(());
6645 }
6646 lock(status).current.push(Current {
6647 worker: None,
6648 task: task.id.clone(),
6649 run: request.run.clone(),
6650 });
6651 runner.on_pause(stop.pause());
6652 runner.watch_interrupt(interrupt);
6653 runner.execute_sync_only(request.clone()).await
6654 }
6655 .await;
6656 if task.sync_only.as_ref() == Some(&request) {
6657 let saved = RunState::load(&request.run).ok();
6658 let detail = result.err().map(|error| {
6659 format!("Base synchronization only: {error:#}; verification was not allowed")
6660 });
6661 crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
6662 record(queue, task);
6663 }
6664}
6665
6666pub fn finish_attempt(
6671 max_attempts: usize,
6672 queue: &Queue,
6673 task: &mut Task,
6674 state: &RunState,
6675 quota_before: &[QuotaLoss],
6676 result: Result<()>,
6677) -> Vec<QuotaLoss> {
6678 let detail = match result {
6679 Ok(()) => describe(state),
6680 Err(e) => format!("{e:#}"),
6681 };
6682 let fresh = losses_this_attempt(quota_before, &state.quota);
6683 let verdict = Verdict {
6684 status: state.status,
6685 left_pr: state.pr.is_some(),
6688 quota_hit: !fresh.is_empty(),
6694 parked: state.parked,
6698 no_viable_candidates: state.viable().is_empty(),
6701 };
6702 if let Some(replacement) = &state.replaces
6703 && let Some(pr) = &state.pr
6704 && let Ok(mut old) = RunState::load(&replacement.run)
6705 && let Some(d) = &mut old.merge_decision
6706 {
6707 d.replacement_pr = Some(pr.url.clone());
6708 let _ = old.save();
6709 }
6710 settle_and_diagnose(task, verdict, &detail, max_attempts, state);
6711 if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
6712 task.hold_unrequested_retry(Some(format!(
6713 "Candidate setup failed: {detail}. Correct the explicit sources with `magi task sources {}` (README, \"Use\": implementation imports), or select a complete implementation with `magi task recover-pr`, then explicitly release the task.",
6714 task.short()
6715 )));
6716 }
6717 if task.status == TaskStatus::Done {
6718 supersede_prior_runs(task, &crate::run::home());
6719 }
6720 record(queue, task);
6721 tracing::info!(
6722 "task {} is {} after run {} ({})",
6723 task.short(),
6724 task.status.as_str(),
6725 state.short(),
6726 label(state.status)
6727 );
6728 fresh
6729}
6730
6731pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
6735 if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
6738 && !awaiting_resume_with(task, RunState::load)
6739 && withheld_text_wait(task).is_none()
6743 && !(task.fresh_start && task.replacement.is_some())
6744 {
6745 let why = task.last_error.clone().map_or_else(
6746 || "the run did not finish".to_owned(),
6747 |e| format!("the run did not finish: {e}"),
6748 );
6749 task.hold_unrequested_retry(Some(format!(
6750 "{why}. It was started by hand, so it is not retried \
6751 automatically; `magi task release` retries it."
6752 )));
6753 record(queue, task);
6754 }
6755}
6756
6757#[must_use]
6761pub fn loop_would_resume(run: &str) -> bool {
6762 unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
6763}
6764
6765#[must_use]
6775pub fn foreign_loop(
6776 reading: Option<&Reading>,
6777 now: Timestamp,
6778 own_pid: u32,
6779) -> Option<Option<u32>> {
6780 let reading = reading.filter(|r| r.running(now))?;
6781 match reading.pid {
6782 Some(pid) if pid == own_pid => None,
6783 pid => Some(pid),
6784 }
6785}
6786
6787fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
6788 reading.worker_protocol != Some(1)
6789 && (foreign_loop(Some(reading), now, own_pid).is_some()
6790 || reading
6791 .pid
6792 .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
6793}
6794
6795pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
6806 run_claimed_until(opts, queue, task, &Stop::new()).await;
6807}
6808
6809async fn run_claimed_until(
6810 opts: &Opts,
6811 queue: &Queue,
6812 task: &mut Task,
6813 stop: &Stop,
6814) -> Vec<QuotaLoss> {
6815 let status = Arc::new(Mutex::new(Status::new()));
6816 let mut quota = Box::pin(attempt(
6819 opts,
6820 queue,
6821 &status,
6822 stop,
6823 crate::graph::Pause::new(),
6824 task,
6825 ))
6826 .await;
6827 let mut resumes = 0;
6836 while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
6837 let Some(timeout) = withheld_text_wait(task) else {
6838 break;
6839 };
6840 eprintln!(
6841 "waiting for the owner's answer on a withheld pull request text \
6842 (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
6843 );
6844 let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
6847 let ready = loop {
6848 match land_resume_state(task) {
6849 LandResume::StillWaiting
6850 if !stop.parking() && std::time::Instant::now() < limit =>
6851 {
6852 tokio::time::sleep(WITHHELD_POLL).await;
6853 }
6854 LandResume::Ready => break true,
6855 _ => break false,
6856 }
6857 };
6858 if !ready || stop.parking() {
6859 break;
6860 }
6861 resumes += 1;
6862 quota.extend(
6863 Box::pin(attempt(
6864 opts,
6865 queue,
6866 &status,
6867 stop,
6868 crate::graph::Pause::new(),
6869 task,
6870 ))
6871 .await,
6872 );
6873 }
6874 hold_if_runnable(queue, task);
6875 quota
6876}
6877
6878const MAX_WITHHELD_RESUMES: u32 = 3;
6881
6882const WITHHELD_POLL: Duration = Duration::from_secs(15);
6884
6885fn withheld_text_wait(task: &Task) -> Option<u64> {
6888 let id = task.execution_runs().last()?;
6889 let s = RunState::load(id).ok()?;
6890 (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
6891 .then_some(s.config.graph.answer_timeout)
6892}
6893
6894fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
6904 after
6905 .iter()
6906 .filter(|q| !before.contains(q))
6907 .cloned()
6908 .collect()
6909}
6910
6911fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
6914 let quota: Vec<_> = quota
6915 .iter()
6916 .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
6917 .collect();
6918 if quota.is_empty() {
6919 return None;
6920 }
6921 let with_hint = quota.iter().find(|q| q.reset.is_some());
6922 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
6923 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
6924 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
6925 Some(
6926 now.checked_add(jiff::SignedDuration::from_secs(secs))
6927 .unwrap_or(Timestamp::MAX),
6928 )
6929}
6930
6931fn implementers_match(task: &Task, state: &RunState) -> bool {
6933 task.replacement.as_ref().map_or_else(
6934 || {
6935 task.implementers()
6936 .is_none_or(|n| n == state.config.graph.implementers)
6937 },
6938 |replacement| {
6939 state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
6940 && state.config.graph.implementers == 1
6941 },
6942 )
6943}
6944
6945fn starter_with_implementers(
6947 task: &Task,
6948 previous: Option<&RunState>,
6949 proposed: Starter,
6950) -> Starter {
6951 if previous.is_some_and(|s| !implementers_match(task, s)) {
6952 task.review_of
6953 .as_ref()
6954 .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
6955 } else {
6956 proposed
6957 }
6958}
6959
6960fn apply_task_implementers(config: &mut Config, task: &Task) {
6962 if let Some(n) = task.implementers() {
6963 config.graph.implementers = n;
6964 }
6965}
6966
6967#[cfg(test)]
6972fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
6973 let explicit = match &task.overrides {
6974 Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
6975 _ => opts.config.as_deref(),
6976 };
6977 let (mut config, _) = Config::discover(repo, explicit)?;
6978 apply_options(&mut config, opts, task)?;
6979 Ok(config)
6980}
6981
6982fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
6983 if task
6984 .overrides
6985 .as_ref()
6986 .is_none_or(|o| o.inherit_daemon_options)
6987 && let Some(mode) = opts.merge.as_deref()
6988 {
6989 config.merge.mode = merge_mode(mode)?;
6990 }
6991 if let Some(o) = &task.overrides {
6992 o.apply(config);
6993 }
6994 if let Some((mode, _)) = task.build_cache_override(config) {
6995 config.verify.build_cache = mode;
6996 }
6997 Ok(())
6998}
6999
7000fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
7002 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
7003 if let Some(mode) = &opts.merge {
7004 config.merge.mode = merge_mode(mode)?;
7005 }
7006 Ok(config)
7007}
7008
7009async fn maybe_prune_cache_between_runs(
7014 repo: &Path,
7015 opts: &Opts,
7016 home: &Path,
7017 stop: &Stop,
7018 last_checked: &mut Option<Timestamp>,
7019 now: Timestamp,
7020) {
7021 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
7022 return;
7023 }
7024 *last_checked = Some(now);
7025 let cfg = match prepare(repo, opts) {
7026 Ok(cfg) => cfg,
7027 Err(e) => {
7028 tracing::warn!("cache check: no config: {e:#}");
7029 return;
7030 }
7031 };
7032 match clean::prune_cache_if_over_limit(&cfg, home) {
7033 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
7034 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
7035 pruned.files,
7036 pruned.freed
7037 ),
7038 Ok(_) => {}
7039 Err(e) => {
7040 tracing::warn!("housekeep: prune cache: {e:#}");
7041 notices::raise_in(
7042 home,
7043 Notice::warn(
7044 "housekeep:cache",
7045 format!(
7046 "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
7047 e.to_string()
7048 .lines()
7049 .next()
7050 .unwrap_or("unknown cleanup error")
7051 ),
7052 ),
7053 );
7054 }
7055 }
7056}
7057
7058fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
7062 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
7063}
7064
7065async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
7084 let cfg = match prepare(repo, opts) {
7085 Ok(cfg) => cfg,
7086 Err(e) => {
7087 tracing::warn!("housekeep: no config: {e:#}");
7088 return;
7089 }
7090 };
7091 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
7100 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
7101 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
7106 let mut extra = Vec::new();
7107 if out.unreadable > 0 {
7108 extra.push(format!("{} unreadable", out.unreadable));
7109 }
7110 if out.orphaned_worktrees > 0 {
7111 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
7112 }
7113 let detail = if extra.is_empty() {
7114 String::new()
7115 } else {
7116 format!(" ({})", extra.join(", "))
7117 };
7118 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
7119 }
7120 if out.external_merges_recorded > 0 {
7121 tracing::info!(
7122 "housekeep: recorded {} run(s) as merged externally",
7123 out.external_merges_recorded
7124 );
7125 }
7126 if out.stale_pr_states_repaired > 0 {
7127 tracing::info!(
7128 "housekeep: rewrote {} run record(s) whose pull request had already settled",
7129 out.stale_pr_states_repaired
7130 );
7131 }
7132 if out.cache_files > 0 {
7133 tracing::info!(
7134 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
7135 out.cache_files,
7136 out.cache_freed
7137 );
7138 }
7139 if out.questions_abandoned > 0 {
7140 tracing::info!(
7141 "housekeep: abandoned {} question(s) left open by a finished run",
7142 out.questions_abandoned
7143 );
7144 }
7145}
7146
7147async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
7156 let questions = Questions::at(home.join("questions"));
7157 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
7158 if report.is_empty() {
7159 return;
7160 }
7161 if !report.quarantined.is_empty() {
7162 tracing::info!(
7163 "triage: held {} blocked task(s) whose blocked-on task or \
7164 question no longer exists: {}",
7165 report.quarantined.len(),
7166 report.quarantined.join(", ")
7167 );
7168 }
7169 if !report.resumed.is_empty() {
7170 tracing::info!(
7171 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
7172 report.resumed.len(),
7173 report.resumed.join(", ")
7174 );
7175 }
7176 if !report.asked.is_empty() {
7177 tracing::info!(
7178 "triage: asked about {} held task(s): {}",
7179 report.asked.len(),
7180 report.asked.join(", ")
7181 );
7182 }
7183 if !report.answered.is_empty() {
7184 tracing::info!(
7185 "triage: applied {} operator answer(s): {}",
7186 report.answered.len(),
7187 report.answered.join(", ")
7188 );
7189 }
7190}
7191
7192pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
7199 disk_gate_at(repo, config, crate::run::home)
7200}
7201
7202pub(crate) fn disk_gate_at(
7203 repo: &Path,
7204 config: &Config,
7205 home: impl FnOnce() -> PathBuf,
7206) -> Option<String> {
7207 let measure = if crate::build_target::isolated(config) {
7208 crate::disk::managed_free_bytes
7209 } else {
7210 crate::disk::free_bytes
7211 };
7212 disk_gate_with(repo, config, home, measure)
7213}
7214
7215fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
7219 repo: &Path,
7220 config: &Config,
7221 home: impl FnOnce() -> PathBuf,
7222 free_bytes: F,
7223) -> Option<String> {
7224 let min = config.disk.min_free_bytes;
7225 if min == 0 {
7226 return None;
7227 }
7228 let output = match config.verify.build_cache {
7229 BuildCache::Shared => config.cache_dir(),
7230 BuildCache::Isolated => Some(home()),
7231 };
7232 let default_worktree_root;
7233 let worktree_root = match config.graph.worktree_root.as_deref() {
7234 Some(root) => root,
7235 None => {
7236 default_worktree_root = crate::run::default_worktree_root();
7237 &default_worktree_root
7238 }
7239 };
7240 for path in [Some(repo), output.as_deref(), Some(worktree_root)]
7241 .into_iter()
7242 .flatten()
7243 {
7244 let probe = if path == repo {
7245 path
7246 } else {
7247 path.ancestors().find(|p| p.exists()).unwrap_or(path)
7248 };
7249 let reason = match free_bytes(probe) {
7250 Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
7251 Err(e) => Some(crate::disk::unmeasured_in(
7252 probe,
7253 &e,
7254 &config.graph.language,
7255 )),
7256 };
7257 if reason.is_some() {
7258 return reason;
7259 }
7260 }
7261 None
7262}
7263
7264const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
7271
7272const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
7276
7277fn quota_wait(
7286 reset_at: Option<Timestamp>,
7287 now: Timestamp,
7288 fallback: Duration,
7289 cap: Duration,
7290) -> Duration {
7291 match reset_at {
7292 Some(at) if at > now => {
7293 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
7294 Duration::from_secs(secs).min(cap)
7295 }
7296 _ => fallback,
7297 }
7298}
7299
7300fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
7314 parse_reset_hint_zoned(text, now)
7315 .or_else(|| parse_reset_hint_dated(text))
7316 .or_else(|| parse_reset_hint_relative(text, recorded))
7317}
7318
7319fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
7323 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
7324 let mut rest = rest.trim();
7325 if rest.is_empty() {
7326 return None;
7327 }
7328 let mut total: i64 = 0;
7329 let mut matched = false;
7330 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
7331 if let Some((digits, tail)) = rest.split_once(unit)
7332 && !digits.is_empty()
7333 && digits.bytes().all(|b| b.is_ascii_digit())
7334 {
7335 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
7336 rest = tail;
7337 matched = true;
7338 }
7339 }
7340 if !rest.is_empty() || !matched {
7341 return None;
7342 }
7343 recorded
7344 .checked_add(jiff::SignedDuration::from_secs(total))
7345 .ok()
7346}
7347
7348fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
7352 let clock = clock.trim().to_lowercase();
7353 let (digits, pm) = clock
7354 .strip_suffix("am")
7355 .map(|d| (d, false))
7356 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
7357 let (h, m) = digits.trim().split_once(':')?;
7358 let mut hour: i8 = h.trim().parse().ok()?;
7359 let minute: i8 = m.trim().parse().ok()?;
7360 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
7361 return None;
7362 }
7363 if pm && hour != 12 {
7364 hour += 12;
7365 } else if !pm && hour == 12 {
7366 hour = 0;
7367 }
7368 Some((hour, minute))
7369}
7370
7371fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
7376 let open = text.find('(')?;
7377 let close = text.rfind(')')?;
7378 if close <= open {
7379 return None;
7380 }
7381 let zone = text[open + 1..close].trim();
7382 let (hour, minute) = parse_12h_clock(&text[..open])?;
7383 let tz = jiff::tz::TimeZone::get(zone).ok()?;
7384 let candidate = now
7385 .to_zoned(tz)
7386 .with()
7387 .hour(hour)
7388 .minute(minute)
7389 .second(0)
7390 .millisecond(0)
7391 .microsecond(0)
7392 .nanosecond(0)
7393 .build()
7394 .ok()?;
7395 let mut at = candidate.timestamp();
7396 if at <= now {
7397 at += jiff::SignedDuration::from_hours(24);
7398 }
7399 Some(at)
7400}
7401
7402fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
7411 let words: Vec<&str> = text.split_whitespace().collect();
7412 if words.len() < 5 {
7413 return None;
7414 }
7415 (0..=words.len() - 5)
7416 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
7417}
7418
7419fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
7425 if trailing.is_some_and(|next| next.starts_with('(')) {
7426 return None;
7427 }
7428 let month = month_number(window[0])?;
7429 let day_token = window[1].strip_suffix(',')?.to_lowercase();
7430 let day_digits = ["st", "nd", "rd", "th"]
7431 .iter()
7432 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
7433 let day: i8 = day_digits.parse().ok()?;
7434 let year_token = window[2];
7435 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
7436 return None;
7437 }
7438 let year: i16 = year_token.parse().ok()?;
7439 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
7443 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
7444 let date = jiff::civil::Date::new(year, month, day).ok()?;
7445 let candidate = date
7446 .at(hour, minute, 0, 0)
7447 .to_zoned(jiff::tz::TimeZone::UTC)
7448 .ok()?;
7449 Some(candidate.timestamp())
7450}
7451
7452fn month_number(name: &str) -> Option<i8> {
7455 const NAMES: [&str; 12] = [
7456 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
7457 ];
7458 let lower = name.to_lowercase();
7459 NAMES
7460 .iter()
7461 .position(|n| *n == lower.as_str())
7462 .map(|i| i as i8 + 1)
7463}
7464
7465#[cfg(test)]
7467fn exhausted_review_budget(state: &RunState) -> bool {
7468 !crate::handover::can_resume(state)
7471 && state.status == RunStatus::Blocked
7472 && !state.released()
7473 && state.retired_to.is_none()
7474}
7475
7476fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
7513 unfinished_run_with(runs, short, RunState::load)
7514}
7515
7516pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
7519where
7520 F: FnMut(&str) -> Result<RunState>,
7521{
7522 let mut id = runs.last()?.clone();
7523 let mut visited = std::collections::BTreeSet::new();
7524 let mut repo = None;
7525 loop {
7526 if !runs.contains(&id) || !visited.insert(id.clone()) {
7527 tracing::warn!("invalid or cyclic recovery authority for task {short}");
7528 return None;
7529 }
7530 let state = match load(&id) {
7531 Ok(state) if state.id == id => state,
7532 Ok(_) => return None,
7533 Err(e) => {
7534 tracing::warn!("could not read run {id} for task {short}: {e:#}");
7535 return None;
7536 }
7537 };
7538 if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
7539 return None;
7540 }
7541 repo = Some(state.repo.clone());
7542 if let Some(authority) = state.retired_to {
7543 id = authority;
7544 continue;
7545 }
7546 return (crate::handover::can_resume(&state)
7547 && state.liveness(false) != crate::run::Liveness::Live)
7548 .then_some(id);
7549 }
7550}
7551
7552fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
7560where
7561 F: FnOnce(&str) -> Result<RunState>,
7562{
7563 if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
7565 || task.fresh_start
7566 || task.review_branch.is_some()
7567 {
7568 return false;
7569 }
7570 let Some(id) = task.execution_runs().last() else {
7571 return false;
7572 };
7573 load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
7574}
7575
7576#[derive(Debug, Clone, PartialEq, Eq)]
7579enum Starter {
7580 Review(String),
7583 Resume(String),
7585 Start,
7587}
7588
7589fn retained_attempt_hold(
7594 task: &Task,
7595 starter: &Starter,
7596 limit: usize,
7597 mut load: impl FnMut(&str) -> Result<RunState>,
7598) -> Option<String> {
7599 if limit == 0 || matches!(starter, Starter::Resume(_)) {
7600 return None;
7601 }
7602 let mut retained = 0;
7603 for id in task
7604 .runs
7605 .iter()
7606 .chain(task.startup_failures.iter().map(|failure| &failure.run))
7607 .collect::<std::collections::BTreeSet<_>>()
7608 {
7609 let state = match load(id) {
7610 Ok(state) if state.id == *id => state,
7611 _ => {
7612 return Some(format!(
7613 "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
7614 ));
7615 }
7616 };
7617 if state.retired_to.is_some() || state.released() {
7618 continue;
7619 }
7620 retained += 1;
7623 }
7624 (retained >= limit).then(|| format!(
7625 "[recovery-backlog] {retained} unretired attempts reach the limit of {limit}. Resume an existing recovery owner or inspect the lineage and retire proved-obsolete attempts before creating another run. Releases, refunds and changed upstream inputs do not reset this limit. No source or historical report was removed."
7626 ))
7627}
7628
7629fn selected_starter(
7631 selected: &crate::pr_recovery::Selection,
7632 previous: Option<&RunState>,
7633 unfinished: Option<&str>,
7634) -> Starter {
7635 if let Some(id) = unfinished
7636 && previous.is_some_and(|r| {
7637 r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
7638 })
7639 {
7640 Starter::Resume(id.to_owned())
7641 } else {
7642 Starter::Review(selected.branch.clone())
7643 }
7644}
7645
7646fn take_divergence_answer(
7650 branch: &str,
7651 remote: &str,
7652 task: &mut Task,
7653) -> Option<crate::reconcile::Choice> {
7654 let summary = crate::reconcile::summary_for(branch, remote);
7655 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
7656 (a.question == summary)
7657 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
7658 .flatten()
7659 .map(|c| (i, c))
7660 })?;
7661 task.answers.remove(idx);
7662 Some(choice)
7663}
7664
7665fn choose_starter(
7677 review_branch: Option<&str>,
7678 branch_exists: bool,
7679 unfinished: Option<&str>,
7680) -> Starter {
7681 match review_branch {
7682 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
7683 Some(_) => Starter::Start,
7684 None => match unfinished {
7685 Some(id) => Starter::Resume(id.to_owned()),
7686 None => Starter::Start,
7687 },
7688 }
7689}
7690
7691fn review_retry_starter(
7695 task: &Task,
7696 previous: Option<&RunState>,
7697 branch: Option<&str>,
7698 exists: bool,
7699 unfinished: Option<&str>,
7700) -> Starter {
7701 if let Some(run) = previous
7702 && unfinished == Some(run.id.as_str())
7703 && run.reviewed_commits.is_some()
7704 && branch.is_some_and(|branch| {
7705 exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
7706 })
7707 && may_resume_run(run, task)
7708 {
7709 return Starter::Resume(run.id.clone());
7710 }
7711 match (branch, unfinished, &task.review_of) {
7712 (None, None, Some(branch)) => Starter::Review(branch.clone()),
7713 _ => choose_starter(branch, exists, unfinished),
7714 }
7715}
7716
7717fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
7719 task.review_branch
7720 .as_deref()
7721 .filter(|&branch| match &task.review_instruction {
7722 Some(authored) => *authored == task.instruction,
7723 None => previous.map_or_else(
7726 || task.review_of.as_deref() == Some(branch),
7727 |run| compatible_run_instruction(run, task),
7728 ),
7729 })
7730}
7731
7732fn may_resume_run(run: &RunState, task: &Task) -> bool {
7735 if !task.assignment_accepts(run) {
7736 return false;
7737 }
7738 task.resume_override
7739 .as_ref()
7740 .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
7741 || compatible_run_instruction(run, task)
7742}
7743
7744pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
7746 if let Some(authored) = &run.task_instruction {
7747 return compatible_instruction(authored, task);
7748 }
7749 if compatible_instruction(&run.instruction, task) {
7750 return true;
7751 }
7752 if run.reviewed_commits.is_some() {
7755 if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
7756 return strip_answers_block(authored, task).trim() == task.instruction.trim();
7757 }
7758 if let Some(branch) = &task.review_of {
7759 let canonical = format!(
7760 "Review the branch `{branch}` (review-only: no implementation, no judging)."
7761 );
7762 let generated = format!(
7763 "Review the work already on branch `{branch}`. There is no task statement: what the change claims to do is whatever its commits say.\n\n"
7764 );
7765 return task.instruction == canonical && run.instruction.starts_with(&generated);
7766 }
7767 }
7768 false
7769}
7770
7771pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
7773 strip_answers_block(old, task) == task.instruction
7774}
7775
7776fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
7779 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
7780 return fallback.to_path_buf();
7781 }
7782 task.repo.clone()
7783}
7784
7785const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
7789
7790fn answers_block(task: &Task, count: usize) -> String {
7792 let mut s = ANSWERS_HEADER.to_owned();
7793 for a in &task.answers[..count] {
7794 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
7795 }
7796 s
7797}
7798
7799fn resumption_block(r: &crate::queue::Resumption) -> String {
7802 format!(
7803 "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
7804 Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
7805 r.generation, r.at, r.instruction, r.answers_through,
7806 )
7807}
7808
7809fn append_answers(base: &str, task: &Task) -> String {
7811 let mut s = base.to_owned();
7812 if !task.answers.is_empty() {
7813 s.push_str(&answers_block(task, task.answers.len()));
7814 }
7815 if let Some(r) = &task.resumption {
7816 s.push_str(&resumption_block(r));
7817 }
7818 s
7819}
7820
7821fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
7825 let mut instruction = instruction;
7826 for approval in task
7827 .resumption
7828 .iter()
7829 .chain(task.resumption_history.iter().rev())
7830 {
7831 if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
7832 instruction = base;
7833 break;
7834 }
7835 }
7836 for count in (1..=task.answers.len()).rev() {
7837 let block = answers_block(task, count);
7838 if let Some(base) = instruction.strip_suffix(&block) {
7839 return base;
7840 }
7841 }
7842 instruction
7843}
7844
7845fn instruction_for(task: &Task) -> String {
7853 append_answers(&task.instruction, task)
7854}
7855
7856fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
7868 append_answers(strip_answers_block(old_instruction, task), task)
7869}
7870
7871fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
7873 let failure = error.downcast_ref::<crate::config::ConfigFailure>();
7874 task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
7875 if let Some(cause) = task.hold_notice_cause.as_mut() {
7876 cause.target = failure.map(|f| f.target.clone());
7877 }
7878}
7879
7880#[derive(Debug, thiserror::Error)]
7881#[error("attachment `{name}` is recorded on the task but {path} is missing")]
7882struct MissingAttachment {
7883 name: String,
7884 path: PathBuf,
7885}
7886
7887fn task_attachments(
7889 queue: &Queue,
7890 task: &Task,
7891) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
7892 let paths = queue.attachment_paths(task);
7893 for (name, path) in task.attachments.iter().zip(&paths) {
7894 if !path.is_file() {
7895 return Err(MissingAttachment {
7896 name: name.clone(),
7897 path: path.clone(),
7898 });
7899 }
7900 }
7901 Ok(paths)
7902}
7903
7904fn prepare_instruction(
7915 starter: &Starter,
7916 old_instruction: Option<&str>,
7917 task: &Task,
7918) -> Option<String> {
7919 match starter {
7920 Starter::Start => Some(instruction_for(task)),
7921 Starter::Resume(_) => Some(resumed_instruction(
7922 old_instruction.expect("a resumed run always has a prior instruction"),
7923 task,
7924 )),
7925 Starter::Review(_) => None,
7926 }
7927}
7928
7929fn record(queue: &Queue, task: &mut Task) {
7933 if let Err(e) = queue.put(task) {
7934 tracing::error!("could not record task {}: {e:#}", task.short());
7935 let notice = Notice::error(
7936 "loop:record",
7937 format!(
7938 "Task {} state could not be saved: {}. Check the disk.",
7939 task.id,
7940 e.to_string().lines().next().unwrap_or("unknown save error")
7941 ),
7942 )
7943 .link(Link::Task {
7944 id: task.id.clone(),
7945 });
7946 match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
7948 Some(home) => notices::raise_in(home, notice),
7949 None => notices::raise(notice),
7950 }
7951 }
7952}
7953
7954fn runnable(queue: &Queue) -> Vec<Task> {
7960 let mut tasks: Vec<Task> = queue
7961 .list()
7962 .into_iter()
7963 .filter(|t| t.status.runnable())
7964 .collect();
7965 tasks.sort_unstable_by(crate::queue::dispatch_order);
7966 tasks
7967}
7968
7969fn describe(state: &RunState) -> String {
7983 let p = phrases(&state.config.graph.language);
7984 let mut detail = if state.status == RunStatus::Stalled {
7985 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
7986 seats.sort_unstable();
7987 seats.dedup();
7988 if seats.is_empty() {
7989 p.quorum_lost.to_owned()
7990 } else {
7991 format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
7992 }
7993 } else {
7994 format!("{}{}", p.run_ended, state.status.display_label())
7995 };
7996 if let Some(cause) = state.verification_blocking_cause() {
7997 detail.push_str(&format!(" ({cause})"));
7998 } else if let Some(last) = state.events.last() {
7999 let unanswered = state
8003 .reviews
8004 .last()
8005 .filter(|r| {
8006 state.status == RunStatus::Blocked
8007 && last.node == "review"
8008 && r.incomplete()
8009 && r.blocking == 0
8010 && r.round == state.config.graph.review_rounds
8011 && r.e2e.iter().all(crate::run::CommandOutcome::ok)
8012 })
8013 .map(|r| (r.expected - r.answered, r.round));
8014 match unanswered {
8015 Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
8016 detail.push_str(&format!(
8017 " ({}: {})",
8018 last.node,
8019 (p.reviewers_never_answered)(missing, rounds)
8020 ));
8021 }
8022 _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
8023 }
8024 }
8025 detail.push_str(&format!(" [run {}]", state.id));
8026 detail
8027}
8028
8029const DIAGNOSTIC_MAX: usize = 4_000;
8035
8036const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
8041
8042pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
8056 diagnostic(state)
8057}
8058
8059fn diagnostic(state: &RunState) -> Option<String> {
8060 let mut parts: Vec<String> = Vec::new();
8061
8062 if let Some(e2e) = &state.head_e2e
8063 && !e2e.passed
8064 {
8065 for o in e2e
8066 .outcomes
8067 .iter()
8068 .filter(|o| !o.ok() && !o.resource_blocked)
8069 {
8070 parts.push(format!(
8071 "head_e2e `{}` failed on {} ({}):\n{}",
8072 o.command,
8073 e2e.head.chars().take(7).collect::<String>(),
8074 notices::exit_status(o.code),
8075 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8076 ));
8077 }
8078 }
8079
8080 for o in state.gate.iter().filter(|o| !o.ok()) {
8082 parts.push(format!(
8083 "gate `{}` failed ({}):\n{}",
8084 o.command,
8085 notices::exit_status(o.code),
8086 crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8087 ));
8088 }
8089
8090 if let Some(last) = state
8093 .events
8094 .iter()
8095 .rev()
8096 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
8097 {
8098 parts.push(last.message.clone());
8099 }
8100
8101 if state.viable().is_empty() {
8108 for c in &state.candidates {
8109 if c.has_valid_verified_noop()
8110 && let Some(evidence) = c.verified_noop_display()
8111 {
8112 parts.push(format!(
8113 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
8114 c.label
8115 ));
8116 } else if !c.summary.trim().is_empty() {
8117 if let Some(why) = &c.failed {
8118 parts.push(format!(
8119 "candidate {} ({why}): {}",
8120 c.label,
8121 c.summary.trim()
8122 ));
8123 } else {
8124 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
8125 }
8126 } else if let Some(why) = &c.failed {
8127 parts.push(format!("candidate {}: {why}", c.label));
8128 }
8129 }
8130 }
8131
8132 if parts.is_empty() {
8133 return None;
8134 }
8135 Some(crate::run::tail(
8140 &parts.join("\n\n"),
8141 DIAGNOSTIC_MAX.saturating_sub(100),
8142 ))
8143}
8144
8145fn label(status: RunStatus) -> &'static str {
8153 status.as_str()
8154}
8155
8156pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
8158 match mode {
8159 "none" => Ok(MergeMode::None),
8160 "local" => Ok(MergeMode::Local),
8161 "pr" => Ok(MergeMode::Pr),
8162 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
8163 }
8164}
8165
8166fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
8171 mutex
8172 .lock()
8173 .unwrap_or_else(std::sync::PoisonError::into_inner)
8174}
8175
8176#[cfg(test)]
8177mod tests {
8178 use super::*;
8179 use crate::queue::{Source, TaskStatus};
8180 use crate::run::{Candidate, CommandOutcome};
8181 use pretty_assertions::assert_eq;
8182
8183 fn task() -> Task {
8184 Task::new(
8185 "add retries".to_owned(),
8186 "add retries".to_owned(),
8187 PathBuf::from("/repo"),
8188 Source::Human,
8189 )
8190 }
8191
8192 #[test]
8193 fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
8194 let skips = DispatchSkips::from([
8195 ("a".into(), SkipReason::CoolingDown),
8196 ("b".into(), SkipReason::WaitingOnLanding),
8197 ("c".into(), SkipReason::WaitingOnLanding),
8198 ("d".into(), SkipReason::OrdinaryCapacity),
8199 ]);
8200 let wait = aggregate_dispatch_wait(4, &skips).unwrap();
8201 assert_eq!(wait.runnable, 4);
8202 assert_eq!(
8203 wait.reasons
8204 .iter()
8205 .map(|r| (r.reason.as_str(), r.count))
8206 .collect::<Vec<_>>(),
8207 [
8208 ("waiting_on_landing", 2),
8209 ("cooling_down", 1),
8210 ("ordinary_capacity", 1)
8211 ]
8212 );
8213 assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
8214 assert!(
8215 aggregate_dispatch_wait(2, &DispatchSkips::new())
8216 .unwrap()
8217 .reasons
8218 .is_empty()
8219 );
8220 }
8221
8222 #[test]
8223 fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
8224 let before = vec!["a".into(), "b".into(), "c".into()];
8225 let allowed = vec![task_with_id("b")];
8226 let skips = interrupt_skips(&before, &allowed);
8227 assert_eq!(
8228 skips,
8229 DispatchSkips::from([
8230 ("a".into(), SkipReason::InterruptGate),
8231 ("c".into(), SkipReason::InterruptGate),
8232 ])
8233 );
8234 let mut previous = DispatchSkips::new();
8235 assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8236 assert!(changed_dispatch_skips(&mut previous, skips.clone()));
8237 assert!(!changed_dispatch_skips(&mut previous, skips));
8238 assert!(changed_dispatch_skips(
8239 &mut previous,
8240 DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
8241 ));
8242 assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8243 }
8244
8245 #[test]
8246 fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
8247 let mut value = serde_json::to_value(Status::new()).unwrap();
8248 value.as_object_mut().unwrap().remove("dispatch_wait");
8249 assert!(
8250 serde_json::from_value::<Status>(value.clone())
8251 .unwrap()
8252 .dispatch_wait
8253 .is_none()
8254 );
8255 assert!(
8256 serde_json::from_value::<Reading>(value.clone())
8257 .unwrap()
8258 .dispatch_wait
8259 .is_none()
8260 );
8261 value["dispatch_wait"] = serde_json::json!({
8262 "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
8263 });
8264 let reading = serde_json::from_value::<Reading>(value).unwrap();
8265 assert_eq!(
8266 reading.dispatch_wait.unwrap().reasons[0].reason,
8267 "future_reason"
8268 );
8269 }
8270
8271 fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
8272 let job = crate::worker::Job {
8273 id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
8274 sequence: 1,
8275 kind: "task".into(),
8276 key: format!("task:{}", request.task),
8277 payload: serde_json::to_value(request).unwrap(),
8278 generation: "a".repeat(64),
8279 version: None,
8280 status: crate::worker::Status::Starting,
8281 result: None,
8282 pid: None,
8283 created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
8284 finished_at: None,
8285 };
8286 let dir = home.join("workers/jobs").join(&job.id);
8287 std::fs::create_dir_all(&dir).unwrap();
8288 std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
8289 job
8290 }
8291
8292 #[test]
8293 fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
8294 let home = tempfile::tempdir().unwrap();
8295 let request = TaskWorker {
8296 opts: Opts::default(),
8297 queue: home.path().join("queue"),
8298 task: "startup".into(),
8299 lane: PermitKind::Ordinary,
8300 standalone: false,
8301 };
8302 let job = starting_task_reservation(home.path(), &request);
8303 let error = task_worker_spawn_error(
8304 home.path(),
8305 &request,
8306 anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
8307 )
8308 .expect_err("our own reservation must not turn a failed spawn into a resync");
8309 let active = crate::worker::active(home.path()).unwrap();
8310 assert_eq!(active.len(), 1);
8311 assert_eq!(active[0].id, job.id);
8312 assert_eq!(active[0].status, crate::worker::Status::Starting);
8313 assert!(
8314 crate::worker::control(home.path(), &job.key)
8315 .unwrap()
8316 .is_none()
8317 );
8318 let notices = notices::Notices::at(home.path().join("notifications")).list();
8319 assert_eq!(notices.len(), 1);
8320 assert_eq!(notices[0].key, "loop:worker-startup");
8321 assert!(!notices[0].message.contains("private-error-detail"));
8322 assert!(notices[0].message.contains(&request.task));
8323 assert!(
8324 notices[0]
8325 .message
8326 .contains("could not be started or acknowledged")
8327 );
8328 assert!(notices[0].message.contains("worker.log"));
8329 assert_eq!(
8330 notices[0].link,
8331 Some(Link::Task {
8332 id: request.task.clone()
8333 })
8334 );
8335 assert!(format!("{error:#}").contains("private-error-detail"));
8336 }
8337
8338 #[test]
8339 fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
8340 let home = tempfile::tempdir().unwrap();
8341 let mut request = TaskWorker {
8342 opts: Opts::default(),
8343 queue: home.path().join("queue"),
8344 task: "handoff".into(),
8345 lane: PermitKind::Ordinary,
8346 standalone: true,
8347 };
8348 let job = starting_task_reservation(home.path(), &request);
8349 request.standalone = false;
8350 task_worker_spawn_error(
8351 home.path(),
8352 &request,
8353 anyhow::anyhow!("operation key is already reserved for a different request"),
8354 )
8355 .expect("a different standalone request is the handoff race, not our startup failure");
8356 let active = crate::worker::active(home.path()).unwrap();
8357 assert_eq!(active.len(), 1);
8358 assert_eq!(active[0].id, job.id);
8359 assert_eq!(active[0].payload, job.payload);
8360 assert!(
8361 notices::Notices::at(home.path().join("notifications"))
8362 .list()
8363 .is_empty()
8364 );
8365 }
8366
8367 #[test]
8368 fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
8369 let home = tempfile::tempdir().unwrap();
8370 let queue = Queue::at(home.path().join("queue"));
8371 let mut task = task();
8372 task.runs = vec!["previous".into()];
8373 queue.put(&mut task).unwrap();
8374 let request = TaskWorker {
8375 opts: Opts::default(),
8376 queue: home.path().join("queue"),
8377 task: task.id.clone(),
8378 lane: PermitKind::Ordinary,
8379 standalone: false,
8380 };
8381 let job = starting_task_reservation(home.path(), &request);
8382 let claims = current_work(home.path(), Timestamp::now());
8383 assert_eq!(claims.len(), 1);
8384 assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
8385 assert_eq!(claims[0].run, "previous");
8386 assert!(other_claims_run(&claims, "previous", None));
8387 assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
8390 assert!(is_working_on(home.path(), "previous", Timestamp::now()));
8391 }
8392
8393 #[test]
8394 fn admission_excludes_only_the_callers_exact_reservation() {
8395 let own = Current {
8396 worker: Some("own".into()),
8397 task: "same-task".into(),
8398 run: "previous".into(),
8399 };
8400 assert!(!other_claims_run(
8401 std::slice::from_ref(&own),
8402 "previous",
8403 Some("own")
8404 ));
8405 assert!(other_claims_run(
8406 std::slice::from_ref(&own),
8407 "previous",
8408 None
8409 ));
8410 for worker in [None, Some("other".into())] {
8411 let other = Current {
8412 worker,
8413 ..own.clone()
8414 };
8415 assert!(other_claims_run(
8416 &[own.clone(), other],
8417 "previous",
8418 Some("own")
8419 ));
8420 }
8421 let legacy: Current =
8422 serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
8423 assert!(other_claims_run(&[legacy], "previous", Some("own")));
8424 }
8425
8426 #[test]
8427 fn os_leased_task_worker_survives_wall_clock_advance() {
8428 let home = tempfile::tempdir().unwrap();
8429 let queue = Queue::at(home.path().join("queue"));
8430 let mut task = task();
8431 let run = "20260903-100000-abcd";
8432 task.start(run.into());
8433 queue.put(&mut task).unwrap();
8434 let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
8435 let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
8436 assert!(
8437 current_work(home.path(), future)
8438 .iter()
8439 .any(
8440 |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
8441 && claim.run == run
8442 )
8443 );
8444 worker.release_lease();
8445 assert!(worker.dir.join("job.json").is_file());
8446 assert!(!is_working_on(home.path(), run, future));
8447 let dir = worker.dir.clone();
8448 drop(worker);
8449 assert!(!dir.exists());
8450 }
8451
8452 #[test]
8453 fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
8454 let mut task = task();
8455 let mut run = run_state(RunStatus::Reviewing);
8456 run.task_instruction = Some(task.instruction.clone());
8457 run.reviewed_commits = Some(vec!["committed-fix".into()]);
8458 let branch = "magi/test/B";
8459 run.candidates.push(crate::run::Candidate {
8460 branch: branch.into(),
8461 ..candidate('B', "preserved work", false, None)
8462 });
8463 task.runs = vec![run.id.clone()];
8464 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
8465 assert_eq!(
8466 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8467 Starter::Resume(run.id.clone())
8468 );
8469 assert!(matches!(
8470 review_retry_starter(
8471 &task,
8472 Some(&run),
8473 Some("different"),
8474 true,
8475 unfinished.as_deref()
8476 ),
8477 Starter::Review(_)
8478 ));
8479 assert_eq!(
8480 review_retry_starter(
8481 &task,
8482 Some(&run),
8483 Some(branch),
8484 false,
8485 unfinished.as_deref()
8486 ),
8487 Starter::Start
8488 );
8489 task.instruction.push_str(" changed criteria");
8490 assert!(matches!(
8491 review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8492 Starter::Review(_)
8493 ));
8494 assert!(matches!(
8495 review_retry_starter(&task, Some(&run), Some(branch), true, None),
8496 Starter::Review(_)
8497 ));
8498 }
8499
8500 #[test]
8501 fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
8502 let dir = tempfile::tempdir().unwrap();
8503 let queue = Queue::at(dir.path().join("queue"));
8504 let mut task = task();
8505 task.status = TaskStatus::Running;
8506 task.attempts = 1;
8507 queue.put(&mut task).unwrap();
8508 let live = std::collections::BTreeSet::from([task.id.clone()]);
8509 assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
8510 drop(queue.claim(&task.id).unwrap());
8511 let saved = queue.get(&task.id).unwrap();
8512 assert_eq!(saved.status, TaskStatus::Running);
8513 assert_eq!(saved.attempts, 1);
8514 assert!(saved.last_error.is_none());
8515 }
8516
8517 #[test]
8518 fn standalone_workers_do_not_consume_scheduler_lanes() {
8519 let request = |task: &str, lane, standalone| TaskWorker {
8520 opts: Opts::default(),
8521 queue: PathBuf::from("/queue"),
8522 task: task.to_owned(),
8523 lane,
8524 standalone,
8525 };
8526 let mut jobs = vec![
8527 request("ordinary", PermitKind::Ordinary, false),
8528 request("standalone-urgent", PermitKind::Urgent, true),
8529 request("standalone-ordinary", PermitKind::Ordinary, true),
8530 request("decision", PermitKind::None, false),
8531 ];
8532 assert_eq!(available_slots(&jobs, 2), (1, 1));
8533 jobs.push(request("urgent", PermitKind::Urgent, false));
8534 assert_eq!(available_slots(&jobs, 2), (1, 0));
8535 assert_eq!(available_slots(&jobs, 0), (0, 0));
8536 }
8537
8538 #[test]
8539 fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
8540 let now = Timestamp::now();
8541 let mut reading = Reading {
8542 pid: Some(std::process::id()),
8543 updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
8544 ..Reading::default()
8545 };
8546 assert!(!reading.running(now));
8547 assert!(legacy_scheduler_running(&reading, now, 0));
8548 reading.worker_protocol = Some(1);
8549 assert!(!legacy_scheduler_running(&reading, now, 0));
8550 }
8551
8552 #[test]
8553 fn selected_public_head_overrides_historical_resume_and_pin() {
8554 let mut t = task();
8555 let mut old = run_state(RunStatus::Blocked);
8556 let selection = crate::pr_recovery::Selection {
8557 url: "url".into(),
8558 branch: format!("magi/task-{}", t.id),
8559 head: "a".repeat(40),
8560 source_head: None,
8561 source_run: None,
8562 source_proof: None,
8563 disposition: Some(crate::pr_recovery::Disposition::Review),
8564 instruction: t.instruction.clone(),
8565 approved_at: Timestamp::now(),
8566 };
8567 t.resume_override = Some(crate::queue::OperatorResume {
8568 pinned_run: Some(old.id.clone()),
8569 question_id: "choice".into(),
8570 at: Timestamp::now(),
8571 conductor_rehold: None,
8572 forced: false,
8573 });
8574 assert_eq!(
8575 selected_starter(&selection, Some(&old), Some(&old.id)),
8576 Starter::Review(selection.branch.clone())
8577 );
8578 old.pr_recovery = Some(selection.clone());
8579 assert_eq!(
8580 selected_starter(&selection, Some(&old), Some(&old.id)),
8581 Starter::Review(selection.branch.clone())
8582 );
8583 old.reviewed_commits = Some(vec!["implementation".into()]);
8584 assert_eq!(
8585 selected_starter(&selection, Some(&old), Some(&old.id)),
8586 Starter::Resume(old.id.clone())
8587 );
8588 let mut changed = selection.clone();
8589 changed.head = "b".repeat(40);
8590 assert_eq!(
8591 selected_starter(&changed, Some(&old), Some(&old.id)),
8592 Starter::Review(changed.branch)
8593 );
8594 }
8595
8596 #[test]
8597 fn candidate_transplant_failure_is_one_actionable_hold() {
8598 let dir = tempfile::tempdir().unwrap();
8599 let q = Queue::at(dir.path().join("queue"));
8600 let mut t = task();
8601 let mut state = run_state(RunStatus::Blocked);
8602 state.event("prep", "cannot apply referenced commit: conflict");
8603 state.prep_failure = Some("conflict".into());
8604 t.start(state.id.clone());
8605 finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
8606 assert_eq!(t.attempts, 1);
8607 assert_eq!(t.status, TaskStatus::Held);
8608 assert!(t.operator_held());
8609 assert!(!t.status.runnable());
8610 assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
8611 let first = t.chat_notice_key().unwrap();
8612 t.chat_notices.push(first.clone());
8613 t.release_operator("test", None);
8614 state.id = "another-unprepared-run".into();
8615 t.start(state.id.clone());
8616 finish_attempt(
8617 3,
8618 &q,
8619 &mut t,
8620 &state,
8621 &[],
8622 Err(anyhow::anyhow!("still conflicts")),
8623 );
8624 assert_eq!(
8625 t.chat_notice_key().as_ref(),
8626 Some(&first),
8627 "no work happened"
8628 );
8629 t.release_operator("test", None);
8630 state.prep_failure = None;
8631 state.status = RunStatus::Failed;
8632 state.begin_pass();
8633 t.start(state.id.clone());
8634 finish_attempt(
8635 1,
8636 &q,
8637 &mut t,
8638 &state,
8639 &[],
8640 Err(anyhow::anyhow!("new gate failure")),
8641 );
8642 let failure = t.chat_notice_key().unwrap();
8643 assert_ne!(failure, first, "approved recovery reached a real failure");
8644 t.release_operator("test", None);
8645 state.begin_pass();
8646 t.start(state.id.clone());
8647 finish_attempt(
8648 1,
8649 &q,
8650 &mut t,
8651 &state,
8652 &[],
8653 Err(anyhow::anyhow!("new failure on resume")),
8654 );
8655 assert_ne!(
8656 t.chat_notice_key().as_ref(),
8657 Some(&failure),
8658 "a new settled pass"
8659 );
8660 }
8661
8662 #[test]
8663 fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
8664 for source in ["cli", "web"] {
8665 let mut t = task();
8666 let mut run = run_state(RunStatus::Blocked);
8667 run.instruction = "Run A original criteria".into();
8668 run.task_instruction = Some(run.instruction.clone());
8669 t.start(run.id.clone());
8670 t.release_operator("choice", Some("resume-question"));
8671 t.resume_override = Some(crate::queue::OperatorResume {
8672 question_id: "resume-question".into(),
8673 at: Timestamp::now(),
8674 conductor_rehold: None,
8675 forced: true,
8676 pinned_run: Some(run.id.clone()),
8677 });
8678 t.hold_machine(Some("not enough free space to start a run".into()));
8679 let mut unchanged = t.clone();
8680 unchanged
8681 .edit("title changed".into(), unchanged.instruction.clone())
8682 .unwrap();
8683 unchanged.release_operator(source, None);
8684 assert_eq!(
8685 unchanged
8686 .resume_override
8687 .as_ref()
8688 .unwrap()
8689 .pinned_run
8690 .as_deref(),
8691 Some(run.id.as_str())
8692 );
8693 assert!(!compatible_run_instruction(&run, &unchanged));
8694 assert!(may_resume_run(&run, &unchanged));
8695
8696 t.edit(
8697 "approved recovery".into(),
8698 "Reuse measured PR head B; fix Clippy; review".into(),
8699 )
8700 .unwrap();
8701 assert!(t.resume_override.is_none());
8702 t.release_operator(source, None);
8703 let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
8704 assert!(reloaded.resume_override.is_none());
8705 assert!(!may_resume_run(&run, &reloaded));
8706 let unfinished =
8707 unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
8708 .filter(|_| may_resume_run(&run, &reloaded));
8709 assert_eq!(
8710 choose_starter(None, false, unfinished.as_deref()),
8711 Starter::Start
8712 );
8713 assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
8714 assert_eq!(
8715 reloaded.resumption_history[0].question_id.as_deref(),
8716 Some("resume-question")
8717 );
8718
8719 unchanged.instruction = "Reuse measured PR head B".into();
8722 unchanged.hold_machine(Some("disk hold".into()));
8723 unchanged.release_operator(source, None);
8724 assert!(unchanged.resume_override.is_none());
8725 assert!(!may_resume_run(&run, &unchanged));
8726 }
8727 }
8728
8729 #[test]
8730 fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
8731 let mut t = task();
8732 let mut run = run_state(RunStatus::Blocked);
8733 t.review_of = Some("approved-head".into());
8734 t.instruction =
8735 "Review the branch `approved-head` (review-only: no implementation, no judging)."
8736 .into();
8737 run.instruction = "Review the work already on branch `approved-head`. There is no task statement: what the change claims to do is whatever its commits say.\n\nCommit log".into();
8738 run.reviewed_commits = Some(vec!["Commit log".into()]);
8739 t.start(run.id.clone());
8740 t.hold_machine(Some("interrupted review".into()));
8741 t.release_operator("cli", None);
8742 assert!(
8743 compatible_run_instruction(&run, &t),
8744 "legacy explicit review remains resumable"
8745 );
8746 let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
8747 .filter(|_| compatible_run_instruction(&run, &t));
8748 assert_eq!(
8749 choose_starter(None, false, unfinished.as_deref()),
8750 Starter::Resume(run.id.clone())
8751 );
8752 run.task_instruction = Some(t.instruction.clone());
8753 assert!(compatible_run_instruction(&run, &t));
8754 let reloaded: RunState =
8755 serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
8756 assert!(compatible_run_instruction(&reloaded, &t));
8757 t.edit(
8758 "new approved head".into(),
8759 "Reuse measured PR head B".into(),
8760 )
8761 .unwrap();
8762 assert!(!compatible_run_instruction(&run, &t));
8763
8764 t.review_of = None;
8766 t.instruction = "Fix Clippy on approved head".into();
8767 run.task_instruction = None;
8768 run.instruction = format!(
8769 "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
8770 t.instruction
8771 );
8772 assert!(compatible_run_instruction(&run, &t));
8773 t.instruction.push('\n');
8774 assert!(
8775 compatible_run_instruction(&run, &t),
8776 "legacy generated review trimmed the original criteria"
8777 );
8778 t.hold_for_handover(Some("approved-head".into()), "refused".into());
8779 assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
8780 t.edit("new plan".into(), "Reuse measured PR head B".into())
8781 .unwrap();
8782 assert!(review_branch_for(&t, Some(&run)).is_none());
8783 assert!(!compatible_run_instruction(&run, &t));
8784 t.review_branch = Some("approved-head".into());
8785 t.review_instruction = None;
8786 assert!(
8787 review_branch_for(&t, Some(&run)).is_none(),
8788 "legacy retained candidate cannot replace a revised approved head"
8789 );
8790 }
8791
8792 #[test]
8793 fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
8794 let home = crate::run::test_home();
8795 crate::run::pin_test_home();
8796 let dir = tempfile::tempdir().unwrap();
8797 let queue = Queue::at(dir.path().join("queue"));
8798 for resume in [true, false] {
8799 let state = run_state(RunStatus::Blocked);
8800 let mut t = task();
8801 t.start(state.id.clone());
8802 let action = if resume {
8803 ask::ChoiceAction::Resume {
8804 run: state.id.clone(),
8805 }
8806 } else {
8807 ask::ChoiceAction::Requeue
8808 };
8809 let mut q = action_question(&state.id, action);
8810 q.status = ask::QuestionStatus::Open;
8811 q.answer = None;
8812 q.answered_at = None;
8813 t.fail("run stopped with a question", 3);
8814 hold_if_runnable(&queue, &mut t);
8815 assert!(t.operator_decided_at.is_none());
8816 assert!(t.operator_held());
8817 q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
8818 let expected = if resume {
8819 ActionDecision::Resume(state.id.clone())
8820 } else {
8821 ActionDecision::Requeue
8822 };
8823 assert_eq!(
8824 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8825 expected
8826 );
8827 t.hold_manual(Some("later explicit hold".into()));
8828 assert_eq!(
8829 decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8830 ActionDecision::Stale
8831 );
8832 }
8833 }
8834
8835 #[test]
8836 fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
8837 let mut t = task();
8838 t.answers.push(crate::queue::AnsweredQuestion {
8839 question: "Inspect the remote?".into(),
8840 answer: "Inspect then wait".into(),
8841 });
8842 let old = instruction_for(&t);
8843 assert!(compatible_instruction(&old, &t));
8844 t.instruction = "Reuse approved PR head and review".into();
8845 t.release_operator("cli", None);
8846 assert!(!compatible_instruction(&old, &t));
8847 let approved = instruction_for(&t);
8848 assert!(approved.contains("waiting premises are superseded"));
8849 assert!(compatible_instruction(&approved, &t));
8850 assert_eq!(resumed_instruction(&approved, &t), approved);
8851 t.release_operator("web", None);
8852 assert!(compatible_instruction(&approved, &t));
8853 assert_eq!(t.resumption_history.len(), 1);
8854 t.start("run".into());
8855 assert!(instruction_for(&t).contains("Explicit operator resumption"));
8856 }
8857
8858 #[test]
8862 fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
8863 let mut state = RunState::new(
8864 PathBuf::from("/repo"),
8865 "main".into(),
8866 "base".into(),
8867 "task".into(),
8868 Config::default(),
8869 );
8870 state.status = RunStatus::Landing;
8871 state.parked = true;
8872 state.pr_pushed_head = Some("head".into());
8873 state.land_unrelated = Some(
8874 serde_json::from_value(serde_json::json!({
8875 "head": "head", "question": "ci-question",
8876 "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
8877 }))
8878 .unwrap(),
8879 );
8880 let mut t = task();
8881 t.start(state.id.clone());
8882 let verdict = Verdict {
8883 status: RunStatus::Landing,
8884 left_pr: true,
8885 quota_hit: false,
8886 parked: true,
8887 no_viable_candidates: false,
8888 };
8889 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8890 assert_eq!(t.attempts, 0);
8891 assert_eq!(t.status, TaskStatus::Held);
8892 assert!(!t.operator_held());
8893 assert!(
8894 t.hold_reason
8895 .as_deref()
8896 .unwrap()
8897 .starts_with("[ci-unrelated]")
8898 );
8899 t.attempts = 1;
8901 settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8902 assert_eq!(t.attempts, 1);
8903 assert_eq!(t.passes.len(), 1);
8904 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8905 state.pr_pushed_head = Some("new-head".into());
8906 state.parked = false;
8907 state.status = RunStatus::Blocked;
8908 let stale = Verdict {
8909 status: RunStatus::Blocked,
8910 parked: false,
8911 ..verdict
8912 };
8913 settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
8914 assert_eq!(t.attempts, 1);
8915 state.begin_pass();
8917 state.begin_pass();
8918 state.status = RunStatus::Landing;
8919 state.parked = true;
8920 state.pr_pushed_head = Some("head".into());
8921 settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
8922 assert_eq!(t.attempts, 0);
8923 assert_eq!(t.passes.len(), 2);
8924 }
8925
8926 #[test]
8927 fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
8928 let mut state = run_state(RunStatus::Failed);
8929 state
8930 .quota
8931 .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
8932 state.begin_pass();
8933 let mut t = task();
8934 t.start(state.id.clone());
8935 reclaim(&mut t, Some(state), 2, "en");
8936 assert_eq!(t.attempts, 1);
8937 }
8938
8939 #[test]
8940 fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
8941 let mut state = run_state(RunStatus::Blocked);
8942 let losses: Vec<_> = ["alpha", "beta"]
8943 .into_iter()
8944 .enumerate()
8945 .map(|(i, agent)| {
8946 QuotaLoss::from_report(
8947 format!("advisor-{i}"),
8948 "advise",
8949 Some(&crate::agent::Quota {
8950 cause: crate::agent::QuotaCause::Authentication,
8951 agent: agent.to_owned(),
8952 reset: None,
8953 }),
8954 )
8955 })
8956 .collect();
8957 crate::graph::block_machine_outage(&mut state, "advise", &losses);
8958 state.quota = losses;
8959 let mut t = task();
8960 t.start(state.id.clone());
8961 let verdict = Verdict {
8962 status: state.status,
8963 left_pr: false,
8964 quota_hit: true,
8965 parked: false,
8966 no_viable_candidates: true,
8967 };
8968 settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
8969 assert_eq!(t.attempts, 0);
8970 assert_eq!(t.status, TaskStatus::Held);
8971 assert!(!t.operator_held());
8972 let reason = t.hold_reason.as_deref().unwrap();
8973 assert!(reason.starts_with("[authentication]"));
8974 assert!(
8975 reason.contains("alpha")
8976 && reason.contains("beta")
8977 && reason.contains("re-authenticate")
8978 );
8979 assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
8980 let mut orphan = task();
8982 orphan.start(state.id.clone());
8983 reclaim(&mut orphan, Some(state), 2, "en");
8984 assert_eq!(orphan.attempts, 0);
8985 assert_eq!(orphan.status, TaskStatus::Held);
8986 }
8987
8988 #[test]
8989 fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
8990 let mut state = RunState::new(
8991 PathBuf::from("/repo"),
8992 "main".to_owned(),
8993 "abc1234".to_owned(),
8994 "task".to_owned(),
8995 Config::default(),
8996 );
8997 state.status = RunStatus::Blocked;
8998 state.resource_block = Some(crate::run::ResourceBlock {
8999 cause: crate::run::ResourceBlockCause::Other,
9000 node: "graft".to_owned(),
9001 kind: "shared build cache".to_owned(),
9002 detail: "timed out".to_owned(),
9003 at: jiff::Timestamp::now(),
9004 });
9005 let mut t = task();
9006 t.start("20260902-000000-aaaa".to_owned());
9007 assert_eq!(t.attempts, 1);
9008 let verdict = Verdict {
9009 status: RunStatus::Blocked,
9010 left_pr: false,
9011 quota_hit: false,
9012 parked: false,
9013 no_viable_candidates: false,
9014 };
9015 settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
9016 assert_eq!(t.status, TaskStatus::Held);
9017 assert_eq!(t.attempts, 0, "the attempt is refunded");
9018 assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
9019 assert!(
9020 !t.operator_held(),
9021 "a machine hold, released without a human"
9022 );
9023
9024 let mut selected = task();
9025 selected.start("20260902-000000-cccc".into());
9026 selected.replacement = Some(crate::merge_decision::Replacement {
9027 question: "fixture".into(),
9028 run: "earlier".into(),
9029 pr: "https://example.invalid/pr/1".into(),
9030 agent: "selected".into(),
9031 context: "fixture".into(),
9032 });
9033 state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
9034 settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
9035 assert_eq!(selected.attempts, 0);
9036 assert!(
9037 !selected.operator_held(),
9038 "a selected agent also retains a machine resource hold"
9039 );
9040 assert!(
9041 selected
9042 .hold_reason
9043 .as_deref()
9044 .unwrap()
9045 .starts_with("[resource] ")
9046 );
9047
9048 let mut p = task();
9050 p.start("20260902-000000-bbbb".to_owned());
9051 settle_and_diagnose(
9052 &mut p,
9053 Verdict {
9054 parked: true,
9055 ..verdict
9056 },
9057 "parked",
9058 2,
9059 &state,
9060 );
9061 assert_eq!(p.status, TaskStatus::Parked);
9062 assert_eq!(
9063 p.attempts, 0,
9064 "parking refunds once rather than also settling the resource hold"
9065 );
9066 }
9067
9068 #[test]
9069 fn record_failure_notice_links_the_task() {
9070 let dir = tempfile::tempdir().unwrap();
9071 std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
9074 let queue = Queue::at(dir.path().join("queue"));
9075 let mut t = interrupt_task("rec-fail-1");
9076 record(&queue, &mut t);
9077
9078 let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
9079 assert_eq!(found.len(), 1);
9080 assert_eq!(found[0].key, "loop:record");
9081 assert_eq!(
9082 found[0].link,
9083 Some(Link::Task {
9084 id: "rec-fail-1".to_owned()
9085 })
9086 );
9087 }
9088
9089 fn interrupt_task(id: &str) -> Task {
9092 let mut t = task();
9093 t.id = id.to_owned();
9094 t.interrupt = true;
9095 t
9096 }
9097
9098 fn task_with_id(id: &str) -> Task {
9100 let mut t = task();
9101 t.id = id.to_owned();
9102 t
9103 }
9104
9105 fn urgent_task(id: &str) -> Task {
9107 let mut t = task();
9108 t.id = id.to_owned();
9109 t.urgent = true;
9110 t
9111 }
9112
9113 #[test]
9114 fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
9115 let dir = tempfile::tempdir().unwrap();
9116 let queue = Queue::at(dir.path().join("queue"));
9117 let mut parked = task_with_id("parked");
9118 parked.start("run".into());
9119 parked.park("upgrade");
9120 parked.record_pass_at(
9121 "run",
9122 0,
9123 Some(Timestamp::now()),
9124 1,
9125 Some(crate::run::ParkCause::Upgrade {
9126 from: "old".into(),
9127 to: None,
9128 }),
9129 );
9130 let mut fresh = task_with_id("fresh");
9131 fresh.priority = 100;
9132 let mut urgent_task = urgent_task("urgent");
9133 for t in [&mut parked, &mut fresh, &mut urgent_task] {
9134 queue.put(t).unwrap();
9135 }
9136 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9137 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9138 let candidates = runnable(&queue);
9139 assert_eq!(candidates[0].id, parked.id);
9140 let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
9141 assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
9142 assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
9143 drop(first);
9144 let claimed_elsewhere = queue.claim(&parked.id).unwrap();
9145 let next = runnable(&queue)
9146 .into_iter()
9147 .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
9148 .unwrap();
9149 assert_eq!(next.task.id, fresh.id);
9150 assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
9151 drop(claimed_elsewhere);
9152 drop(next);
9153 assert!(matches!(
9154 claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
9155 Err(SkipReason::CoolingDown)
9156 ));
9157 }
9158
9159 #[test]
9160 fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
9161 let dir = tempfile::tempdir().unwrap();
9162 let queue = Queue::at(dir.path().join("queue"));
9163 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9164 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9165 let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9166 let mut first = task();
9167 queue.put(&mut first).unwrap();
9168 let stale_plain = queue.get(&first.id).unwrap();
9169 first.set_urgent(true).unwrap();
9170 queue.put(&mut first).unwrap();
9171 let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
9172 let mut second = urgent_task("second");
9173 queue.put(&mut second).unwrap();
9174 assert!(matches!(
9175 claim_dispatch(&queue, &second, false, &ordinary, &urgent),
9176 Err(SkipReason::UrgentCapacity)
9177 ));
9178 drop(queue.claim(&second.id).unwrap());
9179 assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
9180 drop(dispatched);
9181 let stale_urgent = queue.get(&first.id).unwrap();
9182 first.set_urgent(false).unwrap();
9183 queue.put(&mut first).unwrap();
9184 assert!(matches!(
9185 claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
9186 Err(SkipReason::OrdinaryCapacity)
9187 ));
9188 assert_eq!(urgent.available_permits(), 1);
9189 drop(queue.claim(&first.id).unwrap());
9190 drop(occupied);
9191 }
9192
9193 #[test]
9194 fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
9195 let dir = tempfile::tempdir().unwrap();
9196 let queue = Queue::at(dir.path().join("queue"));
9197 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9198 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9199 let mut t = task();
9200 queue.put(&mut t).unwrap();
9201 for enabled in [true, false] {
9202 let stale = queue.get(&t.id).unwrap();
9203 t.set_urgent(enabled).unwrap();
9204 queue.put(&mut t).unwrap();
9205 assert_ne!(stale.urgent, enabled);
9206 let DispatchClaim {
9207 task: fresh,
9208 claim,
9209 lane,
9210 permit,
9211 } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9212 assert_eq!(fresh.urgent, enabled);
9213 assert_eq!(
9214 lane,
9215 if enabled {
9216 PermitKind::Urgent
9217 } else {
9218 PermitKind::Ordinary
9219 }
9220 );
9221 assert_eq!(ordinary.available_permits(), usize::from(enabled));
9222 assert_eq!(urgent.available_permits(), usize::from(!enabled));
9223 assert!(queue.claim(&t.id).is_err());
9224 assert_eq!(fresh.attempts, stale.attempts);
9225 drop((claim, permit));
9226 assert_eq!(ordinary.available_permits(), 1);
9227 assert_eq!(urgent.available_permits(), 1);
9228 }
9229 t.set_urgent(true).unwrap();
9230 queue.put(&mut t).unwrap();
9231 let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
9232 assert!(matches!(
9233 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9234 Err(SkipReason::UrgentCapacity)
9235 ));
9236 assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
9237 drop(queue.claim(&t.id).unwrap());
9238 assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
9239 drop(occupied);
9240 assert!(matches!(
9241 claim_dispatch(&queue, &t, true, &ordinary, &urgent),
9242 Err(SkipReason::CoolingDown)
9243 ));
9244 drop(queue.claim(&t.id).unwrap());
9245 let held = queue.claim(&t.id).unwrap();
9246 assert!(matches!(
9247 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9248 Err(SkipReason::ClaimUnavailable)
9249 ));
9250 drop(held);
9251 t.status = TaskStatus::Held;
9252 queue.put(&mut t).unwrap();
9253 assert!(matches!(
9254 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9255 Err(SkipReason::NoLongerRunnable)
9256 ));
9257 drop(queue.claim(&t.id).unwrap());
9258 std::fs::remove_file(queue.path_of(&t.id)).unwrap();
9259 assert!(matches!(
9260 claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9261 Err(SkipReason::RereadFailed)
9262 ));
9263 drop(queue.claim(&t.id).unwrap());
9264 assert_eq!(urgent.available_permits(), 1);
9265 }
9266
9267 #[test]
9272 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
9273 assert_eq!(permit_kind(true, false, false), PermitKind::None);
9274 assert_eq!(permit_kind(true, false, true), PermitKind::None);
9275 assert_eq!(permit_kind(true, true, false), PermitKind::None);
9276 assert_eq!(permit_kind(true, true, true), PermitKind::None);
9277 }
9278
9279 #[test]
9284 fn permit_kind_separates_urgent_from_ordinary() {
9285 assert_eq!(permit_kind(false, false, true), PermitKind::Urgent);
9286 assert_eq!(permit_kind(false, false, false), PermitKind::Ordinary);
9287 assert_eq!(permit_kind(false, true, false), PermitKind::Immediate);
9288 assert_eq!(permit_kind(false, true, true), PermitKind::Immediate);
9289 }
9290
9291 #[test]
9292 fn immediate_lane_does_not_consume_ordinary_or_urgent_slots() {
9293 let request = |task: &str, lane, standalone| TaskWorker {
9294 opts: Opts::default(),
9295 queue: PathBuf::from("/queue"),
9296 task: task.to_owned(),
9297 lane,
9298 standalone,
9299 };
9300 let jobs = vec![
9301 request("ordinary", PermitKind::Ordinary, false),
9302 request("urgent", PermitKind::Urgent, false),
9303 request("immediate-1", PermitKind::Immediate, false),
9304 request("immediate-2", PermitKind::Immediate, false),
9305 request("decision", PermitKind::None, false),
9306 ];
9307 assert_eq!(available_slots(&jobs, 1), (0, 0));
9308 assert_eq!(available_slots(&jobs, 2), (1, 0));
9309 let immediate_only = vec![
9310 request("immediate-1", PermitKind::Immediate, false),
9311 request("immediate-2", PermitKind::Immediate, false),
9312 ];
9313 assert_eq!(available_slots(&immediate_only, 1), (1, 1));
9314 }
9315
9316 #[test]
9317 fn immediate_dispatch_bypasses_saturated_lanes_and_preserves_non_concurrency_gates() {
9318 let dir = tempfile::tempdir().unwrap();
9319 let queue = Queue::at(dir.path().join("queue"));
9320 let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9321 let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9322 let _ord_permit = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9323 let _urg_permit = Arc::clone(&urgent).try_acquire_owned().unwrap();
9324
9325 let mut imm1 = task_with_id("imm-1");
9327 imm1.immediate = true;
9328 let mut imm2 = task_with_id("imm-2");
9329 imm2.immediate = true;
9330 imm2.urgent = true;
9331 queue.put(&mut imm1).unwrap();
9332 queue.put(&mut imm2).unwrap();
9333
9334 let mut stale = imm1.clone();
9336 stale.immediate = false;
9337 let claim1 = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9338 assert_eq!(claim1.lane, PermitKind::Immediate);
9339 assert!(claim1.permit.is_none());
9340
9341 let claim2 = claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).unwrap();
9343 assert_eq!(claim2.lane, PermitKind::Immediate);
9344 assert!(claim2.permit.is_none());
9345 assert_eq!(ordinary.available_permits(), 0);
9346 assert_eq!(urgent.available_permits(), 0);
9347
9348 assert_eq!(
9350 claim_dispatch(&queue, &imm1, false, &ordinary, &urgent).err(),
9351 Some(SkipReason::ClaimUnavailable)
9352 );
9353 drop((claim1, claim2));
9354
9355 assert_eq!(
9357 claim_dispatch(&queue, &imm1, true, &ordinary, &urgent).err(),
9358 Some(SkipReason::CoolingDown)
9359 );
9360
9361 imm2.set_immediate(false).unwrap();
9363 queue.put(&mut imm2).unwrap();
9364 assert_eq!(
9365 claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).err(),
9366 Some(SkipReason::UrgentCapacity)
9367 );
9368
9369 let interrupt = Interrupt::Parking {
9371 parked: vec!["in-flight".into()],
9372 interrupt_task: "other".into(),
9373 };
9374 assert!(
9375 interrupt_gate(&interrupt, &["in-flight".into()], vec![imm1.clone()]).is_empty(),
9376 "an active interrupt sequence must withhold immediate tasks too"
9377 );
9378 }
9379
9380 #[test]
9381 fn admission_snapshot_distinguishes_mode_lane_blockers_and_unknown_state() {
9382 let dir = tempfile::tempdir().unwrap();
9383 let home = dir.path();
9384 let queue = Queue::at(home.join("queue"));
9385 let now = Timestamp::now();
9386
9387 let mut imm = task_with_id("imm-ready");
9388 imm.immediate = true;
9389 queue.put(&mut imm).unwrap();
9390
9391 let snap = AdmissionSnapshot::capture(home, now);
9393 let adm = snap.evaluate(&imm, &queue, None, home);
9394 assert_eq!(adm.mode, "immediate");
9395 assert_eq!(adm.state, "waiting");
9396 assert_eq!(adm.label, "Immediate: waiting — scheduler not running");
9397
9398 let mut status = Status::new();
9400 status.updated_at = now;
9401 status
9402 .dispatch_skips
9403 .insert(imm.id.clone(), SkipReason::UrgentCapacity.key().to_owned());
9404 write_status_to(&home.join("daemon.json"), &status).unwrap();
9405
9406 let mut ord = task_with_id("ord-running");
9407 ord.status = TaskStatus::Running;
9408 queue.put(&mut ord).unwrap();
9409 let ord_req = TaskWorker {
9410 opts: Opts::default(),
9411 queue: queue.root().to_path_buf(),
9412 task: ord.id.clone(),
9413 lane: PermitKind::Ordinary,
9414 standalone: false,
9415 };
9416 let (_ord_job, _ord_lease) = crate::worker::running_fixture(
9417 home,
9418 &format!("task:{}", ord.id),
9419 serde_json::to_value(&ord_req).unwrap(),
9420 )
9421 .unwrap();
9422
9423 let mut urg = task_with_id("urg-running");
9424 urg.urgent = true;
9425 urg.status = TaskStatus::Running;
9426 queue.put(&mut urg).unwrap();
9427 let urg_req = TaskWorker {
9428 opts: Opts::default(),
9429 queue: queue.root().to_path_buf(),
9430 task: urg.id.clone(),
9431 lane: PermitKind::Urgent,
9432 standalone: false,
9433 };
9434 let (_urg_job, _urg_lease) = crate::worker::running_fixture(
9435 home,
9436 &format!("task:{}", urg.id),
9437 serde_json::to_value(&urg_req).unwrap(),
9438 )
9439 .unwrap();
9440
9441 let snap = AdmissionSnapshot::capture(home, now);
9442 let adm = snap.evaluate(&imm, &queue, None, home);
9443 assert_eq!(adm.state, "next_poll");
9444 assert_eq!(adm.label, "Immediate: next poll");
9445 assert_eq!(adm.reservation_lane, None);
9446
9447 let ord_adm = snap.evaluate(&ord, &queue, None, home);
9449 assert_eq!(ord_adm.state, "running");
9450 assert_eq!(ord_adm.reservation_lane, Some("ordinary"));
9451 assert_eq!(ord_adm.label, "Running (ordinary lane)");
9452
9453 let mut held = task_with_id("imm-held");
9455 held.immediate = true;
9456 held.hold_manual(Some("awaiting signoff".into()));
9457 queue.put(&mut held).unwrap();
9458 let held_adm = snap.evaluate(&held, &queue, None, home);
9459 assert_eq!(held_adm.state, "waiting");
9460 assert_eq!(
9461 held_adm.label,
9462 "Immediate: waiting — held (awaiting signoff)"
9463 );
9464
9465 let mut disk_held = task_with_id("imm-disk");
9466 disk_held.immediate = true;
9467 disk_held.hold_machine(Some("only 1 GiB free".into()));
9468 disk_held.mark_startup_disk_capacity();
9469 queue.put(&mut disk_held).unwrap();
9470 let disk_adm = snap.evaluate(&disk_held, &queue, None, home);
9471 assert_eq!(disk_adm.state, "waiting");
9472 assert!(disk_adm.label.contains("disk admission"), "{disk_adm:?}");
9473
9474 let mut blocked = task_with_id("imm-blocked");
9475 blocked.immediate = true;
9476 blocked.block(vec![held.id.clone()], Some("needs held task".into()));
9477 queue.put(&mut blocked).unwrap();
9478 let questions = Questions::at(home.join("questions"));
9479 let inv = crate::blockers::Inventory::load(&queue, &questions);
9480 let blocked_adm = snap.evaluate(&blocked, &queue, Some(&inv), home);
9481 assert_eq!(blocked_adm.state, "waiting");
9482 assert!(
9483 blocked_adm
9484 .label
9485 .starts_with("Immediate: waiting — waiting on dependencies"),
9486 "{blocked_adm:?}"
9487 );
9488
9489 let _claim = queue.claim(&imm.id).unwrap();
9491 let claimed_adm = snap.evaluate(&imm, &queue, None, home);
9492 assert_eq!(claimed_adm.state, "waiting");
9493 assert_eq!(
9494 claimed_adm.label,
9495 "Immediate: waiting — claimed by another process"
9496 );
9497 drop(_claim);
9498
9499 let until = now + jiff::SignedDuration::from_secs(120);
9501 std::fs::write(
9502 home.join("task-quota-cooldown.json"),
9503 serde_json::to_vec(&until).unwrap(),
9504 )
9505 .unwrap();
9506 let cool_snap = AdmissionSnapshot::capture(home, now);
9507 let cool_adm = cool_snap.evaluate(&imm, &queue, None, home);
9508 assert_eq!(cool_adm.state, "waiting");
9509 assert!(cool_adm.label.contains("quota cooldown"), "{cool_adm:?}");
9510 std::fs::remove_file(home.join("task-quota-cooldown.json")).unwrap();
9511
9512 std::fs::write(home.join("scheduler-interrupt.json"), "{broken").unwrap();
9514 let bad_snap = AdmissionSnapshot::capture(home, now);
9515 let bad_adm = bad_snap.evaluate(&imm, &queue, None, home);
9516 assert_eq!(bad_adm.state, "unknown");
9517 assert_ne!(bad_adm.label, "Immediate: next poll");
9518 }
9519
9520 #[test]
9527 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
9528 let cfg = Config::default();
9529 let repo = Path::new("/any/repo/path");
9530
9531 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
9532 .expect("must hold below the threshold");
9533 assert!(reason.contains("1024"), "{reason}");
9534 assert!(
9535 reason.contains(&cfg.disk.min_free_bytes.to_string()),
9536 "{reason}"
9537 );
9538
9539 assert_eq!(
9540 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
9541 None,
9542 "exactly at the floor is open"
9543 );
9544 assert_eq!(
9545 disk_gate_with(
9546 repo,
9547 &cfg,
9548 PathBuf::new,
9549 |_| Ok(cfg.disk.min_free_bytes + 1)
9550 ),
9551 None,
9552 "comfortably above the floor is open"
9553 );
9554 }
9555
9556 #[test]
9560 fn disk_gate_ignores_the_collection_threshold() {
9561 let mut cfg = Config::default();
9562 cfg.disk.reclaim_free_bytes = Some(cfg.disk.min_free_bytes * 100);
9563 let repo = Path::new("/any/repo/path");
9564 assert_eq!(
9565 disk_gate_with(
9566 repo,
9567 &cfg,
9568 PathBuf::new,
9569 |_| Ok(cfg.disk.min_free_bytes + 1)
9570 ),
9571 None
9572 );
9573 assert!(
9574 disk_gate_with(
9575 repo,
9576 &cfg,
9577 PathBuf::new,
9578 |_| Ok(cfg.disk.min_free_bytes - 1)
9579 )
9580 .is_some(),
9581 "below the admission floor still holds"
9582 );
9583 }
9584
9585 #[test]
9586 fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
9587 let dir = tempfile::tempdir().unwrap();
9588 let repo = dir.path().join("repo");
9589 let cache = dir.path().join("cache");
9590 let worktrees = dir.path().join("worktrees");
9591 for path in [&repo, &cache, &worktrees] {
9592 std::fs::create_dir(path).unwrap();
9593 }
9594 let mut cfg = Config::default();
9595 cfg.graph.worktree_root = Some(worktrees.clone());
9596 cfg.verify.gate = vec![format!(
9597 "CARGO_TARGET_DIR='{}' cargo build",
9598 cache.display()
9599 )];
9600 for blocked in [&cache, &worktrees] {
9601 for unmeasured in [false, true] {
9602 assert!(
9603 disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
9604 if path == blocked {
9605 if unmeasured {
9606 Err(anyhow::anyhow!("measurement failed"))
9607 } else {
9608 Ok(0)
9609 }
9610 } else {
9611 Ok(u64::MAX)
9612 }
9613 })
9614 .is_some(),
9615 "a blocked secondary output volume must close admission"
9616 );
9617 }
9618 }
9619 assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
9620 }
9621
9622 #[test]
9623 fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
9624 let dir = tempfile::tempdir().unwrap();
9625 let repo = dir.path().join("repo");
9626 let cache = dir.path().join("cache");
9627 let home_parent = dir.path().join("run-volume");
9628 let home = home_parent.join("new-home");
9629 for path in [&repo, &cache, &home_parent] {
9630 std::fs::create_dir(path).unwrap();
9631 }
9632 let mut cfg = Config::default();
9633 cfg.graph.worktree_root = Some(repo.clone());
9634 cfg.verify.gate = vec![format!(
9635 "CARGO_TARGET_DIR='{}' cargo build",
9636 cache.display()
9637 )];
9638 cfg.verify.build_cache = BuildCache::Isolated;
9639 let denied = |blocked: &Path| {
9640 disk_gate_with(
9641 &repo,
9642 &cfg,
9643 || home.clone(),
9644 |path| Ok(if path == blocked { 0 } else { u64::MAX }),
9645 )
9646 .is_some()
9647 };
9648 assert!(!denied(&cache));
9649 assert!(denied(&home_parent));
9650 }
9651
9652 #[test]
9653 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
9654 let mut cfg = Config::default();
9655 cfg.disk.min_free_bytes = 0;
9656 let repo = Path::new("/any/repo/path");
9657 assert_eq!(
9658 disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
9659 None,
9660 "a zero floor never measures at all"
9661 );
9662 }
9663
9664 #[test]
9665 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
9666 let cfg = Config::default();
9667 let repo = Path::new("/any/repo/path");
9668 let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
9669 Err(anyhow::anyhow!("no df on this box"))
9670 })
9671 .expect("a measurement failure must close the gate, not open it");
9672 assert!(reason.contains("could not measure"), "{reason}");
9673 }
9674
9675 #[test]
9676 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
9677 let ordinary = task();
9678 let next = advance_interrupt(
9679 Interrupt::Idle,
9680 std::slice::from_ref(&ordinary.id),
9681 std::slice::from_ref(&ordinary),
9682 );
9683 assert_eq!(next, Interrupt::Idle);
9684 }
9685
9686 #[test]
9687 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
9688 let marked = interrupt_task("marked");
9691 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9692 assert_eq!(next, Interrupt::Idle);
9693 }
9694
9695 #[test]
9696 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
9697 let marked = interrupt_task("marked");
9698 let next = advance_interrupt(
9699 Interrupt::Idle,
9700 &["running".to_owned()],
9701 std::slice::from_ref(&marked),
9702 );
9703 assert_eq!(
9704 next,
9705 Interrupt::Parking {
9706 parked: vec!["running".to_owned()],
9707 interrupt_task: "marked".to_owned(),
9708 }
9709 );
9710 }
9711
9712 #[test]
9721 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
9722 let marked = interrupt_task("marked");
9723
9724 let two = advance_interrupt(
9725 Interrupt::Idle,
9726 &["a".to_owned(), "b".to_owned()],
9727 std::slice::from_ref(&marked),
9728 );
9729 assert_eq!(two, Interrupt::Idle);
9730
9731 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9732 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
9733 }
9734
9735 #[test]
9736 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
9737 let state = Interrupt::Parking {
9738 parked: vec!["running".to_owned()],
9739 interrupt_task: "marked".to_owned(),
9740 };
9741 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
9743 assert_eq!(still_going, state);
9744
9745 let stopped_but_not_yet_dispatched =
9749 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
9750 assert_eq!(stopped_but_not_yet_dispatched, state);
9751
9752 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
9754 assert_eq!(
9755 dispatched,
9756 Interrupt::Running {
9757 parked: vec!["running".to_owned()],
9758 interrupt_task: "marked".to_owned(),
9759 }
9760 );
9761 }
9762
9763 #[test]
9764 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
9765 let state = Interrupt::Running {
9766 parked: vec!["running".to_owned()],
9767 interrupt_task: "marked".to_owned(),
9768 };
9769 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
9770 assert_eq!(still_running, state);
9771
9772 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
9779 assert_eq!(
9780 ended,
9781 Interrupt::Resuming {
9782 parked: vec!["running".to_owned()]
9783 }
9784 );
9785 }
9786
9787 #[test]
9788 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
9789 let state = Interrupt::Resuming {
9790 parked: vec!["running".to_owned()],
9791 };
9792 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
9793 assert_eq!(still_waiting, state);
9794
9795 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
9796 assert_eq!(dispatched, Interrupt::Idle);
9797 }
9798
9799 #[test]
9805 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
9806 {
9807 let state = Interrupt::Parking {
9808 parked: vec!["running".to_owned()],
9809 interrupt_task: "marked".to_owned(),
9810 };
9811 let next = advance_interrupt(state, &[], &[]);
9814 assert_eq!(
9815 next,
9816 Interrupt::Resuming {
9817 parked: vec!["running".to_owned()]
9818 },
9819 "abandoning the interrupt must not abandon the resume it owes"
9820 );
9821 }
9822
9823 #[test]
9826 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
9827 let state = Interrupt::Resuming {
9828 parked: vec!["running".to_owned()],
9829 };
9830 let next = advance_interrupt(state, &[], &[]);
9831 assert_eq!(
9832 next,
9833 Interrupt::Idle,
9834 "nothing is left to wait for; the loop must not stay wedged"
9835 );
9836 }
9837
9838 #[test]
9839 fn disabled_by_config_the_sequence_can_never_leave_idle() {
9840 let marked = interrupt_task("marked");
9841 let next = advance_interrupt_tick(
9842 false,
9843 Interrupt::Idle,
9844 &["running".to_owned()],
9845 std::slice::from_ref(&marked),
9846 );
9847 assert_eq!(
9848 next,
9849 Interrupt::Idle,
9850 "an unmarked, unconfigured daemon must behave exactly as before"
9851 );
9852 }
9853
9854 #[test]
9855 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
9856 let state = Interrupt::Parking {
9857 parked: vec!["running".to_owned()],
9858 interrupt_task: "marked".to_owned(),
9859 };
9860 let candidates = vec![interrupt_task("marked"), task()];
9861 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9862 assert!(
9863 allowed.is_empty(),
9864 "nothing may dispatch - not even the interrupt task itself - \
9865 until the parked run has actually stopped"
9866 );
9867 }
9868
9869 #[test]
9883 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
9884 for state in [
9885 Interrupt::Parking {
9886 parked: vec!["running".to_owned()],
9887 interrupt_task: "marked".to_owned(),
9888 },
9889 Interrupt::Running {
9890 parked: vec!["running".to_owned()],
9891 interrupt_task: "marked".to_owned(),
9892 },
9893 Interrupt::Resuming {
9894 parked: vec!["running".to_owned()],
9895 },
9896 ] {
9897 let candidates = vec![
9898 interrupt_task("marked"),
9899 urgent_task("hot"),
9900 task_with_id("ordinary"),
9901 ];
9902 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9903 assert!(
9904 !allowed.iter().any(|t| t.id == "hot"),
9905 "an urgent candidate must wait out the same gate as anything \
9906 else while the run it would run alongside has not actually \
9907 left flight, for state {state:?}: {allowed:?}"
9908 );
9909 }
9910 }
9911
9912 #[test]
9918 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
9919 let state = Interrupt::Resuming {
9920 parked: vec!["hot".to_owned()],
9921 };
9922 let candidates = vec![urgent_task("hot"), task()];
9923 let allowed = interrupt_gate(&state, &[], candidates);
9924 assert_eq!(
9925 allowed.iter().filter(|t| t.id == "hot").count(),
9926 1,
9927 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
9928 );
9929 }
9930
9931 #[test]
9932 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
9933 let state = Interrupt::Parking {
9934 parked: vec!["running".to_owned()],
9935 interrupt_task: "marked".to_owned(),
9936 };
9937 let other = task();
9938 let candidates = vec![interrupt_task("marked"), other.clone()];
9939 let allowed = interrupt_gate(&state, &[], candidates);
9940 assert_eq!(allowed.len(), 1);
9941 assert_eq!(allowed[0].id, "marked");
9942 }
9943
9944 #[test]
9945 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
9946 let state = Interrupt::Running {
9947 parked: vec!["running".to_owned()],
9948 interrupt_task: "marked".to_owned(),
9949 };
9950 let candidates = vec![task(), task()];
9951 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
9952 assert!(allowed.is_empty());
9953 }
9954
9955 #[test]
9962 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
9963 let state = Interrupt::Resuming {
9964 parked: vec!["a".to_owned(), "c".to_owned()],
9965 };
9966 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
9967 let allowed = interrupt_gate(&state, &[], candidates);
9968 assert_eq!(
9969 allowed.len(),
9970 1,
9971 "at most one candidate may be offered while resuming: {allowed:?}"
9972 );
9973 assert_eq!(allowed[0].id, "a");
9974 }
9975
9976 #[test]
9977 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
9978 let state = Interrupt::Resuming {
9979 parked: vec!["a".to_owned()],
9980 };
9981 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
9982 assert!(allowed.is_empty());
9983 }
9984
9985 #[test]
9991 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
9992 let running = task(); let marked = interrupt_task("marked");
9994
9995 let mut state = Interrupt::Idle;
9996 let in_flight = vec![running.id.clone()];
9998 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
9999 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
10000 assert!(gated.is_empty(), "still waiting on `running` to park");
10001
10002 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
10004 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
10005 assert_eq!(
10006 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10007 vec!["marked"],
10008 "only the interrupt task may be offered to the dispatcher now"
10009 );
10010
10011 state = advance_interrupt_tick(
10013 true,
10014 state,
10015 &["marked".to_owned()],
10016 std::slice::from_ref(&running),
10017 );
10018 let gated = interrupt_gate(
10019 &state,
10020 &["marked".to_owned()],
10021 vec![marked.clone(), running.clone()],
10022 );
10023 assert!(
10024 gated.is_empty(),
10025 "the parked run must not be offered back while the interrupt \
10026 task is still running"
10027 );
10028
10029 let other = task_with_id("other");
10033 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
10034 assert_eq!(
10035 state,
10036 Interrupt::Resuming {
10037 parked: vec![running.id.clone()]
10038 }
10039 );
10040 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
10041 assert_eq!(
10042 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10043 vec![running.id.as_str()],
10044 "exactly the parked run resumes - not the unrelated task, even \
10045 though it was offered first"
10046 );
10047
10048 state = advance_interrupt_tick(
10052 true,
10053 state,
10054 std::slice::from_ref(&running.id),
10055 std::slice::from_ref(&other),
10056 );
10057 assert_eq!(state, Interrupt::Idle);
10058 let gated = interrupt_gate(
10059 &state,
10060 std::slice::from_ref(&running.id),
10061 vec![other.clone()],
10062 );
10063 assert_eq!(
10064 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10065 vec![other.id.as_str()],
10066 "ordinary dispatch is unrestricted again"
10067 );
10068 }
10069
10070 #[test]
10071 fn every_run_status_settles_the_task_it_came_from() {
10072 let table = [
10074 (RunStatus::Merged, TaskStatus::Done, 1),
10075 (RunStatus::Ready, TaskStatus::Done, 1),
10076 (RunStatus::Stalled, TaskStatus::Failed, 0),
10077 (RunStatus::Blocked, TaskStatus::Failed, 1),
10078 (RunStatus::Failed, TaskStatus::Failed, 1),
10079 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
10080 (RunStatus::Prep, TaskStatus::Failed, 1),
10081 (RunStatus::Implementing, TaskStatus::Failed, 1),
10082 (RunStatus::Judging, TaskStatus::Failed, 1),
10083 (RunStatus::Deliberating, TaskStatus::Failed, 1),
10084 (RunStatus::Voting, TaskStatus::Failed, 1),
10085 (RunStatus::Reviewing, TaskStatus::Failed, 1),
10086 (RunStatus::Gating, TaskStatus::Failed, 1),
10087 ];
10088 for (run, want, attempts) in table {
10089 let mut t = task();
10090 t.start("20260902-000000-aaaa".to_owned());
10091 settle(
10092 &mut t,
10093 Verdict {
10094 status: run,
10095 left_pr: false,
10096 parked: false,
10097 quota_hit: matches!(run, RunStatus::Stalled),
10098 no_viable_candidates: false,
10099 },
10100 "why",
10101 2,
10102 );
10103 assert_eq!(t.status, want, "task status after {}", label(run));
10104 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
10105 }
10106 }
10107
10108 #[test]
10109 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
10110 let mut stalled = task();
10111 stalled.start("20260902-000000-aaaa".to_owned());
10112 settle(
10113 &mut stalled,
10114 Verdict {
10115 status: RunStatus::Stalled,
10116 left_pr: false,
10117 parked: false,
10118 quota_hit: true,
10119 no_viable_candidates: false,
10120 },
10121 "quota",
10122 1,
10123 );
10124 assert_eq!(stalled.attempts, 0);
10125 assert!(
10126 stalled.status.runnable(),
10127 "a machine problem must leave the task in line"
10128 );
10129
10130 let mut blocked = task();
10131 blocked.start("20260902-000000-aaaa".to_owned());
10132 settle(
10133 &mut blocked,
10134 Verdict {
10135 status: RunStatus::Blocked,
10136 left_pr: false,
10137 parked: false,
10138 quota_hit: false,
10139 no_viable_candidates: false,
10140 },
10141 "findings open",
10142 1,
10143 );
10144 assert_eq!(blocked.attempts, 1);
10145 assert_eq!(
10146 blocked.status,
10147 TaskStatus::Held,
10148 "the last attempt hands the task to a human"
10149 );
10150 }
10151
10152 #[test]
10153 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
10154 let mut delivered = task();
10157 delivered.start("20260903-080619-01c2".to_owned());
10158 settle(
10159 &mut delivered,
10160 Verdict {
10161 status: RunStatus::Blocked,
10162 left_pr: true,
10163 parked: false,
10164 quota_hit: false,
10165 no_viable_candidates: false,
10166 },
10167 "no check status",
10168 4,
10169 );
10170 assert_eq!(
10171 delivered.status,
10172 TaskStatus::Held,
10173 "a pull request waiting on CI or a person is not a retryable failure"
10174 );
10175 assert!(
10176 !delivered.status.runnable(),
10177 "the loop must not pick this task up again"
10178 );
10179 assert_eq!(
10180 delivered.last_error.as_deref(),
10181 Some("no check status"),
10182 "the operator needs to be told what the gate was waiting for"
10183 );
10184
10185 let mut empty_handed = task();
10188 empty_handed.start("20260903-080619-01c2".to_owned());
10189 settle(
10190 &mut empty_handed,
10191 Verdict {
10192 status: RunStatus::Blocked,
10193 left_pr: false,
10194 parked: false,
10195 quota_hit: false,
10196 no_viable_candidates: false,
10197 },
10198 "findings open",
10199 4,
10200 );
10201 assert_eq!(empty_handed.status, TaskStatus::Failed);
10202 assert!(empty_handed.status.runnable());
10203 }
10204
10205 #[test]
10206 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
10207 let mut noop = task();
10213 noop.start("20260912-131304-391f".to_owned());
10214 settle(
10215 &mut noop,
10216 Verdict {
10217 status: RunStatus::VerifiedNoop,
10218 left_pr: false,
10219 parked: false,
10220 quota_hit: false,
10221 no_viable_candidates: true,
10222 },
10223 "candidate A: already fixed by b32cfc4, on main",
10224 4,
10225 );
10226 assert_eq!(
10227 noop.status,
10228 TaskStatus::Held,
10229 "an unverified claim is a request for a human, not a failure"
10230 );
10231 assert!(
10232 !noop.status.runnable(),
10233 "the loop must not requeue this on the same unverified claim"
10234 );
10235 assert_eq!(noop.attempts, 1);
10240 }
10241
10242 #[test]
10243 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
10244 let mut parked = task();
10249 parked.start("20260903-183634-2d98".to_owned());
10250 settle(
10251 &mut parked,
10252 Verdict {
10253 status: RunStatus::Implementing,
10254 left_pr: false,
10255 quota_hit: false,
10256 parked: true,
10257 no_viable_candidates: false,
10258 },
10259 "parked after `implementing`",
10260 2,
10261 );
10262 assert_eq!(parked.attempts, 0, "a park is refunded");
10263 assert!(
10264 parked.status.runnable(),
10265 "and the task stays in line so the next loop resumes its run"
10266 );
10267 assert_eq!(parked.status, TaskStatus::Parked);
10268 assert_eq!(
10269 parked.park_reason.as_deref(),
10270 Some("parked after `implementing`"),
10271 "the card says where it stopped"
10272 );
10273 assert_eq!(parked.last_error, None, "nothing failed");
10274
10275 let mut broken = task();
10279 broken.start("20260903-183634-2d98".to_owned());
10280 settle(
10281 &mut broken,
10282 Verdict {
10283 status: RunStatus::Implementing,
10284 left_pr: false,
10285 quota_hit: false,
10286 parked: false,
10287 no_viable_candidates: false,
10288 },
10289 "returned mid-flight",
10290 2,
10291 );
10292 assert_eq!(broken.attempts, 1);
10293 }
10294
10295 #[test]
10296 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
10297 let mut flaky = task();
10302 flaky.start("20260903-123023-e633".to_owned());
10303 settle(
10304 &mut flaky,
10305 Verdict {
10306 status: RunStatus::Stalled,
10307 left_pr: false,
10308 parked: false,
10309 quota_hit: false,
10310 no_viable_candidates: false,
10311 },
10312 "verdict rests on 1 of 3 judges",
10313 2,
10314 );
10315 assert_eq!(
10316 flaky.attempts, 1,
10317 "flakiness spends an attempt, so `max_attempts` still bounds it"
10318 );
10319 assert!(flaky.status.runnable(), "and it is still worth retrying");
10320
10321 let mut limited = task();
10323 limited.start("20260903-123023-e633".to_owned());
10324 settle(
10325 &mut limited,
10326 Verdict {
10327 status: RunStatus::Stalled,
10328 left_pr: false,
10329 parked: false,
10330 quota_hit: true,
10331 no_viable_candidates: false,
10332 },
10333 "judge-2, judge-3 out of quota",
10334 2,
10335 );
10336 assert_eq!(limited.attempts, 0, "a quota window is refunded");
10337 assert!(limited.status.runnable());
10338
10339 let mut worn = task();
10342 for _ in 0..2 {
10343 worn.release();
10344 }
10345 worn.start("20260903-123023-e633".to_owned());
10346 worn.attempts = 2;
10347 settle(
10348 &mut worn,
10349 Verdict {
10350 status: RunStatus::Stalled,
10351 left_pr: false,
10352 parked: false,
10353 quota_hit: false,
10354 no_viable_candidates: false,
10355 },
10356 "no quorum again",
10357 2,
10358 );
10359 assert_eq!(worn.status, TaskStatus::Held);
10360 assert!(!worn.status.runnable());
10361 }
10362
10363 #[test]
10364 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
10365 let mut wiped_out = task();
10372 wiped_out.start("20260907-025000-a1b2".to_owned());
10373 settle(
10374 &mut wiped_out,
10375 Verdict {
10376 status: RunStatus::Failed,
10377 left_pr: false,
10378 parked: false,
10379 quota_hit: true,
10380 no_viable_candidates: true,
10381 },
10382 "no candidate produced a change; nothing to judge",
10383 2,
10384 );
10385 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
10386 assert!(
10387 wiped_out.status.runnable(),
10388 "a machine problem must leave the task in line"
10389 );
10390
10391 let mut partial_progress = task();
10397 partial_progress.start("20260907-025500-c3d4".to_owned());
10398 settle(
10399 &mut partial_progress,
10400 Verdict {
10401 status: RunStatus::Failed,
10402 left_pr: false,
10403 parked: false,
10404 quota_hit: true,
10405 no_viable_candidates: false,
10406 },
10407 "gate failed on the winning candidate",
10408 2,
10409 );
10410 assert_eq!(
10411 partial_progress.attempts, 1,
10412 "a candidate that actually produced a change spends the attempt \
10413 even though some other seat hit its quota"
10414 );
10415 assert!(partial_progress.status.runnable());
10416 }
10417
10418 #[test]
10419 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
10420 let mut t = task();
10426 t.start("20260907-025000-a1b2".to_owned());
10427 let mut state = run_state(RunStatus::Failed);
10428 state.quota.push(QuotaLoss {
10429 cause: crate::agent::QuotaCause::UsageLimit,
10430 agent: String::new(),
10431 seat: "cand-a".to_owned(),
10432 node: "implement".to_owned(),
10433 at: Timestamp::now(),
10434 reset: None,
10435 });
10436 assert!(
10437 state.viable().is_empty(),
10438 "no candidate was added, so nothing is viable"
10439 );
10440 reclaim(&mut t, Some(state), 2, "en");
10441 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
10442 assert!(t.status.runnable());
10443 }
10444
10445 #[test]
10446 fn a_held_task_is_never_offered_to_the_loop() {
10447 let dir = tempfile::tempdir().unwrap();
10448 let queue = Queue::at(dir.path().to_path_buf());
10449 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
10450 let mut t = task();
10451 t.id = format!("2026090{n}-000000-000{n}");
10452 t.priority = priority;
10453 queue.put(&mut t).unwrap();
10454 }
10455 let mut held = task();
10456 held.id = "20260909-000000-9999".to_owned();
10457 held.priority = 99;
10458 held.hold_machine(None);
10459 queue.put(&mut held).unwrap();
10460
10461 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
10462 assert_eq!(order.len(), 3);
10463 assert!(!order.contains(&held.id));
10464 assert_eq!(
10465 order.first().cloned(),
10466 queue.next_runnable().map(|t| t.id),
10467 "the loop's first candidate is exactly what the queue offers"
10468 );
10469 assert_eq!(
10470 order,
10471 vec![
10472 "20260902-000000-0002".to_owned(),
10473 "20260903-000000-0003".to_owned(),
10474 "20260901-000000-0001".to_owned(),
10475 ],
10476 "priority first, then oldest, so nothing starves"
10477 );
10478 }
10479
10480 #[test]
10481 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
10482 let dir = tempfile::tempdir().unwrap();
10483 let queue = Queue::at(dir.path().to_path_buf());
10484 let mut old = task();
10485 old.id = "20260101-000000-old0".to_owned();
10486 queue.put(&mut old).unwrap();
10487 let mut fresh = task();
10488 fresh.id = "20260101-000000-new0".to_owned();
10489 queue.put(&mut fresh).unwrap();
10490
10491 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
10495 std::thread::sleep(Duration::from_millis(60));
10496 let live = queue.claim(&fresh.id).unwrap();
10497
10498 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10499 assert_eq!(swept, vec![old.id.clone()]);
10500 assert!(
10501 queue.claim(&old.id).is_ok(),
10502 "an unparseable lock older than the threshold is swept"
10503 );
10504 assert!(
10505 queue.claim(&fresh.id).is_err(),
10506 "a live pid protects its lock regardless of age"
10507 );
10508 drop(live);
10509 }
10510
10511 #[test]
10512 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
10513 let dir = tempfile::tempdir().unwrap();
10516 let queue = Queue::at(dir.path().to_path_buf());
10517 let mut t = task();
10518 t.id = "20260101-000000-live".to_owned();
10519 queue.put(&mut t).unwrap();
10520
10521 let claim = queue.claim(&t.id).unwrap();
10522 std::thread::sleep(Duration::from_millis(60));
10523
10524 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10525 assert!(
10526 swept.is_empty(),
10527 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
10528 );
10529 assert!(
10530 queue.claim(&t.id).is_err(),
10531 "the lock still protects its task"
10532 );
10533 drop(claim);
10534 }
10535
10536 fn injected_dead_pid() -> u32 {
10539 std::process::id().checked_add(1).unwrap_or(1)
10540 }
10541
10542 #[test]
10543 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
10544 let dir = tempfile::tempdir().unwrap();
10545 let queue = Queue::at(dir.path().to_path_buf());
10546 let mut t = task();
10547 t.id = "20260101-000000-dead".to_owned();
10548 queue.put(&mut t).unwrap();
10549 let dead_pid = injected_dead_pid();
10550
10551 std::fs::write(
10556 dir.path().join(format!("{}.lock", t.id)),
10557 dead_pid.to_string(),
10558 )
10559 .unwrap();
10560
10561 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10562 pid != dead_pid
10563 });
10564 assert_eq!(
10565 swept,
10566 vec![t.id.clone()],
10567 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
10568 );
10569 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
10570 }
10571
10572 #[test]
10573 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
10574 let dir = tempfile::tempdir().unwrap();
10575 let queue = Queue::at(dir.path().to_path_buf());
10576 let mut t = task();
10577 t.id = "20260101-000000-late".to_owned();
10578 queue.put(&mut t).unwrap();
10579 let dead_pid = injected_dead_pid();
10580
10581 assert!(
10584 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
10585 "nothing has claimed the task yet"
10586 );
10587
10588 std::fs::write(
10591 dir.path().join(format!("{}.lock", t.id)),
10592 dead_pid.to_string(),
10593 )
10594 .unwrap();
10595
10596 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10600 pid != dead_pid
10601 });
10602 assert_eq!(swept, vec![t.id.clone()]);
10603 }
10604
10605 #[test]
10606 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
10607 crate::run::pin_test_home();
10612 let dir = tempfile::tempdir().unwrap();
10613 let queue = Queue::at(dir.path().to_path_buf());
10614 let mut t = task();
10615 t.id = "20260101-000000-crsh".to_owned();
10616 t.status = TaskStatus::Running;
10617 t.attempts = 1;
10618 t.runs.push("20260904-000000-4043".to_owned());
10622 queue.put(&mut t).unwrap();
10623 let dead_pid = injected_dead_pid();
10624
10625 std::fs::write(
10628 dir.path().join(format!("{}.lock", t.id)),
10629 dead_pid.to_string(),
10630 )
10631 .unwrap();
10632
10633 assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
10639 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10640
10641 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10642 pid != dead_pid
10643 });
10644 assert_eq!(swept, vec![t.id.clone()]);
10645
10646 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10647 assert_eq!(reclaimed, vec![t.id.clone()]);
10648 let after = queue.get(&t.id).unwrap();
10649 assert_eq!(
10650 after.status,
10651 TaskStatus::Held,
10652 "no run.json to recover from, so a human is asked"
10653 );
10654 assert_eq!(
10655 after.runs,
10656 vec!["20260904-000000-4043".to_owned()],
10657 "the crashed run's id is kept as evidence, not discarded"
10658 );
10659 }
10660
10661 #[test]
10662 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
10663 let dir = tempfile::tempdir().unwrap();
10664 let queue = Queue::at(dir.path().to_path_buf());
10665 let mut t = task();
10666 t.id = "20260101-000000-unknown".to_owned();
10667 queue.put(&mut t).unwrap();
10668 let dead_pid = injected_dead_pid();
10669 std::fs::write(
10670 dir.path().join(format!("{}.lock", t.id)),
10671 dead_pid.to_string(),
10672 )
10673 .unwrap();
10674
10675 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
10676 assert!(swept.is_empty(), "an unknown pid must keep its lock");
10677 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
10678 }
10679
10680 fn run_state_in(status: RunStatus, language: &str) -> RunState {
10681 let mut s = run_state(status);
10682 s.config.graph.language = language.to_owned();
10683 s
10684 }
10685
10686 fn unstarted_verdict(status: RunStatus) -> Verdict {
10687 Verdict {
10688 status,
10689 left_pr: false,
10690 quota_hit: false,
10691 parked: false,
10692 no_viable_candidates: false,
10693 }
10694 }
10695
10696 #[test]
10697 fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
10698 let mut t = task();
10699 t.attempts = 1;
10700 settle_in(
10701 &mut t,
10702 unstarted_verdict(RunStatus::AlreadyInBase),
10703 "already in main",
10704 1,
10705 phrases("en"),
10706 None,
10707 );
10708 assert_eq!(t.status, TaskStatus::Done);
10709 assert_eq!(t.attempts, 0);
10710 }
10711
10712 #[test]
10713 fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
10714 let reason = |language: &str| {
10715 let mut t = task();
10716 settle_in(
10717 &mut t,
10718 unstarted_verdict(RunStatus::Judging),
10719 "boom",
10720 1,
10721 phrases(language),
10722 None,
10723 );
10724 t.last_error.or(t.hold_reason).unwrap_or_default()
10725 };
10726 assert!(
10727 reason("en").starts_with("the graph stopped at `"),
10728 "{}",
10729 reason("en")
10730 );
10731 assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
10732 assert!(reason("日本語").contains("boom"));
10733 assert_eq!(reason("fr"), reason("en"));
10734 }
10735
10736 #[test]
10737 fn describe_follows_the_run_language_and_keeps_the_run_id() {
10738 let en = describe(&run_state_in(RunStatus::Stalled, "en"));
10739 assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
10740 let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
10741 assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
10742 assert!(ja.contains("[run "), "{ja}");
10743 let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
10744 assert!(ended.starts_with("run 終了: "), "{ended}");
10745 let mut de = run_state_in(RunStatus::Failed, "de");
10746 let mut en = run_state_in(RunStatus::Failed, "en");
10747 de.id = "same".to_owned();
10748 en.id = "same".to_owned();
10749 assert_eq!(describe(&de), describe(&en));
10750 }
10751
10752 #[test]
10753 fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
10754 use crate::handover::Refused;
10755 let cases = [
10756 Refused::Foreign {
10757 branch: "b".into(),
10758 path: "/w/x".into(),
10759 why: "made by hand".into(),
10760 },
10761 Refused::Unsafe {
10762 branch: "b".into(),
10763 path: "/w/x".into(),
10764 why: "its worktree has uncommitted changes (a.rs)".into(),
10765 },
10766 Refused::ReleaseFailed {
10767 branch: "b".into(),
10768 path: "/w/x".into(),
10769 run: "ab12".into(),
10770 },
10771 ];
10772 for r in &cases {
10773 let en = (phrases("en").handover_refused)(r);
10774 assert_eq!(en, r.to_string());
10775 let ja = (phrases("ja").handover_refused)(r);
10776 assert!(
10777 !ja.contains("is checked out") && !ja.contains("try again"),
10778 "{ja}"
10779 );
10780 assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
10781 if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
10782 assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
10783 }
10784 }
10785 assert!(phrases("en").handover_hint.contains("release the task"));
10786 assert!(phrases("ja").handover_hint.contains("解放"));
10787 }
10788
10789 #[test]
10790 fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
10791 let build = |lang: &str| {
10792 let mut s = run_state_in(RunStatus::Blocked, lang);
10793 s.id = "same".to_owned();
10794 s.config.graph.review_rounds = 3;
10795 let mut r = review_round(3);
10796 r.expected = 3;
10797 r.answered = 1;
10798 s.reviews.push(r);
10799 s.event(
10800 "review",
10801 "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
10802 );
10803 s
10804 };
10805 let en = describe(&build("en"));
10806 assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
10807 let ja = describe(&build("ja"));
10808 assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
10809 assert!(!ja.contains("never answered"), "{ja}");
10810 assert!(ja.contains("[run "), "{ja}");
10811
10812 let mut failed = build("ja");
10815 failed.reviews[0].e2e.push(crate::run::CommandOutcome {
10816 command: "cargo test".to_owned(),
10817 code: Some(1),
10818 output_tail: String::new(),
10819 duration_ms: 0,
10820 resource_blocked: false,
10821 ..Default::default()
10822 });
10823 failed.event("review", "stopped; e2e failed: cargo test");
10824 let ja = describe(&failed);
10825 assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
10826 assert!(!ja.contains("席のレビュアー"), "{ja}");
10827 }
10828
10829 #[test]
10830 fn refusals_and_recovery_prose_follow_the_language() {
10831 let home = crate::run::test_home();
10832 let t = held_task_with("r1");
10833 let q = action_question(
10834 "r1",
10835 ask::ChoiceAction::Resume {
10836 run: "r1".to_owned(),
10837 },
10838 );
10839 let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
10840 ActionDecision::Refuse(s) => s,
10841 other => panic!("{other:?}"),
10842 };
10843 assert!(refuse(phrases("en")).contains("could not be read: gone"));
10844 assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
10845 assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
10846
10847 let mut held = task();
10848 reclaim(&mut held, None, 2, "ja");
10849 assert!(held.hold_reason.unwrap().contains("保留にしました"));
10850 let mut held = task();
10851 reclaim(&mut held, None, 2, "xx");
10852 assert!(held.hold_reason.unwrap().contains("held for a human"));
10853 }
10854
10855 fn run_state(status: RunStatus) -> RunState {
10856 let mut state = RunState::new(
10857 PathBuf::from("/repo"),
10858 "main".to_owned(),
10859 "abc1234def".to_owned(),
10860 "add retries".to_owned(),
10861 Config::default(),
10862 );
10863 state.status = status;
10864 state
10865 }
10866
10867 #[test]
10868 fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
10869 crate::run::pin_test_home();
10870 let dir = tempfile::tempdir().unwrap();
10871 let mut state = run_state(RunStatus::Blocked);
10872 state.id = "20260101-000000-audit".into();
10873 state.save_under(dir.path()).unwrap();
10874 let mut t = task();
10875 t.start(state.id.clone());
10876 state.status = RunStatus::Ready;
10879 settle_and_diagnose(
10880 &mut t,
10881 unstarted_verdict(RunStatus::Ready),
10882 "Verified local delivery",
10883 2,
10884 &state,
10885 );
10886 let completion = t.completion_history.last().unwrap();
10887 assert_eq!(completion.actor, CompletionActor::DaemonSettle);
10888 assert_eq!(completion.prior_status, TaskStatus::Running);
10889 assert_eq!(
10890 completion.reason.as_deref(),
10891 Some("Verified local delivery")
10892 );
10893 let snapshot = completion.run.as_ref().unwrap();
10894 assert_eq!(snapshot.id, state.id);
10895 assert_eq!(snapshot.status, Some(RunStatus::Ready));
10896 assert_eq!(
10897 RunState::load_under(&state.id, dir.path()).unwrap().status,
10898 RunStatus::Blocked,
10899 "settlement records the actual outcome without rewriting run history"
10900 );
10901 }
10902
10903 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
10904 Candidate {
10905 index: 0,
10906 label,
10907 agent: "claude".to_owned(),
10908 branch: format!("magi/x/{label}"),
10909 worktree: PathBuf::from("/repo"),
10910 summary: summary.to_owned(),
10911 stat: String::new(),
10912 files: 0,
10913 commits: usize::from(!empty),
10914 empty,
10915 failed: failed.map(str::to_owned),
10916 verified_noop: None,
10917 duration_ms: 0,
10918 folded: false,
10919 }
10920 }
10921
10922 #[test]
10923 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
10924 let mut state = run_state(RunStatus::Blocked);
10925 state.gate = vec![
10926 CommandOutcome {
10927 command: "cargo make check".to_owned(),
10928 code: Some(0),
10929 output_tail: "ok".to_owned(),
10930 duration_ms: 0,
10931 resource_blocked: false,
10932 ..Default::default()
10933 },
10934 CommandOutcome {
10935 command: "cargo test".to_owned(),
10936 code: Some(101),
10937 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
10938 duration_ms: 0,
10939 resource_blocked: false,
10940 ..Default::default()
10941 },
10942 ];
10943 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
10944 assert!(d.contains("cargo test"), "{d}");
10945 assert!(
10946 !d.contains("cargo make check"),
10947 "a passing check is not a diagnostic: {d}"
10948 );
10949 assert!(d.contains("assertion failed"), "{d}");
10950 }
10951
10952 #[test]
10953 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
10954 let mut state = run_state(RunStatus::Blocked);
10955 state.event(
10956 "land",
10957 "stopped: the fixer produced no commit while 2 check(s) were failing \
10958 (build, lint); stopping instead of looping on an unchanged tree",
10959 );
10960 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
10961 assert!(d.contains("build"), "{d}");
10962 assert!(d.contains("lint"), "{d}");
10963 assert!(d.contains("fixer produced no commit"), "{d}");
10964 }
10965
10966 #[test]
10967 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
10968 let state = run_state(RunStatus::VerifiedNoop);
10973 let d = describe(&state);
10974 assert!(
10975 d.contains("agent-verified no-op"),
10976 "expected the display label, not the wire spelling: {d}"
10977 );
10978 assert!(!d.contains("verified_noop"), "{d}");
10979 }
10980
10981 #[test]
10982 fn diagnostic_keeps_gate_panic_before_large_backtrace() {
10983 let mut state = run_state(RunStatus::Failed);
10984 state.gate.push(crate::run::CommandOutcome {
10985 command: "cargo test".into(),
10986 code: Some(101),
10987 output_tail: format!(
10988 "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
10989 " 41: 0x1234 - backtrace frame\n".repeat(10000)
10990 ),
10991 duration_ms: 1,
10992 resource_blocked: false,
10993 ..Default::default()
10994 });
10995 let d = diagnostic(&state).unwrap();
10996 assert!(d.contains("panicked at widget.rs:12"), "{d}");
10997 assert!(d.contains("assertion failed: widget missing"));
10998 assert!(d.contains("widget log"));
10999 }
11000
11001 #[test]
11002 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
11003 let mut state = run_state(RunStatus::Failed);
11009 state.candidates = vec![candidate(
11010 'A',
11011 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
11012 true,
11013 None,
11014 )];
11015 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
11016 assert!(d.contains("candidate A"), "{d}");
11017 assert!(d.contains("tagged v1.2.3"), "{d}");
11018 }
11019
11020 #[test]
11021 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
11022 let mut state = run_state(RunStatus::Failed);
11023 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
11024 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
11025 assert!(d.contains("candidate A"), "{d}");
11026 assert!(d.contains("agent timed out"), "{d}");
11027 }
11028
11029 #[test]
11030 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
11031 let mut state = run_state(RunStatus::Failed);
11034 state.candidates = vec![candidate('A', "did the work", false, None)];
11035 assert!(diagnostic(&state).is_none());
11036 }
11037
11038 #[test]
11039 fn diagnostic_is_bounded_however_much_a_run_printed() {
11040 let mut state = run_state(RunStatus::Blocked);
11041 state.gate = vec![
11042 CommandOutcome {
11043 command: "cargo test".to_owned(),
11044 code: Some(101),
11045 output_tail: "x".repeat(50_000),
11046 duration_ms: 0,
11047 resource_blocked: false,
11048 ..Default::default()
11049 },
11050 CommandOutcome {
11051 command: "cargo clippy".to_owned(),
11052 code: Some(1),
11053 output_tail: "y".repeat(50_000),
11054 duration_ms: 0,
11055 resource_blocked: false,
11056 ..Default::default()
11057 },
11058 ];
11059 state.candidates = vec![
11060 candidate('A', &"z".repeat(50_000), true, None),
11061 candidate('B', &"w".repeat(50_000), true, None),
11062 ];
11063 let d = diagnostic(&state).expect("plenty here to diagnose");
11064 assert!(
11065 d.len() <= DIAGNOSTIC_MAX,
11066 "diagnostic grew to {} bytes, unbounded",
11067 d.len()
11068 );
11069 }
11070
11071 #[test]
11072 fn selected_delivery_guards_survive_recovery_failure_accounting() {
11073 for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
11074 let mut t = task();
11075 let mut state = run_state(status);
11076 t.pr_recovery = Some(crate::pr_recovery::Selection {
11077 url: "url".into(),
11078 branch: format!("magi/task-{}", t.id),
11079 head: "a".repeat(40),
11080 source_head: None,
11081 source_run: None,
11082 source_proof: None,
11083 disposition: Some(crate::pr_recovery::Disposition::Land),
11084 instruction: t.instruction.clone(),
11085 approved_at: Timestamp::now(),
11086 });
11087 state.pr_recovery = t.pr_recovery.clone();
11088 t.start(state.id.clone());
11089 settle_and_diagnose(
11090 &mut t,
11091 Verdict {
11092 status,
11093 left_pr: false,
11094 quota_hit: false,
11095 parked: false,
11096 no_viable_candidates: false,
11097 },
11098 "delivery stopped",
11099 5,
11100 &state,
11101 );
11102 assert_eq!(t.status, TaskStatus::Held);
11103 let reason = t.hold_reason.as_deref().unwrap();
11104 if status == RunStatus::Ready {
11105 assert!(reason.contains("Selected PR delivery is incomplete"));
11106 assert!(t.recovery_budget.is_none());
11107 } else {
11108 assert!(reason.contains("Selected recovery stopped"));
11109 assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
11110 }
11111 assert!(t.pr_recovery.is_some());
11112 }
11113 }
11114
11115 #[test]
11116 fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
11117 let mut state = run_state(RunStatus::Voting);
11118 state.base_sync = Some(crate::run::BaseSync {
11119 tip: "base-tip".into(),
11120 behind: 3,
11121 attempts: 4,
11122 conflict: Some("base stopped".into()),
11123 already_in: None,
11124 });
11125 state.record_base_sync_stop("candidate-head");
11126 let mut t = task();
11127 t.start(state.id.clone());
11128 let verdict = Verdict {
11129 status: RunStatus::Blocked,
11130 left_pr: false,
11131 quota_hit: false,
11132 parked: false,
11133 no_viable_candidates: false,
11134 };
11135 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11136 assert_eq!(
11137 t.status,
11138 TaskStatus::Held,
11139 "unspent task attempts cannot start another competition"
11140 );
11141 let at = t.held_at;
11142 let cause = t.hold_notice_cause.clone();
11143 state.begin_pass();
11144 t.release_operator("test-resume", None);
11145 t.start(state.id.clone());
11146 settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11147 assert_eq!(t.status, TaskStatus::Held);
11148 assert_eq!(t.held_at, at);
11149 assert_eq!(t.hold_notice_cause, cause);
11150 }
11151
11152 #[test]
11153 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
11154 let mut state = run_state(RunStatus::Blocked);
11155 state.gate = vec![CommandOutcome {
11156 command: "cargo test".to_owned(),
11157 code: Some(101),
11158 output_tail: "assertion failed".to_owned(),
11159 duration_ms: 0,
11160 resource_blocked: false,
11161 ..Default::default()
11162 }];
11163 let verdict = Verdict {
11164 status: RunStatus::Blocked,
11165 left_pr: false,
11166 quota_hit: false,
11167 parked: false,
11168 no_viable_candidates: false,
11169 };
11170
11171 let mut t = task();
11174 t.start("run-1".to_owned());
11175 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11176 assert_eq!(t.status, TaskStatus::Failed);
11177 assert!(t.diagnostic.is_none());
11178
11179 t.start("run-2".to_owned());
11182 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11183 assert_eq!(t.status, TaskStatus::Held);
11184 let d = t.diagnostic.expect("a held task must carry its diagnostic");
11185 assert!(d.contains("cargo test"), "{d}");
11186 }
11187
11188 fn verified_noop_run_state() -> RunState {
11189 let mut state = run_state(RunStatus::VerifiedNoop);
11190 let summary = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"commit","target":"b32cfc4","method":"git merge-base --is-ancestor b32cfc4 HEAD","observed":"exit 0; b32cfc4 is on main","passed":true}],"unresolved":[]}"#;
11191 let mut c = candidate('A', summary, true, None);
11192 c.verified_noop = Some(summary.to_owned());
11193 state.candidates = vec![c];
11194 state
11195 }
11196
11197 #[test]
11198 fn a_held_task_names_the_open_question_it_is_waiting_on() {
11199 crate::run::pin_test_home();
11204 let home = crate::run::home();
11205 let state = verified_noop_run_state();
11206 let mut q = ask::Question::new(
11207 state.id.clone(),
11208 "implement".to_owned(),
11209 "impl-A".to_owned(),
11210 "is this really a no-op?".to_owned(),
11211 String::new(),
11212 Vec::new(),
11213 );
11214 Questions::at(home.join("questions")).put(&mut q).unwrap();
11215
11216 let verdict = Verdict {
11217 status: RunStatus::VerifiedNoop,
11218 left_pr: false,
11219 quota_hit: false,
11220 parked: false,
11221 no_viable_candidates: true,
11222 };
11223 let mut t = task();
11224 t.start(state.id.clone());
11225 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11226
11227 assert_eq!(t.status, TaskStatus::Held);
11228 let reason = t.hold_reason.expect("a held task must record why");
11229 assert!(
11230 reason.starts_with("run ended agent-verified no-op"),
11231 "the original settle reason must survive unchanged: {reason}"
11232 );
11233 assert!(
11234 reason.contains(q.short()),
11235 "the open question's id must be named so the notice is actionable: {reason}"
11236 );
11237 }
11238
11239 #[test]
11240 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
11241 crate::run::pin_test_home();
11242 let state = verified_noop_run_state();
11243
11244 let verdict = Verdict {
11245 status: RunStatus::VerifiedNoop,
11246 left_pr: false,
11247 quota_hit: false,
11248 parked: false,
11249 no_viable_candidates: true,
11250 };
11251 let mut t = task();
11252 t.start(state.id.clone());
11253 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11254
11255 assert_eq!(t.status, TaskStatus::Held);
11256 assert_eq!(
11257 t.hold_reason.as_deref(),
11258 Some("run ended agent-verified no-op"),
11259 "nothing to append when the question was already answered or never asked"
11260 );
11261 }
11262
11263 #[test]
11264 fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
11265 crate::run::pin_test_home();
11266
11267 let mut bad = run_state(RunStatus::VerifiedNoop);
11270 let mut c = candidate(
11271 'A',
11272 "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
11273 true,
11274 None,
11275 );
11276 c.verified_noop = Some("Not established.".to_owned());
11277 bad.candidates = vec![c];
11278
11279 let mut t = task();
11280 t.start(bad.id.clone());
11281 let verdict = Verdict {
11282 status: RunStatus::VerifiedNoop,
11283 left_pr: false,
11284 quota_hit: true,
11285 parked: false,
11286 no_viable_candidates: true,
11287 };
11288 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
11289 assert_eq!(
11290 t.status,
11291 TaskStatus::Failed,
11292 "inconsistent verified_noop must retry as Failed when attempts remain"
11293 );
11294 assert_eq!(t.attempts, 1);
11295 assert_eq!(
11296 t.last_error.as_deref(),
11297 Some("no-change result lacks verified evidence")
11298 );
11299 assert!(t.hold_reason.is_none());
11300
11301 let mut t_exhausted = task();
11305 t_exhausted.start(bad.id.clone());
11306 reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
11307 assert_eq!(t_exhausted.status, TaskStatus::Held);
11308 assert_eq!(t_exhausted.attempts, 1);
11309 assert_eq!(
11310 t_exhausted
11311 .hold_notice_cause
11312 .as_ref()
11313 .map(|c| c.stage.as_str()),
11314 Some("failed"),
11315 "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
11316 );
11317 let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
11318 assert!(
11319 !diag.contains("agent-verified no-op"),
11320 "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
11321 );
11322 assert!(diag.contains("Not established"), "{diag}");
11323 }
11324
11325 #[test]
11326 fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
11327 let mut state = verified_noop_run_state();
11328 let summary = state.candidates[0].summary.clone();
11329 state.candidates[0].summary = "Already satisfied.".to_owned();
11330 assert!(state.all_candidates_verified_noop());
11331
11332 state.candidates[0].summary = summary;
11333 state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
11334 assert!(!state.all_candidates_verified_noop());
11335 }
11336
11337 #[test]
11338 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
11339 crate::run::pin_test_home();
11340 let mut first = run_state(RunStatus::Blocked);
11341 first.id = "20260101-000000-sup1".to_owned();
11342 first.save().unwrap();
11343 let mut second = run_state(RunStatus::Merged);
11344 second.id = "20260101-000000-sup2".to_owned();
11345 second.save().unwrap();
11346
11347 let mut t = task();
11348 t.runs = vec![first.id.clone(), second.id.clone()];
11349 t.status = TaskStatus::Done;
11350
11351 supersede_prior_runs(&t, &crate::run::home());
11352
11353 assert_eq!(
11354 RunState::load(&first.id).unwrap().status,
11355 RunStatus::Superseded,
11356 "the first attempt's Blocked no longer needs anyone's attention"
11357 );
11358 assert_eq!(
11359 RunState::load(&second.id).unwrap().status,
11360 RunStatus::Merged,
11361 "the run that actually succeeded is left exactly as it was"
11362 );
11363 }
11364
11365 #[test]
11366 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
11367 crate::run::pin_test_home();
11373 let mut first = run_state(RunStatus::Blocked);
11374 first.id = "20260101-000000-sup9".to_owned();
11375 first.driver_pid = Some(std::process::id());
11378 first.driver_started_at = Some(
11379 crate::proc::process_started_at(std::process::id())
11380 .expect("this test process's own start time must be queryable"),
11381 );
11382 first.save().unwrap();
11383 let mut second = run_state(RunStatus::Merged);
11384 second.id = "20260101-000000-supa".to_owned();
11385 second.save().unwrap();
11386
11387 let mut t = task();
11388 t.runs = vec![first.id.clone(), second.id.clone()];
11389 t.status = TaskStatus::Done;
11390
11391 supersede_prior_runs(&t, &crate::run::home());
11392
11393 assert_eq!(
11394 RunState::load(&first.id).unwrap().status,
11395 RunStatus::Blocked,
11396 "a live driver_pid means something is still actually working this run, \
11397 even though no daemon claims it - rewriting under it would just be \
11398 undone the next time that process saves"
11399 );
11400 }
11401
11402 #[test]
11403 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
11404 let dir = tempfile::tempdir().unwrap();
11410 let home = dir.path().to_path_buf();
11411 let queue = Queue::at(dir.path().join("queue"));
11412
11413 let mut first = run_state(RunStatus::Blocked);
11414 first.id = "20260101-000000-supd".to_owned();
11415 first.driver_pid = Some(std::process::id());
11416 first.driver_started_at = Some(
11417 crate::proc::process_started_at(std::process::id())
11418 .expect("this test process's own start time must be queryable"),
11419 );
11420 first.save_under(&home).unwrap();
11421 let mut second = run_state(RunStatus::Merged);
11422 second.id = "20260101-000000-supe".to_owned();
11423 second.save_under(&home).unwrap();
11424
11425 let mut t = task();
11426 t.runs = vec![first.id.clone(), second.id.clone()];
11427 t.status = TaskStatus::Done;
11428 queue.put(&mut t).unwrap();
11429
11430 resweep_superseded_attempts(&queue, &home);
11431 assert_eq!(
11432 RunState::load_under(&first.id, &home).unwrap().status,
11433 RunStatus::Blocked,
11434 "still live on the first pass, so still untouched"
11435 );
11436
11437 let mut stale = RunState::load_under(&first.id, &home).unwrap();
11443 stale.driver_started_at = Some("1".to_owned());
11444 stale.save_under(&home).unwrap();
11445
11446 resweep_superseded_attempts(&queue, &home);
11447 assert_eq!(
11448 RunState::load_under(&first.id, &home).unwrap().status,
11449 RunStatus::Superseded,
11450 "the second pass catches up what the first one correctly skipped"
11451 );
11452 }
11453
11454 #[test]
11455 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
11456 crate::run::pin_test_home();
11457 let mut first = run_state(RunStatus::Blocked);
11458 first.id = "20260101-000000-sup3".to_owned();
11459 first.save().unwrap();
11460 let mut second = run_state(RunStatus::Blocked);
11461 second.id = "20260101-000000-sup4".to_owned();
11462 second.save().unwrap();
11463
11464 let mut t = task();
11465 t.runs = vec![first.id.clone(), second.id.clone()];
11466 t.status = TaskStatus::Failed;
11470
11471 supersede_prior_runs(&t, &crate::run::home());
11472
11473 assert_eq!(
11474 RunState::load(&first.id).unwrap().status,
11475 RunStatus::Blocked
11476 );
11477 assert_eq!(
11478 RunState::load(&second.id).unwrap().status,
11479 RunStatus::Blocked
11480 );
11481 }
11482
11483 #[test]
11484 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
11485 crate::run::pin_test_home();
11489 let mut first = run_state(RunStatus::Blocked);
11490 first.id = "20260101-000000-sup5".to_owned();
11491 first.save().unwrap();
11492
11493 let mut t = task();
11494 t.runs = vec![first.id.clone()];
11495 t.status = TaskStatus::Done;
11496
11497 supersede_prior_runs(&t, &crate::run::home());
11498
11499 assert_eq!(
11500 RunState::load(&first.id).unwrap().status,
11501 RunStatus::Blocked,
11502 "a single-attempt task has no earlier run to supersede"
11503 );
11504 }
11505
11506 #[test]
11507 fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
11508 for status in [
11509 RunStatus::Blocked,
11510 RunStatus::Stalled,
11511 RunStatus::Failed,
11512 RunStatus::Ready,
11513 RunStatus::Merged,
11514 ] {
11515 let dir = tempfile::tempdir().unwrap();
11516 let home = dir.path();
11517 let mut first = run_state(RunStatus::Blocked);
11518 first.id = "20260101-000000-supb".to_owned();
11519 first.save_under(home).unwrap();
11520 let mut second = run_state(status);
11521 second.id = "20260101-000000-supc".to_owned();
11522 second.save_under(home).unwrap();
11523
11524 let mut t = task();
11525 t.runs = vec![first.id.clone(), second.id.clone()];
11526 t.hold_manual(Some("Unmerged work remains".into()));
11527 let mut context = CompletionContext::new(
11528 CompletionActor::Cli,
11529 Some("Discard the unmerged attempts".into()),
11530 home,
11531 &t,
11532 );
11533 context.discard = true;
11534 t.succeed(context);
11535 assert_eq!(t.completion_history.len(), 1);
11536
11537 supersede_prior_runs(&t, home);
11538
11539 assert_eq!(
11540 RunState::load_under(&first.id, home).unwrap().status,
11541 RunStatus::Blocked,
11542 "an audited manual close is not proof the earlier work landed"
11543 );
11544 assert_eq!(
11545 RunState::load_under(&second.id, home).unwrap().status,
11546 status,
11547 "the latest attempt retains its actual outcome"
11548 );
11549 }
11550 }
11551
11552 #[test]
11553 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
11554 crate::run::pin_test_home();
11558 let mut failed = run_state(RunStatus::Failed);
11559 failed.id = "20260101-000000-sup6".to_owned();
11560 failed.save().unwrap();
11561 let mut noop = run_state(RunStatus::VerifiedNoop);
11562 noop.id = "20260101-000000-sup7".to_owned();
11563 noop.save().unwrap();
11564 let mut winner = run_state(RunStatus::Ready);
11565 winner.id = "20260101-000000-sup8".to_owned();
11566 winner.save().unwrap();
11567
11568 let mut t = task();
11569 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
11570 t.status = TaskStatus::Done;
11571
11572 supersede_prior_runs(&t, &crate::run::home());
11573
11574 assert_eq!(
11575 RunState::load(&failed.id).unwrap().status,
11576 RunStatus::Failed
11577 );
11578 assert_eq!(
11579 RunState::load(&noop.id).unwrap().status,
11580 RunStatus::VerifiedNoop
11581 );
11582 }
11583
11584 fn approval_question(run: &str) -> ask::Question {
11585 ask::Question::new(
11586 run.to_owned(),
11587 land::APPROVAL_NODE.to_owned(),
11588 "land".to_owned(),
11589 "merge?".to_owned(),
11590 String::new(),
11591 vec!["merge".to_owned(), "hold".to_owned()],
11592 )
11593 }
11594
11595 #[test]
11596 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
11597 crate::run::pin_test_home();
11598 let mut state = run_state(RunStatus::Landing);
11599 state.id = "20260101-000000-fre1".to_owned();
11600 state.parked = true;
11601 state.save().unwrap();
11602 ask::Questions::open()
11603 .put(&mut approval_question(&state.id))
11604 .unwrap();
11605
11606 let mut t = task();
11607 t.runs.push(state.id.clone());
11608 assert_eq!(
11609 land_resume_state(&t),
11610 LandResume::StillWaiting,
11611 "nobody has answered and the timeout has not passed"
11612 );
11613 }
11614
11615 #[test]
11616 fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
11617 crate::run::pin_test_home();
11618 let mut state = run_state(RunStatus::Gating);
11619 state.id = "20260101-000000-gt01".to_owned();
11620 state.parked = true;
11621 state.config.graph.answer_timeout = 60;
11622 state.github_text = Some(crate::run::GithubTextAsk {
11623 rewrite: None,
11624 fingerprint: "f".into(),
11625 title: true,
11626 body: false,
11627 categories: vec!["title-language".into()],
11628 question: None,
11629 asks: 1,
11630 resolved: false,
11631 chosen_title: None,
11632 choice: None,
11633 publication: None,
11634 });
11635 state.save().unwrap();
11636 let store = ask::Questions::open();
11637 let mut q = ask::Question::new(
11638 state.id.clone(),
11639 crate::github_text::ASK_NODE.to_owned(),
11640 crate::github_text::ASK_SEAT.to_owned(),
11641 "s".into(),
11642 String::new(),
11643 vec!["use fallback".into()],
11644 );
11645 store.put(&mut q).unwrap();
11646 let mut t = task();
11647 t.runs.push(state.id.clone());
11648 assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
11649 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11650 store.put(&mut q).unwrap();
11651 assert_eq!(land_resume_state(&t), LandResume::Ready);
11652 assert!(!store.get(&q.id).unwrap().status.open());
11653 state.github_text.as_mut().unwrap().resolved = true;
11655 state.save().unwrap();
11656 assert_eq!(land_resume_state(&t), LandResume::NotLanding);
11657 }
11658
11659 #[test]
11660 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
11661 crate::run::pin_test_home();
11666 let mut state = run_state(RunStatus::Landing);
11667 state.id = "20260101-000000-exp1".to_owned();
11668 state.parked = true;
11669 state.config.graph.answer_timeout = 60;
11670 state.save().unwrap();
11671
11672 let store = ask::Questions::open();
11673 let mut q = approval_question(&state.id);
11674 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11675 store.put(&mut q).unwrap();
11676
11677 let mut t = task();
11678 t.runs.push(state.id.clone());
11679 assert_eq!(
11680 land_resume_state(&t),
11681 LandResume::Ready,
11682 "an expired question must not be waited on forever"
11683 );
11684
11685 let after = store.get(&q.id).unwrap();
11686 assert!(
11687 !after.status.open(),
11688 "the question is abandoned, not silently ignored"
11689 );
11690 assert!(
11691 after.resolution().is_none(),
11692 "an abandoned question is not read as a decision"
11693 );
11694 }
11695
11696 #[test]
11697 fn reclaim_settles_a_running_task_against_its_last_run() {
11698 let mut t = task();
11699 t.start("20260904-000000-4043".to_owned());
11700 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
11701 assert_eq!(
11702 t.status,
11703 TaskStatus::Done,
11704 "a run that actually finished must not stay `running` forever"
11705 );
11706 }
11707
11708 #[test]
11709 fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
11710 let dir = tempfile::tempdir().unwrap();
11711 let queue = Queue::at(dir.path().join("queue"));
11712 let mut task = task();
11713 let mut run = run_state(RunStatus::Blocked);
11714 run.reserve_under(dir.path()).unwrap();
11715 run.driver_exited = true;
11716 run.save_under(dir.path()).unwrap();
11717 queue.put(&mut task).unwrap();
11718 let stale = task.clone();
11719 task.resume_override = Some(crate::queue::OperatorResume {
11720 question_id: "pending-resume".into(),
11721 at: Timestamp::now(),
11722 conductor_rehold: None,
11723 forced: true,
11724 pinned_run: Some(run.id.clone()),
11725 });
11726 task.start(run.id.clone());
11727 queue.put(&mut task).unwrap();
11728 let mut recovered = queue.get(&task.id).unwrap();
11730 let disk = RunState::load_under(&run.id, dir.path()).unwrap();
11731 reclaim(&mut recovered, Some(disk), 2, "en");
11732 queue.put(&mut recovered).unwrap();
11733 assert!(recovered.resume_override.is_none());
11734 assert_eq!(
11735 recovered.dispatched_resumes.get("pending-resume"),
11736 Some(&run.id)
11737 );
11738 let mut stale = stale;
11739 queue.put(&mut stale).unwrap();
11740 assert_eq!(
11741 stale.dispatched_resumes, recovered.dispatched_resumes,
11742 "a stale task writer cannot erase dispatch ownership"
11743 );
11744 let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
11745 assert!(resumed.decision_starts.is_empty());
11746 resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
11747 assert!(
11748 resumed.decision_starts.is_empty(),
11749 "handoff is not execution proof"
11750 );
11751 resumed.begin_pass();
11752 resumed.save_under(dir.path()).unwrap();
11753 let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
11754 assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
11755 disk.carry_dispatched_resumes(&recovered);
11756 disk.begin_pass();
11757 assert_eq!(
11758 disk.decision_starts.get("pending-resume"),
11759 Some(&0),
11760 "later execution must preserve the original pass receipt"
11761 );
11762 }
11763
11764 #[test]
11765 fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
11766 let mut t = task();
11767 t.start("20260904-000000-4043".to_owned());
11768 t.last_error = Some("earlier trouble".to_owned());
11769 let mut state = run_state(RunStatus::Judging);
11770 state.parked = true;
11771 reclaim(&mut t, Some(state), 1, "en");
11772 assert_eq!(t.status, TaskStatus::Parked);
11773 assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
11774 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11775 assert!(t.park_reason.is_some());
11776 assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
11777 assert!(!t.fresh_start);
11778 assert!(t.status.runnable());
11779 }
11780
11781 #[test]
11782 fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
11783 let mut t = task();
11784 t.start("20260904-000000-4043".to_owned());
11785 t.last_error = Some("earlier trouble".to_owned());
11786 settle(
11787 &mut t,
11788 Verdict {
11789 status: RunStatus::Judging,
11790 left_pr: false,
11791 quota_hit: false,
11792 parked: true,
11793 no_viable_candidates: false,
11794 },
11795 "parked after `judging`",
11796 1,
11797 );
11798 assert_eq!(t.status, TaskStatus::Parked);
11799 assert_eq!(t.attempts, 0);
11800 assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11801 assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
11802 assert_eq!(t.schema, crate::queue::SCHEMA);
11803 assert!(
11804 crate::notices::task_held(&t).is_none(),
11805 "a park is not news"
11806 );
11807 t.start("20260904-000000-4043".to_owned());
11808 assert_eq!(t.park_reason, None);
11809 }
11810
11811 #[test]
11812 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
11813 let mut t = task();
11817 t.start("20260904-000000-4043".to_owned());
11818 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
11819 assert_eq!(t.status, TaskStatus::Failed);
11820 assert!(t.status.runnable());
11821 }
11822
11823 #[test]
11824 fn a_settled_parked_pass_records_its_cause_and_the_refund() {
11825 let mut t = task();
11826 t.start("20260904-000000-4043".to_owned());
11827 assert_eq!(t.attempts, 1);
11828 let mut run = run_state(RunStatus::Implementing);
11829 run.id = "20260904-000000-4043".to_owned();
11830 run.begin_pass();
11831 let cause = crate::run::ParkCause::Upgrade {
11832 from: "0.121.0".to_owned(),
11833 to: Some("0.121.1".to_owned()),
11834 };
11835 run.end_pass_parked(cause.clone());
11836 run.parked = true;
11837 let verdict = Verdict {
11838 status: run.status,
11839 left_pr: false,
11840 quota_hit: false,
11841 parked: true,
11842 no_viable_candidates: false,
11843 };
11844 let mut orphan = t.clone();
11847 reclaim(&mut orphan, Some(run.clone()), 2, "en");
11848 assert_eq!(orphan.status, TaskStatus::Parked);
11849 assert_eq!(orphan.attempts, 0);
11850 assert_eq!(
11851 orphan.upgrade_resume_key(),
11852 Some((run.passes[0].started_at, orphan.id.as_str()))
11853 );
11854 settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
11855 assert_eq!(t.attempts, 0);
11856 assert_eq!(t.passes.len(), 1);
11857 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11858 assert_eq!(t.passes[0].parked, Some(cause));
11859 assert_eq!(t.passes[0].pass_index, 0);
11860 assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
11861 assert!(t.upgrade_resume_key().is_some());
11862
11863 t.start("20260904-000000-4043".to_owned());
11866 run.begin_pass();
11867 run.status = RunStatus::Failed;
11868 let verdict = Verdict {
11869 status: RunStatus::Failed,
11870 left_pr: false,
11871 quota_hit: false,
11872 parked: false,
11873 no_viable_candidates: false,
11874 };
11875 settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
11876 assert_eq!(t.passes.len(), 2);
11877 assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11878 assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
11879 assert_eq!(t.passes[1].pass_index, 1);
11880 assert_eq!(t.attempts, 1);
11881 }
11882
11883 #[test]
11884 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
11885 let mut t = task();
11886 t.start("20260904-000000-4043".to_owned());
11887 reclaim(&mut t, None, 2, "en");
11888 assert_eq!(t.status, TaskStatus::Held);
11889 assert!(
11890 t.last_error
11891 .as_deref()
11892 .is_some_and(|e| e.contains("running")),
11893 "the operator needs to know why this task was held"
11894 );
11895 }
11896
11897 #[test]
11898 fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
11899 let dir = tempfile::tempdir().unwrap();
11900 let queue = Queue::at(dir.path().to_path_buf());
11901 let mut task = task();
11902 let run = "20261124-000000-dead";
11903 task.link_run(run);
11904 task.attempts = 2;
11905 task.status = TaskStatus::Running;
11906 task.sync_only = Some(crate::base_sync_only::Request {
11907 run: run.into(),
11908 at: Timestamp::now(),
11909 });
11910 queue.put(&mut task).unwrap();
11911 assert_eq!(
11912 reclaim_orphaned_running(&queue, 3, &Default::default()),
11913 vec![task.id.clone()]
11914 );
11915 let saved = queue.get(&task.id).unwrap();
11916 assert_eq!(saved.status, TaskStatus::Held);
11917 assert_eq!(saved.attempts, 2);
11918 assert_eq!(saved.execution_runs(), [run]);
11919 assert!(
11920 saved
11921 .last_error
11922 .unwrap()
11923 .contains("verification was not allowed")
11924 );
11925 assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
11926 }
11927
11928 #[test]
11929 fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
11930 use crate::base_sync_only::{Outcome, Pass, Request};
11931
11932 let mut state = run_state(RunStatus::Blocked);
11933 let mut task = task();
11934 let request = Request {
11935 run: state.id.clone(),
11936 at: Timestamp::now(),
11937 };
11938 task.start(state.id.clone());
11939 task.sync_only = Some(request.clone());
11940 task.attempts = 2;
11942 let mut pass = Pass::new(request, &state);
11943 pass.result = Outcome::AlreadyCurrent;
11944 state.sync_only_passes.push(pass);
11945 state.begin_pass();
11946
11947 reclaim(&mut task, Some(state), 3, "en");
11948
11949 assert_eq!(task.status, TaskStatus::Held);
11950 assert_eq!(task.attempts, 2);
11951 assert!(task.sync_only.is_none());
11952 let detail = task.hold_reason.unwrap();
11953 assert!(detail.contains("HEAD already contains the base"));
11954 assert!(detail.contains("verification was not allowed"));
11955 }
11956
11957 #[test]
11958 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
11959 let dir = tempfile::tempdir().unwrap();
11960 let queue = Queue::at(dir.path().to_path_buf());
11961
11962 let mut orphaned = task();
11964 orphaned.id = "20260904-000000-orph".to_owned();
11965 orphaned.status = TaskStatus::Running;
11966 orphaned.attempts = 1;
11967 queue.put(&mut orphaned).unwrap();
11968
11969 let mut alive = task();
11970 alive.id = "20260904-000000-live".to_owned();
11971 alive.status = TaskStatus::Running;
11972 alive.attempts = 1;
11973 queue.put(&mut alive).unwrap();
11974 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
11975
11976 let mut queued = task();
11977 queued.id = "20260904-000000-wait".to_owned();
11978 queue.put(&mut queued).unwrap();
11979
11980 let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
11981 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
11982
11983 assert_eq!(
11984 queue.get(&orphaned.id).unwrap().status,
11985 TaskStatus::Held,
11986 "nothing was driving it and there was no run to recover"
11987 );
11988 assert_eq!(
11989 queue.get(&alive.id).unwrap().status,
11990 TaskStatus::Running,
11991 "a live claim must protect the task it belongs to"
11992 );
11993 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
11994 }
11995
11996 fn read_run_under(home: &Path, id: &str) -> RunState {
12002 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
12003 serde_json::from_str(&body).unwrap()
12004 }
12005
12006 #[test]
12007 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
12008 let dir = tempfile::tempdir().unwrap();
12009 let home = dir.path().to_path_buf();
12010 let now = Timestamp::now();
12011 let overrun_seat = || crate::run::ActiveSeat {
12012 node: "implement".to_owned(),
12013 started_at: now - jiff::SignedDuration::new(21_000, 0),
12014 timeout_secs: 3_600,
12015 attempt: 0,
12016 task: None,
12017 command: None,
12018 index: None,
12019 total: None,
12020 };
12021
12022 let mut dead = run_state(RunStatus::Implementing);
12023 dead.id = "20260101-000000-dead".to_owned();
12024 dead.active.insert("impl-A".to_owned(), overrun_seat());
12025 dead.driver_pid = Some(4242);
12028 dead.save_under(&home).unwrap();
12029
12030 let mut alive = run_state(RunStatus::Implementing);
12033 alive.id = "20260101-000000-aliv".to_owned();
12034 alive.active.insert("impl-A".to_owned(), overrun_seat());
12035 alive.save_under(&home).unwrap();
12036 let mut status = Status::new();
12037 status.current = vec![Current {
12038 worker: None,
12039 task: "20260101-000000-task".to_owned(),
12040 run: alive.id.clone(),
12041 }];
12042 write_status_to(&home.join("daemon.json"), &status).unwrap();
12043
12044 let questions = Questions::at(home.join("questions"));
12048 let mut q = ask::Question::new(
12049 dead.id.clone(),
12050 "implement".to_owned(),
12051 "impl-A".to_owned(),
12052 "Which storage backend?".to_owned(),
12053 String::new(),
12054 vec!["SQLite".to_owned(), "Redis".to_owned()],
12055 );
12056 questions.put(&mut q).unwrap();
12057
12058 let abandoned = reclaim_abandoned_runs_with(
12059 &home,
12060 now,
12061 |pid| if pid == 4242 { Some(false) } else { None },
12062 |_| panic!("a query answering Dead outright needs no identity corroboration"),
12063 );
12064 assert_eq!(abandoned, vec![dead.id.clone()]);
12065
12066 let reloaded = read_run_under(&home, &dead.id);
12067 assert_eq!(reloaded.status, RunStatus::Failed);
12068 assert!(reloaded.active.is_empty());
12069 assert!(
12070 !questions.get(&q.id).unwrap().status.open(),
12071 "the failed run's own open question must be settled in the same pass"
12072 );
12073
12074 let still_alive = read_run_under(&home, &alive.id);
12075 assert_eq!(
12076 still_alive.status,
12077 RunStatus::Implementing,
12078 "a live daemon's claim protects it"
12079 );
12080 assert!(!still_alive.active.is_empty());
12081 }
12082
12083 #[test]
12093 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
12094 let dir = tempfile::tempdir().unwrap();
12095 let home = dir.path().to_path_buf();
12096 let now = Timestamp::now();
12097
12098 let mut manual = run_state(RunStatus::Reviewing);
12099 manual.id = "20260101-000000-manl".to_owned();
12100 manual.active.insert(
12101 "review-1".to_owned(),
12102 crate::run::ActiveSeat {
12103 node: "review".to_owned(),
12104 started_at: now - jiff::SignedDuration::new(21_000, 0),
12105 timeout_secs: 3_600,
12106 attempt: 0,
12107 task: None,
12108 command: None,
12109 index: None,
12110 total: None,
12111 },
12112 );
12113 manual.driver_pid = Some(4242);
12117 manual.driver_started_at = Some("1790000000".to_owned());
12118 manual.save_under(&home).unwrap();
12119
12120 let abandoned = reclaim_abandoned_runs_with(
12121 &home,
12122 now,
12123 |pid| if pid == 4242 { Some(true) } else { None },
12124 |pid| {
12125 if pid == 4242 {
12126 Some("1790000000".to_owned())
12127 } else {
12128 None
12129 }
12130 },
12131 );
12132 assert!(
12133 abandoned.is_empty(),
12134 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
12135 );
12136
12137 let reloaded = read_run_under(&home, &manual.id);
12138 assert_eq!(reloaded.status, RunStatus::Reviewing);
12139 assert!(!reloaded.active.is_empty());
12140 }
12141
12142 #[test]
12143 fn an_already_claimed_task_is_skipped_rather_than_failed() {
12144 let dir = tempfile::tempdir().unwrap();
12145 let queue = Queue::at(dir.path().to_path_buf());
12146 let mut only = task();
12147 queue.put(&mut only).unwrap();
12148
12149 let _elsewhere = queue.claim(&only.id).unwrap();
12150 let candidates = runnable(&queue);
12151 assert_eq!(candidates.len(), 1, "the task is still runnable");
12152 assert!(
12153 queue.claim(&candidates[0].id).is_err(),
12154 "the loop cannot take a claim somebody else holds"
12155 );
12156
12157 let after = queue.get(&only.id).unwrap();
12158 assert_eq!(after.status, TaskStatus::Queued);
12159 assert_eq!(
12160 after.attempts, 0,
12161 "losing the race is not an attempt at the task"
12162 );
12163 assert_eq!(after.last_error, None);
12164 }
12165
12166 #[test]
12167 fn the_status_file_round_trips_and_its_heartbeat_advances() {
12168 let dir = tempfile::tempdir().unwrap();
12169 let path = dir.path().join("daemon.json");
12170
12171 let mut status = Status::new();
12172 status.idle = false;
12173 status.completed = 7;
12174 status.current = vec![Current {
12175 worker: None,
12176 task: "20260902-000000-t111".to_owned(),
12177 run: "20260902-000001-r111".to_owned(),
12178 }];
12179 write_status_to(&path, &status).unwrap();
12180 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12181 assert_eq!(first.schema, SCHEMA);
12182 assert_eq!(first.pid, std::process::id());
12183 assert!(!first.idle);
12184 assert_eq!(first.completed, 7);
12185 assert_eq!(first.current, status.current);
12186 assert!(
12187 !path.with_extension("json.tmp").exists(),
12188 "the temp file is renamed, not left behind"
12189 );
12190
12191 std::thread::sleep(Duration::from_millis(5));
12192 status.updated_at = Timestamp::now();
12193 status.polls = 3;
12194 write_status_to(&path, &status).unwrap();
12195 let second: Status =
12196 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12197 assert!(
12198 second.updated_at > first.updated_at,
12199 "a reader can only detect staleness if the heartbeat moves"
12200 );
12201 assert_eq!(
12202 second.started_at, first.started_at,
12203 "the start time is not a heartbeat"
12204 );
12205 assert_eq!(second.polls, 3);
12206 }
12207
12208 #[test]
12209 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
12210 let dir = tempfile::tempdir().unwrap();
12211
12212 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
12213
12214 let mut status = Status::new();
12215 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
12216 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12217 let stale = read_status(dir.path()).unwrap();
12218 assert!(
12219 !stale.running(Timestamp::now()),
12220 "a minute without a heartbeat is a dead daemon, not a busy one"
12221 );
12222 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
12223
12224 status.updated_at = Timestamp::now();
12225 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12226 let fresh = read_status(dir.path()).unwrap();
12227 assert!(fresh.running(Timestamp::now()));
12228 }
12229
12230 #[test]
12231 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
12232 let dir = tempfile::tempdir().unwrap();
12233 let now = Timestamp::now();
12234 let mine = "20260903-080619-01c2";
12235
12236 assert!(
12237 !is_working_on(dir.path(), mine, now),
12238 "no status file means nobody is working on anything"
12239 );
12240
12241 let mut status = Status::new();
12242 status.current = vec![Current {
12243 worker: None,
12244 task: "20260903-080340-0167".to_owned(),
12245 run: mine.to_owned(),
12246 }];
12247 status.updated_at = now;
12248 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12249 assert!(is_working_on(dir.path(), mine, now));
12250 assert!(
12251 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
12252 "a daemon busy with one run is not working on another"
12253 );
12254
12255 status.updated_at = now - jiff::SignedDuration::from_secs(600);
12258 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12259 assert!(
12260 !is_working_on(dir.path(), mine, now),
12261 "a stale heartbeat is a dead daemon, so its run is a leftover"
12262 );
12263 }
12264
12265 #[test]
12266 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
12267 let dir = tempfile::tempdir().unwrap();
12268 let now = Timestamp::now();
12269
12270 assert!(
12271 !is_working_on_short(dir.path(), "01c2", now),
12272 "no status file means nobody is working on anything"
12273 );
12274
12275 let mut status = Status::new();
12276 status.current = vec![Current {
12277 worker: None,
12278 task: "20260903-080340-0167".to_owned(),
12279 run: "20260903-080619-01c2".to_owned(),
12280 }];
12281 status.updated_at = now;
12282 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12283 assert!(
12284 is_working_on_short(dir.path(), "01c2", now),
12285 "the run's short id is the last block of its full id"
12286 );
12287 assert!(
12288 !is_working_on_short(dir.path(), "3cbf", now),
12289 "a daemon busy with one worktree bay is not working on another"
12290 );
12291 }
12292
12293 #[test]
12294 fn a_newer_status_file_still_yields_a_reading() {
12295 let dir = tempfile::tempdir().unwrap();
12296 std::fs::write(
12299 dir.path().join("daemon.json"),
12300 serde_json::json!({
12301 "schema": 2,
12302 "updated_at": Timestamp::now().to_string(),
12303 "idle": true,
12304 "surprise": { "nested": [1, 2, 3] },
12305 })
12306 .to_string(),
12307 )
12308 .unwrap();
12309
12310 let reading = read_status(dir.path()).expect("a forward-compatible read");
12311 assert!(reading.running(Timestamp::now()));
12312 assert!(reading.idle);
12313 assert!(reading.current.is_empty());
12314 }
12315
12316 #[test]
12317 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
12318 let dir = tempfile::tempdir().unwrap();
12324 std::fs::write(
12325 dir.path().join("daemon.json"),
12326 serde_json::json!({
12327 "schema": 1,
12328 "pid": 4242,
12329 "updated_at": Timestamp::now().to_string(),
12330 "idle": false,
12331 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
12332 "completed": 3,
12333 "polls": 9,
12334 })
12335 .to_string(),
12336 )
12337 .unwrap();
12338
12339 let reading = read_status(dir.path()).expect("an older shape must still parse");
12340 assert!(reading.running(Timestamp::now()));
12341 assert_eq!(
12342 reading.current,
12343 vec![Current {
12344 worker: None,
12345 task: "20260902-140501-aaaa".to_owned(),
12346 run: "20260902-140502-bbbb".to_owned(),
12347 }]
12348 );
12349 }
12350
12351 #[test]
12352 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
12353 let dir = tempfile::tempdir().unwrap();
12354 std::fs::write(
12355 dir.path().join("daemon.json"),
12356 serde_json::json!({
12357 "schema": 1,
12358 "updated_at": Timestamp::now().to_string(),
12359 "idle": true,
12360 "current": null,
12361 })
12362 .to_string(),
12363 )
12364 .unwrap();
12365 let with_null = read_status(dir.path()).expect("null must still parse");
12366 assert!(with_null.current.is_empty());
12367
12368 std::fs::write(
12369 dir.path().join("daemon.json"),
12370 serde_json::json!({
12371 "schema": 1,
12372 "updated_at": Timestamp::now().to_string(),
12373 "idle": true,
12374 })
12375 .to_string(),
12376 )
12377 .unwrap();
12378 let absent = read_status(dir.path()).expect("a missing field must still parse");
12379 assert!(absent.current.is_empty());
12380 }
12381
12382 #[test]
12383 fn a_task_without_a_repository_runs_in_the_daemons_default() {
12384 let fallback = Path::new("/default");
12385 let mut blank = task();
12386 blank.repo = PathBuf::new();
12387 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
12388 let mut dot = task();
12389 dot.repo = PathBuf::from(".");
12390 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
12391 assert_eq!(
12392 repo_for(&task(), fallback),
12393 PathBuf::from("/repo"),
12394 "a task that names a repository keeps it"
12395 );
12396 }
12397
12398 #[test]
12399 fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
12400 let dir = tempfile::tempdir().unwrap();
12401 let repo = dir.path();
12402 let path = repo.join("explicit.toml");
12403 std::fs::write(
12404 &path,
12405 "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
12406 )
12407 .unwrap();
12408 let opts = Opts {
12409 config: Some(path),
12410 ..Opts::default()
12411 };
12412 let queue = Queue::at(repo.join("queue"));
12413 let mut new = task();
12414 queue.put(&mut new).unwrap();
12415 let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
12416 assert_eq!(
12417 resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
12418 BuildCache::Isolated
12419 );
12420
12421 let mut old = task();
12422 old.schema = 22;
12423 queue.put(&mut old).unwrap();
12424 let mut old = queue.get(&old.id).unwrap();
12425 let config = resolved(&old);
12426 assert_eq!(config.verify.build_cache, BuildCache::Shared);
12427 assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
12428 old.hold_manual(Some("wait".into()));
12429 queue.put(&mut old).unwrap();
12430
12431 let mut saved = queue.get(&old.id).unwrap();
12432 assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
12433 saved
12434 .overrides
12435 .as_mut()
12436 .unwrap()
12437 .merge_over(&crate::queue::RunOverrides {
12438 build_cache: Some(BuildCache::Isolated),
12439 ..Default::default()
12440 });
12441 queue.put(&mut saved).unwrap();
12442 assert_eq!(
12443 resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
12444 BuildCache::Isolated
12445 );
12446 }
12447
12448 #[test]
12449 fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
12450 let dir = tempfile::tempdir().unwrap();
12451 let path = dir.path().join("explicit.toml");
12452 let write = |verify: &str| {
12453 std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
12454 };
12455 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
12456 let opts = Opts {
12457 config: Some(path.clone()),
12458 ..Opts::default()
12459 };
12460 let mut task = task();
12461 task.set_urgent(true).unwrap();
12462 let resolved = |task: &Task| {
12463 prepare_for(dir.path(), &opts, task)
12464 .unwrap()
12465 .verify
12466 .build_cache
12467 };
12468 assert_eq!(resolved(&task), BuildCache::Isolated);
12469 task.change_build_cache(Some(BuildCache::Shared)).unwrap();
12470 assert_eq!(resolved(&task), BuildCache::Shared);
12471 task.change_build_cache(None).unwrap();
12472 assert_eq!(resolved(&task), BuildCache::Isolated);
12473 task.set_urgent(false).unwrap();
12474 assert_eq!(resolved(&task), BuildCache::Shared);
12475
12476 task.set_urgent(true).unwrap();
12480 write("e2e = [\"npm test\"]\n");
12481 assert_eq!(resolved(&task), BuildCache::Shared);
12482 write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
12483 assert_eq!(resolved(&task), BuildCache::Shared);
12484 task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
12486 assert_eq!(resolved(&task), BuildCache::Isolated);
12487 }
12488
12489 #[test]
12490 fn task_implementers_edit_inherits_daemon_config_and_merge() {
12491 let dir = tempfile::tempdir().unwrap();
12492 let path = dir.path().join("explicit.toml");
12493 std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
12494 let opts = Opts {
12495 config: Some(path),
12496 merge: Some("none".into()),
12497 ..Default::default()
12498 };
12499 let mut t = task();
12500 t.set_implementers(
12501 2,
12502 &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12503 .unwrap(),
12504 )
12505 .unwrap();
12506 let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12507 assert_eq!(cfg.graph.implementers, 2);
12508 assert_eq!(cfg.graph.judges, 1);
12509 assert_eq!(cfg.merge.mode, MergeMode::None);
12510 t.set_implementers(1, &cfg).unwrap();
12511 let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12512 apply_task_implementers(&mut cfg, &t);
12513 assert_eq!(cfg.graph.implementers, 1);
12514 assert_eq!(cfg.graph.judges, 1);
12515 assert_eq!(cfg.merge.mode, MergeMode::None);
12516 }
12517
12518 #[test]
12519 fn task_implementers_direct_overrides_stay_isolated_after_edits() {
12520 let dir = tempfile::tempdir().unwrap();
12521 let repo = dir.path().join("repo");
12522 std::fs::create_dir(&repo).unwrap();
12523 std::fs::write(
12524 repo.join("magi.toml"),
12525 "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
12526 )
12527 .unwrap();
12528 let daemon_config = dir.path().join("daemon.toml");
12529 std::fs::write(
12530 &daemon_config,
12531 "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
12532 )
12533 .unwrap();
12534 let opts = Opts {
12535 config: Some(daemon_config),
12536 merge: Some("pr".into()),
12537 ..Default::default()
12538 };
12539 let q = Queue::at(dir.path().join("queue"));
12540 let validation: Config =
12541 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12542 .unwrap();
12543 for record in ["{}", r#"{"candidates":2}"#] {
12545 let overrides = serde_json::from_str(record).unwrap();
12546 let filing = crate::direct::Filing {
12547 instruction: "work".into(),
12548 title: "direct".into(),
12549 repo: repo.clone(),
12550 source: crate::queue::Source::Human,
12551 solo: false,
12552 overrides,
12553 review_of: None,
12554 sources: Default::default(),
12555 };
12556 let filed =
12557 crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
12558 let crate::direct::Filed::Standalone {
12559 mut task,
12560 claim: _claim,
12561 } = filed
12562 else {
12563 panic!("local filing")
12564 };
12565 let before = prepare_for(&repo, &opts, &task).unwrap();
12566 assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
12567 assert_eq!(
12568 before.merge.mode,
12569 MergeMode::None,
12570 "daemon --merge must not leak"
12571 );
12572 for n in [2, 1, 2] {
12573 task.set_implementers(n, &validation).unwrap();
12574 q.put(&mut task).unwrap();
12575 task = q.get(&task.id).unwrap();
12576 assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
12577 let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
12578 apply_task_implementers(&mut cfg, &task);
12579 assert_eq!(cfg.graph.implementers, usize::from(n));
12580 assert_eq!(cfg.graph.judges, 2);
12581 assert_eq!(cfg.merge.mode, MergeMode::None);
12582 }
12583 }
12584 }
12585
12586 #[test]
12587 fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
12588 let cfg: Config =
12589 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12590 .unwrap();
12591 let mut t = task();
12592 t.review_of = Some("review-target".into());
12593 t.hold_manual(Some("retry".into()));
12594 let mut previous = RunState::new(
12595 PathBuf::from("/repo"),
12596 "main".into(),
12597 "abc1234".into(),
12598 "review".into(),
12599 cfg.clone(),
12600 );
12601 previous.config.graph.implementers = 2;
12602 for count in [1, 3] {
12603 t.set_implementers(count, &cfg).unwrap();
12604 t.release();
12605 assert_eq!(t.review_of.as_deref(), Some("review-target"));
12606 for proposed in [
12607 Starter::Resume(previous.id.clone()),
12608 Starter::Review("recovery-target".into()),
12609 ] {
12610 assert_eq!(
12611 starter_with_implementers(&t, Some(&previous), proposed),
12612 Starter::Review("review-target".into())
12613 );
12614 }
12615 let mut configured = cfg.clone();
12616 apply_task_implementers(&mut configured, &t);
12617 assert_eq!(configured.graph.implementers, usize::from(count));
12618 assert_eq!(previous.config.graph.implementers, 2);
12619 }
12620 }
12621
12622 #[test]
12623 fn task_implementers_dispatch_and_resume_agree() {
12624 let mut t = task();
12625 let cfg: crate::config::Config =
12626 toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12627 .unwrap();
12628 let mut run = RunState::new(
12629 PathBuf::from("/repo"),
12630 "main".into(),
12631 "abc1234".into(),
12632 "work".into(),
12633 cfg.clone(),
12634 );
12635 run.config.graph.implementers = 2;
12636 for n in [2, 1, 3, 2] {
12637 t.set_implementers(n, &cfg).unwrap();
12638 let mut dispatched = cfg.clone();
12639 apply_task_implementers(&mut dispatched, &t);
12640 assert_eq!(dispatched.graph.implementers, usize::from(n));
12641 assert_eq!(implementers_match(&t, &run), n == 2);
12642 for proposed in [
12643 Starter::Resume(run.id.clone()),
12644 Starter::Review("old-branch".into()),
12645 ] {
12646 let expected = if n == 2 {
12647 proposed.clone()
12648 } else {
12649 Starter::Start
12650 };
12651 assert_eq!(
12652 starter_with_implementers(&t, Some(&run), proposed),
12653 expected
12654 );
12655 }
12656 assert_eq!(
12657 run.config.graph.implementers, 2,
12658 "history must not be rewritten"
12659 );
12660 }
12661 t.solo = false;
12662 t.overrides = None;
12663 assert!(implementers_match(&t, &run));
12664 }
12665
12666 #[test]
12667 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
12668 let mut solo_cfg = Config::default();
12674 solo_cfg.graph.implementers = 3;
12675 let mut solo_task = task();
12676 solo_task.solo = true;
12677 apply_task_implementers(&mut solo_cfg, &solo_task);
12678 assert_eq!(solo_cfg.graph.implementers, 1);
12679
12680 let mut plain_cfg = Config::default();
12681 plain_cfg.graph.implementers = 3;
12682 let plain_task = task();
12683 assert!(!plain_task.solo);
12684 apply_task_implementers(&mut plain_cfg, &plain_task);
12685 assert_eq!(
12686 plain_cfg.graph.implementers, 3,
12687 "a task that did not ask to run alone keeps the config's candidates"
12688 );
12689 }
12690
12691 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
12692 QuotaLoss {
12693 cause: crate::agent::QuotaCause::UsageLimit,
12694 agent: String::new(),
12695 seat: seat.into(),
12696 node: "judge".into(),
12697 at: at.parse().unwrap(),
12698 reset: reset.map(str::to_string),
12699 }
12700 }
12701
12702 #[test]
12703 fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
12704 let now = Timestamp::now();
12705 for reset in [None, Some("in 1h")] {
12706 let auth = crate::agent::Quota {
12707 cause: crate::agent::QuotaCause::Authentication,
12708 agent: "alpha".into(),
12709 reset: reset.map(str::to_owned),
12710 };
12711 let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
12712 assert_eq!(cooldown_until(&[loss], now), None);
12713 }
12714 }
12715
12716 #[test]
12717 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
12718 let old: Vec<QuotaLoss> = (1..=4)
12719 .map(|i| {
12720 loss(
12721 &format!("judge-{i}"),
12722 "2026-09-23T05:23:00Z",
12723 Some("2:40pm (Asia/Tokyo)"),
12724 )
12725 })
12726 .collect();
12727 let fresh = losses_this_attempt(&old, &old);
12728 assert!(fresh.is_empty());
12729 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
12730 }
12732
12733 #[test]
12734 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
12735 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
12736 let now = Timestamp::now();
12737 let mut after = old.clone();
12738 after.push(loss("judge-2", &now.to_string(), None));
12739 let fresh = losses_this_attempt(&old, &after);
12740 assert_eq!(fresh, vec![after[1].clone()]);
12741 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
12742 assert_eq!(
12743 until,
12744 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
12745 );
12746 }
12747
12748 #[test]
12749 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
12750 let before = vec![
12753 loss("judge-1", "2026-09-23T05:23:00Z", None),
12754 loss("judge-2", "2026-09-23T05:24:00Z", None),
12755 ];
12756 let after = vec![
12757 loss("judge-2", "2026-09-23T05:24:00Z", None),
12758 loss("judge-1", "2026-09-24T01:00:00Z", None),
12759 ];
12760 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
12761 }
12762
12763 #[test]
12764 fn merge_overrides_are_parsed_or_refused() {
12765 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
12766 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
12767 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
12768 assert!(merge_mode("squash").is_err());
12769 }
12770
12771 #[test]
12772 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
12773 let now = Timestamp::now();
12774 let fallback = Duration::from_secs(300);
12775 let cap = Duration::from_secs(1800);
12776
12777 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
12779
12780 let soon = now + jiff::SignedDuration::from_secs(600);
12782 assert_eq!(
12783 quota_wait(Some(soon), now, fallback, cap),
12784 Duration::from_secs(600)
12785 );
12786
12787 let past = now - jiff::SignedDuration::from_secs(60);
12790 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
12791
12792 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
12795 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
12796 }
12797
12798 #[test]
12799 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
12800 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12801
12802 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
12803 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
12804
12805 let already_past =
12809 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
12810 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
12811
12812 assert!(
12813 parse_reset_hint("session limit reached", now, now).is_none(),
12814 "free text with no recognised shape is not guessed at"
12815 );
12816 assert!(
12817 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
12818 "an unresolvable zone name is not guessed at either"
12819 );
12820 }
12821
12822 #[test]
12823 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
12824 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12825
12826 let at = parse_reset_hint(
12827 "You've hit your usage limit. Visit \
12828 https://chatgpt.com/codex/settings/usage to purchase more \
12829 credits or try again at Sep 19th, 2026 5:10 PM.",
12830 now,
12831 now,
12832 )
12833 .expect("the codex reset wording is a recognised shape");
12834 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
12835
12836 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
12841 .expect("an explicit year needs no rollover");
12842 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
12843
12844 assert!(
12845 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
12846 "a two-digit year is not the documented shape and is not guessed at"
12847 );
12848 assert!(
12849 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
12850 "a four-letter month name is not the documented three-letter abbreviation"
12851 );
12852 assert!(
12853 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
12854 "an explicit zone on the dated shape is a format nobody has \
12855 documented, and is refused rather than guessed at as UTC"
12856 );
12857 }
12858
12859 #[test]
12860 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
12861 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
12862 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
12863
12864 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
12865 assert_eq!(at.as_second() - recorded.as_second(), 3769);
12866
12867 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
12868 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
12869
12870 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
12871 assert!(
12872 parse_reset_hint(bad, now, recorded).is_none(),
12873 "{bad:?} must not be guessed at"
12874 );
12875 }
12876 }
12877
12878 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
12882 let config = dir.join("magi.toml");
12883 std::fs::write(
12884 &config,
12885 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
12886 )
12887 .unwrap();
12888 let opts = Opts {
12889 poll: Duration::from_secs(30),
12890 config: Some(config),
12891 repo: dir.join("repo"),
12895 ..Opts::default()
12896 };
12897 let home = dir.join("home");
12906 let stamps = home.join("service-ticks");
12909 std::fs::create_dir_all(&stamps).unwrap();
12910 for service in ["waiter", "deputies", "release-watch"] {
12911 std::fs::write(
12912 stamps.join(service),
12913 Timestamp::now().as_second().to_string(),
12914 )
12915 .unwrap();
12916 }
12917 for operation in [
12918 "conductor",
12919 "maintenance",
12920 "housekeeping",
12921 "disk-pressure",
12922 "fold",
12923 "cache",
12924 "fetch",
12925 "chat-goals",
12926 ] {
12927 std::fs::write(
12928 stamps.join(format!("daemon-{operation}")),
12929 serde_json::to_vec(&Timestamp::now()).unwrap(),
12930 )
12931 .unwrap();
12932 }
12933 let worktrees = dir.join("wt");
12934 (
12935 opts,
12936 Queue::at(dir.join("queue")),
12937 home.join("daemon.json"),
12938 home,
12939 worktrees,
12940 )
12941 }
12942
12943 #[tokio::test]
12944 async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
12945 let dir = tempfile::tempdir().unwrap();
12946 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12947 let mut waiting = task();
12948 waiting.repo = opts.repo.clone();
12949 waiting.hold_machine(crate::disk::gate(1, 100));
12950 waiting.mark_disk_capacity();
12951 waiting.attempts = 2;
12952 queue.put(&mut waiting).unwrap();
12953 let mut busy = task();
12954 busy.status = TaskStatus::Running;
12955 queue.put(&mut busy).unwrap();
12956 let payload = serde_json::to_value(ServiceWorker {
12957 opts,
12958 queue: queue.root().to_owned(),
12959 worktrees_root: worktrees,
12960 operation: "maintenance".into(),
12961 })
12962 .unwrap();
12963 run_service_worker(&home, payload.clone()).await.unwrap();
12964 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
12965 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12966 assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
12967 run_service_worker(&home, payload).await.unwrap();
12968 assert!(
12969 crate::worker::active(&home).unwrap().is_empty(),
12970 "monitoring only queues; normal dispatch owns launches"
12971 );
12972 assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12973 }
12974
12975 #[tokio::test]
12976 async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
12977 let dir = tempfile::tempdir().unwrap();
12978 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12979 let cfg = Config::default();
12980 start_service(
12981 &home,
12982 &opts,
12983 &queue,
12984 &worktrees,
12985 "housekeeping",
12986 Some(&cfg),
12987 true,
12988 )
12989 .await
12990 .unwrap();
12991 let receipt = home.join("source-eviction-housekeeping-dispatch.json");
12992 let read = |path: &Path| -> serde_json::Value {
12993 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
12994 };
12995 assert_eq!(read(&receipt)["detail"], "cadence not due");
12996 std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
12997 start_service(
12998 &home,
12999 &opts,
13000 &queue,
13001 &worktrees,
13002 "housekeeping",
13003 Some(&cfg),
13004 true,
13005 )
13006 .await
13007 .unwrap();
13008 assert_eq!(
13009 read(&receipt)["detail"],
13010 "active work or runnable task queue"
13011 );
13012 assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
13013 assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
13014 std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
13015 start_service(
13016 &home,
13017 &opts,
13018 &queue,
13019 &worktrees,
13020 "disk-pressure",
13021 Some(&cfg),
13022 false,
13023 )
13024 .await
13025 .unwrap();
13026 assert_eq!(
13027 read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
13028 "no active work; idle housekeeping owns scan"
13029 );
13030 assert!(crate::worker::active(&home).unwrap().is_empty());
13031 }
13032
13033 #[test]
13038 fn the_fold_turn_is_admitted_exactly_where_housekeeping_is_not() {
13039 let on = Config::default();
13040 for busy in [false, true] {
13041 for runnable in [false, true] {
13042 assert_ne!(
13043 housekeeping_eligible(busy, runnable),
13044 fold_turn_eligible(busy, runnable, Some(&on)),
13045 "busy={busy} runnable={runnable}"
13046 );
13047 }
13048 }
13049 assert!(!housekeeping_eligible(true, true), "the 1275 machine");
13050 assert!(!fold_turn_eligible(true, true, None));
13051 let mut off = Config::default();
13052 off.disk.auto_fold = false;
13053 assert!(!fold_turn_eligible(true, true, Some(&off)));
13054 assert!(fold_turn_eligible(true, true, Some(&Config::default())));
13055 }
13056
13057 #[tokio::test]
13058 async fn the_fold_service_says_why_it_skipped_a_dispatch() {
13059 let dir = tempfile::tempdir().unwrap();
13060 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13061 let read = || -> serde_json::Value {
13062 serde_json::from_slice(
13063 &std::fs::read(home.join("source-eviction-fold-dispatch.json")).unwrap(),
13064 )
13065 .unwrap()
13066 };
13067 let tick = home.join("service-ticks/daemon-fold");
13068 let cfg = Config::default();
13069 let dispatch = |busy: bool, cfg: Config| {
13070 let (home, opts, queue, worktrees) = (&home, &opts, &queue, &worktrees);
13071 async move {
13072 start_service(home, opts, queue, worktrees, "fold", Some(&cfg), busy)
13073 .await
13074 .unwrap();
13075 }
13076 };
13077 dispatch(true, cfg.clone()).await;
13078 assert_eq!(read()["detail"], "cadence not due");
13079
13080 std::fs::remove_file(&tick).unwrap();
13081 dispatch(false, cfg.clone()).await;
13082 assert_eq!(
13083 read()["detail"],
13084 "idle machine; housekeeping owns finished-run folding"
13085 );
13086 let mut off = cfg.clone();
13087 off.disk.auto_fold = false;
13088 dispatch(true, off).await;
13089 assert_eq!(read()["detail"], "auto_fold disabled");
13090 start_service(&home, &opts, &queue, &worktrees, "fold", None, true)
13092 .await
13093 .unwrap();
13094 assert_eq!(read()["detail"], "startup configuration unavailable");
13095
13096 let directory = home.join("workers/jobs/abcdef");
13098 std::fs::create_dir_all(&directory).unwrap();
13099 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13100 crate::pr_head::try_lock_file(&lease).unwrap();
13101 let mut job = crate::worker::Job {
13102 id: "abcdef".into(),
13103 sequence: 1,
13104 kind: "daemon-service".into(),
13105 key: "service:daemon-housekeeping".into(),
13106 payload: serde_json::Value::Null,
13107 generation: "fixture".into(),
13108 version: None,
13109 status: crate::worker::Status::Running,
13110 result: None,
13111 pid: Some(std::process::id()),
13112 created_at: Timestamp::now().as_second() as u64,
13113 finished_at: None,
13114 };
13115 let record = directory.join("job.json");
13116 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13117 dispatch(true, cfg).await;
13118 assert_eq!(
13119 read()["detail"],
13120 "another finished-run folding service is active"
13121 );
13122 assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
13123 job.status = crate::worker::Status::Finished;
13124 std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13125 drop(lease);
13126 }
13127
13128 #[tokio::test]
13136 async fn the_scheduler_folds_a_merged_run_beside_a_busy_worker_and_a_runnable_task() {
13137 let dir = tempfile::tempdir().unwrap();
13138 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13139 let repo = dir.path().join("checkout");
13140 std::fs::create_dir_all(&repo).unwrap();
13141 crate::clean::tests::init_repo(&repo);
13142 std::fs::write(
13143 opts.config.as_ref().unwrap(),
13144 "[disk]\nmin_free_bytes = 0\nauto_fold = true\ncache_limit_bytes = 0\n",
13145 )
13146 .unwrap();
13147 let (id, historical) = crate::clean::tests::merged_run_with_worktree(
13148 &home,
13149 &repo,
13150 &worktrees,
13151 "20260801-000000-s001",
13152 )
13153 .await;
13154 let active = dir.path().join("active");
13155 crate::git::worktree_add_branch(&repo, &active, "magi/active", "main")
13156 .await
13157 .unwrap();
13158 let (owned_id, owned_worktree) = crate::clean::tests::due_run_with_winner_worktree(
13163 &home.join("runs"),
13164 &worktrees,
13165 &repo,
13166 "20260801-000000-s002",
13167 RunStatus::Superseded,
13168 )
13169 .await;
13170 let owned_run = home.join("runs").join(&owned_id);
13171 let owned_record = std::fs::read(owned_run.join("run.json")).unwrap();
13172 let mut busy = task();
13173 busy.repo = repo.clone();
13174 busy.status = TaskStatus::Running;
13175 busy.link_run(&owned_id);
13176 queue.put(&mut busy).unwrap();
13177 let worker_lease = crate::worker::running_fixture(
13178 &home,
13179 &format!("task:{}", busy.id),
13180 serde_json::to_value(TaskWorker {
13181 opts: Opts::default(),
13182 queue: queue.root().to_owned(),
13183 task: busy.id.clone(),
13184 lane: PermitKind::default(),
13185 standalone: true,
13186 })
13187 .unwrap(),
13188 )
13189 .unwrap();
13190 let execution = crate::driver::maintenance(&home, &owned_id).unwrap();
13191 let mut waiting = task();
13192 waiting.repo = repo.clone();
13193 queue.put(&mut waiting).unwrap();
13194 std::fs::remove_file(home.join("service-ticks/daemon-fold")).unwrap();
13195
13196 let mut cfg = Config::default();
13197 cfg.disk.auto_fold = true;
13198 INLINE_SERVICES.with(|inline| inline.set(true));
13199 let status = Arc::new(Mutex::new(Status::new()));
13200 let stop = Stop::new();
13201 let mut dispatch = Box::pin(poll(
13202 &opts,
13203 &queue,
13204 &status,
13205 &home,
13206 &worktrees,
13207 &stop,
13208 DispatchLimits {
13209 max_concurrent: 0,
13210 pause_for_interrupts: false,
13211 recovery_cfg: Some(cfg),
13212 },
13213 ));
13214 let receipt = home.join("source-eviction-fold-worker.json");
13215 let completed = async {
13216 loop {
13217 let done = std::fs::read(&receipt)
13218 .ok()
13219 .and_then(|body| serde_json::from_slice::<serde_json::Value>(&body).ok())
13220 .is_some_and(|receipt| receipt["outcome"] == "completed");
13221 if done {
13222 break;
13223 }
13224 tokio::time::sleep(Duration::from_millis(25)).await;
13225 }
13226 };
13227 tokio::select! {
13228 result = &mut dispatch => panic!("the scheduler stopped before the fold service ran: {result:?}"),
13229 result = tokio::time::timeout(Duration::from_secs(120), completed) => {
13230 result.expect("the scheduler never admitted the fold service");
13231 }
13232 }
13233 stop.stop();
13234 dispatch.await.unwrap();
13235 INLINE_SERVICES.with(|inline| inline.set(false));
13236
13237 assert!(!historical.exists(), "the merged run's worktree is folded");
13238 assert!(
13239 active.join("README.md").is_file(),
13240 "the repository's active checkout is untouched"
13241 );
13242 let run = home.join("runs").join(&id);
13243 assert!(run.join("run.json").is_file());
13244 assert!(run.join("artifacts/fold-evidence/manifest.json").is_file());
13245 let read = |name: &str| -> serde_json::Value {
13246 serde_json::from_slice(&std::fs::read(home.join(name)).unwrap()).unwrap()
13247 };
13248 assert_eq!(
13249 read("source-eviction-fold-dispatch.json")["detail"],
13250 "eligible and cadence due"
13251 );
13252 let worker = read("source-eviction-fold-worker.json");
13253 assert_eq!(worker["fold"]["records"], 2);
13254 assert_eq!(worker["fold"]["folded"], 1);
13255 assert_eq!(worker["fold"]["invoked"], 1);
13256 assert_eq!(
13257 worker["fold"]["live"], 1,
13258 "the busy worker's own run is left alone: {worker}"
13259 );
13260 assert!(owned_worktree.exists());
13263 assert_eq!(
13264 std::fs::read(owned_run.join("run.json")).unwrap(),
13265 owned_record
13266 );
13267 assert!(
13268 !RunState::load_under(&owned_id, &home).unwrap().candidates[0].folded,
13269 "the owned run's candidate is not folded"
13270 );
13271 assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
13272 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
13273 drop(execution);
13274 drop(worker_lease);
13275 }
13276
13277 #[tokio::test]
13282 async fn the_disk_pressure_service_reports_a_platform_without_containment() {
13283 let dir = tempfile::tempdir().unwrap();
13284 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13285 let payload = serde_json::to_value(ServiceWorker {
13286 opts,
13287 queue: queue.root().to_owned(),
13288 worktrees_root: worktrees,
13289 operation: "disk-pressure".into(),
13290 })
13291 .unwrap();
13292 let _platform = crate::retention::WithoutContainment::new();
13293 run_service_worker(&home, payload).await.unwrap();
13294
13295 let refusal = "Automatic output reclamation requires Unix process containment";
13296 let report: serde_json::Value =
13297 serde_json::from_slice(&std::fs::read(home.join("retention.json")).unwrap()).unwrap();
13298 assert_eq!(report["failures"], serde_json::json!([refusal]));
13299 let receipt: serde_json::Value = serde_json::from_slice(
13300 &std::fs::read(home.join("source-eviction-disk-pressure-worker.json")).unwrap(),
13301 )
13302 .unwrap();
13303 assert_eq!(receipt["outcome"], "retention swept");
13304 assert_eq!(receipt["retention"]["failure_count"], 1);
13305 assert_eq!(
13306 receipt["retention"]["failures"],
13307 serde_json::json!([refusal])
13308 );
13309 }
13310
13311 #[tokio::test]
13312 async fn goal_observation_service_does_not_block_scheduler_decisions() {
13313 let dir = tempfile::tempdir().unwrap();
13314 let (opts, _, _, home, worktrees) = idle_loop(dir.path());
13315 let queue = Queue::at(home.join("queue"));
13316 let mut task = task();
13317 task.repo = opts.repo.clone();
13318 task.chat = Some("decision-chat".into());
13319 task.hold_machine(Some("waiting for a decision".into()));
13320 queue.put(&mut task).unwrap();
13321 let questions = Questions::at(home.join("questions"));
13322 let mut question = action_question(&task.id, ask::ChoiceAction::Done);
13323 question.node = crate::conduct::NODE.into();
13324 question.status = ask::QuestionStatus::Open;
13325 question.answer = None;
13326 question.answered_at = None;
13327 questions.put(&mut question).unwrap();
13328 questions
13329 .update(&question.id, |q| {
13330 q.answer(ask::Answer::Choice("resume で続行する".into()))
13331 })
13332 .unwrap();
13333
13334 let talks = crate::talk::Talks::at(home.join("talks"));
13335 let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
13336 decision_chat.pending = "Keep this unsent status question".into();
13337 talks.put(&mut decision_chat).unwrap();
13338 let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
13339 talk.goals.push(serde_json::from_value(serde_json::json!({
13340 "id":"goal","purpose":"follow the retained job","scope":"one task",
13341 "condition":{"description":"land the result","kind":"runs_merged"},
13342 "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
13343 "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
13344 "started":1,"wakes":1,"last_checked":null,"fingerprint":""
13345 })).unwrap());
13346 talks.put(&mut talk).unwrap();
13347
13348 let directory = home.join("workers/jobs/abcdef");
13351 std::fs::create_dir_all(&directory).unwrap();
13352 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13353 crate::pr_head::try_lock_file(&lease).unwrap();
13354 let mut job = crate::worker::Job {
13355 id: "abcdef".into(),
13356 sequence: 1,
13357 kind: "daemon-service".into(),
13358 key: "service:daemon-chat-goals".into(),
13359 payload: serde_json::Value::Null,
13360 generation: "fixture".into(),
13361 version: None,
13362 status: crate::worker::Status::Running,
13363 result: None,
13364 pid: Some(std::process::id()),
13365 created_at: Timestamp::now().as_second() as u64,
13366 finished_at: None,
13367 };
13368 let record = directory.join("job.json");
13369 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13370 let status = Arc::new(Mutex::new(Status::new()));
13371 let stop = Stop::new();
13372 let mut dispatch = Box::pin(poll(
13373 &opts,
13374 &queue,
13375 &status,
13376 &home,
13377 &worktrees,
13378 &stop,
13379 DispatchLimits {
13380 max_concurrent: 1,
13381 pause_for_interrupts: false,
13382 recovery_cfg: None,
13383 },
13384 ));
13385 std::future::poll_fn(|cx| {
13386 assert!(dispatch.as_mut().poll(cx).is_pending());
13387 std::task::Poll::Ready(())
13388 })
13389 .await;
13390 assert!(lock(&status).polls > 0);
13391 let saved = queue.get(&task.id).unwrap();
13392 assert_eq!(saved.status, TaskStatus::Done);
13393 assert!(saved.action_applied(&question.id));
13394 assert!(
13395 talks
13396 .get("decision-chat")
13397 .unwrap()
13398 .pending
13399 .contains("Keep this unsent status question")
13400 );
13401 let goal = talks.get(&talk.id).unwrap().goals.remove(0);
13402 assert_eq!(goal.state, crate::chat_goal::State::Runnable);
13403 assert_eq!(
13404 goal.started,
13405 Some(1),
13406 "only the observation worker may reconcile its goal"
13407 );
13408 assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
13409
13410 stop.stop();
13411 dispatch.await.unwrap();
13412 job.status = crate::worker::Status::Finished;
13413 std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13414 drop(lease);
13415 }
13416
13417 #[test]
13418 fn a_stop_is_idempotent_and_once_set_stays_set() {
13419 let stop = Stop::new();
13420 assert!(!stop.stopped());
13421
13422 stop.stop();
13423 assert!(stop.stopped());
13424 stop.stop();
13425 assert!(stop.stopped(), "a second stop is not a toggle");
13426
13427 let shared = stop.clone();
13428 assert!(
13429 shared.stopped(),
13430 "a clone is the same stop; that is how the loop and its caller share one"
13431 );
13432 }
13433
13434 #[tokio::test]
13435 async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
13436 for operation in ["conductor", "maintenance", "housekeeping"] {
13437 let dir = tempfile::tempdir().unwrap();
13438 let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
13439 opts.once = true;
13440 opts.poll = Duration::from_millis(1);
13441 let mut state = run_state(RunStatus::Ready);
13444 state.reserve_under(&home).unwrap();
13445 state.save_under(&home).unwrap();
13446 let mut task = task();
13447 task.runs.push(state.id.clone());
13448 queue.put(&mut task).unwrap();
13449 let claim = queue.claim(&task.id).unwrap();
13450
13451 let directory = home.join("workers/jobs/abcdef");
13454 std::fs::create_dir_all(&directory).unwrap();
13455 let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13456 crate::pr_head::try_lock_file(&lease).unwrap();
13457 let mut job = crate::worker::Job {
13458 id: "abcdef".into(),
13459 sequence: 1,
13460 kind: "daemon-service".into(),
13461 key: format!("service:daemon-{operation}"),
13462 payload: serde_json::Value::Null,
13463 generation: "fixture".into(),
13464 version: None,
13465 status: crate::worker::Status::Running,
13466 result: None,
13467 pid: Some(std::process::id()),
13468 created_at: Timestamp::now().as_second() as u64,
13469 finished_at: None,
13470 };
13471 let record = directory.join("job.json");
13472 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13473
13474 let status = Arc::new(Mutex::new(Status::new()));
13475 let stop = Stop::new();
13476 let mut drain = Box::pin(poll(
13477 &opts,
13478 &queue,
13479 &status,
13480 &home,
13481 &worktrees,
13482 &stop,
13483 DispatchLimits {
13484 max_concurrent: 1,
13485 pause_for_interrupts: false,
13486 recovery_cfg: None,
13487 },
13488 ));
13489 std::future::poll_fn(|cx| {
13490 use std::future::Future;
13491 assert!(
13492 drain.as_mut().poll(cx).is_pending(),
13493 "--once must wait for {operation} to release its queue claim"
13494 );
13495 std::task::Poll::Ready(())
13496 })
13497 .await;
13498 assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
13499
13500 let questions = Questions::at(home.join("questions"));
13503 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13504 questions.put(&mut q).unwrap();
13505 drop(claim);
13506 let expired =
13510 serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
13511 for service in [operation, "housekeeping"] {
13512 std::fs::write(
13513 home.join("service-ticks").join(format!("daemon-{service}")),
13514 &expired,
13515 )
13516 .unwrap();
13517 }
13518 job.status = crate::worker::Status::Finished;
13519 std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13520 drop(lease);
13521 tokio::time::timeout(Duration::from_secs(2), drain)
13522 .await
13523 .expect("the settled service must allow the drain to finish")
13524 .unwrap();
13525 let after = queue.get(&task.id).unwrap();
13526 assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
13527 assert!(after.action_applied(&q.id));
13528 for service in [operation, "housekeeping"] {
13529 assert_eq!(
13530 std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
13531 .unwrap(),
13532 expired,
13533 "the final once rescan must not restart {service}"
13534 );
13535 }
13536 }
13537 }
13538
13539 #[test]
13540 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
13541 let stop = Stop::new();
13542 stop.busy.store(1, Ordering::SeqCst);
13543 assert!(
13544 !stop.finishing(),
13545 "a busy loop nobody has asked to stop is just running"
13546 );
13547
13548 stop.stop();
13549 assert!(
13550 stop.finishing(),
13551 "a stop asked for mid-run has not landed until the run is settled"
13552 );
13553
13554 stop.busy.store(0, Ordering::SeqCst);
13555 assert!(
13556 !stop.finishing(),
13557 "once the run is settled the stop has landed and there is nothing to finish"
13558 );
13559 }
13560
13561 #[test]
13562 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
13563 let stop = Stop::new();
13564 stop.busy.store(2, Ordering::SeqCst);
13565 stop.stop();
13566 assert!(stop.finishing(), "two runs still in flight");
13567
13568 stop.busy.store(1, Ordering::SeqCst);
13569 assert!(
13570 stop.finishing(),
13571 "one run finished, but a sibling is still working"
13572 );
13573
13574 stop.busy.store(0, Ordering::SeqCst);
13575 assert!(
13576 !stop.finishing(),
13577 "the last run out is what actually lands the stop"
13578 );
13579 }
13580
13581 #[tokio::test]
13582 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
13583 let dir = tempfile::tempdir().unwrap();
13584 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13585 let stop = Stop::new();
13586 stop.stop();
13587
13588 let began = std::time::Instant::now();
13589 tokio::time::timeout(
13590 Duration::from_secs(2),
13591 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13592 )
13593 .await
13594 .expect("a stopped loop must return, not sit out its poll interval")
13595 .expect("the loop's own setup and teardown must not fail");
13596 assert!(
13597 began.elapsed() < opts.poll,
13598 "returned only after {:?}, which is a poll interval, not a stop",
13599 began.elapsed()
13600 );
13601 }
13602
13603 #[tokio::test]
13604 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
13605 let dir = tempfile::tempdir().unwrap();
13606 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13607 let stop = Stop::new();
13608
13609 let asker = {
13612 let stop = stop.clone();
13613 tokio::spawn(async move {
13614 tokio::time::sleep(Duration::from_millis(20)).await;
13615 stop.stop();
13616 })
13617 };
13618
13619 let began = std::time::Instant::now();
13620 tokio::time::timeout(
13621 Duration::from_secs(2),
13622 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13623 )
13624 .await
13625 .expect("a stop asked for while idle must wake the wait")
13626 .expect("the loop's own setup and teardown must not fail");
13627 asker.await.unwrap();
13628 assert!(
13629 began.elapsed() < opts.poll,
13630 "returned only after {:?}, so the stop waited on the sleep",
13631 began.elapsed()
13632 );
13633 }
13634
13635 #[tokio::test]
13636 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
13637 let dir = tempfile::tempdir().unwrap();
13638 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13639 let stop = Stop::new();
13640 stop.stop();
13641
13642 tokio::time::timeout(
13643 Duration::from_secs(2),
13644 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13645 )
13646 .await
13647 .expect("a stopped loop must return")
13648 .expect("the loop's own setup and teardown must not fail");
13649
13650 assert!(
13651 home.is_dir(),
13652 "the loop did publish a status file, so its removal is the teardown and not an absence"
13653 );
13654 assert!(
13655 !status_file.exists(),
13656 "a stopped loop clears its status file"
13657 );
13658 assert!(
13659 read_status(&home).is_none(),
13660 "a reader must see no daemon at all, not a heartbeat that merely stopped"
13661 );
13662 }
13663
13664 #[tokio::test]
13665 async fn housekeeping_worker_settles_questions_without_a_scheduler() {
13666 let dir = tempfile::tempdir().unwrap();
13667 let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13668
13669 let mut settled = RunState::new(
13670 dir.path().join("repo"),
13671 "main".to_owned(),
13672 "abc1234".to_owned(),
13673 "fixture".to_owned(),
13674 Config::default(),
13675 );
13676 settled.status = RunStatus::Ready;
13677 let run_dir = home.join("runs").join(&settled.id);
13678 std::fs::create_dir_all(&run_dir).unwrap();
13679 std::fs::write(
13680 run_dir.join("run.json"),
13681 serde_json::to_string_pretty(&settled).unwrap(),
13682 )
13683 .unwrap();
13684 let questions = Questions::at(home.join("questions"));
13685 let mut question = ask::Question::new(
13686 settled.id.clone(),
13687 "review".to_owned(),
13688 "reviewer-1".to_owned(),
13689 "Continue?".to_owned(),
13690 String::new(),
13691 Vec::new(),
13692 );
13693 questions.put(&mut question).unwrap();
13694
13695 run_service_worker(
13696 &home,
13697 serde_json::to_value(ServiceWorker {
13698 opts,
13699 queue: queue.root().to_path_buf(),
13700 worktrees_root: worktrees,
13701 operation: "housekeeping".to_owned(),
13702 })
13703 .unwrap(),
13704 )
13705 .await
13706 .unwrap();
13707
13708 assert_eq!(
13709 questions.get(&question.id).unwrap().status,
13710 ask::QuestionStatus::Abandoned,
13711 "the independent housekeeping worker settles ended-run questions"
13712 );
13713 }
13714
13715 #[test]
13716 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
13717 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13718
13719 assert!(
13720 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
13721 "never checked before: due at once"
13722 );
13723
13724 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
13725 assert!(
13726 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
13727 "well inside the interval: not due yet"
13728 );
13729
13730 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
13731 assert!(
13732 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
13733 "exactly at the edge: not yet due, same convention as `clean::due`"
13734 );
13735
13736 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13737 assert!(
13738 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
13739 "past the interval: due again"
13740 );
13741 }
13742
13743 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
13748 let config = dir.join("magi.toml");
13749 std::fs::write(
13755 &config,
13756 format!(
13757 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
13758 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
13759 cache_dir.display()
13760 ),
13761 )
13762 .unwrap();
13763 Opts {
13764 config: Some(config),
13765 repo: dir.join("repo"),
13766 ..Opts::default()
13767 }
13768 }
13769
13770 #[tokio::test]
13771 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
13772 let dir = tempfile::tempdir().unwrap();
13773 let home = dir.path().join("home");
13774 let cache_dir = dir.path().join("cache");
13775 std::fs::create_dir_all(&cache_dir).unwrap();
13776 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13777 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13778
13779 let running = Stop::new();
13782 let mut last_checked = None;
13783 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13784 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
13785 .await;
13786 assert_eq!(
13787 crate::disk::dir_size(&cache_dir),
13788 0,
13789 "over the cap on the first check ever: pruned at once, no idle queue required"
13790 );
13791 assert_eq!(last_checked, Some(t0));
13792
13793 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
13795 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
13796 maybe_prune_cache_between_runs(
13797 &opts.repo,
13798 &opts,
13799 &home,
13800 &running,
13801 &mut last_checked,
13802 too_soon,
13803 )
13804 .await;
13805 assert_eq!(
13806 crate::disk::dir_size(&cache_dir),
13807 10,
13808 "too soon since the last check: left alone rather than rescanned every call"
13809 );
13810 assert_eq!(
13811 last_checked,
13812 Some(t0),
13813 "an idle check does not reset the clock"
13814 );
13815
13816 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13818 maybe_prune_cache_between_runs(
13819 &opts.repo,
13820 &opts,
13821 &home,
13822 &running,
13823 &mut last_checked,
13824 due_again,
13825 )
13826 .await;
13827 assert_eq!(
13828 crate::disk::dir_size(&cache_dir),
13829 0,
13830 "due again: pruned back under the cap"
13831 );
13832 }
13833
13834 #[tokio::test]
13842 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
13843 let dir = tempfile::tempdir().unwrap();
13844 let home = dir.path().join("home");
13845 let cache_dir = dir.path().join("cache");
13846 std::fs::create_dir_all(&cache_dir).unwrap();
13847 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13848 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13849
13850 let stop = Stop::new();
13851 stop.stop();
13852 assert!(
13853 !stop.finishing(),
13854 "no run is in flight at a between-runs boundary, so nothing else \
13855 would tell the operator this stop had not taken effect yet"
13856 );
13857
13858 let mut last_checked = None;
13859 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13860 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
13861 .await;
13862 assert_eq!(
13863 crate::disk::dir_size(&cache_dir),
13864 10,
13865 "over its cap, and due for the first check ever, but a stop outranks \
13866 it: the cap is a standing policy the next start measures again"
13867 );
13868 assert_eq!(
13869 last_checked, None,
13870 "a check that never happened must not claim the interval"
13871 );
13872 }
13873
13874 #[tokio::test]
13877 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
13878 let dir = tempfile::tempdir().unwrap();
13879 let cache_dir = dir.path().join("cache");
13880 std::fs::create_dir_all(&cache_dir).unwrap();
13881 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
13882
13883 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
13884 opts.poll = Duration::from_millis(20);
13885 opts.max_attempts = 1_000;
13886
13887 let queue = Queue::at(dir.path().join("queue"));
13888 for i in 0..128 {
13889 let mut task = Task::new(
13890 format!("queued work {i}"),
13891 format!("queued work {i}"),
13892 opts.repo.clone(),
13893 Source::Human,
13894 );
13895 queue.put(&mut task).unwrap();
13896 }
13897
13898 let home = dir.path().join("home");
13899 let worktrees = dir.path().join("wt");
13900 run_service_worker(
13901 &home,
13902 serde_json::to_value(ServiceWorker {
13903 opts,
13904 queue: queue.root().to_path_buf(),
13905 worktrees_root: worktrees,
13906 operation: "cache".to_owned(),
13907 })
13908 .unwrap(),
13909 )
13910 .await
13911 .unwrap();
13912 let after = queue.list();
13913 assert_eq!(after.len(), 128);
13914 assert!(
13915 after
13916 .iter()
13917 .all(|task| task.status.runnable() && task.attempts == 0)
13918 );
13919
13920 assert_eq!(
13921 crate::disk::dir_size(&cache_dir),
13922 0,
13923 "an oversized cache must not be left to grow unboundedly just because the \
13924 queue kept the loop busy the whole time"
13925 );
13926 }
13927
13928 #[test]
13929 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
13930 let dir = tempfile::tempdir().unwrap();
13931 let queue = Queue::at(dir.path().join("queue"));
13932 let questions = Questions::at(dir.path().join("questions"));
13933 let mut task = task();
13934 queue.put(&mut task).unwrap();
13935
13936 let mut task_question = ask::Question::new(
13937 task.id.clone(),
13938 crate::conduct::NODE.to_owned(),
13939 "conduct".to_owned(),
13940 "Which backend?".to_owned(),
13941 String::new(),
13942 Vec::new(),
13943 );
13944 questions.put(&mut task_question).unwrap();
13945 task.block(vec![task_question.id.clone()], None);
13946 queue.put(&mut task).unwrap();
13947
13948 let mut run_question = ask::Question::new(
13949 "20260101-000000-run1".to_owned(),
13950 "review".to_owned(),
13951 "reviewer-1".to_owned(),
13952 "Run question".to_owned(),
13953 String::new(),
13954 Vec::new(),
13955 );
13956 questions.put(&mut run_question).unwrap();
13957
13958 let mut coincidental = ask::Question::new(
13963 task.id.clone(),
13964 "review".to_owned(),
13965 "reviewer-1".to_owned(),
13966 "Unrelated review question".to_owned(),
13967 String::new(),
13968 Vec::new(),
13969 );
13970 questions.put(&mut coincidental).unwrap();
13971
13972 reconcile_task_questions(&queue, &questions);
13973 assert!(questions.get(&task_question.id).unwrap().status.open());
13974 assert!(questions.get(&run_question.id).unwrap().status.open());
13975 assert!(questions.get(&coincidental.id).unwrap().status.open());
13976
13977 task.release();
13978 queue.put(&mut task).unwrap();
13979 reconcile_task_questions(&queue, &questions);
13980 assert_eq!(
13981 questions.get(&task_question.id).unwrap().status,
13982 ask::QuestionStatus::Abandoned
13983 );
13984 assert!(
13985 questions.get(&run_question.id).unwrap().status.open(),
13986 "run questions remain the run janitor's responsibility"
13987 );
13988 assert!(
13989 questions.get(&coincidental.id).unwrap().status.open(),
13990 "a non-conductor question must not be abandoned just because its \
13991 run id coincides with a task id"
13992 );
13993 }
13994
13995 #[test]
13996 fn a_freshly_started_running_task_is_never_stalled() {
13997 let dir = tempfile::tempdir().unwrap();
13998 let mut t = task();
13999 t.start("run-1".to_owned());
14000 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
14003 }
14004
14005 #[test]
14006 fn a_long_running_task_with_no_live_daemon_is_stalled() {
14007 let dir = tempfile::tempdir().unwrap();
14008 let mut t = task();
14009 t.start("run-1".to_owned());
14010 t.updated_at = Timestamp::now()
14011 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14012 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
14013 assert_eq!(
14014 stalled_tasks(
14015 &Queue::at(dir.path().join("q")),
14016 dir.path(),
14017 Timestamp::now()
14018 )
14019 .len(),
14020 0,
14021 "the task was never written to this queue"
14022 );
14023 }
14024
14025 #[test]
14026 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
14027 let dir = tempfile::tempdir().unwrap();
14028 let mut t = task();
14029 t.id = "20260903-080340-0167".to_owned();
14030 t.start("20260903-080619-01c2".to_owned());
14031 t.updated_at = Timestamp::now()
14032 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14033
14034 let mut status = Status::new();
14035 status.current = vec![Current {
14036 worker: None,
14037 task: t.id.clone(),
14038 run: "20260903-080619-01c2".to_owned(),
14039 }];
14040 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
14041
14042 assert!(
14043 !is_stalled(&t, dir.path(), Timestamp::now()),
14044 "a live daemon's own heartbeat rules out stalled, however long the task has run"
14045 );
14046 }
14047
14048 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
14052 let path = queue.path_of(id);
14053 let body = std::fs::read_to_string(&path).unwrap();
14054 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
14055 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
14056 v["updated_at"] = serde_json::Value::String(old.to_string());
14057 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
14058 }
14059
14060 #[test]
14061 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
14062 let dir = tempfile::tempdir().unwrap();
14075 let queue = Queue::at(dir.path().join("queue"));
14076 let home = dir.path().join("home");
14077
14078 let mut t = task();
14079 t.id = "20260101-000001-lock".to_owned();
14080 t.start("run-1".to_owned());
14081 queue.put(&mut t).unwrap();
14082 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14083 std::fs::write(
14084 dir.path().join("queue").join(format!("{}.lock", t.id)),
14085 "not a pid",
14086 )
14087 .unwrap();
14088
14089 let now = Timestamp::now();
14090 assert!(
14091 reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
14092 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
14093 and reclaim must leave the task alone"
14094 );
14095 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14096
14097 let stalled = stalled_tasks(&queue, &home, now);
14098 assert_eq!(
14099 stalled.len(),
14100 1,
14101 "reclaim's inability to claim it yet must not hide it from the conductor"
14102 );
14103 assert_eq!(stalled[0].id, t.id);
14104 }
14105
14106 #[test]
14107 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
14108 let dir = tempfile::tempdir().unwrap();
14109 crate::run::set_home(dir.path().join("run-home"));
14110 let queue = Queue::at(dir.path().join("queue"));
14111 let home = dir.path().join("home");
14112 let questions = Questions::at(dir.path().join("questions"));
14113
14114 let mut t = task();
14115 t.id = "20260101-000003-dead".to_owned();
14116 t.start("missing-run".to_owned());
14117 queue.put(&mut t).unwrap();
14118 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14119
14120 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14123 assert_eq!(
14124 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
14125 [&t.id]
14126 );
14127 assert_eq!(
14128 reclaim_orphaned_running(&queue, 2, &Default::default()),
14129 [t.id.clone()]
14130 );
14131 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14132
14133 crate::conduct::apply(
14136 &queue,
14137 &questions,
14138 &crate::conduct::Verdict {
14139 decisions: vec![crate::conduct::Decision {
14140 id: t.id.clone(),
14141 recovery: Some(crate::conduct::Recovery::Requeue),
14142 ..crate::conduct::Decision::default()
14143 }],
14144 },
14145 )
14146 .unwrap();
14147 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14148 }
14149
14150 #[test]
14151 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
14152 let dir = tempfile::tempdir().unwrap();
14153 let queue = Queue::at(dir.path().join("queue"));
14154 let home = dir.path().join("home");
14155
14156 let mut fresh = task();
14157 fresh.id = "20260101-000001-aaaa".to_owned();
14158 fresh.start("run-1".to_owned());
14159 queue.put(&mut fresh).unwrap();
14160
14161 let mut old = task();
14162 old.id = "20260101-000002-bbbb".to_owned();
14163 old.start("run-2".to_owned());
14164 queue.put(&mut old).unwrap();
14165 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
14166
14167 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14168 assert_eq!(stalled.len(), 1);
14169 assert_eq!(stalled[0].id, old.id);
14170 }
14171
14172 #[test]
14173 fn queued_and_finished_task_views_partition_by_status() {
14174 let dir = tempfile::tempdir().unwrap();
14175 let queue = Queue::at(dir.path().join("queue"));
14176
14177 let mut queued = task();
14178 queued.id = "20260101-000001-aaaa".to_owned();
14179 queue.put(&mut queued).unwrap();
14180
14181 let mut failed = task();
14182 failed.id = "20260101-000002-bbbb".to_owned();
14183 failed.start("run-1".to_owned());
14184 failed.fail("gate red", 5);
14185 queue.put(&mut failed).unwrap();
14186
14187 let mut held = task();
14188 held.id = "20260101-000003-cccc".to_owned();
14189 held.hold_machine(None);
14190 queue.put(&mut held).unwrap();
14191
14192 let mut running = task();
14193 running.id = "20260101-000004-dddd".to_owned();
14194 running.start("run-2".to_owned());
14195 queue.put(&mut running).unwrap();
14196
14197 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
14198 assert_eq!(queued_ids, [queued.id.clone()]);
14199
14200 let mut finished_ids: Vec<String> =
14201 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
14202 finished_ids.sort_unstable();
14203 let mut want = vec![failed.id.clone(), held.id.clone()];
14204 want.sort_unstable();
14205 assert_eq!(finished_ids, want);
14206 }
14207
14208 #[test]
14209 fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
14210 for short in [false, true] {
14211 let dir = tempfile::tempdir().unwrap();
14212 let queue = Queue::at(dir.path().join("queue"));
14213 let questions = ask::Questions::at(dir.path().join("questions"));
14214 let mut running = task();
14215 running.id = "20261013-192213-feb2".into();
14216 running.start("existing-run".into());
14217 queue.put(&mut running).unwrap();
14218 let mut middle = task();
14219 middle.id = "20261013-193611-ca5b".into();
14220 middle.block(
14221 vec![if short {
14222 "feb2".into()
14223 } else {
14224 running.id.clone()
14225 }],
14226 None,
14227 );
14228 queue.put(&mut middle).unwrap();
14229 let mut waiting = task();
14230 waiting.id = "20261013-202849-ee37".into();
14231 waiting.block(
14232 vec![if short {
14233 "ca5b".into()
14234 } else {
14235 middle.id.clone()
14236 }],
14237 Some("wait for implementation".into()),
14238 );
14239 queue.put(&mut waiting).unwrap();
14240 assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
14241 let inv = crate::blockers::Inventory::load(&queue, &questions);
14242 assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
14243 assert!(inv.stuck().is_empty());
14244 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14245 assert!(report.quarantined.is_empty());
14246 assert!(report.asked.is_empty());
14247 resolve_blockers(&queue, &questions);
14248 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14249 assert!(questions.list().is_empty());
14250 running.succeed(CompletionContext::new(
14253 CompletionActor::DaemonSettle,
14254 None,
14255 dir.path(),
14256 &running,
14257 ));
14258 queue.put(&mut running).unwrap();
14259 resolve_blockers(&queue, &questions);
14260 assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
14261 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14262 middle = queue.get(&middle.id).unwrap();
14263 middle.succeed(CompletionContext::new(
14264 CompletionActor::DaemonSettle,
14265 None,
14266 dir.path(),
14267 &middle,
14268 ));
14269 queue.put(&mut middle).unwrap();
14270 resolve_blockers(&queue, &questions);
14271 let after = queue.get(&waiting.id).unwrap();
14272 assert_eq!(after.status, TaskStatus::Queued);
14273 assert!(after.blocked_by.is_empty());
14274 assert_eq!(after.instruction, waiting.instruction);
14275 }
14276 }
14277
14278 #[test]
14279 fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
14280 for future_schema in [false, true] {
14281 let name = "20261013-193611-ca5b";
14282 let mut future = task();
14283 future.id = name.into();
14284 future.schema = crate::queue::SCHEMA + 1;
14285 let contents = if future_schema {
14286 serde_json::to_string(&future).unwrap()
14287 } else {
14288 "corrupt".into()
14289 };
14290 let dir = tempfile::tempdir().unwrap();
14291 let queue = Queue::at(dir.path().join("queue"));
14292 let questions = ask::Questions::at(dir.path().join("questions"));
14293 let mut waiting = task();
14294 waiting.id = "20261013-202849-ee37".into();
14295 waiting.block(vec!["ca5b".into()], None);
14296 queue.put(&mut waiting).unwrap();
14297 std::fs::write(queue.path_of(name), contents).unwrap();
14298 assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
14299 assert!(
14300 crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
14301 );
14302 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14303 assert!(report.asked.is_empty());
14304 resolve_blockers(&queue, &questions);
14305 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14306 assert!(questions.list().is_empty());
14307 }
14308 let dir = tempfile::tempdir().unwrap();
14309 let queue = Queue::at(dir.path().join("queue"));
14310 let questions = ask::Questions::at(dir.path().join("questions"));
14311 let mut waiting = task();
14312 waiting.id = "20261013-202849-ee37".into();
14313 waiting.block(vec!["ca5b".into()], None);
14314 queue.put(&mut waiting).unwrap();
14315 let mut done = task();
14316 done.id = "20261013-193611-ca5b".into();
14317 done.succeed(CompletionContext::new(
14318 CompletionActor::Cli,
14319 None,
14320 dir.path(),
14321 &done,
14322 ));
14323 queue.put(&mut done).unwrap();
14324 std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
14327 assert!(queue.get("ca5b").is_err());
14328 assert_eq!(
14329 crate::queue::dependency(&queue, &questions, "ca5b"),
14330 crate::queue::Dependency::Ambiguous
14331 );
14332 resolve_blockers(&queue, &questions);
14333 let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14334 assert!(report.asked.is_empty());
14335 assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14336 assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
14337 }
14338
14339 #[test]
14340 fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
14341 for held in [false, true] {
14342 for question in [false, true] {
14343 for reference in ["ca5b", "20261013-193611-ca5b"] {
14344 let dir = tempfile::tempdir().unwrap();
14345 let queue = Queue::at(dir.path().join("queue"));
14346 let questions = ask::Questions::at(dir.path().join("questions"));
14347 let mut prerequisite = task();
14348 prerequisite.id = "20261013-193611-ca5b".into();
14349 prerequisite.start("existing-run".into());
14350 queue.put(&mut prerequisite).unwrap();
14351 let mut waiting = task();
14352 waiting.id = "20261013-202849-ee37".into();
14353 if held {
14354 waiting.hold_machine(Some("waiting for separate consent".into()));
14355 }
14356 queue.put(&mut waiting).unwrap();
14357 let reason = "Deleting saved data requires separate owner consent";
14358 crate::conduct::apply(
14359 &queue,
14360 &questions,
14361 &crate::conduct::Verdict {
14362 decisions: vec![crate::conduct::Decision {
14363 id: waiting.id.clone(),
14364 blocked_by: vec![reference.into()],
14365 question: question.then(|| "May the saved data be deleted?".into()),
14366 recovery: (!question).then_some(crate::conduct::Recovery::Hold),
14367 reason: Some(reason.into()),
14368 ..crate::conduct::Decision::default()
14369 }],
14370 },
14371 )
14372 .unwrap();
14373 let before = queue.get(&waiting.id).unwrap();
14374 if question {
14375 assert_eq!(before.status, TaskStatus::Blocked);
14376 let q = questions.get(&before.blocked_by[0]).unwrap();
14377 assert_eq!(q.summary, "May the saved data be deleted?");
14378 assert!(q.status.open());
14379 } else {
14380 assert_eq!(before.status, TaskStatus::Held);
14381 let recorded_reason = before.hold_reason.as_deref().unwrap();
14382 assert!(recorded_reason.starts_with(reason));
14383 if held {
14384 assert!(recorded_reason.contains("waiting for separate consent"));
14385 }
14386 }
14387 prerequisite.succeed(CompletionContext::new(
14388 CompletionActor::DaemonSettle,
14389 None,
14390 dir.path(),
14391 &prerequisite,
14392 ));
14393 queue.put(&mut prerequisite).unwrap();
14394 resolve_blockers(&queue, &questions);
14395 let after = queue.get(&waiting.id).unwrap();
14396 assert_eq!(after.status, before.status);
14397 assert_eq!(after.blocked_by, before.blocked_by);
14398 assert_eq!(after.hold_reason, before.hold_reason);
14399 assert_eq!(after.instruction, waiting.instruction);
14400 if question {
14401 assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
14402 }
14403 assert!(
14404 queue.next_runnable().is_none(),
14405 "dependency completion is not consent"
14406 );
14407 }
14408 }
14409 }
14410 }
14411
14412 #[test]
14413 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
14414 let dir = tempfile::tempdir().unwrap();
14415 let queue = Queue::at(dir.path().join("queue"));
14416 let questions = ask::Questions::at(dir.path().join("questions"));
14417
14418 let mut dep = task();
14419 dep.id = "20260101-000001-dep0".to_owned();
14420 dep.succeed(CompletionContext::new(
14421 CompletionActor::DaemonSettle,
14422 None,
14423 dir.path(),
14424 &dep,
14425 ));
14426 queue.put(&mut dep).unwrap();
14427
14428 let mut still_going = task();
14429 still_going.id = "20260101-000002-dep1".to_owned();
14430 queue.put(&mut still_going).unwrap();
14431
14432 let mut blocked = task();
14433 blocked.id = "20260101-000003-main".to_owned();
14434 blocked.block(
14435 vec![dep.id.clone(), still_going.id.clone()],
14436 Some("waits on both".to_owned()),
14437 );
14438 queue.put(&mut blocked).unwrap();
14439
14440 resolve_blockers(&queue, &questions);
14441
14442 let after = queue.get(&blocked.id).unwrap();
14443 assert_eq!(
14444 after.status,
14445 TaskStatus::Blocked,
14446 "one dependency is still outstanding"
14447 );
14448 assert_eq!(after.blocked_by, [still_going.id.clone()]);
14449 }
14450
14451 #[test]
14452 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
14453 let dir = tempfile::tempdir().unwrap();
14454 let queue = Queue::at(dir.path().join("queue"));
14455 let questions = ask::Questions::at(dir.path().join("questions"));
14456
14457 let mut q = crate::ask::Question::new(
14458 "20260101-000001-main".to_owned(),
14459 crate::conduct::NODE.to_owned(),
14460 "conduct".to_owned(),
14461 "Which backend?".to_owned(),
14462 String::new(),
14463 Vec::new(),
14464 );
14465 questions.put(&mut q).unwrap();
14466 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
14467 .unwrap();
14468 questions.put(&mut q).unwrap();
14469
14470 let mut blocked = task();
14471 blocked.id = "20260101-000001-main".to_owned();
14472 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
14473 queue.put(&mut blocked).unwrap();
14474
14475 resolve_blockers(&queue, &questions);
14476
14477 let after = queue.get(&blocked.id).unwrap();
14478 assert_eq!(
14479 after.status,
14480 TaskStatus::Queued,
14481 "the only blocker resolved"
14482 );
14483 assert_eq!(after.answers.len(), 1);
14484 assert_eq!(after.answers[0].question, "Which backend?");
14485 assert_eq!(after.answers[0].answer, "SQLite");
14486
14487 let instruction = instruction_for(&after);
14489 assert!(instruction.contains("Which backend?"));
14490 assert!(instruction.contains("SQLite"));
14491 }
14492
14493 #[test]
14494 fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
14495 let dir = tempfile::tempdir().unwrap();
14496 let queue = Queue::at(dir.path().join("queue"));
14497 let questions = ask::Questions::at(dir.path().join("questions"));
14498
14499 let mut q = crate::ask::Question::new(
14500 "20260101-000001-main".to_owned(),
14501 crate::conduct::NODE.to_owned(),
14502 "conduct".to_owned(),
14503 "Is the setup done?".to_owned(),
14504 String::new(),
14505 Vec::new(),
14506 );
14507 q.abandon("no answer within 60s of asking");
14508 questions.put(&mut q).unwrap();
14509
14510 let mut blocked = task();
14511 blocked.id = "20260101-000001-main".to_owned();
14512 blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
14513 queue.put(&mut blocked).unwrap();
14514
14515 resolve_blockers(&queue, &questions);
14516
14517 let after = queue.get(&blocked.id).unwrap();
14518 assert_eq!(
14519 after.status,
14520 TaskStatus::Held,
14521 "never left blocked on nothing"
14522 );
14523 assert!(!after.operator_held(), "a machine hold, for triage");
14524 assert!(
14525 after
14526 .hold_reason
14527 .as_deref()
14528 .unwrap_or_default()
14529 .contains("went unanswered")
14530 );
14531 }
14532
14533 #[test]
14534 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
14535 let dir = tempfile::tempdir().unwrap();
14541 let queue = Queue::at(dir.path().join("queue"));
14542 let questions = ask::Questions::at(dir.path().join("questions"));
14543
14544 let mut q = crate::ask::Question::new(
14545 "20260101-000001-main".to_owned(),
14546 crate::conduct::NODE.to_owned(),
14547 "conduct".to_owned(),
14548 "How should this be handled?".to_owned(),
14549 String::new(),
14550 Vec::new(),
14551 );
14552 questions.put(&mut q).unwrap();
14553 q.answer(crate::ask::Answer::Text(
14554 "leave it held, a human will look at it later".to_owned(),
14555 ))
14556 .unwrap();
14557 questions.put(&mut q).unwrap();
14558
14559 let mut held = task();
14560 held.id = "20260101-000001-main".to_owned();
14561 held.hold_machine(Some("out of attempts".to_owned()));
14562 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
14563 queue.put(&mut held).unwrap();
14564
14565 resolve_blockers(&queue, &questions);
14566
14567 let after = queue.get(&held.id).unwrap();
14568 assert_eq!(after.status, TaskStatus::Held);
14569 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
14570 assert_eq!(
14571 after.answers[0].answer,
14572 "leave it held, a human will look at it later"
14573 );
14574 }
14575
14576 #[test]
14577 fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
14578 let dir = tempfile::tempdir().unwrap();
14579 let queue = Queue::at(dir.path().join("queue"));
14580 let questions = ask::Questions::at(dir.path().join("questions"));
14581 let mut dep = task();
14582 dep.id = "20260101-000001-gone".to_owned();
14583 queue.put(&mut dep).unwrap();
14584 let mut blocked = task();
14585 blocked.id = "20260101-000003-main".to_owned();
14586 blocked.block(vec![dep.id.clone()], None);
14587 queue.put(&mut blocked).unwrap();
14588
14589 let claim = queue.claim(&blocked.id).unwrap();
14591 queue.remove(&dep.id, false, &questions).unwrap();
14592 drop(claim);
14593 resolve_blockers(&queue, &questions);
14594
14595 let after = queue.get(&blocked.id).unwrap();
14596 assert_eq!(after.status, TaskStatus::Queued);
14597 assert!(after.blocked_by.is_empty());
14598 }
14599
14600 #[test]
14601 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
14602 let dir = tempfile::tempdir().unwrap();
14608 let queue = Queue::at(dir.path().join("queue"));
14609 let questions = ask::Questions::at(dir.path().join("questions"));
14610
14611 let mut still_going = task();
14612 still_going.id = "20260101-000002-dep1".to_owned();
14613 queue.put(&mut still_going).unwrap();
14614
14615 let mut blocked = task();
14616 blocked.id = "20260101-000003-main".to_owned();
14617 blocked.block(
14618 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
14619 Some("waits on both".to_owned()),
14620 );
14621 queue.put(&mut blocked).unwrap();
14622
14623 resolve_blockers(&queue, &questions);
14624
14625 let after = queue.get(&blocked.id).unwrap();
14626 assert_eq!(
14627 after.status,
14628 TaskStatus::Held,
14629 "a missing dependency must not leave the task blocked forever"
14630 );
14631 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
14632 assert!(after.blocked_by.is_empty());
14633 let reason = after.hold_reason.as_deref().unwrap_or_default();
14634 assert!(
14635 reason.contains("20260101-000001-gone"),
14636 "the missing id must be named so an operator can tell what happened: {reason}"
14637 );
14638 assert!(
14639 reason.contains(&still_going.id),
14640 "the still-valid dependency must not silently vanish from the record: {reason}"
14641 );
14642 }
14643
14644 #[test]
14645 fn instruction_for_is_unchanged_without_any_answers() {
14646 let t = task();
14647 assert_eq!(instruction_for(&t), t.instruction);
14648 }
14649
14650 #[test]
14651 fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
14652 let dir = tempfile::tempdir().unwrap();
14653 let q = Queue::at(dir.path().join("queue"));
14654 let src = dir.path().join("shot.png");
14655 std::fs::write(&src, "x").unwrap();
14656 let mut t = task();
14657 q.attach(&mut t, &[src]).unwrap();
14658 let paths = task_attachments(&q, &t).unwrap();
14659 assert_eq!(paths.len(), 1);
14660 assert!(paths[0].is_absolute() && paths[0].is_file());
14661 std::fs::remove_file(&paths[0]).unwrap();
14662 let err = task_attachments(&q, &t).unwrap_err().to_string();
14663 assert!(err.contains("shot.png"), "{err}");
14664 }
14665
14666 #[tokio::test]
14667 async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
14668 let dir = tempfile::tempdir().unwrap();
14669 let queue_path = dir.path().join("queue");
14670 let queue = Queue::at(queue_path.clone());
14671 let mut t = task();
14672 t.source = Source::Agent {
14673 run: "originating-chat".into(),
14674 node: crate::queue::CHAT_NODE.into(),
14675 };
14676 let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
14677 stage: "config-fetch",
14678 target: "origin/main".into(),
14679 });
14680 record_config_failure(&mut t, &fetch);
14681 t.hold_machine(Some(format!("{fetch:#}")));
14682 let fetch_key = t.chat_notice_due().unwrap();
14683 t.chat_notices.push(fetch_key.clone());
14684 queue.put(&mut t).unwrap();
14685
14686 let queue = Queue::at(queue_path);
14687 let mut t = queue.get(&t.id).unwrap();
14688 let a = dir.path().join("a.toml");
14689 let b = dir.path().join("b.toml");
14690 for (path, text, new_cause) in [
14691 (&a, "[graph", true),
14692 (&a, "[verify", false),
14693 (&a, "[graph]\nimplementers = 'invalid-type'", true),
14694 (&b, "[graph]\nimplementers = 'invalid-type'", true),
14695 ] {
14696 t.release_operator("test", None);
14697 std::fs::write(path, text).unwrap();
14698 let error = Config::discover_fetched(dir.path(), Some(path))
14699 .await
14700 .unwrap_err();
14701 record_config_failure(&mut t, &error);
14702 t.hold_machine(Some(format!("{error:#}")));
14703 let due = t.chat_notice_due();
14704 assert_eq!(due.is_some(), new_cause, "{error:#}");
14705 if let Some(key) = due {
14706 assert_ne!(key, fetch_key);
14707 t.chat_notices.push(key);
14708 }
14709 }
14710 t.succeed(CompletionContext::new(
14711 CompletionActor::DaemonSettle,
14712 None,
14713 dir.path(),
14714 &t,
14715 ));
14716 assert_eq!(
14717 t.chat_notice_due(),
14718 Some(format!(
14719 "done:{}",
14720 t.completion_history.last().unwrap().occurrence
14721 ))
14722 );
14723 }
14724
14725 #[test]
14726 fn different_missing_attachments_have_distinct_persisted_notice_causes() {
14727 let dir = tempfile::tempdir().unwrap();
14728 let queue_path = dir.path().join("queue");
14729 let queue = Queue::at(queue_path.clone());
14730 let mut t = task();
14731 t.source = crate::queue::Source::Agent {
14732 run: "originating-chat".into(),
14733 node: crate::queue::CHAT_NODE.into(),
14734 };
14735 let a = dir.path().join("a.png");
14736 let b = dir.path().join("b.png");
14737 std::fs::write(&a, "a").unwrap();
14738 std::fs::write(&b, "b").unwrap();
14739 queue.attach(&mut t, &[a, b]).unwrap();
14740 let paths = task_attachments(&queue, &t).unwrap();
14741 for path in &paths {
14742 std::fs::remove_file(path).unwrap();
14743 }
14744 let missing = task_attachments(&queue, &t).unwrap_err();
14745 t.attempts += 1;
14746 let reason = missing.to_string();
14747 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14748 let first = t.chat_notice_due().expect("first attachment notice");
14749 t.chat_notices.push(first.clone());
14750 queue.put(&mut t).unwrap();
14751
14752 let queue = Queue::at(queue_path.clone());
14753 let mut t = queue.get(&t.id).unwrap();
14754 assert!(t.chat_notice_due().is_none(), "restart does not replay");
14755 t.release_operator("test", None);
14756 t.attempts += 1;
14757 let missing = task_attachments(&queue, &t).unwrap_err();
14758 t.fail_startup_target(
14759 "startup-attachments",
14760 missing.name,
14761 "same missing attachment with regenerated wording",
14762 1,
14763 );
14764 assert!(t.chat_notice_due().is_none(), "same object stays quiet");
14765
14766 std::fs::write(&paths[0], "restored").unwrap();
14767 t.release_operator("test", None);
14768 t.attempts += 1;
14769 let missing = task_attachments(&queue, &t).unwrap_err();
14770 let reason = missing.to_string();
14771 t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14772 let second = t
14773 .chat_notice_due()
14774 .expect("different attachment must notify");
14775 assert_ne!(first, second);
14776 assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
14777 }
14778
14779 #[test]
14780 fn resumed_instruction_is_unchanged_without_any_answers() {
14781 let t = task();
14782 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
14783 }
14784
14785 #[test]
14786 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
14787 let mut t = task();
14788 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14789 let old = t.instruction.clone();
14793
14794 let refreshed = resumed_instruction(&old, &t);
14795 assert!(refreshed.starts_with(&old), "the original text is kept");
14796 assert!(refreshed.contains("Which backend?"));
14797 assert!(refreshed.contains("SQLite"));
14798 }
14799
14800 #[test]
14801 fn resumed_instruction_keeps_an_original_answers_heading() {
14802 let mut t = task();
14803 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
14804 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14805
14806 let refreshed = resumed_instruction(&t.instruction, &t);
14807
14808 assert!(
14809 refreshed.starts_with(&t.instruction),
14810 "an answers heading in the original instruction is not the appended block"
14811 );
14812 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
14813 assert!(refreshed.contains("Which backend?"));
14814 assert!(refreshed.contains("SQLite"));
14815
14816 let repeated = resumed_instruction(&refreshed, &t);
14817 assert_eq!(
14818 repeated, refreshed,
14819 "only the final appended block is refreshed"
14820 );
14821 }
14822
14823 #[test]
14824 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
14825 let mut t = task();
14826 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14827
14828 let once = resumed_instruction(&t.instruction, &t);
14832 let twice = resumed_instruction(&once, &t);
14833 assert_eq!(once, twice);
14834 assert_eq!(once.matches("Which backend?").count(), 1);
14835
14836 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
14838 let refreshed = resumed_instruction(&once, &t);
14839 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
14840 assert!(refreshed.contains("Which backend?"));
14841 assert!(refreshed.contains("Which cache?"));
14842 }
14843
14844 #[test]
14845 fn prepare_instruction_covers_all_three_starters() {
14846 let mut t = task();
14847 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14848
14849 assert_eq!(
14852 prepare_instruction(&Starter::Start, None, &t),
14853 Some(instruction_for(&t))
14854 );
14855
14856 let old = t.instruction.clone();
14859 assert_eq!(
14860 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
14861 Some(resumed_instruction(&old, &t))
14862 );
14863
14864 assert_eq!(
14868 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
14869 None
14870 );
14871 }
14872
14873 #[test]
14874 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
14875 assert_eq!(
14876 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
14877 Starter::Review("magi/eba2/A".to_owned())
14878 );
14879 }
14880
14881 #[test]
14882 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
14883 assert_eq!(
14884 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
14885 Starter::Start,
14886 "a vanished review branch must not fall back to resuming the old run either"
14887 );
14888 }
14889
14890 #[test]
14891 fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
14892 let mut t = task();
14893 t.start("old-run".to_owned());
14894 t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
14895 t.release();
14896 let branch = t.review_branch.take();
14897 assert_eq!(
14898 choose_starter(branch.as_deref(), true, Some("old-run")),
14899 Starter::Review("magi/eba2/A".to_owned()),
14900 "a review wins over resuming the old run"
14901 );
14902 }
14903
14904 #[test]
14905 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
14906 assert_eq!(
14907 choose_starter(None, false, Some("some-run")),
14908 Starter::Resume("some-run".to_owned())
14909 );
14910 assert_eq!(choose_starter(None, false, None), Starter::Start);
14911 }
14912
14913 #[test]
14914 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
14915 let mut released = task();
14916 released.start("stalled-run".to_owned());
14917 released.requeue();
14918 let unfinished = (!released.fresh_start)
14919 .then(|| Some("stalled-run".to_owned()))
14920 .flatten();
14921 assert_eq!(
14922 choose_starter(None, false, unfinished.as_deref()),
14923 Starter::Start,
14924 "release keeps run history but must not resume it"
14925 );
14926 assert_eq!(released.runs, ["stalled-run"]);
14927 }
14928
14929 #[test]
14930 fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
14931 let dir = tempfile::tempdir().unwrap();
14932 let queue = Queue::at(dir.path().join("queue"));
14933 let mut state = run_state(RunStatus::Blocked);
14934 state.merge_decision = Some(crate::merge_decision::Decision {
14935 question: "hold-inquiry".into(),
14936 target: crate::merge_decision::Target {
14937 pr: "https://example.test/pull/1".into(),
14938 head: "reviewed-head".into(),
14939 language: "en".into(),
14940 },
14941 choice: land::HOLD.into(),
14942 closed: false,
14943 replacement_run: None,
14944 replacement_pr: None,
14945 });
14946 let mut t = task();
14947 t.start(state.id.clone());
14948 settle_and_diagnose(
14949 &mut t,
14950 Verdict {
14951 status: RunStatus::Blocked,
14952 left_pr: true,
14953 quota_hit: false,
14954 parked: false,
14955 no_viable_candidates: false,
14956 },
14957 "held",
14958 2,
14959 &state,
14960 );
14961 queue.put(&mut t).unwrap();
14962 t.release_operator("chat", None);
14963 t.edit("revised".into(), "revised instruction".into())
14964 .unwrap();
14965 queue.put(&mut t).unwrap();
14966 drop(state);
14967 assert_eq!(
14968 queue
14969 .get(&t.id)
14970 .unwrap()
14971 .decision_effects
14972 .get("hold-inquiry"),
14973 Some(&format!("decision: {}", land::HOLD))
14974 );
14975 }
14976
14977 fn stopped_public_run(status: RunStatus) -> RunState {
14978 let mut state = run_state(status);
14979 state.driver_exited = true;
14980 state.config.graph.land = true;
14981 state.config.graph.review_rounds = 1;
14982 state.reviews = vec![review_round(1)];
14983 state.merge = Some(crate::run::MergeOutcome {
14984 mode: MergeMode::Pr,
14985 ok: false,
14986 detail: "landing stopped".into(),
14987 empty: false,
14988 });
14989 state.pr = Some(crate::run::PrRecord {
14990 url: "https://example.test/pull/1".into(),
14991 number: 1,
14992 state: "open".into(),
14993 checks: "red".into(),
14994 round: 1,
14995 rounds: 1,
14996 red_at_merge: Vec::new(),
14997 });
14998 state
14999 }
15000
15001 #[test]
15002 fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
15003 for status in [RunStatus::Blocked, RunStatus::Gating] {
15004 let home = tempfile::tempdir().unwrap();
15005 let mut state = stopped_public_run(status);
15006 state.save_under(home.path()).unwrap();
15007 assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
15008 assert!(!exhausted_review_budget(&state));
15009 let mut task = held_task_with(&state.id);
15010 task.release();
15011 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15012 assert_eq!(
15013 choose_starter(None, false, unfinished.as_deref()),
15014 Starter::Resume(state.id.clone())
15015 );
15016 let question = action_question(&state.id, resume_action(&state.id));
15017 assert_eq!(
15018 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15019 state.clone()
15020 )),
15021 ActionDecision::Resume(state.id.clone())
15022 );
15023 assert_eq!(
15025 crate::resume::validate(home.path(), &state.id).unwrap().id,
15026 state.id
15027 );
15028 let queue = Queue::at(home.path().join("queue"));
15029 let mut controlled = Task::new(
15030 "resume land".into(),
15031 state.instruction.clone(),
15032 state.repo.clone(),
15033 Source::Agent {
15034 run: "talk".into(),
15035 node: crate::queue::CHAT_NODE.into(),
15036 },
15037 );
15038 controlled.runs.push(state.id.clone());
15039 controlled.hold_machine(Some("land stopped".into()));
15040 queue.put(&mut controlled).unwrap();
15041 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15042 assert_eq!(resumed.status, TaskStatus::Queued);
15043 assert_eq!(
15044 resumed.resume_override.unwrap().pinned_run,
15045 Some(state.id.clone())
15046 );
15047 assert_eq!(resumed.attempts, 0);
15048 }
15049 }
15050
15051 #[test]
15052 fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
15053 for review_rounds in [0, 1] {
15054 let home = tempfile::tempdir().unwrap();
15055 let mut state = run_state(RunStatus::Blocked);
15056 state.config.graph.review_rounds = review_rounds;
15057 if review_rounds > 0 {
15058 let mut review = review_round(1);
15059 review.clean = true;
15060 state.reviews = vec![review];
15061 }
15062 state.gate_ran = true;
15063 state.gate = vec![crate::run::CommandOutcome {
15064 command: "verify".into(),
15065 code: Some(1),
15066 output_tail: "gate failed after repair budget exhausted".into(),
15067 duration_ms: 0,
15068 resource_blocked: false,
15069 ..Default::default()
15070 }];
15071 state.save_under(home.path()).unwrap();
15072 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15073 assert!(exhausted_review_budget(&state));
15074 let mut task = held_task_with(&state.id);
15075 task.release();
15076 assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
15077 let question = action_question(&state.id, resume_action(&state.id));
15078 assert_ne!(
15079 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15080 state.clone()
15081 )),
15082 ActionDecision::Resume(state.id.clone())
15083 );
15084 let error = crate::resume::validate(home.path(), &state.id)
15085 .unwrap_err()
15086 .to_string();
15087 assert!(!error.contains("review budget exhausted"), "{error}");
15088 assert!(
15089 error.contains(if review_rounds == 0 {
15090 "review is disabled"
15091 } else {
15092 "gate already ran"
15093 }),
15094 "{error}"
15095 );
15096
15097 state.gate_ran = false;
15099 state.gate.clear();
15100 assert!(!exhausted_review_budget(&state));
15101 assert_eq!(
15102 unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
15103 Some(state.id)
15104 );
15105 }
15106 }
15107
15108 #[test]
15109 fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
15110 let home = tempfile::tempdir().unwrap();
15111 let mut state = run_state(RunStatus::Blocked);
15112 state.config.graph.review_rounds = 1;
15113 let mut unresolved = review_round(1);
15114 unresolved.blocking = 1;
15115 unresolved.e2e.push(crate::run::CommandOutcome {
15116 command: "verify".into(),
15117 code: Some(1),
15118 output_tail: "previous verification failed".into(),
15119 duration_ms: 0,
15120 resource_blocked: false,
15121 artifact: None,
15122 failure_evidence: None,
15123 rerun_comparison: None,
15124 });
15125 state.reviews.push(unresolved);
15126 state.base_sync = Some(crate::run::BaseSync {
15127 tip: "base".into(),
15128 behind: 1,
15129 attempts: 0,
15130 conflict: None,
15131 already_in: None,
15132 });
15133 state.reserve_base_operation("winner", "base");
15134 state.resource_block = Some(crate::run::ResourceBlock {
15135 cause: crate::run::ResourceBlockCause::Other,
15136 node: "rebase".into(),
15137 kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
15138 detail: "recording exec failed".into(),
15139 at: jiff::Timestamp::now(),
15140 });
15141 state.save_under(home.path()).unwrap();
15142 assert_eq!(
15143 crate::resume::validate(home.path(), &state.id).unwrap().id,
15144 state.id
15145 );
15146 assert_eq!(
15147 crate::repair_budget::legacy::classify(&state, "winner", "base").class,
15148 crate::repair_budget::legacy::Class::SequencerInfrastructure
15149 );
15150 state.finish_base_operation(None);
15151 state.save_under(home.path()).unwrap();
15152 assert!(crate::resume::validate(home.path(), &state.id).is_err());
15153 }
15154
15155 #[test]
15156 fn resource_blocked_verification_resumes_the_same_run() {
15157 for (kind, stage) in [
15158 ("cache", "clean"),
15159 ("coordination", "clean"),
15160 ("cache", "review-e2e"),
15161 ("coordination", "no-reviews"),
15162 ("coordination", "handoff"),
15163 ] {
15164 let home = tempfile::tempdir().unwrap();
15165 let mut state = run_state(RunStatus::Blocked);
15166 state.config.graph.review_rounds = 1;
15167 let mut review = review_round(1);
15168 review.clean = true;
15169 state.reviews = vec![review];
15170 if stage == "review-e2e" {
15171 let review = &mut state.reviews[0];
15172 review.clean = false;
15173 review.blocking = 1;
15174 review.e2e = vec![crate::run::CommandOutcome {
15175 command: "verify".into(),
15176 code: None,
15177 output_tail: "resource wait expired".into(),
15178 duration_ms: 0,
15179 resource_blocked: true,
15180 ..Default::default()
15181 }];
15182 } else if stage == "no-reviews" {
15183 state.config.graph.review_rounds = 0;
15184 state.reviews.clear();
15185 } else if stage == "handoff" {
15186 let review = &mut state.reviews[0];
15189 review.clean = false;
15190 review.blocking = 1;
15191 review.e2e = vec![crate::run::CommandOutcome {
15192 command: "verify".into(),
15193 code: Some(0),
15194 output_tail: String::new(),
15195 duration_ms: 0,
15196 resource_blocked: false,
15197 ..Default::default()
15198 }];
15199 }
15200 state.gate_ran = false;
15201 state.resource_block = Some(crate::run::ResourceBlock {
15202 cause: crate::run::ResourceBlockCause::Other,
15203 node: if stage == "review-e2e" {
15204 "review"
15205 } else {
15206 "gate"
15207 }
15208 .into(),
15209 kind: kind.into(),
15210 detail: "resource wait expired".into(),
15211 at: jiff::Timestamp::now(),
15212 });
15213 state.save_under(home.path()).unwrap();
15214 assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15215 assert!(!exhausted_review_budget(&state));
15216 let mut task = held_task_with(&state.id);
15217 task.release();
15218 let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15219 assert_eq!(
15220 choose_starter(None, false, unfinished.as_deref()),
15221 Starter::Resume(state.id.clone())
15222 );
15223 let question = action_question(&state.id, resume_action(&state.id));
15224 assert_eq!(
15225 decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15226 state.clone()
15227 )),
15228 ActionDecision::Resume(state.id.clone())
15229 );
15230 assert_eq!(
15231 crate::resume::validate(home.path(), &state.id).unwrap().id,
15232 state.id
15233 );
15234 let queue = Queue::at(home.path().join("queue"));
15235 let mut controlled = Task::new(
15236 "resume verification".into(),
15237 state.instruction.clone(),
15238 state.repo.clone(),
15239 Source::Agent {
15240 run: "talk".into(),
15241 node: crate::queue::CHAT_NODE.into(),
15242 },
15243 );
15244 controlled.runs.push(state.id.clone());
15245 controlled.hold_machine(Some("verification resource unavailable".into()));
15246 queue.put(&mut controlled).unwrap();
15247 let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15248 assert_eq!(resumed.status, TaskStatus::Queued);
15249 assert_eq!(
15250 resumed.resume_override.unwrap().pinned_run,
15251 Some(state.id.clone())
15252 );
15253 assert_eq!(resumed.attempts, 0);
15254
15255 state.config.graph.review_rounds = 1;
15257 let mut unresolved = review_round(1);
15258 unresolved.blocking = 1;
15259 state.reviews = vec![unresolved];
15260 state.resource_block = None;
15261 state.save_under(home.path()).unwrap();
15262 assert!(exhausted_review_budget(&state));
15263 assert!(crate::resume::validate(home.path(), &state.id).is_err());
15264 }
15265 }
15266
15267 #[tokio::test]
15268 async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
15269 if !crate::standalone_test(
15270 "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
15271 ) {
15272 return;
15273 }
15274 let home = tempfile::tempdir().unwrap();
15275 let mut owner = stopped_public_run(RunStatus::Blocked);
15276 owner.save_under(home.path()).unwrap();
15277 let history = vec![owner.id.clone()];
15278 let repo = owner.repo.clone();
15279 let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
15280 let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
15281 let initial =
15282 std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
15283 assert!(
15284 initial.is_pending(),
15285 "a busy record must not hold or resume the task"
15286 );
15287 owner.retired_to = Some("20260101-000001-bbbb".into());
15288 owner.save_under(home.path()).unwrap();
15289 drop(lock);
15290 let result = tokio::time::timeout(Duration::from_secs(10), lookup)
15291 .await
15292 .expect("ownership lock released")
15293 .expect("read settled owner");
15294 assert!(
15295 result.is_none(),
15296 "the retired owner must not be resumed from a stale read"
15297 );
15298 }
15299
15300 #[tokio::test]
15301 async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
15302 if !crate::standalone_test(
15303 "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
15304 ) {
15305 return;
15306 }
15307 let home = tempfile::tempdir().unwrap();
15308 let mut owner = stopped_public_run(RunStatus::Blocked);
15309 let repo = tempfile::tempdir().unwrap();
15310 crate::git::git(repo.path(), &["init"]).await.unwrap();
15311 owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
15312 owner.id = "20260101-000000-aaaa".into();
15313 owner.save_under(home.path()).unwrap();
15314 let mut successor = run_state(RunStatus::Blocked);
15315 successor.id = "20260101-000001-bbbb".into();
15316 successor.save_under(home.path()).unwrap();
15317 let runs = vec![owner.id.clone(), successor.id.clone()];
15318 assert_eq!(
15319 public_resume_owner(home.path(), &runs, &owner.repo)
15320 .await
15321 .unwrap()
15322 .unwrap()
15323 .id,
15324 owner.id
15325 );
15326 let subdir = owner.repo.join("nested");
15327 std::fs::create_dir(&subdir).unwrap();
15328 assert_eq!(
15329 public_resume_owner(home.path(), &runs, &subdir)
15330 .await
15331 .unwrap()
15332 .unwrap()
15333 .id,
15334 owner.id
15335 );
15336 #[cfg(unix)]
15337 {
15338 let alias = home.path().join("repo-alias");
15339 std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
15340 assert_eq!(
15341 public_resume_owner(home.path(), &runs, &alias.join("nested"))
15342 .await
15343 .unwrap()
15344 .unwrap()
15345 .id,
15346 owner.id
15347 );
15348 }
15349 let different = tempfile::tempdir().unwrap();
15350 crate::git::git(different.path(), &["init"]).await.unwrap();
15351 assert!(
15352 public_resume_owner(home.path(), &runs, different.path())
15353 .await
15354 .is_err()
15355 );
15356 owner.status = RunStatus::Superseded;
15359 owner.pr.as_mut().unwrap().state = "closed".into();
15360 owner.save_under(home.path()).unwrap();
15361 assert!(
15362 public_resume_owner(home.path(), &runs, &owner.repo)
15363 .await
15364 .unwrap()
15365 .is_none()
15366 );
15367 std::fs::remove_file(
15368 home.path()
15369 .join("runs")
15370 .join(&successor.id)
15371 .join("run.json"),
15372 )
15373 .unwrap();
15374 assert!(
15375 public_resume_owner(home.path(), &runs, &owner.repo)
15376 .await
15377 .is_err()
15378 );
15379 }
15380
15381 #[test]
15382 fn an_ordinary_release_keeps_a_resumable_run_available() {
15383 let mut released = task();
15384 released.start("stalled-run".to_owned());
15385 released.release();
15386 let unfinished = (!released.fresh_start)
15387 .then(|| Some("stalled-run".to_owned()))
15388 .flatten();
15389 assert_eq!(
15390 choose_starter(None, false, unfinished.as_deref()),
15391 Starter::Resume("stalled-run".to_owned()),
15392 "manual release must preserve the normal resume path"
15393 );
15394 }
15395
15396 #[test]
15397 fn resume_refusals_explain_admission_without_changing_task_or_run() {
15398 use crate::handover::{ResumeRefusal, resume_refusal_under};
15399 let home = tempfile::tempdir().unwrap();
15400 let mut exhausted = run_state(RunStatus::Blocked);
15401 exhausted.driver_exited = true;
15402 exhausted.config.graph.review_rounds = 3;
15403 exhausted.reviews = (1..=3).map(review_round).collect();
15404 for refusal in [
15405 ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
15406 ResumeRefusal::Status(RunStatus::Ready),
15407 ResumeRefusal::Released("20261022-000000-aaaa".into()),
15408 ResumeRefusal::Retired("retirement-successor".into()),
15409 ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
15410 ] {
15411 let mut state = exhausted.clone();
15412 let expected = match refusal {
15413 ResumeRefusal::Status(_) => {
15414 state.status = RunStatus::Ready;
15415 "status `ready`"
15416 }
15417 ResumeRefusal::Released(ref target) => {
15418 state.released_to = Some(target.clone());
15419 "execution was released"
15420 }
15421 ResumeRefusal::Retired(ref target) => {
15422 state.retired_to = Some(target.clone());
15423 "execution was retired"
15424 }
15425 ResumeRefusal::OwnershipTransferred(ref target) => {
15426 state.pr_taken_over_by = Some(target.clone());
15427 "PR ownership was transferred"
15428 }
15429 _ => "review budget exhausted (3/3 rounds used)",
15430 };
15431 assert_eq!(
15432 resume_refusal_under(&state, Some(home.path())),
15433 Some(refusal.clone())
15434 );
15435 assert_eq!(
15436 refusal.successor(),
15437 state
15438 .released_to
15439 .as_deref()
15440 .or(state.retired_to.as_deref())
15441 .or(state.pr_taken_over_by.as_deref())
15442 );
15443 state.save_under(home.path()).unwrap();
15444 let queue = Queue::at(home.path().join("queue"));
15445 let mut task = Task::new(
15446 "retained implementation".into(),
15447 state.instruction.clone(),
15448 state.repo.clone(),
15449 Source::Agent {
15450 run: "talk".into(),
15451 node: crate::queue::CHAT_NODE.into(),
15452 },
15453 );
15454 task.runs.push(state.id.clone());
15455 task.hold_machine(Some("stopped".into()));
15456 queue.put(&mut task).unwrap();
15457 let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
15458 let before_run = serde_json::to_value(&state).unwrap();
15459 let error = crate::chat_control::resume(&queue, home.path(), &state.id)
15460 .unwrap_err()
15461 .to_string();
15462 assert!(error.contains(expected), "{error}");
15463 assert!(!error.contains("only a stalled or blocked"), "{error}");
15464 if matches!(refusal, ResumeRefusal::Status(_)) {
15465 assert!(
15466 error.contains("is final; there is nothing left to resume"),
15467 "{error}"
15468 );
15469 }
15470 if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
15471 assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
15472 assert!(error.contains("review-only successor with a new review budget"));
15473 assert!(error.contains("does not resume this run"));
15474 }
15475 for target in [
15476 &state.released_to,
15477 &state.retired_to,
15478 &state.pr_taken_over_by,
15479 ]
15480 .into_iter()
15481 .flatten()
15482 {
15483 let short = if state.retired_to.as_ref() == Some(target) {
15484 target.as_str()
15485 } else {
15486 crate::run::short_of(target)
15487 };
15488 assert!(
15489 error.contains(&format!("run {short}; inspect `magi show {short}`")),
15490 "{error}"
15491 );
15492 if short != target {
15493 assert!(!error.contains(target), "full successor id leaked: {error}");
15494 }
15495 }
15496 assert_eq!(
15497 serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
15498 before_task
15499 );
15500 assert_eq!(
15501 serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
15502 .unwrap(),
15503 before_run
15504 );
15505 let question = action_question(&state.id, resume_action(&state.id));
15506 for phrases in [&PHRASES_EN, &PHRASES_JA] {
15507 let decision = decide_action(home.path(), &task, &question, phrases, |id| {
15508 RunState::load_under(id, home.path())
15509 });
15510 let ActionDecision::Refuse(detail) = decision else {
15511 panic!(
15512 "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
15513 state.id,
15514 home.path().display()
15515 );
15516 };
15517 assert!(detail.contains(expected), "{detail}");
15518 }
15519 }
15520 exhausted.status = RunStatus::Ready;
15522 exhausted.released_to = Some("released".into());
15523 exhausted.retired_to = Some("retired".into());
15524 exhausted.pr_taken_over_by = Some("owner".into());
15525 let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
15526 assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
15527 let detail = reason.diagnostic(&exhausted);
15528 for target in ["released", "retired", "owner"] {
15529 assert!(detail.contains(&format!("magi show {target}")));
15530 }
15531 }
15532
15533 #[test]
15534 fn resume_action_ignores_question_checkpoints_in_another_home() {
15535 crate::run::pin_test_home();
15536 let home = tempfile::tempdir().unwrap();
15537 let mut state = run_state(RunStatus::Blocked);
15538 state.id = format!(
15541 "resume-context-{}",
15542 home.path().file_name().unwrap().to_str().unwrap()
15543 );
15544 state.driver_exited = true;
15545 state.config.graph.review_rounds = 1;
15546 state.reviews = vec![review_round(1)];
15547 state.save_under(home.path()).unwrap();
15548 let task = held_task_with(&state.id);
15549 let answer = action_question(&state.id, resume_action(&state.id));
15550 let mut checkpoint = approval_question(&state.id);
15551 let foreign = Questions::open();
15552 foreign.put(&mut checkpoint).unwrap();
15553 let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
15554 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15555 RunState::load_under(id, home.path())
15556 });
15557 let matching: Vec<_> = foreign
15558 .list()
15559 .into_iter()
15560 .filter(|q| q.run == state.id && q.status.open())
15561 .collect();
15562 std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
15563 assert!(
15564 matches!(decision, ActionDecision::Refuse(_)),
15565 "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
15566 state.id,
15567 home.path().display(),
15568 crate::run::test_home().display()
15569 );
15570 assert_eq!(
15571 refusal,
15572 Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
15573 );
15574 let local = Questions::at(home.path().join("questions"));
15575 for status in [
15576 ask::QuestionStatus::Open,
15577 ask::QuestionStatus::Answered,
15578 ask::QuestionStatus::Abandoned,
15579 ] {
15580 let mut question = checkpoint.clone();
15581 match status {
15582 ask::QuestionStatus::Open => {}
15583 ask::QuestionStatus::Answered => {
15584 question
15585 .answer(ask::Answer::Choice(question.choices[0].clone()))
15586 .unwrap();
15587 }
15588 ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
15589 }
15590 local.put(&mut question).unwrap();
15591 let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15592 RunState::load_under(id, home.path())
15593 });
15594 if status.open() {
15595 assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
15596 } else {
15597 assert!(
15598 matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
15599 "status={status:?}, decision={decision:?}"
15600 );
15601 }
15602 }
15603 }
15604
15605 #[test]
15606 fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
15607 let home = tempfile::tempdir().unwrap();
15608 let mut state = run_state(RunStatus::Stalled);
15609 state.id = format!(
15610 "resume-driver-{}",
15611 home.path().file_name().unwrap().to_str().unwrap()
15612 );
15613 state.driver_claimed = Some(false);
15614 state.save_under(home.path()).unwrap();
15615 let task = held_task_with(&state.id);
15616 let question = action_question(&state.id, resume_action(&state.id));
15617 let decide = || {
15618 decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
15619 RunState::load_under(id, home.path())
15620 })
15621 };
15622 let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
15623 assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
15624 let expected_lock = home.path().join("runs").join(&state.id).join("driver.lock");
15625 match decide() {
15626 ActionDecision::Refuse(detail) => {
15627 assert!(
15628 detail.starts_with("run already has a live driver: "),
15629 "{detail}"
15630 );
15631 assert!(
15632 detail.contains(&expected_lock.display().to_string()),
15633 "{detail}"
15634 );
15635 }
15636 other => panic!("expected live driver refusal, got {other:?}"),
15637 }
15638 drop(lease);
15639 assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
15640 }
15641
15642 #[test]
15643 fn resume_checkpoint_admission_uses_the_supplied_question_store() {
15644 let home = tempfile::tempdir().unwrap();
15645 let mut state = run_state(RunStatus::Blocked);
15646 state.driver_exited = true;
15647 state.config.graph.review_rounds = 1;
15648 state.reviews = vec![review_round(1)];
15649 assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
15650 for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
15651 let mut saved = state.clone();
15652 match checkpoint {
15653 "publication" => saved.pr_publication_pending = true,
15654 "approval" => {
15655 saved.land_approval = Some(crate::run::LandApproval {
15656 question: "approval".into(),
15657 head: "head".into(),
15658 })
15659 }
15660 "armed" => saved.land_armed_head = Some("head".into()),
15661 "landing" => saved.status = RunStatus::Landing,
15662 _ => {
15663 let mut question = ask::Question::new(
15664 saved.id.clone(),
15665 "review".into(),
15666 "review-1".into(),
15667 "continue?".into(),
15668 String::new(),
15669 vec!["continue".into()],
15670 );
15671 ask::Questions::at(home.path().join("questions"))
15672 .put(&mut question)
15673 .unwrap();
15674 }
15675 }
15676 saved.save_under(home.path()).unwrap();
15677 assert!(
15678 crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
15679 "{checkpoint}"
15680 );
15681 assert!(
15682 crate::resume::validate(home.path(), &saved.id).is_ok(),
15683 "{checkpoint}"
15684 );
15685 }
15686 }
15687
15688 #[test]
15689 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
15690 let mut state = run_state(RunStatus::Blocked);
15691 state.config.graph.review_rounds = 3;
15692 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
15693 assert!(exhausted_review_budget(&state));
15694
15695 state.reviews.pop();
15697 assert!(!exhausted_review_budget(&state));
15698
15699 let mut stalled = run_state(RunStatus::Stalled);
15702 stalled.config.graph.review_rounds = 1;
15703 stalled.reviews = vec![review_round(1)];
15704 assert!(!exhausted_review_budget(&stalled));
15705 }
15706
15707 fn review_round(round: usize) -> crate::run::ReviewRound {
15708 crate::run::ReviewRound {
15709 round,
15710 head: "deadbeef".to_owned(),
15711 verified_head: None,
15712 verified_at: None,
15713 reviews: Vec::new(),
15714 e2e: Vec::new(),
15715 verify_retried: false,
15716 e2e_deferred: false,
15717 e2e_defer_reason: None,
15718 fix: None,
15719 blocking: 0,
15720 answered: 1,
15721 expected: 1,
15722 clean: false,
15723 progressed: true,
15724 vote_split: false,
15725 reconsideration: Vec::new(),
15726 verdict: None,
15727 }
15728 }
15729
15730 #[test]
15731 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
15732 let mut run = RunState::new(
15733 PathBuf::from("/repo"),
15734 "main".to_owned(),
15735 "abc1234def".to_owned(),
15736 "add retries".to_owned(),
15737 Config::default(),
15738 );
15739 run.status = RunStatus::Judging;
15740 run.parked = true;
15741 let mut task = Task::new(
15742 "add retries".to_owned(),
15743 "add retries".to_owned(),
15744 PathBuf::from("/repo"),
15745 crate::queue::Source::Human,
15746 );
15747 task.status = TaskStatus::Failed;
15748 task.runs = vec![run.id.clone()];
15749 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
15750 assert!(with(&task, &run), "parked after judging is the case");
15751 let mut parked_task = task.clone();
15752 parked_task.status = TaskStatus::Parked;
15753 assert!(with(&parked_task, &run), "the Parked status is the case");
15754
15755 let mut not_parked = run.clone();
15756 not_parked.parked = false;
15757 not_parked.status = RunStatus::Stalled;
15758 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
15759
15760 let mut fresh = task.clone();
15761 fresh.fresh_start = true;
15762 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
15763
15764 let mut review = task.clone();
15765 review.review_branch = Some("magi/x/A".to_owned());
15766 assert!(!with(&review, &run), "review is ranked before resume");
15767
15768 let mut held = task.clone();
15769 held.status = TaskStatus::Held;
15770 assert!(!with(&held, &run), "a hold stays visible to the conductor");
15771
15772 let mut released = run.clone();
15773 released.released_to = Some("20260901-000000-new1".to_owned());
15774 assert!(!with(&task, &released), "nothing left to resume into");
15775
15776 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
15777 "unreadable"
15778 )));
15779 }
15780
15781 #[test]
15782 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
15783 let mut released = RunState::new(
15784 PathBuf::from("/repo"),
15785 "main".to_owned(),
15786 "abc1234def".to_owned(),
15787 "add retries".to_owned(),
15788 Config::default(),
15789 );
15790 released.status = RunStatus::Blocked;
15791 assert_eq!(
15792 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15793 Some(released.id.clone())
15794 );
15795 released.released_to = Some("20260901-000000-new1".to_owned());
15796 assert_eq!(
15797 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15798 None,
15799 "there is nothing left to resume it into"
15800 );
15801 }
15802
15803 #[test]
15804 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
15805 let mut exhausted = RunState::new(
15814 PathBuf::from("/repo"),
15815 "main".to_owned(),
15816 "abc1234def".to_owned(),
15817 "add retries".to_owned(),
15818 Config::default(),
15819 );
15820 exhausted.status = RunStatus::Blocked;
15821 exhausted.config.graph.review_rounds = 1;
15822 exhausted.reviews = vec![review_round(1)];
15823
15824 assert_eq!(
15825 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
15826 None,
15827 "an exhausted `Blocked` run must not be offered as resumable"
15828 );
15829
15830 let mut has_budget_left = RunState::new(
15833 PathBuf::from("/repo"),
15834 "main".to_owned(),
15835 "abc1234def".to_owned(),
15836 "add retries".to_owned(),
15837 Config::default(),
15838 );
15839 has_budget_left.status = RunStatus::Blocked;
15840 has_budget_left.config.graph.review_rounds = 3;
15841 has_budget_left.reviews = vec![review_round(1)];
15842
15843 assert_eq!(
15844 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
15845 Ok(has_budget_left.clone())
15846 }),
15847 Some(has_budget_left.id.clone())
15848 );
15849 }
15850
15851 #[test]
15852 fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
15853 let mut run = RunState::new(
15854 PathBuf::from("/repo"),
15855 "main".to_owned(),
15856 "abc1234def".to_owned(),
15857 "add retries".to_owned(),
15858 Config::default(),
15859 );
15860 run.status = RunStatus::Blocked;
15861 run.config.graph.review_rounds = 1;
15862 run.reviews = vec![review_round(1)];
15863 run.pr_publication_pending = true;
15864 assert_eq!(
15865 unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
15866 Some(run.id.clone()),
15867 "a spent review budget must not turn a failed publication into a re-competition"
15868 );
15869 }
15870
15871 #[test]
15872 fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
15873 let mut task = Task::new(
15874 "recover work".into(),
15875 "recover work".into(),
15876 PathBuf::from("/repo"),
15877 crate::queue::Source::Human,
15878 );
15879 let mut history = std::collections::BTreeMap::new();
15880 for index in 0..8 {
15881 let mut run = run_state(RunStatus::Blocked);
15882 run.id = format!("20260101-000000-{index:04}");
15883 run.base_commit = format!("upstream-{index}");
15884 if index > 0 {
15886 run.candidates.clear();
15887 }
15888 task.runs.extend([run.id.clone(), run.id.clone()]);
15889 history.insert(run.id.clone(), run);
15890 task.requeue();
15891 }
15892 let check = |task: &Task, starter: &Starter, limit| {
15893 retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
15894 };
15895 assert!(
15896 check(&task, &Starter::Start, 8)
15897 .unwrap()
15898 .contains("8 unretired")
15899 );
15900 assert!(check(&task, &Starter::Start, 9).is_none());
15901 assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
15902 task.release_operator("owner", None);
15903 assert_eq!(task.attempts, 0);
15904 let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15905 assert!(check(&restored, &Starter::Start, 8).is_some());
15906 assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
15907 assert!(check(&restored, &Starter::Start, 0).is_none());
15908 }
15909
15910 #[test]
15911 fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
15912 let tmp = tempfile::tempdir().unwrap();
15913 let mut task = Task::new(
15914 "recover selected PR".into(),
15915 "preserve implementation".into(),
15916 tmp.path().join("repo"),
15917 crate::queue::Source::Human,
15918 );
15919 let mut failed = run_state(RunStatus::Failed);
15920 failed.id = "20260101-000000-fail".into();
15921 failed.candidates.clear();
15922 failed.prep_complete = Some(false);
15923 failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15924 failed.startup = Some(crate::run::Startup {
15925 kind: "pr-recovery".into(),
15926 branch: Some("selected-public-head".into()),
15927 stage: "worktree-setup".into(),
15928 complete: false,
15929 failure: Some("setup modified a tracked file and failed".into()),
15930 });
15931 let worktree = failed.worktree_root().join("under-review");
15934 std::fs::create_dir_all(&worktree).unwrap();
15935 let retained_edit = worktree.join("implementation");
15936 std::fs::write(&retained_edit, "retained setup edit").unwrap();
15937 task.record_startup_failure(crate::run::StartupFailure {
15938 run: failed.id.clone(),
15939 stage: "worktree-setup".into(),
15940 });
15941 let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15942 assert!(task.runs.is_empty() && task.passes.is_empty());
15943 assert_eq!(task.attempts, 0);
15944 let starter = Starter::Review("selected-public-head".into());
15945 assert!(
15946 retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
15947 .unwrap()
15948 .contains("1 unretired")
15949 );
15950 assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
15951 assert!(
15952 retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
15953 .unwrap()
15954 .contains("Cannot verify")
15955 );
15956 let mut mixed = task.clone();
15958 mixed.runs.push(failed.id.clone());
15959 mixed
15960 .startup_failures
15961 .push(task.startup_failures[0].clone());
15962 assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
15963 failed.retired_to = Some("verified-recovery-owner".into());
15964 assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
15965 assert!(
15966 retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
15967 panic!("resuming the existing owner must not allocate a new attempt")
15968 })
15969 .is_none()
15970 );
15971 assert_eq!(
15972 std::fs::read_to_string(retained_edit).unwrap(),
15973 "retained setup edit"
15974 );
15975 assert!(task.runs.is_empty() && task.passes.is_empty());
15976 assert_eq!(task.attempts, 0);
15977 }
15978
15979 #[test]
15980 fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
15981 let mut task = Task::new(
15982 "recover work".into(),
15983 "recover work".into(),
15984 PathBuf::from("/repo"),
15985 crate::queue::Source::Human,
15986 );
15987 let mut run = run_state(RunStatus::Superseded);
15988 run.candidates.clear();
15989 task.runs.push(run.id.clone());
15990 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
15991 run.retired_to = Some("authority".into());
15992 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
15993 run.retired_to = None;
15994 run.released_to = Some("authority".into());
15995 assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
15996 assert!(
15997 retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
15998 .unwrap()
15999 .contains("Cannot verify")
16000 );
16001 assert!(
16003 retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
16004 panic!("resume must not load historical attempts")
16005 })
16006 .is_none()
16007 );
16008 }
16009
16010 #[test]
16011 fn retired_resume_requires_a_valid_same_repository_authority() {
16012 let mut source = run_state(RunStatus::Blocked);
16013 let mut empty = run_state(RunStatus::Blocked);
16014 empty.retired_to = Some(source.id.clone());
16015 let runs = vec![source.id.clone(), empty.id.clone()];
16016 let resolve = |source: &RunState, empty: &RunState| {
16017 unfinished_run_with(&runs, "fixture", |id| {
16018 if id == source.id {
16019 Ok(source.clone())
16020 } else if id == empty.id {
16021 Ok(empty.clone())
16022 } else {
16023 bail!("unreadable authority")
16024 }
16025 })
16026 };
16027 assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
16028 assert_eq!(
16029 choose_starter(None, false, resolve(&source, &empty).as_deref()),
16030 Starter::Resume(source.id.clone())
16031 );
16032 source.retired_to = Some(empty.id.clone());
16033 assert!(
16034 resolve(&source, &empty).is_none(),
16035 "cycles do not revive obsolete runs"
16036 );
16037 source.retired_to = None;
16038 source.repo = PathBuf::from("/another-repository");
16039 assert!(resolve(&source, &empty).is_none());
16040 source.repo = empty.repo.clone();
16041 source.released_to = Some("later".into());
16042 assert!(resolve(&source, &empty).is_none());
16043 empty.retired_to = Some("unlisted-run".into());
16044 assert!(resolve(&source, &empty).is_none());
16045 }
16046
16047 #[test]
16048 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
16049 let mut older_stalled = RunState::new(
16057 PathBuf::from("/repo"),
16058 "main".to_owned(),
16059 "abc1234def".to_owned(),
16060 "add retries".to_owned(),
16061 Config::default(),
16062 );
16063 older_stalled.status = RunStatus::Stalled;
16064
16065 let mut newest_exhausted = RunState::new(
16066 PathBuf::from("/repo"),
16067 "main".to_owned(),
16068 "abc1234def".to_owned(),
16069 "add retries".to_owned(),
16070 Config::default(),
16071 );
16072 newest_exhausted.status = RunStatus::Blocked;
16073 newest_exhausted.config.graph.review_rounds = 1;
16074 newest_exhausted.reviews = vec![review_round(1)];
16075
16076 assert_eq!(
16077 unfinished_run_with(
16078 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
16079 "t",
16080 |_| Ok(newest_exhausted.clone())
16081 ),
16082 None,
16083 "the newest run is exhausted, so nothing here is worth resuming - \
16084 least of all the older, already-superseded run"
16085 );
16086 }
16087
16088 #[test]
16089 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
16090 assert_eq!(
16091 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
16092 Err(anyhow::anyhow!("fixture is absent"))
16093 }),
16094 None
16095 );
16096 }
16097
16098 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
16099 let mut q = ask::Question::new(
16100 run.to_owned(),
16101 "implement".to_owned(),
16102 "impl-A".to_owned(),
16103 "continue?".to_owned(),
16104 String::new(),
16105 vec!["resume で続行する".to_owned(), "other".to_owned()],
16106 );
16107 q.actions.insert("resume で続行する".to_owned(), action);
16108 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
16109 .unwrap();
16110 q
16111 }
16112
16113 fn held_task_with(run: &str) -> Task {
16114 let mut t = task();
16115 t.runs = vec![run.to_owned()];
16116 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
16117 t
16118 }
16119
16120 fn resume_action(run: &str) -> ask::ChoiceAction {
16121 ask::ChoiceAction::Resume { run: run.into() }
16122 }
16123
16124 #[test]
16125 fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
16126 let home = crate::run::test_home();
16127 for parked in [false, true] {
16128 let mut t = task();
16129 t.start("A".into());
16130 t.start("B".into());
16131 assert_eq!(t.runs, vec!["A", "B"]);
16132 t.start("A".into());
16133 let mut resumed = run_state(RunStatus::Blocked);
16134 resumed.id = "A".into();
16135 resumed.parked = parked;
16136 resumed.driver_exited = true;
16137 t.hold_machine(Some("resumed run stopped".into()));
16138 let q = action_question("A", resume_action("A"));
16139 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16140 assert_eq!(
16141 decide_action(&home, &t, &q, &PHRASES_EN, |id| {
16142 assert_eq!(id, "A");
16143 Ok(resumed.clone())
16144 }),
16145 ActionDecision::Resume("A".into())
16146 );
16147 assert_eq!(
16148 action_standing(&t, &action_question("B", resume_action("B"))),
16149 ActionStanding::Stale
16150 );
16151 t.release_operator("cli", None);
16152 let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
16153 assert_eq!(id, "A");
16154 Ok(resumed.clone())
16155 });
16156 assert_eq!(
16157 choose_starter(None, false, unfinished.as_deref()),
16158 Starter::Resume("A".into())
16159 );
16160 assert_eq!(t.runs, vec!["B", "A"]);
16161 }
16162 }
16163
16164 #[test]
16165 fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
16166 let home = crate::run::test_home();
16167 let mut state = crate::land::tests::repair_state(true, true);
16168 state.status = RunStatus::Landing;
16169 state.parked = true;
16170 state.driver_exited = true;
16171 let mut q = ask::Question::new(
16172 state.id.clone(),
16173 land::APPROVAL_NODE.into(),
16174 "land".into(),
16175 "Merge?".into(),
16176 String::new(),
16177 vec![land::APPROVE.into(), land::HOLD.into()],
16178 );
16179 q.id = state.id.clone();
16180 state.land_approval = Some(crate::run::LandApproval {
16181 question: q.id.clone(),
16182 head: "current-head".into(),
16183 });
16184 assert!(land::upgrade_repair_choice(&mut q, &state));
16185 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16186 let mut task = held_task_with(&state.id);
16187 task.status = TaskStatus::Parked;
16188 assert_eq!(
16189 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16190 ActionDecision::Resume(state.id.clone())
16191 );
16192 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16193 q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
16194 task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
16195 assert_eq!(
16196 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16197 ActionDecision::Resume(state.id.clone()),
16198 "a repair answer newer than the manual hold resumes the existing owner"
16199 );
16200 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16201 for answered_at in [q.answered_at, None] {
16202 let mut older = q.clone();
16203 older.answered_at = answered_at;
16204 let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
16205 panic!("a later manual hold must prevent dispatch")
16206 });
16207 let ActionDecision::Refuse(reason) = refused else {
16208 panic!("expected an actionable refusal, got {refused:?}");
16209 };
16210 assert!(reason.contains("later operator decision"));
16211 assert!(reason.contains(&format!("magi task release {}", task.id)));
16212 }
16213 task.operator_decided_at = None;
16214 let mut superseded = state.clone();
16215 superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
16216 assert_eq!(
16217 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
16218 ActionDecision::Stale
16219 );
16220 for case in 1..4 {
16221 let mut changed = state.clone();
16222 match case {
16223 1 => changed.status = RunStatus::Blocked,
16224 2 => changed.released_to = Some("new-owner".into()),
16225 _ => changed.land_approval.as_mut().unwrap().head.clear(),
16226 }
16227 assert!(matches!(
16228 decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
16229 ActionDecision::Refuse(_)
16230 ));
16231 }
16232 assert!(matches!(
16233 decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
16234 "missing owner"
16235 )),
16236 ActionDecision::Refuse(_)
16237 ));
16238 task.runs.push("replacement".into());
16239 task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16240 assert_eq!(
16241 decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
16242 "old owner must not load"
16243 )),
16244 ActionDecision::Stale
16245 );
16246 }
16247
16248 #[test]
16249 fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
16250 let mut state = crate::land::tests::repair_state(true, true);
16251 state.status = RunStatus::Landing;
16252 state.parked = true;
16253 state.driver_exited = true;
16254 let mut q = ask::Question::new(
16255 state.id.clone(),
16256 land::APPROVAL_NODE.into(),
16257 "land".into(),
16258 "Merge?".into(),
16259 String::new(),
16260 vec![land::APPROVE.into(), land::HOLD.into()],
16261 );
16262 q.id = state.id.clone();
16263 state.land_approval = Some(crate::run::LandApproval {
16264 question: q.id.clone(),
16265 head: "current-head".into(),
16266 });
16267 state.save().unwrap();
16268 land::upgrade_repair_choice(&mut q, &state);
16269 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16270 Questions::open().put(&mut q).unwrap();
16271 let tmp = tempfile::tempdir().unwrap();
16272 let queue = Queue::at(tmp.path().join("queue"));
16273 let mut task = held_task_with(&state.id);
16274 task.status = TaskStatus::Parked;
16275 queue.put(&mut task).unwrap();
16276 let empty = Arc::new(tokio::sync::Semaphore::new(0));
16277 let free = Arc::new(tokio::sync::Semaphore::new(1));
16278 assert!(matches!(
16279 claim_dispatch(&queue, &task, false, &empty, &free),
16280 Err(SkipReason::OrdinaryCapacity)
16281 ));
16282 assert!(matches!(
16283 claim_dispatch(&queue, &task, true, &free, &free),
16284 Err(SkipReason::CoolingDown)
16285 ));
16286 let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
16287 assert!(claim.permit.is_some());
16288 assert!(matches!(
16289 claim_dispatch(&queue, &task, false, &free, &free),
16290 Err(SkipReason::ClaimUnavailable)
16291 ));
16292 drop(claim);
16293 Questions::open()
16294 .update(&q.id, |q| {
16295 q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
16296 Ok(())
16297 })
16298 .unwrap();
16299 let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
16300 assert!(claim.permit.is_none());
16301 assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
16302 }
16303
16304 #[test]
16305 fn decide_action_resumes_only_the_latest_resumable_run() {
16306 let home = crate::run::test_home();
16307 let t = held_task_with("r1");
16308 let q = action_question("r1", resume_action("r1"));
16309 let load = |s: RunState| move |_: &str| Ok(s);
16310 assert_eq!(
16311 decide_action(
16312 &home,
16313 &t,
16314 &q,
16315 &PHRASES_EN,
16316 load(run_state(RunStatus::Blocked))
16317 ),
16318 ActionDecision::Resume("r1".into())
16319 );
16320 let q_other = action_question("r1", resume_action("r0"));
16322 assert!(matches!(
16323 decide_action(
16324 &home,
16325 &t,
16326 &q_other,
16327 &PHRASES_EN,
16328 load(run_state(RunStatus::Blocked))
16329 ),
16330 ActionDecision::Refuse(_)
16331 ));
16332 assert!(matches!(
16334 decide_action(
16335 &home,
16336 &t,
16337 &q,
16338 &PHRASES_EN,
16339 load(run_state(RunStatus::Ready))
16340 ),
16341 ActionDecision::Refuse(_)
16342 ));
16343 let mut released = run_state(RunStatus::Blocked);
16345 released.released_to = Some("elsewhere".into());
16346 assert!(matches!(
16347 decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
16348 ActionDecision::Refuse(_)
16349 ));
16350 assert!(matches!(
16352 decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
16353 ActionDecision::Refuse(_)
16354 ));
16355 }
16356
16357 #[test]
16358 fn decide_action_ignores_a_question_about_an_earlier_run() {
16359 let home = crate::run::test_home();
16360 let mut t = held_task_with("r1");
16361 t.runs.push("r2".to_owned());
16362 let never = |_: &str| -> Result<RunState> { bail!("not read") };
16363 assert_eq!(
16364 decide_action(
16365 &home,
16366 &t,
16367 &action_question("r1", ask::ChoiceAction::Done),
16368 &PHRASES_EN,
16369 never
16370 ),
16371 ActionDecision::Stale
16372 );
16373 }
16374
16375 #[test]
16376 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
16377 let home = crate::run::test_home();
16378 let mut t = held_task_with("r1");
16379 let never = |_: &str| -> Result<RunState> { bail!("not read") };
16380 assert_eq!(
16381 decide_action(
16382 &home,
16383 &t,
16384 &action_question("r1", ask::ChoiceAction::Requeue),
16385 &PHRASES_EN,
16386 never
16387 ),
16388 ActionDecision::Requeue
16389 );
16390 let done_q = action_question("r1", ask::ChoiceAction::Done);
16391 assert_eq!(
16392 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16393 ActionDecision::Done
16394 );
16395 t.mark_action_applied(&done_q.id);
16396 assert_eq!(
16397 decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16398 ActionDecision::Skip
16399 );
16400
16401 let mut plain = action_question("r1", ask::ChoiceAction::Done);
16403 plain.actions.clear();
16404 assert_eq!(
16405 decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
16406 ActionDecision::Skip
16407 );
16408 let mut running = held_task_with("r1");
16410 running.status = TaskStatus::Running;
16411 assert_eq!(
16412 decide_action(
16413 &home,
16414 &running,
16415 &action_question("r1", ask::ChoiceAction::Done),
16416 &PHRASES_EN,
16417 never
16418 ),
16419 ActionDecision::Skip
16420 );
16421 }
16422
16423 #[test]
16424 fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
16425 crate::run::pin_test_home();
16426 for legacy in [false, true] {
16427 let dir = tempfile::tempdir().unwrap();
16428 let queue = Queue::at(dir.path().join("queue"));
16429 let questions = Questions::at(dir.path().join("questions"));
16430 let run = "20260101-000000-hold";
16431 let mut task = held_task_with(run);
16432 task.status = TaskStatus::Parked;
16433 let mut q = ask::Question::new(
16434 run.into(),
16435 land::APPROVAL_NODE.into(),
16436 "land".into(),
16437 "Repair?".into(),
16438 String::new(),
16439 vec![land::REPAIR.into()],
16440 );
16441 q.actions.insert(land::REPAIR.into(), resume_action(run));
16442 q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16443 q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16445 q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
16446 questions.put(&mut q).unwrap();
16447 task.hold_manual(Some("Keep this PR paused".into()));
16448 if legacy {
16449 task.hold_source = None;
16450 }
16451 queue.put(&mut task).unwrap();
16452
16453 apply_task_choice_actions(&queue, &questions, dir.path());
16454 let after = queue.get(&task.id).unwrap();
16455 assert!(after.operator_held());
16456 assert_eq!(after.hold_source, task.hold_source);
16457 assert_eq!(after.operator_decided_at, task.operator_decided_at);
16458 assert_eq!(after.runs, task.runs);
16459 assert_eq!(after.instruction, task.instruction);
16460 assert!(after.resume_override.is_none());
16461 assert!(after.action_applied(&q.id));
16462 let reason = after.hold_reason.as_deref().unwrap();
16463 assert!(reason.starts_with("Keep this PR paused"));
16464 assert!(reason.contains("later operator decision"));
16465 assert!(reason.contains(&format!("magi task release {}", task.id)));
16466
16467 for recovery in [
16468 crate::conduct::Recovery::Review,
16469 crate::conduct::Recovery::Requeue,
16470 ] {
16471 crate::conduct::apply(
16472 &queue,
16473 &questions,
16474 &crate::conduct::Verdict {
16475 decisions: vec![crate::conduct::Decision {
16476 id: task.id.clone(),
16477 recovery: Some(recovery),
16478 ..Default::default()
16479 }],
16480 },
16481 )
16482 .unwrap();
16483 }
16484 apply_task_choice_actions(&queue, &questions, dir.path());
16487 let still_held = queue.get(&task.id).unwrap();
16488 assert!(still_held.operator_held());
16489 assert_eq!(still_held.hold_reason, after.hold_reason);
16490 assert_eq!(still_held.runs, task.runs);
16491 assert!(still_held.review_branch.is_none());
16492 assert!(!still_held.fresh_start);
16493 assert!(queue.next_runnable().is_none());
16494 }
16495 }
16496
16497 #[test]
16498 fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
16499 for held in [false, true] {
16500 for retry in [false, true] {
16501 let dir = tempfile::tempdir().unwrap();
16502 let queue = Queue::at(dir.path().join("queue"));
16503 let questions = Questions::at(dir.path().join("questions"));
16504 let home = dir.path().join("home");
16505 let mut t = task();
16506 if held {
16507 t.hold_machine(Some("driver state unknown".into()));
16508 }
16509 queue.put(&mut t).unwrap();
16510 let verdict = serde_json::from_value(serde_json::json!({
16511 "decisions": [{
16512 "id": t.id,
16513 "question": "Driver state unknown; retry the checks or hold?",
16514 "choices": ["daemon: recheck and retry", "daemon: hold the task"],
16515 "actions": {
16516 "daemon: recheck and retry": {"do": "requeue"},
16517 "daemon: hold the task": {"do": "hold"}
16518 }
16519 }]
16520 }))
16521 .unwrap();
16522 crate::conduct::apply(&queue, &questions, &verdict).unwrap();
16523 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16524 let mut q = questions.list().pop().unwrap();
16525 let choice = if retry {
16526 "daemon: recheck and retry"
16527 } else {
16528 "daemon: hold the task"
16529 };
16530 assert_eq!(q.actions.len(), 2);
16531 q.answer(ask::Answer::Choice(choice.into())).unwrap();
16532 questions.put(&mut q).unwrap();
16533
16534 questions.beat(&q.id, ask::WaiterKind::Deputy);
16536 for _ in 0..2 {
16537 resolve_blockers(&queue, &questions);
16538 apply_task_choice_actions(&queue, &questions, &home);
16539 let waiting = queue.get(&t.id).unwrap();
16540 assert_eq!(waiting.status, TaskStatus::Blocked);
16541 assert_eq!(waiting.blocked_by, [q.id.clone()]);
16542 assert!(waiting.answers.is_empty());
16543 assert!(!waiting.action_applied(&q.id));
16544 assert!(runnable(&queue).is_empty());
16545 let free = Arc::new(tokio::sync::Semaphore::new(1));
16546 assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
16547 }
16548 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16549
16550 resolve_blockers(&queue, &questions);
16552 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16553 apply_task_choice_actions(&queue, &questions, &home);
16554 let after = queue.get(&t.id).unwrap();
16555 assert_eq!(
16556 after.status,
16557 if retry {
16558 TaskStatus::Queued
16559 } else {
16560 TaskStatus::Held
16561 }
16562 );
16563 assert!(after.action_applied(&q.id));
16564 assert_eq!(after.operator_held(), !retry);
16565 assert_eq!(after.answers.len(), 1);
16566
16567 let mut changed = after;
16569 if retry {
16570 changed.hold_manual(Some("later hold".into()));
16571 } else {
16572 changed.release_operator("test", None);
16573 }
16574 let expected = changed.status;
16575 queue.put(&mut changed).unwrap();
16576 apply_task_choice_actions(&queue, &questions, &home);
16577 assert_eq!(queue.get(&t.id).unwrap().status, expected);
16578 }
16579 }
16580 }
16581
16582 #[test]
16583 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
16584 let dir = tempfile::tempdir().unwrap();
16585 let queue = Queue::at(dir.path().join("queue"));
16586 let questions = Questions::at(dir.path().join("questions"));
16587 let home = dir.path().join("home");
16588 let mut state = run_state(RunStatus::Blocked);
16589 state.id = "20260101-000000-act1".to_owned();
16590 state.save_under(&home).unwrap();
16591
16592 let mut t = held_task_with(&state.id);
16593 queue.put(&mut t).unwrap();
16594 let mut q = action_question(&state.id, resume_action(&state.id));
16595 questions.put(&mut q).unwrap();
16596
16597 apply_task_choice_actions(&queue, &questions, &home);
16598 let after = queue.get(&t.id).unwrap();
16599 assert_eq!(after.status, TaskStatus::Queued);
16600 assert!(!after.fresh_start);
16601 assert!(after.action_applied(&q.id));
16602 let pin = after.resume_override.clone().unwrap();
16603 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
16604 assert!(pin.forced);
16605
16606 let mut again = queue.get(&t.id).unwrap();
16608 again.hold_machine(Some("later".into()));
16609 queue.put(&mut again).unwrap();
16610 apply_task_choice_actions(&queue, &questions, &home);
16611 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16612 }
16613
16614 #[test]
16615 fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
16616 let dir = tempfile::tempdir().unwrap();
16617 let home = dir.path();
16618 let queue = Queue::at(home.join("queue"));
16619 let questions = Questions::at(home.join("questions"));
16620 let mut state = run_state(RunStatus::Blocked);
16621 state.save_under(home).unwrap();
16622 let mut task = held_task_with(&state.id);
16623 queue.put(&mut task).unwrap();
16624 let mut question = action_question(&state.id, ask::ChoiceAction::Done);
16625 questions.put(&mut question).unwrap();
16626
16627 apply_task_choice_actions(&queue, &questions, home);
16628
16629 let after = queue.get(&task.id).unwrap();
16630 assert_eq!(after.status, TaskStatus::Held);
16631 assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
16632 assert_eq!(after.runs, task.runs);
16633 assert!(after.completion_history.is_empty());
16634 assert!(!after.decision_effects.contains_key(&question.id));
16635 assert_eq!(
16636 RunState::load_under(&state.id, home).unwrap().status,
16637 RunStatus::Blocked
16638 );
16639 }
16640
16641 #[test]
16642 fn a_delivered_answer_is_still_acted_on_exactly_once() {
16643 let dir = tempfile::tempdir().unwrap();
16644 let queue = Queue::at(dir.path().join("queue"));
16645 let questions = Questions::at(dir.path().join("questions"));
16646 let home = dir.path().join("home");
16647 let mut state = run_state(RunStatus::Blocked);
16648 state.id = "20260101-000000-act2".to_owned();
16649 state.save_under(&home).unwrap();
16650
16651 let mut t = held_task_with(&state.id);
16652 queue.put(&mut t).unwrap();
16653 let mut q = action_question(&state.id, resume_action(&state.id));
16654 q.answer_delivered = true;
16655 questions.put(&mut q).unwrap();
16656
16657 apply_task_choice_actions(&queue, &questions, &home);
16660 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16661 assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
16662
16663 let mut again = queue.get(&t.id).unwrap();
16665 again.hold_machine(Some("later".into()));
16666 queue.put(&mut again).unwrap();
16667 apply_task_choice_actions(&queue, &questions, &home);
16668 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16669 }
16670
16671 #[test]
16672 fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
16673 let dir = tempfile::tempdir().unwrap();
16674 let queue = Queue::at(dir.path().join("queue"));
16675 let questions = Questions::at(dir.path().join("questions"));
16676 let home = dir.path().join("home");
16677 let mut state = run_state(RunStatus::Blocked);
16678 state.id = "20260101-000000-act3".to_owned();
16679 state.save_under(&home).unwrap();
16680 let mut t = held_task_with(&state.id);
16681 queue.put(&mut t).unwrap();
16682 let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
16683 questions.put(&mut q).unwrap();
16684
16685 questions.beat(&q.id, crate::ask::WaiterKind::Asker);
16686 apply_task_choice_actions(&queue, &questions, &home);
16687 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16688
16689 std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16690 apply_task_choice_actions(&queue, &questions, &home);
16691 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16692 }
16693
16694 #[test]
16695 fn action_standing_tells_the_reasons_apart() {
16696 let mut t = held_task_with("r1");
16697 let q = action_question("r1", ask::ChoiceAction::Requeue);
16698 assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16699 let mut plain = q.clone();
16700 plain.actions.clear();
16701 assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
16702
16703 t.mark_action_applied(&q.id);
16705 assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
16706
16707 let mut t = held_task_with("r1");
16709 t.start("r2".to_owned());
16710 assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
16711 let q2 = action_question("r2", ask::ChoiceAction::Requeue);
16713 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16714 t.status = TaskStatus::Blocked;
16715 assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16716
16717 let mut c = action_question("r0", ask::ChoiceAction::Requeue);
16719 c.node = crate::conduct::NODE.to_owned();
16720 assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
16721 assert!(!ActionStanding::Busy.daemon_owns());
16722 }
16723
16724 #[test]
16725 fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
16726 let dir = tempfile::tempdir().unwrap();
16727 let queue = Queue::at(dir.path().join("queue"));
16728 let questions = Questions::at(dir.path().join("questions"));
16729 let home = dir.path().join("home");
16730 let mut state = run_state(RunStatus::Ready);
16732 state.id = "20260101-000000-act4".to_owned();
16733 state.save_under(&home).unwrap();
16734 let mut t = held_task_with(&state.id);
16735 t.status = TaskStatus::Running;
16736 queue.put(&mut t).unwrap();
16737 let mut q = action_question(&state.id, ask::ChoiceAction::Done);
16738 q.cwd = Some(dir.path().display().to_string());
16739 questions.put(&mut q).unwrap();
16740
16741 let running = queue.get(&t.id).unwrap();
16744 assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
16745 assert!(matches!(
16746 crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
16747 crate::waiter::Action::Deliver(_)
16748 ));
16749 apply_task_choice_actions(&queue, &questions, &home);
16751 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
16752 let mut back = queue.get(&t.id).unwrap();
16753 back.hold_machine(Some("later".into()));
16754 queue.put(&mut back).unwrap();
16755 apply_task_choice_actions(&queue, &questions, &home);
16756 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
16757 let mut again = queue.get(&t.id).unwrap();
16758 again.hold_machine(Some("again".into()));
16759 queue.put(&mut again).unwrap();
16760 apply_task_choice_actions(&queue, &questions, &home);
16761 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16762 }
16763
16764 #[test]
16765 fn stale_heartbeat_pointing_to_terminal_worker_does_not_block_resume_while_unproven_claims_stay_protected()
16766 {
16767 let dir = tempfile::tempdir().unwrap();
16768 let home = dir.path();
16769 let queue = Queue::at(home.join("queue"));
16770 let mut state = run_state(RunStatus::Blocked);
16771 state.id = "20261125-084544-669a".to_owned();
16772 state.driver_exited = true;
16773 state.driver_pid = None;
16774 state.driver_started_at = None;
16775 state.save_under(home).unwrap();
16776
16777 let mut t = held_task_with(&state.id);
16778 queue.put(&mut t).unwrap();
16779
16780 let worker_id = "fc769e65-0000-4000-8000-000000000001";
16783 let retained_dir = home.join("workers").join("results").join(worker_id);
16784 std::fs::create_dir_all(&retained_dir).unwrap();
16785 let finished_job = crate::worker::Job {
16786 id: worker_id.to_owned(),
16787 sequence: 1,
16788 kind: "task".to_owned(),
16789 key: format!("task:{}", t.id),
16790 payload: serde_json::json!({
16791 "queue": home.join("queue"),
16792 "task": t.id,
16793 "opts": Opts::default(),
16794 "standalone": false,
16795 }),
16796 generation: "a".repeat(64),
16797 version: Some("0.260.0".to_owned()),
16798 status: crate::worker::Status::Finished,
16799 result: Some("completed".to_owned()),
16800 pid: Some(37456),
16801 created_at: 1,
16802 finished_at: Some(2),
16803 };
16804 std::fs::write(
16805 retained_dir.join("job.json"),
16806 serde_json::to_vec(&finished_job).unwrap(),
16807 )
16808 .unwrap();
16809
16810 let now = Timestamp::now();
16811 let mut status = Status::new();
16812 status.updated_at = now;
16813 status.current = vec![Current {
16814 worker: Some(worker_id.to_owned()),
16815 task: t.id.clone(),
16816 run: state.id.clone(),
16817 }];
16818 write_status_to(&home.join("daemon.json"), &status).unwrap();
16819
16820 assert!(
16821 claim_for_run(home, &state.id, now).is_none(),
16822 "a fresh heartbeat pointing to a confirmed terminal worker must not claim the run"
16823 );
16824 assert!(crate::resume::validate(home, &state.id).is_ok());
16825
16826 status.current = vec![Current {
16828 worker: None,
16829 task: t.id.clone(),
16830 run: state.id.clone(),
16831 }];
16832 write_status_to(&home.join("daemon.json"), &status).unwrap();
16833 let legacy_err = crate::resume::validate(home, &state.id)
16834 .unwrap_err()
16835 .to_string();
16836 assert!(
16837 legacy_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16838 "{legacy_err}"
16839 );
16840 assert!(legacy_err.contains("worker=none"), "{legacy_err}");
16841
16842 let missing_id = "fc769e65-0000-4000-8000-000000000002";
16844 status.current = vec![Current {
16845 worker: Some(missing_id.to_owned()),
16846 task: t.id.clone(),
16847 run: state.id.clone(),
16848 }];
16849 write_status_to(&home.join("daemon.json"), &status).unwrap();
16850 let missing_err = crate::resume::validate(home, &state.id)
16851 .unwrap_err()
16852 .to_string();
16853 assert!(
16854 missing_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16855 "{missing_err}"
16856 );
16857 assert!(missing_err.contains(missing_id), "{missing_err}");
16858 assert!(missing_err.contains("status=unknown"), "{missing_err}");
16859
16860 let running_id = "fc769e65-0000-4000-8000-000000000003";
16863 let running_dir = home.join("workers").join("jobs").join(running_id);
16864 std::fs::create_dir_all(&running_dir).unwrap();
16865 let running_job = crate::worker::Job {
16866 id: running_id.to_owned(),
16867 status: crate::worker::Status::Running,
16868 pid: Some(42424),
16869 finished_at: None,
16870 result: None,
16871 ..finished_job
16872 };
16873 std::fs::write(
16874 running_dir.join("job.json"),
16875 serde_json::to_vec(&running_job).unwrap(),
16876 )
16877 .unwrap();
16878 std::fs::write(running_dir.join("live.lock"), b"").unwrap();
16879 status.current = vec![Current {
16880 worker: Some(running_id.to_owned()),
16881 task: t.id.clone(),
16882 run: state.id.clone(),
16883 }];
16884 write_status_to(&home.join("daemon.json"), &status).unwrap();
16885 let running_err = crate::resume::validate(home, &state.id)
16886 .unwrap_err()
16887 .to_string();
16888 assert!(
16889 running_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16890 "{running_err}"
16891 );
16892 assert!(running_err.contains(running_id), "{running_err}");
16893 assert!(running_err.contains("pid=42424"), "{running_err}");
16894 assert!(running_err.contains("status=running"), "{running_err}");
16895 }
16896
16897 #[test]
16898 fn resume_validate_refusals_include_concrete_evidence_for_every_live_path() {
16899 let dir = tempfile::tempdir().unwrap();
16900 let home = dir.path();
16901 let queue = Queue::at(home.join("queue"));
16902 let mut state = run_state(RunStatus::Blocked);
16903 state.id = "20261125-090000-evid".to_owned();
16904 state.driver_exited = true;
16905 state.save_under(home).unwrap();
16906 let mut t = held_task_with(&state.id);
16907 queue.put(&mut t).unwrap();
16908
16909 let payload = serde_json::json!({
16911 "queue": home.join("queue"),
16912 "task": t.id,
16913 "opts": Opts::default(),
16914 "standalone": false,
16915 });
16916 let (job, lease) =
16917 crate::worker::running_fixture(home, &format!("task:{}", t.id), payload).unwrap();
16918 let worker_err = crate::resume::validate(home, &state.id)
16919 .unwrap_err()
16920 .to_string();
16921 assert!(
16922 worker_err.starts_with("run already has a live driver: worker claim"),
16923 "{worker_err}"
16924 );
16925 assert!(worker_err.contains(&job.id), "{worker_err}");
16926 assert!(
16927 worker_err.contains(&format!("pid={}", std::process::id())),
16928 "{worker_err}"
16929 );
16930 assert!(worker_err.contains("status=running"), "{worker_err}");
16931 assert!(worker_err.contains("live.lock held"), "{worker_err}");
16932 drop(lease);
16933 std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id)).unwrap();
16934
16935 let starting_id = "fc769e65-0000-4000-8000-000000000010";
16937 let starting_dir = home.join("workers").join("jobs").join(starting_id);
16938 std::fs::create_dir_all(&starting_dir).unwrap();
16939 let starting_job = crate::worker::Job {
16940 id: starting_id.to_owned(),
16941 sequence: 2,
16942 kind: "task".to_owned(),
16943 key: format!("task:{}", t.id),
16944 payload: serde_json::json!({
16945 "queue": home.join("queue"),
16946 "task": t.id,
16947 "opts": Opts::default(),
16948 "standalone": false,
16949 }),
16950 generation: "a".repeat(64),
16951 version: None,
16952 status: crate::worker::Status::Starting,
16953 result: None,
16954 pid: None,
16955 created_at: 1,
16956 finished_at: None,
16957 };
16958 std::fs::write(
16959 starting_dir.join("job.json"),
16960 serde_json::to_vec(&starting_job).unwrap(),
16961 )
16962 .unwrap();
16963 let starting_err = crate::resume::validate(home, &state.id)
16964 .unwrap_err()
16965 .to_string();
16966 assert!(
16967 starting_err.starts_with("run already has a live driver: worker claim"),
16968 "{starting_err}"
16969 );
16970 assert!(starting_err.contains(starting_id), "{starting_err}");
16971 assert!(starting_err.contains("status=starting"), "{starting_err}");
16972 assert!(
16973 starting_err.contains("unfenced starting reservation"),
16974 "{starting_err}"
16975 );
16976 std::fs::remove_dir_all(&starting_dir).unwrap();
16977
16978 let corrupt_id = "bad00000-0000-4000-8000-000000000099";
16980 let corrupt_dir = home.join("workers").join("jobs").join(corrupt_id);
16981 std::fs::create_dir_all(&corrupt_dir).unwrap();
16982 std::fs::write(corrupt_dir.join("job.json"), b"{not valid json").unwrap();
16983 let store_err = crate::resume::validate(home, &state.id)
16984 .unwrap_err()
16985 .to_string();
16986 assert!(
16987 store_err.starts_with(
16988 "run already has a live driver: worker store observation failed (conservative protection):"
16989 ),
16990 "{store_err}"
16991 );
16992 assert!(store_err.contains(corrupt_id), "{store_err}");
16993 std::fs::remove_dir_all(&corrupt_dir).unwrap();
16994
16995 state.driver_exited = false;
16997 state.driver_claimed = Some(false);
16998 state.driver_pid = None;
16999 state.driver_started_at = None;
17000 state.save_under(home).unwrap();
17001 let exec_lease = crate::driver::maintenance(home, &state.id).unwrap();
17002 let lease_err = crate::resume::validate(home, &state.id)
17003 .unwrap_err()
17004 .to_string();
17005 let lock_path = home.join("runs").join(&state.id).join("driver.lock");
17006 assert!(
17007 lease_err.starts_with("run already has a live driver: execution lease held"),
17008 "{lease_err}"
17009 );
17010 assert!(
17011 lease_err.contains(&lock_path.display().to_string()),
17012 "{lease_err}"
17013 );
17014 drop(exec_lease);
17015
17016 let pid = std::process::id();
17018 let identity = crate::proc::process_started_at(pid).expect("current process identity");
17019 state.driver_claimed = None;
17020 state.driver_pid = Some(pid);
17021 state.driver_started_at = Some(identity.clone());
17022 state.save_under(home).unwrap();
17023 let pid_err = crate::resume::validate(home, &state.id)
17024 .unwrap_err()
17025 .to_string();
17026 assert!(
17027 pid_err.starts_with("run already has a live driver: live driver process"),
17028 "{pid_err}"
17029 );
17030 assert!(pid_err.contains(&format!("pid={pid}")), "{pid_err}");
17031 assert!(
17032 pid_err.contains(&format!("identity={identity}")),
17033 "{pid_err}"
17034 );
17035
17036 let question = action_question(&state.id, resume_action(&state.id));
17038 let decision = decide_action(home, &t, &question, &PHRASES_EN, |id| {
17039 RunState::load_under(id, home)
17040 });
17041 assert_eq!(decision, ActionDecision::Refuse(pid_err));
17042 }
17043}