Skip to main content

magi/
daemon.rs

1//! The unattended loop: take the next task, run the graph, record what
2//! happened, take the next one.
3//!
4//! This is what turns magi from a command a human types into something an
5//! agent can hand work to. [`crate::queue`] is the mailbox; this module is the
6//! thing that empties it. Nothing here decides *how* a task is implemented —
7//! that is [`crate::graph`] — it only decides which task runs next, and what a
8//! finished run means for the task that produced it.
9//!
10//! # One run at a time, on purpose
11//!
12//! There is no `--jobs` flag and there will not be one. A single run is
13//! already internally parallel: candidates implement concurrently and judges
14//! rank concurrently, so the machine is not idle while one task is in flight.
15//! The real constraint is not CPU but the agent CLIs' quota, and two graphs at
16//! once doubles the burn rate on exactly the resource whose exhaustion produces
17//! [`RunStatus::Stalled`]. Serialising the loop is what keeps a full backlog
18//! from converting the whole day's quota into a pile of untrustworthy verdicts.
19//!
20//! # A crash is legible, and the loop notices on its own
21//!
22//! The task is written as [`crate::queue::TaskStatus::Running`], with its run
23//! id, *before* the graph starts, and is only rewritten once the run reaches a
24//! terminal status. A daemon killed mid-run therefore leaves the task
25//! `Running` and pointing at the run that was in flight. The alternative —
26//! reverting the task to `Queued` on the way out — would hide the abandoned
27//! run and re-spend its quota on the next poll.
28//!
29//! A task left `Running` forever is not the point, though:
30//! [`crate::queue::TaskStatus::runnable`] never offers it again, so a daemon
31//! that died mid-run would otherwise strand its task for good.
32//! [`reclaim_orphaned_running`] runs on every poll and settles exactly the
33//! tasks no live process is actually driving — proven by [`Queue::claim`]
34//! succeeding rather than by a staleness guess — against whatever their last
35//! run actually became, through the same [`settle`] a live finish uses. A run
36//! that genuinely cannot be read still holds its task for a human; the run's
37//! own report explains how far it got.
38//!
39//! # Retries are bounded
40//!
41//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
42//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
43//! exception is a run that ended `Stalled`: the panel collapsed because the
44//! agent CLIs hit their quota, which is a fact about the machine and not about
45//! the task, so it must not spend an attempt. Without that exception a quota
46//! outage would quietly hold the entire backlog, and the operator would come
47//! back to a reset quota and nothing left that the loop is willing to run.
48
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::{Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58use tokio::sync::Notify;
59
60use crate::ask::{self, Questions};
61use crate::clean;
62use crate::conduct::Conductor;
63use crate::config::{Config, MergeMode};
64use crate::graph::Runner;
65use crate::land;
66use crate::notices::{self, Link, Notice};
67use crate::queue::{Queue, Task, TaskStatus};
68use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
69use crate::triage;
70
71/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
72pub const SCHEMA: u32 = 1;
73
74/// How often the status file is refreshed. A reader treats a status file older
75/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
76/// that a busy daemon is never mistaken for a dead one.
77pub const HEARTBEAT: Duration = Duration::from_secs(5);
78
79/// How old a heartbeat may be before a reader calls the daemon dead. Six
80/// missed beats: long enough to survive a slow filesystem, short enough that
81/// a crashed daemon is not still reported as running a task.
82///
83/// The single threshold every reader shares — the web UI's `/api/health` and
84/// `magi doctor` both call [`Reading::running`] rather than each comparing
85/// against their own copy of this number, so a crashed daemon cannot look
86/// alive on one screen and dead on another.
87pub const STALE_SECS: i64 = 30;
88
89/// Default queue poll interval.
90pub const POLL: Duration = Duration::from_secs(5);
91
92/// How old a claim has to be before startup sweeps it. Longer than any run
93/// this graph plausibly takes, so a sweep cannot pull a task out from under a
94/// daemon that is merely slow.
95pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
96
97/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
98/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
99///
100/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
101/// poll, by attempting the task's own claim: a dead pid is proof enough for
102/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
103/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
104/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
105/// age instead, since there is nothing else to check (see
106/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
107/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
108/// task `running` — see
109/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
110/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
111/// conductor well before the mechanical six-hour sweep would, and thirty
112/// minutes is comfortably below `STALE_CLAIM` while still being generous
113/// enough that a task merely late to publish its first [`HEARTBEAT`] is
114/// never mistaken for abandoned.
115pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
116
117/// What the loop is working on, for the status file.
118#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct Current {
121    /// Task id being run.
122    pub task: String,
123    /// Run id the task produced.
124    pub run: String,
125}
126
127/// The daemon's liveness, published to `<home>/daemon.json`.
128///
129/// This is the only interface between the loop and the web UI, which is why it
130/// carries `updated_at` as well as `started_at`: a reader cannot tell a
131/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
132/// can compare the heartbeat against the clock.
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct Status {
135    /// On-disk format version.
136    pub schema: u32,
137    /// Process id, so a human can find or kill the daemon.
138    pub pid: u32,
139    /// When this process started.
140    pub started_at: Timestamp,
141    /// Last heartbeat.
142    pub updated_at: Timestamp,
143    /// True when the queue has nothing runnable.
144    pub idle: bool,
145    /// Every task and run currently in flight. More than one entry means the
146    /// loop is driving more than one run at once — see
147    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
148    /// nothing is running, so a reader never has to treat "no field" and "an
149    /// empty list" as two different kinds of idle.
150    pub current: Vec<Current>,
151    /// Tasks that reached a terminal status in this process.
152    pub completed: usize,
153    /// Queue polls since start, so a wedged loop shows up as a frozen count.
154    pub polls: u64,
155}
156
157impl Status {
158    /// A fresh, idle status for this process.
159    #[must_use]
160    pub fn new() -> Self {
161        let now = Timestamp::now();
162        Self {
163            schema: SCHEMA,
164            pid: std::process::id(),
165            started_at: now,
166            updated_at: now,
167            idle: true,
168            current: Vec::new(),
169            completed: 0,
170            polls: 0,
171        }
172    }
173}
174
175impl Default for Status {
176    fn default() -> Self {
177        Self::new()
178    }
179}
180
181/// How the loop should behave.
182#[derive(Debug, Clone)]
183pub struct Opts {
184    /// Repository used by tasks that name none.
185    pub repo: PathBuf,
186    /// Explicit `magi.toml`, instead of the discovered layer stack.
187    pub config: Option<PathBuf>,
188    /// Queue poll interval.
189    pub poll: Duration,
190    /// Attempts a task gets before it is held for a human.
191    pub max_attempts: usize,
192    /// Drain what is runnable now, then return, instead of waiting for more.
193    pub once: bool,
194    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
195    pub merge: Option<String>,
196    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
197    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
198    /// `None` resolves to [`crate::run::default_worktree_root`] - the
199    /// operator's real `~/wt/<repo>` - the same way a run with no
200    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
201    /// that does not own that directory (a test, an embedding that manages
202    /// worktrees itself) must set this, or every idle tick reclaims worktrees
203    /// out from under whoever actually does.
204    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
221/// How many runs a plain `usize` from config may drive concurrently, floored
222/// at one. A `0` in a config file would otherwise stall the loop entirely -
223/// no runnable task could ever start - which is never what an operator who
224/// wrote `0` meant.
225fn max_concurrent(n: usize) -> usize {
226    n.max(1)
227}
228
229/// Where the status file lives.
230#[must_use]
231pub fn status_path() -> PathBuf {
232    crate::run::home().join("daemon.json")
233}
234
235/// Publish the status file for this process.
236pub fn write_status(status: &Status) -> Result<()> {
237    write_status_to(&status_path(), status)
238}
239
240/// Publish a status to an explicit path.
241///
242/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
243/// on every health poll and must never see a half-written one.
244pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
245    if let Some(parent) = path.parent() {
246        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
247    }
248    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
249    let tmp = path.with_extension("json.tmp");
250    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
251    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
252    Ok(())
253}
254
255/// Delete the status file. Called on the way out so a clean exit reads as
256/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
257pub fn clear_status() {
258    clear_status_at(&status_path());
259}
260
261/// Delete a status file at an explicit path, so the loop's teardown and
262/// [`clear_status`] cannot drift apart: the loop is handed the path it
263/// published to, and a test can watch a temp file disappear.
264fn clear_status_at(path: &Path) {
265    let _ = std::fs::remove_file(path);
266}
267
268/// A cooperative stop, shared with whoever asked the loop to run.
269///
270/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
271/// Ctrl-C listener and the web UI keep others, and every clone points at the
272/// same flag. There is no channel because there is nothing to send — the only
273/// message is "stop", it is idempotent, and a flag cannot be missed by a
274/// receiver that was not listening yet.
275///
276/// The handle also answers the question the operator's screen asks next: a
277/// stop does not take effect until the run in flight has finished, so
278/// [`Stop::finishing`] reports "asked to stop, still working" rather than
279/// leaving a caller to infer it from a heartbeat and hope.
280#[derive(Debug, Clone, Default)]
281pub struct Stop {
282    /// Set once, never cleared: a stop is not something an operator takes back
283    /// half way through, and a clearable flag would let a start racing a stop
284    /// resurrect a loop that is already unwinding.
285    stopped: Arc<AtomicBool>,
286    /// How many runs are in flight, so `finishing` can distinguish a stop
287    /// that has landed from one that is waiting on `execute`. A count, not a
288    /// flag, because more than one run can be in flight at once - see
289    /// [`crate::config::Daemon::max_concurrent_runs`] - and the last one to
290    /// finish is the one that should turn "finishing" off.
291    busy: Arc<std::sync::atomic::AtomicUsize>,
292    /// Wakes the idle wait. Without this a stop would not be seen until the
293    /// poll interval elapsed, and an operator tapping stop on a phone would
294    /// watch a button do nothing for five seconds.
295    wake: Arc<Notify>,
296    /// Handed to the run in flight, so a stop can also mean "park at the next
297    /// node boundary" instead of "finish the whole competition first".
298    pause: crate::graph::Pause,
299}
300
301impl Stop {
302    /// A stop nobody has asked for yet.
303    #[must_use]
304    pub fn new() -> Self {
305        Self::default()
306    }
307
308    /// Ask the loop to stop. Idempotent, and safe to call before the loop
309    /// starts: the flag is checked before the first poll.
310    pub fn stop(&self) {
311        self.stopped.store(true, Ordering::SeqCst);
312        // `notify_one` rather than `notify_waiters` because the loop may not be
313        // parked yet: this stores a permit, so a wait that registers a moment
314        // later returns at once instead of sleeping out the whole interval.
315        self.wake.notify_one();
316    }
317
318    /// Has a stop been asked for?
319    #[must_use]
320    pub fn stopped(&self) -> bool {
321        self.stopped.load(Ordering::SeqCst)
322    }
323
324    /// Has a stop been asked for that has not taken effect yet, because a run
325    /// is still in flight?
326    ///
327    /// This is the state a screen has to be able to show. A stop never abandons
328    /// a run — see [`serve_until`] — so between the tap and the loop's return
329    /// there is a window of tens of minutes in which "running" and "stopped"
330    /// are both misleading answers.
331    #[must_use]
332    pub fn finishing(&self) -> bool {
333        self.stopped() && self.busy_now()
334    }
335
336    /// Ask the loop to stop *and* the run in flight to park at its next node
337    /// boundary.
338    ///
339    /// The plain [`Stop::stop`] never abandons a run, which is right when the
340    /// operator only wants the queue to drain: a competition is tens of
341    /// minutes and its worktrees are paid for. But an operator who wants to
342    /// replace the binary cannot wait out a run that has an hour left, and
343    /// killing the process loses whatever the seats in flight had not written.
344    /// Parking costs at most the node in progress and leaves the run
345    /// resumable.
346    pub fn park(&self) {
347        self.pause.park();
348        self.stop();
349    }
350
351    /// Has a park been asked for?
352    #[must_use]
353    pub fn parking(&self) -> bool {
354        self.pause.parked()
355    }
356
357    /// The pause handle to give a runner.
358    #[must_use]
359    pub fn pause(&self) -> crate::graph::Pause {
360        self.pause.clone()
361    }
362
363    /// Is any run in flight right now?
364    ///
365    /// `finishing` answers "a stop is waiting on a run", which is false until
366    /// someone asks to stop. An upgrade needs the plain question, because it
367    /// is about to be the one asking.
368    #[must_use]
369    pub fn busy_now(&self) -> bool {
370        self.busy.load(Ordering::SeqCst) > 0
371    }
372
373    /// Mark one more run as in flight, for [`Stop::finishing`].
374    fn enter(&self) {
375        self.busy.fetch_add(1, Ordering::SeqCst);
376    }
377
378    /// Mark one run as finished. The last one out is what makes
379    /// [`Stop::busy_now`] false again.
380    fn exit(&self) {
381        self.busy.fetch_sub(1, Ordering::SeqCst);
382    }
383
384    /// Wait out one poll interval, returning early once a stop is asked for.
385    async fn idle(&self, poll: Duration) {
386        tokio::select! {
387            () = tokio::time::sleep(poll) => {}
388            () = self.wake.notified() => {}
389        }
390    }
391}
392
393/// The daemon's published state, read permissively.
394///
395/// This mirrors [`Status`], but is a separate declaration on purpose: every
396/// field defaults, so a status file from an older or newer magi still yields
397/// a usable reading — one this build has never heard of — instead of a parse
398/// error that hides the daemon entirely.
399#[derive(Debug, Clone, Default, Deserialize)]
400#[serde(default)]
401pub struct Reading {
402    /// Format version the daemon claims.
403    pub schema: u32,
404    /// Daemon process id, for an operator who wants to stop it.
405    pub pid: Option<u32>,
406    /// When that process started.
407    pub started_at: Option<Timestamp>,
408    /// Last heartbeat. Absent means the file is unusable, hence not running.
409    pub updated_at: Option<Timestamp>,
410    /// True when the queue had nothing runnable at the last poll.
411    pub idle: bool,
412    /// What the daemon is working on. Empty means idle; more than one entry
413    /// means more than one run is in flight at once.
414    ///
415    /// `deserialize_with` rather than the plain derive: a daemon started
416    /// before this field became a list is still out there writing the old
417    /// shape — a single `{"task":...,"run":...}` object, or its absence —
418    /// on every heartbeat until it is restarted, and a live process reading
419    /// that file during the rollout must still see it as running rather than
420    /// as absent. A bare type change here would fail the whole struct's
421    /// deserialization on a type mismatch, defeating the permissiveness this
422    /// type exists for.
423    #[serde(deserialize_with = "de_current")]
424    pub current: Vec<Current>,
425    /// Tasks this daemon process has finished.
426    pub completed: u64,
427    /// Queue polls this daemon process has made.
428    pub polls: u64,
429}
430
431/// Accept the old single-`Current`-or-absent shape as well as the current
432/// list, so a reader never has to know which build wrote the file.
433fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
434where
435    D: serde::Deserializer<'de>,
436{
437    #[derive(Deserialize)]
438    #[serde(untagged)]
439    enum Shape {
440        Many(Vec<Current>),
441        One(Current),
442    }
443    Ok(
444        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
445            Shape::Many(v) => v,
446            Shape::One(c) => vec![c],
447        }),
448    )
449}
450
451impl Reading {
452    /// Seconds since the last heartbeat, or `None` when there has never been
453    /// one.
454    #[must_use]
455    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
456        self.updated_at
457            .map(|at| (now.as_second() - at.as_second()).max(0))
458    }
459
460    /// Whether the loop counts as running: a heartbeat no older than
461    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
462    /// progress hours after the daemon that owned it was killed.
463    #[must_use]
464    pub fn running(&self, now: Timestamp) -> bool {
465        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
466    }
467}
468
469/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
470/// usable there.
471///
472/// Missing, half-written and unparseable all collapse to `None`, because the
473/// only question a reader asks is whether a daemon is alive, and a file it
474/// cannot read is not evidence that one is.
475#[must_use]
476pub fn read_status(home: &Path) -> Option<Reading> {
477    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
478    serde_json::from_str(&body).ok()
479}
480
481/// Every run a live daemon is working on right now.
482///
483/// One definition of liveness, because deleting a task and deleting a run are
484/// both gated on it from both the CLI and the web UI - four callers that must
485/// never disagree about whether the same thing is in flight. A stale heartbeat
486/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
487/// left at `running` or a run left at `implementing` by a killed daemon is a
488/// leftover record rather than work in progress. More than one entry once
489/// [`crate::config::Daemon::max_concurrent_runs`] is more than one - a caller
490/// after "the one thing in flight" wants [`is_working_on`] or
491/// [`is_working_on_task`], not this directly.
492#[must_use]
493pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
494    read_status(home)
495        .filter(|reading| reading.running(now))
496        .map(|reading| reading.current)
497        .unwrap_or_default()
498}
499
500/// Whether a live daemon is working on this run at this moment.
501#[must_use]
502pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
503    current_work(home, now).iter().any(|c| c.run == run)
504}
505
506/// Whether a live daemon is working on a run whose short id is this one.
507///
508/// For a worktree that has no run record to compare against at all -
509/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
510/// id is not available to hand to [`is_working_on`]. The short id is: a run's
511/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
512/// and it is exactly the gap between the daemon claiming a task and
513/// `RunState::new` saving the first `run.json` that this exists to protect -
514/// a run genuinely in flight but invisible to a scan of `runs/`.
515#[must_use]
516pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
517    current_work(home, now)
518        .iter()
519        .any(|c| crate::run::short_of(&c.run) == short)
520}
521
522/// Whether a live daemon is working on this task at this moment.
523#[must_use]
524pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
525    current_work(home, now).iter().any(|c| c.task == task)
526}
527
528/// Remove claim files whose owner is provably dead, or that have simply
529/// outlived `older_than`, and return the task ids swept.
530///
531/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
532/// destructor, and the orphaned `.lock` file would make its task permanently
533/// unclaimable — the backlog would stop for good at exactly the task that was
534/// in flight when the machine went down.
535///
536/// The pid recorded in the lock is the authority whenever it can be read at
537/// all; age is only a fallback for when it cannot be.
538///
539/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
540///   full stop — dead sweeps the lock immediately, regardless of age; alive
541///   protects it, regardless of age. This is what lets a lock be reclaimed in
542///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
543///   before this daemon even started, next to a `queued` task, no longer has
544///   to sit for six hours before anything notices its owner is gone.
545/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
546///   falls back to `older_than`, since there is nothing else to check.
547///
548/// Age must never override a *positive* liveness confirmation. `sweep`
549/// [`poll`]s concurrently with every attempt this daemon itself has spawned —
550/// see [`InFlightGuard`] — not only between them the way a single sequential
551/// loop once did, so a run that legitimately runs longer than `older_than`
552/// (a multi-round review, a long land wait carried across several resumed
553/// attempts) still has this very process's own live pid sitting in its own
554/// lock file on every later sweep. Deciding by age alone in that case would
555/// delete this daemon's own still-valid claim on its own in-flight task,
556/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
557/// to a second attempt — two `Runner`s writing the same `run.json` and the
558/// same worktree at once. `pid_alive` answering "alive" for anything it
559/// cannot determine (a live process, a pid this build cannot check, one
560/// under another account) is exactly what keeps that path from ever
561/// firing on a guess.
562///
563/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
564/// output unreadable must not be license to guess, and the risk of an
565/// unparseable lock outliving a genuinely dead owner is bounded by an order
566/// of magnitude above any plausible run rather than by a positive check.
567///
568/// Runs on every poll, not only at startup — a daemon up for days must keep
569/// noticing a lock some other, now-dead, daemon left behind just as readily
570/// as one it trips over on the way up.
571pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
572    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
573}
574
575/// [`sweep_stale_claims`] with its process-query boundary supplied by the
576/// caller. This keeps the lock policy testable where process listing is
577/// unavailable, while production still uses the platform query above.
578fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
579where
580    F: Fn(u32) -> bool,
581{
582    let this_process = std::process::id();
583    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
584        .into_iter()
585        .flatten()
586        .flatten()
587        .map(|e| e.path())
588        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
589        .filter(|p| {
590            match std::fs::read_to_string(p)
591                .ok()
592                .and_then(|body| body.trim().parse::<u32>().ok())
593            {
594                // This process wrote it and is asking the question right
595                // now, so it is definitionally still alive - settled without
596                // spawning a helper process at all.
597                Some(pid) if pid == this_process => false,
598                Some(pid) => !pid_alive(pid),
599                None => p
600                    .metadata()
601                    .and_then(|m| m.modified())
602                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
603                    .is_ok_and(|age| age >= older_than),
604            }
605        })
606        .filter(|p| std::fs::remove_file(p).is_ok())
607        .filter_map(|p| {
608            p.file_stem()
609                .and_then(|s| s.to_str())
610                .map(std::borrow::ToOwned::to_owned)
611        })
612        .collect();
613    swept.sort_unstable();
614    swept
615}
616
617/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
618/// no live daemon's heartbeat naming it? Deterministic — no model call, and
619/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
620/// shown.
621fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
622    task.status == TaskStatus::Running
623        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
624        && !is_working_on_task(home, &task.id, now)
625}
626
627/// Every task [`is_stalled`] right now — "止まったタスク" in
628/// `crate::conduct`'s vocabulary.
629fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
630    queue
631        .list()
632        .into_iter()
633        .filter(|t| is_stalled(t, home, now))
634        .collect()
635}
636
637/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
638/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
639/// `Failed`-and-so-also-runnable: a task that already attempted and lost
640/// belongs in [`finished_tasks`], where the question is a recovery, not a
641/// dependency.
642fn queued_tasks(queue: &Queue) -> Vec<Task> {
643    queue
644        .list()
645        .into_iter()
646        .filter(|t| t.status == TaskStatus::Queued)
647        .collect()
648}
649
650/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
651/// タスク" in `crate::conduct`'s vocabulary.
652fn finished_tasks(queue: &Queue) -> Vec<Task> {
653    queue
654        .list()
655        .into_iter()
656        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
657        .collect()
658}
659
660/// Deterministically resolve `Task::blocked_by`: a dependency task that
661/// reached `Done`, or a question that was answered, is removed — no model
662/// involved, on every poll. An answered question's content is copied onto
663/// the task ([`Task::record_answer`]) before its id is dropped, so it
664/// reaches the next `crate::conduct` prompt and the next run's instruction
665/// (see [`instruction_for`]) rather than only clearing the block.
666///
667/// A `blocked_by` id that names neither an existing task nor an existing
668/// question - `magi task rm` (or an operator by hand) deleted it while this
669/// task was still waiting - is caught before any of that: it can never
670/// become `Done` or `Answered`, so the ordinary loop below would otherwise
671/// leave the task `blocked` forever with nothing to notice. Such a task is
672/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
673/// which puts it in front of `crate::triage::run_once`'s own walk the next
674/// time it runs - see that module's doc for why the choice is "ask a human",
675/// never "assume the missing dependency was satisfied and unblock anyway".
676fn resolve_blockers(queue: &Queue, questions: &Questions) {
677    for listed in queue.list() {
678        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
679            continue;
680        }
681        let Ok(_claim) = queue.claim(&listed.id) else {
682            continue;
683        };
684        let Ok(mut task) = queue.get(&listed.id) else {
685            continue;
686        };
687        if task.status != TaskStatus::Blocked {
688            continue;
689        }
690        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
691        if !missing.is_empty() {
692            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason(
693                &task.blocked_by,
694                &missing,
695            )));
696            record(queue, &mut task);
697            continue;
698        }
699        let mut changed = false;
700        for id in task.blocked_by.clone() {
701            if let Ok(dep) = queue.get(&id) {
702                if dep.status == TaskStatus::Done {
703                    task.unblock(&id);
704                    changed = true;
705                }
706                continue;
707            }
708            if let Ok(q) = questions.get(&id)
709                && q.status == ask::QuestionStatus::Answered
710            {
711                let answer = match &q.answer {
712                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
713                    None => String::new(),
714                };
715                task.record_answer(q.summary.clone(), answer);
716                task.unblock(&id);
717                changed = true;
718            }
719        }
720        if changed {
721            record(queue, &mut task);
722        }
723    }
724}
725
726/// Retire an unanswered conductor question after its task no longer refers to
727/// it. Conductor questions use the task id in `Question::run`, so run-based
728/// cleanup cannot observe a manual release or completion.
729///
730/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
731/// own question also carries a `run`, and a run id that happens to collide
732/// with some task's id is not this loop's business — only a conductor
733/// question actually uses the task id that way. One `Questions::list()` scan
734/// is taken up front and matched against the in-memory task set, rather than
735/// calling `Questions::open_for` (a full disk scan on its own) once per task.
736fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
737    let tasks = queue.list();
738    let by_id: std::collections::BTreeMap<&str, &Task> =
739        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
740    let referenced: std::collections::BTreeSet<&str> = tasks
741        .iter()
742        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
743        .collect();
744
745    for mut question in questions.list() {
746        if !question.status.open() || question.node != crate::conduct::NODE {
747            continue;
748        }
749        // Keep questions a task still names, including when the reference
750        // moved to a dependent task.
751        if referenced.contains(question.id.as_str()) {
752            continue;
753        }
754        let Some(task) = by_id.get(question.run.as_str()) else {
755            continue;
756        };
757        question.abandon(format!(
758            "task {} no longer waits for this answer",
759            task.short()
760        ));
761        if let Err(e) = questions.put(&mut question) {
762            tracing::warn!(
763                "could not retire question {} for task {}: {e:#}",
764                question.short(),
765                task.short()
766            );
767        }
768    }
769}
770
771/// What a finished run tells the queue about the task it came from.
772///
773/// A struct rather than a fourth and fifth boolean argument: the two flags
774/// answer different questions about the same run, and a call site passing
775/// `(…, true, false)` is one transposition away from refunding attempts
776/// forever.
777#[derive(Debug, Clone, Copy)]
778pub struct Verdict {
779    /// Where the graph stopped.
780    pub status: RunStatus,
781    /// The run opened a pull request.
782    pub left_pr: bool,
783    /// At least one seat was lost to a rate limit.
784    pub quota_hit: bool,
785    /// The run parked at a node boundary because it was asked to.
786    pub parked: bool,
787    /// The run never produced a single candidate a judge could look at.
788    ///
789    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
790    /// still have another candidate worth judging, in which case the loss was
791    /// not the reason nothing came of the run. This is `true` only when the
792    /// implement wave ended with nothing viable at all.
793    pub no_viable_candidates: bool,
794}
795
796/// Record a finished run against the task it came from.
797///
798/// Kept pure and separate from the loop because this mapping *is* the retry
799/// policy, and a policy that can only be exercised by spawning a graph is a
800/// policy nobody checks. The table:
801///
802/// | run status                           | task becomes        | attempt spent |
803/// |---------------------------------------|---------------------|---------------|
804/// | parked at a boundary                  | `Failed` (requeued) | **no**        |
805/// | `Merged`, `Ready`                      | `Done`               | yes          |
806/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
807/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
808/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
809/// | `Blocked` with a PR                    | `Held`               | yes          |
810/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
811/// | `VerifiedNoop`                          | `Held`               | yes          |
812/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
813///
814/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
815/// deliberately: every candidate agreeing there is nothing to write is not a
816/// machine fact about a rate limit, it is an unverified claim about the
817/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
818/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
819/// claim could be wrong (a misread instruction, a stale check), and closing
820/// the task automatically on an implementer's say-so would be the exact
821/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
822/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
823/// above, which settles through the same [`Task::handed_off`]: `Held` is not
824/// `Failed`-and-requeued, so nothing retries this task on the same unverified
825/// claim regardless of whether the one already-spent attempt is refunded, and
826/// [`Task::release`] resets the count to zero anyway the moment a human looks
827/// at the evidence and lets it run again.
828///
829/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
830/// twice, together. A quorum lost to rate limits is a property of the machine
831/// and not of the task, so the attempt is refunded and a reset quota picks
832/// the work up where it stopped — and that is just as true when every
833/// implement seat lost the same race and `after_implement` bails with nothing
834/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
835/// machine fact. The `no_viable_candidates` guard is what keeps that row
836/// narrow: a `Failed` run that produced a real candidate which then lost for
837/// some other reason still spends the attempt, exactly like the quorum lost
838/// to judges that answered with the wrong shape is ordinary flakiness, and
839/// refunding *that* takes the bound off the retry loop entirely: run e633
840/// stalled with `quota: []` after two judges wrote unusable JSON, was
841/// refunded, and the next attempt paid for a fresh hour-long implement wave
842/// before it could fail the same way. `max_attempts` exists precisely so
843/// that cannot repeat forever.
844///
845/// A non-terminal status means `execute` returned while the graph was still
846/// mid-flight, which is a bug rather than a verdict; it is treated as a
847/// failure so that a task cannot loop on it either.
848///
849/// `left_pr` splits the `Blocked` row, and it is the difference between a run
850/// that failed and a run that finished into a gate. See [`Task::handed_off`].
851pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
852    // A parked run is the operator's own doing, and its work is intact on
853    // disk. The task goes back in line with its attempt refunded so the next
854    // loop resumes the same run - which `one_task` prefers over competing
855    // again - and so that swapping the binary a few times cannot exhaust a
856    // budget meant for agents that actually misbehaved.
857    if verdict.parked {
858        task.stall(detail);
859        return;
860    }
861    match verdict.status {
862        RunStatus::Merged | RunStatus::Ready => task.succeed(),
863        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
864        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
865            task.stall(detail)
866        }
867        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
868        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
869        RunStatus::Blocked => task.fail(detail, max_attempts),
870        RunStatus::VerifiedNoop => task.handed_off(detail),
871        other => task.fail(
872            format!(
873                "the graph stopped at `{}` without reaching a terminal status: {detail}",
874                label(other)
875            ),
876            max_attempts,
877        ),
878    }
879}
880
881/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
882/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
883/// itself has actually finished *and* its own last attempt is provably why:
884/// this loads that run and requires `Merged`/`Ready` before touching
885/// anything earlier in `runs`, since `Task::succeed` can also be called
886/// directly on a task whose last attempt never landed at all.
887///
888/// Called right after whatever call set `task.status` to
889/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
890/// `reclaim`'s, but also every other place a task can be closed by hand
891/// without the loop ever settling it itself: `magi task done`
892/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
893/// (`web::queue_done`). Closing a task by hand — after confirming a manual
894/// GitHub merge, say, exactly the workflow this repository's own
895/// "Landing a run's winner by hand" documents — is just as much "this task's
896/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
897/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
898/// forever, which is the exact backlog this status exists to clear. `pub`
899/// for those two out-of-module callers; everything else about this stays
900/// internal bookkeeping.
901///
902/// A run something is still actually driving is left alone: a
903/// task cannot be `Done` while one of its *own* attempts is still in flight,
904/// so a live one at this point can only be an unrelated process — a manual
905/// `--resume` of this old, now-moot run — and rewriting under it would just
906/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
907/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
908/// pair `run_report`/`run_detail` use for the same question elsewhere:
909/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
910/// --resume` invoked by hand outside it, which `liveness` also checks via
911/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
912/// (already terminal in some other way, or itself mid-run) is left untouched
913/// too.
914///
915/// Best-effort, like the rest of this module's bookkeeping: a load or save
916/// failure here is a `tracing::warn`, not a failed settle, and the next time
917/// this same task's completion is recorded — or a daemon restart replays
918/// `reclaim_orphaned_running` — is another chance to catch up. There is no
919/// separate reconciliation pass; if that gap ever matters in practice, one
920/// can be added then.
921///
922/// `home` is a parameter, not the process-global [`crate::run::home`], for
923/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
924/// calls this with `ui.home`, which is `crate::run::home()` in a real
925/// process but a fixture's own directory under test — falling through to
926/// the global there would read and write through whichever home some other
927/// test in the same binary happened to pin into that `OnceLock` first, not
928/// the run this call actually means.
929pub fn supersede_prior_runs(task: &Task, home: &Path) {
930    let now = Timestamp::now();
931    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
932    // right behind a `Merged`/`Ready` verdict) from one set directly by
933    // `magi task done`/its web equivalent/the conductor on a task whose last
934    // recorded attempt never actually landed - that requires reading the
935    // run itself, which is exactly what this does before trusting anything
936    // in `runs` is safe to relabel.
937    let last_run_succeeded = task
938        .runs
939        .last()
940        .and_then(|id| RunState::load_under(id, home).ok())
941        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
942    for id in task.superseded_attempts(last_run_succeeded) {
943        let mut state = match RunState::load_under(id, home) {
944            Ok(s) => s,
945            Err(e) => {
946                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
947                continue;
948            }
949        };
950        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
951            continue;
952        }
953        let daemon_claims = is_working_on(home, id, now);
954        if state.liveness(daemon_claims) == Liveness::Live {
955            continue;
956        }
957        state.status = RunStatus::Superseded;
958        if let Err(e) = state.save_under(home) {
959            tracing::warn!("could not mark run {id} superseded: {e:#}");
960        }
961    }
962}
963
964/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
965/// finish the moment it was called, because one of its earlier attempts was
966/// still live then - a `magi run --resume` invoked by hand on an old run,
967/// most likely.
968///
969/// That skip is correct at the time (rewriting under a run something is
970/// still actively saving would just be undone), but a task only ever
971/// reaches `Done` once, so without this nothing would ever look at it
972/// again: if that manual process later ends anywhere other than
973/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
974/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
975/// backlog this status exists to clear. Called on the same idle-only
976/// cadence as [`janitor`], next to it rather than folded into it: this
977/// walks `queue` and `janitor` never otherwise needs one.
978///
979/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
980/// more than one attempt, every pass: each call is a handful of local file
981/// reads bounded by that task's own attempt count, the same order of cost
982/// [`clean::fold_due`] already pays scanning every run on disk on the same
983/// cadence, and a task already fully resolved costs one failed liveness
984/// check turned no-op the moment its lingering attempt is no longer live.
985fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
986    for task in queue.list() {
987        if task.status != TaskStatus::Done || task.runs.len() < 2 {
988            continue;
989        }
990        supersede_prior_runs(&task, home);
991    }
992}
993
994/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
995/// task ends up held.
996///
997/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
998/// dead daemon never got back to) share this, so the two cannot drift into
999/// disagreeing about which held tasks get a diagnostic.
1000fn settle_and_diagnose(
1001    task: &mut Task,
1002    verdict: Verdict,
1003    detail: &str,
1004    max_attempts: usize,
1005    state: &RunState,
1006) {
1007    settle(task, verdict, detail, max_attempts);
1008    if task.status == TaskStatus::Held {
1009        task.diagnostic = diagnostic(state);
1010        note_open_question(task, &state.id);
1011    }
1012}
1013
1014/// If `task` is held with a `magi ask` question still open on `run`, name the
1015/// question in [`Task::hold_reason`] rather than leaving the hold reading
1016/// only [`describe`]'s run summary.
1017///
1018/// This is the shape task 20260928-191407-05fd left underspecified: an
1019/// implementer settled a verified no-op and filed a question for the
1020/// operator, and the hold that followed said nothing about the question
1021/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
1022/// existing text ([`is_disk_hold`](crate::triage), the answered-question
1023/// marker) and must keep seeing it unchanged.
1024///
1025/// Best-effort: an unreadable question store must not stop a run from
1026/// settling, so this is a no-op rather than a propagated error when
1027/// [`crate::run::try_home`] has nothing to offer or the store is empty.
1028fn note_open_question(task: &mut Task, run: &str) {
1029    let Some(home) = crate::run::try_home() else {
1030        return;
1031    };
1032    let open = Questions::at(home.join("questions")).open_for(run);
1033    let Some(q) = open.first() else {
1034        return;
1035    };
1036    let base = task.hold_reason.clone().unwrap_or_default();
1037    task.hold_reason = Some(format!(
1038        "{base} - waiting for operator answer to question {}",
1039        q.short()
1040    ));
1041}
1042
1043/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
1044/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
1045/// by some other means entirely, like a manual `magi run` resume that
1046/// finishes the graph outside the queue's bookkeeping.
1047///
1048/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
1049/// `settle` is separate from `attempt`: a task recovered this way must land
1050/// exactly where a live daemon would have put it — the same policy table,
1051/// not a second one that quietly drifts from it — and that is only checkable
1052/// without spawning a real run.
1053fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize) {
1054    match last_run {
1055        Some(state) => {
1056            let verdict = Verdict {
1057                status: state.status,
1058                left_pr: state.pr.is_some(),
1059                quota_hit: !state.quota.is_empty(),
1060                parked: state.parked,
1061                no_viable_candidates: state.viable().is_empty(),
1062            };
1063            let detail = format!(
1064                "recovered a `running` task whose daemon never recorded the outcome: {}",
1065                describe(&state)
1066            );
1067            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1068        }
1069        None => {
1070            let why = "task was `running` with no live daemon and no readable \
1071                       run to recover; held for a human to check what happened";
1072            task.last_error = Some(why.to_owned());
1073            // The phone shows `hold_reason`, so a task held by the machine
1074            // says why there too and not only in `last_error`.
1075            task.hold_machine(Some(why.to_owned()));
1076        }
1077    }
1078}
1079
1080/// Find every task left at `running` that no live process is actually
1081/// driving, and settle each one against whatever its last run became.
1082///
1083/// # Why a claim is proof, not a guess
1084///
1085/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
1086/// `running`, and the guard is held for the task's whole time in that status:
1087/// `attempt` does not return, and the loop does not move past the scope
1088/// holding the claim, until the run has settled. So a `running` task whose
1089/// lock is gone cannot have a live owner — this process or any other —
1090/// without needing a staleness threshold or a pid check the way
1091/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
1092/// task that never got as far as `running` at all. Taking the claim here is
1093/// the whole test: it either fails, because something really does hold it
1094/// and the task is left alone, or it succeeds, which is the proof — and it is
1095/// kept for the rest of the decision so nothing else can start a competing
1096/// run while this one is being written.
1097///
1098/// Called on every poll, not only at startup, for the reason
1099/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
1100/// keep noticing this, not only on the one morning it happened to restart.
1101fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1102    let mut reclaimed = Vec::new();
1103    for listed in queue.list() {
1104        if listed.status != TaskStatus::Running {
1105            continue;
1106        }
1107        let Ok(_claim) = queue.claim(&listed.id) else {
1108            continue;
1109        };
1110        // Re-read under the claim: a release or an edit landed by a human
1111        // between the listing above and the claim just taken must not be
1112        // clobbered by a decision based on the stale copy.
1113        let Ok(mut task) = queue.get(&listed.id) else {
1114            continue;
1115        };
1116        if task.status != TaskStatus::Running {
1117            continue;
1118        }
1119        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1120        // `execute` normally abandons a run's own open questions the moment
1121        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
1122        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
1123        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
1124        // with the question still `open`, because the process died before
1125        // reaching that call. `reclaim` itself stays pure on purpose (see its
1126        // own doc), so the same cleanup runs here instead, against the run
1127        // this reclaim is already reading. `settle_run` costs nothing when
1128        // `execute` already got there first.
1129        if let Some(state) = &last_run
1130            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1131        {
1132            tracing::warn!("abandon questions for {}: {e:#}", state.id);
1133        }
1134        reclaim(&mut task, last_run, max_attempts);
1135        if task.status == TaskStatus::Done {
1136            supersede_prior_runs(&task, &crate::run::home());
1137        }
1138        record(queue, &mut task);
1139        reclaimed.push(task.id.clone());
1140    }
1141    reclaimed
1142}
1143
1144/// Find every run whose `run.json` is provably dead — every seat it still
1145/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
1146/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
1147/// not merely "no daemon claims it" — and fail it, clearing the leftover
1148/// active seats so the run stops reading as `implementing` (or whichever
1149/// node) forever.
1150///
1151/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
1152/// `running`, using whatever `run.json` already says — but nothing in that
1153/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
1154/// stays pure on purpose, see its own doc), so a `run.json` a killed process
1155/// never got back to sits exactly where it was left: `active` full of seats
1156/// nobody will ever answer for, `status` stuck on whatever node was in
1157/// flight. `magi show` already tells an operator this in prose (`no live
1158/// daemon claims this run right now`); this is what makes that fact durable
1159/// on disk, the same way a task's own `TaskStatus::Running` does not get to
1160/// stay stuck once nothing is driving it.
1161///
1162/// Runs on every poll, not only at startup, for the reason
1163/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
1164/// daemon up for days must keep noticing a run some other, now-dead, daemon
1165/// left behind just as readily as one it trips over on the way up.
1166///
1167/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
1168/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
1169/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
1170/// `runs` directory instead: `home` here is a parameter precisely so a test
1171/// can point it away from the operator's real history (see [`drive`]'s own
1172/// doc), and a scan that fell through to the global home anyway would walk
1173/// whichever directory some *other* process or test pinned into that
1174/// `OnceLock` first — mutating runs this call was never handed.
1175fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1176    reclaim_abandoned_runs_with(
1177        home,
1178        now,
1179        crate::proc::pid_status,
1180        crate::proc::process_started_at,
1181    )
1182}
1183
1184/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
1185/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
1186/// for the identical reason: this sweep's real damage (wiping a run's active
1187/// seats and failing it) has to be provable against an injected answer in a
1188/// test, not just the real process table.
1189fn reclaim_abandoned_runs_with<F, G>(
1190    home: &Path,
1191    now: Timestamp,
1192    query: F,
1193    identity: G,
1194) -> Vec<String>
1195where
1196    F: Fn(u32) -> Option<bool>,
1197    G: Fn(u32) -> Option<String>,
1198{
1199    let mut abandoned = Vec::new();
1200    for entry in std::fs::read_dir(home.join("runs"))
1201        .into_iter()
1202        .flatten()
1203        .flatten()
1204    {
1205        let id = entry.file_name().to_string_lossy().into_owned();
1206        if !crate::run::is_run_id(&id) {
1207            continue;
1208        }
1209        // Unreadable is `clean::fold_due`'s problem, not this one's — see
1210        // that module's docs for why a run this cannot parse is left alone
1211        // rather than guessed at. A different schema number is not that: this
1212        // touches only `status` and `active`, never a field whose meaning a
1213        // schema bump changed, so an old record's values serve this exactly
1214        // as well as a current one's (see `clean::read_state`'s own doc for
1215        // the same reasoning applied to folding).
1216        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1217            continue;
1218        };
1219        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1220            continue;
1221        };
1222        if state.status.done() || !state.active_all_overrun(now) {
1223            continue;
1224        }
1225        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
1226        // it", which is also the normal, healthy shape of a manual `magi
1227        // run` / `magi review` sharing this same home — this scan walks
1228        // every run on disk, not only ones this daemon itself started. Such
1229        // a run's active seats can legitimately sit past their own timeout
1230        // for a little while (the CLI finishing up, its result still being
1231        // collected) without the process driving it having died. `liveness`
1232        // is what actually tells the two apart, by corroborating
1233        // `driver_pid` against the process it names — see its own doc. Only
1234        // its strongest, provable answer licenses wiping this run's active
1235        // seats and failing it out from under whatever is still running it.
1236        let daemon_claims = is_working_on(home, &id, now);
1237        if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1238            continue;
1239        }
1240        state.abandon("daemon");
1241        if let Err(e) = state.save_under(home) {
1242            tracing::warn!("could not persist abandoned run {id}: {e:#}");
1243            continue;
1244        }
1245        // This run never passes through `Runner::execute` again, so its end
1246        // is announced here.
1247        if let Some(notice) = notices::run_ended(&state) {
1248            notices::raise_in(home, notice);
1249        }
1250        // The seat that asked is gone for good now, exactly like any other
1251        // door `graph::Runner::settle_questions` closes the moment `status`
1252        // lands somewhere non-resumable - see that method's own doc. Nothing
1253        // else reaches this one before the next `janitor()` startup pass
1254        // (`clean::abandon_settled_questions`), and a daemon that stays up
1255        // for days must not leave an open question badging the operator
1256        // until it happens to restart.
1257        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1258            tracing::warn!("abandon questions for {id}: {e:#}");
1259        }
1260        abandoned.push(id);
1261    }
1262    abandoned
1263}
1264
1265/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
1266///
1267/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
1268/// sets, so there is one loop body rather than two that drift apart the first
1269/// time the retry policy changes on only one of them.
1270pub async fn serve(opts: Opts) -> Result<()> {
1271    serve_until(opts, Stop::new()).await
1272}
1273
1274/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
1275///
1276/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
1277/// mid-node leaves worktrees, branches and agent sessions behind, and every
1278/// agent call already paid for is lost; finishing the run costs the operator a
1279/// wait and saves them a cleanup. A stop therefore only sets a flag: the
1280/// current `execute` runs to its terminal status, the task's outcome is
1281/// recorded, and only then does the loop return. That window is what
1282/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
1283/// still has a second Ctrl-C, which the runtime turns into a process kill —
1284/// and the task left `Running` then tells the next daemon, and the next human,
1285/// where to look.
1286///
1287/// While the queue is empty the stop is honoured within one wakeup rather than
1288/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
1289/// caller that taps stop does not sit through the remainder of a sleep.
1290pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1291    let signal = {
1292        let stop = stop.clone();
1293        tokio::spawn(async move {
1294            if tokio::signal::ctrl_c().await.is_ok() {
1295                stop.stop();
1296                tracing::info!("shutdown requested; a run in flight will be finished first");
1297            }
1298        })
1299    };
1300
1301    let worktrees_root = opts
1302        .worktrees_root
1303        .clone()
1304        .unwrap_or_else(crate::run::default_worktree_root);
1305    let outcome = drive(
1306        &opts,
1307        &Queue::open(),
1308        &status_path(),
1309        &crate::run::home(),
1310        &worktrees_root,
1311        &stop,
1312    )
1313    .await;
1314
1315    signal.abort();
1316    outcome
1317}
1318
1319/// The loop proper: setup, poll, teardown, with the queue and the status file
1320/// supplied rather than discovered.
1321///
1322/// All three of `home`, `worktrees_root` and the queue/status paths are
1323/// parameters rather than resolved here, for the same reason:
1324/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
1325/// so a unit test that pinned it would fight every other test in the binary,
1326/// and a loop that resolved its own worktree bay could only be exercised
1327/// against the operator's real `~/wt/<repo>` - publishing over a live
1328/// daemon's status file, claiming tasks out of a live backlog, and, since
1329/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
1330/// whatever the operator actually has on disk.
1331async fn drive(
1332    opts: &Opts,
1333    queue: &Queue,
1334    status_file: &Path,
1335    home: &Path,
1336    worktrees_root: &Path,
1337    stop: &Stop,
1338) -> Result<()> {
1339    // The status file is a *snapshot*, not a stream of events: a reader only
1340    // ever wants the latest values, and every tick rewrites the whole file
1341    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
1342    // while an mpsc channel would force the loop to re-send unchanged fields on
1343    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
1344    // for no gain. The lock is only ever held across a field assignment, never
1345    // across an await.
1346    let status = Arc::new(Mutex::new(Status::new()));
1347    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1348    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1349
1350    // Read once at startup, not per task: how many runs this loop drives at
1351    // once is a property of the machine running it, not of whichever
1352    // repository a given task happens to name - see
1353    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
1354    // fact in the same sense the agent roster is.
1355    let daemon_cfg = prepare(&opts.repo, opts)
1356        .map(|c| c.daemon)
1357        .unwrap_or_default();
1358    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1359
1360    tracing::info!(
1361        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1362        queue.root().display(),
1363        opts.poll.as_secs(),
1364        opts.max_attempts,
1365        concurrency,
1366        if daemon_cfg.pause_for_interrupts {
1367            ", interrupts enabled"
1368        } else {
1369            ""
1370        }
1371    );
1372
1373    // `--once` drains an already-idle queue without reaching the idle wait,
1374    // but must still perform the startup cleanup.
1375    janitor(&opts.repo, opts, home, worktrees_root).await;
1376    resweep_superseded_attempts(queue, home);
1377
1378    let outcome = poll(
1379        opts,
1380        queue,
1381        &status,
1382        home,
1383        worktrees_root,
1384        stop,
1385        DispatchLimits {
1386            max_concurrent: concurrency,
1387            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1388        },
1389    )
1390    .await;
1391
1392    beat.abort();
1393    clear_status_at(status_file);
1394    outcome
1395}
1396
1397/// Refresh the status file on a fixed tick.
1398///
1399/// Separate from the loop because a run takes tens of minutes: a status file
1400/// written only between tasks would look stale for the whole of every run, and
1401/// a reader would report the daemon dead exactly while it was busiest.
1402async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1403    loop {
1404        tokio::time::sleep(HEARTBEAT).await;
1405        let snapshot = {
1406            let mut guard = lock(&status);
1407            guard.updated_at = Timestamp::now();
1408            guard.clone()
1409        };
1410        if let Err(e) = write_status_to(&path, &snapshot) {
1411            // A failed heartbeat must not take the daemon down: the loop is the
1412            // product, the status file is only the window onto it.
1413            tracing::warn!("could not refresh the daemon status file: {e:#}");
1414        }
1415    }
1416}
1417
1418/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
1419/// if so, whether that wait is over.
1420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1421enum LandResume {
1422    /// The task's last run is not parked on a land approval; schedule it
1423    /// like any other candidate.
1424    NotLanding,
1425    /// Parked in `land`, waiting on a question nobody has answered yet.
1426    /// Left alone: attempting it now would only re-observe the same pull
1427    /// request and park again, spending a `gh` call on a decision that has
1428    /// not changed since the last time this was checked.
1429    StillWaiting,
1430    /// Parked in `land`, and the question is settled - answered or
1431    /// abandoned. Resuming this is the one kind of candidate that must not
1432    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
1433    Ready,
1434}
1435
1436/// Classify a runnable candidate by whether it is parked on a land-merge
1437/// approval. Read-only - no claim taken, nothing written - so it is cheap
1438/// enough to call on every candidate, every poll.
1439fn land_resume_state(task: &Task) -> LandResume {
1440    let Some(run_id) = task.runs.last() else {
1441        return LandResume::NotLanding;
1442    };
1443    let Ok(state) = RunState::load(run_id) else {
1444        return LandResume::NotLanding;
1445    };
1446    if state.status != RunStatus::Landing || !state.parked {
1447        return LandResume::NotLanding;
1448    }
1449    let store = ask::Questions::open();
1450    let waiting = store
1451        .list()
1452        .into_iter()
1453        .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
1454        .max_by(|a, b| a.id.cmp(&b.id));
1455    let Some(mut q) = waiting else {
1456        return LandResume::Ready;
1457    };
1458    if !q.status.open() {
1459        return LandResume::Ready;
1460    }
1461    // `ask::ask_and_wait`'s own deadline is what used to retire a question
1462    // nobody ever answered; land's approval bypasses that wait entirely (see
1463    // `land::approval_gate`), so the same deadline has to be enforced here
1464    // instead, or `graph.answer_timeout` silently stops meaning anything for
1465    // a land approval and a run can sit `StillWaiting` forever with nobody
1466    // told to look at it.
1467    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
1468    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
1469    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
1470        q.abandon(format!(
1471            "no answer within {}s of asking",
1472            timeout.as_secs().max(1)
1473        ));
1474        // If this can't be persisted, do not treat the wait as settled on a
1475        // guess: fall through and try again next poll.
1476        if store.put(&mut q).is_ok() {
1477            return LandResume::Ready;
1478        }
1479    }
1480    LandResume::StillWaiting
1481}
1482
1483/// How often the loop rechecks for new work while something it already
1484/// started is still running, rather than sleeping out the whole
1485/// [`Opts::poll`] interval.
1486///
1487/// Short on purpose: this is what lets a land-merge approval that comes back
1488/// while another task is mid-competition be noticed and resumed within a
1489/// fraction of a second, not within the next multi-second poll.
1490const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
1491
1492/// How often [`poll`] rechecks the shared build cache against its cap at a
1493/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
1494/// waiting for the queue to run dry.
1495///
1496/// A queue that never empties means the `janitor` call at the bottom of this
1497/// loop's fully-idle branch can go unreached for as long as the backlog
1498/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
1499/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
1500/// 81.8 GiB an idle-only check let it reach before this existed, and it is
1501/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
1502/// backlog of short tasks does not pay for that walk on every poll.
1503const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
1504
1505/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
1506/// in `Status::current` - on drop, so both are released even if the attempt
1507/// panics rather than returning.
1508///
1509/// A `Drop` impl rather than statements written after the `.await` it
1510/// guards: a panic unwinds straight past code placed "after" a call, and
1511/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
1512/// that ruling a panic out there is not a bet this loop can make. Without
1513/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
1514/// forever - the idle branch in [`poll`], and with it the janitor, would
1515/// never run again - and a ghost entry in `Status::current` naming a task
1516/// nothing is still working on.
1517struct InFlightGuard<'a> {
1518    status: &'a Arc<Mutex<Status>>,
1519    stop: &'a Stop,
1520    task_id: &'a str,
1521}
1522
1523impl Drop for InFlightGuard<'_> {
1524    fn drop(&mut self) {
1525        lock(self.status).current.retain(|c| c.task != self.task_id);
1526        self.stop.exit();
1527    }
1528}
1529
1530/// State of [`poll`]'s own interrupt-scheduling sequence - see
1531/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
1532/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
1533/// both kept free of `Task`'s non-identity fields on purpose: every decision
1534/// here turns only on task ids and which ones are in flight, so the "never
1535/// more than one run at once" and "exactly one resume" invariants can be
1536/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
1537/// queue - which is exactly the coverage this feature's first two attempts
1538/// were missing.
1539///
1540/// Deliberately in-memory only, not written to disk anywhere: a daemon
1541/// restart mid-sequence loses track of which run it had asked to park and
1542/// which task was meant to run first, and simply falls back to `Idle` -
1543/// see [`drive`]'s own setup. The parked run itself is not lost - it is
1544/// sitting in the queue exactly like any other resumable, interrupted task,
1545/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
1546/// just resumes on the ordinary priority order rather than guaranteed to go
1547/// first. Giving that guarantee a crash-proof memory would mean a new queue
1548/// field and a recovery ordering to go with it, which is exactly the
1549/// complexity this feature's constraints rule out for the one property that
1550/// actually matters: at most one run, ever, at once.
1551#[derive(Debug, Clone, PartialEq, Eq)]
1552enum Interrupt {
1553    /// No interrupt sequence in progress. Ordinary dispatch applies.
1554    Idle,
1555    /// `interrupt_task` is runnable and exactly one other run is in flight;
1556    /// `parked` names that one task's id. Dispatch is withheld from
1557    /// everyone, including `interrupt_task` itself, until it has left
1558    /// flight - only then is `interrupt_task` let through.
1559    ///
1560    /// `parked` is a `Vec` rather than a bare id for symmetry with
1561    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
1562    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
1563    /// when exactly one run is in flight, so it is guaranteed to hold
1564    /// exactly one entry in practice - see that branch's own doc for why
1565    /// more than one is deliberately never attempted.
1566    Parking {
1567        parked: Vec<String>,
1568        interrupt_task: String,
1569    },
1570    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
1571    /// withheld from everyone until it leaves flight - merged, failed, held,
1572    /// it makes no difference - at which point the sequence moves to
1573    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
1574    /// going straight to `Idle` would hand `parked` back to ordinary
1575    /// priority-order dispatch, where a higher-priority task filed in the
1576    /// meantime could start ahead of it.
1577    Running {
1578        parked: Vec<String>,
1579        interrupt_task: String,
1580    },
1581    /// `interrupt_task` left flight; `parked` still names the one run this
1582    /// sequence owes a resume. Dispatch is withheld from everyone except
1583    /// that task - see [`interrupt_gate`] - so the resume this feature
1584    /// promises is never raced by, or run alongside, an unrelated candidate.
1585    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
1586    /// own doc on abandonment - the moment it is no longer runnable at all.
1587    Resuming { parked: Vec<String> },
1588}
1589
1590/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
1591/// and `runnable` are read-only snapshots of this tick's reality, and the
1592/// only side effect the caller still owes the world is asking whichever
1593/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
1594/// site.
1595///
1596/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
1597/// accepted rather than a narrower type because that is what [`poll`] already
1598/// has on hand from [`runnable`], and building a second, smaller list on
1599/// every tick just to satisfy this signature would cost more than it proves.
1600///
1601/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
1602/// back to a task they are waiting on no longer being [`runnable`] - held,
1603/// blocked, deleted, or finished by some other means entirely, all of which
1604/// an operator can do to a task sitting in the queue with no claim on it at
1605/// all, at any moment, interrupt sequence or not. Without this check the
1606/// sequence would wait forever for a dispatch that can never come, and
1607/// `interrupt_gate` would withhold every other task in the queue right along
1608/// with it - a single `magi task hold` on the wrong id turning into a
1609/// daemon that never dispatches anything again.
1610fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
1611    match state {
1612        Interrupt::Idle => {
1613            // Not just "something to interrupt": exactly one thing. More
1614            // than one run in flight only happens above the default
1615            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
1616            // one resume, never run alongside anything else" only because
1617            // it is only ever seeded with exactly one id - see
1618            // `Interrupt::Resuming`'s own doc on why releasing more than one
1619            // parked id back to ordinary dispatch cannot be made safe
1620            // against that same setting's own extra concurrency slots.
1621            // Waiting here for the herd to settle to one is the
1622            // simplification this feature's own constraints ask for rather
1623            // than a second concurrency model to reconcile with the first.
1624            if in_flight.len() != 1 {
1625                return Interrupt::Idle;
1626            }
1627            match runnable.iter().find(|t| t.interrupt) {
1628                Some(t) => Interrupt::Parking {
1629                    parked: in_flight.to_vec(),
1630                    interrupt_task: t.id.clone(),
1631                },
1632                None => Interrupt::Idle,
1633            }
1634        }
1635        Interrupt::Parking {
1636            parked,
1637            interrupt_task,
1638        } => {
1639            if in_flight.iter().any(|id| parked.contains(id)) {
1640                // Still waiting for what was in flight to actually stop.
1641                Interrupt::Parking {
1642                    parked,
1643                    interrupt_task,
1644                }
1645            } else if in_flight.contains(&interrupt_task) {
1646                Interrupt::Running {
1647                    parked,
1648                    interrupt_task,
1649                }
1650            } else if runnable.iter().any(|t| t.id == interrupt_task) {
1651                // The parked run(s) are gone, but the interrupt task has not
1652                // been dispatched yet on this tick - `interrupt_gate` is
1653                // what lets it through next.
1654                Interrupt::Parking {
1655                    parked,
1656                    interrupt_task,
1657                }
1658            } else {
1659                // The interrupt task itself is no longer runnable - see this
1660                // function's own doc on abandonment. The parked run(s) still
1661                // get their guaranteed resume; there is simply no interrupt
1662                // to run ahead of them any longer.
1663                Interrupt::Resuming { parked }
1664            }
1665        }
1666        Interrupt::Running {
1667            parked,
1668            interrupt_task,
1669        } => {
1670            if in_flight.contains(&interrupt_task) {
1671                Interrupt::Running {
1672                    parked,
1673                    interrupt_task,
1674                }
1675            } else {
1676                // The interrupt task's own run reached a terminal status,
1677                // whichever one - this is the *only* trigger that moves the
1678                // sequence on, driven straight off the same in-flight
1679                // bookkeeping `poll` already reaps every tick, not a second,
1680                // independent poll of anything.
1681                Interrupt::Resuming { parked }
1682            }
1683        }
1684        Interrupt::Resuming { parked } => {
1685            if in_flight.iter().any(|id| parked.contains(id)) {
1686                // One of the parked runs has been dispatched - the resume
1687                // this sequence owed is fulfilled. Whatever else is left in
1688                // `parked` (ordinarily nothing, at the default concurrency
1689                // of one) rejoins ordinary priority-order dispatch, same as
1690                // any other runnable task.
1691                Interrupt::Idle
1692            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
1693                Interrupt::Resuming { parked }
1694            } else {
1695                // Abandonment (see this function's own doc): nothing left in
1696                // `parked` is even runnable any longer.
1697                Interrupt::Idle
1698            }
1699        }
1700    }
1701}
1702
1703/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
1704/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
1705/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
1706/// indistinguishable from any other runnable task - exactly the "off does
1707/// nothing" this feature promises.
1708fn advance_interrupt_tick(
1709    enabled: bool,
1710    state: Interrupt,
1711    in_flight: &[String],
1712    runnable: &[Task],
1713) -> Interrupt {
1714    if !enabled {
1715        return Interrupt::Idle;
1716    }
1717    advance_interrupt(state, in_flight, runnable)
1718}
1719
1720/// Which of this tick's runnable candidates the interrupt sequence actually
1721/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
1722/// each half is assertable on its own: this is the half that keeps a
1723/// competition and an interrupt from ever running at the same moment.
1724fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
1725    match state {
1726        Interrupt::Idle => candidates,
1727        Interrupt::Parking {
1728            parked,
1729            interrupt_task,
1730        } => {
1731            if in_flight.iter().any(|id| parked.contains(id)) {
1732                Vec::new()
1733            } else {
1734                candidates
1735                    .into_iter()
1736                    .filter(|t| &t.id == interrupt_task)
1737                    .collect()
1738            }
1739        }
1740        Interrupt::Running { .. } => Vec::new(),
1741        // At most one: even if `parked` names more than one id (more than
1742        // one run was in flight when the sequence began, only possible
1743        // above the default `max_concurrent_runs = 1`), only the first match
1744        // is offered. Capping this to a single candidate - not merely to
1745        // `parked`'s own ids - is what makes "exactly one resume, never two
1746        // dispatched together" true regardless of how many ordinary slots
1747        // happen to be free this tick.
1748        Interrupt::Resuming { parked } => candidates
1749            .into_iter()
1750            .find(|t| parked.contains(&t.id))
1751            .into_iter()
1752            .collect(),
1753    }
1754}
1755
1756/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
1757/// bundled into one parameter so `poll`'s own signature stays readable -
1758/// see [`drive`]'s call site for where these are actually read.
1759struct DispatchLimits {
1760    /// How many *ordinary* candidates run at once. See
1761    /// [`crate::config::Daemon::max_concurrent_runs`].
1762    max_concurrent: usize,
1763    /// See [`crate::config::Daemon::pause_for_interrupts`].
1764    pause_for_interrupts: bool,
1765}
1766
1767/// Which semaphore, if any, dispatching a candidate should draw its permit
1768/// from.
1769///
1770/// Pure and separate from [`poll`]'s loop body for the same reason
1771/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
1772/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
1773/// exactly the policy this feature adds, and a policy only exercisable by
1774/// running the whole loop is a policy nobody checks.
1775#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1776enum PermitKind {
1777    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
1778    /// Checked first - a task can be both a land resume and marked
1779    /// [`Task::urgent`], and the resume's own "must not queue behind
1780    /// anything" guarantee takes precedence.
1781    None,
1782    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
1783    /// (never in addition to trying) the ordinary pool. This is what lets
1784    /// an urgent task dispatch while every ordinary slot is already checked
1785    /// out, and what stops a second urgent task from opening a third run: it
1786    /// waits on this same one-slot semaphore rather than falling through to
1787    /// the ordinary one.
1788    Urgent,
1789    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
1790    /// above.
1791    Ordinary,
1792}
1793
1794/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
1795/// own boolean, already computed by the caller from [`land_resume_state`].
1796fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
1797    if priority {
1798        PermitKind::None
1799    } else if urgent {
1800        PermitKind::Urgent
1801    } else {
1802        PermitKind::Ordinary
1803    }
1804}
1805
1806/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
1807/// teardown and cannot skip the teardown on an early return.
1808///
1809/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
1810/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
1811/// land approval that has since been answered is dispatched outside that
1812/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
1813/// the whole point of parking there is that it must not queue behind
1814/// whatever else the loop happens to be running, even at the default of one.
1815/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
1816/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
1817/// these exemptions is still subject to the interrupt gate below, urgent
1818/// included: a land-resume or urgent candidate is exactly as much "something
1819/// else running" as an ordinary one from the interrupt sequence's point of
1820/// view, and letting either slip through while a run is being parked, or
1821/// while the interrupt task itself has the floor, is precisely the second
1822/// run 75dd's own "at most one run, ever, at once" guarantee must never
1823/// allow - see [`Interrupt`]'s own doc.
1824async fn poll(
1825    opts: &Opts,
1826    queue: &Queue,
1827    status: &Arc<Mutex<Status>>,
1828    home: &Path,
1829    worktrees_root: &Path,
1830    stop: &Stop,
1831    limits: DispatchLimits,
1832) -> Result<()> {
1833    let DispatchLimits {
1834        max_concurrent,
1835        pause_for_interrupts,
1836    } = limits;
1837    // Only consulted by `once`, where a task that just failed is still
1838    // `runnable` and would otherwise be picked up again inside the same drain.
1839    // In the long-running mode a later poll retrying a failed task is the point,
1840    // and the attempt counter is what bounds it.
1841    let mut attempted: Vec<String> = Vec::new();
1842    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
1843    // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
1844    // entirely separate from `sem`: an urgent candidate must dispatch
1845    // alongside whatever `sem` already has checked out, never by waiting for
1846    // one of those ordinary slots to free up and never by growing
1847    // `max_concurrent_runs` itself. Sized at one, not unbounded - see
1848    // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
1849    // first on this same slot rather than opening a third run.
1850    let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
1851    // A quota hit is a fact about the machine, not the task that happened to
1852    // surface it, and every other *ordinary* candidate is no less likely to
1853    // hit the same wall - see the warning below. A land-merge resume is
1854    // exempt: it is a human decision finishing, not a fresh competition, and
1855    // must not sit out a quota cooldown it did not cause.
1856    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
1857    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
1858    let mut conductor = Conductor::new();
1859    // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
1860    // a congested queue would otherwise starve of the fully-idle branch below.
1861    let mut cache_last_checked: Option<Timestamp> = None;
1862    // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
1863    let mut interrupt = Interrupt::Idle;
1864    // The `Pause` handed to each dispatched candidate's own `Runner` - see
1865    // `attempt`'s new parameter - kept here so the tick that decides to park
1866    // a run for an interrupt can reach that specific run's handle and no
1867    // other's. Pruned to whatever is still in flight at the top of every
1868    // tick, so a finished attempt's handle does not linger.
1869    let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
1870        std::collections::HashMap::new();
1871
1872    while !stop.stopped() {
1873        lock(status).polls += 1;
1874
1875        // Reap whatever finished since the last tick without blocking on
1876        // anything still running. `InFlightGuard` already released the slot
1877        // even if the spawned attempt panicked; this only surfaces that it
1878        // happened, since a panic swallowed here otherwise leaves no trace.
1879        while let Some(result) = inflight.try_join_next() {
1880            if let Err(e) = result {
1881                tracing::error!("a spawned attempt did not finish cleanly: {e}");
1882                notices::raise(Notice::error(
1883                    "loop:attempt",
1884                    "A queued attempt ended abnormally; check the task it was running.",
1885                ));
1886            }
1887        }
1888
1889        let swept = sweep_stale_claims(queue, STALE_CLAIM);
1890        if !swept.is_empty() {
1891            tracing::warn!(
1892                "swept {} stale claim(s) left behind by an earlier daemon: {}",
1893                swept.len(),
1894                swept.join(", ")
1895            );
1896        }
1897        // Capture stalled work before reclaiming it. A dead daemon's ordinary
1898        // lock is swept and reclaimed in this same poll, but the conductor
1899        // must still see that it was stranded rather than only its mechanical
1900        // terminal state.
1901        let now = Timestamp::now();
1902
1903        // No run this daemon spawned is mid-compile right now, whether or
1904        // not another candidate is about to start - see
1905        // `maybe_prune_cache_between_runs`'s own doc for why this cannot
1906        // wait for the queue to run dry.
1907        if !stop.busy_now() {
1908            maybe_prune_cache_between_runs(
1909                &opts.repo,
1910                opts,
1911                home,
1912                stop,
1913                &mut cache_last_checked,
1914                now,
1915            )
1916            .await;
1917        }
1918
1919        let stalled = stalled_tasks(queue, home, now);
1920        let stalled_ids: std::collections::BTreeSet<_> =
1921            stalled.iter().map(|task| task.id.clone()).collect();
1922        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
1923        if !reclaimed.is_empty() {
1924            tracing::warn!(
1925                "reclaimed {} task(s) left `running` by a daemon that never \
1926                 recorded the outcome: {}",
1927                reclaimed.len(),
1928                reclaimed.join(", ")
1929            );
1930        }
1931        let abandoned_runs = reclaim_abandoned_runs(home, now);
1932        if !abandoned_runs.is_empty() {
1933            tracing::warn!(
1934                "failed {} run(s) left behind by a killed process, past every \
1935                 active seat's own timeout: {}",
1936                abandoned_runs.len(),
1937                abandoned_runs.join(", ")
1938            );
1939        }
1940
1941        // `home`, not `ask::Questions::open()`'s own process-global default:
1942        // `poll` is handed its home explicitly precisely so a test can point
1943        // it elsewhere, the same reason `Queue::at` and the status file path
1944        // are parameters rather than resolved here - see `drive`'s own doc.
1945        let questions = Questions::at(home.join("questions"));
1946
1947        // Deterministic: no model, run before the conductor sees anything so
1948        // its input reflects the queue's current, already-resolved state.
1949        resolve_blockers(queue, &questions);
1950        reconcile_task_questions(queue, &questions);
1951
1952        // The conductor gets one look per cycle, right before the loop takes
1953        // its next task, and only when there is something new to look at -
1954        // see `Conductor::worth_a_look`'s own doc for why "stalled is
1955        // non-empty" is the wrong test. Checked before `prepare` so an
1956        // unchanged cycle never pays for a synchronous config load.
1957        let finished: Vec<Task> = finished_tasks(queue)
1958            .into_iter()
1959            .filter(|task| !stalled_ids.contains(&task.id))
1960            .collect();
1961        let queued = queued_tasks(queue);
1962        // An empty queue has nothing to arrange. In particular, do not let
1963        // the conductor's initial snapshot cause synchronous config I/O
1964        // between the caller's stop notification and the idle wait below.
1965        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
1966            && conductor.worth_a_look(queue, &stalled, &finished)
1967        {
1968            match prepare(&opts.repo, opts) {
1969                Ok(cfg) => {
1970                    conductor
1971                        .maybe_run(
1972                            &cfg,
1973                            &opts.repo,
1974                            queue,
1975                            &questions,
1976                            home,
1977                            &queued,
1978                            &stalled,
1979                            &finished,
1980                            opts.max_attempts,
1981                        )
1982                        .await;
1983                }
1984                Err(e) => {
1985                    tracing::warn!("conductor: no config: {e:#}");
1986                    notices::raise(Notice::warn(
1987                        "loop:no-config",
1988                        "The loop could not read this repository's config, so held tasks are not being triaged.",
1989                    ));
1990                }
1991            }
1992        }
1993
1994        let candidates: Vec<Task> = runnable(queue)
1995            .into_iter()
1996            .filter(|t| !opts.once || !attempted.contains(&t.id))
1997            .collect();
1998
1999        // A task id only stays a key here while its attempt is genuinely in
2000        // flight; `status.current` is the same liveness fact `InFlightGuard`
2001        // maintains for the phone's own status file, so this piggybacks on
2002        // it rather than tracking a second copy of the same thing.
2003        let in_flight: Vec<String> = lock(status)
2004            .current
2005            .iter()
2006            .map(|c| c.task.clone())
2007            .collect();
2008        interrupt_pauses.retain(|id, _| in_flight.contains(id));
2009
2010        interrupt =
2011            advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2012        if let Interrupt::Parking {
2013            parked,
2014            interrupt_task,
2015        } = &interrupt
2016        {
2017            let reason = format!(
2018                "task {} asked to run first",
2019                crate::run::short_of(interrupt_task)
2020            );
2021            for id in parked {
2022                if let Some(pause) = interrupt_pauses.get(id) {
2023                    pause.park_because(reason.clone());
2024                }
2025            }
2026        }
2027        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2028
2029        let cooling_down =
2030            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2031
2032        let mut started_any = false;
2033        for candidate in candidates {
2034            if stop.stopped() {
2035                break;
2036            }
2037
2038            let resume = land_resume_state(&candidate);
2039            if resume == LandResume::StillWaiting {
2040                continue;
2041            }
2042            let priority = resume == LandResume::Ready;
2043
2044            if !priority && cooling_down {
2045                continue;
2046            }
2047            let permit = match permit_kind(priority, candidate.urgent) {
2048                PermitKind::None => None,
2049                PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
2050                    Ok(p) => Some(p),
2051                    // The one urgent slot is already spoken for by another
2052                    // `--urgent` task's run. Keep looking rather than falling
2053                    // back to the ordinary pool - see `PermitKind::Urgent`'s
2054                    // own doc - a later candidate might still be an ordinary
2055                    // task with a free slot, or another priority resume.
2056                    Err(_) => continue,
2057                },
2058                PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
2059                    Ok(p) => Some(p),
2060                    // No ordinary slot free right now. A later candidate in
2061                    // this same list might still be a priority resume or an
2062                    // urgent task, so keep looking rather than stopping here.
2063                    Err(_) => continue,
2064                },
2065            };
2066
2067            // A claim we cannot take means another daemon, or a human running
2068            // `magi run`, got there first. That is not the task's fault and
2069            // must not spend one of its attempts: move to the next candidate
2070            // rather than recording a failure.
2071            let Ok(claim) = queue.claim(&candidate.id) else {
2072                tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2073                continue;
2074            };
2075            // Re-read under the claim: the task on disk may have been held or
2076            // edited between the listing and the lock.
2077            let mut task = match queue.get(&candidate.id) {
2078                Ok(t) if t.status.runnable() => t,
2079                Ok(_) => continue,
2080                Err(e) => {
2081                    tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2082                    continue;
2083                }
2084            };
2085            let task_id = task.id.clone();
2086            attempted.push(task_id.clone());
2087            lock(status).idle = false;
2088            // A stop asked for from here on is "finishing", not "stopped": the
2089            // run gets to reach a terminal status before the loop returns.
2090            stop.enter();
2091            started_any = true;
2092
2093            // A fresh, unshared handle - never `stop.pause()` - so parking
2094            // this run for an interrupt cannot leak into any other run this
2095            // loop ever drives. See `Pause`'s own doc.
2096            let run_pause = crate::graph::Pause::new();
2097            interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2098
2099            let opts = opts.clone();
2100            let queue = queue.clone();
2101            let status = Arc::clone(status);
2102            let stop = stop.clone();
2103            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
2104            inflight.spawn(async move {
2105                // Held for the whole attempt: dropping either at the end of
2106                // this task is what releases the claim and, for an ordinary
2107                // candidate, frees its concurrency slot back to the loop.
2108                let _claim = claim;
2109                let _permit = permit;
2110                // See `InFlightGuard`: this must survive a panic inside `attempt`.
2111                let _inflight = InFlightGuard {
2112                    status: &status,
2113                    stop: &stop,
2114                    task_id: &task_id,
2115                };
2116                let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2117                lock(&status).completed += 1;
2118                // A quota loss is a fact about the machine, not this task, and
2119                // the next ordinary candidate the loop offers is no less
2120                // likely to hit the same wall: without a cooldown here a
2121                // whole backlog can be run - and failed - in the seconds it
2122                // takes each attempt to notice the CLI is out of quota.
2123                let now = Timestamp::now();
2124                if let Some(until) = cooldown_until(&quota, now) {
2125                    let wait = until.as_second() - now.as_second();
2126                    *lock(&quota_cooldown_until) = Some(until);
2127                    let hint = quota
2128                        .iter()
2129                        .find(|q| q.reset.is_some())
2130                        .and_then(|q| q.reset.as_deref());
2131                    match hint {
2132                        Some(h) => tracing::warn!(
2133                            "quota hit; waiting {wait}s before taking another ordinary task \
2134                             (CLI reported reset: {h})"
2135                        ),
2136                        None => tracing::warn!(
2137                            "quota hit; waiting {wait}s before taking another ordinary task \
2138                             (no reset hint reported)"
2139                        ),
2140                    }
2141                }
2142            });
2143        }
2144
2145        if started_any {
2146            continue;
2147        }
2148
2149        if stop.busy_now() {
2150            // Something started on an earlier tick is still running. Recheck
2151            // soon rather than sleeping out the whole poll interval - a freed
2152            // slot, or a land approval answered mid-run, must not sit idle
2153            // for it.
2154            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2155            continue;
2156        }
2157
2158        // Truly idle: nothing new to start and nothing still running.
2159        lock(status).idle = true;
2160        if opts.once {
2161            // A one-shot drain must perform the same post-work cleanup as a
2162            // daemon that reached a normal idle interval. The startup pass
2163            // cannot see runs or cache files produced by this drain.
2164            janitor(&opts.repo, opts, home, worktrees_root).await;
2165            resweep_superseded_attempts(queue, home);
2166            triage_held(queue, home, opts).await;
2167            break;
2168        }
2169        stop.idle(opts.poll).await;
2170        if stop.stopped() {
2171            continue;
2172        }
2173        // Housekeeping only after a full quiet interval. Running it before
2174        // the first idle wait can block the executor while an operator's
2175        // stop request is waiting to be scheduled, defeating Stop's retained
2176        // wake permit. No run can start while this branch is active, so the
2177        // janitor still never races an in-flight compile.
2178        janitor(&opts.repo, opts, home, worktrees_root).await;
2179        resweep_superseded_attempts(queue, home);
2180        triage_held(queue, home, opts).await;
2181    }
2182
2183    // Never return while a run is still in flight, whichever way the loop
2184    // above exited: a stop only sets a flag - see `serve_until` - and
2185    // returning here while `inflight` still holds spawned work would abandon
2186    // it exactly as a mid-node kill would.
2187    while let Some(result) = inflight.join_next().await {
2188        if let Err(e) = result {
2189            tracing::error!("a spawned attempt did not finish cleanly: {e}");
2190            notices::raise(Notice::error(
2191                "loop:attempt",
2192                "A queued attempt ended abnormally; check the task it was running.",
2193            ));
2194        }
2195    }
2196    Ok(())
2197}
2198
2199/// Run one claimed task to a terminal status and record the outcome.
2200///
2201/// Every transition is flushed to the queue as it happens, so the state on disk
2202/// is what actually occurred rather than what this process still intends to
2203/// write.
2204async fn attempt(
2205    opts: &Opts,
2206    queue: &Queue,
2207    status: &Arc<Mutex<Status>>,
2208    stop: &Stop,
2209    interrupt_pause: crate::graph::Pause,
2210    task: &mut Task,
2211) -> Vec<QuotaLoss> {
2212    let repo = repo_for(task, &opts.repo);
2213    tracing::info!(
2214        "task {} — {} (repo {})",
2215        task.short(),
2216        task.title,
2217        repo.display()
2218    );
2219
2220    let mut config = match prepare(&repo, opts) {
2221        Ok(c) => c,
2222        Err(e) => {
2223            // A setup failure spends an attempt even though no run was minted.
2224            // Without that, a task naming a repository that does not exist
2225            // would be retried at every poll for as long as the daemon lives.
2226            task.attempts += 1;
2227            task.fail(format!("config: {e:#}"), opts.max_attempts);
2228            record(queue, task);
2229            return Vec::new();
2230        }
2231    };
2232    apply_solo(&mut config, task);
2233
2234    // The free-space gate, checked *before* anything is minted: a task that
2235    // waits out a full disk costs nothing yet, and must not spend an attempt
2236    // or start a run the machine cannot finish. Held tasks stay in the list
2237    // for the human to see, and `magi task release` re-queues them when space
2238    // comes back - the same recovery as any other hold. A volume whose free
2239    // space cannot be measured closes the gate too: starting a run blind on a
2240    // disk that may be full is how the machine ends up with 6.7 GB free.
2241    if let Some(reason) = disk_gate(&repo, &config) {
2242        task.last_error = Some(reason.clone());
2243        task.hold_machine(Some(reason.clone()));
2244        record(queue, task);
2245        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2246        // Stable wording - the free-space figures live in the task's hold
2247        // reason, and changing numbers would relight the bell every poll.
2248        notices::raise(
2249            Notice::warn(
2250                &format!("disk:{}", repo.display()),
2251                "A task was held for want of free disk space; free some, then release it from the queue.",
2252            )
2253            .link(Link::Task {
2254                id: task.id.clone(),
2255            }),
2256        );
2257        return Vec::new();
2258    }
2259
2260    // A resumable run of this task is carried on, never re-competed. The
2261    // candidates are built and paid for, and a fresh competition races a
2262    // second implementation against them.
2263    //
2264    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
2265    // started 3cbf on the same task a moment later, duplicating two and a
2266    // half hours of agent work. Then b25f stalled on a judge that timed out
2267    // and one that answered with no JSON - `quota: 0`, so nothing the machine
2268    // was to blame for - and 4043 started **one second** later, buying three
2269    // fresh implementations to reach the same panel. `RunStatus::resumable`
2270    // rather than `!done()` is what catches the second case: a stall is
2271    // terminal, and its cheap recovery re-asks only the absent seats.
2272    //
2273    // A load failure is warned about rather than silently read as "not
2274    // resumable": the alternative is exactly what let a schema mismatch on
2275    // run `eba2` fall through to a full re-competition with nobody told why.
2276    // `crate::conduct` is what actually offers a better answer than
2277    // `Runner::start` here (see `Recovery::Review`), once this task's next
2278    // failure shows it up as `held`/`failed` with the run state unreadable.
2279    let unfinished = (!task.fresh_start)
2280        .then(|| unfinished_run(&task.runs, task.short()))
2281        .flatten();
2282    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
2283    // branch survived, and this reopens exactly that branch as a
2284    // review-only pass rather than resuming or competing again. Consumed
2285    // (cleared) here whichever way this goes, so it never outlives this one
2286    // attempt - see `queue::Task::review_branch`.
2287    let review_branch = task.review_branch.take();
2288    let branch_exists = match &review_branch {
2289        Some(branch) => crate::git::branch_exists(&repo, branch)
2290            .await
2291            .unwrap_or(false),
2292        None => false,
2293    };
2294    let starter = choose_starter(
2295        review_branch.as_deref(),
2296        branch_exists,
2297        unfinished.as_deref(),
2298    );
2299    let started = match &starter {
2300        Starter::Review(branch) => {
2301            tracing::info!(
2302                "task {} reopens `{branch}` as a review-only pass",
2303                task.short()
2304            );
2305            // Every earlier attempt is superseded by the one being minted
2306            // now, so a branch one of them still holds may be taken over.
2307            let takeover = crate::handover::Takeover {
2308                earlier: task.earlier_attempts().to_vec(),
2309                home: crate::run::home(),
2310            };
2311            Runner::review_taking_over(&repo, branch, config, Some(takeover)).await
2312        }
2313        Starter::Resume(id) => {
2314            tracing::info!("resuming run {id} rather than competing again");
2315            Runner::resume(id).map(|mut r| {
2316                if let Some(instruction) =
2317                    prepare_instruction(&starter, Some(&r.state.instruction), task)
2318                {
2319                    r.state.instruction = instruction;
2320                }
2321                r
2322            })
2323        }
2324        Starter::Start => {
2325            if let Some(branch) = &review_branch {
2326                tracing::warn!(
2327                    "conductor chose review for task {} but branch `{branch}` no longer \
2328                     exists; requeuing as a fresh competition instead",
2329                    task.short()
2330                );
2331            }
2332            let instruction = prepare_instruction(&starter, None, task)
2333                .unwrap_or_else(|| task.instruction.clone());
2334            Runner::start(&repo, instruction, config).await
2335        }
2336    };
2337    let mut runner = match started {
2338        Ok(r) => r,
2339        // A branch an earlier attempt still holds and magi will not release
2340        // by itself is the operator's call, not a failed attempt: hold the
2341        // task with the reason, spend nothing, and say so on the bell.
2342        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
2343            let reason = format!("could not start the run: {e:#}");
2344            task.last_error = Some(reason.clone());
2345            task.hold_machine(Some(reason));
2346            record(queue, task);
2347            tracing::warn!(
2348                "holding {} for a branch it cannot take over: {e:#}",
2349                task.short()
2350            );
2351            // Stable wording; the specifics live in the task's hold reason.
2352            notices::raise(
2353                Notice::warn(
2354                    &format!("handover:{}", task.id),
2355                    "A task was held because an earlier attempt still has its branch checked out; see the task's hold reason, then release it from the queue.",
2356                )
2357                .link(Link::Task {
2358                    id: task.id.clone(),
2359                }),
2360            );
2361            return Vec::new();
2362        }
2363        Err(e) => {
2364            task.attempts += 1;
2365            task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
2366            record(queue, task);
2367            return Vec::new();
2368        }
2369    };
2370    // A stop that means "park" reaches the graph through this handle.
2371    runner.on_pause(stop.pause());
2372    // `poll`'s interrupt scheduler reaches this one run - and no other -
2373    // through this handle. See `Pause`'s own doc for why these are never
2374    // the same one.
2375    runner.watch_interrupt(interrupt_pause);
2376
2377    // `start` has minted the run, so the task can now point at it. Persisting
2378    // `Running` before `execute` is what makes a crash mid-run legible.
2379    let run = runner.state.id.clone();
2380    task.start(run.clone());
2381    record(queue, task);
2382    lock(status).current.push(Current {
2383        task: task.id.clone(),
2384        run,
2385    });
2386
2387    // `RunState::quota` is the run's whole history across every resume, so
2388    // only what this execution added may arm the cooldown or earn a refund.
2389    let quota_before = runner.state.quota.clone();
2390    let detail = match runner.execute().await {
2391        Ok(()) => describe(&runner.state),
2392        Err(e) => format!("{e:#}"),
2393    };
2394    let fresh = losses_this_attempt(&quota_before, &runner.state.quota);
2395    let verdict = Verdict {
2396        status: runner.state.status,
2397        // A run that opened a pull request handed its work over, whatever the
2398        // gate then decided about merging it.
2399        left_pr: runner.state.pr.is_some(),
2400        // Only a rate limit earns the task its attempt back - and only one
2401        // suffered now: a refund justified by a previous session's loss is
2402        // the same mistake as re-arming the cooldown from it. A stalled run
2403        // resumed without hitting quota again therefore spends its attempt,
2404        // like any other failure of the task's own.
2405        quota_hit: !fresh.is_empty(),
2406        // A run that parked was asked to stop; that is not a failure and must
2407        // not spend an attempt, or replacing the binary a few times would
2408        // exhaust a task's budget without an agent ever misbehaving.
2409        parked: runner.state.parked,
2410        // A quota loss that left nothing viable is the same machine fact as a
2411        // `Stalled` quota loss; see `settle`'s doc table.
2412        no_viable_candidates: runner.state.viable().is_empty(),
2413    };
2414    settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
2415    if task.status == TaskStatus::Done {
2416        supersede_prior_runs(task, &crate::run::home());
2417    }
2418    record(queue, task);
2419    tracing::info!(
2420        "task {} is {} after run {} ({})",
2421        task.short(),
2422        task.status.as_str(),
2423        runner.state.short(),
2424        label(runner.state.status)
2425    );
2426    fresh
2427}
2428
2429/// The quota losses `after` holds that `before` did not: what one execution
2430/// suffered, as opposed to the run's history.
2431///
2432/// Compared by value rather than by length or position because
2433/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
2434/// the vector can shrink and shift under a resume. A retried seat that hits
2435/// quota again is a `push` with a new `at`, so it shows up as new here.
2436/// `reclaim` deliberately keeps reading the whole history: after a crash there
2437/// is no attempt boundary to diff against.
2438fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
2439    after
2440        .iter()
2441        .filter(|q| !before.contains(q))
2442        .cloned()
2443        .collect()
2444}
2445
2446/// When the loop-wide quota cooldown should end, given this attempt's losses;
2447/// `None` when there were none. Reset-hint parsing and the cap live here.
2448fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
2449    if quota.is_empty() {
2450        return None;
2451    }
2452    let with_hint = quota.iter().find(|q| q.reset.is_some());
2453    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
2454    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
2455    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
2456    Some(
2457        now.checked_add(jiff::SignedDuration::from_secs(secs))
2458            .unwrap_or(Timestamp::MAX),
2459    )
2460}
2461
2462/// Cut this attempt's candidate count to one when the task asked to run
2463/// alone.
2464///
2465/// Pure and separate from [`attempt`] so the one thing this feature changes -
2466/// which `candidates` a `solo` task's run is built with - can be asserted
2467/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
2468/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
2469/// value from the caller's own copy, so a repository's `magi.toml` on disk is
2470/// never touched - only the `Config` this one attempt hands to `Runner::start`.
2471fn apply_solo(config: &mut Config, task: &Task) {
2472    if task.solo {
2473        config.graph.candidates = 1;
2474    }
2475}
2476
2477/// Load the config for a task's repository, with the merge override applied.
2478fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
2479    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
2480    if let Some(mode) = &opts.merge {
2481        config.merge.mode = merge_mode(mode)?;
2482    }
2483    Ok(config)
2484}
2485
2486/// Prune the shared build cache back under its cap at a safe boundary
2487/// between runs, so a queue that never empties - and so never reaches
2488/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
2489/// does not leave the cache to grow unchecked for as long as the backlog
2490/// lasts.
2491///
2492/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
2493/// same liveness fact the idle branch's own janitor call rests on - no run
2494/// this daemon spawned is still mid-compile - so pruning here races nothing.
2495/// The caller must not call this while a run is in flight; there is no
2496/// second `busy_now()` check inside this function, on purpose, because there
2497/// is nothing left to check that `busy_now()` has not already answered.
2498///
2499/// A stop that has already been asked for *is* checked here, for a different
2500/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
2501/// synchronously before it decides anything, so the poll loop cannot get back
2502/// to its own `stopped()` test until that walk is over — and a loop already
2503/// on its way out must not make the operator wait out housekeeping it is
2504/// about to stop needing. This is the same call the idle branch makes when it
2505/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
2506/// it matters more here: `busy_now()` is false throughout, so
2507/// [`Stop::finishing`] would report a stop as already landed while the walk
2508/// still held the loop. Nothing is lost by skipping — the cap is a standing
2509/// policy, and the next daemon's startup pass measures the same cache.
2510///
2511/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
2512/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
2513/// and the next has not yet claimed a task, which can be every few
2514/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
2515/// more than the growth it is guarding against.
2516async fn maybe_prune_cache_between_runs(
2517    repo: &Path,
2518    opts: &Opts,
2519    home: &Path,
2520    stop: &Stop,
2521    last_checked: &mut Option<Timestamp>,
2522    now: Timestamp,
2523) {
2524    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
2525        return;
2526    }
2527    *last_checked = Some(now);
2528    let cfg = match prepare(repo, opts) {
2529        Ok(cfg) => cfg,
2530        Err(e) => {
2531            tracing::warn!("cache check: no config: {e:#}");
2532            return;
2533        }
2534    };
2535    match clean::prune_cache_if_over_limit(&cfg, home) {
2536        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
2537            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
2538            pruned.files,
2539            pruned.freed
2540        ),
2541        Ok(_) => {}
2542        Err(e) => {
2543            tracing::warn!("housekeep: prune cache: {e:#}");
2544            notices::raise_in(
2545                home,
2546                Notice::warn(
2547                    "housekeep:cache",
2548                    "Pruning the shared build cache failed; disk usage may keep growing.",
2549                ),
2550            );
2551        }
2552    }
2553}
2554
2555/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
2556/// now, given when it last did (if ever). Pure, so the cadence is asserted
2557/// directly rather than by waiting out real minutes in a test.
2558fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
2559    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
2560}
2561
2562/// The disk janitor, with its housekeeping logged rather than fatal.
2563///
2564/// Called only at the loop's idle points, for the reason the caller documents:
2565/// a prune racing a live compile would delete files mid-build. The config is
2566/// re-read on every call because the repository that just ran may not be the
2567/// daemon's own default, and the cache directory is a repository fact.
2568///
2569/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
2570/// and [`crate::run::default_worktree_root`] read here, for the same reason
2571/// [`drive`] takes its queue and status file rather than resolving them: a
2572/// test driving the loop must not reach through to the operator's real home
2573/// or worktree bay just because the janitor runs on every idle tick.
2574/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
2575/// to get wrong silently - a test's `home` was already isolated, but nothing
2576/// exercised the parameter next to it, so a real worktree bay stayed wired in
2577/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
2578/// it for real, every test in this file that drives the loop at all started
2579/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
2580async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
2581    let cfg = match prepare(repo, opts) {
2582        Ok(cfg) => cfg,
2583        Err(e) => {
2584            tracing::warn!("housekeep: no config: {e:#}");
2585            return;
2586        }
2587    };
2588    // A run's own worktree lives under `config.graph.worktree_root` when the
2589    // repository sets one - the same precedence `RunState::worktree_root`
2590    // uses - and `worktrees_root` only stands in for the *default* an
2591    // unconfigured repository resolves to (see this function's own
2592    // parameter, or the test fixture wiring one to a fake path). Housekeeping
2593    // that always swept the default regardless of this override would never
2594    // see, and so never reclaim, a single worktree for a repository that
2595    // relocated them elsewhere.
2596    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
2597    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
2598    // Reported whenever there is anything to say, not only when `folded > 0`:
2599    // the incident this exists to prevent was 90 of 93 runs skipped and 0
2600    // folded, on every single pass, for months - a report gated on `folded`
2601    // would have stayed silent through every one of them.
2602    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
2603        let mut extra = Vec::new();
2604        if out.unreadable > 0 {
2605            extra.push(format!("{} unreadable", out.unreadable));
2606        }
2607        if out.orphaned_worktrees > 0 {
2608            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
2609        }
2610        let detail = if extra.is_empty() {
2611            String::new()
2612        } else {
2613            format!(" ({})", extra.join(", "))
2614        };
2615        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
2616    }
2617    if out.external_merges_recorded > 0 {
2618        tracing::info!(
2619            "housekeep: recorded {} run(s) as merged externally",
2620            out.external_merges_recorded
2621        );
2622    }
2623    if out.cache_files > 0 {
2624        tracing::info!(
2625            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
2626            out.cache_files,
2627            out.cache_freed
2628        );
2629    }
2630    if out.questions_abandoned > 0 {
2631        tracing::info!(
2632            "housekeep: abandoned {} question(s) left open by a finished run",
2633            out.questions_abandoned
2634        );
2635    }
2636}
2637
2638/// Run [`triage::run_once`] and log whatever it did, the same "only when
2639/// there is something to say" rule [`janitor`] follows for its own report.
2640///
2641/// Called at the same idle points as [`janitor`] - once per full poll
2642/// interval, never mid-attempt - for the same reason: it is not liveness
2643/// critical, and a task's own `hold_reason` string is the one thing this
2644/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
2645/// tick for no benefit.
2646async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
2647    let questions = Questions::at(home.join("questions"));
2648    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
2649    if report.is_empty() {
2650        return;
2651    }
2652    if !report.quarantined.is_empty() {
2653        tracing::info!(
2654            "triage: held {} blocked task(s) whose blocked-on task or \
2655             question no longer exists: {}",
2656            report.quarantined.len(),
2657            report.quarantined.join(", ")
2658        );
2659    }
2660    if !report.resumed.is_empty() {
2661        tracing::info!(
2662            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
2663            report.resumed.len(),
2664            report.resumed.join(", ")
2665        );
2666    }
2667    if !report.asked.is_empty() {
2668        tracing::info!(
2669            "triage: asked about {} held task(s): {}",
2670            report.asked.len(),
2671            report.asked.join(", ")
2672        );
2673    }
2674    if !report.answered.is_empty() {
2675        tracing::info!(
2676            "triage: applied {} operator answer(s): {}",
2677            report.answered.len(),
2678            report.answered.join(", ")
2679        );
2680    }
2681}
2682
2683/// The free-space gate: what stands between this task and a new run, if
2684/// anything. `Some(reason)` holds the task; `None` lets it start.
2685///
2686/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
2687/// the operator opted out. A measurement failure is a gate, not a pass: both
2688/// sides of "cannot tell" are served by not starting.
2689fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
2690    disk_gate_with(repo, config, crate::disk::free_bytes)
2691}
2692
2693/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
2694/// test can assert the exact wiring `attempt` runs - config's threshold in,
2695/// task-holding reason out - without asking the real machine's disk anything.
2696fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
2697    repo: &Path,
2698    config: &Config,
2699    free_bytes: F,
2700) -> Option<String> {
2701    let min = config.disk.min_free_bytes;
2702    if min == 0 {
2703        return None;
2704    }
2705    match free_bytes(repo) {
2706        Ok(free) => crate::disk::gate(free, min),
2707        Err(e) => Some(format!(
2708            "could not measure free space on {} ({e}); the disk gate refuses \
2709             to let a run start blind",
2710            repo.display()
2711        )),
2712    }
2713}
2714
2715/// How long to wait before offering another task when a run lost a seat to a
2716/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
2717/// could read, or carried nothing at all. Long enough that a quota outage
2718/// cannot burn through a whole backlog in the few seconds each doomed attempt
2719/// takes to fail; short enough that a quota which clears early is not left
2720/// idle for the fallback's sake.
2721const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
2722
2723/// Longest a parsed reset hint may push the wait out to. The hint comes from
2724/// the CLI's own words, not a contract, so a parsing slip that lands a day
2725/// away must not leave the loop asleep for a day.
2726const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
2727
2728/// How long [`poll`] should wait before offering the next task, after a run
2729/// lost at least one seat to a rate limit.
2730///
2731/// Pure and separate from the loop so the policy can be exercised without a
2732/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
2733/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
2734/// nothing to parse, or the parsed time has already passed; `cap` bounds how
2735/// far a parsed hint is trusted to push the wait out.
2736fn quota_wait(
2737    reset_at: Option<Timestamp>,
2738    now: Timestamp,
2739    fallback: Duration,
2740    cap: Duration,
2741) -> Duration {
2742    match reset_at {
2743        Some(at) if at > now => {
2744            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
2745            Duration::from_secs(secs).min(cap)
2746        }
2747        _ => fallback,
2748    }
2749}
2750
2751/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
2752///
2753/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
2754/// explains why parsing it exactly "would be a bug factory" — so this only
2755/// recognises the shapes actually observed in the wild, and returns `None`
2756/// for anything else rather than guess at a format nobody has seen.
2757///
2758/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
2759/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
2760/// said it, not from whenever this loop happens to read it: anchoring on `now`
2761/// would push the reset later on every read and would read an already-elapsed
2762/// reset as still in the future. (A long hint is still clamped by
2763/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
2764fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
2765    parse_reset_hint_zoned(text, now)
2766        .or_else(|| parse_reset_hint_dated(text))
2767        .or_else(|| parse_reset_hint_relative(text, recorded))
2768}
2769
2770/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
2771/// optional but at least one required, in that order. A bare number or any
2772/// unknown unit is refused.
2773fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
2774    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
2775    let mut rest = rest.trim();
2776    if rest.is_empty() {
2777        return None;
2778    }
2779    let mut total: i64 = 0;
2780    let mut matched = false;
2781    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
2782        if let Some((digits, tail)) = rest.split_once(unit)
2783            && !digits.is_empty()
2784            && digits.bytes().all(|b| b.is_ascii_digit())
2785        {
2786            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
2787            rest = tail;
2788            matched = true;
2789        }
2790    }
2791    if !rest.is_empty() || !matched {
2792        return None;
2793    }
2794    recorded
2795        .checked_add(jiff::SignedDuration::from_secs(total))
2796        .ok()
2797}
2798
2799/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
2800/// case-insensitive) into a 24-hour hour and minute. Shared by every
2801/// reset-hint shape below.
2802fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
2803    let clock = clock.trim().to_lowercase();
2804    let (digits, pm) = clock
2805        .strip_suffix("am")
2806        .map(|d| (d, false))
2807        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
2808    let (h, m) = digits.trim().split_once(':')?;
2809    let mut hour: i8 = h.trim().parse().ok()?;
2810    let minute: i8 = m.trim().parse().ok()?;
2811    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
2812        return None;
2813    }
2814    if pm && hour != 12 {
2815        hour += 12;
2816    } else if !pm && hour == 12 {
2817        hour = 0;
2818    }
2819    Some((hour, minute))
2820}
2821
2822/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
2823/// and a zone, never a date. A clock reading already past today is read as
2824/// tomorrow's: a CLI naming a same-day reset that has already gone by means
2825/// the window rolled over while nothing was watching.
2826fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
2827    let open = text.find('(')?;
2828    let close = text.rfind(')')?;
2829    if close <= open {
2830        return None;
2831    }
2832    let zone = text[open + 1..close].trim();
2833    let (hour, minute) = parse_12h_clock(&text[..open])?;
2834    let tz = jiff::tz::TimeZone::get(zone).ok()?;
2835    let candidate = now
2836        .to_zoned(tz)
2837        .with()
2838        .hour(hour)
2839        .minute(minute)
2840        .second(0)
2841        .millisecond(0)
2842        .microsecond(0)
2843        .nanosecond(0)
2844        .build()
2845        .ok()?;
2846    let mut at = candidate.timestamp();
2847    if at <= now {
2848        at += jiff::SignedDuration::from_hours(24);
2849    }
2850    Some(at)
2851}
2852
2853/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
2854/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
2855/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
2856/// "already past today" correction to make: the year already disambiguates
2857/// it. Scanned as a five-word window so it can be pulled out of the middle
2858/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
2859/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
2860/// any other timestamp with no zone attached.
2861fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
2862    let words: Vec<&str> = text.split_whitespace().collect();
2863    if words.len() < 5 {
2864        return None;
2865    }
2866    (0..=words.len() - 5)
2867        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
2868}
2869
2870/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
2871/// parenthesis right after the window is refused rather than ignored — it
2872/// reads as an explicit zone annotation on a shape that otherwise carries
2873/// none, and guessing UTC anyway would be exactly the silent misread this
2874/// module's parsing otherwise avoids.
2875fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
2876    if trailing.is_some_and(|next| next.starts_with('(')) {
2877        return None;
2878    }
2879    let month = month_number(window[0])?;
2880    let day_token = window[1].strip_suffix(',')?.to_lowercase();
2881    let day_digits = ["st", "nd", "rd", "th"]
2882        .iter()
2883        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
2884    let day: i8 = day_digits.parse().ok()?;
2885    let year_token = window[2];
2886    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
2887        return None;
2888    }
2889    let year: i16 = year_token.parse().ok()?;
2890    // The am/pm word carries the sentence's own trailing punctuation, e.g.
2891    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
2892    // reusing the same 12-hour clock reader the bracketed shape uses.
2893    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
2894    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
2895    let date = jiff::civil::Date::new(year, month, day).ok()?;
2896    let candidate = date
2897        .at(hour, minute, 0, 0)
2898        .to_zoned(jiff::tz::TimeZone::UTC)
2899        .ok()?;
2900    Some(candidate.timestamp())
2901}
2902
2903/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
2904/// case-insensitively, into a 1-based month number.
2905fn month_number(name: &str) -> Option<i8> {
2906    const NAMES: [&str; 12] = [
2907        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
2908    ];
2909    let lower = name.to_lowercase();
2910    NAMES
2911        .iter()
2912        .position(|n| *n == lower.as_str())
2913        .map(|i| i as i8 + 1)
2914}
2915
2916/// Resuming a `Blocked` run that already spent every review round its own
2917/// config allowed cannot make progress: `graph::Runner`'s review loop walks
2918/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
2919/// reached `max_rounds`, so `execute` would settle straight back to
2920/// `Blocked` without asking anyone anything. Read-only against a state this
2921/// build never mutates — `src/graph.rs` stays untouched — but without this
2922/// check, [`unfinished_run`] would keep reporting such a run as still
2923/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
2924/// promise is a fresh competition when a design needs to change) would
2925/// silently resume the exhausted run instead, spending an attempt on a
2926/// cycle that cannot change anything.
2927fn exhausted_review_budget(state: &RunState) -> bool {
2928    state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
2929}
2930
2931/// This task's *most recent* run, if resuming it would actually make
2932/// progress. `short` is only for the warning's own message.
2933///
2934/// Only ever `runs.last()` — never a search back through older history.
2935/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
2936/// mint, oldest first, and every entry before the last one was already
2937/// superseded at the moment it was minted: the daemon only ever starts a new
2938/// run when the previous one was not worth resuming (unresumable, exhausted,
2939/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
2940/// opens a fresh review-only run alongside an older, already-failed
2941/// competition. Searching further back would let an old run that merely
2942/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
2943/// behind, say — get resumed instead of the fresh competition
2944/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
2945/// nothing asked to revisit.
2946///
2947/// Two runs paid for the "prefer resuming over restarting" half of this
2948/// lesson, which is why this still checks `runs.last()` rather than always
2949/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
2950/// task a moment later, duplicating two and a half hours of agent work. Then
2951/// b25f stalled on a judge that timed out and one that answered with no JSON
2952/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
2953/// **one second** later, buying three fresh implementations to reach the
2954/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
2955/// the second case: a stall is terminal, and its cheap recovery re-asks only
2956/// the absent seats. [`exhausted_review_budget`] is the other half: a run
2957/// that is technically `resumable()` but provably cannot progress must not
2958/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
2959/// no-op instead of the fresh competition it promises.
2960///
2961/// A load failure is warned about rather than silently read as "not
2962/// resumable": the alternative is exactly what let a schema mismatch on run
2963/// `eba2` fall through to a full re-competition with nobody told why.
2964/// `crate::conduct` is what actually offers a better answer than
2965/// `Runner::start` here (see `Recovery::Review`), once this task's next
2966/// failure shows it up as `held`/`failed` with the run state unreadable.
2967fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
2968    unfinished_run_with(runs, short, RunState::load)
2969}
2970
2971/// [`unfinished_run`] with an injected state reader. Tests provide their
2972/// fixtures directly rather than touching the process-global run home.
2973fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
2974where
2975    F: FnOnce(&str) -> Result<RunState>,
2976{
2977    let id = runs.last()?;
2978    match load(id) {
2979        Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
2980            Some(id.clone())
2981        }
2982        Ok(_) => None,
2983        Err(e) => {
2984            tracing::warn!("could not read run {id} for task {short}: {e:#}");
2985            None
2986        }
2987    }
2988}
2989
2990/// Which of the three ways [`attempt`] can mint or continue a run this task
2991/// should use.
2992#[derive(Debug, Clone, PartialEq, Eq)]
2993enum Starter {
2994    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
2995    /// and that still exists.
2996    Review(String),
2997    /// `crate::graph::Runner::resume` on an unfinished run of this task.
2998    Resume(String),
2999    /// `crate::graph::Runner::start`: a fresh competition.
3000    Start,
3001}
3002
3003/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
3004/// this attempt should use. Pure, and separate from [`attempt`], so the
3005/// routing itself is assertable without spawning a real graph or a git
3006/// process: `attempt`'s own `crate::git::branch_exists` call has already
3007/// happened by the time this is called.
3008///
3009/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
3010/// whose branch is gone falls all the way through to [`Starter::Start`], not
3011/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
3012/// old (likely `Blocked`) run in the first place, and a branch that vanished
3013/// out from under that choice is not evidence resuming it would fare better.
3014fn choose_starter(
3015    review_branch: Option<&str>,
3016    branch_exists: bool,
3017    unfinished: Option<&str>,
3018) -> Starter {
3019    match review_branch {
3020        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
3021        Some(_) => Starter::Start,
3022        None => match unfinished {
3023            Some(id) => Starter::Resume(id.to_owned()),
3024            None => Starter::Start,
3025        },
3026    }
3027}
3028
3029/// Which repository a task runs in. A task that names none — the normal case
3030/// for one filed from a phone — runs in the daemon's own default.
3031fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
3032    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
3033        return fallback.to_path_buf();
3034    }
3035    task.repo.clone()
3036}
3037
3038/// The header [`append_answers`] appends operator answers under. Shared with
3039/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
3040/// rather than grown a new block on every resume.
3041const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
3042
3043/// Render the first `count` answers in the block appended to an instruction.
3044fn answers_block(task: &Task, count: usize) -> String {
3045    let mut s = ANSWERS_HEADER.to_owned();
3046    for a in &task.answers[..count] {
3047        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
3048    }
3049    s
3050}
3051
3052/// Append every answer `crate::conduct` has collected for `task` onto `base`,
3053/// in the shape both [`instruction_for`] and [`resumed_instruction`] use.
3054fn append_answers(base: &str, task: &Task) -> String {
3055    if task.answers.is_empty() {
3056        return base.to_owned();
3057    }
3058    let mut s = base.to_owned();
3059    s.push_str(&answers_block(task, task.answers.len()));
3060    s
3061}
3062
3063/// Drop the prior answer block only when it is exactly the suffix this task
3064/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
3065/// the task author is ordinary instruction text, not a block to remove.
3066fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
3067    for count in (1..=task.answers.len()).rev() {
3068        let block = answers_block(task, count);
3069        if let Some(base) = instruction.strip_suffix(&block) {
3070            return base;
3071        }
3072    }
3073    instruction
3074}
3075
3076/// The instruction handed to `Runner::start`: the task's own text, plus any
3077/// operator answers `crate::conduct` collected for it (see
3078/// [`Task::answers`]), so a decision the operator actually made reaches the
3079/// implementers rather than only clearing the block that was waiting on it.
3080///
3081/// Appended rather than merged into [`Task::instruction`] itself, so the
3082/// task's own record stays exactly what its author wrote.
3083fn instruction_for(task: &Task) -> String {
3084    append_answers(&task.instruction, task)
3085}
3086
3087/// The instruction a resumed run should carry on with: whatever it already
3088/// had, refreshed with the task's *current* operator answers.
3089///
3090/// A resumable run's own `RunState::instruction` predates any answer
3091/// `crate::conduct` collects after the run parks, so resuming it unchanged —
3092/// the behaviour before this function existed — silently drops the very
3093/// decision the operator made to unblock it. Re-stripping any block this
3094/// function appended on an earlier resume before re-appending the current
3095/// list (rather than blindly appending again) is what keeps a task resumed
3096/// three times over three answered questions from carrying the same answer
3097/// three times.
3098fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
3099    append_answers(strip_answers_block(old_instruction, task), task)
3100}
3101
3102/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
3103/// answers before handing it to `Runner` — the actual boundary between
3104/// [`choose_starter`]'s routing and the graph, factored out so it is
3105/// assertable without a real repository, git branch, or agent CLI.
3106///
3107/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
3108/// instruction from the reviewed branch's own commit log because there is no
3109/// task statement to speak of for hand-written work, and splicing operator
3110/// answers into that text would contradict the very message it sends
3111/// reviewers ("there is no task statement").
3112fn prepare_instruction(
3113    starter: &Starter,
3114    old_instruction: Option<&str>,
3115    task: &Task,
3116) -> Option<String> {
3117    match starter {
3118        Starter::Start => Some(instruction_for(task)),
3119        Starter::Resume(_) => Some(resumed_instruction(
3120            old_instruction.expect("a resumed run always has a prior instruction"),
3121            task,
3122        )),
3123        Starter::Review(_) => None,
3124    }
3125}
3126
3127/// Persist a transition. A queue write failure is logged rather than fatal: the
3128/// run already happened, and taking the daemon down would only add a lost
3129/// backlog to a full disk.
3130fn record(queue: &Queue, task: &mut Task) {
3131    if let Err(e) = queue.put(task) {
3132        tracing::error!("could not record task {}: {e:#}", task.short());
3133        notices::raise(Notice::error(
3134            "loop:record",
3135            "The loop could not save a task's state; check the disk.",
3136        ));
3137    }
3138}
3139
3140/// Every runnable task, in the order the loop should try them.
3141///
3142/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
3143/// tail exists so that a claim somebody else holds costs the loop the next
3144/// candidate rather than a whole poll interval of idleness.
3145fn runnable(queue: &Queue) -> Vec<Task> {
3146    let mut tasks: Vec<Task> = queue
3147        .list()
3148        .into_iter()
3149        .filter(|t| t.status.runnable())
3150        .collect();
3151    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
3152    tasks
3153}
3154
3155/// Why a run ended where it did, in one line, for [`Task::last_error`].
3156///
3157/// A stalled run names the seats the quota took out: "out of quota" is not
3158/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
3159/// agent to replace or which plan to top up.
3160///
3161/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
3162/// purpose: unlike `label`'s other callers (an internal log line, an
3163/// already-a-bug fallback message), this string becomes `Task::last_error`
3164/// verbatim, which the phone renders in the same alarm-styled box an
3165/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
3166/// `.err` styling. A bare `verified_noop` there would read exactly like the
3167/// failure this whole feature exists to tell apart from one.
3168fn describe(state: &RunState) -> String {
3169    let mut detail = if state.status == RunStatus::Stalled {
3170        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
3171        seats.sort_unstable();
3172        seats.dedup();
3173        if seats.is_empty() {
3174            "the judging panel lost its quorum".to_owned()
3175        } else {
3176            format!(
3177                "the judging panel lost its quorum; quota took out {}",
3178                seats.join(", ")
3179            )
3180        }
3181    } else {
3182        format!("run ended {}", state.status.display_label())
3183    };
3184    if let Some(last) = state.events.last() {
3185        detail.push_str(&format!(" ({}: {})", last.node, last.message));
3186    }
3187    detail.push_str(&format!(" [run {}]", state.id));
3188    detail
3189}
3190
3191/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
3192///
3193/// The task file lives in the backlog indefinitely; a diagnostic is an
3194/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
3195/// stay small regardless of how much a gate command or a candidate printed.
3196const DIAGNOSTIC_MAX: usize = 4_000;
3197
3198/// Tail kept from a single failing command's output inside a diagnostic.
3199/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
3200/// pointer for a human deciding whether to go read the full artifact by hand,
3201/// not a replacement for reading it.
3202const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
3203
3204/// Assemble a bounded diagnostic excerpt from a held task's own run, so
3205/// `magi task show` says more than the one-line reason in [`describe`].
3206///
3207/// The one-liner answers "where did the run stop"; this answers "what would a
3208/// human have found opening `artifacts/` by hand" — the point of the whole
3209/// feature is the case that one-liner actively misleads on: a run held as "no
3210/// candidate produced a change" can mean the implementer actually finished
3211/// the task (opened a PR, merged it, tagged a release) and only left a clean
3212/// local worktree behind, which reads as "nothing happened" unless someone
3213/// goes and reads what the agent actually said. `None` when the run carries
3214/// none of the three shapes this recognises — an ordinary run held for
3215/// something not diagnosable from `RunState` alone still explains itself
3216/// through `Task::last_error`.
3217fn diagnostic(state: &RunState) -> Option<String> {
3218    let mut parts: Vec<String> = Vec::new();
3219
3220    // Gate failure: which check(s), and the tail of what each printed.
3221    for o in state.gate.iter().filter(|o| !o.ok()) {
3222        parts.push(format!(
3223            "gate `{}` failed ({:?}):\n{}",
3224            o.command,
3225            o.code,
3226            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
3227        ));
3228    }
3229
3230    // The land loop gave up because the fixer declined while checks were
3231    // still red: the message already names them (see `land::run`).
3232    if let Some(last) = state
3233        .events
3234        .iter()
3235        .rev()
3236        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
3237    {
3238        parts.push(last.message.clone());
3239    }
3240
3241    // No viable candidate: every implementer's own final word, sanitized the
3242    // same way a judge would have read it, so a run that actually finished
3243    // the job does not read as an unexplained failure. A verified no-op is
3244    // called out ahead of its own summary and apart from an ordinary
3245    // failure's `why` — this is the one candidate shape whose diagnostic a
3246    // human is expected to actually judge, not just skim.
3247    if state.viable().is_empty() {
3248        for c in &state.candidates {
3249            if let Some(evidence) = &c.verified_noop {
3250                parts.push(format!(
3251                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
3252                    c.label
3253                ));
3254            } else if !c.summary.trim().is_empty() {
3255                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
3256            } else if let Some(why) = &c.failed {
3257                parts.push(format!("candidate {}: {why}", c.label));
3258            }
3259        }
3260    }
3261
3262    if parts.is_empty() {
3263        return None;
3264    }
3265    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
3266    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
3267    // back slightly over. Leave it enough room to always land under the
3268    // limit.
3269    Some(crate::run::tail(
3270        &parts.join("\n\n"),
3271        DIAGNOSTIC_MAX.saturating_sub(100),
3272    ))
3273}
3274
3275/// Stable lower-case name for a run status, for an internal log line and the
3276/// "graph stopped without reaching a terminal status" bug message in
3277/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
3278/// doc for why that one reads [`RunStatus::display_label`] instead. One
3279/// definition of a status's name, on the type that owns it: this table used
3280/// to live here as a second copy, and a status renamed in one place would
3281/// have gone on reading correctly in the other.
3282fn label(status: RunStatus) -> &'static str {
3283    status.as_str()
3284}
3285
3286/// Parse a merge mode override.
3287fn merge_mode(mode: &str) -> Result<MergeMode> {
3288    match mode {
3289        "none" => Ok(MergeMode::None),
3290        "local" => Ok(MergeMode::Local),
3291        "pr" => Ok(MergeMode::Pr),
3292        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
3293    }
3294}
3295
3296/// Take the status lock, recovering from a poisoned one.
3297///
3298/// A panic elsewhere must not silently stop the heartbeat: the status is plain
3299/// data, and the worst a poisoned lock can hold is a stale timestamp.
3300fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
3301    mutex
3302        .lock()
3303        .unwrap_or_else(std::sync::PoisonError::into_inner)
3304}
3305
3306#[cfg(test)]
3307mod tests {
3308    use super::*;
3309    use crate::queue::{Source, TaskStatus};
3310    use crate::run::{Candidate, CommandOutcome};
3311    use pretty_assertions::assert_eq;
3312
3313    fn task() -> Task {
3314        Task::new(
3315            "add retries".to_owned(),
3316            "add retries".to_owned(),
3317            PathBuf::from("/repo"),
3318            Source::Human,
3319        )
3320    }
3321
3322    /// A runnable task marked to interrupt, with an id fixed for assertions
3323    /// rather than the random one [`Task::new`] mints.
3324    fn interrupt_task(id: &str) -> Task {
3325        let mut t = task();
3326        t.id = id.to_owned();
3327        t.interrupt = true;
3328        t
3329    }
3330
3331    /// An ordinary runnable task with an id fixed for assertions.
3332    fn task_with_id(id: &str) -> Task {
3333        let mut t = task();
3334        t.id = id.to_owned();
3335        t
3336    }
3337
3338    /// A runnable task marked `--urgent`, with an id fixed for assertions.
3339    fn urgent_task(id: &str) -> Task {
3340        let mut t = task();
3341        t.id = id.to_owned();
3342        t.urgent = true;
3343        t
3344    }
3345
3346    /// The land-resume exemption wins outright, whether or not the candidate
3347    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
3348    /// queue behind anything" guarantee cannot be weaker just because the
3349    /// same task was also filed with `--urgent`.
3350    #[test]
3351    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
3352        assert_eq!(permit_kind(true, false), PermitKind::None);
3353        assert_eq!(permit_kind(true, true), PermitKind::None);
3354    }
3355
3356    /// The one property this whole feature exists for: `--urgent` draws from
3357    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
3358    /// ordinary candidate draws from the ordinary pool exactly as before,
3359    /// untouched by the urgent slot's existence.
3360    #[test]
3361    fn permit_kind_separates_urgent_from_ordinary() {
3362        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
3363        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
3364    }
3365
3366    /// The exact wiring `attempt` runs before minting anything: a config's
3367    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
3368    /// Free space is injected rather than asked of the real disk - the point
3369    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
3370    /// is deterministic on every machine this test runs on, never dependent
3371    /// on how full the CI runner's own disk happens to be.
3372    #[test]
3373    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
3374        let cfg = Config::default();
3375        let repo = Path::new("/any/repo/path");
3376
3377        let reason =
3378            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
3379        assert!(reason.contains("1024"), "{reason}");
3380        assert!(
3381            reason.contains(&cfg.disk.min_free_bytes.to_string()),
3382            "{reason}"
3383        );
3384
3385        assert_eq!(
3386            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
3387            None,
3388            "exactly at the floor is open"
3389        );
3390        assert_eq!(
3391            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
3392            None,
3393            "comfortably above the floor is open"
3394        );
3395    }
3396
3397    #[test]
3398    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
3399        let mut cfg = Config::default();
3400        cfg.disk.min_free_bytes = 0;
3401        let repo = Path::new("/any/repo/path");
3402        assert_eq!(
3403            disk_gate_with(repo, &cfg, |_| Ok(0)),
3404            None,
3405            "a zero floor never measures at all"
3406        );
3407    }
3408
3409    #[test]
3410    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
3411        let cfg = Config::default();
3412        let repo = Path::new("/any/repo/path");
3413        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
3414            .expect("a measurement failure must close the gate, not open it");
3415        assert!(reason.contains("could not measure"), "{reason}");
3416    }
3417
3418    #[test]
3419    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
3420        let ordinary = task();
3421        let next = advance_interrupt(
3422            Interrupt::Idle,
3423            std::slice::from_ref(&ordinary.id),
3424            std::slice::from_ref(&ordinary),
3425        );
3426        assert_eq!(next, Interrupt::Idle);
3427    }
3428
3429    #[test]
3430    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
3431        // Nothing to interrupt - this is just an ordinary candidate, and the
3432        // loop's normal dispatch will pick it up like any other.
3433        let marked = interrupt_task("marked");
3434        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3435        assert_eq!(next, Interrupt::Idle);
3436    }
3437
3438    #[test]
3439    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
3440        let marked = interrupt_task("marked");
3441        let next = advance_interrupt(
3442            Interrupt::Idle,
3443            &["running".to_owned()],
3444            std::slice::from_ref(&marked),
3445        );
3446        assert_eq!(
3447            next,
3448            Interrupt::Parking {
3449                parked: vec!["running".to_owned()],
3450                interrupt_task: "marked".to_owned(),
3451            }
3452        );
3453    }
3454
3455    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
3456    /// one run can be in flight when a task becomes runnable and marked.
3457    /// Parking all of them would mean `Resuming` later has more than one id
3458    /// to release back to ordinary dispatch, which cannot be made safe
3459    /// against that same setting's own extra concurrency slots letting two
3460    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
3461    /// The simplification the task's own constraints ask for: do not begin
3462    /// a sequence at all until the herd settles back to exactly one.
3463    #[test]
3464    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
3465        let marked = interrupt_task("marked");
3466
3467        let two = advance_interrupt(
3468            Interrupt::Idle,
3469            &["a".to_owned(), "b".to_owned()],
3470            std::slice::from_ref(&marked),
3471        );
3472        assert_eq!(two, Interrupt::Idle);
3473
3474        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3475        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
3476    }
3477
3478    #[test]
3479    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
3480        let state = Interrupt::Parking {
3481            parked: vec!["running".to_owned()],
3482            interrupt_task: "marked".to_owned(),
3483        };
3484        // Still in flight: no change.
3485        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
3486        assert_eq!(still_going, state);
3487
3488        // Left flight, but the interrupt task has not been dispatched yet on
3489        // this tick - stays `Parking` so `interrupt_gate` can let it through,
3490        // as long as it is still runnable.
3491        let stopped_but_not_yet_dispatched =
3492            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
3493        assert_eq!(stopped_but_not_yet_dispatched, state);
3494
3495        // Left flight, and the interrupt task is now in flight itself.
3496        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
3497        assert_eq!(
3498            dispatched,
3499            Interrupt::Running {
3500                parked: vec!["running".to_owned()],
3501                interrupt_task: "marked".to_owned(),
3502            }
3503        );
3504    }
3505
3506    #[test]
3507    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
3508        let state = Interrupt::Running {
3509            parked: vec!["running".to_owned()],
3510            interrupt_task: "marked".to_owned(),
3511        };
3512        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
3513        assert_eq!(still_running, state);
3514
3515        // Whatever it ended as - merged, failed, held - is not this
3516        // function's concern: leaving flight is the only trigger, driven
3517        // straight off the same in-flight list `poll` already reaps. It does
3518        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
3519        // why that would let an unrelated task start ahead of, or alongside,
3520        // the guaranteed resume.
3521        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
3522        assert_eq!(
3523            ended,
3524            Interrupt::Resuming {
3525                parked: vec!["running".to_owned()]
3526            }
3527        );
3528    }
3529
3530    #[test]
3531    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
3532        let state = Interrupt::Resuming {
3533            parked: vec!["running".to_owned()],
3534        };
3535        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
3536        assert_eq!(still_waiting, state);
3537
3538        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
3539        assert_eq!(dispatched, Interrupt::Idle);
3540    }
3541
3542    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
3543    /// or otherwise moved on by an operator with no claim standing in the
3544    /// way - must not wedge the sequence (and so the whole loop's dispatch,
3545    /// via `interrupt_gate`) waiting forever for a dispatch that can never
3546    /// come. The parked run still gets its resume.
3547    #[test]
3548    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
3549    {
3550        let state = Interrupt::Parking {
3551            parked: vec!["running".to_owned()],
3552            interrupt_task: "marked".to_owned(),
3553        };
3554        // `marked` has been held/blocked/deleted since the sequence began:
3555        // it no longer appears in `runnable` at all.
3556        let next = advance_interrupt(state, &[], &[]);
3557        assert_eq!(
3558            next,
3559            Interrupt::Resuming {
3560                parked: vec!["running".to_owned()]
3561            },
3562            "abandoning the interrupt must not abandon the resume it owes"
3563        );
3564    }
3565
3566    /// The same abandonment, one step later: `Resuming` itself must not wait
3567    /// forever for a parked task that has since become unrunnable.
3568    #[test]
3569    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
3570        let state = Interrupt::Resuming {
3571            parked: vec!["running".to_owned()],
3572        };
3573        let next = advance_interrupt(state, &[], &[]);
3574        assert_eq!(
3575            next,
3576            Interrupt::Idle,
3577            "nothing is left to wait for; the loop must not stay wedged"
3578        );
3579    }
3580
3581    #[test]
3582    fn disabled_by_config_the_sequence_can_never_leave_idle() {
3583        let marked = interrupt_task("marked");
3584        let next = advance_interrupt_tick(
3585            false,
3586            Interrupt::Idle,
3587            &["running".to_owned()],
3588            std::slice::from_ref(&marked),
3589        );
3590        assert_eq!(
3591            next,
3592            Interrupt::Idle,
3593            "an unmarked, unconfigured daemon must behave exactly as before"
3594        );
3595    }
3596
3597    #[test]
3598    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
3599        let state = Interrupt::Parking {
3600            parked: vec!["running".to_owned()],
3601            interrupt_task: "marked".to_owned(),
3602        };
3603        let candidates = vec![interrupt_task("marked"), task()];
3604        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3605        assert!(
3606            allowed.is_empty(),
3607            "nothing may dispatch - not even the interrupt task itself - \
3608             until the parked run has actually stopped"
3609        );
3610    }
3611
3612    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
3613    /// grow a special case for it: an urgent candidate that is not the
3614    /// interrupt task withholds exactly like an ordinary one for as long as
3615    /// the parked run it is racing has not actually left flight. A version
3616    /// of this feature once bypassed the gate for urgent candidates, on the
3617    /// theory that a genuinely separate concurrency lane could not collide
3618    /// with 75dd's own; it could, and did - the bypassed task dispatched
3619    /// alongside a run 75dd's own state machine had only *asked* to park,
3620    /// not yet confirmed gone, which is exactly the second run
3621    /// `Interrupt::Parking`'s own doc says must never happen. There is no
3622    /// tick during Parking/Running/Resuming where letting an extra
3623    /// candidate through is safe, urgent or not - the parked run may still
3624    /// be genuinely mid-call.
3625    #[test]
3626    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
3627        for state in [
3628            Interrupt::Parking {
3629                parked: vec!["running".to_owned()],
3630                interrupt_task: "marked".to_owned(),
3631            },
3632            Interrupt::Running {
3633                parked: vec!["running".to_owned()],
3634                interrupt_task: "marked".to_owned(),
3635            },
3636            Interrupt::Resuming {
3637                parked: vec!["running".to_owned()],
3638            },
3639        ] {
3640            let candidates = vec![
3641                interrupt_task("marked"),
3642                urgent_task("hot"),
3643                task_with_id("ordinary"),
3644            ];
3645            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3646            assert!(
3647                !allowed.iter().any(|t| t.id == "hot"),
3648                "an urgent candidate must wait out the same gate as anything \
3649                 else while the run it would run alongside has not actually \
3650                 left flight, for state {state:?}: {allowed:?}"
3651            );
3652        }
3653    }
3654
3655    /// The one case where marking a task `--urgent` and `interrupt` at once
3656    /// is not redundant: once the interrupt sequence's own guaranteed
3657    /// resume/dispatch actually admits the task, it is unaffected by also
3658    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
3659    /// never on the urgent flag.
3660    #[test]
3661    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
3662        let state = Interrupt::Resuming {
3663            parked: vec!["hot".to_owned()],
3664        };
3665        let candidates = vec![urgent_task("hot"), task()];
3666        let allowed = interrupt_gate(&state, &[], candidates);
3667        assert_eq!(
3668            allowed.iter().filter(|t| t.id == "hot").count(),
3669            1,
3670            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
3671        );
3672    }
3673
3674    #[test]
3675    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
3676        let state = Interrupt::Parking {
3677            parked: vec!["running".to_owned()],
3678            interrupt_task: "marked".to_owned(),
3679        };
3680        let other = task();
3681        let candidates = vec![interrupt_task("marked"), other.clone()];
3682        let allowed = interrupt_gate(&state, &[], candidates);
3683        assert_eq!(allowed.len(), 1);
3684        assert_eq!(allowed[0].id, "marked");
3685    }
3686
3687    #[test]
3688    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
3689        let state = Interrupt::Running {
3690            parked: vec!["running".to_owned()],
3691            interrupt_task: "marked".to_owned(),
3692        };
3693        let candidates = vec![task(), task()];
3694        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
3695        assert!(allowed.is_empty());
3696    }
3697
3698    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
3699    /// sequence began (only reachable above the default
3700    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
3701    /// never both in the same tick, which is what "exactly one resume, no
3702    /// simultaneous run" actually requires structurally rather than by
3703    /// coincidence of how many ordinary slots happen to be free.
3704    #[test]
3705    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
3706        let state = Interrupt::Resuming {
3707            parked: vec!["a".to_owned(), "c".to_owned()],
3708        };
3709        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
3710        let allowed = interrupt_gate(&state, &[], candidates);
3711        assert_eq!(
3712            allowed.len(),
3713            1,
3714            "at most one candidate may be offered while resuming: {allowed:?}"
3715        );
3716        assert_eq!(allowed[0].id, "a");
3717    }
3718
3719    #[test]
3720    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
3721        let state = Interrupt::Resuming {
3722            parked: vec!["a".to_owned()],
3723        };
3724        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
3725        assert!(allowed.is_empty());
3726    }
3727
3728    /// The invariant the completion criteria ask for by name: across a whole
3729    /// simulated sequence, there is never a tick where the gate would let
3730    /// through both the parked run's resume and the interrupt task, and
3731    /// exactly one candidate resumes the instant the interrupt task's run
3732    /// ends - never zero, never more than one.
3733    #[test]
3734    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
3735        let running = task(); // id: whatever `Task::new` minted
3736        let marked = interrupt_task("marked");
3737
3738        let mut state = Interrupt::Idle;
3739        // Tick 1: `running` is in flight, `marked` becomes runnable.
3740        let in_flight = vec![running.id.clone()];
3741        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
3742        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
3743        assert!(gated.is_empty(), "still waiting on `running` to park");
3744
3745        // Tick 2: `running` parked and left flight; nothing dispatched yet.
3746        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
3747        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
3748        assert_eq!(
3749            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3750            vec!["marked"],
3751            "only the interrupt task may be offered to the dispatcher now"
3752        );
3753
3754        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
3755        state = advance_interrupt_tick(
3756            true,
3757            state,
3758            &["marked".to_owned()],
3759            std::slice::from_ref(&running),
3760        );
3761        let gated = interrupt_gate(
3762            &state,
3763            &["marked".to_owned()],
3764            vec![marked.clone(), running.clone()],
3765        );
3766        assert!(
3767            gated.is_empty(),
3768            "the parked run must not be offered back while the interrupt \
3769             task is still running"
3770        );
3771
3772        // Tick 4: `marked`'s run reached a terminal status and left flight.
3773        // A higher-priority ordinary task `other` is also runnable now - it
3774        // must not be let through instead of, or alongside, `running`.
3775        let other = task_with_id("other");
3776        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
3777        assert_eq!(
3778            state,
3779            Interrupt::Resuming {
3780                parked: vec![running.id.clone()]
3781            }
3782        );
3783        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
3784        assert_eq!(
3785            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3786            vec![running.id.as_str()],
3787            "exactly the parked run resumes - not the unrelated task, even \
3788             though it was offered first"
3789        );
3790
3791        // Tick 5: `running` is now in flight (dispatched from tick 4's
3792        // gate). Only now does the sequence end and ordinary dispatch fully
3793        // resume.
3794        state = advance_interrupt_tick(
3795            true,
3796            state,
3797            std::slice::from_ref(&running.id),
3798            std::slice::from_ref(&other),
3799        );
3800        assert_eq!(state, Interrupt::Idle);
3801        let gated = interrupt_gate(
3802            &state,
3803            std::slice::from_ref(&running.id),
3804            vec![other.clone()],
3805        );
3806        assert_eq!(
3807            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3808            vec![other.id.as_str()],
3809            "ordinary dispatch is unrestricted again"
3810        );
3811    }
3812
3813    #[test]
3814    fn every_run_status_settles_the_task_it_came_from() {
3815        // run status, resulting task status, attempts still standing after one
3816        let table = [
3817            (RunStatus::Merged, TaskStatus::Done, 1),
3818            (RunStatus::Ready, TaskStatus::Done, 1),
3819            (RunStatus::Stalled, TaskStatus::Failed, 0),
3820            (RunStatus::Blocked, TaskStatus::Failed, 1),
3821            (RunStatus::Failed, TaskStatus::Failed, 1),
3822            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
3823            (RunStatus::Prep, TaskStatus::Failed, 1),
3824            (RunStatus::Implementing, TaskStatus::Failed, 1),
3825            (RunStatus::Judging, TaskStatus::Failed, 1),
3826            (RunStatus::Deliberating, TaskStatus::Failed, 1),
3827            (RunStatus::Voting, TaskStatus::Failed, 1),
3828            (RunStatus::Reviewing, TaskStatus::Failed, 1),
3829            (RunStatus::Gating, TaskStatus::Failed, 1),
3830        ];
3831        for (run, want, attempts) in table {
3832            let mut t = task();
3833            t.start("20260902-000000-aaaa".to_owned());
3834            settle(
3835                &mut t,
3836                Verdict {
3837                    status: run,
3838                    left_pr: false,
3839                    parked: false,
3840                    quota_hit: matches!(run, RunStatus::Stalled),
3841                    no_viable_candidates: false,
3842                },
3843                "why",
3844                2,
3845            );
3846            assert_eq!(t.status, want, "task status after {}", label(run));
3847            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
3848        }
3849    }
3850
3851    #[test]
3852    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
3853        let mut stalled = task();
3854        stalled.start("20260902-000000-aaaa".to_owned());
3855        settle(
3856            &mut stalled,
3857            Verdict {
3858                status: RunStatus::Stalled,
3859                left_pr: false,
3860                parked: false,
3861                quota_hit: true,
3862                no_viable_candidates: false,
3863            },
3864            "quota",
3865            1,
3866        );
3867        assert_eq!(stalled.attempts, 0);
3868        assert!(
3869            stalled.status.runnable(),
3870            "a machine problem must leave the task in line"
3871        );
3872
3873        let mut blocked = task();
3874        blocked.start("20260902-000000-aaaa".to_owned());
3875        settle(
3876            &mut blocked,
3877            Verdict {
3878                status: RunStatus::Blocked,
3879                left_pr: false,
3880                parked: false,
3881                quota_hit: false,
3882                no_viable_candidates: false,
3883            },
3884            "findings open",
3885            1,
3886        );
3887        assert_eq!(blocked.attempts, 1);
3888        assert_eq!(
3889            blocked.status,
3890            TaskStatus::Held,
3891            "the last attempt hands the task to a human"
3892        );
3893    }
3894
3895    #[test]
3896    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
3897        // Attempts to spare: without the pull request this task would go
3898        // straight back in line and run the whole competition again.
3899        let mut delivered = task();
3900        delivered.start("20260903-080619-01c2".to_owned());
3901        settle(
3902            &mut delivered,
3903            Verdict {
3904                status: RunStatus::Blocked,
3905                left_pr: true,
3906                parked: false,
3907                quota_hit: false,
3908                no_viable_candidates: false,
3909            },
3910            "no check status",
3911            4,
3912        );
3913        assert_eq!(
3914            delivered.status,
3915            TaskStatus::Held,
3916            "a pull request waiting on CI or a person is not a retryable failure"
3917        );
3918        assert!(
3919            !delivered.status.runnable(),
3920            "the loop must not pick this task up again"
3921        );
3922        assert_eq!(
3923            delivered.last_error.as_deref(),
3924            Some("no check status"),
3925            "the operator needs to be told what the gate was waiting for"
3926        );
3927
3928        // The same status without a pull request is a plain failure, and with
3929        // attempts left it is retried.
3930        let mut empty_handed = task();
3931        empty_handed.start("20260903-080619-01c2".to_owned());
3932        settle(
3933            &mut empty_handed,
3934            Verdict {
3935                status: RunStatus::Blocked,
3936                left_pr: false,
3937                parked: false,
3938                quota_hit: false,
3939                no_viable_candidates: false,
3940            },
3941            "findings open",
3942            4,
3943        );
3944        assert_eq!(empty_handed.status, TaskStatus::Failed);
3945        assert!(empty_handed.status.runnable());
3946    }
3947
3948    #[test]
3949    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
3950        // Every candidate agreed, with evidence, that nothing belonged in the
3951        // worktree. That is not a confirmed success to close automatically -
3952        // a human still has to check the claim - and it is not an ordinary
3953        // failure either, so this settles exactly like a pull request nobody
3954        // merged yet: `Held`, same as `Blocked` with a PR.
3955        let mut noop = task();
3956        noop.start("20260912-131304-391f".to_owned());
3957        settle(
3958            &mut noop,
3959            Verdict {
3960                status: RunStatus::VerifiedNoop,
3961                left_pr: false,
3962                parked: false,
3963                quota_hit: false,
3964                no_viable_candidates: true,
3965            },
3966            "candidate A: already fixed by b32cfc4, on main",
3967            4,
3968        );
3969        assert_eq!(
3970            noop.status,
3971            TaskStatus::Held,
3972            "an unverified claim is a request for a human, not a failure"
3973        );
3974        assert!(
3975            !noop.status.runnable(),
3976            "the loop must not requeue this on the same unverified claim"
3977        );
3978        // `Task::release` resets attempts to zero the moment a human looks at
3979        // the evidence and lets it run again, so it does not matter here
3980        // whether the one attempt already spent stays spent - what matters is
3981        // that nothing retries this task unattended in the meantime.
3982        assert_eq!(noop.attempts, 1);
3983    }
3984
3985    #[test]
3986    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
3987        // Parking is the operator asking for the process back - to replace the
3988        // binary, most of all. The run's work is intact on disk, so this is
3989        // not a failed attempt, and charging for it would mean a few upgrades
3990        // could exhaust a budget meant for agents that misbehaved.
3991        let mut parked = task();
3992        parked.start("20260903-183634-2d98".to_owned());
3993        settle(
3994            &mut parked,
3995            Verdict {
3996                status: RunStatus::Implementing,
3997                left_pr: false,
3998                quota_hit: false,
3999                parked: true,
4000                no_viable_candidates: false,
4001            },
4002            "parked after `implementing`",
4003            2,
4004        );
4005        assert_eq!(parked.attempts, 0, "a park is refunded");
4006        assert!(
4007            parked.status.runnable(),
4008            "and the task stays in line so the next loop resumes its run"
4009        );
4010        assert_eq!(
4011            parked.last_error.as_deref(),
4012            Some("parked after `implementing`"),
4013            "the card says where it stopped"
4014        );
4015
4016        // Without the park flag the same non-terminal status is what it always
4017        // was: `execute` returning mid-flight, which is a bug and spends an
4018        // attempt so a task cannot loop on it forever.
4019        let mut broken = task();
4020        broken.start("20260903-183634-2d98".to_owned());
4021        settle(
4022            &mut broken,
4023            Verdict {
4024                status: RunStatus::Implementing,
4025                left_pr: false,
4026                quota_hit: false,
4027                parked: false,
4028                no_viable_candidates: false,
4029            },
4030            "returned mid-flight",
4031            2,
4032        );
4033        assert_eq!(broken.attempts, 1);
4034    }
4035
4036    #[test]
4037    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
4038        // Run e633: quorum lost because two judges answered with the wrong
4039        // JSON shape, `quota: []`. Refunding that takes the bound off the
4040        // retry loop, and each retry pays for a fresh hour-long implement
4041        // wave before it can fail the same way.
4042        let mut flaky = task();
4043        flaky.start("20260903-123023-e633".to_owned());
4044        settle(
4045            &mut flaky,
4046            Verdict {
4047                status: RunStatus::Stalled,
4048                left_pr: false,
4049                parked: false,
4050                quota_hit: false,
4051                no_viable_candidates: false,
4052            },
4053            "verdict rests on 1 of 3 judges",
4054            2,
4055        );
4056        assert_eq!(
4057            flaky.attempts, 1,
4058            "flakiness spends an attempt, so `max_attempts` still bounds it"
4059        );
4060        assert!(flaky.status.runnable(), "and it is still worth retrying");
4061
4062        // The same status, lost to a rate limit, is the machine's fault.
4063        let mut limited = task();
4064        limited.start("20260903-123023-e633".to_owned());
4065        settle(
4066            &mut limited,
4067            Verdict {
4068                status: RunStatus::Stalled,
4069                left_pr: false,
4070                parked: false,
4071                quota_hit: true,
4072                no_viable_candidates: false,
4073            },
4074            "judge-2, judge-3 out of quota",
4075            2,
4076        );
4077        assert_eq!(limited.attempts, 0, "a quota window is refunded");
4078        assert!(limited.status.runnable());
4079
4080        // And the bound really binds: a task that keeps stalling on flakiness
4081        // reaches a human instead of running the roster forever.
4082        let mut worn = task();
4083        for _ in 0..2 {
4084            worn.release();
4085        }
4086        worn.start("20260903-123023-e633".to_owned());
4087        worn.attempts = 2;
4088        settle(
4089            &mut worn,
4090            Verdict {
4091                status: RunStatus::Stalled,
4092                left_pr: false,
4093                parked: false,
4094                quota_hit: false,
4095                no_viable_candidates: false,
4096            },
4097            "no quorum again",
4098            2,
4099        );
4100        assert_eq!(worn.status, TaskStatus::Held);
4101        assert!(!worn.status.runnable());
4102    }
4103
4104    #[test]
4105    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
4106        // The implement wave loses every seat to the same rate limit and
4107        // `after_implement` bails with nothing viable, which surfaces as
4108        // `Failed` rather than `Stalled`. That is the same machine fact the
4109        // `Stalled`-quota row already refunds, and must be refunded the same
4110        // way, or a quota outage quietly holds every task it touches instead
4111        // of leaving them in line for the reset.
4112        let mut wiped_out = task();
4113        wiped_out.start("20260907-025000-a1b2".to_owned());
4114        settle(
4115            &mut wiped_out,
4116            Verdict {
4117                status: RunStatus::Failed,
4118                left_pr: false,
4119                parked: false,
4120                quota_hit: true,
4121                no_viable_candidates: true,
4122            },
4123            "no candidate produced a change; nothing to judge",
4124            2,
4125        );
4126        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
4127        assert!(
4128            wiped_out.status.runnable(),
4129            "a machine problem must leave the task in line"
4130        );
4131
4132        // This is the exemption that must stay narrow: a candidate that did
4133        // produce a change, and then failed for some other reason, still
4134        // spends the attempt even though a seat elsewhere hit its quota.
4135        // Otherwise every ordinary failure that happens to share a run with
4136        // an unrelated rate limit would be refunded for free.
4137        let mut partial_progress = task();
4138        partial_progress.start("20260907-025500-c3d4".to_owned());
4139        settle(
4140            &mut partial_progress,
4141            Verdict {
4142                status: RunStatus::Failed,
4143                left_pr: false,
4144                parked: false,
4145                quota_hit: true,
4146                no_viable_candidates: false,
4147            },
4148            "gate failed on the winning candidate",
4149            2,
4150        );
4151        assert_eq!(
4152            partial_progress.attempts, 1,
4153            "a candidate that actually produced a change spends the attempt \
4154             even though some other seat hit its quota"
4155        );
4156        assert!(partial_progress.status.runnable());
4157    }
4158
4159    #[test]
4160    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
4161        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
4162        // disk, and that construction must reach the same conclusion as the
4163        // one `attempt` builds from a live run, or a crash at exactly the
4164        // wrong moment gives a recovered task a different policy than one a
4165        // daemon finished settling itself.
4166        let mut t = task();
4167        t.start("20260907-025000-a1b2".to_owned());
4168        let mut state = run_state(RunStatus::Failed);
4169        state.quota.push(QuotaLoss {
4170            seat: "cand-a".to_owned(),
4171            node: "implement".to_owned(),
4172            at: Timestamp::now(),
4173            reset: None,
4174        });
4175        assert!(
4176            state.viable().is_empty(),
4177            "no candidate was added, so nothing is viable"
4178        );
4179        reclaim(&mut t, Some(state), 2);
4180        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
4181        assert!(t.status.runnable());
4182    }
4183
4184    #[test]
4185    fn a_held_task_is_never_offered_to_the_loop() {
4186        let dir = tempfile::tempdir().unwrap();
4187        let queue = Queue::at(dir.path().to_path_buf());
4188        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
4189            let mut t = task();
4190            t.id = format!("2026090{n}-000000-000{n}");
4191            t.priority = priority;
4192            queue.put(&mut t).unwrap();
4193        }
4194        let mut held = task();
4195        held.id = "20260909-000000-9999".to_owned();
4196        held.priority = 99;
4197        held.hold_machine(None);
4198        queue.put(&mut held).unwrap();
4199
4200        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
4201        assert_eq!(order.len(), 3);
4202        assert!(!order.contains(&held.id));
4203        assert_eq!(
4204            order.first().cloned(),
4205            queue.next_runnable().map(|t| t.id),
4206            "the loop's first candidate is exactly what the queue offers"
4207        );
4208        assert_eq!(
4209            order,
4210            vec![
4211                "20260902-000000-0002".to_owned(),
4212                "20260903-000000-0003".to_owned(),
4213                "20260901-000000-0001".to_owned(),
4214            ],
4215            "priority first, then oldest, so nothing starves"
4216        );
4217    }
4218
4219    #[test]
4220    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
4221        let dir = tempfile::tempdir().unwrap();
4222        let queue = Queue::at(dir.path().to_path_buf());
4223        let mut old = task();
4224        old.id = "20260101-000000-old0".to_owned();
4225        queue.put(&mut old).unwrap();
4226        let mut fresh = task();
4227        fresh.id = "20260101-000000-new0".to_owned();
4228        queue.put(&mut fresh).unwrap();
4229
4230        // No parseable pid at all, so age is the only signal there is to
4231        // check - unlike a real `Queue::claim`, which always names a real,
4232        // and therefore alive, pid this test cannot fake as dead.
4233        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
4234        std::thread::sleep(Duration::from_millis(60));
4235        let live = queue.claim(&fresh.id).unwrap();
4236
4237        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4238        assert_eq!(swept, vec![old.id.clone()]);
4239        assert!(
4240            queue.claim(&old.id).is_ok(),
4241            "an unparseable lock older than the threshold is swept"
4242        );
4243        assert!(
4244            queue.claim(&fresh.id).is_err(),
4245            "a live pid protects its lock regardless of age"
4246        );
4247        drop(live);
4248    }
4249
4250    #[test]
4251    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
4252        // The regression this guards: `sweep` now runs concurrently with
4253        // every attempt this daemon itself has spawned (see
4254        // `InFlightGuard`), not only between them the way a single
4255        // sequential loop once did. A run that legitimately outlives
4256        // `older_than` still has this very process's own live pid sitting in
4257        // its own lock file on every later sweep, and deciding by age alone
4258        // would delete that still-valid claim out from under the attempt
4259        // that holds it - which `reclaim_orphaned_running` would then read
4260        // as abandoned and hand to a second, competing attempt.
4261        let dir = tempfile::tempdir().unwrap();
4262        let queue = Queue::at(dir.path().to_path_buf());
4263        let mut t = task();
4264        t.id = "20260101-000000-live".to_owned();
4265        queue.put(&mut t).unwrap();
4266
4267        let claim = queue.claim(&t.id).unwrap();
4268        std::thread::sleep(Duration::from_millis(60));
4269
4270        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4271        assert!(
4272            swept.is_empty(),
4273            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
4274        );
4275        assert!(
4276            queue.claim(&t.id).is_err(),
4277            "the lock still protects its task"
4278        );
4279        drop(claim);
4280    }
4281
4282    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
4283    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
4284    fn injected_dead_pid() -> u32 {
4285        std::process::id().checked_add(1).unwrap_or(1)
4286    }
4287
4288    #[test]
4289    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
4290        let dir = tempfile::tempdir().unwrap();
4291        let queue = Queue::at(dir.path().to_path_buf());
4292        let mut t = task();
4293        t.id = "20260101-000000-dead".to_owned();
4294        queue.put(&mut t).unwrap();
4295        let dead_pid = injected_dead_pid();
4296
4297        // Written directly rather than through `Queue::claim`, which would
4298        // stamp this test process's own very much alive pid and defeat the
4299        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
4300        // like moments after it died, not six hours later.
4301        std::fs::write(
4302            dir.path().join(format!("{}.lock", t.id)),
4303            dead_pid.to_string(),
4304        )
4305        .unwrap();
4306
4307        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4308            pid != dead_pid
4309        });
4310        assert_eq!(
4311            swept,
4312            vec![t.id.clone()],
4313            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
4314        );
4315        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
4316    }
4317
4318    #[test]
4319    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
4320        let dir = tempfile::tempdir().unwrap();
4321        let queue = Queue::at(dir.path().to_path_buf());
4322        let mut t = task();
4323        t.id = "20260101-000000-late".to_owned();
4324        queue.put(&mut t).unwrap();
4325        let dead_pid = injected_dead_pid();
4326
4327        // Tick one, standing in for the sweep `poll` already runs at
4328        // startup: nothing to find yet.
4329        assert!(
4330            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
4331            "nothing has claimed the task yet"
4332        );
4333
4334        // A second daemon claims the task and dies before it ever writes
4335        // `running`, well after this loop's own startup sweep already ran.
4336        std::fs::write(
4337            dir.path().join(format!("{}.lock", t.id)),
4338            dead_pid.to_string(),
4339        )
4340        .unwrap();
4341
4342        // Tick two, standing in for a poll long into this daemon's uptime:
4343        // the same function, called again, notices what only just appeared -
4344        // proving the sweep is not a one-shot startup check.
4345        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4346            pid != dead_pid
4347        });
4348        assert_eq!(swept, vec![t.id.clone()]);
4349    }
4350
4351    #[test]
4352    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
4353        // `reclaim_orphaned_running` looks up the task's last run, which
4354        // touches `run::home()`; the first call anywhere in this binary wins,
4355        // so this is a no-op if another test already pinned one, and either
4356        // way the run id below is never written under it.
4357        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4358        let dir = tempfile::tempdir().unwrap();
4359        let queue = Queue::at(dir.path().to_path_buf());
4360        let mut t = task();
4361        t.id = "20260101-000000-crsh".to_owned();
4362        t.status = TaskStatus::Running;
4363        t.attempts = 1;
4364        // No `run.json` behind this id: standing in for a run this test does
4365        // not need to make readable, since the point is the lock, not the
4366        // recovery table `reclaim` already has its own tests for.
4367        t.runs.push("20260904-000000-4043".to_owned());
4368        queue.put(&mut t).unwrap();
4369        let dead_pid = injected_dead_pid();
4370
4371        // The crashed daemon's own claim, naming a pid nothing on the
4372        // machine holds anymore.
4373        std::fs::write(
4374            dir.path().join(format!("{}.lock", t.id)),
4375            dead_pid.to_string(),
4376        )
4377        .unwrap();
4378
4379        // Before the lock is swept the task looks claimed, and
4380        // `reclaim_orphaned_running` must leave it alone - this is exactly
4381        // the bug: a `running` task stranded behind a dead daemon's lock,
4382        // invisible to the claim-as-proof check because the lock outlived
4383        // the process that wrote it.
4384        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
4385        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
4386
4387        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4388            pid != dead_pid
4389        });
4390        assert_eq!(swept, vec![t.id.clone()]);
4391
4392        let reclaimed = reclaim_orphaned_running(&queue, 2);
4393        assert_eq!(reclaimed, vec![t.id.clone()]);
4394        let after = queue.get(&t.id).unwrap();
4395        assert_eq!(
4396            after.status,
4397            TaskStatus::Held,
4398            "no run.json to recover from, so a human is asked"
4399        );
4400        assert_eq!(
4401            after.runs,
4402            vec!["20260904-000000-4043".to_owned()],
4403            "the crashed run's id is kept as evidence, not discarded"
4404        );
4405    }
4406
4407    #[test]
4408    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
4409        let dir = tempfile::tempdir().unwrap();
4410        let queue = Queue::at(dir.path().to_path_buf());
4411        let mut t = task();
4412        t.id = "20260101-000000-unknown".to_owned();
4413        queue.put(&mut t).unwrap();
4414        let dead_pid = injected_dead_pid();
4415        std::fs::write(
4416            dir.path().join(format!("{}.lock", t.id)),
4417            dead_pid.to_string(),
4418        )
4419        .unwrap();
4420
4421        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
4422        assert!(swept.is_empty(), "an unknown pid must keep its lock");
4423        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
4424    }
4425
4426    fn run_state(status: RunStatus) -> RunState {
4427        let mut state = RunState::new(
4428            PathBuf::from("/repo"),
4429            "main".to_owned(),
4430            "abc1234def".to_owned(),
4431            "add retries".to_owned(),
4432            Config::default(),
4433        );
4434        state.status = status;
4435        state
4436    }
4437
4438    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
4439        Candidate {
4440            index: 0,
4441            label,
4442            agent: "claude".to_owned(),
4443            branch: format!("magi/x/{label}"),
4444            worktree: PathBuf::from("/repo"),
4445            summary: summary.to_owned(),
4446            stat: String::new(),
4447            files: 0,
4448            commits: usize::from(!empty),
4449            empty,
4450            failed: failed.map(str::to_owned),
4451            verified_noop: None,
4452            duration_ms: 0,
4453            folded: false,
4454        }
4455    }
4456
4457    #[test]
4458    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
4459        let mut state = run_state(RunStatus::Blocked);
4460        state.gate = vec![
4461            CommandOutcome {
4462                command: "cargo make check".to_owned(),
4463                code: Some(0),
4464                output_tail: "ok".to_owned(),
4465                duration_ms: 0,
4466                resource_blocked: false,
4467            },
4468            CommandOutcome {
4469                command: "cargo test".to_owned(),
4470                code: Some(101),
4471                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
4472                duration_ms: 0,
4473                resource_blocked: false,
4474            },
4475        ];
4476        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
4477        assert!(d.contains("cargo test"), "{d}");
4478        assert!(
4479            !d.contains("cargo make check"),
4480            "a passing check is not a diagnostic: {d}"
4481        );
4482        assert!(d.contains("assertion failed"), "{d}");
4483    }
4484
4485    #[test]
4486    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
4487        let mut state = run_state(RunStatus::Blocked);
4488        state.event(
4489            "land",
4490            "stopped: the fixer produced no commit while 2 check(s) were failing \
4491             (build, lint); stopping instead of looping on an unchanged tree",
4492        );
4493        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
4494        assert!(d.contains("build"), "{d}");
4495        assert!(d.contains("lint"), "{d}");
4496        assert!(d.contains("fixer produced no commit"), "{d}");
4497    }
4498
4499    #[test]
4500    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
4501        // `describe`'s output becomes `Task::last_error` verbatim, and the
4502        // phone renders that in the same alarm-styled box an ordinary
4503        // failure gets. A bare `verified_noop` there would read exactly like
4504        // the failure this status exists to be told apart from.
4505        let state = run_state(RunStatus::VerifiedNoop);
4506        let d = describe(&state);
4507        assert!(
4508            d.contains("agent-verified no-op"),
4509            "expected the display label, not the wire spelling: {d}"
4510        );
4511        assert!(!d.contains("verified_noop"), "{d}");
4512    }
4513
4514    #[test]
4515    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
4516        // The whole point of the feature: a run held as "no candidate produced
4517        // a change" can mean the implementer actually finished the task and
4518        // only left a clean local tree behind - see AGENTS.md on this exact
4519        // failure mode. The diagnostic has to carry what the agent actually
4520        // said, not just the fact that nothing was there to judge.
4521        let mut state = run_state(RunStatus::Failed);
4522        state.candidates = vec![candidate(
4523            'A',
4524            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
4525            true,
4526            None,
4527        )];
4528        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
4529        assert!(d.contains("candidate A"), "{d}");
4530        assert!(d.contains("tagged v1.2.3"), "{d}");
4531    }
4532
4533    #[test]
4534    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
4535        let mut state = run_state(RunStatus::Failed);
4536        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
4537        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
4538        assert!(d.contains("candidate A"), "{d}");
4539        assert!(d.contains("agent timed out"), "{d}");
4540    }
4541
4542    #[test]
4543    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
4544        // A viable candidate existed, the gate never ran, and nothing land
4545        // said matches - `Task::last_error` is left to explain this one alone.
4546        let mut state = run_state(RunStatus::Failed);
4547        state.candidates = vec![candidate('A', "did the work", false, None)];
4548        assert!(diagnostic(&state).is_none());
4549    }
4550
4551    #[test]
4552    fn diagnostic_is_bounded_however_much_a_run_printed() {
4553        let mut state = run_state(RunStatus::Blocked);
4554        state.gate = vec![
4555            CommandOutcome {
4556                command: "cargo test".to_owned(),
4557                code: Some(101),
4558                output_tail: "x".repeat(50_000),
4559                duration_ms: 0,
4560                resource_blocked: false,
4561            },
4562            CommandOutcome {
4563                command: "cargo clippy".to_owned(),
4564                code: Some(1),
4565                output_tail: "y".repeat(50_000),
4566                duration_ms: 0,
4567                resource_blocked: false,
4568            },
4569        ];
4570        state.candidates = vec![
4571            candidate('A', &"z".repeat(50_000), true, None),
4572            candidate('B', &"w".repeat(50_000), true, None),
4573        ];
4574        let d = diagnostic(&state).expect("plenty here to diagnose");
4575        assert!(
4576            d.len() <= DIAGNOSTIC_MAX,
4577            "diagnostic grew to {} bytes, unbounded",
4578            d.len()
4579        );
4580    }
4581
4582    #[test]
4583    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
4584        let mut state = run_state(RunStatus::Blocked);
4585        state.gate = vec![CommandOutcome {
4586            command: "cargo test".to_owned(),
4587            code: Some(101),
4588            output_tail: "assertion failed".to_owned(),
4589            duration_ms: 0,
4590            resource_blocked: false,
4591        }];
4592        let verdict = Verdict {
4593            status: RunStatus::Blocked,
4594            left_pr: false,
4595            quota_hit: false,
4596            parked: false,
4597            no_viable_candidates: false,
4598        };
4599
4600        // Attempt one of two still has a retry coming: no diagnostic yet, the
4601        // task is going to run again and this run's evidence would go stale.
4602        let mut t = task();
4603        t.start("run-1".to_owned());
4604        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4605        assert_eq!(t.status, TaskStatus::Failed);
4606        assert!(t.diagnostic.is_none());
4607
4608        // Attempt two exhausts the budget: now it is held, and the
4609        // diagnostic is what `magi task show` has to say more than one line.
4610        t.start("run-2".to_owned());
4611        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4612        assert_eq!(t.status, TaskStatus::Held);
4613        let d = t.diagnostic.expect("a held task must carry its diagnostic");
4614        assert!(d.contains("cargo test"), "{d}");
4615    }
4616
4617    #[test]
4618    fn a_held_task_names_the_open_question_it_is_waiting_on() {
4619        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
4620        // `magi ask` question settled Held with `hold_reason: null`, so the
4621        // notification said nothing actionable. `note_open_question` should
4622        // append the question id to whatever `handed_off` already wrote.
4623        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4624        let home = crate::run::home();
4625        let state = run_state(RunStatus::VerifiedNoop);
4626        let mut q = ask::Question::new(
4627            state.id.clone(),
4628            "implement".to_owned(),
4629            "impl-A".to_owned(),
4630            "is this really a no-op?".to_owned(),
4631            String::new(),
4632            Vec::new(),
4633        );
4634        Questions::at(home.join("questions")).put(&mut q).unwrap();
4635
4636        let verdict = Verdict {
4637            status: RunStatus::VerifiedNoop,
4638            left_pr: false,
4639            quota_hit: false,
4640            parked: false,
4641            no_viable_candidates: false,
4642        };
4643        let mut t = task();
4644        t.start(state.id.clone());
4645        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
4646
4647        assert_eq!(t.status, TaskStatus::Held);
4648        let reason = t.hold_reason.expect("a held task must record why");
4649        assert!(
4650            reason.starts_with("run ended agent-verified no-op"),
4651            "the original settle reason must survive unchanged: {reason}"
4652        );
4653        assert!(
4654            reason.contains(q.short()),
4655            "the open question's id must be named so the notice is actionable: {reason}"
4656        );
4657    }
4658
4659    #[test]
4660    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
4661        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4662        let state = run_state(RunStatus::VerifiedNoop);
4663
4664        let verdict = Verdict {
4665            status: RunStatus::VerifiedNoop,
4666            left_pr: false,
4667            quota_hit: false,
4668            parked: false,
4669            no_viable_candidates: false,
4670        };
4671        let mut t = task();
4672        t.start(state.id.clone());
4673        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
4674
4675        assert_eq!(t.status, TaskStatus::Held);
4676        assert_eq!(
4677            t.hold_reason.as_deref(),
4678            Some("run ended agent-verified no-op"),
4679            "nothing to append when the question was already answered or never asked"
4680        );
4681    }
4682
4683    #[test]
4684    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
4685        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4686        let mut first = run_state(RunStatus::Blocked);
4687        first.id = "20260101-000000-sup1".to_owned();
4688        first.save().unwrap();
4689        let mut second = run_state(RunStatus::Merged);
4690        second.id = "20260101-000000-sup2".to_owned();
4691        second.save().unwrap();
4692
4693        let mut t = task();
4694        t.runs = vec![first.id.clone(), second.id.clone()];
4695        t.status = TaskStatus::Done;
4696
4697        supersede_prior_runs(&t, &crate::run::home());
4698
4699        assert_eq!(
4700            RunState::load(&first.id).unwrap().status,
4701            RunStatus::Superseded,
4702            "the first attempt's Blocked no longer needs anyone's attention"
4703        );
4704        assert_eq!(
4705            RunState::load(&second.id).unwrap().status,
4706            RunStatus::Merged,
4707            "the run that actually succeeded is left exactly as it was"
4708        );
4709    }
4710
4711    #[test]
4712    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
4713        // `is_working_on` alone only proves a *daemon* claim; a `magi run
4714        // --resume` invoked by hand outside the daemon never touches
4715        // `daemon.json` at all, so it would look identical to a genuinely
4716        // idle run without also consulting `RunState::liveness`, which reads
4717        // this run's own recorded `driver_pid` instead.
4718        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4719        let mut first = run_state(RunStatus::Blocked);
4720        first.id = "20260101-000000-sup9".to_owned();
4721        // This test process's own pid: guaranteed alive without needing a
4722        // real second process or daemon.
4723        first.driver_pid = Some(std::process::id());
4724        first.driver_started_at = Some(
4725            crate::proc::process_started_at(std::process::id())
4726                .expect("this test process's own start time must be queryable"),
4727        );
4728        first.save().unwrap();
4729        let mut second = run_state(RunStatus::Merged);
4730        second.id = "20260101-000000-supa".to_owned();
4731        second.save().unwrap();
4732
4733        let mut t = task();
4734        t.runs = vec![first.id.clone(), second.id.clone()];
4735        t.status = TaskStatus::Done;
4736
4737        supersede_prior_runs(&t, &crate::run::home());
4738
4739        assert_eq!(
4740            RunState::load(&first.id).unwrap().status,
4741            RunStatus::Blocked,
4742            "a live driver_pid means something is still actually working this run, \
4743             even though no daemon claims it - rewriting under it would just be \
4744             undone the next time that process saves"
4745        );
4746    }
4747
4748    #[test]
4749    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
4750        // The first resweep must skip a still-live attempt exactly like
4751        // `supersede_prior_runs` itself does; a later resweep, once that
4752        // process is no longer actually driving it, is what closes the gap
4753        // `supersede_prior_runs` alone leaves - a task only ever reaches
4754        // `Done` once, so nothing else would ever look at this run again.
4755        let dir = tempfile::tempdir().unwrap();
4756        let home = dir.path().to_path_buf();
4757        let queue = Queue::at(dir.path().join("queue"));
4758
4759        let mut first = run_state(RunStatus::Blocked);
4760        first.id = "20260101-000000-supd".to_owned();
4761        first.driver_pid = Some(std::process::id());
4762        first.driver_started_at = Some(
4763            crate::proc::process_started_at(std::process::id())
4764                .expect("this test process's own start time must be queryable"),
4765        );
4766        first.save_under(&home).unwrap();
4767        let mut second = run_state(RunStatus::Merged);
4768        second.id = "20260101-000000-supe".to_owned();
4769        second.save_under(&home).unwrap();
4770
4771        let mut t = task();
4772        t.runs = vec![first.id.clone(), second.id.clone()];
4773        t.status = TaskStatus::Done;
4774        queue.put(&mut t).unwrap();
4775
4776        resweep_superseded_attempts(&queue, &home);
4777        assert_eq!(
4778            RunState::load_under(&first.id, &home).unwrap().status,
4779            RunStatus::Blocked,
4780            "still live on the first pass, so still untouched"
4781        );
4782
4783        // Stand in for the manual process no longer being the one driving
4784        // this run: same pid (this test process really is still alive), but
4785        // an identity marker that no longer matches it - see
4786        // `RunState::liveness`'s own doc for why a mismatched
4787        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
4788        let mut stale = RunState::load_under(&first.id, &home).unwrap();
4789        stale.driver_started_at = Some("not-this-processes-real-start-time".to_owned());
4790        stale.save_under(&home).unwrap();
4791
4792        resweep_superseded_attempts(&queue, &home);
4793        assert_eq!(
4794            RunState::load_under(&first.id, &home).unwrap().status,
4795            RunStatus::Superseded,
4796            "the second pass catches up what the first one correctly skipped"
4797        );
4798    }
4799
4800    #[test]
4801    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
4802        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4803        let mut first = run_state(RunStatus::Blocked);
4804        first.id = "20260101-000000-sup3".to_owned();
4805        first.save().unwrap();
4806        let mut second = run_state(RunStatus::Blocked);
4807        second.id = "20260101-000000-sup4".to_owned();
4808        second.save().unwrap();
4809
4810        let mut t = task();
4811        t.runs = vec![first.id.clone(), second.id.clone()];
4812        // Still retrying: nothing about this task's story is settled yet, so
4813        // neither Blocked run may be relabelled, even though a later attempt
4814        // already exists.
4815        t.status = TaskStatus::Failed;
4816
4817        supersede_prior_runs(&t, &crate::run::home());
4818
4819        assert_eq!(
4820            RunState::load(&first.id).unwrap().status,
4821            RunStatus::Blocked
4822        );
4823        assert_eq!(
4824            RunState::load(&second.id).unwrap().status,
4825            RunStatus::Blocked
4826        );
4827    }
4828
4829    #[test]
4830    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
4831        // `magi task done` (or the API's equivalent) can close a task with no
4832        // run of its own ever having succeeded - there is nothing here that
4833        // counts as "the attempt that finished it", so nothing is rewritten.
4834        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4835        let mut first = run_state(RunStatus::Blocked);
4836        first.id = "20260101-000000-sup5".to_owned();
4837        first.save().unwrap();
4838
4839        let mut t = task();
4840        t.runs = vec![first.id.clone()];
4841        t.status = TaskStatus::Done;
4842
4843        supersede_prior_runs(&t, &crate::run::home());
4844
4845        assert_eq!(
4846            RunState::load(&first.id).unwrap().status,
4847            RunStatus::Blocked,
4848            "a single-attempt task has no earlier run to supersede"
4849        );
4850    }
4851
4852    #[test]
4853    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
4854        // `magi task done` (or the web/conductor equivalents) can close a
4855        // task in any status, including one whose *last* recorded attempt is
4856        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
4857        // never watched, say. `runs.last()` being `Done`-adjacent is not
4858        // proof it actually succeeded, so nothing earlier may be relabelled
4859        // on its say-so alone.
4860        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4861        let mut first = run_state(RunStatus::Blocked);
4862        first.id = "20260101-000000-supb".to_owned();
4863        first.save().unwrap();
4864        let mut second = run_state(RunStatus::Failed);
4865        second.id = "20260101-000000-supc".to_owned();
4866        second.save().unwrap();
4867
4868        let mut t = task();
4869        t.runs = vec![first.id.clone(), second.id.clone()];
4870        t.status = TaskStatus::Done;
4871
4872        supersede_prior_runs(&t, &crate::run::home());
4873
4874        assert_eq!(
4875            RunState::load(&first.id).unwrap().status,
4876            RunStatus::Blocked,
4877            "the task's last attempt never landed, so there is nothing here \
4878             actually superseding it"
4879        );
4880    }
4881
4882    #[test]
4883    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
4884        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
4885        // to look" - `Failed` and `VerifiedNoop` are already their own
4886        // terminal answers and must not be relabelled into a third one.
4887        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4888        let mut failed = run_state(RunStatus::Failed);
4889        failed.id = "20260101-000000-sup6".to_owned();
4890        failed.save().unwrap();
4891        let mut noop = run_state(RunStatus::VerifiedNoop);
4892        noop.id = "20260101-000000-sup7".to_owned();
4893        noop.save().unwrap();
4894        let mut winner = run_state(RunStatus::Ready);
4895        winner.id = "20260101-000000-sup8".to_owned();
4896        winner.save().unwrap();
4897
4898        let mut t = task();
4899        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
4900        t.status = TaskStatus::Done;
4901
4902        supersede_prior_runs(&t, &crate::run::home());
4903
4904        assert_eq!(
4905            RunState::load(&failed.id).unwrap().status,
4906            RunStatus::Failed
4907        );
4908        assert_eq!(
4909            RunState::load(&noop.id).unwrap().status,
4910            RunStatus::VerifiedNoop
4911        );
4912    }
4913
4914    fn approval_question(run: &str) -> ask::Question {
4915        ask::Question::new(
4916            run.to_owned(),
4917            land::APPROVAL_NODE.to_owned(),
4918            "land".to_owned(),
4919            "merge?".to_owned(),
4920            String::new(),
4921            vec!["merge".to_owned(), "hold".to_owned()],
4922        )
4923    }
4924
4925    #[test]
4926    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
4927        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4928        let mut state = run_state(RunStatus::Landing);
4929        state.id = "20260101-000000-fre1".to_owned();
4930        state.parked = true;
4931        state.save().unwrap();
4932        ask::Questions::open()
4933            .put(&mut approval_question(&state.id))
4934            .unwrap();
4935
4936        let mut t = task();
4937        t.runs.push(state.id.clone());
4938        assert_eq!(
4939            land_resume_state(&t),
4940            LandResume::StillWaiting,
4941            "nobody has answered and the timeout has not passed"
4942        );
4943    }
4944
4945    #[test]
4946    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
4947        // `ask::ask_and_wait`'s own deadline used to retire a question
4948        // nobody answered; land's approval bypasses that wait (see
4949        // `land::approval_gate`), so this is now the only place
4950        // `graph.answer_timeout` is enforced for a land approval at all.
4951        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4952        let mut state = run_state(RunStatus::Landing);
4953        state.id = "20260101-000000-exp1".to_owned();
4954        state.parked = true;
4955        state.config.graph.answer_timeout = 60;
4956        state.save().unwrap();
4957
4958        let store = ask::Questions::open();
4959        let mut q = approval_question(&state.id);
4960        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
4961        store.put(&mut q).unwrap();
4962
4963        let mut t = task();
4964        t.runs.push(state.id.clone());
4965        assert_eq!(
4966            land_resume_state(&t),
4967            LandResume::Ready,
4968            "an expired question must not be waited on forever"
4969        );
4970
4971        let after = store.get(&q.id).unwrap();
4972        assert!(
4973            !after.status.open(),
4974            "the question is abandoned, not silently ignored"
4975        );
4976        assert!(
4977            after.resolution().is_none(),
4978            "an abandoned question is not read as a decision"
4979        );
4980    }
4981
4982    #[test]
4983    fn reclaim_settles_a_running_task_against_its_last_run() {
4984        let mut t = task();
4985        t.start("20260904-000000-4043".to_owned());
4986        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
4987        assert_eq!(
4988            t.status,
4989            TaskStatus::Done,
4990            "a run that actually finished must not stay `running` forever"
4991        );
4992    }
4993
4994    #[test]
4995    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
4996        // A blocked run with attempts left goes back to `Failed`, exactly as
4997        // it would from `attempt` itself - `reclaim` must not invent a second
4998        // policy for a task a daemon merely stopped without reporting.
4999        let mut t = task();
5000        t.start("20260904-000000-4043".to_owned());
5001        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
5002        assert_eq!(t.status, TaskStatus::Failed);
5003        assert!(t.status.runnable());
5004    }
5005
5006    #[test]
5007    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
5008        let mut t = task();
5009        t.start("20260904-000000-4043".to_owned());
5010        reclaim(&mut t, None, 2);
5011        assert_eq!(t.status, TaskStatus::Held);
5012        assert!(
5013            t.last_error
5014                .as_deref()
5015                .is_some_and(|e| e.contains("running")),
5016            "the operator needs to know why this task was held"
5017        );
5018    }
5019
5020    #[test]
5021    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
5022        let dir = tempfile::tempdir().unwrap();
5023        let queue = Queue::at(dir.path().to_path_buf());
5024
5025        // No run recorded, so this never has to touch `RunState::load`.
5026        let mut orphaned = task();
5027        orphaned.id = "20260904-000000-orph".to_owned();
5028        orphaned.status = TaskStatus::Running;
5029        orphaned.attempts = 1;
5030        queue.put(&mut orphaned).unwrap();
5031
5032        let mut alive = task();
5033        alive.id = "20260904-000000-live".to_owned();
5034        alive.status = TaskStatus::Running;
5035        alive.attempts = 1;
5036        queue.put(&mut alive).unwrap();
5037        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
5038
5039        let mut queued = task();
5040        queued.id = "20260904-000000-wait".to_owned();
5041        queue.put(&mut queued).unwrap();
5042
5043        let reclaimed = reclaim_orphaned_running(&queue, 2);
5044        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
5045
5046        assert_eq!(
5047            queue.get(&orphaned.id).unwrap().status,
5048            TaskStatus::Held,
5049            "nothing was driving it and there was no run to recover"
5050        );
5051        assert_eq!(
5052            queue.get(&alive.id).unwrap().status,
5053            TaskStatus::Running,
5054            "a live claim must protect the task it belongs to"
5055        );
5056        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
5057    }
5058
5059    /// Read a run.json back from an explicit `home`, the same way
5060    /// `reclaim_abandoned_runs` itself does - never through the
5061    /// process-global `RunState::load`, which this test's own `home` (an
5062    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
5063    /// use at all.
5064    fn read_run_under(home: &Path, id: &str) -> RunState {
5065        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
5066        serde_json::from_str(&body).unwrap()
5067    }
5068
5069    #[test]
5070    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
5071        let dir = tempfile::tempdir().unwrap();
5072        let home = dir.path().to_path_buf();
5073        let now = Timestamp::now();
5074        let overrun_seat = || crate::run::ActiveSeat {
5075            node: "implement".to_owned(),
5076            started_at: now - jiff::SignedDuration::new(21_000, 0),
5077            timeout_secs: 3_600,
5078            attempt: 0,
5079            task: None,
5080            command: None,
5081            index: None,
5082            total: None,
5083        };
5084
5085        let mut dead = run_state(RunStatus::Implementing);
5086        dead.id = "20260101-000000-dead".to_owned();
5087        dead.active.insert("impl-A".to_owned(), overrun_seat());
5088        // A `driver_pid` the injected query below confirms gone outright —
5089        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
5090        dead.driver_pid = Some(4242);
5091        dead.save_under(&home).unwrap();
5092
5093        // Same shape, but a live daemon's heartbeat names it: must be left
5094        // exactly alone, however far past its own timeout the seat sits.
5095        let mut alive = run_state(RunStatus::Implementing);
5096        alive.id = "20260101-000000-aliv".to_owned();
5097        alive.active.insert("impl-A".to_owned(), overrun_seat());
5098        alive.save_under(&home).unwrap();
5099        let mut status = Status::new();
5100        status.current = vec![Current {
5101            task: "20260101-000000-task".to_owned(),
5102            run: alive.id.clone(),
5103        }];
5104        write_status_to(&home.join("daemon.json"), &status).unwrap();
5105
5106        // The abandoned seat left an open question behind: nobody is left to
5107        // read an answer once the run is failed, and this must not wait for
5108        // some later daemon startup's own sweep to notice that.
5109        let questions = Questions::at(home.join("questions"));
5110        let mut q = ask::Question::new(
5111            dead.id.clone(),
5112            "implement".to_owned(),
5113            "impl-A".to_owned(),
5114            "Which storage backend?".to_owned(),
5115            String::new(),
5116            vec!["SQLite".to_owned(), "Redis".to_owned()],
5117        );
5118        questions.put(&mut q).unwrap();
5119
5120        let abandoned = reclaim_abandoned_runs_with(
5121            &home,
5122            now,
5123            |pid| if pid == 4242 { Some(false) } else { None },
5124            |_| panic!("a query answering Dead outright needs no identity corroboration"),
5125        );
5126        assert_eq!(abandoned, vec![dead.id.clone()]);
5127
5128        let reloaded = read_run_under(&home, &dead.id);
5129        assert_eq!(reloaded.status, RunStatus::Failed);
5130        assert!(reloaded.active.is_empty());
5131        assert!(
5132            !questions.get(&q.id).unwrap().status.open(),
5133            "the failed run's own open question must be settled in the same pass"
5134        );
5135
5136        let still_alive = read_run_under(&home, &alive.id);
5137        assert_eq!(
5138            still_alive.status,
5139            RunStatus::Implementing,
5140            "a live daemon's claim protects it"
5141        );
5142        assert!(!still_alive.active.is_empty());
5143    }
5144
5145    /// The exact shape a review round flagged as broken: `magi serve` running
5146    /// in this same `home` scans *every* run on disk, including a manual
5147    /// `magi review` / `magi run` this daemon never started and that
5148    /// therefore claims no heartbeat of its own. Before this scan asked
5149    /// `liveness` rather than just `is_working_on`, a manual run whose active
5150    /// seat merely ran a little past its own timeout — the CLI finishing up,
5151    /// its result still being collected — got wiped and failed by a daemon
5152    /// that had nothing to do with it, out from under a process that was
5153    /// still very much running.
5154    #[test]
5155    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
5156        let dir = tempfile::tempdir().unwrap();
5157        let home = dir.path().to_path_buf();
5158        let now = Timestamp::now();
5159
5160        let mut manual = run_state(RunStatus::Reviewing);
5161        manual.id = "20260101-000000-manl".to_owned();
5162        manual.active.insert(
5163            "review-1".to_owned(),
5164            crate::run::ActiveSeat {
5165                node: "review".to_owned(),
5166                started_at: now - jiff::SignedDuration::new(21_000, 0),
5167                timeout_secs: 3_600,
5168                attempt: 0,
5169                task: None,
5170                command: None,
5171                index: None,
5172                total: None,
5173            },
5174        );
5175        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
5176        // but a real, still-running process: `liveness` must corroborate this
5177        // as `Live`, not read the missing daemon claim as death.
5178        manual.driver_pid = Some(4242);
5179        manual.driver_started_at = Some("2026-09-22T10:00:00Z".to_owned());
5180        manual.save_under(&home).unwrap();
5181
5182        let abandoned = reclaim_abandoned_runs_with(
5183            &home,
5184            now,
5185            |pid| if pid == 4242 { Some(true) } else { None },
5186            |pid| {
5187                if pid == 4242 {
5188                    Some("2026-09-22T10:00:00Z".to_owned())
5189                } else {
5190                    None
5191                }
5192            },
5193        );
5194        assert!(
5195            abandoned.is_empty(),
5196            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
5197        );
5198
5199        let reloaded = read_run_under(&home, &manual.id);
5200        assert_eq!(reloaded.status, RunStatus::Reviewing);
5201        assert!(!reloaded.active.is_empty());
5202    }
5203
5204    #[test]
5205    fn an_already_claimed_task_is_skipped_rather_than_failed() {
5206        let dir = tempfile::tempdir().unwrap();
5207        let queue = Queue::at(dir.path().to_path_buf());
5208        let mut only = task();
5209        queue.put(&mut only).unwrap();
5210
5211        let _elsewhere = queue.claim(&only.id).unwrap();
5212        let candidates = runnable(&queue);
5213        assert_eq!(candidates.len(), 1, "the task is still runnable");
5214        assert!(
5215            queue.claim(&candidates[0].id).is_err(),
5216            "the loop cannot take a claim somebody else holds"
5217        );
5218
5219        let after = queue.get(&only.id).unwrap();
5220        assert_eq!(after.status, TaskStatus::Queued);
5221        assert_eq!(
5222            after.attempts, 0,
5223            "losing the race is not an attempt at the task"
5224        );
5225        assert_eq!(after.last_error, None);
5226    }
5227
5228    #[test]
5229    fn the_status_file_round_trips_and_its_heartbeat_advances() {
5230        let dir = tempfile::tempdir().unwrap();
5231        let path = dir.path().join("daemon.json");
5232
5233        let mut status = Status::new();
5234        status.idle = false;
5235        status.completed = 7;
5236        status.current = vec![Current {
5237            task: "20260902-000000-t111".to_owned(),
5238            run: "20260902-000001-r111".to_owned(),
5239        }];
5240        write_status_to(&path, &status).unwrap();
5241        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5242        assert_eq!(first.schema, SCHEMA);
5243        assert_eq!(first.pid, std::process::id());
5244        assert!(!first.idle);
5245        assert_eq!(first.completed, 7);
5246        assert_eq!(first.current, status.current);
5247        assert!(
5248            !path.with_extension("json.tmp").exists(),
5249            "the temp file is renamed, not left behind"
5250        );
5251
5252        std::thread::sleep(Duration::from_millis(5));
5253        status.updated_at = Timestamp::now();
5254        status.polls = 3;
5255        write_status_to(&path, &status).unwrap();
5256        let second: Status =
5257            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5258        assert!(
5259            second.updated_at > first.updated_at,
5260            "a reader can only detect staleness if the heartbeat moves"
5261        );
5262        assert_eq!(
5263            second.started_at, first.started_at,
5264            "the start time is not a heartbeat"
5265        );
5266        assert_eq!(second.polls, 3);
5267    }
5268
5269    #[test]
5270    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
5271        let dir = tempfile::tempdir().unwrap();
5272
5273        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
5274
5275        let mut status = Status::new();
5276        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
5277        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5278        let stale = read_status(dir.path()).unwrap();
5279        assert!(
5280            !stale.running(Timestamp::now()),
5281            "a minute without a heartbeat is a dead daemon, not a busy one"
5282        );
5283        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
5284
5285        status.updated_at = Timestamp::now();
5286        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5287        let fresh = read_status(dir.path()).unwrap();
5288        assert!(fresh.running(Timestamp::now()));
5289    }
5290
5291    #[test]
5292    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
5293        let dir = tempfile::tempdir().unwrap();
5294        let now = Timestamp::now();
5295        let mine = "20260903-080619-01c2";
5296
5297        assert!(
5298            !is_working_on(dir.path(), mine, now),
5299            "no status file means nobody is working on anything"
5300        );
5301
5302        let mut status = Status::new();
5303        status.current = vec![Current {
5304            task: "20260903-080340-0167".to_owned(),
5305            run: mine.to_owned(),
5306        }];
5307        status.updated_at = now;
5308        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5309        assert!(is_working_on(dir.path(), mine, now));
5310        assert!(
5311            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
5312            "a daemon busy with one run is not working on another"
5313        );
5314
5315        // A killed daemon stops writing heartbeats but leaves the file behind
5316        // naming the run it died in. That run must not be undeletable forever.
5317        status.updated_at = now - jiff::SignedDuration::from_secs(600);
5318        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5319        assert!(
5320            !is_working_on(dir.path(), mine, now),
5321            "a stale heartbeat is a dead daemon, so its run is a leftover"
5322        );
5323    }
5324
5325    #[test]
5326    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
5327        let dir = tempfile::tempdir().unwrap();
5328        let now = Timestamp::now();
5329
5330        assert!(
5331            !is_working_on_short(dir.path(), "01c2", now),
5332            "no status file means nobody is working on anything"
5333        );
5334
5335        let mut status = Status::new();
5336        status.current = vec![Current {
5337            task: "20260903-080340-0167".to_owned(),
5338            run: "20260903-080619-01c2".to_owned(),
5339        }];
5340        status.updated_at = now;
5341        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5342        assert!(
5343            is_working_on_short(dir.path(), "01c2", now),
5344            "the run's short id is the last block of its full id"
5345        );
5346        assert!(
5347            !is_working_on_short(dir.path(), "3cbf", now),
5348            "a daemon busy with one worktree bay is not working on another"
5349        );
5350    }
5351
5352    #[test]
5353    fn a_newer_status_file_still_yields_a_reading() {
5354        let dir = tempfile::tempdir().unwrap();
5355        // A field this build has never heard of must not turn the reading into
5356        // nothing at all; that is the whole reason the reader is permissive.
5357        std::fs::write(
5358            dir.path().join("daemon.json"),
5359            serde_json::json!({
5360                "schema": 2,
5361                "updated_at": Timestamp::now().to_string(),
5362                "idle": true,
5363                "surprise": { "nested": [1, 2, 3] },
5364            })
5365            .to_string(),
5366        )
5367        .unwrap();
5368
5369        let reading = read_status(dir.path()).expect("a forward-compatible read");
5370        assert!(reading.running(Timestamp::now()));
5371        assert!(reading.idle);
5372        assert!(reading.current.is_empty());
5373    }
5374
5375    #[test]
5376    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
5377        // A daemon started before `current` became a list keeps writing this
5378        // shape on every heartbeat until it is restarted. A rolling upgrade
5379        // - a newer `magi web` or `magi doctor` reading an older `magi
5380        // serve`'s heartbeat - must still see the run it is on, not "no
5381        // daemon" from a type mismatch failing the whole struct.
5382        let dir = tempfile::tempdir().unwrap();
5383        std::fs::write(
5384            dir.path().join("daemon.json"),
5385            serde_json::json!({
5386                "schema": 1,
5387                "pid": 4242,
5388                "updated_at": Timestamp::now().to_string(),
5389                "idle": false,
5390                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
5391                "completed": 3,
5392                "polls": 9,
5393            })
5394            .to_string(),
5395        )
5396        .unwrap();
5397
5398        let reading = read_status(dir.path()).expect("an older shape must still parse");
5399        assert!(reading.running(Timestamp::now()));
5400        assert_eq!(
5401            reading.current,
5402            vec![Current {
5403                task: "20260902-140501-aaaa".to_owned(),
5404                run: "20260902-140502-bbbb".to_owned(),
5405            }]
5406        );
5407    }
5408
5409    #[test]
5410    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
5411        let dir = tempfile::tempdir().unwrap();
5412        std::fs::write(
5413            dir.path().join("daemon.json"),
5414            serde_json::json!({
5415                "schema": 1,
5416                "updated_at": Timestamp::now().to_string(),
5417                "idle": true,
5418                "current": null,
5419            })
5420            .to_string(),
5421        )
5422        .unwrap();
5423        let with_null = read_status(dir.path()).expect("null must still parse");
5424        assert!(with_null.current.is_empty());
5425
5426        std::fs::write(
5427            dir.path().join("daemon.json"),
5428            serde_json::json!({
5429                "schema": 1,
5430                "updated_at": Timestamp::now().to_string(),
5431                "idle": true,
5432            })
5433            .to_string(),
5434        )
5435        .unwrap();
5436        let absent = read_status(dir.path()).expect("a missing field must still parse");
5437        assert!(absent.current.is_empty());
5438    }
5439
5440    #[test]
5441    fn a_task_without_a_repository_runs_in_the_daemons_default() {
5442        let fallback = Path::new("/default");
5443        let mut blank = task();
5444        blank.repo = PathBuf::new();
5445        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
5446        let mut dot = task();
5447        dot.repo = PathBuf::from(".");
5448        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
5449        assert_eq!(
5450            repo_for(&task(), fallback),
5451            PathBuf::from("/repo"),
5452            "a task that names a repository keeps it"
5453        );
5454    }
5455
5456    #[test]
5457    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
5458        // Three seats said out loud. What `solo` promises is one candidate
5459        // *whatever the config asks for*, so the contrast has to be a number
5460        // this test owns - it used to be `Config::default()`'s, which became
5461        // 1 when one implementation became the default and left the two
5462        // halves of this test asserting the same thing.
5463        let mut solo_cfg = Config::default();
5464        solo_cfg.graph.candidates = 3;
5465        let mut solo_task = task();
5466        solo_task.solo = true;
5467        apply_solo(&mut solo_cfg, &solo_task);
5468        assert_eq!(solo_cfg.graph.candidates, 1);
5469
5470        let mut plain_cfg = Config::default();
5471        plain_cfg.graph.candidates = 3;
5472        let plain_task = task();
5473        assert!(!plain_task.solo);
5474        apply_solo(&mut plain_cfg, &plain_task);
5475        assert_eq!(
5476            plain_cfg.graph.candidates, 3,
5477            "a task that did not ask to run alone keeps the config's candidates"
5478        );
5479    }
5480
5481    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
5482        QuotaLoss {
5483            seat: seat.into(),
5484            node: "judge".into(),
5485            at: at.parse().unwrap(),
5486            reset: reset.map(str::to_string),
5487        }
5488    }
5489
5490    #[test]
5491    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
5492        let old: Vec<QuotaLoss> = (1..=4)
5493            .map(|i| {
5494                loss(
5495                    &format!("judge-{i}"),
5496                    "2026-09-23T05:23:00Z",
5497                    Some("2:40pm (Asia/Tokyo)"),
5498                )
5499            })
5500            .collect();
5501        let fresh = losses_this_attempt(&old, &old);
5502        assert!(fresh.is_empty());
5503        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
5504        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
5505    }
5506
5507    #[test]
5508    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
5509        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
5510        let now = Timestamp::now();
5511        let mut after = old.clone();
5512        after.push(loss("judge-2", &now.to_string(), None));
5513        let fresh = losses_this_attempt(&old, &after);
5514        assert_eq!(fresh, vec![after[1].clone()]);
5515        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
5516        assert_eq!(
5517            until,
5518            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
5519        );
5520    }
5521
5522    #[test]
5523    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
5524        // `recover_stall` removes judge-1's loss and the retry then hits quota
5525        // again: the vector is the same length, so an index diff sees nothing.
5526        let before = vec![
5527            loss("judge-1", "2026-09-23T05:23:00Z", None),
5528            loss("judge-2", "2026-09-23T05:24:00Z", None),
5529        ];
5530        let after = vec![
5531            loss("judge-2", "2026-09-23T05:24:00Z", None),
5532            loss("judge-1", "2026-09-24T01:00:00Z", None),
5533        ];
5534        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
5535    }
5536
5537    #[test]
5538    fn merge_overrides_are_parsed_or_refused() {
5539        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
5540        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
5541        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
5542        assert!(merge_mode("squash").is_err());
5543    }
5544
5545    #[test]
5546    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
5547        let now = Timestamp::now();
5548        let fallback = Duration::from_secs(300);
5549        let cap = Duration::from_secs(1800);
5550
5551        // No reset hint at all: the fallback.
5552        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
5553
5554        // A reset ten minutes out, well inside the cap: waited for exactly.
5555        let soon = now + jiff::SignedDuration::from_secs(600);
5556        assert_eq!(
5557            quota_wait(Some(soon), now, fallback, cap),
5558            Duration::from_secs(600)
5559        );
5560
5561        // A reset already in the past is not trusted: the fallback, not a
5562        // zero or negative wait that would spin the loop right back around.
5563        let past = now - jiff::SignedDuration::from_secs(60);
5564        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
5565
5566        // A reset further out than the cap is trusted for direction but not
5567        // for magnitude: a parsing slip must not sleep the loop for a day.
5568        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
5569        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
5570    }
5571
5572    #[test]
5573    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
5574        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5575
5576        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
5577        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
5578
5579        // Same clock reading, but it has already gone by today: read as
5580        // tomorrow's, since the CLI would not still be reporting a limit past
5581        // its own stated reset.
5582        let already_past =
5583            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
5584        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
5585
5586        assert!(
5587            parse_reset_hint("session limit reached", now, now).is_none(),
5588            "free text with no recognised shape is not guessed at"
5589        );
5590        assert!(
5591            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
5592            "an unresolvable zone name is not guessed at either"
5593        );
5594    }
5595
5596    #[test]
5597    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
5598        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5599
5600        let at = parse_reset_hint(
5601            "You've hit your usage limit. Visit \
5602             https://chatgpt.com/codex/settings/usage to purchase more \
5603             credits or try again at Sep 19th, 2026 5:10 PM.",
5604            now,
5605            now,
5606        )
5607        .expect("the codex reset wording is a recognised shape");
5608        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
5609
5610        // The month is explicit, so a date already earlier in the same
5611        // sentence-implied year than `now` is trusted as written rather than
5612        // rolled forward a year the way the bracketed shape rolls a
5613        // same-day clock reading to tomorrow.
5614        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
5615            .expect("an explicit year needs no rollover");
5616        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
5617
5618        assert!(
5619            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
5620            "a two-digit year is not the documented shape and is not guessed at"
5621        );
5622        assert!(
5623            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
5624            "a four-letter month name is not the documented three-letter abbreviation"
5625        );
5626        assert!(
5627            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
5628            "an explicit zone on the dated shape is a format nobody has \
5629             documented, and is refused rather than guessed at as UTC"
5630        );
5631    }
5632
5633    #[test]
5634    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
5635        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
5636        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
5637
5638        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
5639        assert_eq!(at.as_second() - recorded.as_second(), 3769);
5640
5641        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
5642        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
5643
5644        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
5645            assert!(
5646                parse_reset_hint(bad, now, recorded).is_none(),
5647                "{bad:?} must not be guessed at"
5648            );
5649        }
5650    }
5651
5652    /// A loop whose queue lives in a temp tree and whose poll interval is far
5653    /// longer than the test's patience, so anything that waits out a poll
5654    /// instead of noticing the stop fails rather than merely being slow.
5655    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
5656        let config = dir.join("magi.toml");
5657        std::fs::write(
5658            &config,
5659            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
5660        )
5661        .unwrap();
5662        let opts = Opts {
5663            poll: Duration::from_secs(30),
5664            config: Some(config),
5665            // The explicit fixture config keeps startup cleanup from reading
5666            // machine configuration. This fictional repository likewise
5667            // keeps any best-effort git cleanup away from this checkout.
5668            repo: dir.join("repo"),
5669            ..Opts::default()
5670        };
5671        // The status file goes in a directory that does not exist yet, so its
5672        // creation is itself evidence the loop published one. `worktrees`
5673        // must be just as fictional: the janitor reclaims worktrees under it
5674        // for real, and a test that let it fall through to
5675        // `crate::run::default_worktree_root()` would have it reclaim
5676        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
5677        // which is exactly what happened before this function took the
5678        // parameter at all.
5679        let home = dir.join("home");
5680        let worktrees = dir.join("wt");
5681        (
5682            opts,
5683            Queue::at(dir.join("queue")),
5684            home.join("daemon.json"),
5685            home,
5686            worktrees,
5687        )
5688    }
5689
5690    #[test]
5691    fn a_stop_is_idempotent_and_once_set_stays_set() {
5692        let stop = Stop::new();
5693        assert!(!stop.stopped());
5694
5695        stop.stop();
5696        assert!(stop.stopped());
5697        stop.stop();
5698        assert!(stop.stopped(), "a second stop is not a toggle");
5699
5700        let shared = stop.clone();
5701        assert!(
5702            shared.stopped(),
5703            "a clone is the same stop; that is how the loop and its caller share one"
5704        );
5705    }
5706
5707    #[test]
5708    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
5709        let stop = Stop::new();
5710        stop.enter();
5711        assert!(
5712            !stop.finishing(),
5713            "a busy loop nobody has asked to stop is just running"
5714        );
5715
5716        stop.stop();
5717        assert!(
5718            stop.finishing(),
5719            "a stop asked for mid-run has not landed until the run is settled"
5720        );
5721
5722        stop.exit();
5723        assert!(
5724            !stop.finishing(),
5725            "once the run is settled the stop has landed and there is nothing to finish"
5726        );
5727    }
5728
5729    #[test]
5730    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
5731        let stop = Stop::new();
5732        stop.enter();
5733        stop.enter();
5734        stop.stop();
5735        assert!(stop.finishing(), "two runs still in flight");
5736
5737        stop.exit();
5738        assert!(
5739            stop.finishing(),
5740            "one run finished, but a sibling is still working"
5741        );
5742
5743        stop.exit();
5744        assert!(
5745            !stop.finishing(),
5746            "the last run out is what actually lands the stop"
5747        );
5748    }
5749
5750    #[tokio::test]
5751    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
5752        let dir = tempfile::tempdir().unwrap();
5753        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5754        let stop = Stop::new();
5755        stop.stop();
5756
5757        let began = std::time::Instant::now();
5758        tokio::time::timeout(
5759            Duration::from_secs(2),
5760            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5761        )
5762        .await
5763        .expect("a stopped loop must return, not sit out its poll interval")
5764        .expect("the loop's own setup and teardown must not fail");
5765        assert!(
5766            began.elapsed() < opts.poll,
5767            "returned only after {:?}, which is a poll interval, not a stop",
5768            began.elapsed()
5769        );
5770    }
5771
5772    #[tokio::test]
5773    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
5774        let dir = tempfile::tempdir().unwrap();
5775        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5776        let stop = Stop::new();
5777
5778        // Asked for after the loop is already parked on its empty queue, which
5779        // is the case an operator tapping stop on a phone actually hits.
5780        let asker = {
5781            let stop = stop.clone();
5782            tokio::spawn(async move {
5783                tokio::time::sleep(Duration::from_millis(20)).await;
5784                stop.stop();
5785            })
5786        };
5787
5788        let began = std::time::Instant::now();
5789        tokio::time::timeout(
5790            Duration::from_secs(2),
5791            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5792        )
5793        .await
5794        .expect("a stop asked for while idle must wake the wait")
5795        .expect("the loop's own setup and teardown must not fail");
5796        asker.await.unwrap();
5797        assert!(
5798            began.elapsed() < opts.poll,
5799            "returned only after {:?}, so the stop waited on the sleep",
5800            began.elapsed()
5801        );
5802    }
5803
5804    #[tokio::test]
5805    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
5806        let dir = tempfile::tempdir().unwrap();
5807        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5808        let stop = Stop::new();
5809        stop.stop();
5810
5811        tokio::time::timeout(
5812            Duration::from_secs(2),
5813            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5814        )
5815        .await
5816        .expect("a stopped loop must return")
5817        .expect("the loop's own setup and teardown must not fail");
5818
5819        assert!(
5820            home.is_dir(),
5821            "the loop did publish a status file, so its removal is the teardown and not an absence"
5822        );
5823        assert!(
5824            !status_file.exists(),
5825            "a stopped loop clears its status file"
5826        );
5827        assert!(
5828            read_status(&home).is_none(),
5829            "a reader must see no daemon at all, not a heartbeat that merely stopped"
5830        );
5831    }
5832
5833    #[tokio::test]
5834    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
5835        let dir = tempfile::tempdir().unwrap();
5836        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5837        opts.once = true;
5838
5839        let mut settled = RunState::new(
5840            dir.path().join("repo"),
5841            "main".to_owned(),
5842            "abc1234".to_owned(),
5843            "fixture".to_owned(),
5844            Config::default(),
5845        );
5846        settled.status = RunStatus::Ready;
5847        let run_dir = home.join("runs").join(&settled.id);
5848        std::fs::create_dir_all(&run_dir).unwrap();
5849        std::fs::write(
5850            run_dir.join("run.json"),
5851            serde_json::to_string_pretty(&settled).unwrap(),
5852        )
5853        .unwrap();
5854        let questions = Questions::at(home.join("questions"));
5855        let mut question = ask::Question::new(
5856            settled.id.clone(),
5857            "review".to_owned(),
5858            "reviewer-1".to_owned(),
5859            "Continue?".to_owned(),
5860            String::new(),
5861            Vec::new(),
5862        );
5863        questions.put(&mut question).unwrap();
5864
5865        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
5866            .await
5867            .unwrap();
5868
5869        assert_eq!(
5870            questions.get(&question.id).unwrap().status,
5871            ask::QuestionStatus::Abandoned,
5872            "an empty --once drain still performs startup question cleanup"
5873        );
5874    }
5875
5876    #[test]
5877    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
5878        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5879
5880        assert!(
5881            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
5882            "never checked before: due at once"
5883        );
5884
5885        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
5886        assert!(
5887            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
5888            "well inside the interval: not due yet"
5889        );
5890
5891        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
5892        assert!(
5893            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
5894            "exactly at the edge: not yet due, same convention as `clean::due`"
5895        );
5896
5897        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
5898        assert!(
5899            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
5900            "past the interval: due again"
5901        );
5902    }
5903
5904    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
5905    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
5906    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
5907    /// and the congestion test below both need, and must not drift apart.
5908    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
5909        let config = dir.join("magi.toml");
5910        // A literal (single-quoted) TOML string, not a basic one: the cache
5911        // path is a Windows path full of backslashes, and a basic string
5912        // would have TOML try to interpret `\U` (from `\Users\...`) as a
5913        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
5914        // `{{ vars.cache }}` rendering documents.
5915        std::fs::write(
5916            &config,
5917            format!(
5918                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
5919                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
5920                cache_dir.display()
5921            ),
5922        )
5923        .unwrap();
5924        Opts {
5925            config: Some(config),
5926            repo: dir.join("repo"),
5927            ..Opts::default()
5928        }
5929    }
5930
5931    #[tokio::test]
5932    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
5933        let dir = tempfile::tempdir().unwrap();
5934        let home = dir.path().join("home");
5935        let cache_dir = dir.path().join("cache");
5936        std::fs::create_dir_all(&cache_dir).unwrap();
5937        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
5938        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
5939
5940        // Nobody has asked this daemon to stop, which is the ordinary case;
5941        // the skip that a stop buys is asserted by its own test below.
5942        let running = Stop::new();
5943        let mut last_checked = None;
5944        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5945        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
5946            .await;
5947        assert_eq!(
5948            crate::disk::dir_size(&cache_dir),
5949            0,
5950            "over the cap on the first check ever: pruned at once, no idle queue required"
5951        );
5952        assert_eq!(last_checked, Some(t0));
5953
5954        // A fresh oversized file lands, but the next check is not due yet.
5955        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
5956        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
5957        maybe_prune_cache_between_runs(
5958            &opts.repo,
5959            &opts,
5960            &home,
5961            &running,
5962            &mut last_checked,
5963            too_soon,
5964        )
5965        .await;
5966        assert_eq!(
5967            crate::disk::dir_size(&cache_dir),
5968            10,
5969            "too soon since the last check: left alone rather than rescanned every call"
5970        );
5971        assert_eq!(
5972            last_checked,
5973            Some(t0),
5974            "an idle check does not reset the clock"
5975        );
5976
5977        // Once the interval elapses, the same oversized cache is caught again.
5978        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
5979        maybe_prune_cache_between_runs(
5980            &opts.repo,
5981            &opts,
5982            &home,
5983            &running,
5984            &mut last_checked,
5985            due_again,
5986        )
5987        .await;
5988        assert_eq!(
5989            crate::disk::dir_size(&cache_dir),
5990            0,
5991            "due again: pruned back under the cap"
5992        );
5993    }
5994
5995    /// A stop must not queue behind housekeeping. The prune below is a
5996    /// synchronous walk of the whole cache with no await point in it, so a
5997    /// loop that entered it could not get back to its own `stopped()` test
5998    /// until the walk finished - and because no run is in flight at this
5999    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
6000    /// the stop had already landed. The idle branch has always made this same
6001    /// check before reaching `janitor`; the between-runs path makes it too.
6002    #[tokio::test]
6003    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
6004        let dir = tempfile::tempdir().unwrap();
6005        let home = dir.path().join("home");
6006        let cache_dir = dir.path().join("cache");
6007        std::fs::create_dir_all(&cache_dir).unwrap();
6008        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
6009        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
6010
6011        let stop = Stop::new();
6012        stop.stop();
6013        assert!(
6014            !stop.finishing(),
6015            "no run is in flight at a between-runs boundary, so nothing else \
6016             would tell the operator this stop had not taken effect yet"
6017        );
6018
6019        let mut last_checked = None;
6020        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6021        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
6022            .await;
6023        assert_eq!(
6024            crate::disk::dir_size(&cache_dir),
6025            10,
6026            "over its cap, and due for the first check ever, but a stop outranks \
6027             it: the cap is a standing policy the next start measures again"
6028        );
6029        assert_eq!(
6030            last_checked, None,
6031            "a check that never happened must not claim the interval"
6032        );
6033    }
6034
6035    /// The regression this whole change exists for: gate timeouts on runs
6036    /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
6037    /// GiB against a 10 GiB cap, because the operator's queue never had a
6038    /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
6039    /// `janitor` pass.
6040    ///
6041    /// Reproduced here with a task whose repository is never created:
6042    /// `Runner::start` fails at `git::toplevel` in a few milliseconds,
6043    /// spawning no agent CLI, so the task keeps failing and re-queuing
6044    /// (`Task::fail` with attempts still under the budget leaves it
6045    /// `Failed`, which `TaskStatus::runnable` still offers) for as long as
6046    /// the loop keeps polling - exactly the "queue with no idle moment"
6047    /// this task describes, produced without a real competition.
6048    #[tokio::test]
6049    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
6050        let dir = tempfile::tempdir().unwrap();
6051        let cache_dir = dir.path().join("cache");
6052        std::fs::create_dir_all(&cache_dir).unwrap();
6053        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
6054
6055        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
6056        opts.poll = Duration::from_millis(20);
6057        opts.max_attempts = 1_000;
6058
6059        let queue = Queue::at(dir.path().join("queue"));
6060        let mut t = Task::new(
6061            "x".to_owned(),
6062            "x".to_owned(),
6063            opts.repo.clone(),
6064            Source::Human,
6065        );
6066        queue.put(&mut t).unwrap();
6067
6068        let home = dir.path().join("home");
6069        let worktrees = dir.path().join("wt");
6070        let status_file = home.join("daemon.json");
6071        let stop = Stop::new();
6072        let stopper = {
6073            let stop = stop.clone();
6074            tokio::spawn(async move {
6075                tokio::time::sleep(Duration::from_millis(400)).await;
6076                stop.stop();
6077            })
6078        };
6079
6080        tokio::time::timeout(
6081            Duration::from_secs(10),
6082            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6083        )
6084        .await
6085        .expect("the loop must not hang on a queue that keeps producing failing work")
6086        .expect("the loop's own setup and teardown must not fail");
6087        stopper.await.unwrap();
6088
6089        let after = queue.get(&t.id).unwrap();
6090        assert!(
6091            after.attempts >= 2,
6092            "the harness must actually have retried more than once, or this is not \
6093             exercising a busy queue at all (got {} attempt(s))",
6094            after.attempts
6095        );
6096        assert!(
6097            after.status.runnable(),
6098            "still under its attempt budget: the queue never reached a natural idle \
6099             on its own, only the external stop ended the test"
6100        );
6101
6102        assert_eq!(
6103            crate::disk::dir_size(&cache_dir),
6104            0,
6105            "an oversized cache must not be left to grow unboundedly just because the \
6106             queue kept the loop busy the whole time"
6107        );
6108    }
6109
6110    #[test]
6111    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
6112        let dir = tempfile::tempdir().unwrap();
6113        let queue = Queue::at(dir.path().join("queue"));
6114        let questions = Questions::at(dir.path().join("questions"));
6115        let mut task = task();
6116        queue.put(&mut task).unwrap();
6117
6118        let mut task_question = ask::Question::new(
6119            task.id.clone(),
6120            crate::conduct::NODE.to_owned(),
6121            "conduct".to_owned(),
6122            "Which backend?".to_owned(),
6123            String::new(),
6124            Vec::new(),
6125        );
6126        questions.put(&mut task_question).unwrap();
6127        task.block(vec![task_question.id.clone()], None);
6128        queue.put(&mut task).unwrap();
6129
6130        let mut run_question = ask::Question::new(
6131            "20260101-000000-run1".to_owned(),
6132            "review".to_owned(),
6133            "reviewer-1".to_owned(),
6134            "Run question".to_owned(),
6135            String::new(),
6136            Vec::new(),
6137        );
6138        questions.put(&mut run_question).unwrap();
6139
6140        // A question from another node whose `run` happens to equal this
6141        // task's id — the same field, filled in for an unrelated reason. Only
6142        // `crate::conduct::NODE` questions use `run` as a task id; this one
6143        // must never be touched by this reconciliation, even after release.
6144        let mut coincidental = ask::Question::new(
6145            task.id.clone(),
6146            "review".to_owned(),
6147            "reviewer-1".to_owned(),
6148            "Unrelated review question".to_owned(),
6149            String::new(),
6150            Vec::new(),
6151        );
6152        questions.put(&mut coincidental).unwrap();
6153
6154        reconcile_task_questions(&queue, &questions);
6155        assert!(questions.get(&task_question.id).unwrap().status.open());
6156        assert!(questions.get(&run_question.id).unwrap().status.open());
6157        assert!(questions.get(&coincidental.id).unwrap().status.open());
6158
6159        task.release();
6160        queue.put(&mut task).unwrap();
6161        reconcile_task_questions(&queue, &questions);
6162        assert_eq!(
6163            questions.get(&task_question.id).unwrap().status,
6164            ask::QuestionStatus::Abandoned
6165        );
6166        assert!(
6167            questions.get(&run_question.id).unwrap().status.open(),
6168            "run questions remain the run janitor's responsibility"
6169        );
6170        assert!(
6171            questions.get(&coincidental.id).unwrap().status.open(),
6172            "a non-conductor question must not be abandoned just because its \
6173             run id coincides with a task id"
6174        );
6175    }
6176
6177    #[test]
6178    fn a_freshly_started_running_task_is_never_stalled() {
6179        let dir = tempfile::tempdir().unwrap();
6180        let mut t = task();
6181        t.start("run-1".to_owned());
6182        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
6183        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
6184        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
6185    }
6186
6187    #[test]
6188    fn a_long_running_task_with_no_live_daemon_is_stalled() {
6189        let dir = tempfile::tempdir().unwrap();
6190        let mut t = task();
6191        t.start("run-1".to_owned());
6192        t.updated_at = Timestamp::now()
6193            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6194        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
6195        assert_eq!(
6196            stalled_tasks(
6197                &Queue::at(dir.path().join("q")),
6198                dir.path(),
6199                Timestamp::now()
6200            )
6201            .len(),
6202            0,
6203            "the task was never written to this queue"
6204        );
6205    }
6206
6207    #[test]
6208    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
6209        let dir = tempfile::tempdir().unwrap();
6210        let mut t = task();
6211        t.id = "20260903-080340-0167".to_owned();
6212        t.start("20260903-080619-01c2".to_owned());
6213        t.updated_at = Timestamp::now()
6214            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6215
6216        let mut status = Status::new();
6217        status.current = vec![Current {
6218            task: t.id.clone(),
6219            run: "20260903-080619-01c2".to_owned(),
6220        }];
6221        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6222
6223        assert!(
6224            !is_stalled(&t, dir.path(), Timestamp::now()),
6225            "a live daemon's own heartbeat rules out stalled, however long the task has run"
6226        );
6227    }
6228
6229    /// Rewrite a task's `updated_at` on disk directly, bypassing
6230    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
6231    /// a fixture look like it has genuinely been `running` for a while.
6232    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
6233        let path = queue.path_of(id);
6234        let body = std::fs::read_to_string(&path).unwrap();
6235        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
6236        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
6237        v["updated_at"] = serde_json::Value::String(old.to_string());
6238        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
6239    }
6240
6241    #[test]
6242    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
6243        // The realistic `poll()` ordering, not `is_stalled` in isolation:
6244        // `reclaim_orphaned_running` runs first, on every poll, and settles
6245        // any `running` task whose claim it can actually take. For most
6246        // crashes that is immediate - a dead pid is proof enough for
6247        // `sweep_stale_claims` to drop the lock the same tick, and the very
6248        // next claim attempt succeeds. But a lock whose pid cannot be parsed
6249        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
6250        // `sweep_stale_claims`'s own doc), so the lock - and the claim
6251        // failure behind it - can legitimately outlive many polls. This is
6252        // exactly the gap `stalled_tasks` exists to surface well before that
6253        // six-hour sweep would: reclaim leaves the task `running`, and it
6254        // must still reach the conductor as stalled.
6255        let dir = tempfile::tempdir().unwrap();
6256        let queue = Queue::at(dir.path().join("queue"));
6257        let home = dir.path().join("home");
6258
6259        let mut t = task();
6260        t.id = "20260101-000001-lock".to_owned();
6261        t.start("run-1".to_owned());
6262        queue.put(&mut t).unwrap();
6263        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6264        std::fs::write(
6265            dir.path().join("queue").join(format!("{}.lock", t.id)),
6266            "not a pid",
6267        )
6268        .unwrap();
6269
6270        let now = Timestamp::now();
6271        assert!(
6272            reclaim_orphaned_running(&queue, 2).is_empty(),
6273            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
6274             and reclaim must leave the task alone"
6275        );
6276        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6277
6278        let stalled = stalled_tasks(&queue, &home, now);
6279        assert_eq!(
6280            stalled.len(),
6281            1,
6282            "reclaim's inability to claim it yet must not hide it from the conductor"
6283        );
6284        assert_eq!(stalled[0].id, t.id);
6285    }
6286
6287    #[test]
6288    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
6289        let dir = tempfile::tempdir().unwrap();
6290        crate::run::set_home(dir.path().join("run-home"));
6291        let queue = Queue::at(dir.path().join("queue"));
6292        let home = dir.path().join("home");
6293        let questions = Questions::at(dir.path().join("questions"));
6294
6295        let mut t = task();
6296        t.id = "20260101-000003-dead".to_owned();
6297        t.start("missing-run".to_owned());
6298        queue.put(&mut t).unwrap();
6299        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6300
6301        // This is the real poll ordering: retain the deterministic stalled
6302        // input before a claim proves the owner is gone and reclaims it.
6303        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6304        assert_eq!(
6305            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
6306            [&t.id]
6307        );
6308        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
6309        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
6310
6311        // Reclaim drops its guard before conductor decisions are applied, so
6312        // the decision for the captured stalled input has a real write path.
6313        crate::conduct::apply(
6314            &queue,
6315            &questions,
6316            &crate::conduct::Verdict {
6317                decisions: vec![crate::conduct::Decision {
6318                    id: t.id.clone(),
6319                    recovery: Some(crate::conduct::Recovery::Requeue),
6320                    ..crate::conduct::Decision::default()
6321                }],
6322            },
6323        )
6324        .unwrap();
6325        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
6326    }
6327
6328    #[test]
6329    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
6330        let dir = tempfile::tempdir().unwrap();
6331        let queue = Queue::at(dir.path().join("queue"));
6332        let home = dir.path().join("home");
6333
6334        let mut fresh = task();
6335        fresh.id = "20260101-000001-aaaa".to_owned();
6336        fresh.start("run-1".to_owned());
6337        queue.put(&mut fresh).unwrap();
6338
6339        let mut old = task();
6340        old.id = "20260101-000002-bbbb".to_owned();
6341        old.start("run-2".to_owned());
6342        queue.put(&mut old).unwrap();
6343        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
6344
6345        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6346        assert_eq!(stalled.len(), 1);
6347        assert_eq!(stalled[0].id, old.id);
6348    }
6349
6350    #[test]
6351    fn queued_and_finished_task_views_partition_by_status() {
6352        let dir = tempfile::tempdir().unwrap();
6353        let queue = Queue::at(dir.path().join("queue"));
6354
6355        let mut queued = task();
6356        queued.id = "20260101-000001-aaaa".to_owned();
6357        queue.put(&mut queued).unwrap();
6358
6359        let mut failed = task();
6360        failed.id = "20260101-000002-bbbb".to_owned();
6361        failed.start("run-1".to_owned());
6362        failed.fail("gate red", 5);
6363        queue.put(&mut failed).unwrap();
6364
6365        let mut held = task();
6366        held.id = "20260101-000003-cccc".to_owned();
6367        held.hold_machine(None);
6368        queue.put(&mut held).unwrap();
6369
6370        let mut running = task();
6371        running.id = "20260101-000004-dddd".to_owned();
6372        running.start("run-2".to_owned());
6373        queue.put(&mut running).unwrap();
6374
6375        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
6376        assert_eq!(queued_ids, [queued.id.clone()]);
6377
6378        let mut finished_ids: Vec<String> =
6379            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
6380        finished_ids.sort_unstable();
6381        let mut want = vec![failed.id.clone(), held.id.clone()];
6382        want.sort_unstable();
6383        assert_eq!(finished_ids, want);
6384    }
6385
6386    #[test]
6387    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
6388        let dir = tempfile::tempdir().unwrap();
6389        let queue = Queue::at(dir.path().join("queue"));
6390        let questions = ask::Questions::at(dir.path().join("questions"));
6391
6392        let mut dep = task();
6393        dep.id = "20260101-000001-dep0".to_owned();
6394        dep.succeed();
6395        queue.put(&mut dep).unwrap();
6396
6397        let mut still_going = task();
6398        still_going.id = "20260101-000002-dep1".to_owned();
6399        queue.put(&mut still_going).unwrap();
6400
6401        let mut blocked = task();
6402        blocked.id = "20260101-000003-main".to_owned();
6403        blocked.block(
6404            vec![dep.id.clone(), still_going.id.clone()],
6405            Some("waits on both".to_owned()),
6406        );
6407        queue.put(&mut blocked).unwrap();
6408
6409        resolve_blockers(&queue, &questions);
6410
6411        let after = queue.get(&blocked.id).unwrap();
6412        assert_eq!(
6413            after.status,
6414            TaskStatus::Blocked,
6415            "one dependency is still outstanding"
6416        );
6417        assert_eq!(after.blocked_by, [still_going.id.clone()]);
6418    }
6419
6420    #[test]
6421    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
6422        let dir = tempfile::tempdir().unwrap();
6423        let queue = Queue::at(dir.path().join("queue"));
6424        let questions = ask::Questions::at(dir.path().join("questions"));
6425
6426        let mut q = crate::ask::Question::new(
6427            "20260101-000001-main".to_owned(),
6428            crate::conduct::NODE.to_owned(),
6429            "conduct".to_owned(),
6430            "Which backend?".to_owned(),
6431            String::new(),
6432            Vec::new(),
6433        );
6434        questions.put(&mut q).unwrap();
6435        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
6436            .unwrap();
6437        questions.put(&mut q).unwrap();
6438
6439        let mut blocked = task();
6440        blocked.id = "20260101-000001-main".to_owned();
6441        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
6442        queue.put(&mut blocked).unwrap();
6443
6444        resolve_blockers(&queue, &questions);
6445
6446        let after = queue.get(&blocked.id).unwrap();
6447        assert_eq!(
6448            after.status,
6449            TaskStatus::Queued,
6450            "the only blocker resolved"
6451        );
6452        assert_eq!(after.answers.len(), 1);
6453        assert_eq!(after.answers[0].question, "Which backend?");
6454        assert_eq!(after.answers[0].answer, "SQLite");
6455
6456        // And the run this task starts next is told about it.
6457        let instruction = instruction_for(&after);
6458        assert!(instruction.contains("Which backend?"));
6459        assert!(instruction.contains("SQLite"));
6460    }
6461
6462    #[test]
6463    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
6464        // Reproduces the reported bug (task 3958): a task held out of
6465        // attempts, blocked on a `crate::conduct` follow-up question, must
6466        // come back `held` once that question is answered - never `queued`,
6467        // whatever the answer said - or it silently re-enters the
6468        // competition queue with its attempts already exhausted.
6469        let dir = tempfile::tempdir().unwrap();
6470        let queue = Queue::at(dir.path().join("queue"));
6471        let questions = ask::Questions::at(dir.path().join("questions"));
6472
6473        let mut q = crate::ask::Question::new(
6474            "20260101-000001-main".to_owned(),
6475            crate::conduct::NODE.to_owned(),
6476            "conduct".to_owned(),
6477            "How should this be handled?".to_owned(),
6478            String::new(),
6479            Vec::new(),
6480        );
6481        questions.put(&mut q).unwrap();
6482        q.answer(crate::ask::Answer::Text(
6483            "leave it held, a human will look at it later".to_owned(),
6484        ))
6485        .unwrap();
6486        questions.put(&mut q).unwrap();
6487
6488        let mut held = task();
6489        held.id = "20260101-000001-main".to_owned();
6490        held.hold_machine(Some("out of attempts".to_owned()));
6491        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
6492        queue.put(&mut held).unwrap();
6493
6494        resolve_blockers(&queue, &questions);
6495
6496        let after = queue.get(&held.id).unwrap();
6497        assert_eq!(after.status, TaskStatus::Held);
6498        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
6499        assert_eq!(
6500            after.answers[0].answer,
6501            "leave it held, a human will look at it later"
6502        );
6503    }
6504
6505    #[test]
6506    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
6507        // Reproduces the reported bug: a task blocked on a task id that was
6508        // removed (`magi task rm`, or deleted by hand) can never see that id
6509        // reach `Done`, so the ordinary per-id loop has nothing to notice and
6510        // would otherwise leave the task `blocked` forever with no way for an
6511        // operator to find out why.
6512        let dir = tempfile::tempdir().unwrap();
6513        let queue = Queue::at(dir.path().join("queue"));
6514        let questions = ask::Questions::at(dir.path().join("questions"));
6515
6516        let mut still_going = task();
6517        still_going.id = "20260101-000002-dep1".to_owned();
6518        queue.put(&mut still_going).unwrap();
6519
6520        let mut blocked = task();
6521        blocked.id = "20260101-000003-main".to_owned();
6522        blocked.block(
6523            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
6524            Some("waits on both".to_owned()),
6525        );
6526        queue.put(&mut blocked).unwrap();
6527
6528        resolve_blockers(&queue, &questions);
6529
6530        let after = queue.get(&blocked.id).unwrap();
6531        assert_eq!(
6532            after.status,
6533            TaskStatus::Held,
6534            "a missing dependency must not leave the task blocked forever"
6535        );
6536        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
6537        assert!(after.blocked_by.is_empty());
6538        let reason = after.hold_reason.as_deref().unwrap_or_default();
6539        assert!(
6540            reason.contains("20260101-000001-gone"),
6541            "the missing id must be named so an operator can tell what happened: {reason}"
6542        );
6543        assert!(
6544            reason.contains(&still_going.id),
6545            "the still-valid dependency must not silently vanish from the record: {reason}"
6546        );
6547    }
6548
6549    #[test]
6550    fn instruction_for_is_unchanged_without_any_answers() {
6551        let t = task();
6552        assert_eq!(instruction_for(&t), t.instruction);
6553    }
6554
6555    #[test]
6556    fn resumed_instruction_is_unchanged_without_any_answers() {
6557        let t = task();
6558        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
6559    }
6560
6561    #[test]
6562    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
6563        let mut t = task();
6564        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6565        // The run's own instruction on disk predates the answer: it is the
6566        // plain original text `Runner::start` saved before the operator was
6567        // ever asked anything.
6568        let old = t.instruction.clone();
6569
6570        let refreshed = resumed_instruction(&old, &t);
6571        assert!(refreshed.starts_with(&old), "the original text is kept");
6572        assert!(refreshed.contains("Which backend?"));
6573        assert!(refreshed.contains("SQLite"));
6574    }
6575
6576    #[test]
6577    fn resumed_instruction_keeps_an_original_answers_heading() {
6578        let mut t = task();
6579        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
6580        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6581
6582        let refreshed = resumed_instruction(&t.instruction, &t);
6583
6584        assert!(
6585            refreshed.starts_with(&t.instruction),
6586            "an answers heading in the original instruction is not the appended block"
6587        );
6588        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
6589        assert!(refreshed.contains("Which backend?"));
6590        assert!(refreshed.contains("SQLite"));
6591
6592        let repeated = resumed_instruction(&refreshed, &t);
6593        assert_eq!(
6594            repeated, refreshed,
6595            "only the final appended block is refreshed"
6596        );
6597    }
6598
6599    #[test]
6600    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
6601        let mut t = task();
6602        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6603
6604        // A first resume appends the block; a second resume of the same run,
6605        // with no new answer in between, must reproduce exactly the same
6606        // text rather than appending the block a second time.
6607        let once = resumed_instruction(&t.instruction, &t);
6608        let twice = resumed_instruction(&once, &t);
6609        assert_eq!(once, twice);
6610        assert_eq!(once.matches("Which backend?").count(), 1);
6611
6612        // A later answer replaces the block wholesale rather than growing it.
6613        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
6614        let refreshed = resumed_instruction(&once, &t);
6615        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
6616        assert!(refreshed.contains("Which backend?"));
6617        assert!(refreshed.contains("Which cache?"));
6618    }
6619
6620    #[test]
6621    fn prepare_instruction_covers_all_three_starters() {
6622        let mut t = task();
6623        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6624
6625        // Start: a fresh run gets the task text plus every answer so far —
6626        // exactly `instruction_for`.
6627        assert_eq!(
6628            prepare_instruction(&Starter::Start, None, &t),
6629            Some(instruction_for(&t))
6630        );
6631
6632        // Resume: the run's prior instruction is refreshed with the answer,
6633        // not discarded and not left stale.
6634        let old = t.instruction.clone();
6635        assert_eq!(
6636            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
6637            Some(resumed_instruction(&old, &t))
6638        );
6639
6640        // Review: a review-only pass builds its own instruction from the
6641        // branch's history in `crate::graph`, with no task statement at all -
6642        // this boundary must leave it alone.
6643        assert_eq!(
6644            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
6645            None
6646        );
6647    }
6648
6649    #[test]
6650    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
6651        assert_eq!(
6652            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
6653            Starter::Review("magi/eba2/A".to_owned())
6654        );
6655    }
6656
6657    #[test]
6658    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
6659        assert_eq!(
6660            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
6661            Starter::Start,
6662            "a vanished review branch must not fall back to resuming the old run either"
6663        );
6664    }
6665
6666    #[test]
6667    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
6668        assert_eq!(
6669            choose_starter(None, false, Some("some-run")),
6670            Starter::Resume("some-run".to_owned())
6671        );
6672        assert_eq!(choose_starter(None, false, None), Starter::Start);
6673    }
6674
6675    #[test]
6676    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
6677        let mut released = task();
6678        released.start("stalled-run".to_owned());
6679        released.requeue();
6680        let unfinished = (!released.fresh_start)
6681            .then(|| Some("stalled-run".to_owned()))
6682            .flatten();
6683        assert_eq!(
6684            choose_starter(None, false, unfinished.as_deref()),
6685            Starter::Start,
6686            "release keeps run history but must not resume it"
6687        );
6688        assert_eq!(released.runs, ["stalled-run"]);
6689    }
6690
6691    #[test]
6692    fn an_ordinary_release_keeps_a_resumable_run_available() {
6693        let mut released = task();
6694        released.start("stalled-run".to_owned());
6695        released.release();
6696        let unfinished = (!released.fresh_start)
6697            .then(|| Some("stalled-run".to_owned()))
6698            .flatten();
6699        assert_eq!(
6700            choose_starter(None, false, unfinished.as_deref()),
6701            Starter::Resume("stalled-run".to_owned()),
6702            "manual release must preserve the normal resume path"
6703        );
6704    }
6705
6706    #[test]
6707    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
6708        let mut state = run_state(RunStatus::Blocked);
6709        state.config.graph.review_rounds = 3;
6710        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
6711        assert!(exhausted_review_budget(&state));
6712
6713        // One round still unused: resuming can still ask a reviewer something.
6714        state.reviews.pop();
6715        assert!(!exhausted_review_budget(&state));
6716
6717        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
6718        // count: only a `Blocked` run re-enters the review loop on resume.
6719        let mut stalled = run_state(RunStatus::Stalled);
6720        stalled.config.graph.review_rounds = 1;
6721        stalled.reviews = vec![review_round(1)];
6722        assert!(!exhausted_review_budget(&stalled));
6723    }
6724
6725    fn review_round(round: usize) -> crate::run::ReviewRound {
6726        crate::run::ReviewRound {
6727            round,
6728            head: "deadbeef".to_owned(),
6729            verified_head: None,
6730            verified_at: None,
6731            reviews: Vec::new(),
6732            e2e: Vec::new(),
6733            verify_retried: false,
6734            e2e_deferred: false,
6735            e2e_defer_reason: None,
6736            fix: None,
6737            blocking: 0,
6738            answered: 1,
6739            expected: 1,
6740            clean: false,
6741            progressed: true,
6742            vote_split: false,
6743            reconsideration: Vec::new(),
6744            verdict: None,
6745        }
6746    }
6747
6748    #[test]
6749    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
6750        let mut released = RunState::new(
6751            PathBuf::from("/repo"),
6752            "main".to_owned(),
6753            "abc1234def".to_owned(),
6754            "add retries".to_owned(),
6755            Config::default(),
6756        );
6757        released.status = RunStatus::Blocked;
6758        assert_eq!(
6759            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
6760            Some(released.id.clone())
6761        );
6762        released.released_to = Some("20260901-000000-new1".to_owned());
6763        assert_eq!(
6764            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
6765            None,
6766            "there is nothing left to resume it into"
6767        );
6768    }
6769
6770    #[test]
6771    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
6772        // Mirrors the failure this exists to close: a task's last run ended
6773        // `Blocked` with the review budget spent, `crate::conduct` chose
6774        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
6775        // evidence), and without this check `attempt` would go on treating
6776        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
6777        // review loop iterates zero times over an already-spent budget, so
6778        // the resumed run settles right back to `Blocked` having asked nobody
6779        // anything, and `Requeue`'s promised fresh competition never happens.
6780        let mut exhausted = RunState::new(
6781            PathBuf::from("/repo"),
6782            "main".to_owned(),
6783            "abc1234def".to_owned(),
6784            "add retries".to_owned(),
6785            Config::default(),
6786        );
6787        exhausted.status = RunStatus::Blocked;
6788        exhausted.config.graph.review_rounds = 1;
6789        exhausted.reviews = vec![review_round(1)];
6790
6791        assert_eq!(
6792            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
6793            None,
6794            "an exhausted `Blocked` run must not be offered as resumable"
6795        );
6796
6797        // A `Blocked` run with rounds still unused is genuinely worth
6798        // resuming, and must still be found.
6799        let mut has_budget_left = RunState::new(
6800            PathBuf::from("/repo"),
6801            "main".to_owned(),
6802            "abc1234def".to_owned(),
6803            "add retries".to_owned(),
6804            Config::default(),
6805        );
6806        has_budget_left.status = RunStatus::Blocked;
6807        has_budget_left.config.graph.review_rounds = 3;
6808        has_budget_left.reviews = vec![review_round(1)];
6809
6810        assert_eq!(
6811            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
6812                Ok(has_budget_left.clone())
6813            }),
6814            Some(has_budget_left.id.clone())
6815        );
6816    }
6817
6818    #[test]
6819    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
6820        // A task whose history holds an *older* run that still looks
6821        // resumable (say, a competition `Runner::review` was started
6822        // alongside after that older run went `Stalled`) and a *newest* run
6823        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
6824        // on this task must mean a fresh competition — falling back to the
6825        // stale, superseded `Stalled` run instead would resurrect history
6826        // nothing asked to revisit and silently defeat the requeue.
6827        let mut older_stalled = RunState::new(
6828            PathBuf::from("/repo"),
6829            "main".to_owned(),
6830            "abc1234def".to_owned(),
6831            "add retries".to_owned(),
6832            Config::default(),
6833        );
6834        older_stalled.status = RunStatus::Stalled;
6835
6836        let mut newest_exhausted = RunState::new(
6837            PathBuf::from("/repo"),
6838            "main".to_owned(),
6839            "abc1234def".to_owned(),
6840            "add retries".to_owned(),
6841            Config::default(),
6842        );
6843        newest_exhausted.status = RunStatus::Blocked;
6844        newest_exhausted.config.graph.review_rounds = 1;
6845        newest_exhausted.reviews = vec![review_round(1)];
6846
6847        assert_eq!(
6848            unfinished_run_with(
6849                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
6850                "t",
6851                |_| Ok(newest_exhausted.clone())
6852            ),
6853            None,
6854            "the newest run is exhausted, so nothing here is worth resuming - \
6855             least of all the older, already-superseded run"
6856        );
6857    }
6858
6859    #[test]
6860    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
6861        assert_eq!(
6862            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
6863                Err(anyhow::anyhow!("fixture is absent"))
6864            }),
6865            None
6866        );
6867    }
6868}