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