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::queue::{Queue, Task, TaskStatus};
67use crate::run::{QuotaLoss, RunState, RunStatus};
68
69/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
70pub const SCHEMA: u32 = 1;
71
72/// How often the status file is refreshed. A reader treats a status file older
73/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
74/// that a busy daemon is never mistaken for a dead one.
75pub const HEARTBEAT: Duration = Duration::from_secs(5);
76
77/// How old a heartbeat may be before a reader calls the daemon dead. Six
78/// missed beats: long enough to survive a slow filesystem, short enough that
79/// a crashed daemon is not still reported as running a task.
80///
81/// The single threshold every reader shares — the web UI's `/api/health` and
82/// `magi doctor` both call [`Reading::running`] rather than each comparing
83/// against their own copy of this number, so a crashed daemon cannot look
84/// alive on one screen and dead on another.
85pub const STALE_SECS: i64 = 30;
86
87/// Default queue poll interval.
88pub const POLL: Duration = Duration::from_secs(5);
89
90/// How old a claim has to be before startup sweeps it. Longer than any run
91/// this graph plausibly takes, so a sweep cannot pull a task out from under a
92/// daemon that is merely slow.
93pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
94
95/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
96/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
97///
98/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
99/// poll, by attempting the task's own claim: a dead pid is proof enough for
100/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
101/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
102/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
103/// age instead, since there is nothing else to check (see
104/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
105/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
106/// task `running` — see
107/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
108/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
109/// conductor well before the mechanical six-hour sweep would, and thirty
110/// minutes is comfortably below `STALE_CLAIM` while still being generous
111/// enough that a task merely late to publish its first [`HEARTBEAT`] is
112/// never mistaken for abandoned.
113pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
114
115/// What the loop is working on, for the status file.
116#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(default)]
118pub struct Current {
119    /// Task id being run.
120    pub task: String,
121    /// Run id the task produced.
122    pub run: String,
123}
124
125/// The daemon's liveness, published to `<home>/daemon.json`.
126///
127/// This is the only interface between the loop and the web UI, which is why it
128/// carries `updated_at` as well as `started_at`: a reader cannot tell a
129/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
130/// can compare the heartbeat against the clock.
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct Status {
133    /// On-disk format version.
134    pub schema: u32,
135    /// Process id, so a human can find or kill the daemon.
136    pub pid: u32,
137    /// When this process started.
138    pub started_at: Timestamp,
139    /// Last heartbeat.
140    pub updated_at: Timestamp,
141    /// True when the queue has nothing runnable.
142    pub idle: bool,
143    /// Every task and run currently in flight. More than one entry means the
144    /// loop is driving more than one run at once — see
145    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
146    /// nothing is running, so a reader never has to treat "no field" and "an
147    /// empty list" as two different kinds of idle.
148    pub current: Vec<Current>,
149    /// Tasks that reached a terminal status in this process.
150    pub completed: usize,
151    /// Queue polls since start, so a wedged loop shows up as a frozen count.
152    pub polls: u64,
153}
154
155impl Status {
156    /// A fresh, idle status for this process.
157    #[must_use]
158    pub fn new() -> Self {
159        let now = Timestamp::now();
160        Self {
161            schema: SCHEMA,
162            pid: std::process::id(),
163            started_at: now,
164            updated_at: now,
165            idle: true,
166            current: Vec::new(),
167            completed: 0,
168            polls: 0,
169        }
170    }
171}
172
173impl Default for Status {
174    fn default() -> Self {
175        Self::new()
176    }
177}
178
179/// How the loop should behave.
180#[derive(Debug, Clone)]
181pub struct Opts {
182    /// Repository used by tasks that name none.
183    pub repo: PathBuf,
184    /// Explicit `magi.toml`, instead of the discovered layer stack.
185    pub config: Option<PathBuf>,
186    /// Queue poll interval.
187    pub poll: Duration,
188    /// Attempts a task gets before it is held for a human.
189    pub max_attempts: usize,
190    /// Drain what is runnable now, then return, instead of waiting for more.
191    pub once: bool,
192    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
193    pub merge: Option<String>,
194    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
195    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
196    /// `None` resolves to [`crate::run::default_worktree_root`] - the
197    /// operator's real `~/wt/<repo>` - the same way a run with no
198    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
199    /// that does not own that directory (a test, an embedding that manages
200    /// worktrees itself) must set this, or every idle tick reclaims worktrees
201    /// out from under whoever actually does.
202    pub worktrees_root: Option<PathBuf>,
203}
204
205impl Default for Opts {
206    fn default() -> Self {
207        Self {
208            repo: PathBuf::from("."),
209            config: None,
210            poll: POLL,
211            max_attempts: 2,
212            once: false,
213            merge: None,
214            worktrees_root: None,
215        }
216    }
217}
218
219/// How many runs a plain `usize` from config may drive concurrently, floored
220/// at one. A `0` in a config file would otherwise stall the loop entirely -
221/// no runnable task could ever start - which is never what an operator who
222/// wrote `0` meant.
223fn max_concurrent(n: usize) -> usize {
224    n.max(1)
225}
226
227/// Where the status file lives.
228#[must_use]
229pub fn status_path() -> PathBuf {
230    crate::run::home().join("daemon.json")
231}
232
233/// Publish the status file for this process.
234pub fn write_status(status: &Status) -> Result<()> {
235    write_status_to(&status_path(), status)
236}
237
238/// Publish a status to an explicit path.
239///
240/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
241/// on every health poll and must never see a half-written one.
242pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
243    if let Some(parent) = path.parent() {
244        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
245    }
246    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
247    let tmp = path.with_extension("json.tmp");
248    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
249    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
250    Ok(())
251}
252
253/// Delete the status file. Called on the way out so a clean exit reads as
254/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
255pub fn clear_status() {
256    clear_status_at(&status_path());
257}
258
259/// Delete a status file at an explicit path, so the loop's teardown and
260/// [`clear_status`] cannot drift apart: the loop is handed the path it
261/// published to, and a test can watch a temp file disappear.
262fn clear_status_at(path: &Path) {
263    let _ = std::fs::remove_file(path);
264}
265
266/// A cooperative stop, shared with whoever asked the loop to run.
267///
268/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
269/// Ctrl-C listener and the web UI keep others, and every clone points at the
270/// same flag. There is no channel because there is nothing to send — the only
271/// message is "stop", it is idempotent, and a flag cannot be missed by a
272/// receiver that was not listening yet.
273///
274/// The handle also answers the question the operator's screen asks next: a
275/// stop does not take effect until the run in flight has finished, so
276/// [`Stop::finishing`] reports "asked to stop, still working" rather than
277/// leaving a caller to infer it from a heartbeat and hope.
278#[derive(Debug, Clone, Default)]
279pub struct Stop {
280    /// Set once, never cleared: a stop is not something an operator takes back
281    /// half way through, and a clearable flag would let a start racing a stop
282    /// resurrect a loop that is already unwinding.
283    stopped: Arc<AtomicBool>,
284    /// How many runs are in flight, so `finishing` can distinguish a stop
285    /// that has landed from one that is waiting on `execute`. A count, not a
286    /// flag, because more than one run can be in flight at once - see
287    /// [`crate::config::Daemon::max_concurrent_runs`] - and the last one to
288    /// finish is the one that should turn "finishing" off.
289    busy: Arc<std::sync::atomic::AtomicUsize>,
290    /// Wakes the idle wait. Without this a stop would not be seen until the
291    /// poll interval elapsed, and an operator tapping stop on a phone would
292    /// watch a button do nothing for five seconds.
293    wake: Arc<Notify>,
294    /// Handed to the run in flight, so a stop can also mean "park at the next
295    /// node boundary" instead of "finish the whole competition first".
296    pause: crate::graph::Pause,
297}
298
299impl Stop {
300    /// A stop nobody has asked for yet.
301    #[must_use]
302    pub fn new() -> Self {
303        Self::default()
304    }
305
306    /// Ask the loop to stop. Idempotent, and safe to call before the loop
307    /// starts: the flag is checked before the first poll.
308    pub fn stop(&self) {
309        self.stopped.store(true, Ordering::SeqCst);
310        // `notify_one` rather than `notify_waiters` because the loop may not be
311        // parked yet: this stores a permit, so a wait that registers a moment
312        // later returns at once instead of sleeping out the whole interval.
313        self.wake.notify_one();
314    }
315
316    /// Has a stop been asked for?
317    #[must_use]
318    pub fn stopped(&self) -> bool {
319        self.stopped.load(Ordering::SeqCst)
320    }
321
322    /// Has a stop been asked for that has not taken effect yet, because a run
323    /// is still in flight?
324    ///
325    /// This is the state a screen has to be able to show. A stop never abandons
326    /// a run — see [`serve_until`] — so between the tap and the loop's return
327    /// there is a window of tens of minutes in which "running" and "stopped"
328    /// are both misleading answers.
329    #[must_use]
330    pub fn finishing(&self) -> bool {
331        self.stopped() && self.busy_now()
332    }
333
334    /// Ask the loop to stop *and* the run in flight to park at its next node
335    /// boundary.
336    ///
337    /// The plain [`Stop::stop`] never abandons a run, which is right when the
338    /// operator only wants the queue to drain: a competition is tens of
339    /// minutes and its worktrees are paid for. But an operator who wants to
340    /// replace the binary cannot wait out a run that has an hour left, and
341    /// killing the process loses whatever the seats in flight had not written.
342    /// Parking costs at most the node in progress and leaves the run
343    /// resumable.
344    pub fn park(&self) {
345        self.pause.park();
346        self.stop();
347    }
348
349    /// Has a park been asked for?
350    #[must_use]
351    pub fn parking(&self) -> bool {
352        self.pause.parked()
353    }
354
355    /// The pause handle to give a runner.
356    #[must_use]
357    pub fn pause(&self) -> crate::graph::Pause {
358        self.pause.clone()
359    }
360
361    /// Is any run in flight right now?
362    ///
363    /// `finishing` answers "a stop is waiting on a run", which is false until
364    /// someone asks to stop. An upgrade needs the plain question, because it
365    /// is about to be the one asking.
366    #[must_use]
367    pub fn busy_now(&self) -> bool {
368        self.busy.load(Ordering::SeqCst) > 0
369    }
370
371    /// Mark one more run as in flight, for [`Stop::finishing`].
372    fn enter(&self) {
373        self.busy.fetch_add(1, Ordering::SeqCst);
374    }
375
376    /// Mark one run as finished. The last one out is what makes
377    /// [`Stop::busy_now`] false again.
378    fn exit(&self) {
379        self.busy.fetch_sub(1, Ordering::SeqCst);
380    }
381
382    /// Wait out one poll interval, returning early once a stop is asked for.
383    async fn idle(&self, poll: Duration) {
384        tokio::select! {
385            () = tokio::time::sleep(poll) => {}
386            () = self.wake.notified() => {}
387        }
388    }
389}
390
391/// The daemon's published state, read permissively.
392///
393/// This mirrors [`Status`], but is a separate declaration on purpose: every
394/// field defaults, so a status file from an older or newer magi still yields
395/// a usable reading — one this build has never heard of — instead of a parse
396/// error that hides the daemon entirely.
397#[derive(Debug, Clone, Default, Deserialize)]
398#[serde(default)]
399pub struct Reading {
400    /// Format version the daemon claims.
401    pub schema: u32,
402    /// Daemon process id, for an operator who wants to stop it.
403    pub pid: Option<u32>,
404    /// When that process started.
405    pub started_at: Option<Timestamp>,
406    /// Last heartbeat. Absent means the file is unusable, hence not running.
407    pub updated_at: Option<Timestamp>,
408    /// True when the queue had nothing runnable at the last poll.
409    pub idle: bool,
410    /// What the daemon is working on. Empty means idle; more than one entry
411    /// means more than one run is in flight at once.
412    ///
413    /// `deserialize_with` rather than the plain derive: a daemon started
414    /// before this field became a list is still out there writing the old
415    /// shape — a single `{"task":...,"run":...}` object, or its absence —
416    /// on every heartbeat until it is restarted, and a live process reading
417    /// that file during the rollout must still see it as running rather than
418    /// as absent. A bare type change here would fail the whole struct's
419    /// deserialization on a type mismatch, defeating the permissiveness this
420    /// type exists for.
421    #[serde(deserialize_with = "de_current")]
422    pub current: Vec<Current>,
423    /// Tasks this daemon process has finished.
424    pub completed: u64,
425    /// Queue polls this daemon process has made.
426    pub polls: u64,
427}
428
429/// Accept the old single-`Current`-or-absent shape as well as the current
430/// list, so a reader never has to know which build wrote the file.
431fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
432where
433    D: serde::Deserializer<'de>,
434{
435    #[derive(Deserialize)]
436    #[serde(untagged)]
437    enum Shape {
438        Many(Vec<Current>),
439        One(Current),
440    }
441    Ok(
442        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
443            Shape::Many(v) => v,
444            Shape::One(c) => vec![c],
445        }),
446    )
447}
448
449impl Reading {
450    /// Seconds since the last heartbeat, or `None` when there has never been
451    /// one.
452    #[must_use]
453    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
454        self.updated_at
455            .map(|at| (now.as_second() - at.as_second()).max(0))
456    }
457
458    /// Whether the loop counts as running: a heartbeat no older than
459    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
460    /// progress hours after the daemon that owned it was killed.
461    #[must_use]
462    pub fn running(&self, now: Timestamp) -> bool {
463        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
464    }
465}
466
467/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
468/// usable there.
469///
470/// Missing, half-written and unparseable all collapse to `None`, because the
471/// only question a reader asks is whether a daemon is alive, and a file it
472/// cannot read is not evidence that one is.
473#[must_use]
474pub fn read_status(home: &Path) -> Option<Reading> {
475    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
476    serde_json::from_str(&body).ok()
477}
478
479/// Every run a live daemon is working on right now.
480///
481/// One definition of liveness, because deleting a task and deleting a run are
482/// both gated on it from both the CLI and the web UI - four callers that must
483/// never disagree about whether the same thing is in flight. A stale heartbeat
484/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
485/// left at `running` or a run left at `implementing` by a killed daemon is a
486/// leftover record rather than work in progress. More than one entry once
487/// [`crate::config::Daemon::max_concurrent_runs`] is more than one - a caller
488/// after "the one thing in flight" wants [`is_working_on`] or
489/// [`is_working_on_task`], not this directly.
490#[must_use]
491pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
492    read_status(home)
493        .filter(|reading| reading.running(now))
494        .map(|reading| reading.current)
495        .unwrap_or_default()
496}
497
498/// Whether a live daemon is working on this run at this moment.
499#[must_use]
500pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
501    current_work(home, now).iter().any(|c| c.run == run)
502}
503
504/// Whether a live daemon is working on a run whose short id is this one.
505///
506/// For a worktree that has no run record to compare against at all -
507/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
508/// id is not available to hand to [`is_working_on`]. The short id is: a run's
509/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
510/// and it is exactly the gap between the daemon claiming a task and
511/// `RunState::new` saving the first `run.json` that this exists to protect -
512/// a run genuinely in flight but invisible to a scan of `runs/`.
513#[must_use]
514pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
515    current_work(home, now)
516        .iter()
517        .any(|c| crate::run::short_of(&c.run) == short)
518}
519
520/// Whether a live daemon is working on this task at this moment.
521#[must_use]
522pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
523    current_work(home, now).iter().any(|c| c.task == task)
524}
525
526/// Remove claim files whose owner is provably dead, or that have simply
527/// outlived `older_than`, and return the task ids swept.
528///
529/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
530/// destructor, and the orphaned `.lock` file would make its task permanently
531/// unclaimable — the backlog would stop for good at exactly the task that was
532/// in flight when the machine went down.
533///
534/// The pid recorded in the lock is the authority whenever it can be read at
535/// all; age is only a fallback for when it cannot be.
536///
537/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
538///   full stop — dead sweeps the lock immediately, regardless of age; alive
539///   protects it, regardless of age. This is what lets a lock be reclaimed in
540///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
541///   before this daemon even started, next to a `queued` task, no longer has
542///   to sit for six hours before anything notices its owner is gone.
543/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
544///   falls back to `older_than`, since there is nothing else to check.
545///
546/// Age must never override a *positive* liveness confirmation. `sweep`
547/// [`poll`]s concurrently with every attempt this daemon itself has spawned —
548/// see [`InFlightGuard`] — not only between them the way a single sequential
549/// loop once did, so a run that legitimately runs longer than `older_than`
550/// (a multi-round review, a long land wait carried across several resumed
551/// attempts) still has this very process's own live pid sitting in its own
552/// lock file on every later sweep. Deciding by age alone in that case would
553/// delete this daemon's own still-valid claim on its own in-flight task,
554/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
555/// to a second attempt — two `Runner`s writing the same `run.json` and the
556/// same worktree at once. `pid_alive` answering "alive" for anything it
557/// cannot determine (a live process, a pid this build cannot check, one
558/// under another account) is exactly what keeps that path from ever
559/// firing on a guess.
560///
561/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
562/// output unreadable must not be license to guess, and the risk of an
563/// unparseable lock outliving a genuinely dead owner is bounded by an order
564/// of magnitude above any plausible run rather than by a positive check.
565///
566/// Runs on every poll, not only at startup — a daemon up for days must keep
567/// noticing a lock some other, now-dead, daemon left behind just as readily
568/// as one it trips over on the way up.
569pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
570    let this_process = std::process::id();
571    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
572        .into_iter()
573        .flatten()
574        .flatten()
575        .map(|e| e.path())
576        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
577        .filter(|p| {
578            match std::fs::read_to_string(p)
579                .ok()
580                .and_then(|body| body.trim().parse::<u32>().ok())
581            {
582                // This process wrote it and is asking the question right
583                // now, so it is definitionally still alive - settled without
584                // spawning a helper process at all.
585                Some(pid) if pid == this_process => false,
586                Some(pid) => !crate::proc::pid_alive(pid),
587                None => p
588                    .metadata()
589                    .and_then(|m| m.modified())
590                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
591                    .is_ok_and(|age| age >= older_than),
592            }
593        })
594        .filter(|p| std::fs::remove_file(p).is_ok())
595        .filter_map(|p| {
596            p.file_stem()
597                .and_then(|s| s.to_str())
598                .map(std::borrow::ToOwned::to_owned)
599        })
600        .collect();
601    swept.sort_unstable();
602    swept
603}
604
605/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
606/// no live daemon's heartbeat naming it? Deterministic — no model call, and
607/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
608/// shown.
609fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
610    task.status == TaskStatus::Running
611        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
612        && !is_working_on_task(home, &task.id, now)
613}
614
615/// Every task [`is_stalled`] right now — "止まったタスク" in
616/// `crate::conduct`'s vocabulary.
617fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
618    queue
619        .list()
620        .into_iter()
621        .filter(|t| is_stalled(t, home, now))
622        .collect()
623}
624
625/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
626/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
627/// `Failed`-and-so-also-runnable: a task that already attempted and lost
628/// belongs in [`finished_tasks`], where the question is a recovery, not a
629/// dependency.
630fn queued_tasks(queue: &Queue) -> Vec<Task> {
631    queue
632        .list()
633        .into_iter()
634        .filter(|t| t.status == TaskStatus::Queued)
635        .collect()
636}
637
638/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
639/// タスク" in `crate::conduct`'s vocabulary.
640fn finished_tasks(queue: &Queue) -> Vec<Task> {
641    queue
642        .list()
643        .into_iter()
644        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
645        .collect()
646}
647
648/// Deterministically resolve `Task::blocked_by`: a dependency task that
649/// reached `Done`, or a question that was answered, is removed — no model
650/// involved, on every poll. An answered question's content is copied onto
651/// the task ([`Task::record_answer`]) before its id is dropped, so it
652/// reaches the next `crate::conduct` prompt and the next run's instruction
653/// (see [`instruction_for`]) rather than only clearing the block.
654fn resolve_blockers(queue: &Queue, questions: &Questions) {
655    for listed in queue.list() {
656        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
657            continue;
658        }
659        let Ok(_claim) = queue.claim(&listed.id) else {
660            continue;
661        };
662        let Ok(mut task) = queue.get(&listed.id) else {
663            continue;
664        };
665        if task.status != TaskStatus::Blocked {
666            continue;
667        }
668        let mut changed = false;
669        for id in task.blocked_by.clone() {
670            if let Ok(dep) = queue.get(&id) {
671                if dep.status == TaskStatus::Done {
672                    task.unblock(&id);
673                    changed = true;
674                }
675                continue;
676            }
677            if let Ok(q) = questions.get(&id)
678                && q.status == ask::QuestionStatus::Answered
679            {
680                let answer = match &q.answer {
681                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
682                    None => String::new(),
683                };
684                task.record_answer(q.summary.clone(), answer);
685                task.unblock(&id);
686                changed = true;
687            }
688        }
689        if changed {
690            record(queue, &mut task);
691        }
692    }
693}
694
695/// Retire an unanswered conductor question after its task no longer refers to
696/// it. Conductor questions use the task id in `Question::run`, so run-based
697/// cleanup cannot observe a manual release or completion.
698///
699/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
700/// own question also carries a `run`, and a run id that happens to collide
701/// with some task's id is not this loop's business — only a conductor
702/// question actually uses the task id that way. One `Questions::list()` scan
703/// is taken up front and matched against the in-memory task set, rather than
704/// calling `Questions::open_for` (a full disk scan on its own) once per task.
705fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
706    let tasks = queue.list();
707    let by_id: std::collections::BTreeMap<&str, &Task> =
708        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
709    let referenced: std::collections::BTreeSet<&str> = tasks
710        .iter()
711        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
712        .collect();
713
714    for mut question in questions.list() {
715        if !question.status.open() || question.node != crate::conduct::NODE {
716            continue;
717        }
718        // Keep questions a task still names, including when the reference
719        // moved to a dependent task.
720        if referenced.contains(question.id.as_str()) {
721            continue;
722        }
723        let Some(task) = by_id.get(question.run.as_str()) else {
724            continue;
725        };
726        question.abandon(format!(
727            "task {} no longer waits for this answer",
728            task.short()
729        ));
730        if let Err(e) = questions.put(&mut question) {
731            tracing::warn!(
732                "could not retire question {} for task {}: {e:#}",
733                question.short(),
734                task.short()
735            );
736        }
737    }
738}
739
740/// What a finished run tells the queue about the task it came from.
741///
742/// A struct rather than a fourth and fifth boolean argument: the two flags
743/// answer different questions about the same run, and a call site passing
744/// `(…, true, false)` is one transposition away from refunding attempts
745/// forever.
746#[derive(Debug, Clone, Copy)]
747pub struct Verdict {
748    /// Where the graph stopped.
749    pub status: RunStatus,
750    /// The run opened a pull request.
751    pub left_pr: bool,
752    /// At least one seat was lost to a rate limit.
753    pub quota_hit: bool,
754    /// The run parked at a node boundary because it was asked to.
755    pub parked: bool,
756    /// The run never produced a single candidate a judge could look at.
757    ///
758    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
759    /// still have another candidate worth judging, in which case the loss was
760    /// not the reason nothing came of the run. This is `true` only when the
761    /// implement wave ended with nothing viable at all.
762    pub no_viable_candidates: bool,
763}
764
765/// Record a finished run against the task it came from.
766///
767/// Kept pure and separate from the loop because this mapping *is* the retry
768/// policy, and a policy that can only be exercised by spawning a graph is a
769/// policy nobody checks. The table:
770///
771/// | run status                           | task becomes        | attempt spent |
772/// |---------------------------------------|---------------------|---------------|
773/// | parked at a boundary                  | `Failed` (requeued) | **no**        |
774/// | `Merged`, `Ready`                      | `Done`               | yes          |
775/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
776/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
777/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
778/// | `Blocked` with a PR                    | `Held`               | yes          |
779/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
780/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
781///
782/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
783/// twice, together. A quorum lost to rate limits is a property of the machine
784/// and not of the task, so the attempt is refunded and a reset quota picks
785/// the work up where it stopped — and that is just as true when every
786/// implement seat lost the same race and `after_implement` bails with nothing
787/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
788/// machine fact. The `no_viable_candidates` guard is what keeps that row
789/// narrow: a `Failed` run that produced a real candidate which then lost for
790/// some other reason still spends the attempt, exactly like the quorum lost
791/// to judges that answered with the wrong shape is ordinary flakiness, and
792/// refunding *that* takes the bound off the retry loop entirely: run e633
793/// stalled with `quota: []` after two judges wrote unusable JSON, was
794/// refunded, and the next attempt paid for a fresh hour-long implement wave
795/// before it could fail the same way. `max_attempts` exists precisely so
796/// that cannot repeat forever.
797///
798/// A non-terminal status means `execute` returned while the graph was still
799/// mid-flight, which is a bug rather than a verdict; it is treated as a
800/// failure so that a task cannot loop on it either.
801///
802/// `left_pr` splits the `Blocked` row, and it is the difference between a run
803/// that failed and a run that finished into a gate. See [`Task::handed_off`].
804pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
805    // A parked run is the operator's own doing, and its work is intact on
806    // disk. The task goes back in line with its attempt refunded so the next
807    // loop resumes the same run - which `one_task` prefers over competing
808    // again - and so that swapping the binary a few times cannot exhaust a
809    // budget meant for agents that actually misbehaved.
810    if verdict.parked {
811        task.stall(detail);
812        return;
813    }
814    match verdict.status {
815        RunStatus::Merged | RunStatus::Ready => task.succeed(),
816        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
817        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
818            task.stall(detail)
819        }
820        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
821        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
822        RunStatus::Blocked => task.fail(detail, max_attempts),
823        other => task.fail(
824            format!(
825                "the graph stopped at `{}` without reaching a terminal status: {detail}",
826                label(other)
827            ),
828            max_attempts,
829        ),
830    }
831}
832
833/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
834/// task ends up held.
835///
836/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
837/// dead daemon never got back to) share this, so the two cannot drift into
838/// disagreeing about which held tasks get a diagnostic.
839fn settle_and_diagnose(
840    task: &mut Task,
841    verdict: Verdict,
842    detail: &str,
843    max_attempts: usize,
844    state: &RunState,
845) {
846    settle(task, verdict, detail, max_attempts);
847    if task.status == TaskStatus::Held {
848        task.diagnostic = diagnostic(state);
849    }
850}
851
852/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
853/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
854/// by some other means entirely, like a manual `magi run` resume that
855/// finishes the graph outside the queue's bookkeeping.
856///
857/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
858/// `settle` is separate from `attempt`: a task recovered this way must land
859/// exactly where a live daemon would have put it — the same policy table,
860/// not a second one that quietly drifts from it — and that is only checkable
861/// without spawning a real run.
862fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize) {
863    match last_run {
864        Some(state) => {
865            let verdict = Verdict {
866                status: state.status,
867                left_pr: state.pr.is_some(),
868                quota_hit: !state.quota.is_empty(),
869                parked: state.parked,
870                no_viable_candidates: state.viable().is_empty(),
871            };
872            let detail = format!(
873                "recovered a `running` task whose daemon never recorded the outcome: {}",
874                describe(&state)
875            );
876            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
877        }
878        None => {
879            let why = "task was `running` with no live daemon and no readable \
880                       run to recover; held for a human to check what happened";
881            task.last_error = Some(why.to_owned());
882            // The phone shows `hold_reason`, so a task held by the machine
883            // says why there too and not only in `last_error`.
884            task.hold(Some(why.to_owned()));
885        }
886    }
887}
888
889/// Find every task left at `running` that no live process is actually
890/// driving, and settle each one against whatever its last run became.
891///
892/// # Why a claim is proof, not a guess
893///
894/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
895/// `running`, and the guard is held for the task's whole time in that status:
896/// `attempt` does not return, and the loop does not move past the scope
897/// holding the claim, until the run has settled. So a `running` task whose
898/// lock is gone cannot have a live owner — this process or any other —
899/// without needing a staleness threshold or a pid check the way
900/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
901/// task that never got as far as `running` at all. Taking the claim here is
902/// the whole test: it either fails, because something really does hold it
903/// and the task is left alone, or it succeeds, which is the proof — and it is
904/// kept for the rest of the decision so nothing else can start a competing
905/// run while this one is being written.
906///
907/// Called on every poll, not only at startup, for the reason
908/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
909/// keep noticing this, not only on the one morning it happened to restart.
910fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
911    let mut reclaimed = Vec::new();
912    for listed in queue.list() {
913        if listed.status != TaskStatus::Running {
914            continue;
915        }
916        let Ok(_claim) = queue.claim(&listed.id) else {
917            continue;
918        };
919        // Re-read under the claim: a release or an edit landed by a human
920        // between the listing above and the claim just taken must not be
921        // clobbered by a decision based on the stale copy.
922        let Ok(mut task) = queue.get(&listed.id) else {
923            continue;
924        };
925        if task.status != TaskStatus::Running {
926            continue;
927        }
928        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
929        // `execute` normally abandons a run's own open questions the moment
930        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
931        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
932        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
933        // with the question still `open`, because the process died before
934        // reaching that call. `reclaim` itself stays pure on purpose (see its
935        // own doc), so the same cleanup runs here instead, against the run
936        // this reclaim is already reading. `settle_run` costs nothing when
937        // `execute` already got there first.
938        if let Some(state) = &last_run
939            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
940        {
941            tracing::warn!("abandon questions for {}: {e:#}", state.id);
942        }
943        reclaim(&mut task, last_run, max_attempts);
944        record(queue, &mut task);
945        reclaimed.push(task.id.clone());
946    }
947    reclaimed
948}
949
950/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
951///
952/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
953/// sets, so there is one loop body rather than two that drift apart the first
954/// time the retry policy changes on only one of them.
955pub async fn serve(opts: Opts) -> Result<()> {
956    serve_until(opts, Stop::new()).await
957}
958
959/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
960///
961/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
962/// mid-node leaves worktrees, branches and agent sessions behind, and every
963/// agent call already paid for is lost; finishing the run costs the operator a
964/// wait and saves them a cleanup. A stop therefore only sets a flag: the
965/// current `execute` runs to its terminal status, the task's outcome is
966/// recorded, and only then does the loop return. That window is what
967/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
968/// still has a second Ctrl-C, which the runtime turns into a process kill —
969/// and the task left `Running` then tells the next daemon, and the next human,
970/// where to look.
971///
972/// While the queue is empty the stop is honoured within one wakeup rather than
973/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
974/// caller that taps stop does not sit through the remainder of a sleep.
975pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
976    let signal = {
977        let stop = stop.clone();
978        tokio::spawn(async move {
979            if tokio::signal::ctrl_c().await.is_ok() {
980                stop.stop();
981                tracing::info!("shutdown requested; a run in flight will be finished first");
982            }
983        })
984    };
985
986    let worktrees_root = opts
987        .worktrees_root
988        .clone()
989        .unwrap_or_else(crate::run::default_worktree_root);
990    let outcome = drive(
991        &opts,
992        &Queue::open(),
993        &status_path(),
994        &crate::run::home(),
995        &worktrees_root,
996        &stop,
997    )
998    .await;
999
1000    signal.abort();
1001    outcome
1002}
1003
1004/// The loop proper: setup, poll, teardown, with the queue and the status file
1005/// supplied rather than discovered.
1006///
1007/// All three of `home`, `worktrees_root` and the queue/status paths are
1008/// parameters rather than resolved here, for the same reason:
1009/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
1010/// so a unit test that pinned it would fight every other test in the binary,
1011/// and a loop that resolved its own worktree bay could only be exercised
1012/// against the operator's real `~/wt/<repo>` - publishing over a live
1013/// daemon's status file, claiming tasks out of a live backlog, and, since
1014/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
1015/// whatever the operator actually has on disk.
1016async fn drive(
1017    opts: &Opts,
1018    queue: &Queue,
1019    status_file: &Path,
1020    home: &Path,
1021    worktrees_root: &Path,
1022    stop: &Stop,
1023) -> Result<()> {
1024    // The status file is a *snapshot*, not a stream of events: a reader only
1025    // ever wants the latest values, and every tick rewrites the whole file
1026    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
1027    // while an mpsc channel would force the loop to re-send unchanged fields on
1028    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
1029    // for no gain. The lock is only ever held across a field assignment, never
1030    // across an await.
1031    let status = Arc::new(Mutex::new(Status::new()));
1032    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1033    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1034
1035    // Read once at startup, not per task: how many runs this loop drives at
1036    // once is a property of the machine running it, not of whichever
1037    // repository a given task happens to name - see
1038    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
1039    // fact in the same sense the agent roster is.
1040    let concurrency = max_concurrent(
1041        prepare(&opts.repo, opts)
1042            .map(|c| c.daemon.max_concurrent_runs)
1043            .unwrap_or(1),
1044    );
1045
1046    tracing::info!(
1047        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once)",
1048        queue.root().display(),
1049        opts.poll.as_secs(),
1050        opts.max_attempts,
1051        concurrency
1052    );
1053
1054    // `--once` drains an already-idle queue without reaching the idle wait,
1055    // but must still perform the startup cleanup.
1056    janitor(&opts.repo, opts, home, worktrees_root).await;
1057
1058    let outcome = poll(
1059        opts,
1060        queue,
1061        &status,
1062        home,
1063        worktrees_root,
1064        stop,
1065        concurrency,
1066    )
1067    .await;
1068
1069    beat.abort();
1070    clear_status_at(status_file);
1071    outcome
1072}
1073
1074/// Refresh the status file on a fixed tick.
1075///
1076/// Separate from the loop because a run takes tens of minutes: a status file
1077/// written only between tasks would look stale for the whole of every run, and
1078/// a reader would report the daemon dead exactly while it was busiest.
1079async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1080    loop {
1081        tokio::time::sleep(HEARTBEAT).await;
1082        let snapshot = {
1083            let mut guard = lock(&status);
1084            guard.updated_at = Timestamp::now();
1085            guard.clone()
1086        };
1087        if let Err(e) = write_status_to(&path, &snapshot) {
1088            // A failed heartbeat must not take the daemon down: the loop is the
1089            // product, the status file is only the window onto it.
1090            tracing::warn!("could not refresh the daemon status file: {e:#}");
1091        }
1092    }
1093}
1094
1095/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
1096/// if so, whether that wait is over.
1097#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1098enum LandResume {
1099    /// The task's last run is not parked on a land approval; schedule it
1100    /// like any other candidate.
1101    NotLanding,
1102    /// Parked in `land`, waiting on a question nobody has answered yet.
1103    /// Left alone: attempting it now would only re-observe the same pull
1104    /// request and park again, spending a `gh` call on a decision that has
1105    /// not changed since the last time this was checked.
1106    StillWaiting,
1107    /// Parked in `land`, and the question is settled - answered or
1108    /// abandoned. Resuming this is the one kind of candidate that must not
1109    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
1110    Ready,
1111}
1112
1113/// Classify a runnable candidate by whether it is parked on a land-merge
1114/// approval. Read-only - no claim taken, nothing written - so it is cheap
1115/// enough to call on every candidate, every poll.
1116fn land_resume_state(task: &Task) -> LandResume {
1117    let Some(run_id) = task.runs.last() else {
1118        return LandResume::NotLanding;
1119    };
1120    let Ok(state) = RunState::load(run_id) else {
1121        return LandResume::NotLanding;
1122    };
1123    if state.status != RunStatus::Landing || !state.parked {
1124        return LandResume::NotLanding;
1125    }
1126    let store = ask::Questions::open();
1127    let waiting = store
1128        .list()
1129        .into_iter()
1130        .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
1131        .max_by(|a, b| a.id.cmp(&b.id));
1132    let Some(mut q) = waiting else {
1133        return LandResume::Ready;
1134    };
1135    if !q.status.open() {
1136        return LandResume::Ready;
1137    }
1138    // `ask::ask_and_wait`'s own deadline is what used to retire a question
1139    // nobody ever answered; land's approval bypasses that wait entirely (see
1140    // `land::approval_gate`), so the same deadline has to be enforced here
1141    // instead, or `graph.answer_timeout` silently stops meaning anything for
1142    // a land approval and a run can sit `StillWaiting` forever with nobody
1143    // told to look at it.
1144    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
1145    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
1146    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
1147        q.abandon(format!(
1148            "no answer within {}s of asking",
1149            timeout.as_secs().max(1)
1150        ));
1151        // If this can't be persisted, do not treat the wait as settled on a
1152        // guess: fall through and try again next poll.
1153        if store.put(&mut q).is_ok() {
1154            return LandResume::Ready;
1155        }
1156    }
1157    LandResume::StillWaiting
1158}
1159
1160/// How often the loop rechecks for new work while something it already
1161/// started is still running, rather than sleeping out the whole
1162/// [`Opts::poll`] interval.
1163///
1164/// Short on purpose: this is what lets a land-merge approval that comes back
1165/// while another task is mid-competition be noticed and resumed within a
1166/// fraction of a second, not within the next multi-second poll.
1167const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
1168
1169/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
1170/// in `Status::current` - on drop, so both are released even if the attempt
1171/// panics rather than returning.
1172///
1173/// A `Drop` impl rather than statements written after the `.await` it
1174/// guards: a panic unwinds straight past code placed "after" a call, and
1175/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
1176/// that ruling a panic out there is not a bet this loop can make. Without
1177/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
1178/// forever - the idle branch in [`poll`], and with it the janitor, would
1179/// never run again - and a ghost entry in `Status::current` naming a task
1180/// nothing is still working on.
1181struct InFlightGuard<'a> {
1182    status: &'a Arc<Mutex<Status>>,
1183    stop: &'a Stop,
1184    task_id: &'a str,
1185}
1186
1187impl Drop for InFlightGuard<'_> {
1188    fn drop(&mut self) {
1189        lock(self.status).current.retain(|c| c.task != self.task_id);
1190        self.stop.exit();
1191    }
1192}
1193
1194/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
1195/// teardown and cannot skip the teardown on an early return.
1196///
1197/// `max_concurrent` bounds how many *ordinary* candidates run at once - see
1198/// [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a land
1199/// approval that has since been answered is dispatched outside that bound
1200/// the moment [`land_resume_state`] reports it [`LandResume::Ready`]: the
1201/// whole point of parking there is that it must not queue behind whatever
1202/// else the loop happens to be running, even at the default of one.
1203async fn poll(
1204    opts: &Opts,
1205    queue: &Queue,
1206    status: &Arc<Mutex<Status>>,
1207    home: &Path,
1208    worktrees_root: &Path,
1209    stop: &Stop,
1210    max_concurrent: usize,
1211) -> Result<()> {
1212    // Only consulted by `once`, where a task that just failed is still
1213    // `runnable` and would otherwise be picked up again inside the same drain.
1214    // In the long-running mode a later poll retrying a failed task is the point,
1215    // and the attempt counter is what bounds it.
1216    let mut attempted: Vec<String> = Vec::new();
1217    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
1218    // A quota hit is a fact about the machine, not the task that happened to
1219    // surface it, and every other *ordinary* candidate is no less likely to
1220    // hit the same wall - see the warning below. A land-merge resume is
1221    // exempt: it is a human decision finishing, not a fresh competition, and
1222    // must not sit out a quota cooldown it did not cause.
1223    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
1224    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
1225    let mut conductor = Conductor::new();
1226
1227    while !stop.stopped() {
1228        lock(status).polls += 1;
1229
1230        // Reap whatever finished since the last tick without blocking on
1231        // anything still running. `InFlightGuard` already released the slot
1232        // even if the spawned attempt panicked; this only surfaces that it
1233        // happened, since a panic swallowed here otherwise leaves no trace.
1234        while let Some(result) = inflight.try_join_next() {
1235            if let Err(e) = result {
1236                tracing::error!("a spawned attempt did not finish cleanly: {e}");
1237            }
1238        }
1239
1240        let swept = sweep_stale_claims(queue, STALE_CLAIM);
1241        if !swept.is_empty() {
1242            tracing::warn!(
1243                "swept {} stale claim(s) left behind by an earlier daemon: {}",
1244                swept.len(),
1245                swept.join(", ")
1246            );
1247        }
1248        // Capture stalled work before reclaiming it. A dead daemon's ordinary
1249        // lock is swept and reclaimed in this same poll, but the conductor
1250        // must still see that it was stranded rather than only its mechanical
1251        // terminal state.
1252        let now = Timestamp::now();
1253        let stalled = stalled_tasks(queue, home, now);
1254        let stalled_ids: std::collections::BTreeSet<_> =
1255            stalled.iter().map(|task| task.id.clone()).collect();
1256        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
1257        if !reclaimed.is_empty() {
1258            tracing::warn!(
1259                "reclaimed {} task(s) left `running` by a daemon that never \
1260                 recorded the outcome: {}",
1261                reclaimed.len(),
1262                reclaimed.join(", ")
1263            );
1264        }
1265
1266        // `home`, not `ask::Questions::open()`'s own process-global default:
1267        // `poll` is handed its home explicitly precisely so a test can point
1268        // it elsewhere, the same reason `Queue::at` and the status file path
1269        // are parameters rather than resolved here - see `drive`'s own doc.
1270        let questions = Questions::at(home.join("questions"));
1271
1272        // Deterministic: no model, run before the conductor sees anything so
1273        // its input reflects the queue's current, already-resolved state.
1274        resolve_blockers(queue, &questions);
1275        reconcile_task_questions(queue, &questions);
1276
1277        // The conductor gets one look per cycle, right before the loop takes
1278        // its next task, and only when there is something new to look at -
1279        // see `Conductor::worth_a_look`'s own doc for why "stalled is
1280        // non-empty" is the wrong test. Checked before `prepare` so an
1281        // unchanged cycle never pays for a synchronous config load.
1282        let finished: Vec<Task> = finished_tasks(queue)
1283            .into_iter()
1284            .filter(|task| !stalled_ids.contains(&task.id))
1285            .collect();
1286        let queued = queued_tasks(queue);
1287        // An empty queue has nothing to arrange. In particular, do not let
1288        // the conductor's initial snapshot cause synchronous config I/O
1289        // between the caller's stop notification and the idle wait below.
1290        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
1291            && conductor.worth_a_look(queue, &stalled, &finished)
1292        {
1293            match prepare(&opts.repo, opts) {
1294                Ok(cfg) => {
1295                    conductor
1296                        .maybe_run(
1297                            &cfg,
1298                            &opts.repo,
1299                            queue,
1300                            &questions,
1301                            home,
1302                            &queued,
1303                            &stalled,
1304                            &finished,
1305                            opts.max_attempts,
1306                        )
1307                        .await;
1308                }
1309                Err(e) => tracing::warn!("conductor: no config: {e:#}"),
1310            }
1311        }
1312
1313        let candidates: Vec<Task> = runnable(queue)
1314            .into_iter()
1315            .filter(|t| !opts.once || !attempted.contains(&t.id))
1316            .collect();
1317
1318        let cooling_down =
1319            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
1320
1321        let mut started_any = false;
1322        for candidate in candidates {
1323            if stop.stopped() {
1324                break;
1325            }
1326
1327            let resume = land_resume_state(&candidate);
1328            if resume == LandResume::StillWaiting {
1329                continue;
1330            }
1331            let priority = resume == LandResume::Ready;
1332
1333            if !priority && cooling_down {
1334                continue;
1335            }
1336            let permit = if priority {
1337                None
1338            } else {
1339                match Arc::clone(&sem).try_acquire_owned() {
1340                    Ok(p) => Some(p),
1341                    // No ordinary slot free right now. A later candidate in
1342                    // this same list might still be a priority resume, so
1343                    // keep looking rather than stopping here.
1344                    Err(_) => continue,
1345                }
1346            };
1347
1348            // A claim we cannot take means another daemon, or a human running
1349            // `magi run`, got there first. That is not the task's fault and
1350            // must not spend one of its attempts: move to the next candidate
1351            // rather than recording a failure.
1352            let Ok(claim) = queue.claim(&candidate.id) else {
1353                tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
1354                continue;
1355            };
1356            // Re-read under the claim: the task on disk may have been held or
1357            // edited between the listing and the lock.
1358            let mut task = match queue.get(&candidate.id) {
1359                Ok(t) if t.status.runnable() => t,
1360                Ok(_) => continue,
1361                Err(e) => {
1362                    tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
1363                    continue;
1364                }
1365            };
1366            let task_id = task.id.clone();
1367            attempted.push(task_id.clone());
1368            lock(status).idle = false;
1369            // A stop asked for from here on is "finishing", not "stopped": the
1370            // run gets to reach a terminal status before the loop returns.
1371            stop.enter();
1372            started_any = true;
1373
1374            let opts = opts.clone();
1375            let queue = queue.clone();
1376            let status = Arc::clone(status);
1377            let stop = stop.clone();
1378            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
1379            inflight.spawn(async move {
1380                // Held for the whole attempt: dropping either at the end of
1381                // this task is what releases the claim and, for an ordinary
1382                // candidate, frees its concurrency slot back to the loop.
1383                let _claim = claim;
1384                let _permit = permit;
1385                // See `InFlightGuard`: this must survive a panic inside `attempt`.
1386                let _inflight = InFlightGuard {
1387                    status: &status,
1388                    stop: &stop,
1389                    task_id: &task_id,
1390                };
1391                let quota = attempt(&opts, &queue, &status, &stop, &mut task).await;
1392                lock(&status).completed += 1;
1393                // A quota loss is a fact about the machine, not this task, and
1394                // the next ordinary candidate the loop offers is no less
1395                // likely to hit the same wall: without a cooldown here a
1396                // whole backlog can be run - and failed - in the seconds it
1397                // takes each attempt to notice the CLI is out of quota.
1398                if !quota.is_empty() {
1399                    let hint = quota.iter().find_map(|q| q.reset.as_deref());
1400                    let reset_at = hint.and_then(|h| parse_reset_hint(h, Timestamp::now()));
1401                    let wait = quota_wait(
1402                        reset_at,
1403                        Timestamp::now(),
1404                        QUOTA_WAIT_FALLBACK,
1405                        QUOTA_WAIT_CAP,
1406                    );
1407                    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
1408                    let until = Timestamp::now()
1409                        .checked_add(jiff::SignedDuration::from_secs(secs))
1410                        .unwrap_or(Timestamp::MAX);
1411                    *lock(&quota_cooldown_until) = Some(until);
1412                    match hint {
1413                        Some(h) => tracing::warn!(
1414                            "quota hit; waiting {}s before taking another ordinary task \
1415                             (CLI reported reset: {h})",
1416                            wait.as_secs()
1417                        ),
1418                        None => tracing::warn!(
1419                            "quota hit; waiting {}s before taking another ordinary task \
1420                             (no reset hint reported)",
1421                            wait.as_secs()
1422                        ),
1423                    }
1424                }
1425            });
1426        }
1427
1428        if started_any {
1429            continue;
1430        }
1431
1432        if stop.busy_now() {
1433            // Something started on an earlier tick is still running. Recheck
1434            // soon rather than sleeping out the whole poll interval - a freed
1435            // slot, or a land approval answered mid-run, must not sit idle
1436            // for it.
1437            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
1438            continue;
1439        }
1440
1441        // Truly idle: nothing new to start and nothing still running.
1442        lock(status).idle = true;
1443        if opts.once {
1444            // A one-shot drain must perform the same post-work cleanup as a
1445            // daemon that reached a normal idle interval. The startup pass
1446            // cannot see runs or cache files produced by this drain.
1447            janitor(&opts.repo, opts, home, worktrees_root).await;
1448            break;
1449        }
1450        stop.idle(opts.poll).await;
1451        if stop.stopped() {
1452            continue;
1453        }
1454        // Housekeeping only after a full quiet interval. Running it before
1455        // the first idle wait can block the executor while an operator's
1456        // stop request is waiting to be scheduled, defeating Stop's retained
1457        // wake permit. No run can start while this branch is active, so the
1458        // janitor still never races an in-flight compile.
1459        janitor(&opts.repo, opts, home, worktrees_root).await;
1460    }
1461
1462    // Never return while a run is still in flight, whichever way the loop
1463    // above exited: a stop only sets a flag - see `serve_until` - and
1464    // returning here while `inflight` still holds spawned work would abandon
1465    // it exactly as a mid-node kill would.
1466    while let Some(result) = inflight.join_next().await {
1467        if let Err(e) = result {
1468            tracing::error!("a spawned attempt did not finish cleanly: {e}");
1469        }
1470    }
1471    Ok(())
1472}
1473
1474/// Run one claimed task to a terminal status and record the outcome.
1475///
1476/// Every transition is flushed to the queue as it happens, so the state on disk
1477/// is what actually occurred rather than what this process still intends to
1478/// write.
1479async fn attempt(
1480    opts: &Opts,
1481    queue: &Queue,
1482    status: &Arc<Mutex<Status>>,
1483    stop: &Stop,
1484    task: &mut Task,
1485) -> Vec<QuotaLoss> {
1486    let repo = repo_for(task, &opts.repo);
1487    tracing::info!(
1488        "task {} — {} (repo {})",
1489        task.short(),
1490        task.title,
1491        repo.display()
1492    );
1493
1494    let mut config = match prepare(&repo, opts) {
1495        Ok(c) => c,
1496        Err(e) => {
1497            // A setup failure spends an attempt even though no run was minted.
1498            // Without that, a task naming a repository that does not exist
1499            // would be retried at every poll for as long as the daemon lives.
1500            task.attempts += 1;
1501            task.fail(format!("config: {e:#}"), opts.max_attempts);
1502            record(queue, task);
1503            return Vec::new();
1504        }
1505    };
1506    apply_solo(&mut config, task);
1507
1508    // The free-space gate, checked *before* anything is minted: a task that
1509    // waits out a full disk costs nothing yet, and must not spend an attempt
1510    // or start a run the machine cannot finish. Held tasks stay in the list
1511    // for the human to see, and `magi task release` re-queues them when space
1512    // comes back - the same recovery as any other hold. A volume whose free
1513    // space cannot be measured closes the gate too: starting a run blind on a
1514    // disk that may be full is how the machine ends up with 6.7 GB free.
1515    if let Some(reason) = disk_gate(&repo, &config) {
1516        task.last_error = Some(reason.clone());
1517        task.hold(Some(reason.clone()));
1518        record(queue, task);
1519        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
1520        return Vec::new();
1521    }
1522
1523    // A resumable run of this task is carried on, never re-competed. The
1524    // candidates are built and paid for, and a fresh competition races a
1525    // second implementation against them.
1526    //
1527    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
1528    // started 3cbf on the same task a moment later, duplicating two and a
1529    // half hours of agent work. Then b25f stalled on a judge that timed out
1530    // and one that answered with no JSON - `quota: 0`, so nothing the machine
1531    // was to blame for - and 4043 started **one second** later, buying three
1532    // fresh implementations to reach the same panel. `RunStatus::resumable`
1533    // rather than `!done()` is what catches the second case: a stall is
1534    // terminal, and its cheap recovery re-asks only the absent seats.
1535    //
1536    // A load failure is warned about rather than silently read as "not
1537    // resumable": the alternative is exactly what let a schema mismatch on
1538    // run `eba2` fall through to a full re-competition with nobody told why.
1539    // `crate::conduct` is what actually offers a better answer than
1540    // `Runner::start` here (see `Recovery::Review`), once this task's next
1541    // failure shows it up as `held`/`failed` with the run state unreadable.
1542    let unfinished = (!task.fresh_start)
1543        .then(|| unfinished_run(&task.runs, task.short()))
1544        .flatten();
1545    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
1546    // branch survived, and this reopens exactly that branch as a
1547    // review-only pass rather than resuming or competing again. Consumed
1548    // (cleared) here whichever way this goes, so it never outlives this one
1549    // attempt - see `queue::Task::review_branch`.
1550    let review_branch = task.review_branch.take();
1551    let branch_exists = match &review_branch {
1552        Some(branch) => crate::git::branch_exists(&repo, branch)
1553            .await
1554            .unwrap_or(false),
1555        None => false,
1556    };
1557    let starter = choose_starter(
1558        review_branch.as_deref(),
1559        branch_exists,
1560        unfinished.as_deref(),
1561    );
1562    let started = match &starter {
1563        Starter::Review(branch) => {
1564            tracing::info!(
1565                "task {} reopens `{branch}` as a review-only pass",
1566                task.short()
1567            );
1568            Runner::review(&repo, branch, config).await
1569        }
1570        Starter::Resume(id) => {
1571            tracing::info!("resuming run {id} rather than competing again");
1572            Runner::resume(id).map(|mut r| {
1573                if let Some(instruction) =
1574                    prepare_instruction(&starter, Some(&r.state.instruction), task)
1575                {
1576                    r.state.instruction = instruction;
1577                }
1578                r
1579            })
1580        }
1581        Starter::Start => {
1582            if let Some(branch) = &review_branch {
1583                tracing::warn!(
1584                    "conductor chose review for task {} but branch `{branch}` no longer \
1585                     exists; requeuing as a fresh competition instead",
1586                    task.short()
1587                );
1588            }
1589            let instruction = prepare_instruction(&starter, None, task)
1590                .unwrap_or_else(|| task.instruction.clone());
1591            Runner::start(&repo, instruction, config).await
1592        }
1593    };
1594    let mut runner = match started {
1595        Ok(r) => r,
1596        Err(e) => {
1597            task.attempts += 1;
1598            task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
1599            record(queue, task);
1600            return Vec::new();
1601        }
1602    };
1603    // A stop that means "park" reaches the graph through this handle.
1604    runner.on_pause(stop.pause());
1605
1606    // `start` has minted the run, so the task can now point at it. Persisting
1607    // `Running` before `execute` is what makes a crash mid-run legible.
1608    let run = runner.state.id.clone();
1609    task.start(run.clone());
1610    record(queue, task);
1611    lock(status).current.push(Current {
1612        task: task.id.clone(),
1613        run,
1614    });
1615
1616    let detail = match runner.execute().await {
1617        Ok(()) => describe(&runner.state),
1618        Err(e) => format!("{e:#}"),
1619    };
1620    let verdict = Verdict {
1621        status: runner.state.status,
1622        // A run that opened a pull request handed its work over, whatever the
1623        // gate then decided about merging it.
1624        left_pr: runner.state.pr.is_some(),
1625        // Only a rate limit earns the task its attempt back.
1626        quota_hit: !runner.state.quota.is_empty(),
1627        // A run that parked was asked to stop; that is not a failure and must
1628        // not spend an attempt, or replacing the binary a few times would
1629        // exhaust a task's budget without an agent ever misbehaving.
1630        parked: runner.state.parked,
1631        // A quota loss that left nothing viable is the same machine fact as a
1632        // `Stalled` quota loss; see `settle`'s doc table.
1633        no_viable_candidates: runner.state.viable().is_empty(),
1634    };
1635    settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
1636    record(queue, task);
1637    tracing::info!(
1638        "task {} is {} after run {} ({})",
1639        task.short(),
1640        task.status.as_str(),
1641        runner.state.short(),
1642        label(runner.state.status)
1643    );
1644    runner.state.quota
1645}
1646
1647/// Cut this attempt's candidate count to one when the task asked to run
1648/// alone.
1649///
1650/// Pure and separate from [`attempt`] so the one thing this feature changes -
1651/// which `candidates` a `solo` task's run is built with - can be asserted
1652/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
1653/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
1654/// value from the caller's own copy, so a repository's `magi.toml` on disk is
1655/// never touched - only the `Config` this one attempt hands to `Runner::start`.
1656fn apply_solo(config: &mut Config, task: &Task) {
1657    if task.solo {
1658        config.graph.candidates = 1;
1659    }
1660}
1661
1662/// Load the config for a task's repository, with the merge override applied.
1663fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
1664    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
1665    if let Some(mode) = &opts.merge {
1666        config.merge.mode = merge_mode(mode)?;
1667    }
1668    Ok(config)
1669}
1670
1671/// The disk janitor, with its housekeeping logged rather than fatal.
1672///
1673/// Called only at the loop's idle points, for the reason the caller documents:
1674/// a prune racing a live compile would delete files mid-build. The config is
1675/// re-read on every call because the repository that just ran may not be the
1676/// daemon's own default, and the cache directory is a repository fact.
1677///
1678/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
1679/// and [`crate::run::default_worktree_root`] read here, for the same reason
1680/// [`drive`] takes its queue and status file rather than resolving them: a
1681/// test driving the loop must not reach through to the operator's real home
1682/// or worktree bay just because the janitor runs on every idle tick.
1683/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
1684/// to get wrong silently - a test's `home` was already isolated, but nothing
1685/// exercised the parameter next to it, so a real worktree bay stayed wired in
1686/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
1687/// it for real, every test in this file that drives the loop at all started
1688/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
1689async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
1690    let cfg = match prepare(repo, opts) {
1691        Ok(cfg) => cfg,
1692        Err(e) => {
1693            tracing::warn!("housekeep: no config: {e:#}");
1694            return;
1695        }
1696    };
1697    // A run's own worktree lives under `config.graph.worktree_root` when the
1698    // repository sets one - the same precedence `RunState::worktree_root`
1699    // uses - and `worktrees_root` only stands in for the *default* an
1700    // unconfigured repository resolves to (see this function's own
1701    // parameter, or the test fixture wiring one to a fake path). Housekeeping
1702    // that always swept the default regardless of this override would never
1703    // see, and so never reclaim, a single worktree for a repository that
1704    // relocated them elsewhere.
1705    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
1706    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
1707    // Reported whenever there is anything to say, not only when `folded > 0`:
1708    // the incident this exists to prevent was 90 of 93 runs skipped and 0
1709    // folded, on every single pass, for months - a report gated on `folded`
1710    // would have stayed silent through every one of them.
1711    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
1712        let mut extra = Vec::new();
1713        if out.unreadable > 0 {
1714            extra.push(format!("{} unreadable", out.unreadable));
1715        }
1716        if out.orphaned_worktrees > 0 {
1717            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
1718        }
1719        let detail = if extra.is_empty() {
1720            String::new()
1721        } else {
1722            format!(" ({})", extra.join(", "))
1723        };
1724        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
1725    }
1726    if out.cache_files > 0 {
1727        tracing::info!(
1728            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
1729            out.cache_files,
1730            out.cache_freed
1731        );
1732    }
1733    if out.questions_abandoned > 0 {
1734        tracing::info!(
1735            "housekeep: abandoned {} question(s) left open by a finished run",
1736            out.questions_abandoned
1737        );
1738    }
1739}
1740
1741/// The free-space gate: what stands between this task and a new run, if
1742/// anything. `Some(reason)` holds the task; `None` lets it start.
1743///
1744/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
1745/// the operator opted out. A measurement failure is a gate, not a pass: both
1746/// sides of "cannot tell" are served by not starting.
1747fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
1748    let min = config.disk.min_free_bytes;
1749    if min == 0 {
1750        return None;
1751    }
1752    match crate::disk::free_bytes(repo) {
1753        Ok(free) => crate::disk::gate(free, min),
1754        Err(e) => Some(format!(
1755            "could not measure free space on {} ({e}); the disk gate refuses \
1756             to let a run start blind",
1757            repo.display()
1758        )),
1759    }
1760}
1761
1762/// How long to wait before offering another task when a run lost a seat to a
1763/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
1764/// could read, or carried nothing at all. Long enough that a quota outage
1765/// cannot burn through a whole backlog in the few seconds each doomed attempt
1766/// takes to fail; short enough that a quota which clears early is not left
1767/// idle for the fallback's sake.
1768const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
1769
1770/// Longest a parsed reset hint may push the wait out to. The hint comes from
1771/// the CLI's own words, not a contract, so a parsing slip that lands a day
1772/// away must not leave the loop asleep for a day.
1773const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
1774
1775/// How long [`poll`] should wait before offering the next task, after a run
1776/// lost at least one seat to a rate limit.
1777///
1778/// Pure and separate from the loop so the policy can be exercised without a
1779/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
1780/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
1781/// nothing to parse, or the parsed time has already passed; `cap` bounds how
1782/// far a parsed hint is trusted to push the wait out.
1783fn quota_wait(
1784    reset_at: Option<Timestamp>,
1785    now: Timestamp,
1786    fallback: Duration,
1787    cap: Duration,
1788) -> Duration {
1789    match reset_at {
1790        Some(at) if at > now => {
1791            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
1792            Duration::from_secs(secs).min(cap)
1793        }
1794        _ => fallback,
1795    }
1796}
1797
1798/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
1799///
1800/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
1801/// explains why parsing it exactly "would be a bug factory" — so this only
1802/// recognises the one shape actually observed in the wild, `"H:MMam/pm
1803/// (Zone)"`, and returns `None` for anything else rather than guess at a
1804/// format nobody has seen. A clock reading already past today is read as
1805/// tomorrow's: a CLI naming a same-day reset that has already gone by means
1806/// the window rolled over while nothing was watching.
1807fn parse_reset_hint(text: &str, now: Timestamp) -> Option<Timestamp> {
1808    let open = text.find('(')?;
1809    let close = text.rfind(')')?;
1810    if close <= open {
1811        return None;
1812    }
1813    let zone = text[open + 1..close].trim();
1814    let clock = text[..open].trim().to_lowercase();
1815    let (digits, pm) = clock
1816        .strip_suffix("am")
1817        .map(|d| (d, false))
1818        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
1819    let (h, m) = digits.trim().split_once(':')?;
1820    let mut hour: i8 = h.trim().parse().ok()?;
1821    let minute: i8 = m.trim().parse().ok()?;
1822    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
1823        return None;
1824    }
1825    if pm && hour != 12 {
1826        hour += 12;
1827    } else if !pm && hour == 12 {
1828        hour = 0;
1829    }
1830    let tz = jiff::tz::TimeZone::get(zone).ok()?;
1831    let candidate = now
1832        .to_zoned(tz)
1833        .with()
1834        .hour(hour)
1835        .minute(minute)
1836        .second(0)
1837        .millisecond(0)
1838        .microsecond(0)
1839        .nanosecond(0)
1840        .build()
1841        .ok()?;
1842    let mut at = candidate.timestamp();
1843    if at <= now {
1844        at += jiff::SignedDuration::from_hours(24);
1845    }
1846    Some(at)
1847}
1848
1849/// Resuming a `Blocked` run that already spent every review round its own
1850/// config allowed cannot make progress: `graph::Runner`'s review loop walks
1851/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
1852/// reached `max_rounds`, so `execute` would settle straight back to
1853/// `Blocked` without asking anyone anything. Read-only against a state this
1854/// build never mutates — `src/graph.rs` stays untouched — but without this
1855/// check, [`unfinished_run`] would keep reporting such a run as still
1856/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
1857/// promise is a fresh competition when a design needs to change) would
1858/// silently resume the exhausted run instead, spending an attempt on a
1859/// cycle that cannot change anything.
1860fn exhausted_review_budget(state: &RunState) -> bool {
1861    state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
1862}
1863
1864/// This task's *most recent* run, if resuming it would actually make
1865/// progress. `short` is only for the warning's own message.
1866///
1867/// Only ever `runs.last()` — never a search back through older history.
1868/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
1869/// mint, oldest first, and every entry before the last one was already
1870/// superseded at the moment it was minted: the daemon only ever starts a new
1871/// run when the previous one was not worth resuming (unresumable, exhausted,
1872/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
1873/// opens a fresh review-only run alongside an older, already-failed
1874/// competition. Searching further back would let an old run that merely
1875/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
1876/// behind, say — get resumed instead of the fresh competition
1877/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
1878/// nothing asked to revisit.
1879///
1880/// Two runs paid for the "prefer resuming over restarting" half of this
1881/// lesson, which is why this still checks `runs.last()` rather than always
1882/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
1883/// task a moment later, duplicating two and a half hours of agent work. Then
1884/// b25f stalled on a judge that timed out and one that answered with no JSON
1885/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
1886/// **one second** later, buying three fresh implementations to reach the
1887/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
1888/// the second case: a stall is terminal, and its cheap recovery re-asks only
1889/// the absent seats. [`exhausted_review_budget`] is the other half: a run
1890/// that is technically `resumable()` but provably cannot progress must not
1891/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
1892/// no-op instead of the fresh competition it promises.
1893///
1894/// A load failure is warned about rather than silently read as "not
1895/// resumable": the alternative is exactly what let a schema mismatch on run
1896/// `eba2` fall through to a full re-competition with nobody told why.
1897/// `crate::conduct` is what actually offers a better answer than
1898/// `Runner::start` here (see `Recovery::Review`), once this task's next
1899/// failure shows it up as `held`/`failed` with the run state unreadable.
1900fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
1901    unfinished_run_with(runs, short, RunState::load)
1902}
1903
1904/// [`unfinished_run`] with an injected state reader. Tests provide their
1905/// fixtures directly rather than touching the process-global run home.
1906fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
1907where
1908    F: FnOnce(&str) -> Result<RunState>,
1909{
1910    let id = runs.last()?;
1911    match load(id) {
1912        Ok(s) if s.status.resumable() && !exhausted_review_budget(&s) => Some(id.clone()),
1913        Ok(_) => None,
1914        Err(e) => {
1915            tracing::warn!("could not read run {id} for task {short}: {e:#}");
1916            None
1917        }
1918    }
1919}
1920
1921/// Which of the three ways [`attempt`] can mint or continue a run this task
1922/// should use.
1923#[derive(Debug, Clone, PartialEq, Eq)]
1924enum Starter {
1925    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
1926    /// and that still exists.
1927    Review(String),
1928    /// `crate::graph::Runner::resume` on an unfinished run of this task.
1929    Resume(String),
1930    /// `crate::graph::Runner::start`: a fresh competition.
1931    Start,
1932}
1933
1934/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
1935/// this attempt should use. Pure, and separate from [`attempt`], so the
1936/// routing itself is assertable without spawning a real graph or a git
1937/// process: `attempt`'s own `crate::git::branch_exists` call has already
1938/// happened by the time this is called.
1939///
1940/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
1941/// whose branch is gone falls all the way through to [`Starter::Start`], not
1942/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
1943/// old (likely `Blocked`) run in the first place, and a branch that vanished
1944/// out from under that choice is not evidence resuming it would fare better.
1945fn choose_starter(
1946    review_branch: Option<&str>,
1947    branch_exists: bool,
1948    unfinished: Option<&str>,
1949) -> Starter {
1950    match review_branch {
1951        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
1952        Some(_) => Starter::Start,
1953        None => match unfinished {
1954            Some(id) => Starter::Resume(id.to_owned()),
1955            None => Starter::Start,
1956        },
1957    }
1958}
1959
1960/// Which repository a task runs in. A task that names none — the normal case
1961/// for one filed from a phone — runs in the daemon's own default.
1962fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
1963    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
1964        return fallback.to_path_buf();
1965    }
1966    task.repo.clone()
1967}
1968
1969/// The header [`append_answers`] appends operator answers under. Shared with
1970/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
1971/// rather than grown a new block on every resume.
1972const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
1973
1974/// Render the first `count` answers in the block appended to an instruction.
1975fn answers_block(task: &Task, count: usize) -> String {
1976    let mut s = ANSWERS_HEADER.to_owned();
1977    for a in &task.answers[..count] {
1978        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
1979    }
1980    s
1981}
1982
1983/// Append every answer `crate::conduct` has collected for `task` onto `base`,
1984/// in the shape both [`instruction_for`] and [`resumed_instruction`] use.
1985fn append_answers(base: &str, task: &Task) -> String {
1986    if task.answers.is_empty() {
1987        return base.to_owned();
1988    }
1989    let mut s = base.to_owned();
1990    s.push_str(&answers_block(task, task.answers.len()));
1991    s
1992}
1993
1994/// Drop the prior answer block only when it is exactly the suffix this task
1995/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
1996/// the task author is ordinary instruction text, not a block to remove.
1997fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
1998    for count in (1..=task.answers.len()).rev() {
1999        let block = answers_block(task, count);
2000        if let Some(base) = instruction.strip_suffix(&block) {
2001            return base;
2002        }
2003    }
2004    instruction
2005}
2006
2007/// The instruction handed to `Runner::start`: the task's own text, plus any
2008/// operator answers `crate::conduct` collected for it (see
2009/// [`Task::answers`]), so a decision the operator actually made reaches the
2010/// implementers rather than only clearing the block that was waiting on it.
2011///
2012/// Appended rather than merged into [`Task::instruction`] itself, so the
2013/// task's own record stays exactly what its author wrote.
2014fn instruction_for(task: &Task) -> String {
2015    append_answers(&task.instruction, task)
2016}
2017
2018/// The instruction a resumed run should carry on with: whatever it already
2019/// had, refreshed with the task's *current* operator answers.
2020///
2021/// A resumable run's own `RunState::instruction` predates any answer
2022/// `crate::conduct` collects after the run parks, so resuming it unchanged —
2023/// the behaviour before this function existed — silently drops the very
2024/// decision the operator made to unblock it. Re-stripping any block this
2025/// function appended on an earlier resume before re-appending the current
2026/// list (rather than blindly appending again) is what keeps a task resumed
2027/// three times over three answered questions from carrying the same answer
2028/// three times.
2029fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
2030    append_answers(strip_answers_block(old_instruction, task), task)
2031}
2032
2033/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
2034/// answers before handing it to `Runner` — the actual boundary between
2035/// [`choose_starter`]'s routing and the graph, factored out so it is
2036/// assertable without a real repository, git branch, or agent CLI.
2037///
2038/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
2039/// instruction from the reviewed branch's own commit log because there is no
2040/// task statement to speak of for hand-written work, and splicing operator
2041/// answers into that text would contradict the very message it sends
2042/// reviewers ("there is no task statement").
2043fn prepare_instruction(
2044    starter: &Starter,
2045    old_instruction: Option<&str>,
2046    task: &Task,
2047) -> Option<String> {
2048    match starter {
2049        Starter::Start => Some(instruction_for(task)),
2050        Starter::Resume(_) => Some(resumed_instruction(
2051            old_instruction.expect("a resumed run always has a prior instruction"),
2052            task,
2053        )),
2054        Starter::Review(_) => None,
2055    }
2056}
2057
2058/// Persist a transition. A queue write failure is logged rather than fatal: the
2059/// run already happened, and taking the daemon down would only add a lost
2060/// backlog to a full disk.
2061fn record(queue: &Queue, task: &mut Task) {
2062    if let Err(e) = queue.put(task) {
2063        tracing::error!("could not record task {}: {e:#}", task.short());
2064    }
2065}
2066
2067/// Every runnable task, in the order the loop should try them.
2068///
2069/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
2070/// tail exists so that a claim somebody else holds costs the loop the next
2071/// candidate rather than a whole poll interval of idleness.
2072fn runnable(queue: &Queue) -> Vec<Task> {
2073    let mut tasks: Vec<Task> = queue
2074        .list()
2075        .into_iter()
2076        .filter(|t| t.status.runnable())
2077        .collect();
2078    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
2079    tasks
2080}
2081
2082/// Why a run ended where it did, in one line, for [`Task::last_error`].
2083///
2084/// A stalled run names the seats the quota took out: "out of quota" is not
2085/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
2086/// agent to replace or which plan to top up.
2087fn describe(state: &RunState) -> String {
2088    let mut detail = if state.status == RunStatus::Stalled {
2089        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
2090        seats.sort_unstable();
2091        seats.dedup();
2092        if seats.is_empty() {
2093            "the judging panel lost its quorum".to_owned()
2094        } else {
2095            format!(
2096                "the judging panel lost its quorum; quota took out {}",
2097                seats.join(", ")
2098            )
2099        }
2100    } else {
2101        format!("run ended {}", label(state.status))
2102    };
2103    if let Some(last) = state.events.last() {
2104        detail.push_str(&format!(" ({}: {})", last.node, last.message));
2105    }
2106    detail.push_str(&format!(" [run {}]", state.id));
2107    detail
2108}
2109
2110/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
2111///
2112/// The task file lives in the backlog indefinitely; a diagnostic is an
2113/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
2114/// stay small regardless of how much a gate command or a candidate printed.
2115const DIAGNOSTIC_MAX: usize = 4_000;
2116
2117/// Tail kept from a single failing command's output inside a diagnostic.
2118/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
2119/// pointer for a human deciding whether to go read the full artifact by hand,
2120/// not a replacement for reading it.
2121const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
2122
2123/// Assemble a bounded diagnostic excerpt from a held task's own run, so
2124/// `magi task show` says more than the one-line reason in [`describe`].
2125///
2126/// The one-liner answers "where did the run stop"; this answers "what would a
2127/// human have found opening `artifacts/` by hand" — the point of the whole
2128/// feature is the case that one-liner actively misleads on: a run held as "no
2129/// candidate produced a change" can mean the implementer actually finished
2130/// the task (opened a PR, merged it, tagged a release) and only left a clean
2131/// local worktree behind, which reads as "nothing happened" unless someone
2132/// goes and reads what the agent actually said. `None` when the run carries
2133/// none of the three shapes this recognises — an ordinary run held for
2134/// something not diagnosable from `RunState` alone still explains itself
2135/// through `Task::last_error`.
2136fn diagnostic(state: &RunState) -> Option<String> {
2137    let mut parts: Vec<String> = Vec::new();
2138
2139    // Gate failure: which check(s), and the tail of what each printed.
2140    for o in state.gate.iter().filter(|o| !o.ok()) {
2141        parts.push(format!(
2142            "gate `{}` failed ({:?}):\n{}",
2143            o.command,
2144            o.code,
2145            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
2146        ));
2147    }
2148
2149    // The land loop gave up because the fixer declined while checks were
2150    // still red: the message already names them (see `land::run`).
2151    if let Some(last) = state
2152        .events
2153        .iter()
2154        .rev()
2155        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
2156    {
2157        parts.push(last.message.clone());
2158    }
2159
2160    // No viable candidate: every implementer's own final word, sanitized the
2161    // same way a judge would have read it, so a run that actually finished
2162    // the job does not read as an unexplained failure.
2163    if state.viable().is_empty() {
2164        for c in &state.candidates {
2165            if !c.summary.trim().is_empty() {
2166                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
2167            } else if let Some(why) = &c.failed {
2168                parts.push(format!("candidate {}: {why}", c.label));
2169            }
2170        }
2171    }
2172
2173    if parts.is_empty() {
2174        return None;
2175    }
2176    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
2177    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
2178    // back slightly over. Leave it enough room to always land under the
2179    // limit.
2180    Some(crate::run::tail(
2181        &parts.join("\n\n"),
2182        DIAGNOSTIC_MAX.saturating_sub(100),
2183    ))
2184}
2185
2186/// Stable lower-case name for a run status, for logs and task errors.
2187/// One definition of a status's name, on the type that owns it: this table
2188/// used to live here as a second copy, and a status renamed in one place would
2189/// have gone on reading correctly in the other.
2190fn label(status: RunStatus) -> &'static str {
2191    status.as_str()
2192}
2193
2194/// Parse a merge mode override.
2195fn merge_mode(mode: &str) -> Result<MergeMode> {
2196    match mode {
2197        "none" => Ok(MergeMode::None),
2198        "local" => Ok(MergeMode::Local),
2199        "pr" => Ok(MergeMode::Pr),
2200        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
2201    }
2202}
2203
2204/// Take the status lock, recovering from a poisoned one.
2205///
2206/// A panic elsewhere must not silently stop the heartbeat: the status is plain
2207/// data, and the worst a poisoned lock can hold is a stale timestamp.
2208fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
2209    mutex
2210        .lock()
2211        .unwrap_or_else(std::sync::PoisonError::into_inner)
2212}
2213
2214#[cfg(test)]
2215mod tests {
2216    use super::*;
2217    use crate::queue::{Source, TaskStatus};
2218    use crate::run::{Candidate, CommandOutcome};
2219    use pretty_assertions::assert_eq;
2220
2221    fn task() -> Task {
2222        Task::new(
2223            "add retries".to_owned(),
2224            "add retries".to_owned(),
2225            PathBuf::from("/repo"),
2226            Source::Human,
2227        )
2228    }
2229
2230    #[test]
2231    fn every_run_status_settles_the_task_it_came_from() {
2232        // run status, resulting task status, attempts still standing after one
2233        let table = [
2234            (RunStatus::Merged, TaskStatus::Done, 1),
2235            (RunStatus::Ready, TaskStatus::Done, 1),
2236            (RunStatus::Stalled, TaskStatus::Failed, 0),
2237            (RunStatus::Blocked, TaskStatus::Failed, 1),
2238            (RunStatus::Failed, TaskStatus::Failed, 1),
2239            (RunStatus::Prep, TaskStatus::Failed, 1),
2240            (RunStatus::Implementing, TaskStatus::Failed, 1),
2241            (RunStatus::Judging, TaskStatus::Failed, 1),
2242            (RunStatus::Deliberating, TaskStatus::Failed, 1),
2243            (RunStatus::Voting, TaskStatus::Failed, 1),
2244            (RunStatus::Reviewing, TaskStatus::Failed, 1),
2245            (RunStatus::Gating, TaskStatus::Failed, 1),
2246        ];
2247        for (run, want, attempts) in table {
2248            let mut t = task();
2249            t.start("20260902-000000-aaaa".to_owned());
2250            settle(
2251                &mut t,
2252                Verdict {
2253                    status: run,
2254                    left_pr: false,
2255                    parked: false,
2256                    quota_hit: matches!(run, RunStatus::Stalled),
2257                    no_viable_candidates: false,
2258                },
2259                "why",
2260                2,
2261            );
2262            assert_eq!(t.status, want, "task status after {}", label(run));
2263            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
2264        }
2265    }
2266
2267    #[test]
2268    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
2269        let mut stalled = task();
2270        stalled.start("20260902-000000-aaaa".to_owned());
2271        settle(
2272            &mut stalled,
2273            Verdict {
2274                status: RunStatus::Stalled,
2275                left_pr: false,
2276                parked: false,
2277                quota_hit: true,
2278                no_viable_candidates: false,
2279            },
2280            "quota",
2281            1,
2282        );
2283        assert_eq!(stalled.attempts, 0);
2284        assert!(
2285            stalled.status.runnable(),
2286            "a machine problem must leave the task in line"
2287        );
2288
2289        let mut blocked = task();
2290        blocked.start("20260902-000000-aaaa".to_owned());
2291        settle(
2292            &mut blocked,
2293            Verdict {
2294                status: RunStatus::Blocked,
2295                left_pr: false,
2296                parked: false,
2297                quota_hit: false,
2298                no_viable_candidates: false,
2299            },
2300            "findings open",
2301            1,
2302        );
2303        assert_eq!(blocked.attempts, 1);
2304        assert_eq!(
2305            blocked.status,
2306            TaskStatus::Held,
2307            "the last attempt hands the task to a human"
2308        );
2309    }
2310
2311    #[test]
2312    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
2313        // Attempts to spare: without the pull request this task would go
2314        // straight back in line and run the whole competition again.
2315        let mut delivered = task();
2316        delivered.start("20260903-080619-01c2".to_owned());
2317        settle(
2318            &mut delivered,
2319            Verdict {
2320                status: RunStatus::Blocked,
2321                left_pr: true,
2322                parked: false,
2323                quota_hit: false,
2324                no_viable_candidates: false,
2325            },
2326            "no check status",
2327            4,
2328        );
2329        assert_eq!(
2330            delivered.status,
2331            TaskStatus::Held,
2332            "a pull request waiting on CI or a person is not a retryable failure"
2333        );
2334        assert!(
2335            !delivered.status.runnable(),
2336            "the loop must not pick this task up again"
2337        );
2338        assert_eq!(
2339            delivered.last_error.as_deref(),
2340            Some("no check status"),
2341            "the operator needs to be told what the gate was waiting for"
2342        );
2343
2344        // The same status without a pull request is a plain failure, and with
2345        // attempts left it is retried.
2346        let mut empty_handed = task();
2347        empty_handed.start("20260903-080619-01c2".to_owned());
2348        settle(
2349            &mut empty_handed,
2350            Verdict {
2351                status: RunStatus::Blocked,
2352                left_pr: false,
2353                parked: false,
2354                quota_hit: false,
2355                no_viable_candidates: false,
2356            },
2357            "findings open",
2358            4,
2359        );
2360        assert_eq!(empty_handed.status, TaskStatus::Failed);
2361        assert!(empty_handed.status.runnable());
2362    }
2363
2364    #[test]
2365    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
2366        // Parking is the operator asking for the process back - to replace the
2367        // binary, most of all. The run's work is intact on disk, so this is
2368        // not a failed attempt, and charging for it would mean a few upgrades
2369        // could exhaust a budget meant for agents that misbehaved.
2370        let mut parked = task();
2371        parked.start("20260903-183634-2d98".to_owned());
2372        settle(
2373            &mut parked,
2374            Verdict {
2375                status: RunStatus::Implementing,
2376                left_pr: false,
2377                quota_hit: false,
2378                parked: true,
2379                no_viable_candidates: false,
2380            },
2381            "parked after `implementing`",
2382            2,
2383        );
2384        assert_eq!(parked.attempts, 0, "a park is refunded");
2385        assert!(
2386            parked.status.runnable(),
2387            "and the task stays in line so the next loop resumes its run"
2388        );
2389        assert_eq!(
2390            parked.last_error.as_deref(),
2391            Some("parked after `implementing`"),
2392            "the card says where it stopped"
2393        );
2394
2395        // Without the park flag the same non-terminal status is what it always
2396        // was: `execute` returning mid-flight, which is a bug and spends an
2397        // attempt so a task cannot loop on it forever.
2398        let mut broken = task();
2399        broken.start("20260903-183634-2d98".to_owned());
2400        settle(
2401            &mut broken,
2402            Verdict {
2403                status: RunStatus::Implementing,
2404                left_pr: false,
2405                quota_hit: false,
2406                parked: false,
2407                no_viable_candidates: false,
2408            },
2409            "returned mid-flight",
2410            2,
2411        );
2412        assert_eq!(broken.attempts, 1);
2413    }
2414
2415    #[test]
2416    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
2417        // Run e633: quorum lost because two judges answered with the wrong
2418        // JSON shape, `quota: []`. Refunding that takes the bound off the
2419        // retry loop, and each retry pays for a fresh hour-long implement
2420        // wave before it can fail the same way.
2421        let mut flaky = task();
2422        flaky.start("20260903-123023-e633".to_owned());
2423        settle(
2424            &mut flaky,
2425            Verdict {
2426                status: RunStatus::Stalled,
2427                left_pr: false,
2428                parked: false,
2429                quota_hit: false,
2430                no_viable_candidates: false,
2431            },
2432            "verdict rests on 1 of 3 judges",
2433            2,
2434        );
2435        assert_eq!(
2436            flaky.attempts, 1,
2437            "flakiness spends an attempt, so `max_attempts` still bounds it"
2438        );
2439        assert!(flaky.status.runnable(), "and it is still worth retrying");
2440
2441        // The same status, lost to a rate limit, is the machine's fault.
2442        let mut limited = task();
2443        limited.start("20260903-123023-e633".to_owned());
2444        settle(
2445            &mut limited,
2446            Verdict {
2447                status: RunStatus::Stalled,
2448                left_pr: false,
2449                parked: false,
2450                quota_hit: true,
2451                no_viable_candidates: false,
2452            },
2453            "judge-2, judge-3 out of quota",
2454            2,
2455        );
2456        assert_eq!(limited.attempts, 0, "a quota window is refunded");
2457        assert!(limited.status.runnable());
2458
2459        // And the bound really binds: a task that keeps stalling on flakiness
2460        // reaches a human instead of running the roster forever.
2461        let mut worn = task();
2462        for _ in 0..2 {
2463            worn.release();
2464        }
2465        worn.start("20260903-123023-e633".to_owned());
2466        worn.attempts = 2;
2467        settle(
2468            &mut worn,
2469            Verdict {
2470                status: RunStatus::Stalled,
2471                left_pr: false,
2472                parked: false,
2473                quota_hit: false,
2474                no_viable_candidates: false,
2475            },
2476            "no quorum again",
2477            2,
2478        );
2479        assert_eq!(worn.status, TaskStatus::Held);
2480        assert!(!worn.status.runnable());
2481    }
2482
2483    #[test]
2484    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
2485        // The implement wave loses every seat to the same rate limit and
2486        // `after_implement` bails with nothing viable, which surfaces as
2487        // `Failed` rather than `Stalled`. That is the same machine fact the
2488        // `Stalled`-quota row already refunds, and must be refunded the same
2489        // way, or a quota outage quietly holds every task it touches instead
2490        // of leaving them in line for the reset.
2491        let mut wiped_out = task();
2492        wiped_out.start("20260907-025000-a1b2".to_owned());
2493        settle(
2494            &mut wiped_out,
2495            Verdict {
2496                status: RunStatus::Failed,
2497                left_pr: false,
2498                parked: false,
2499                quota_hit: true,
2500                no_viable_candidates: true,
2501            },
2502            "no candidate produced a change; nothing to judge",
2503            2,
2504        );
2505        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
2506        assert!(
2507            wiped_out.status.runnable(),
2508            "a machine problem must leave the task in line"
2509        );
2510
2511        // This is the exemption that must stay narrow: a candidate that did
2512        // produce a change, and then failed for some other reason, still
2513        // spends the attempt even though a seat elsewhere hit its quota.
2514        // Otherwise every ordinary failure that happens to share a run with
2515        // an unrelated rate limit would be refunded for free.
2516        let mut partial_progress = task();
2517        partial_progress.start("20260907-025500-c3d4".to_owned());
2518        settle(
2519            &mut partial_progress,
2520            Verdict {
2521                status: RunStatus::Failed,
2522                left_pr: false,
2523                parked: false,
2524                quota_hit: true,
2525                no_viable_candidates: false,
2526            },
2527            "gate failed on the winning candidate",
2528            2,
2529        );
2530        assert_eq!(
2531            partial_progress.attempts, 1,
2532            "a candidate that actually produced a change spends the attempt \
2533             even though some other seat hit its quota"
2534        );
2535        assert!(partial_progress.status.runnable());
2536    }
2537
2538    #[test]
2539    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
2540        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
2541        // disk, and that construction must reach the same conclusion as the
2542        // one `attempt` builds from a live run, or a crash at exactly the
2543        // wrong moment gives a recovered task a different policy than one a
2544        // daemon finished settling itself.
2545        let mut t = task();
2546        t.start("20260907-025000-a1b2".to_owned());
2547        let mut state = run_state(RunStatus::Failed);
2548        state.quota.push(QuotaLoss {
2549            seat: "cand-a".to_owned(),
2550            node: "implement".to_owned(),
2551            at: Timestamp::now(),
2552            reset: None,
2553        });
2554        assert!(
2555            state.viable().is_empty(),
2556            "no candidate was added, so nothing is viable"
2557        );
2558        reclaim(&mut t, Some(state), 2);
2559        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
2560        assert!(t.status.runnable());
2561    }
2562
2563    #[test]
2564    fn a_held_task_is_never_offered_to_the_loop() {
2565        let dir = tempfile::tempdir().unwrap();
2566        let queue = Queue::at(dir.path().to_path_buf());
2567        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
2568            let mut t = task();
2569            t.id = format!("2026090{n}-000000-000{n}");
2570            t.priority = priority;
2571            queue.put(&mut t).unwrap();
2572        }
2573        let mut held = task();
2574        held.id = "20260909-000000-9999".to_owned();
2575        held.priority = 99;
2576        held.hold(None);
2577        queue.put(&mut held).unwrap();
2578
2579        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
2580        assert_eq!(order.len(), 3);
2581        assert!(!order.contains(&held.id));
2582        assert_eq!(
2583            order.first().cloned(),
2584            queue.next_runnable().map(|t| t.id),
2585            "the loop's first candidate is exactly what the queue offers"
2586        );
2587        assert_eq!(
2588            order,
2589            vec![
2590                "20260902-000000-0002".to_owned(),
2591                "20260903-000000-0003".to_owned(),
2592                "20260901-000000-0001".to_owned(),
2593            ],
2594            "priority first, then oldest, so nothing starves"
2595        );
2596    }
2597
2598    #[test]
2599    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
2600        let dir = tempfile::tempdir().unwrap();
2601        let queue = Queue::at(dir.path().to_path_buf());
2602        let mut old = task();
2603        old.id = "20260101-000000-old0".to_owned();
2604        queue.put(&mut old).unwrap();
2605        let mut fresh = task();
2606        fresh.id = "20260101-000000-new0".to_owned();
2607        queue.put(&mut fresh).unwrap();
2608
2609        // No parseable pid at all, so age is the only signal there is to
2610        // check - unlike a real `Queue::claim`, which always names a real,
2611        // and therefore alive, pid this test cannot fake as dead.
2612        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
2613        std::thread::sleep(Duration::from_millis(60));
2614        let live = queue.claim(&fresh.id).unwrap();
2615
2616        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
2617        assert_eq!(swept, vec![old.id.clone()]);
2618        assert!(
2619            queue.claim(&old.id).is_ok(),
2620            "an unparseable lock older than the threshold is swept"
2621        );
2622        assert!(
2623            queue.claim(&fresh.id).is_err(),
2624            "a live pid protects its lock regardless of age"
2625        );
2626        drop(live);
2627    }
2628
2629    #[test]
2630    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
2631        // The regression this guards: `sweep` now runs concurrently with
2632        // every attempt this daemon itself has spawned (see
2633        // `InFlightGuard`), not only between them the way a single
2634        // sequential loop once did. A run that legitimately outlives
2635        // `older_than` still has this very process's own live pid sitting in
2636        // its own lock file on every later sweep, and deciding by age alone
2637        // would delete that still-valid claim out from under the attempt
2638        // that holds it - which `reclaim_orphaned_running` would then read
2639        // as abandoned and hand to a second, competing attempt.
2640        let dir = tempfile::tempdir().unwrap();
2641        let queue = Queue::at(dir.path().to_path_buf());
2642        let mut t = task();
2643        t.id = "20260101-000000-live".to_owned();
2644        queue.put(&mut t).unwrap();
2645
2646        let claim = queue.claim(&t.id).unwrap();
2647        std::thread::sleep(Duration::from_millis(60));
2648
2649        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
2650        assert!(
2651            swept.is_empty(),
2652            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
2653        );
2654        assert!(
2655            queue.claim(&t.id).is_err(),
2656            "the lock still protects its task"
2657        );
2658        drop(claim);
2659    }
2660
2661    /// A pid past any real process table, but not `u32::MAX`: Windows'
2662    /// `tasklist` answers that one with "invalid query" rather than "no such
2663    /// process", which [`crate::proc::pid_alive`] - correctly - cannot tell
2664    /// apart from a check it simply could not run, so it would read as
2665    /// alive. See `proc::tests` for the same choice made for the same
2666    /// reason.
2667    const DEAD_PID: u32 = 999_999_999;
2668
2669    #[test]
2670    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
2671        let dir = tempfile::tempdir().unwrap();
2672        let queue = Queue::at(dir.path().to_path_buf());
2673        let mut t = task();
2674        t.id = "20260101-000000-dead".to_owned();
2675        queue.put(&mut t).unwrap();
2676
2677        // Written directly rather than through `Queue::claim`, which would
2678        // stamp this test process's own very much alive pid and defeat the
2679        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
2680        // like moments after it died, not six hours later.
2681        std::fs::write(
2682            dir.path().join(format!("{}.lock", t.id)),
2683            DEAD_PID.to_string(),
2684        )
2685        .unwrap();
2686
2687        let swept = sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60));
2688        assert_eq!(
2689            swept,
2690            vec![t.id.clone()],
2691            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
2692        );
2693        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
2694    }
2695
2696    #[test]
2697    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
2698        let dir = tempfile::tempdir().unwrap();
2699        let queue = Queue::at(dir.path().to_path_buf());
2700        let mut t = task();
2701        t.id = "20260101-000000-late".to_owned();
2702        queue.put(&mut t).unwrap();
2703
2704        // Tick one, standing in for the sweep `poll` already runs at
2705        // startup: nothing to find yet.
2706        assert!(
2707            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
2708            "nothing has claimed the task yet"
2709        );
2710
2711        // A second daemon claims the task and dies before it ever writes
2712        // `running`, well after this loop's own startup sweep already ran.
2713        std::fs::write(
2714            dir.path().join(format!("{}.lock", t.id)),
2715            DEAD_PID.to_string(),
2716        )
2717        .unwrap();
2718
2719        // Tick two, standing in for a poll long into this daemon's uptime:
2720        // the same function, called again, notices what only just appeared -
2721        // proving the sweep is not a one-shot startup check.
2722        let swept = sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60));
2723        assert_eq!(swept, vec![t.id.clone()]);
2724    }
2725
2726    #[test]
2727    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
2728        // `reclaim_orphaned_running` looks up the task's last run, which
2729        // touches `run::home()`; the first call anywhere in this binary wins,
2730        // so this is a no-op if another test already pinned one, and either
2731        // way the run id below is never written under it.
2732        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2733        let dir = tempfile::tempdir().unwrap();
2734        let queue = Queue::at(dir.path().to_path_buf());
2735        let mut t = task();
2736        t.id = "20260101-000000-crsh".to_owned();
2737        t.status = TaskStatus::Running;
2738        t.attempts = 1;
2739        // No `run.json` behind this id: standing in for a run this test does
2740        // not need to make readable, since the point is the lock, not the
2741        // recovery table `reclaim` already has its own tests for.
2742        t.runs.push("20260904-000000-4043".to_owned());
2743        queue.put(&mut t).unwrap();
2744
2745        // The crashed daemon's own claim, naming a pid nothing on the
2746        // machine holds anymore.
2747        std::fs::write(
2748            dir.path().join(format!("{}.lock", t.id)),
2749            DEAD_PID.to_string(),
2750        )
2751        .unwrap();
2752
2753        // Before the lock is swept the task looks claimed, and
2754        // `reclaim_orphaned_running` must leave it alone - this is exactly
2755        // the bug: a `running` task stranded behind a dead daemon's lock,
2756        // invisible to the claim-as-proof check because the lock outlived
2757        // the process that wrote it.
2758        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
2759        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
2760
2761        let swept = sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60));
2762        assert_eq!(swept, vec![t.id.clone()]);
2763
2764        let reclaimed = reclaim_orphaned_running(&queue, 2);
2765        assert_eq!(reclaimed, vec![t.id.clone()]);
2766        let after = queue.get(&t.id).unwrap();
2767        assert_eq!(
2768            after.status,
2769            TaskStatus::Held,
2770            "no run.json to recover from, so a human is asked"
2771        );
2772        assert_eq!(
2773            after.runs,
2774            vec!["20260904-000000-4043".to_owned()],
2775            "the crashed run's id is kept as evidence, not discarded"
2776        );
2777    }
2778
2779    fn run_state(status: RunStatus) -> RunState {
2780        let mut state = RunState::new(
2781            PathBuf::from("/repo"),
2782            "main".to_owned(),
2783            "abc1234def".to_owned(),
2784            "add retries".to_owned(),
2785            Config::default(),
2786        );
2787        state.status = status;
2788        state
2789    }
2790
2791    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
2792        Candidate {
2793            index: 0,
2794            label,
2795            agent: "claude".to_owned(),
2796            branch: format!("magi/x/{label}"),
2797            worktree: PathBuf::from("/repo"),
2798            summary: summary.to_owned(),
2799            stat: String::new(),
2800            files: 0,
2801            commits: usize::from(!empty),
2802            empty,
2803            failed: failed.map(str::to_owned),
2804            duration_ms: 0,
2805            folded: false,
2806        }
2807    }
2808
2809    #[test]
2810    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
2811        let mut state = run_state(RunStatus::Blocked);
2812        state.gate = vec![
2813            CommandOutcome {
2814                command: "cargo make check".to_owned(),
2815                code: Some(0),
2816                output_tail: "ok".to_owned(),
2817                duration_ms: 0,
2818            },
2819            CommandOutcome {
2820                command: "cargo test".to_owned(),
2821                code: Some(101),
2822                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
2823                duration_ms: 0,
2824            },
2825        ];
2826        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
2827        assert!(d.contains("cargo test"), "{d}");
2828        assert!(
2829            !d.contains("cargo make check"),
2830            "a passing check is not a diagnostic: {d}"
2831        );
2832        assert!(d.contains("assertion failed"), "{d}");
2833    }
2834
2835    #[test]
2836    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
2837        let mut state = run_state(RunStatus::Blocked);
2838        state.event(
2839            "land",
2840            "stopped: the fixer produced no commit while 2 check(s) were failing \
2841             (build, lint); stopping instead of looping on an unchanged tree",
2842        );
2843        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
2844        assert!(d.contains("build"), "{d}");
2845        assert!(d.contains("lint"), "{d}");
2846        assert!(d.contains("fixer produced no commit"), "{d}");
2847    }
2848
2849    #[test]
2850    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
2851        // The whole point of the feature: a run held as "no candidate produced
2852        // a change" can mean the implementer actually finished the task and
2853        // only left a clean local tree behind - see AGENTS.md on this exact
2854        // failure mode. The diagnostic has to carry what the agent actually
2855        // said, not just the fact that nothing was there to judge.
2856        let mut state = run_state(RunStatus::Failed);
2857        state.candidates = vec![candidate(
2858            'A',
2859            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
2860            true,
2861            None,
2862        )];
2863        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
2864        assert!(d.contains("candidate A"), "{d}");
2865        assert!(d.contains("tagged v1.2.3"), "{d}");
2866    }
2867
2868    #[test]
2869    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
2870        let mut state = run_state(RunStatus::Failed);
2871        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
2872        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
2873        assert!(d.contains("candidate A"), "{d}");
2874        assert!(d.contains("agent timed out"), "{d}");
2875    }
2876
2877    #[test]
2878    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
2879        // A viable candidate existed, the gate never ran, and nothing land
2880        // said matches - `Task::last_error` is left to explain this one alone.
2881        let mut state = run_state(RunStatus::Failed);
2882        state.candidates = vec![candidate('A', "did the work", false, None)];
2883        assert!(diagnostic(&state).is_none());
2884    }
2885
2886    #[test]
2887    fn diagnostic_is_bounded_however_much_a_run_printed() {
2888        let mut state = run_state(RunStatus::Blocked);
2889        state.gate = vec![
2890            CommandOutcome {
2891                command: "cargo test".to_owned(),
2892                code: Some(101),
2893                output_tail: "x".repeat(50_000),
2894                duration_ms: 0,
2895            },
2896            CommandOutcome {
2897                command: "cargo clippy".to_owned(),
2898                code: Some(1),
2899                output_tail: "y".repeat(50_000),
2900                duration_ms: 0,
2901            },
2902        ];
2903        state.candidates = vec![
2904            candidate('A', &"z".repeat(50_000), true, None),
2905            candidate('B', &"w".repeat(50_000), true, None),
2906        ];
2907        let d = diagnostic(&state).expect("plenty here to diagnose");
2908        assert!(
2909            d.len() <= DIAGNOSTIC_MAX,
2910            "diagnostic grew to {} bytes, unbounded",
2911            d.len()
2912        );
2913    }
2914
2915    #[test]
2916    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
2917        let mut state = run_state(RunStatus::Blocked);
2918        state.gate = vec![CommandOutcome {
2919            command: "cargo test".to_owned(),
2920            code: Some(101),
2921            output_tail: "assertion failed".to_owned(),
2922            duration_ms: 0,
2923        }];
2924        let verdict = Verdict {
2925            status: RunStatus::Blocked,
2926            left_pr: false,
2927            quota_hit: false,
2928            parked: false,
2929            no_viable_candidates: false,
2930        };
2931
2932        // Attempt one of two still has a retry coming: no diagnostic yet, the
2933        // task is going to run again and this run's evidence would go stale.
2934        let mut t = task();
2935        t.start("run-1".to_owned());
2936        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
2937        assert_eq!(t.status, TaskStatus::Failed);
2938        assert!(t.diagnostic.is_none());
2939
2940        // Attempt two exhausts the budget: now it is held, and the
2941        // diagnostic is what `magi task show` has to say more than one line.
2942        t.start("run-2".to_owned());
2943        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
2944        assert_eq!(t.status, TaskStatus::Held);
2945        let d = t.diagnostic.expect("a held task must carry its diagnostic");
2946        assert!(d.contains("cargo test"), "{d}");
2947    }
2948
2949    fn approval_question(run: &str) -> ask::Question {
2950        ask::Question::new(
2951            run.to_owned(),
2952            land::APPROVAL_NODE.to_owned(),
2953            "land".to_owned(),
2954            "merge?".to_owned(),
2955            String::new(),
2956            vec!["merge".to_owned(), "hold".to_owned()],
2957        )
2958    }
2959
2960    #[test]
2961    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
2962        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2963        let mut state = run_state(RunStatus::Landing);
2964        state.id = "20260101-000000-fre1".to_owned();
2965        state.parked = true;
2966        state.save().unwrap();
2967        ask::Questions::open()
2968            .put(&mut approval_question(&state.id))
2969            .unwrap();
2970
2971        let mut t = task();
2972        t.runs.push(state.id.clone());
2973        assert_eq!(
2974            land_resume_state(&t),
2975            LandResume::StillWaiting,
2976            "nobody has answered and the timeout has not passed"
2977        );
2978    }
2979
2980    #[test]
2981    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
2982        // `ask::ask_and_wait`'s own deadline used to retire a question
2983        // nobody answered; land's approval bypasses that wait (see
2984        // `land::approval_gate`), so this is now the only place
2985        // `graph.answer_timeout` is enforced for a land approval at all.
2986        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
2987        let mut state = run_state(RunStatus::Landing);
2988        state.id = "20260101-000000-exp1".to_owned();
2989        state.parked = true;
2990        state.config.graph.answer_timeout = 60;
2991        state.save().unwrap();
2992
2993        let store = ask::Questions::open();
2994        let mut q = approval_question(&state.id);
2995        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
2996        store.put(&mut q).unwrap();
2997
2998        let mut t = task();
2999        t.runs.push(state.id.clone());
3000        assert_eq!(
3001            land_resume_state(&t),
3002            LandResume::Ready,
3003            "an expired question must not be waited on forever"
3004        );
3005
3006        let after = store.get(&q.id).unwrap();
3007        assert!(
3008            !after.status.open(),
3009            "the question is abandoned, not silently ignored"
3010        );
3011        assert!(
3012            after.resolution().is_none(),
3013            "an abandoned question is not read as a decision"
3014        );
3015    }
3016
3017    #[test]
3018    fn reclaim_settles_a_running_task_against_its_last_run() {
3019        let mut t = task();
3020        t.start("20260904-000000-4043".to_owned());
3021        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
3022        assert_eq!(
3023            t.status,
3024            TaskStatus::Done,
3025            "a run that actually finished must not stay `running` forever"
3026        );
3027    }
3028
3029    #[test]
3030    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
3031        // A blocked run with attempts left goes back to `Failed`, exactly as
3032        // it would from `attempt` itself - `reclaim` must not invent a second
3033        // policy for a task a daemon merely stopped without reporting.
3034        let mut t = task();
3035        t.start("20260904-000000-4043".to_owned());
3036        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
3037        assert_eq!(t.status, TaskStatus::Failed);
3038        assert!(t.status.runnable());
3039    }
3040
3041    #[test]
3042    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
3043        let mut t = task();
3044        t.start("20260904-000000-4043".to_owned());
3045        reclaim(&mut t, None, 2);
3046        assert_eq!(t.status, TaskStatus::Held);
3047        assert!(
3048            t.last_error
3049                .as_deref()
3050                .is_some_and(|e| e.contains("running")),
3051            "the operator needs to know why this task was held"
3052        );
3053    }
3054
3055    #[test]
3056    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
3057        let dir = tempfile::tempdir().unwrap();
3058        let queue = Queue::at(dir.path().to_path_buf());
3059
3060        // No run recorded, so this never has to touch `RunState::load`.
3061        let mut orphaned = task();
3062        orphaned.id = "20260904-000000-orph".to_owned();
3063        orphaned.status = TaskStatus::Running;
3064        orphaned.attempts = 1;
3065        queue.put(&mut orphaned).unwrap();
3066
3067        let mut alive = task();
3068        alive.id = "20260904-000000-live".to_owned();
3069        alive.status = TaskStatus::Running;
3070        alive.attempts = 1;
3071        queue.put(&mut alive).unwrap();
3072        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
3073
3074        let mut queued = task();
3075        queued.id = "20260904-000000-wait".to_owned();
3076        queue.put(&mut queued).unwrap();
3077
3078        let reclaimed = reclaim_orphaned_running(&queue, 2);
3079        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
3080
3081        assert_eq!(
3082            queue.get(&orphaned.id).unwrap().status,
3083            TaskStatus::Held,
3084            "nothing was driving it and there was no run to recover"
3085        );
3086        assert_eq!(
3087            queue.get(&alive.id).unwrap().status,
3088            TaskStatus::Running,
3089            "a live claim must protect the task it belongs to"
3090        );
3091        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
3092    }
3093
3094    #[test]
3095    fn an_already_claimed_task_is_skipped_rather_than_failed() {
3096        let dir = tempfile::tempdir().unwrap();
3097        let queue = Queue::at(dir.path().to_path_buf());
3098        let mut only = task();
3099        queue.put(&mut only).unwrap();
3100
3101        let _elsewhere = queue.claim(&only.id).unwrap();
3102        let candidates = runnable(&queue);
3103        assert_eq!(candidates.len(), 1, "the task is still runnable");
3104        assert!(
3105            queue.claim(&candidates[0].id).is_err(),
3106            "the loop cannot take a claim somebody else holds"
3107        );
3108
3109        let after = queue.get(&only.id).unwrap();
3110        assert_eq!(after.status, TaskStatus::Queued);
3111        assert_eq!(
3112            after.attempts, 0,
3113            "losing the race is not an attempt at the task"
3114        );
3115        assert_eq!(after.last_error, None);
3116    }
3117
3118    #[test]
3119    fn the_status_file_round_trips_and_its_heartbeat_advances() {
3120        let dir = tempfile::tempdir().unwrap();
3121        let path = dir.path().join("daemon.json");
3122
3123        let mut status = Status::new();
3124        status.idle = false;
3125        status.completed = 7;
3126        status.current = vec![Current {
3127            task: "20260902-000000-t111".to_owned(),
3128            run: "20260902-000001-r111".to_owned(),
3129        }];
3130        write_status_to(&path, &status).unwrap();
3131        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3132        assert_eq!(first.schema, SCHEMA);
3133        assert_eq!(first.pid, std::process::id());
3134        assert!(!first.idle);
3135        assert_eq!(first.completed, 7);
3136        assert_eq!(first.current, status.current);
3137        assert!(
3138            !path.with_extension("json.tmp").exists(),
3139            "the temp file is renamed, not left behind"
3140        );
3141
3142        std::thread::sleep(Duration::from_millis(5));
3143        status.updated_at = Timestamp::now();
3144        status.polls = 3;
3145        write_status_to(&path, &status).unwrap();
3146        let second: Status =
3147            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3148        assert!(
3149            second.updated_at > first.updated_at,
3150            "a reader can only detect staleness if the heartbeat moves"
3151        );
3152        assert_eq!(
3153            second.started_at, first.started_at,
3154            "the start time is not a heartbeat"
3155        );
3156        assert_eq!(second.polls, 3);
3157    }
3158
3159    #[test]
3160    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
3161        let dir = tempfile::tempdir().unwrap();
3162
3163        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
3164
3165        let mut status = Status::new();
3166        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
3167        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3168        let stale = read_status(dir.path()).unwrap();
3169        assert!(
3170            !stale.running(Timestamp::now()),
3171            "a minute without a heartbeat is a dead daemon, not a busy one"
3172        );
3173        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
3174
3175        status.updated_at = Timestamp::now();
3176        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3177        let fresh = read_status(dir.path()).unwrap();
3178        assert!(fresh.running(Timestamp::now()));
3179    }
3180
3181    #[test]
3182    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
3183        let dir = tempfile::tempdir().unwrap();
3184        let now = Timestamp::now();
3185        let mine = "20260903-080619-01c2";
3186
3187        assert!(
3188            !is_working_on(dir.path(), mine, now),
3189            "no status file means nobody is working on anything"
3190        );
3191
3192        let mut status = Status::new();
3193        status.current = vec![Current {
3194            task: "20260903-080340-0167".to_owned(),
3195            run: mine.to_owned(),
3196        }];
3197        status.updated_at = now;
3198        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3199        assert!(is_working_on(dir.path(), mine, now));
3200        assert!(
3201            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
3202            "a daemon busy with one run is not working on another"
3203        );
3204
3205        // A killed daemon stops writing heartbeats but leaves the file behind
3206        // naming the run it died in. That run must not be undeletable forever.
3207        status.updated_at = now - jiff::SignedDuration::from_secs(600);
3208        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3209        assert!(
3210            !is_working_on(dir.path(), mine, now),
3211            "a stale heartbeat is a dead daemon, so its run is a leftover"
3212        );
3213    }
3214
3215    #[test]
3216    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
3217        let dir = tempfile::tempdir().unwrap();
3218        let now = Timestamp::now();
3219
3220        assert!(
3221            !is_working_on_short(dir.path(), "01c2", now),
3222            "no status file means nobody is working on anything"
3223        );
3224
3225        let mut status = Status::new();
3226        status.current = vec![Current {
3227            task: "20260903-080340-0167".to_owned(),
3228            run: "20260903-080619-01c2".to_owned(),
3229        }];
3230        status.updated_at = now;
3231        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3232        assert!(
3233            is_working_on_short(dir.path(), "01c2", now),
3234            "the run's short id is the last block of its full id"
3235        );
3236        assert!(
3237            !is_working_on_short(dir.path(), "3cbf", now),
3238            "a daemon busy with one worktree bay is not working on another"
3239        );
3240    }
3241
3242    #[test]
3243    fn a_newer_status_file_still_yields_a_reading() {
3244        let dir = tempfile::tempdir().unwrap();
3245        // A field this build has never heard of must not turn the reading into
3246        // nothing at all; that is the whole reason the reader is permissive.
3247        std::fs::write(
3248            dir.path().join("daemon.json"),
3249            serde_json::json!({
3250                "schema": 2,
3251                "updated_at": Timestamp::now().to_string(),
3252                "idle": true,
3253                "surprise": { "nested": [1, 2, 3] },
3254            })
3255            .to_string(),
3256        )
3257        .unwrap();
3258
3259        let reading = read_status(dir.path()).expect("a forward-compatible read");
3260        assert!(reading.running(Timestamp::now()));
3261        assert!(reading.idle);
3262        assert!(reading.current.is_empty());
3263    }
3264
3265    #[test]
3266    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
3267        // A daemon started before `current` became a list keeps writing this
3268        // shape on every heartbeat until it is restarted. A rolling upgrade
3269        // - a newer `magi web` or `magi doctor` reading an older `magi
3270        // serve`'s heartbeat - must still see the run it is on, not "no
3271        // daemon" from a type mismatch failing the whole struct.
3272        let dir = tempfile::tempdir().unwrap();
3273        std::fs::write(
3274            dir.path().join("daemon.json"),
3275            serde_json::json!({
3276                "schema": 1,
3277                "pid": 4242,
3278                "updated_at": Timestamp::now().to_string(),
3279                "idle": false,
3280                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
3281                "completed": 3,
3282                "polls": 9,
3283            })
3284            .to_string(),
3285        )
3286        .unwrap();
3287
3288        let reading = read_status(dir.path()).expect("an older shape must still parse");
3289        assert!(reading.running(Timestamp::now()));
3290        assert_eq!(
3291            reading.current,
3292            vec![Current {
3293                task: "20260902-140501-aaaa".to_owned(),
3294                run: "20260902-140502-bbbb".to_owned(),
3295            }]
3296        );
3297    }
3298
3299    #[test]
3300    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
3301        let dir = tempfile::tempdir().unwrap();
3302        std::fs::write(
3303            dir.path().join("daemon.json"),
3304            serde_json::json!({
3305                "schema": 1,
3306                "updated_at": Timestamp::now().to_string(),
3307                "idle": true,
3308                "current": null,
3309            })
3310            .to_string(),
3311        )
3312        .unwrap();
3313        let with_null = read_status(dir.path()).expect("null must still parse");
3314        assert!(with_null.current.is_empty());
3315
3316        std::fs::write(
3317            dir.path().join("daemon.json"),
3318            serde_json::json!({
3319                "schema": 1,
3320                "updated_at": Timestamp::now().to_string(),
3321                "idle": true,
3322            })
3323            .to_string(),
3324        )
3325        .unwrap();
3326        let absent = read_status(dir.path()).expect("a missing field must still parse");
3327        assert!(absent.current.is_empty());
3328    }
3329
3330    #[test]
3331    fn a_task_without_a_repository_runs_in_the_daemons_default() {
3332        let fallback = Path::new("/default");
3333        let mut blank = task();
3334        blank.repo = PathBuf::new();
3335        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
3336        let mut dot = task();
3337        dot.repo = PathBuf::from(".");
3338        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
3339        assert_eq!(
3340            repo_for(&task(), fallback),
3341            PathBuf::from("/repo"),
3342            "a task that names a repository keeps it"
3343        );
3344    }
3345
3346    #[test]
3347    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
3348        // Three seats said out loud. What `solo` promises is one candidate
3349        // *whatever the config asks for*, so the contrast has to be a number
3350        // this test owns - it used to be `Config::default()`'s, which became
3351        // 1 when one implementation became the default and left the two
3352        // halves of this test asserting the same thing.
3353        let mut solo_cfg = Config::default();
3354        solo_cfg.graph.candidates = 3;
3355        let mut solo_task = task();
3356        solo_task.solo = true;
3357        apply_solo(&mut solo_cfg, &solo_task);
3358        assert_eq!(solo_cfg.graph.candidates, 1);
3359
3360        let mut plain_cfg = Config::default();
3361        plain_cfg.graph.candidates = 3;
3362        let plain_task = task();
3363        assert!(!plain_task.solo);
3364        apply_solo(&mut plain_cfg, &plain_task);
3365        assert_eq!(
3366            plain_cfg.graph.candidates, 3,
3367            "a task that did not ask to run alone keeps the config's candidates"
3368        );
3369    }
3370
3371    #[test]
3372    fn merge_overrides_are_parsed_or_refused() {
3373        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
3374        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
3375        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
3376        assert!(merge_mode("squash").is_err());
3377    }
3378
3379    #[test]
3380    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
3381        let now = Timestamp::now();
3382        let fallback = Duration::from_secs(300);
3383        let cap = Duration::from_secs(1800);
3384
3385        // No reset hint at all: the fallback.
3386        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
3387
3388        // A reset ten minutes out, well inside the cap: waited for exactly.
3389        let soon = now + jiff::SignedDuration::from_secs(600);
3390        assert_eq!(
3391            quota_wait(Some(soon), now, fallback, cap),
3392            Duration::from_secs(600)
3393        );
3394
3395        // A reset already in the past is not trusted: the fallback, not a
3396        // zero or negative wait that would spin the loop right back around.
3397        let past = now - jiff::SignedDuration::from_secs(60);
3398        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
3399
3400        // A reset further out than the cap is trusted for direction but not
3401        // for magnitude: a parsing slip must not sleep the loop for a day.
3402        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
3403        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
3404    }
3405
3406    #[test]
3407    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
3408        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
3409
3410        let at = parse_reset_hint("4:50am (UTC)", now).expect("a recognised shape parses");
3411        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
3412
3413        // Same clock reading, but it has already gone by today: read as
3414        // tomorrow's, since the CLI would not still be reporting a limit past
3415        // its own stated reset.
3416        let already_past =
3417            parse_reset_hint("1:00am (UTC)", now).expect("a recognised shape parses");
3418        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
3419
3420        assert!(
3421            parse_reset_hint("session limit reached", now).is_none(),
3422            "free text with no recognised shape is not guessed at"
3423        );
3424        assert!(
3425            parse_reset_hint("4:50am (Nowhere/Fake)", now).is_none(),
3426            "an unresolvable zone name is not guessed at either"
3427        );
3428    }
3429
3430    /// A loop whose queue lives in a temp tree and whose poll interval is far
3431    /// longer than the test's patience, so anything that waits out a poll
3432    /// instead of noticing the stop fails rather than merely being slow.
3433    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
3434        let config = dir.join("magi.toml");
3435        std::fs::write(
3436            &config,
3437            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
3438        )
3439        .unwrap();
3440        let opts = Opts {
3441            poll: Duration::from_secs(30),
3442            config: Some(config),
3443            // The explicit fixture config keeps startup cleanup from reading
3444            // machine configuration. This fictional repository likewise
3445            // keeps any best-effort git cleanup away from this checkout.
3446            repo: dir.join("repo"),
3447            ..Opts::default()
3448        };
3449        // The status file goes in a directory that does not exist yet, so its
3450        // creation is itself evidence the loop published one. `worktrees`
3451        // must be just as fictional: the janitor reclaims worktrees under it
3452        // for real, and a test that let it fall through to
3453        // `crate::run::default_worktree_root()` would have it reclaim
3454        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
3455        // which is exactly what happened before this function took the
3456        // parameter at all.
3457        let home = dir.join("home");
3458        let worktrees = dir.join("wt");
3459        (
3460            opts,
3461            Queue::at(dir.join("queue")),
3462            home.join("daemon.json"),
3463            home,
3464            worktrees,
3465        )
3466    }
3467
3468    #[test]
3469    fn a_stop_is_idempotent_and_once_set_stays_set() {
3470        let stop = Stop::new();
3471        assert!(!stop.stopped());
3472
3473        stop.stop();
3474        assert!(stop.stopped());
3475        stop.stop();
3476        assert!(stop.stopped(), "a second stop is not a toggle");
3477
3478        let shared = stop.clone();
3479        assert!(
3480            shared.stopped(),
3481            "a clone is the same stop; that is how the loop and its caller share one"
3482        );
3483    }
3484
3485    #[test]
3486    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
3487        let stop = Stop::new();
3488        stop.enter();
3489        assert!(
3490            !stop.finishing(),
3491            "a busy loop nobody has asked to stop is just running"
3492        );
3493
3494        stop.stop();
3495        assert!(
3496            stop.finishing(),
3497            "a stop asked for mid-run has not landed until the run is settled"
3498        );
3499
3500        stop.exit();
3501        assert!(
3502            !stop.finishing(),
3503            "once the run is settled the stop has landed and there is nothing to finish"
3504        );
3505    }
3506
3507    #[test]
3508    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
3509        let stop = Stop::new();
3510        stop.enter();
3511        stop.enter();
3512        stop.stop();
3513        assert!(stop.finishing(), "two runs still in flight");
3514
3515        stop.exit();
3516        assert!(
3517            stop.finishing(),
3518            "one run finished, but a sibling is still working"
3519        );
3520
3521        stop.exit();
3522        assert!(
3523            !stop.finishing(),
3524            "the last run out is what actually lands the stop"
3525        );
3526    }
3527
3528    #[tokio::test]
3529    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
3530        let dir = tempfile::tempdir().unwrap();
3531        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3532        let stop = Stop::new();
3533        stop.stop();
3534
3535        let began = std::time::Instant::now();
3536        tokio::time::timeout(
3537            Duration::from_secs(2),
3538            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
3539        )
3540        .await
3541        .expect("a stopped loop must return, not sit out its poll interval")
3542        .expect("the loop's own setup and teardown must not fail");
3543        assert!(
3544            began.elapsed() < opts.poll,
3545            "returned only after {:?}, which is a poll interval, not a stop",
3546            began.elapsed()
3547        );
3548    }
3549
3550    #[tokio::test]
3551    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
3552        let dir = tempfile::tempdir().unwrap();
3553        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3554        let stop = Stop::new();
3555
3556        // Asked for after the loop is already parked on its empty queue, which
3557        // is the case an operator tapping stop on a phone actually hits.
3558        let asker = {
3559            let stop = stop.clone();
3560            tokio::spawn(async move {
3561                tokio::time::sleep(Duration::from_millis(20)).await;
3562                stop.stop();
3563            })
3564        };
3565
3566        let began = std::time::Instant::now();
3567        tokio::time::timeout(
3568            Duration::from_secs(2),
3569            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
3570        )
3571        .await
3572        .expect("a stop asked for while idle must wake the wait")
3573        .expect("the loop's own setup and teardown must not fail");
3574        asker.await.unwrap();
3575        assert!(
3576            began.elapsed() < opts.poll,
3577            "returned only after {:?}, so the stop waited on the sleep",
3578            began.elapsed()
3579        );
3580    }
3581
3582    #[tokio::test]
3583    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
3584        let dir = tempfile::tempdir().unwrap();
3585        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3586        let stop = Stop::new();
3587        stop.stop();
3588
3589        tokio::time::timeout(
3590            Duration::from_secs(2),
3591            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
3592        )
3593        .await
3594        .expect("a stopped loop must return")
3595        .expect("the loop's own setup and teardown must not fail");
3596
3597        assert!(
3598            home.is_dir(),
3599            "the loop did publish a status file, so its removal is the teardown and not an absence"
3600        );
3601        assert!(
3602            !status_file.exists(),
3603            "a stopped loop clears its status file"
3604        );
3605        assert!(
3606            read_status(&home).is_none(),
3607            "a reader must see no daemon at all, not a heartbeat that merely stopped"
3608        );
3609    }
3610
3611    #[tokio::test]
3612    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
3613        let dir = tempfile::tempdir().unwrap();
3614        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
3615        opts.once = true;
3616
3617        let mut settled = RunState::new(
3618            dir.path().join("repo"),
3619            "main".to_owned(),
3620            "abc1234".to_owned(),
3621            "fixture".to_owned(),
3622            Config::default(),
3623        );
3624        settled.status = RunStatus::Ready;
3625        let run_dir = home.join("runs").join(&settled.id);
3626        std::fs::create_dir_all(&run_dir).unwrap();
3627        std::fs::write(
3628            run_dir.join("run.json"),
3629            serde_json::to_string_pretty(&settled).unwrap(),
3630        )
3631        .unwrap();
3632        let questions = Questions::at(home.join("questions"));
3633        let mut question = ask::Question::new(
3634            settled.id.clone(),
3635            "review".to_owned(),
3636            "reviewer-1".to_owned(),
3637            "Continue?".to_owned(),
3638            String::new(),
3639            Vec::new(),
3640        );
3641        questions.put(&mut question).unwrap();
3642
3643        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
3644            .await
3645            .unwrap();
3646
3647        assert_eq!(
3648            questions.get(&question.id).unwrap().status,
3649            ask::QuestionStatus::Abandoned,
3650            "an empty --once drain still performs startup question cleanup"
3651        );
3652    }
3653
3654    #[test]
3655    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
3656        let dir = tempfile::tempdir().unwrap();
3657        let queue = Queue::at(dir.path().join("queue"));
3658        let questions = Questions::at(dir.path().join("questions"));
3659        let mut task = task();
3660        queue.put(&mut task).unwrap();
3661
3662        let mut task_question = ask::Question::new(
3663            task.id.clone(),
3664            crate::conduct::NODE.to_owned(),
3665            "conduct".to_owned(),
3666            "Which backend?".to_owned(),
3667            String::new(),
3668            Vec::new(),
3669        );
3670        questions.put(&mut task_question).unwrap();
3671        task.block(vec![task_question.id.clone()], None);
3672        queue.put(&mut task).unwrap();
3673
3674        let mut run_question = ask::Question::new(
3675            "20260101-000000-run1".to_owned(),
3676            "review".to_owned(),
3677            "reviewer-1".to_owned(),
3678            "Run question".to_owned(),
3679            String::new(),
3680            Vec::new(),
3681        );
3682        questions.put(&mut run_question).unwrap();
3683
3684        // A question from another node whose `run` happens to equal this
3685        // task's id — the same field, filled in for an unrelated reason. Only
3686        // `crate::conduct::NODE` questions use `run` as a task id; this one
3687        // must never be touched by this reconciliation, even after release.
3688        let mut coincidental = ask::Question::new(
3689            task.id.clone(),
3690            "review".to_owned(),
3691            "reviewer-1".to_owned(),
3692            "Unrelated review question".to_owned(),
3693            String::new(),
3694            Vec::new(),
3695        );
3696        questions.put(&mut coincidental).unwrap();
3697
3698        reconcile_task_questions(&queue, &questions);
3699        assert!(questions.get(&task_question.id).unwrap().status.open());
3700        assert!(questions.get(&run_question.id).unwrap().status.open());
3701        assert!(questions.get(&coincidental.id).unwrap().status.open());
3702
3703        task.release();
3704        queue.put(&mut task).unwrap();
3705        reconcile_task_questions(&queue, &questions);
3706        assert_eq!(
3707            questions.get(&task_question.id).unwrap().status,
3708            ask::QuestionStatus::Abandoned
3709        );
3710        assert!(
3711            questions.get(&run_question.id).unwrap().status.open(),
3712            "run questions remain the run janitor's responsibility"
3713        );
3714        assert!(
3715            questions.get(&coincidental.id).unwrap().status.open(),
3716            "a non-conductor question must not be abandoned just because its \
3717             run id coincides with a task id"
3718        );
3719    }
3720
3721    #[test]
3722    fn a_freshly_started_running_task_is_never_stalled() {
3723        let dir = tempfile::tempdir().unwrap();
3724        let mut t = task();
3725        t.start("run-1".to_owned());
3726        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
3727        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
3728        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
3729    }
3730
3731    #[test]
3732    fn a_long_running_task_with_no_live_daemon_is_stalled() {
3733        let dir = tempfile::tempdir().unwrap();
3734        let mut t = task();
3735        t.start("run-1".to_owned());
3736        t.updated_at = Timestamp::now()
3737            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
3738        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
3739        assert_eq!(
3740            stalled_tasks(
3741                &Queue::at(dir.path().join("q")),
3742                dir.path(),
3743                Timestamp::now()
3744            )
3745            .len(),
3746            0,
3747            "the task was never written to this queue"
3748        );
3749    }
3750
3751    #[test]
3752    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
3753        let dir = tempfile::tempdir().unwrap();
3754        let mut t = task();
3755        t.id = "20260903-080340-0167".to_owned();
3756        t.start("20260903-080619-01c2".to_owned());
3757        t.updated_at = Timestamp::now()
3758            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
3759
3760        let mut status = Status::new();
3761        status.current = vec![Current {
3762            task: t.id.clone(),
3763            run: "20260903-080619-01c2".to_owned(),
3764        }];
3765        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
3766
3767        assert!(
3768            !is_stalled(&t, dir.path(), Timestamp::now()),
3769            "a live daemon's own heartbeat rules out stalled, however long the task has run"
3770        );
3771    }
3772
3773    /// Rewrite a task's `updated_at` on disk directly, bypassing
3774    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
3775    /// a fixture look like it has genuinely been `running` for a while.
3776    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
3777        let path = queue.path_of(id);
3778        let body = std::fs::read_to_string(&path).unwrap();
3779        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
3780        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
3781        v["updated_at"] = serde_json::Value::String(old.to_string());
3782        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
3783    }
3784
3785    #[test]
3786    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
3787        // The realistic `poll()` ordering, not `is_stalled` in isolation:
3788        // `reclaim_orphaned_running` runs first, on every poll, and settles
3789        // any `running` task whose claim it can actually take. For most
3790        // crashes that is immediate - a dead pid is proof enough for
3791        // `sweep_stale_claims` to drop the lock the same tick, and the very
3792        // next claim attempt succeeds. But a lock whose pid cannot be parsed
3793        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
3794        // `sweep_stale_claims`'s own doc), so the lock - and the claim
3795        // failure behind it - can legitimately outlive many polls. This is
3796        // exactly the gap `stalled_tasks` exists to surface well before that
3797        // six-hour sweep would: reclaim leaves the task `running`, and it
3798        // must still reach the conductor as stalled.
3799        let dir = tempfile::tempdir().unwrap();
3800        let queue = Queue::at(dir.path().join("queue"));
3801        let home = dir.path().join("home");
3802
3803        let mut t = task();
3804        t.id = "20260101-000001-lock".to_owned();
3805        t.start("run-1".to_owned());
3806        queue.put(&mut t).unwrap();
3807        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
3808        std::fs::write(
3809            dir.path().join("queue").join(format!("{}.lock", t.id)),
3810            "not a pid",
3811        )
3812        .unwrap();
3813
3814        let now = Timestamp::now();
3815        assert!(
3816            reclaim_orphaned_running(&queue, 2).is_empty(),
3817            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
3818             and reclaim must leave the task alone"
3819        );
3820        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
3821
3822        let stalled = stalled_tasks(&queue, &home, now);
3823        assert_eq!(
3824            stalled.len(),
3825            1,
3826            "reclaim's inability to claim it yet must not hide it from the conductor"
3827        );
3828        assert_eq!(stalled[0].id, t.id);
3829    }
3830
3831    #[test]
3832    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
3833        let dir = tempfile::tempdir().unwrap();
3834        crate::run::set_home(dir.path().join("run-home"));
3835        let queue = Queue::at(dir.path().join("queue"));
3836        let home = dir.path().join("home");
3837        let questions = Questions::at(dir.path().join("questions"));
3838
3839        let mut t = task();
3840        t.id = "20260101-000003-dead".to_owned();
3841        t.start("missing-run".to_owned());
3842        queue.put(&mut t).unwrap();
3843        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
3844
3845        // This is the real poll ordering: retain the deterministic stalled
3846        // input before a claim proves the owner is gone and reclaims it.
3847        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
3848        assert_eq!(
3849            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
3850            [&t.id]
3851        );
3852        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
3853        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
3854
3855        // Reclaim drops its guard before conductor decisions are applied, so
3856        // the decision for the captured stalled input has a real write path.
3857        crate::conduct::apply(
3858            &queue,
3859            &questions,
3860            &crate::conduct::Verdict {
3861                decisions: vec![crate::conduct::Decision {
3862                    id: t.id.clone(),
3863                    recovery: Some(crate::conduct::Recovery::Requeue),
3864                    ..crate::conduct::Decision::default()
3865                }],
3866            },
3867        )
3868        .unwrap();
3869        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
3870    }
3871
3872    #[test]
3873    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
3874        let dir = tempfile::tempdir().unwrap();
3875        let queue = Queue::at(dir.path().join("queue"));
3876        let home = dir.path().join("home");
3877
3878        let mut fresh = task();
3879        fresh.id = "20260101-000001-aaaa".to_owned();
3880        fresh.start("run-1".to_owned());
3881        queue.put(&mut fresh).unwrap();
3882
3883        let mut old = task();
3884        old.id = "20260101-000002-bbbb".to_owned();
3885        old.start("run-2".to_owned());
3886        queue.put(&mut old).unwrap();
3887        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
3888
3889        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
3890        assert_eq!(stalled.len(), 1);
3891        assert_eq!(stalled[0].id, old.id);
3892    }
3893
3894    #[test]
3895    fn queued_and_finished_task_views_partition_by_status() {
3896        let dir = tempfile::tempdir().unwrap();
3897        let queue = Queue::at(dir.path().join("queue"));
3898
3899        let mut queued = task();
3900        queued.id = "20260101-000001-aaaa".to_owned();
3901        queue.put(&mut queued).unwrap();
3902
3903        let mut failed = task();
3904        failed.id = "20260101-000002-bbbb".to_owned();
3905        failed.start("run-1".to_owned());
3906        failed.fail("gate red", 5);
3907        queue.put(&mut failed).unwrap();
3908
3909        let mut held = task();
3910        held.id = "20260101-000003-cccc".to_owned();
3911        held.hold(None);
3912        queue.put(&mut held).unwrap();
3913
3914        let mut running = task();
3915        running.id = "20260101-000004-dddd".to_owned();
3916        running.start("run-2".to_owned());
3917        queue.put(&mut running).unwrap();
3918
3919        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
3920        assert_eq!(queued_ids, [queued.id.clone()]);
3921
3922        let mut finished_ids: Vec<String> =
3923            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
3924        finished_ids.sort_unstable();
3925        let mut want = vec![failed.id.clone(), held.id.clone()];
3926        want.sort_unstable();
3927        assert_eq!(finished_ids, want);
3928    }
3929
3930    #[test]
3931    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
3932        let dir = tempfile::tempdir().unwrap();
3933        let queue = Queue::at(dir.path().join("queue"));
3934        let questions = ask::Questions::at(dir.path().join("questions"));
3935
3936        let mut dep = task();
3937        dep.id = "20260101-000001-dep0".to_owned();
3938        dep.succeed();
3939        queue.put(&mut dep).unwrap();
3940
3941        let mut still_going = task();
3942        still_going.id = "20260101-000002-dep1".to_owned();
3943        queue.put(&mut still_going).unwrap();
3944
3945        let mut blocked = task();
3946        blocked.id = "20260101-000003-main".to_owned();
3947        blocked.block(
3948            vec![dep.id.clone(), still_going.id.clone()],
3949            Some("waits on both".to_owned()),
3950        );
3951        queue.put(&mut blocked).unwrap();
3952
3953        resolve_blockers(&queue, &questions);
3954
3955        let after = queue.get(&blocked.id).unwrap();
3956        assert_eq!(
3957            after.status,
3958            TaskStatus::Blocked,
3959            "one dependency is still outstanding"
3960        );
3961        assert_eq!(after.blocked_by, [still_going.id.clone()]);
3962    }
3963
3964    #[test]
3965    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
3966        let dir = tempfile::tempdir().unwrap();
3967        let queue = Queue::at(dir.path().join("queue"));
3968        let questions = ask::Questions::at(dir.path().join("questions"));
3969
3970        let mut q = crate::ask::Question::new(
3971            "20260101-000001-main".to_owned(),
3972            crate::conduct::NODE.to_owned(),
3973            "conduct".to_owned(),
3974            "Which backend?".to_owned(),
3975            String::new(),
3976            Vec::new(),
3977        );
3978        questions.put(&mut q).unwrap();
3979        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
3980            .unwrap();
3981        questions.put(&mut q).unwrap();
3982
3983        let mut blocked = task();
3984        blocked.id = "20260101-000001-main".to_owned();
3985        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
3986        queue.put(&mut blocked).unwrap();
3987
3988        resolve_blockers(&queue, &questions);
3989
3990        let after = queue.get(&blocked.id).unwrap();
3991        assert_eq!(
3992            after.status,
3993            TaskStatus::Queued,
3994            "the only blocker resolved"
3995        );
3996        assert_eq!(after.answers.len(), 1);
3997        assert_eq!(after.answers[0].question, "Which backend?");
3998        assert_eq!(after.answers[0].answer, "SQLite");
3999
4000        // And the run this task starts next is told about it.
4001        let instruction = instruction_for(&after);
4002        assert!(instruction.contains("Which backend?"));
4003        assert!(instruction.contains("SQLite"));
4004    }
4005
4006    #[test]
4007    fn instruction_for_is_unchanged_without_any_answers() {
4008        let t = task();
4009        assert_eq!(instruction_for(&t), t.instruction);
4010    }
4011
4012    #[test]
4013    fn resumed_instruction_is_unchanged_without_any_answers() {
4014        let t = task();
4015        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
4016    }
4017
4018    #[test]
4019    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
4020        let mut t = task();
4021        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
4022        // The run's own instruction on disk predates the answer: it is the
4023        // plain original text `Runner::start` saved before the operator was
4024        // ever asked anything.
4025        let old = t.instruction.clone();
4026
4027        let refreshed = resumed_instruction(&old, &t);
4028        assert!(refreshed.starts_with(&old), "the original text is kept");
4029        assert!(refreshed.contains("Which backend?"));
4030        assert!(refreshed.contains("SQLite"));
4031    }
4032
4033    #[test]
4034    fn resumed_instruction_keeps_an_original_answers_heading() {
4035        let mut t = task();
4036        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
4037        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
4038
4039        let refreshed = resumed_instruction(&t.instruction, &t);
4040
4041        assert!(
4042            refreshed.starts_with(&t.instruction),
4043            "an answers heading in the original instruction is not the appended block"
4044        );
4045        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
4046        assert!(refreshed.contains("Which backend?"));
4047        assert!(refreshed.contains("SQLite"));
4048
4049        let repeated = resumed_instruction(&refreshed, &t);
4050        assert_eq!(
4051            repeated, refreshed,
4052            "only the final appended block is refreshed"
4053        );
4054    }
4055
4056    #[test]
4057    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
4058        let mut t = task();
4059        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
4060
4061        // A first resume appends the block; a second resume of the same run,
4062        // with no new answer in between, must reproduce exactly the same
4063        // text rather than appending the block a second time.
4064        let once = resumed_instruction(&t.instruction, &t);
4065        let twice = resumed_instruction(&once, &t);
4066        assert_eq!(once, twice);
4067        assert_eq!(once.matches("Which backend?").count(), 1);
4068
4069        // A later answer replaces the block wholesale rather than growing it.
4070        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
4071        let refreshed = resumed_instruction(&once, &t);
4072        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
4073        assert!(refreshed.contains("Which backend?"));
4074        assert!(refreshed.contains("Which cache?"));
4075    }
4076
4077    #[test]
4078    fn prepare_instruction_covers_all_three_starters() {
4079        let mut t = task();
4080        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
4081
4082        // Start: a fresh run gets the task text plus every answer so far —
4083        // exactly `instruction_for`.
4084        assert_eq!(
4085            prepare_instruction(&Starter::Start, None, &t),
4086            Some(instruction_for(&t))
4087        );
4088
4089        // Resume: the run's prior instruction is refreshed with the answer,
4090        // not discarded and not left stale.
4091        let old = t.instruction.clone();
4092        assert_eq!(
4093            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
4094            Some(resumed_instruction(&old, &t))
4095        );
4096
4097        // Review: a review-only pass builds its own instruction from the
4098        // branch's history in `crate::graph`, with no task statement at all -
4099        // this boundary must leave it alone.
4100        assert_eq!(
4101            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
4102            None
4103        );
4104    }
4105
4106    #[test]
4107    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
4108        assert_eq!(
4109            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
4110            Starter::Review("magi/eba2/A".to_owned())
4111        );
4112    }
4113
4114    #[test]
4115    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
4116        assert_eq!(
4117            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
4118            Starter::Start,
4119            "a vanished review branch must not fall back to resuming the old run either"
4120        );
4121    }
4122
4123    #[test]
4124    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
4125        assert_eq!(
4126            choose_starter(None, false, Some("some-run")),
4127            Starter::Resume("some-run".to_owned())
4128        );
4129        assert_eq!(choose_starter(None, false, None), Starter::Start);
4130    }
4131
4132    #[test]
4133    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
4134        let mut released = task();
4135        released.start("stalled-run".to_owned());
4136        released.requeue();
4137        let unfinished = (!released.fresh_start)
4138            .then(|| Some("stalled-run".to_owned()))
4139            .flatten();
4140        assert_eq!(
4141            choose_starter(None, false, unfinished.as_deref()),
4142            Starter::Start,
4143            "release keeps run history but must not resume it"
4144        );
4145        assert_eq!(released.runs, ["stalled-run"]);
4146    }
4147
4148    #[test]
4149    fn an_ordinary_release_keeps_a_resumable_run_available() {
4150        let mut released = task();
4151        released.start("stalled-run".to_owned());
4152        released.release();
4153        let unfinished = (!released.fresh_start)
4154            .then(|| Some("stalled-run".to_owned()))
4155            .flatten();
4156        assert_eq!(
4157            choose_starter(None, false, unfinished.as_deref()),
4158            Starter::Resume("stalled-run".to_owned()),
4159            "manual release must preserve the normal resume path"
4160        );
4161    }
4162
4163    #[test]
4164    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
4165        let mut state = run_state(RunStatus::Blocked);
4166        state.config.graph.review_rounds = 3;
4167        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
4168        assert!(exhausted_review_budget(&state));
4169
4170        // One round still unused: resuming can still ask a reviewer something.
4171        state.reviews.pop();
4172        assert!(!exhausted_review_budget(&state));
4173
4174        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
4175        // count: only a `Blocked` run re-enters the review loop on resume.
4176        let mut stalled = run_state(RunStatus::Stalled);
4177        stalled.config.graph.review_rounds = 1;
4178        stalled.reviews = vec![review_round(1)];
4179        assert!(!exhausted_review_budget(&stalled));
4180    }
4181
4182    fn review_round(round: usize) -> crate::run::ReviewRound {
4183        crate::run::ReviewRound {
4184            round,
4185            head: "deadbeef".to_owned(),
4186            verified_head: None,
4187            reviews: Vec::new(),
4188            e2e: Vec::new(),
4189            verify_retried: false,
4190            e2e_deferred: false,
4191            e2e_defer_reason: None,
4192            fix: None,
4193            blocking: 0,
4194            answered: 1,
4195            expected: 1,
4196            clean: false,
4197            progressed: true,
4198            vote_split: false,
4199            reconsideration: Vec::new(),
4200            verdict: None,
4201        }
4202    }
4203
4204    #[test]
4205    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
4206        // Mirrors the failure this exists to close: a task's last run ended
4207        // `Blocked` with the review budget spent, `crate::conduct` chose
4208        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
4209        // evidence), and without this check `attempt` would go on treating
4210        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
4211        // review loop iterates zero times over an already-spent budget, so
4212        // the resumed run settles right back to `Blocked` having asked nobody
4213        // anything, and `Requeue`'s promised fresh competition never happens.
4214        let mut exhausted = RunState::new(
4215            PathBuf::from("/repo"),
4216            "main".to_owned(),
4217            "abc1234def".to_owned(),
4218            "add retries".to_owned(),
4219            Config::default(),
4220        );
4221        exhausted.status = RunStatus::Blocked;
4222        exhausted.config.graph.review_rounds = 1;
4223        exhausted.reviews = vec![review_round(1)];
4224
4225        assert_eq!(
4226            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
4227            None,
4228            "an exhausted `Blocked` run must not be offered as resumable"
4229        );
4230
4231        // A `Blocked` run with rounds still unused is genuinely worth
4232        // resuming, and must still be found.
4233        let mut has_budget_left = RunState::new(
4234            PathBuf::from("/repo"),
4235            "main".to_owned(),
4236            "abc1234def".to_owned(),
4237            "add retries".to_owned(),
4238            Config::default(),
4239        );
4240        has_budget_left.status = RunStatus::Blocked;
4241        has_budget_left.config.graph.review_rounds = 3;
4242        has_budget_left.reviews = vec![review_round(1)];
4243
4244        assert_eq!(
4245            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
4246                Ok(has_budget_left.clone())
4247            }),
4248            Some(has_budget_left.id.clone())
4249        );
4250    }
4251
4252    #[test]
4253    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
4254        // A task whose history holds an *older* run that still looks
4255        // resumable (say, a competition `Runner::review` was started
4256        // alongside after that older run went `Stalled`) and a *newest* run
4257        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
4258        // on this task must mean a fresh competition — falling back to the
4259        // stale, superseded `Stalled` run instead would resurrect history
4260        // nothing asked to revisit and silently defeat the requeue.
4261        let mut older_stalled = RunState::new(
4262            PathBuf::from("/repo"),
4263            "main".to_owned(),
4264            "abc1234def".to_owned(),
4265            "add retries".to_owned(),
4266            Config::default(),
4267        );
4268        older_stalled.status = RunStatus::Stalled;
4269
4270        let mut newest_exhausted = RunState::new(
4271            PathBuf::from("/repo"),
4272            "main".to_owned(),
4273            "abc1234def".to_owned(),
4274            "add retries".to_owned(),
4275            Config::default(),
4276        );
4277        newest_exhausted.status = RunStatus::Blocked;
4278        newest_exhausted.config.graph.review_rounds = 1;
4279        newest_exhausted.reviews = vec![review_round(1)];
4280
4281        assert_eq!(
4282            unfinished_run_with(
4283                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
4284                "t",
4285                |_| Ok(newest_exhausted.clone())
4286            ),
4287            None,
4288            "the newest run is exhausted, so nothing here is worth resuming - \
4289             least of all the older, already-superseded run"
4290        );
4291    }
4292
4293    #[test]
4294    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
4295        assert_eq!(
4296            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
4297                Err(anyhow::anyhow!("fixture is absent"))
4298            }),
4299            None
4300        );
4301    }
4302}