Skip to main content

magi/
daemon.rs

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