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    // Absolute paths of the files the task was filed with, re-read from the
2492    // task now so a file attached while it was held reaches a resumed run
2493    // too. A stored name whose file has gone is an error before any agent is
2494    // paid for, never a silent omission the implementer cannot notice.
2495    let attachments = match task_attachments(queue, task) {
2496        Ok(a) => a,
2497        Err(e) => {
2498            task.attempts += 1;
2499            task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
2500            record(queue, task);
2501            return Vec::new();
2502        }
2503    };
2504    let started = match &starter {
2505        Starter::Review(branch) => {
2506            tracing::info!(
2507                "task {} reopens `{branch}` as a review-only pass",
2508                task.short()
2509            );
2510            // Every earlier attempt is superseded by the one being minted
2511            // now, so a branch one of them still holds may be taken over.
2512            let takeover = crate::handover::Takeover {
2513                earlier: task.earlier_attempts().to_vec(),
2514                home: crate::run::home(),
2515                choice: take_divergence_answer(branch, &config.merge.remote, task),
2516            };
2517            Runner::review_taking_over(&repo, branch, config, Some(takeover)).await
2518        }
2519        Starter::Resume(id) => {
2520            tracing::info!("resuming run {id} rather than competing again");
2521            Runner::resume(id).map(|mut r| {
2522                if let Some(instruction) =
2523                    prepare_instruction(&starter, Some(&r.state.instruction), task)
2524                {
2525                    r.state.instruction = instruction;
2526                }
2527                r.state.attachments = attachments.clone();
2528                r
2529            })
2530        }
2531        Starter::Start => {
2532            if let Some(branch) = &review_branch {
2533                tracing::warn!(
2534                    "conductor chose review for task {} but branch `{branch}` no longer \
2535                     exists; requeuing as a fresh competition instead",
2536                    task.short()
2537                );
2538            }
2539            let instruction = prepare_instruction(&starter, None, task)
2540                .unwrap_or_else(|| task.instruction.clone());
2541            Runner::start_naming(&repo, instruction, &task.title, config)
2542                .await
2543                .map(|mut r| {
2544                    r.state.attachments = attachments.clone();
2545                    r
2546                })
2547        }
2548    };
2549    let mut runner = match started {
2550        Ok(r) => r,
2551        // A branch an earlier attempt still holds and magi will not release
2552        // by itself is the operator's call, not a failed attempt: hold the
2553        // task with the reason, spend nothing, and say so on the bell.
2554        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
2555            let reason = format!("could not start the run: {e:#}");
2556            task.last_error = Some(reason.clone());
2557            task.hold_machine(Some(reason));
2558            record(queue, task);
2559            tracing::warn!(
2560                "holding {} for a branch it cannot take over: {e:#}",
2561                task.short()
2562            );
2563            // Stable wording; the specifics live in the task's hold reason.
2564            notices::raise(
2565                Notice::warn(
2566                    &format!("handover:{}", task.id),
2567                    "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.",
2568                )
2569                .link(Link::Task {
2570                    id: task.id.clone(),
2571                })
2572                .about([task.id.clone()]),
2573            );
2574            return Vec::new();
2575        }
2576        // A branch that differs between here and the remote in ways magi
2577        // cannot prove are the same change is a decision for the owner, not a
2578        // failed attempt: ask with both sides laid out, spend no attempt, and
2579        // let the answer requeue the task.
2580        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
2581            let d = e
2582                .downcast_ref::<crate::reconcile::Diverged>()
2583                .expect("checked by the guard");
2584            let mut q = ask::Question::new(
2585                task.id.clone(),
2586                "review".to_owned(),
2587                "sync".to_owned(),
2588                d.summary(),
2589                d.detail(),
2590                d.choices(),
2591            );
2592            match Questions::open().put(&mut q) {
2593                Ok(()) => {
2594                    task.last_error = Some(format!("{e:#}"));
2595                    // Consumed above by `take`; the answer has to reach a review
2596                    // of this same branch, so keep pointing the task at it.
2597                    task.review_branch = Some(d.branch.clone());
2598                    task.block(vec![q.id.clone()], Some(d.summary()));
2599                }
2600                Err(put) => {
2601                    tracing::warn!("could not file the divergence question: {put:#}");
2602                    task.attempts += 1;
2603                    task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
2604                }
2605            }
2606            record(queue, task);
2607            return Vec::new();
2608        }
2609        Err(e) => {
2610            // The answer was stale and nothing was applied: keep pointing at
2611            // the branch so the next attempt asks again against its new tips.
2612            // Nothing went wrong with the task, so no attempt is spent: a
2613            // budget one short of its limit must not hold it instead of
2614            // letting the question be asked again.
2615            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
2616                && let Starter::Review(branch) = &starter
2617            {
2618                task.review_branch = Some(branch.clone());
2619                task.last_error = Some(format!("could not start the run: {e:#}"));
2620                task.status = crate::queue::TaskStatus::Failed;
2621                record(queue, task);
2622                return Vec::new();
2623            }
2624            task.attempts += 1;
2625            task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
2626            record(queue, task);
2627            return Vec::new();
2628        }
2629    };
2630    // A stop that means "park" reaches the graph through this handle.
2631    runner.on_pause(stop.pause());
2632    // `poll`'s interrupt scheduler reaches this one run - and no other -
2633    // through this handle. See `Pause`'s own doc for why these are never
2634    // the same one.
2635    runner.watch_interrupt(interrupt_pause);
2636
2637    // `start` has minted the run, so the task can now point at it. Persisting
2638    // `Running` before `execute` is what makes a crash mid-run legible.
2639    let run = runner.state.id.clone();
2640    task.start(run.clone());
2641    record(queue, task);
2642    lock(status).current.push(Current {
2643        task: task.id.clone(),
2644        run,
2645    });
2646
2647    // `RunState::quota` is the run's whole history across every resume, so
2648    // only what this execution added may arm the cooldown or earn a refund.
2649    let quota_before = runner.state.quota.clone();
2650    let detail = match runner.execute().await {
2651        Ok(()) => describe(&runner.state),
2652        Err(e) => format!("{e:#}"),
2653    };
2654    let fresh = losses_this_attempt(&quota_before, &runner.state.quota);
2655    let verdict = Verdict {
2656        status: runner.state.status,
2657        // A run that opened a pull request handed its work over, whatever the
2658        // gate then decided about merging it.
2659        left_pr: runner.state.pr.is_some(),
2660        // Only a rate limit earns the task its attempt back - and only one
2661        // suffered now: a refund justified by a previous session's loss is
2662        // the same mistake as re-arming the cooldown from it. A stalled run
2663        // resumed without hitting quota again therefore spends its attempt,
2664        // like any other failure of the task's own.
2665        quota_hit: !fresh.is_empty(),
2666        // A run that parked was asked to stop; that is not a failure and must
2667        // not spend an attempt, or replacing the binary a few times would
2668        // exhaust a task's budget without an agent ever misbehaving.
2669        parked: runner.state.parked,
2670        // A quota loss that left nothing viable is the same machine fact as a
2671        // `Stalled` quota loss; see `settle`'s doc table.
2672        no_viable_candidates: runner.state.viable().is_empty(),
2673    };
2674    settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
2675    if task.status == TaskStatus::Done {
2676        supersede_prior_runs(task, &crate::run::home());
2677    }
2678    record(queue, task);
2679    tracing::info!(
2680        "task {} is {} after run {} ({})",
2681        task.short(),
2682        task.status.as_str(),
2683        runner.state.short(),
2684        label(runner.state.status)
2685    );
2686    fresh
2687}
2688
2689/// The quota losses `after` holds that `before` did not: what one execution
2690/// suffered, as opposed to the run's history.
2691///
2692/// Compared by value rather than by length or position because
2693/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
2694/// the vector can shrink and shift under a resume. A retried seat that hits
2695/// quota again is a `push` with a new `at`, so it shows up as new here.
2696/// `reclaim` deliberately keeps reading the whole history: after a crash there
2697/// is no attempt boundary to diff against.
2698fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
2699    after
2700        .iter()
2701        .filter(|q| !before.contains(q))
2702        .cloned()
2703        .collect()
2704}
2705
2706/// When the loop-wide quota cooldown should end, given this attempt's losses;
2707/// `None` when there were none. Reset-hint parsing and the cap live here.
2708fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
2709    if quota.is_empty() {
2710        return None;
2711    }
2712    let with_hint = quota.iter().find(|q| q.reset.is_some());
2713    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
2714    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
2715    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
2716    Some(
2717        now.checked_add(jiff::SignedDuration::from_secs(secs))
2718            .unwrap_or(Timestamp::MAX),
2719    )
2720}
2721
2722/// Cut this attempt's candidate count to one when the task asked to run
2723/// alone.
2724///
2725/// Pure and separate from [`attempt`] so the one thing this feature changes -
2726/// which `candidates` a `solo` task's run is built with - can be asserted
2727/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
2728/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
2729/// value from the caller's own copy, so a repository's `magi.toml` on disk is
2730/// never touched - only the `Config` this one attempt hands to `Runner::start`.
2731fn apply_solo(config: &mut Config, task: &Task) {
2732    if task.solo {
2733        config.graph.candidates = 1;
2734    }
2735}
2736
2737/// Load the config for a task's repository, with the merge override applied.
2738fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
2739    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
2740    if let Some(mode) = &opts.merge {
2741        config.merge.mode = merge_mode(mode)?;
2742    }
2743    Ok(config)
2744}
2745
2746/// Prune the shared build cache back under its cap at a safe boundary
2747/// between runs, so a queue that never empties - and so never reaches
2748/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
2749/// does not leave the cache to grow unchecked for as long as the backlog
2750/// lasts.
2751///
2752/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
2753/// same liveness fact the idle branch's own janitor call rests on - no run
2754/// this daemon spawned is still mid-compile - so pruning here races nothing.
2755/// The caller must not call this while a run is in flight; there is no
2756/// second `busy_now()` check inside this function, on purpose, because there
2757/// is nothing left to check that `busy_now()` has not already answered.
2758///
2759/// A stop that has already been asked for *is* checked here, for a different
2760/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
2761/// synchronously before it decides anything, so the poll loop cannot get back
2762/// to its own `stopped()` test until that walk is over — and a loop already
2763/// on its way out must not make the operator wait out housekeeping it is
2764/// about to stop needing. This is the same call the idle branch makes when it
2765/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
2766/// it matters more here: `busy_now()` is false throughout, so
2767/// [`Stop::finishing`] would report a stop as already landed while the walk
2768/// still held the loop. Nothing is lost by skipping — the cap is a standing
2769/// policy, and the next daemon's startup pass measures the same cache.
2770///
2771/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
2772/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
2773/// and the next has not yet claimed a task, which can be every few
2774/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
2775/// more than the growth it is guarding against.
2776async fn maybe_prune_cache_between_runs(
2777    repo: &Path,
2778    opts: &Opts,
2779    home: &Path,
2780    stop: &Stop,
2781    last_checked: &mut Option<Timestamp>,
2782    now: Timestamp,
2783) {
2784    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
2785        return;
2786    }
2787    *last_checked = Some(now);
2788    let cfg = match prepare(repo, opts) {
2789        Ok(cfg) => cfg,
2790        Err(e) => {
2791            tracing::warn!("cache check: no config: {e:#}");
2792            return;
2793        }
2794    };
2795    match clean::prune_cache_if_over_limit(&cfg, home) {
2796        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
2797            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
2798            pruned.files,
2799            pruned.freed
2800        ),
2801        Ok(_) => {}
2802        Err(e) => {
2803            tracing::warn!("housekeep: prune cache: {e:#}");
2804            notices::raise_in(
2805                home,
2806                Notice::warn(
2807                    "housekeep:cache",
2808                    "Pruning the shared build cache failed; disk usage may keep growing.",
2809                ),
2810            );
2811        }
2812    }
2813}
2814
2815/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
2816/// now, given when it last did (if ever). Pure, so the cadence is asserted
2817/// directly rather than by waiting out real minutes in a test.
2818fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
2819    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
2820}
2821
2822/// The disk janitor, with its housekeeping logged rather than fatal.
2823///
2824/// Called only at the loop's idle points, for the reason the caller documents:
2825/// a prune racing a live compile would delete files mid-build. The config is
2826/// re-read on every call because the repository that just ran may not be the
2827/// daemon's own default, and the cache directory is a repository fact.
2828///
2829/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
2830/// and [`crate::run::default_worktree_root`] read here, for the same reason
2831/// [`drive`] takes its queue and status file rather than resolving them: a
2832/// test driving the loop must not reach through to the operator's real home
2833/// or worktree bay just because the janitor runs on every idle tick.
2834/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
2835/// to get wrong silently - a test's `home` was already isolated, but nothing
2836/// exercised the parameter next to it, so a real worktree bay stayed wired in
2837/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
2838/// it for real, every test in this file that drives the loop at all started
2839/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
2840async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
2841    let cfg = match prepare(repo, opts) {
2842        Ok(cfg) => cfg,
2843        Err(e) => {
2844            tracing::warn!("housekeep: no config: {e:#}");
2845            return;
2846        }
2847    };
2848    // A run's own worktree lives under `config.graph.worktree_root` when the
2849    // repository sets one - the same precedence `RunState::worktree_root`
2850    // uses - and `worktrees_root` only stands in for the *default* an
2851    // unconfigured repository resolves to (see this function's own
2852    // parameter, or the test fixture wiring one to a fake path). Housekeeping
2853    // that always swept the default regardless of this override would never
2854    // see, and so never reclaim, a single worktree for a repository that
2855    // relocated them elsewhere.
2856    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
2857    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
2858    // Reported whenever there is anything to say, not only when `folded > 0`:
2859    // the incident this exists to prevent was 90 of 93 runs skipped and 0
2860    // folded, on every single pass, for months - a report gated on `folded`
2861    // would have stayed silent through every one of them.
2862    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
2863        let mut extra = Vec::new();
2864        if out.unreadable > 0 {
2865            extra.push(format!("{} unreadable", out.unreadable));
2866        }
2867        if out.orphaned_worktrees > 0 {
2868            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
2869        }
2870        let detail = if extra.is_empty() {
2871            String::new()
2872        } else {
2873            format!(" ({})", extra.join(", "))
2874        };
2875        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
2876    }
2877    if out.external_merges_recorded > 0 {
2878        tracing::info!(
2879            "housekeep: recorded {} run(s) as merged externally",
2880            out.external_merges_recorded
2881        );
2882    }
2883    if out.cache_files > 0 {
2884        tracing::info!(
2885            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
2886            out.cache_files,
2887            out.cache_freed
2888        );
2889    }
2890    if out.questions_abandoned > 0 {
2891        tracing::info!(
2892            "housekeep: abandoned {} question(s) left open by a finished run",
2893            out.questions_abandoned
2894        );
2895    }
2896}
2897
2898/// Run [`triage::run_once`] and log whatever it did, the same "only when
2899/// there is something to say" rule [`janitor`] follows for its own report.
2900///
2901/// Called at the same idle points as [`janitor`] - once per full poll
2902/// interval, never mid-attempt - for the same reason: it is not liveness
2903/// critical, and a task's own `hold_reason` string is the one thing this
2904/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
2905/// tick for no benefit.
2906async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
2907    let questions = Questions::at(home.join("questions"));
2908    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
2909    if report.is_empty() {
2910        return;
2911    }
2912    if !report.quarantined.is_empty() {
2913        tracing::info!(
2914            "triage: held {} blocked task(s) whose blocked-on task or \
2915             question no longer exists: {}",
2916            report.quarantined.len(),
2917            report.quarantined.join(", ")
2918        );
2919    }
2920    if !report.resumed.is_empty() {
2921        tracing::info!(
2922            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
2923            report.resumed.len(),
2924            report.resumed.join(", ")
2925        );
2926    }
2927    if !report.asked.is_empty() {
2928        tracing::info!(
2929            "triage: asked about {} held task(s): {}",
2930            report.asked.len(),
2931            report.asked.join(", ")
2932        );
2933    }
2934    if !report.answered.is_empty() {
2935        tracing::info!(
2936            "triage: applied {} operator answer(s): {}",
2937            report.answered.len(),
2938            report.answered.join(", ")
2939        );
2940    }
2941}
2942
2943/// The free-space gate: what stands between this task and a new run, if
2944/// anything. `Some(reason)` holds the task; `None` lets it start.
2945///
2946/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
2947/// the operator opted out. A measurement failure is a gate, not a pass: both
2948/// sides of "cannot tell" are served by not starting.
2949fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
2950    disk_gate_with(repo, config, crate::disk::free_bytes)
2951}
2952
2953/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
2954/// test can assert the exact wiring `attempt` runs - config's threshold in,
2955/// task-holding reason out - without asking the real machine's disk anything.
2956fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
2957    repo: &Path,
2958    config: &Config,
2959    free_bytes: F,
2960) -> Option<String> {
2961    let min = config.disk.min_free_bytes;
2962    if min == 0 {
2963        return None;
2964    }
2965    match free_bytes(repo) {
2966        Ok(free) => crate::disk::gate(free, min),
2967        Err(e) => Some(format!(
2968            "could not measure free space on {} ({e}); the disk gate refuses \
2969             to let a run start blind",
2970            repo.display()
2971        )),
2972    }
2973}
2974
2975/// How long to wait before offering another task when a run lost a seat to a
2976/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
2977/// could read, or carried nothing at all. Long enough that a quota outage
2978/// cannot burn through a whole backlog in the few seconds each doomed attempt
2979/// takes to fail; short enough that a quota which clears early is not left
2980/// idle for the fallback's sake.
2981const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
2982
2983/// Longest a parsed reset hint may push the wait out to. The hint comes from
2984/// the CLI's own words, not a contract, so a parsing slip that lands a day
2985/// away must not leave the loop asleep for a day.
2986const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
2987
2988/// How long [`poll`] should wait before offering the next task, after a run
2989/// lost at least one seat to a rate limit.
2990///
2991/// Pure and separate from the loop so the policy can be exercised without a
2992/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
2993/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
2994/// nothing to parse, or the parsed time has already passed; `cap` bounds how
2995/// far a parsed hint is trusted to push the wait out.
2996fn quota_wait(
2997    reset_at: Option<Timestamp>,
2998    now: Timestamp,
2999    fallback: Duration,
3000    cap: Duration,
3001) -> Duration {
3002    match reset_at {
3003        Some(at) if at > now => {
3004            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3005            Duration::from_secs(secs).min(cap)
3006        }
3007        _ => fallback,
3008    }
3009}
3010
3011/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
3012///
3013/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
3014/// explains why parsing it exactly "would be a bug factory" — so this only
3015/// recognises the shapes actually observed in the wild, and returns `None`
3016/// for anything else rather than guess at a format nobody has seen.
3017///
3018/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
3019/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
3020/// said it, not from whenever this loop happens to read it: anchoring on `now`
3021/// would push the reset later on every read and would read an already-elapsed
3022/// reset as still in the future. (A long hint is still clamped by
3023/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
3024fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3025    parse_reset_hint_zoned(text, now)
3026        .or_else(|| parse_reset_hint_dated(text))
3027        .or_else(|| parse_reset_hint_relative(text, recorded))
3028}
3029
3030/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
3031/// optional but at least one required, in that order. A bare number or any
3032/// unknown unit is refused.
3033fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3034    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3035    let mut rest = rest.trim();
3036    if rest.is_empty() {
3037        return None;
3038    }
3039    let mut total: i64 = 0;
3040    let mut matched = false;
3041    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3042        if let Some((digits, tail)) = rest.split_once(unit)
3043            && !digits.is_empty()
3044            && digits.bytes().all(|b| b.is_ascii_digit())
3045        {
3046            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3047            rest = tail;
3048            matched = true;
3049        }
3050    }
3051    if !rest.is_empty() || !matched {
3052        return None;
3053    }
3054    recorded
3055        .checked_add(jiff::SignedDuration::from_secs(total))
3056        .ok()
3057}
3058
3059/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
3060/// case-insensitive) into a 24-hour hour and minute. Shared by every
3061/// reset-hint shape below.
3062fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3063    let clock = clock.trim().to_lowercase();
3064    let (digits, pm) = clock
3065        .strip_suffix("am")
3066        .map(|d| (d, false))
3067        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3068    let (h, m) = digits.trim().split_once(':')?;
3069    let mut hour: i8 = h.trim().parse().ok()?;
3070    let minute: i8 = m.trim().parse().ok()?;
3071    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3072        return None;
3073    }
3074    if pm && hour != 12 {
3075        hour += 12;
3076    } else if !pm && hour == 12 {
3077        hour = 0;
3078    }
3079    Some((hour, minute))
3080}
3081
3082/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
3083/// and a zone, never a date. A clock reading already past today is read as
3084/// tomorrow's: a CLI naming a same-day reset that has already gone by means
3085/// the window rolled over while nothing was watching.
3086fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3087    let open = text.find('(')?;
3088    let close = text.rfind(')')?;
3089    if close <= open {
3090        return None;
3091    }
3092    let zone = text[open + 1..close].trim();
3093    let (hour, minute) = parse_12h_clock(&text[..open])?;
3094    let tz = jiff::tz::TimeZone::get(zone).ok()?;
3095    let candidate = now
3096        .to_zoned(tz)
3097        .with()
3098        .hour(hour)
3099        .minute(minute)
3100        .second(0)
3101        .millisecond(0)
3102        .microsecond(0)
3103        .nanosecond(0)
3104        .build()
3105        .ok()?;
3106    let mut at = candidate.timestamp();
3107    if at <= now {
3108        at += jiff::SignedDuration::from_hours(24);
3109    }
3110    Some(at)
3111}
3112
3113/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
3114/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
3115/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
3116/// "already past today" correction to make: the year already disambiguates
3117/// it. Scanned as a five-word window so it can be pulled out of the middle
3118/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
3119/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
3120/// any other timestamp with no zone attached.
3121fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
3122    let words: Vec<&str> = text.split_whitespace().collect();
3123    if words.len() < 5 {
3124        return None;
3125    }
3126    (0..=words.len() - 5)
3127        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
3128}
3129
3130/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
3131/// parenthesis right after the window is refused rather than ignored — it
3132/// reads as an explicit zone annotation on a shape that otherwise carries
3133/// none, and guessing UTC anyway would be exactly the silent misread this
3134/// module's parsing otherwise avoids.
3135fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
3136    if trailing.is_some_and(|next| next.starts_with('(')) {
3137        return None;
3138    }
3139    let month = month_number(window[0])?;
3140    let day_token = window[1].strip_suffix(',')?.to_lowercase();
3141    let day_digits = ["st", "nd", "rd", "th"]
3142        .iter()
3143        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
3144    let day: i8 = day_digits.parse().ok()?;
3145    let year_token = window[2];
3146    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
3147        return None;
3148    }
3149    let year: i16 = year_token.parse().ok()?;
3150    // The am/pm word carries the sentence's own trailing punctuation, e.g.
3151    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
3152    // reusing the same 12-hour clock reader the bracketed shape uses.
3153    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
3154    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
3155    let date = jiff::civil::Date::new(year, month, day).ok()?;
3156    let candidate = date
3157        .at(hour, minute, 0, 0)
3158        .to_zoned(jiff::tz::TimeZone::UTC)
3159        .ok()?;
3160    Some(candidate.timestamp())
3161}
3162
3163/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
3164/// case-insensitively, into a 1-based month number.
3165fn month_number(name: &str) -> Option<i8> {
3166    const NAMES: [&str; 12] = [
3167        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
3168    ];
3169    let lower = name.to_lowercase();
3170    NAMES
3171        .iter()
3172        .position(|n| *n == lower.as_str())
3173        .map(|i| i as i8 + 1)
3174}
3175
3176/// Resuming a `Blocked` run that already spent every review round its own
3177/// config allowed cannot make progress: `graph::Runner`'s review loop walks
3178/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
3179/// reached `max_rounds`, so `execute` would settle straight back to
3180/// `Blocked` without asking anyone anything. Read-only against a state this
3181/// build never mutates — `src/graph.rs` stays untouched — but without this
3182/// check, [`unfinished_run`] would keep reporting such a run as still
3183/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
3184/// promise is a fresh competition when a design needs to change) would
3185/// silently resume the exhausted run instead, spending an attempt on a
3186/// cycle that cannot change anything.
3187fn exhausted_review_budget(state: &RunState) -> bool {
3188    state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
3189}
3190
3191/// This task's *most recent* run, if resuming it would actually make
3192/// progress. `short` is only for the warning's own message.
3193///
3194/// Only ever `runs.last()` — never a search back through older history.
3195/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
3196/// mint, oldest first, and every entry before the last one was already
3197/// superseded at the moment it was minted: the daemon only ever starts a new
3198/// run when the previous one was not worth resuming (unresumable, exhausted,
3199/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
3200/// opens a fresh review-only run alongside an older, already-failed
3201/// competition. Searching further back would let an old run that merely
3202/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
3203/// behind, say — get resumed instead of the fresh competition
3204/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
3205/// nothing asked to revisit.
3206///
3207/// Two runs paid for the "prefer resuming over restarting" half of this
3208/// lesson, which is why this still checks `runs.last()` rather than always
3209/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
3210/// task a moment later, duplicating two and a half hours of agent work. Then
3211/// b25f stalled on a judge that timed out and one that answered with no JSON
3212/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
3213/// **one second** later, buying three fresh implementations to reach the
3214/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
3215/// the second case: a stall is terminal, and its cheap recovery re-asks only
3216/// the absent seats. [`exhausted_review_budget`] is the other half: a run
3217/// that is technically `resumable()` but provably cannot progress must not
3218/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
3219/// no-op instead of the fresh competition it promises.
3220///
3221/// A load failure is warned about rather than silently read as "not
3222/// resumable": the alternative is exactly what let a schema mismatch on run
3223/// `eba2` fall through to a full re-competition with nobody told why.
3224/// `crate::conduct` is what actually offers a better answer than
3225/// `Runner::start` here (see `Recovery::Review`), once this task's next
3226/// failure shows it up as `held`/`failed` with the run state unreadable.
3227fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
3228    unfinished_run_with(runs, short, RunState::load)
3229}
3230
3231/// [`unfinished_run`] with an injected state reader. Tests provide their
3232/// fixtures directly rather than touching the process-global run home.
3233fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
3234where
3235    F: FnOnce(&str) -> Result<RunState>,
3236{
3237    let id = runs.last()?;
3238    match load(id) {
3239        Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
3240            Some(id.clone())
3241        }
3242        Ok(_) => None,
3243        Err(e) => {
3244            tracing::warn!("could not read run {id} for task {short}: {e:#}");
3245            None
3246        }
3247    }
3248}
3249
3250/// Is `task` a failed task whose last run was parked at a node boundary, so
3251/// that [`attempt`] will resume it on its own?
3252///
3253/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
3254/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
3255/// injected reader like its sibling. An unreadable run is not awaiting
3256/// anything: it keeps going to the conductor as before.
3257fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
3258where
3259    F: FnOnce(&str) -> Result<RunState>,
3260{
3261    if task.status != TaskStatus::Failed || task.fresh_start || task.review_branch.is_some() {
3262        return false;
3263    }
3264    let Some(id) = task.runs.last() else {
3265        return false;
3266    };
3267    load(id).is_ok_and(|s| {
3268        s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
3269    })
3270}
3271
3272/// Which of the three ways [`attempt`] can mint or continue a run this task
3273/// should use.
3274#[derive(Debug, Clone, PartialEq, Eq)]
3275enum Starter {
3276    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
3277    /// and that still exists.
3278    Review(String),
3279    /// `crate::graph::Runner::resume` on an unfinished run of this task.
3280    Resume(String),
3281    /// `crate::graph::Runner::start`: a fresh competition.
3282    Start,
3283}
3284
3285/// The owner's answer to this branch's divergence question, consumed from the
3286/// task so a later, different divergence asks again. The runner applies it
3287/// (see `Runner::review_taking_over`), after the earlier worktree is released.
3288fn take_divergence_answer(
3289    branch: &str,
3290    remote: &str,
3291    task: &mut Task,
3292) -> Option<crate::reconcile::Choice> {
3293    let summary = crate::reconcile::summary_for(branch, remote);
3294    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
3295        (a.question == summary)
3296            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
3297            .flatten()
3298            .map(|c| (i, c))
3299    })?;
3300    task.answers.remove(idx);
3301    Some(choice)
3302}
3303
3304/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
3305/// this attempt should use. Pure, and separate from [`attempt`], so the
3306/// routing itself is assertable without spawning a real graph or a git
3307/// process: `attempt`'s own `crate::git::branch_exists` call has already
3308/// happened by the time this is called.
3309///
3310/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
3311/// whose branch is gone falls all the way through to [`Starter::Start`], not
3312/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
3313/// old (likely `Blocked`) run in the first place, and a branch that vanished
3314/// out from under that choice is not evidence resuming it would fare better.
3315fn choose_starter(
3316    review_branch: Option<&str>,
3317    branch_exists: bool,
3318    unfinished: Option<&str>,
3319) -> Starter {
3320    match review_branch {
3321        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
3322        Some(_) => Starter::Start,
3323        None => match unfinished {
3324            Some(id) => Starter::Resume(id.to_owned()),
3325            None => Starter::Start,
3326        },
3327    }
3328}
3329
3330/// Which repository a task runs in. A task that names none — the normal case
3331/// for one filed from a phone — runs in the daemon's own default.
3332fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
3333    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
3334        return fallback.to_path_buf();
3335    }
3336    task.repo.clone()
3337}
3338
3339/// The header [`append_answers`] appends operator answers under. Shared with
3340/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
3341/// rather than grown a new block on every resume.
3342const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
3343
3344/// Render the first `count` answers in the block appended to an instruction.
3345fn answers_block(task: &Task, count: usize) -> String {
3346    let mut s = ANSWERS_HEADER.to_owned();
3347    for a in &task.answers[..count] {
3348        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
3349    }
3350    s
3351}
3352
3353/// Append every answer `crate::conduct` has collected for `task` onto `base`,
3354/// in the shape both [`instruction_for`] and [`resumed_instruction`] use.
3355fn append_answers(base: &str, task: &Task) -> String {
3356    if task.answers.is_empty() {
3357        return base.to_owned();
3358    }
3359    let mut s = base.to_owned();
3360    s.push_str(&answers_block(task, task.answers.len()));
3361    s
3362}
3363
3364/// Drop the prior answer block only when it is exactly the suffix this task
3365/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
3366/// the task author is ordinary instruction text, not a block to remove.
3367fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
3368    for count in (1..=task.answers.len()).rev() {
3369        let block = answers_block(task, count);
3370        if let Some(base) = instruction.strip_suffix(&block) {
3371            return base;
3372        }
3373    }
3374    instruction
3375}
3376
3377/// The instruction handed to `Runner::start`: the task's own text, plus any
3378/// operator answers `crate::conduct` collected for it (see
3379/// [`Task::answers`]), so a decision the operator actually made reaches the
3380/// implementers rather than only clearing the block that was waiting on it.
3381///
3382/// Appended rather than merged into [`Task::instruction`] itself, so the
3383/// task's own record stays exactly what its author wrote.
3384fn instruction_for(task: &Task) -> String {
3385    append_answers(&task.instruction, task)
3386}
3387
3388/// The instruction a resumed run should carry on with: whatever it already
3389/// had, refreshed with the task's *current* operator answers.
3390///
3391/// A resumable run's own `RunState::instruction` predates any answer
3392/// `crate::conduct` collects after the run parks, so resuming it unchanged —
3393/// the behaviour before this function existed — silently drops the very
3394/// decision the operator made to unblock it. Re-stripping any block this
3395/// function appended on an earlier resume before re-appending the current
3396/// list (rather than blindly appending again) is what keeps a task resumed
3397/// three times over three answered questions from carrying the same answer
3398/// three times.
3399fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
3400    append_answers(strip_answers_block(old_instruction, task), task)
3401}
3402
3403/// The task's attachments as absolute paths, each checked to still exist.
3404fn task_attachments(queue: &Queue, task: &Task) -> Result<Vec<PathBuf>> {
3405    let paths = queue.attachment_paths(task);
3406    for (name, path) in task.attachments.iter().zip(&paths) {
3407        if !path.is_file() {
3408            bail!(
3409                "attachment `{name}` is recorded on the task but {} is missing",
3410                path.display()
3411            );
3412        }
3413    }
3414    Ok(paths)
3415}
3416
3417/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
3418/// answers before handing it to `Runner` — the actual boundary between
3419/// [`choose_starter`]'s routing and the graph, factored out so it is
3420/// assertable without a real repository, git branch, or agent CLI.
3421///
3422/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
3423/// instruction from the reviewed branch's own commit log because there is no
3424/// task statement to speak of for hand-written work, and splicing operator
3425/// answers into that text would contradict the very message it sends
3426/// reviewers ("there is no task statement").
3427fn prepare_instruction(
3428    starter: &Starter,
3429    old_instruction: Option<&str>,
3430    task: &Task,
3431) -> Option<String> {
3432    match starter {
3433        Starter::Start => Some(instruction_for(task)),
3434        Starter::Resume(_) => Some(resumed_instruction(
3435            old_instruction.expect("a resumed run always has a prior instruction"),
3436            task,
3437        )),
3438        Starter::Review(_) => None,
3439    }
3440}
3441
3442/// Persist a transition. A queue write failure is logged rather than fatal: the
3443/// run already happened, and taking the daemon down would only add a lost
3444/// backlog to a full disk.
3445fn record(queue: &Queue, task: &mut Task) {
3446    if let Err(e) = queue.put(task) {
3447        tracing::error!("could not record task {}: {e:#}", task.short());
3448        notices::raise(Notice::error(
3449            "loop:record",
3450            "The loop could not save a task's state; check the disk.",
3451        ));
3452    }
3453}
3454
3455/// Every runnable task, in the order the loop should try them.
3456///
3457/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
3458/// tail exists so that a claim somebody else holds costs the loop the next
3459/// candidate rather than a whole poll interval of idleness.
3460fn runnable(queue: &Queue) -> Vec<Task> {
3461    let mut tasks: Vec<Task> = queue
3462        .list()
3463        .into_iter()
3464        .filter(|t| t.status.runnable())
3465        .collect();
3466    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
3467    tasks
3468}
3469
3470/// Why a run ended where it did, in one line, for [`Task::last_error`].
3471///
3472/// A stalled run names the seats the quota took out: "out of quota" is not
3473/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
3474/// agent to replace or which plan to top up.
3475///
3476/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
3477/// purpose: unlike `label`'s other callers (an internal log line, an
3478/// already-a-bug fallback message), this string becomes `Task::last_error`
3479/// verbatim, which the phone renders in the same alarm-styled box an
3480/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
3481/// `.err` styling. A bare `verified_noop` there would read exactly like the
3482/// failure this whole feature exists to tell apart from one.
3483fn describe(state: &RunState) -> String {
3484    let mut detail = if state.status == RunStatus::Stalled {
3485        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
3486        seats.sort_unstable();
3487        seats.dedup();
3488        if seats.is_empty() {
3489            "the judging panel lost its quorum".to_owned()
3490        } else {
3491            format!(
3492                "the judging panel lost its quorum; quota took out {}",
3493                seats.join(", ")
3494            )
3495        }
3496    } else {
3497        format!("run ended {}", state.status.display_label())
3498    };
3499    if let Some(last) = state.events.last() {
3500        detail.push_str(&format!(" ({}: {})", last.node, last.message));
3501    }
3502    detail.push_str(&format!(" [run {}]", state.id));
3503    detail
3504}
3505
3506/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
3507///
3508/// The task file lives in the backlog indefinitely; a diagnostic is an
3509/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
3510/// stay small regardless of how much a gate command or a candidate printed.
3511const DIAGNOSTIC_MAX: usize = 4_000;
3512
3513/// Tail kept from a single failing command's output inside a diagnostic.
3514/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
3515/// pointer for a human deciding whether to go read the full artifact by hand,
3516/// not a replacement for reading it.
3517const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
3518
3519/// Assemble a bounded diagnostic excerpt from a held task's own run, so
3520/// `magi task show` says more than the one-line reason in [`describe`].
3521///
3522/// The one-liner answers "where did the run stop"; this answers "what would a
3523/// human have found opening `artifacts/` by hand" — the point of the whole
3524/// feature is the case that one-liner actively misleads on: a run held as "no
3525/// candidate produced a change" can mean the implementer actually finished
3526/// the task (opened a PR, merged it, tagged a release) and only left a clean
3527/// local worktree behind, which reads as "nothing happened" unless someone
3528/// goes and reads what the agent actually said. `None` when the run carries
3529/// none of the three shapes this recognises — an ordinary run held for
3530/// something not diagnosable from `RunState` alone still explains itself
3531/// through `Task::last_error`.
3532fn diagnostic(state: &RunState) -> Option<String> {
3533    let mut parts: Vec<String> = Vec::new();
3534
3535    // Gate failure: which check(s), and the tail of what each printed.
3536    for o in state.gate.iter().filter(|o| !o.ok()) {
3537        parts.push(format!(
3538            "gate `{}` failed ({:?}):\n{}",
3539            o.command,
3540            o.code,
3541            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
3542        ));
3543    }
3544
3545    // The land loop gave up because the fixer declined while checks were
3546    // still red: the message already names them (see `land::run`).
3547    if let Some(last) = state
3548        .events
3549        .iter()
3550        .rev()
3551        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
3552    {
3553        parts.push(last.message.clone());
3554    }
3555
3556    // No viable candidate: every implementer's own final word, sanitized the
3557    // same way a judge would have read it, so a run that actually finished
3558    // the job does not read as an unexplained failure. A verified no-op is
3559    // called out ahead of its own summary and apart from an ordinary
3560    // failure's `why` — this is the one candidate shape whose diagnostic a
3561    // human is expected to actually judge, not just skim.
3562    if state.viable().is_empty() {
3563        for c in &state.candidates {
3564            if let Some(evidence) = &c.verified_noop {
3565                parts.push(format!(
3566                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
3567                    c.label
3568                ));
3569            } else if !c.summary.trim().is_empty() {
3570                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
3571            } else if let Some(why) = &c.failed {
3572                parts.push(format!("candidate {}: {why}", c.label));
3573            }
3574        }
3575    }
3576
3577    if parts.is_empty() {
3578        return None;
3579    }
3580    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
3581    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
3582    // back slightly over. Leave it enough room to always land under the
3583    // limit.
3584    Some(crate::run::tail(
3585        &parts.join("\n\n"),
3586        DIAGNOSTIC_MAX.saturating_sub(100),
3587    ))
3588}
3589
3590/// Stable lower-case name for a run status, for an internal log line and the
3591/// "graph stopped without reaching a terminal status" bug message in
3592/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
3593/// doc for why that one reads [`RunStatus::display_label`] instead. One
3594/// definition of a status's name, on the type that owns it: this table used
3595/// to live here as a second copy, and a status renamed in one place would
3596/// have gone on reading correctly in the other.
3597fn label(status: RunStatus) -> &'static str {
3598    status.as_str()
3599}
3600
3601/// Parse a merge mode override.
3602fn merge_mode(mode: &str) -> Result<MergeMode> {
3603    match mode {
3604        "none" => Ok(MergeMode::None),
3605        "local" => Ok(MergeMode::Local),
3606        "pr" => Ok(MergeMode::Pr),
3607        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
3608    }
3609}
3610
3611/// Take the status lock, recovering from a poisoned one.
3612///
3613/// A panic elsewhere must not silently stop the heartbeat: the status is plain
3614/// data, and the worst a poisoned lock can hold is a stale timestamp.
3615fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
3616    mutex
3617        .lock()
3618        .unwrap_or_else(std::sync::PoisonError::into_inner)
3619}
3620
3621#[cfg(test)]
3622mod tests {
3623    use super::*;
3624    use crate::queue::{Source, TaskStatus};
3625    use crate::run::{Candidate, CommandOutcome};
3626    use pretty_assertions::assert_eq;
3627
3628    fn task() -> Task {
3629        Task::new(
3630            "add retries".to_owned(),
3631            "add retries".to_owned(),
3632            PathBuf::from("/repo"),
3633            Source::Human,
3634        )
3635    }
3636
3637    /// A runnable task marked to interrupt, with an id fixed for assertions
3638    /// rather than the random one [`Task::new`] mints.
3639    fn interrupt_task(id: &str) -> Task {
3640        let mut t = task();
3641        t.id = id.to_owned();
3642        t.interrupt = true;
3643        t
3644    }
3645
3646    /// An ordinary runnable task with an id fixed for assertions.
3647    fn task_with_id(id: &str) -> Task {
3648        let mut t = task();
3649        t.id = id.to_owned();
3650        t
3651    }
3652
3653    /// A runnable task marked `--urgent`, with an id fixed for assertions.
3654    fn urgent_task(id: &str) -> Task {
3655        let mut t = task();
3656        t.id = id.to_owned();
3657        t.urgent = true;
3658        t
3659    }
3660
3661    /// The land-resume exemption wins outright, whether or not the candidate
3662    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
3663    /// queue behind anything" guarantee cannot be weaker just because the
3664    /// same task was also filed with `--urgent`.
3665    #[test]
3666    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
3667        assert_eq!(permit_kind(true, false), PermitKind::None);
3668        assert_eq!(permit_kind(true, true), PermitKind::None);
3669    }
3670
3671    /// The one property this whole feature exists for: `--urgent` draws from
3672    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
3673    /// ordinary candidate draws from the ordinary pool exactly as before,
3674    /// untouched by the urgent slot's existence.
3675    #[test]
3676    fn permit_kind_separates_urgent_from_ordinary() {
3677        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
3678        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
3679    }
3680
3681    /// The exact wiring `attempt` runs before minting anything: a config's
3682    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
3683    /// Free space is injected rather than asked of the real disk - the point
3684    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
3685    /// is deterministic on every machine this test runs on, never dependent
3686    /// on how full the CI runner's own disk happens to be.
3687    #[test]
3688    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
3689        let cfg = Config::default();
3690        let repo = Path::new("/any/repo/path");
3691
3692        let reason =
3693            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
3694        assert!(reason.contains("1024"), "{reason}");
3695        assert!(
3696            reason.contains(&cfg.disk.min_free_bytes.to_string()),
3697            "{reason}"
3698        );
3699
3700        assert_eq!(
3701            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
3702            None,
3703            "exactly at the floor is open"
3704        );
3705        assert_eq!(
3706            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
3707            None,
3708            "comfortably above the floor is open"
3709        );
3710    }
3711
3712    #[test]
3713    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
3714        let mut cfg = Config::default();
3715        cfg.disk.min_free_bytes = 0;
3716        let repo = Path::new("/any/repo/path");
3717        assert_eq!(
3718            disk_gate_with(repo, &cfg, |_| Ok(0)),
3719            None,
3720            "a zero floor never measures at all"
3721        );
3722    }
3723
3724    #[test]
3725    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
3726        let cfg = Config::default();
3727        let repo = Path::new("/any/repo/path");
3728        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
3729            .expect("a measurement failure must close the gate, not open it");
3730        assert!(reason.contains("could not measure"), "{reason}");
3731    }
3732
3733    #[test]
3734    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
3735        let ordinary = task();
3736        let next = advance_interrupt(
3737            Interrupt::Idle,
3738            std::slice::from_ref(&ordinary.id),
3739            std::slice::from_ref(&ordinary),
3740        );
3741        assert_eq!(next, Interrupt::Idle);
3742    }
3743
3744    #[test]
3745    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
3746        // Nothing to interrupt - this is just an ordinary candidate, and the
3747        // loop's normal dispatch will pick it up like any other.
3748        let marked = interrupt_task("marked");
3749        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3750        assert_eq!(next, Interrupt::Idle);
3751    }
3752
3753    #[test]
3754    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
3755        let marked = interrupt_task("marked");
3756        let next = advance_interrupt(
3757            Interrupt::Idle,
3758            &["running".to_owned()],
3759            std::slice::from_ref(&marked),
3760        );
3761        assert_eq!(
3762            next,
3763            Interrupt::Parking {
3764                parked: vec!["running".to_owned()],
3765                interrupt_task: "marked".to_owned(),
3766            }
3767        );
3768    }
3769
3770    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
3771    /// one run can be in flight when a task becomes runnable and marked.
3772    /// Parking all of them would mean `Resuming` later has more than one id
3773    /// to release back to ordinary dispatch, which cannot be made safe
3774    /// against that same setting's own extra concurrency slots letting two
3775    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
3776    /// The simplification the task's own constraints ask for: do not begin
3777    /// a sequence at all until the herd settles back to exactly one.
3778    #[test]
3779    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
3780        let marked = interrupt_task("marked");
3781
3782        let two = advance_interrupt(
3783            Interrupt::Idle,
3784            &["a".to_owned(), "b".to_owned()],
3785            std::slice::from_ref(&marked),
3786        );
3787        assert_eq!(two, Interrupt::Idle);
3788
3789        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3790        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
3791    }
3792
3793    #[test]
3794    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
3795        let state = Interrupt::Parking {
3796            parked: vec!["running".to_owned()],
3797            interrupt_task: "marked".to_owned(),
3798        };
3799        // Still in flight: no change.
3800        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
3801        assert_eq!(still_going, state);
3802
3803        // Left flight, but the interrupt task has not been dispatched yet on
3804        // this tick - stays `Parking` so `interrupt_gate` can let it through,
3805        // as long as it is still runnable.
3806        let stopped_but_not_yet_dispatched =
3807            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
3808        assert_eq!(stopped_but_not_yet_dispatched, state);
3809
3810        // Left flight, and the interrupt task is now in flight itself.
3811        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
3812        assert_eq!(
3813            dispatched,
3814            Interrupt::Running {
3815                parked: vec!["running".to_owned()],
3816                interrupt_task: "marked".to_owned(),
3817            }
3818        );
3819    }
3820
3821    #[test]
3822    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
3823        let state = Interrupt::Running {
3824            parked: vec!["running".to_owned()],
3825            interrupt_task: "marked".to_owned(),
3826        };
3827        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
3828        assert_eq!(still_running, state);
3829
3830        // Whatever it ended as - merged, failed, held - is not this
3831        // function's concern: leaving flight is the only trigger, driven
3832        // straight off the same in-flight list `poll` already reaps. It does
3833        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
3834        // why that would let an unrelated task start ahead of, or alongside,
3835        // the guaranteed resume.
3836        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
3837        assert_eq!(
3838            ended,
3839            Interrupt::Resuming {
3840                parked: vec!["running".to_owned()]
3841            }
3842        );
3843    }
3844
3845    #[test]
3846    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
3847        let state = Interrupt::Resuming {
3848            parked: vec!["running".to_owned()],
3849        };
3850        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
3851        assert_eq!(still_waiting, state);
3852
3853        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
3854        assert_eq!(dispatched, Interrupt::Idle);
3855    }
3856
3857    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
3858    /// or otherwise moved on by an operator with no claim standing in the
3859    /// way - must not wedge the sequence (and so the whole loop's dispatch,
3860    /// via `interrupt_gate`) waiting forever for a dispatch that can never
3861    /// come. The parked run still gets its resume.
3862    #[test]
3863    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
3864    {
3865        let state = Interrupt::Parking {
3866            parked: vec!["running".to_owned()],
3867            interrupt_task: "marked".to_owned(),
3868        };
3869        // `marked` has been held/blocked/deleted since the sequence began:
3870        // it no longer appears in `runnable` at all.
3871        let next = advance_interrupt(state, &[], &[]);
3872        assert_eq!(
3873            next,
3874            Interrupt::Resuming {
3875                parked: vec!["running".to_owned()]
3876            },
3877            "abandoning the interrupt must not abandon the resume it owes"
3878        );
3879    }
3880
3881    /// The same abandonment, one step later: `Resuming` itself must not wait
3882    /// forever for a parked task that has since become unrunnable.
3883    #[test]
3884    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
3885        let state = Interrupt::Resuming {
3886            parked: vec!["running".to_owned()],
3887        };
3888        let next = advance_interrupt(state, &[], &[]);
3889        assert_eq!(
3890            next,
3891            Interrupt::Idle,
3892            "nothing is left to wait for; the loop must not stay wedged"
3893        );
3894    }
3895
3896    #[test]
3897    fn disabled_by_config_the_sequence_can_never_leave_idle() {
3898        let marked = interrupt_task("marked");
3899        let next = advance_interrupt_tick(
3900            false,
3901            Interrupt::Idle,
3902            &["running".to_owned()],
3903            std::slice::from_ref(&marked),
3904        );
3905        assert_eq!(
3906            next,
3907            Interrupt::Idle,
3908            "an unmarked, unconfigured daemon must behave exactly as before"
3909        );
3910    }
3911
3912    #[test]
3913    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
3914        let state = Interrupt::Parking {
3915            parked: vec!["running".to_owned()],
3916            interrupt_task: "marked".to_owned(),
3917        };
3918        let candidates = vec![interrupt_task("marked"), task()];
3919        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3920        assert!(
3921            allowed.is_empty(),
3922            "nothing may dispatch - not even the interrupt task itself - \
3923             until the parked run has actually stopped"
3924        );
3925    }
3926
3927    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
3928    /// grow a special case for it: an urgent candidate that is not the
3929    /// interrupt task withholds exactly like an ordinary one for as long as
3930    /// the parked run it is racing has not actually left flight. A version
3931    /// of this feature once bypassed the gate for urgent candidates, on the
3932    /// theory that a genuinely separate concurrency lane could not collide
3933    /// with 75dd's own; it could, and did - the bypassed task dispatched
3934    /// alongside a run 75dd's own state machine had only *asked* to park,
3935    /// not yet confirmed gone, which is exactly the second run
3936    /// `Interrupt::Parking`'s own doc says must never happen. There is no
3937    /// tick during Parking/Running/Resuming where letting an extra
3938    /// candidate through is safe, urgent or not - the parked run may still
3939    /// be genuinely mid-call.
3940    #[test]
3941    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
3942        for state in [
3943            Interrupt::Parking {
3944                parked: vec!["running".to_owned()],
3945                interrupt_task: "marked".to_owned(),
3946            },
3947            Interrupt::Running {
3948                parked: vec!["running".to_owned()],
3949                interrupt_task: "marked".to_owned(),
3950            },
3951            Interrupt::Resuming {
3952                parked: vec!["running".to_owned()],
3953            },
3954        ] {
3955            let candidates = vec![
3956                interrupt_task("marked"),
3957                urgent_task("hot"),
3958                task_with_id("ordinary"),
3959            ];
3960            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3961            assert!(
3962                !allowed.iter().any(|t| t.id == "hot"),
3963                "an urgent candidate must wait out the same gate as anything \
3964                 else while the run it would run alongside has not actually \
3965                 left flight, for state {state:?}: {allowed:?}"
3966            );
3967        }
3968    }
3969
3970    /// The one case where marking a task `--urgent` and `interrupt` at once
3971    /// is not redundant: once the interrupt sequence's own guaranteed
3972    /// resume/dispatch actually admits the task, it is unaffected by also
3973    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
3974    /// never on the urgent flag.
3975    #[test]
3976    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
3977        let state = Interrupt::Resuming {
3978            parked: vec!["hot".to_owned()],
3979        };
3980        let candidates = vec![urgent_task("hot"), task()];
3981        let allowed = interrupt_gate(&state, &[], candidates);
3982        assert_eq!(
3983            allowed.iter().filter(|t| t.id == "hot").count(),
3984            1,
3985            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
3986        );
3987    }
3988
3989    #[test]
3990    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
3991        let state = Interrupt::Parking {
3992            parked: vec!["running".to_owned()],
3993            interrupt_task: "marked".to_owned(),
3994        };
3995        let other = task();
3996        let candidates = vec![interrupt_task("marked"), other.clone()];
3997        let allowed = interrupt_gate(&state, &[], candidates);
3998        assert_eq!(allowed.len(), 1);
3999        assert_eq!(allowed[0].id, "marked");
4000    }
4001
4002    #[test]
4003    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
4004        let state = Interrupt::Running {
4005            parked: vec!["running".to_owned()],
4006            interrupt_task: "marked".to_owned(),
4007        };
4008        let candidates = vec![task(), task()];
4009        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
4010        assert!(allowed.is_empty());
4011    }
4012
4013    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
4014    /// sequence began (only reachable above the default
4015    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
4016    /// never both in the same tick, which is what "exactly one resume, no
4017    /// simultaneous run" actually requires structurally rather than by
4018    /// coincidence of how many ordinary slots happen to be free.
4019    #[test]
4020    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
4021        let state = Interrupt::Resuming {
4022            parked: vec!["a".to_owned(), "c".to_owned()],
4023        };
4024        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
4025        let allowed = interrupt_gate(&state, &[], candidates);
4026        assert_eq!(
4027            allowed.len(),
4028            1,
4029            "at most one candidate may be offered while resuming: {allowed:?}"
4030        );
4031        assert_eq!(allowed[0].id, "a");
4032    }
4033
4034    #[test]
4035    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
4036        let state = Interrupt::Resuming {
4037            parked: vec!["a".to_owned()],
4038        };
4039        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
4040        assert!(allowed.is_empty());
4041    }
4042
4043    /// The invariant the completion criteria ask for by name: across a whole
4044    /// simulated sequence, there is never a tick where the gate would let
4045    /// through both the parked run's resume and the interrupt task, and
4046    /// exactly one candidate resumes the instant the interrupt task's run
4047    /// ends - never zero, never more than one.
4048    #[test]
4049    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
4050        let running = task(); // id: whatever `Task::new` minted
4051        let marked = interrupt_task("marked");
4052
4053        let mut state = Interrupt::Idle;
4054        // Tick 1: `running` is in flight, `marked` becomes runnable.
4055        let in_flight = vec![running.id.clone()];
4056        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
4057        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
4058        assert!(gated.is_empty(), "still waiting on `running` to park");
4059
4060        // Tick 2: `running` parked and left flight; nothing dispatched yet.
4061        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
4062        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
4063        assert_eq!(
4064            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4065            vec!["marked"],
4066            "only the interrupt task may be offered to the dispatcher now"
4067        );
4068
4069        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
4070        state = advance_interrupt_tick(
4071            true,
4072            state,
4073            &["marked".to_owned()],
4074            std::slice::from_ref(&running),
4075        );
4076        let gated = interrupt_gate(
4077            &state,
4078            &["marked".to_owned()],
4079            vec![marked.clone(), running.clone()],
4080        );
4081        assert!(
4082            gated.is_empty(),
4083            "the parked run must not be offered back while the interrupt \
4084             task is still running"
4085        );
4086
4087        // Tick 4: `marked`'s run reached a terminal status and left flight.
4088        // A higher-priority ordinary task `other` is also runnable now - it
4089        // must not be let through instead of, or alongside, `running`.
4090        let other = task_with_id("other");
4091        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
4092        assert_eq!(
4093            state,
4094            Interrupt::Resuming {
4095                parked: vec![running.id.clone()]
4096            }
4097        );
4098        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
4099        assert_eq!(
4100            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4101            vec![running.id.as_str()],
4102            "exactly the parked run resumes - not the unrelated task, even \
4103             though it was offered first"
4104        );
4105
4106        // Tick 5: `running` is now in flight (dispatched from tick 4's
4107        // gate). Only now does the sequence end and ordinary dispatch fully
4108        // resume.
4109        state = advance_interrupt_tick(
4110            true,
4111            state,
4112            std::slice::from_ref(&running.id),
4113            std::slice::from_ref(&other),
4114        );
4115        assert_eq!(state, Interrupt::Idle);
4116        let gated = interrupt_gate(
4117            &state,
4118            std::slice::from_ref(&running.id),
4119            vec![other.clone()],
4120        );
4121        assert_eq!(
4122            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4123            vec![other.id.as_str()],
4124            "ordinary dispatch is unrestricted again"
4125        );
4126    }
4127
4128    #[test]
4129    fn every_run_status_settles_the_task_it_came_from() {
4130        // run status, resulting task status, attempts still standing after one
4131        let table = [
4132            (RunStatus::Merged, TaskStatus::Done, 1),
4133            (RunStatus::Ready, TaskStatus::Done, 1),
4134            (RunStatus::Stalled, TaskStatus::Failed, 0),
4135            (RunStatus::Blocked, TaskStatus::Failed, 1),
4136            (RunStatus::Failed, TaskStatus::Failed, 1),
4137            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
4138            (RunStatus::Prep, TaskStatus::Failed, 1),
4139            (RunStatus::Implementing, TaskStatus::Failed, 1),
4140            (RunStatus::Judging, TaskStatus::Failed, 1),
4141            (RunStatus::Deliberating, TaskStatus::Failed, 1),
4142            (RunStatus::Voting, TaskStatus::Failed, 1),
4143            (RunStatus::Reviewing, TaskStatus::Failed, 1),
4144            (RunStatus::Gating, TaskStatus::Failed, 1),
4145        ];
4146        for (run, want, attempts) in table {
4147            let mut t = task();
4148            t.start("20260902-000000-aaaa".to_owned());
4149            settle(
4150                &mut t,
4151                Verdict {
4152                    status: run,
4153                    left_pr: false,
4154                    parked: false,
4155                    quota_hit: matches!(run, RunStatus::Stalled),
4156                    no_viable_candidates: false,
4157                },
4158                "why",
4159                2,
4160            );
4161            assert_eq!(t.status, want, "task status after {}", label(run));
4162            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
4163        }
4164    }
4165
4166    #[test]
4167    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
4168        let mut stalled = task();
4169        stalled.start("20260902-000000-aaaa".to_owned());
4170        settle(
4171            &mut stalled,
4172            Verdict {
4173                status: RunStatus::Stalled,
4174                left_pr: false,
4175                parked: false,
4176                quota_hit: true,
4177                no_viable_candidates: false,
4178            },
4179            "quota",
4180            1,
4181        );
4182        assert_eq!(stalled.attempts, 0);
4183        assert!(
4184            stalled.status.runnable(),
4185            "a machine problem must leave the task in line"
4186        );
4187
4188        let mut blocked = task();
4189        blocked.start("20260902-000000-aaaa".to_owned());
4190        settle(
4191            &mut blocked,
4192            Verdict {
4193                status: RunStatus::Blocked,
4194                left_pr: false,
4195                parked: false,
4196                quota_hit: false,
4197                no_viable_candidates: false,
4198            },
4199            "findings open",
4200            1,
4201        );
4202        assert_eq!(blocked.attempts, 1);
4203        assert_eq!(
4204            blocked.status,
4205            TaskStatus::Held,
4206            "the last attempt hands the task to a human"
4207        );
4208    }
4209
4210    #[test]
4211    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
4212        // Attempts to spare: without the pull request this task would go
4213        // straight back in line and run the whole competition again.
4214        let mut delivered = task();
4215        delivered.start("20260903-080619-01c2".to_owned());
4216        settle(
4217            &mut delivered,
4218            Verdict {
4219                status: RunStatus::Blocked,
4220                left_pr: true,
4221                parked: false,
4222                quota_hit: false,
4223                no_viable_candidates: false,
4224            },
4225            "no check status",
4226            4,
4227        );
4228        assert_eq!(
4229            delivered.status,
4230            TaskStatus::Held,
4231            "a pull request waiting on CI or a person is not a retryable failure"
4232        );
4233        assert!(
4234            !delivered.status.runnable(),
4235            "the loop must not pick this task up again"
4236        );
4237        assert_eq!(
4238            delivered.last_error.as_deref(),
4239            Some("no check status"),
4240            "the operator needs to be told what the gate was waiting for"
4241        );
4242
4243        // The same status without a pull request is a plain failure, and with
4244        // attempts left it is retried.
4245        let mut empty_handed = task();
4246        empty_handed.start("20260903-080619-01c2".to_owned());
4247        settle(
4248            &mut empty_handed,
4249            Verdict {
4250                status: RunStatus::Blocked,
4251                left_pr: false,
4252                parked: false,
4253                quota_hit: false,
4254                no_viable_candidates: false,
4255            },
4256            "findings open",
4257            4,
4258        );
4259        assert_eq!(empty_handed.status, TaskStatus::Failed);
4260        assert!(empty_handed.status.runnable());
4261    }
4262
4263    #[test]
4264    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
4265        // Every candidate agreed, with evidence, that nothing belonged in the
4266        // worktree. That is not a confirmed success to close automatically -
4267        // a human still has to check the claim - and it is not an ordinary
4268        // failure either, so this settles exactly like a pull request nobody
4269        // merged yet: `Held`, same as `Blocked` with a PR.
4270        let mut noop = task();
4271        noop.start("20260912-131304-391f".to_owned());
4272        settle(
4273            &mut noop,
4274            Verdict {
4275                status: RunStatus::VerifiedNoop,
4276                left_pr: false,
4277                parked: false,
4278                quota_hit: false,
4279                no_viable_candidates: true,
4280            },
4281            "candidate A: already fixed by b32cfc4, on main",
4282            4,
4283        );
4284        assert_eq!(
4285            noop.status,
4286            TaskStatus::Held,
4287            "an unverified claim is a request for a human, not a failure"
4288        );
4289        assert!(
4290            !noop.status.runnable(),
4291            "the loop must not requeue this on the same unverified claim"
4292        );
4293        // `Task::release` resets attempts to zero the moment a human looks at
4294        // the evidence and lets it run again, so it does not matter here
4295        // whether the one attempt already spent stays spent - what matters is
4296        // that nothing retries this task unattended in the meantime.
4297        assert_eq!(noop.attempts, 1);
4298    }
4299
4300    #[test]
4301    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
4302        // Parking is the operator asking for the process back - to replace the
4303        // binary, most of all. The run's work is intact on disk, so this is
4304        // not a failed attempt, and charging for it would mean a few upgrades
4305        // could exhaust a budget meant for agents that misbehaved.
4306        let mut parked = task();
4307        parked.start("20260903-183634-2d98".to_owned());
4308        settle(
4309            &mut parked,
4310            Verdict {
4311                status: RunStatus::Implementing,
4312                left_pr: false,
4313                quota_hit: false,
4314                parked: true,
4315                no_viable_candidates: false,
4316            },
4317            "parked after `implementing`",
4318            2,
4319        );
4320        assert_eq!(parked.attempts, 0, "a park is refunded");
4321        assert!(
4322            parked.status.runnable(),
4323            "and the task stays in line so the next loop resumes its run"
4324        );
4325        assert_eq!(
4326            parked.last_error.as_deref(),
4327            Some("parked after `implementing`"),
4328            "the card says where it stopped"
4329        );
4330
4331        // Without the park flag the same non-terminal status is what it always
4332        // was: `execute` returning mid-flight, which is a bug and spends an
4333        // attempt so a task cannot loop on it forever.
4334        let mut broken = task();
4335        broken.start("20260903-183634-2d98".to_owned());
4336        settle(
4337            &mut broken,
4338            Verdict {
4339                status: RunStatus::Implementing,
4340                left_pr: false,
4341                quota_hit: false,
4342                parked: false,
4343                no_viable_candidates: false,
4344            },
4345            "returned mid-flight",
4346            2,
4347        );
4348        assert_eq!(broken.attempts, 1);
4349    }
4350
4351    #[test]
4352    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
4353        // Run e633: quorum lost because two judges answered with the wrong
4354        // JSON shape, `quota: []`. Refunding that takes the bound off the
4355        // retry loop, and each retry pays for a fresh hour-long implement
4356        // wave before it can fail the same way.
4357        let mut flaky = task();
4358        flaky.start("20260903-123023-e633".to_owned());
4359        settle(
4360            &mut flaky,
4361            Verdict {
4362                status: RunStatus::Stalled,
4363                left_pr: false,
4364                parked: false,
4365                quota_hit: false,
4366                no_viable_candidates: false,
4367            },
4368            "verdict rests on 1 of 3 judges",
4369            2,
4370        );
4371        assert_eq!(
4372            flaky.attempts, 1,
4373            "flakiness spends an attempt, so `max_attempts` still bounds it"
4374        );
4375        assert!(flaky.status.runnable(), "and it is still worth retrying");
4376
4377        // The same status, lost to a rate limit, is the machine's fault.
4378        let mut limited = task();
4379        limited.start("20260903-123023-e633".to_owned());
4380        settle(
4381            &mut limited,
4382            Verdict {
4383                status: RunStatus::Stalled,
4384                left_pr: false,
4385                parked: false,
4386                quota_hit: true,
4387                no_viable_candidates: false,
4388            },
4389            "judge-2, judge-3 out of quota",
4390            2,
4391        );
4392        assert_eq!(limited.attempts, 0, "a quota window is refunded");
4393        assert!(limited.status.runnable());
4394
4395        // And the bound really binds: a task that keeps stalling on flakiness
4396        // reaches a human instead of running the roster forever.
4397        let mut worn = task();
4398        for _ in 0..2 {
4399            worn.release();
4400        }
4401        worn.start("20260903-123023-e633".to_owned());
4402        worn.attempts = 2;
4403        settle(
4404            &mut worn,
4405            Verdict {
4406                status: RunStatus::Stalled,
4407                left_pr: false,
4408                parked: false,
4409                quota_hit: false,
4410                no_viable_candidates: false,
4411            },
4412            "no quorum again",
4413            2,
4414        );
4415        assert_eq!(worn.status, TaskStatus::Held);
4416        assert!(!worn.status.runnable());
4417    }
4418
4419    #[test]
4420    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
4421        // The implement wave loses every seat to the same rate limit and
4422        // `after_implement` bails with nothing viable, which surfaces as
4423        // `Failed` rather than `Stalled`. That is the same machine fact the
4424        // `Stalled`-quota row already refunds, and must be refunded the same
4425        // way, or a quota outage quietly holds every task it touches instead
4426        // of leaving them in line for the reset.
4427        let mut wiped_out = task();
4428        wiped_out.start("20260907-025000-a1b2".to_owned());
4429        settle(
4430            &mut wiped_out,
4431            Verdict {
4432                status: RunStatus::Failed,
4433                left_pr: false,
4434                parked: false,
4435                quota_hit: true,
4436                no_viable_candidates: true,
4437            },
4438            "no candidate produced a change; nothing to judge",
4439            2,
4440        );
4441        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
4442        assert!(
4443            wiped_out.status.runnable(),
4444            "a machine problem must leave the task in line"
4445        );
4446
4447        // This is the exemption that must stay narrow: a candidate that did
4448        // produce a change, and then failed for some other reason, still
4449        // spends the attempt even though a seat elsewhere hit its quota.
4450        // Otherwise every ordinary failure that happens to share a run with
4451        // an unrelated rate limit would be refunded for free.
4452        let mut partial_progress = task();
4453        partial_progress.start("20260907-025500-c3d4".to_owned());
4454        settle(
4455            &mut partial_progress,
4456            Verdict {
4457                status: RunStatus::Failed,
4458                left_pr: false,
4459                parked: false,
4460                quota_hit: true,
4461                no_viable_candidates: false,
4462            },
4463            "gate failed on the winning candidate",
4464            2,
4465        );
4466        assert_eq!(
4467            partial_progress.attempts, 1,
4468            "a candidate that actually produced a change spends the attempt \
4469             even though some other seat hit its quota"
4470        );
4471        assert!(partial_progress.status.runnable());
4472    }
4473
4474    #[test]
4475    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
4476        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
4477        // disk, and that construction must reach the same conclusion as the
4478        // one `attempt` builds from a live run, or a crash at exactly the
4479        // wrong moment gives a recovered task a different policy than one a
4480        // daemon finished settling itself.
4481        let mut t = task();
4482        t.start("20260907-025000-a1b2".to_owned());
4483        let mut state = run_state(RunStatus::Failed);
4484        state.quota.push(QuotaLoss {
4485            seat: "cand-a".to_owned(),
4486            node: "implement".to_owned(),
4487            at: Timestamp::now(),
4488            reset: None,
4489        });
4490        assert!(
4491            state.viable().is_empty(),
4492            "no candidate was added, so nothing is viable"
4493        );
4494        reclaim(&mut t, Some(state), 2);
4495        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
4496        assert!(t.status.runnable());
4497    }
4498
4499    #[test]
4500    fn a_held_task_is_never_offered_to_the_loop() {
4501        let dir = tempfile::tempdir().unwrap();
4502        let queue = Queue::at(dir.path().to_path_buf());
4503        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
4504            let mut t = task();
4505            t.id = format!("2026090{n}-000000-000{n}");
4506            t.priority = priority;
4507            queue.put(&mut t).unwrap();
4508        }
4509        let mut held = task();
4510        held.id = "20260909-000000-9999".to_owned();
4511        held.priority = 99;
4512        held.hold_machine(None);
4513        queue.put(&mut held).unwrap();
4514
4515        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
4516        assert_eq!(order.len(), 3);
4517        assert!(!order.contains(&held.id));
4518        assert_eq!(
4519            order.first().cloned(),
4520            queue.next_runnable().map(|t| t.id),
4521            "the loop's first candidate is exactly what the queue offers"
4522        );
4523        assert_eq!(
4524            order,
4525            vec![
4526                "20260902-000000-0002".to_owned(),
4527                "20260903-000000-0003".to_owned(),
4528                "20260901-000000-0001".to_owned(),
4529            ],
4530            "priority first, then oldest, so nothing starves"
4531        );
4532    }
4533
4534    #[test]
4535    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
4536        let dir = tempfile::tempdir().unwrap();
4537        let queue = Queue::at(dir.path().to_path_buf());
4538        let mut old = task();
4539        old.id = "20260101-000000-old0".to_owned();
4540        queue.put(&mut old).unwrap();
4541        let mut fresh = task();
4542        fresh.id = "20260101-000000-new0".to_owned();
4543        queue.put(&mut fresh).unwrap();
4544
4545        // No parseable pid at all, so age is the only signal there is to
4546        // check - unlike a real `Queue::claim`, which always names a real,
4547        // and therefore alive, pid this test cannot fake as dead.
4548        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
4549        std::thread::sleep(Duration::from_millis(60));
4550        let live = queue.claim(&fresh.id).unwrap();
4551
4552        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4553        assert_eq!(swept, vec![old.id.clone()]);
4554        assert!(
4555            queue.claim(&old.id).is_ok(),
4556            "an unparseable lock older than the threshold is swept"
4557        );
4558        assert!(
4559            queue.claim(&fresh.id).is_err(),
4560            "a live pid protects its lock regardless of age"
4561        );
4562        drop(live);
4563    }
4564
4565    #[test]
4566    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
4567        // The regression this guards: `sweep` now runs concurrently with
4568        // every attempt this daemon itself has spawned (see
4569        // `InFlightGuard`), not only between them the way a single
4570        // sequential loop once did. A run that legitimately outlives
4571        // `older_than` still has this very process's own live pid sitting in
4572        // its own lock file on every later sweep, and deciding by age alone
4573        // would delete that still-valid claim out from under the attempt
4574        // that holds it - which `reclaim_orphaned_running` would then read
4575        // as abandoned and hand to a second, competing attempt.
4576        let dir = tempfile::tempdir().unwrap();
4577        let queue = Queue::at(dir.path().to_path_buf());
4578        let mut t = task();
4579        t.id = "20260101-000000-live".to_owned();
4580        queue.put(&mut t).unwrap();
4581
4582        let claim = queue.claim(&t.id).unwrap();
4583        std::thread::sleep(Duration::from_millis(60));
4584
4585        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4586        assert!(
4587            swept.is_empty(),
4588            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
4589        );
4590        assert!(
4591            queue.claim(&t.id).is_err(),
4592            "the lock still protects its task"
4593        );
4594        drop(claim);
4595    }
4596
4597    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
4598    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
4599    fn injected_dead_pid() -> u32 {
4600        std::process::id().checked_add(1).unwrap_or(1)
4601    }
4602
4603    #[test]
4604    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
4605        let dir = tempfile::tempdir().unwrap();
4606        let queue = Queue::at(dir.path().to_path_buf());
4607        let mut t = task();
4608        t.id = "20260101-000000-dead".to_owned();
4609        queue.put(&mut t).unwrap();
4610        let dead_pid = injected_dead_pid();
4611
4612        // Written directly rather than through `Queue::claim`, which would
4613        // stamp this test process's own very much alive pid and defeat the
4614        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
4615        // like moments after it died, not six hours later.
4616        std::fs::write(
4617            dir.path().join(format!("{}.lock", t.id)),
4618            dead_pid.to_string(),
4619        )
4620        .unwrap();
4621
4622        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4623            pid != dead_pid
4624        });
4625        assert_eq!(
4626            swept,
4627            vec![t.id.clone()],
4628            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
4629        );
4630        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
4631    }
4632
4633    #[test]
4634    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
4635        let dir = tempfile::tempdir().unwrap();
4636        let queue = Queue::at(dir.path().to_path_buf());
4637        let mut t = task();
4638        t.id = "20260101-000000-late".to_owned();
4639        queue.put(&mut t).unwrap();
4640        let dead_pid = injected_dead_pid();
4641
4642        // Tick one, standing in for the sweep `poll` already runs at
4643        // startup: nothing to find yet.
4644        assert!(
4645            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
4646            "nothing has claimed the task yet"
4647        );
4648
4649        // A second daemon claims the task and dies before it ever writes
4650        // `running`, well after this loop's own startup sweep already ran.
4651        std::fs::write(
4652            dir.path().join(format!("{}.lock", t.id)),
4653            dead_pid.to_string(),
4654        )
4655        .unwrap();
4656
4657        // Tick two, standing in for a poll long into this daemon's uptime:
4658        // the same function, called again, notices what only just appeared -
4659        // proving the sweep is not a one-shot startup check.
4660        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4661            pid != dead_pid
4662        });
4663        assert_eq!(swept, vec![t.id.clone()]);
4664    }
4665
4666    #[test]
4667    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
4668        // `reclaim_orphaned_running` looks up the task's last run, which
4669        // touches `run::home()`; the first call anywhere in this binary wins,
4670        // so this is a no-op if another test already pinned one, and either
4671        // way the run id below is never written under it.
4672        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4673        let dir = tempfile::tempdir().unwrap();
4674        let queue = Queue::at(dir.path().to_path_buf());
4675        let mut t = task();
4676        t.id = "20260101-000000-crsh".to_owned();
4677        t.status = TaskStatus::Running;
4678        t.attempts = 1;
4679        // No `run.json` behind this id: standing in for a run this test does
4680        // not need to make readable, since the point is the lock, not the
4681        // recovery table `reclaim` already has its own tests for.
4682        t.runs.push("20260904-000000-4043".to_owned());
4683        queue.put(&mut t).unwrap();
4684        let dead_pid = injected_dead_pid();
4685
4686        // The crashed daemon's own claim, naming a pid nothing on the
4687        // machine holds anymore.
4688        std::fs::write(
4689            dir.path().join(format!("{}.lock", t.id)),
4690            dead_pid.to_string(),
4691        )
4692        .unwrap();
4693
4694        // Before the lock is swept the task looks claimed, and
4695        // `reclaim_orphaned_running` must leave it alone - this is exactly
4696        // the bug: a `running` task stranded behind a dead daemon's lock,
4697        // invisible to the claim-as-proof check because the lock outlived
4698        // the process that wrote it.
4699        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
4700        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
4701
4702        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4703            pid != dead_pid
4704        });
4705        assert_eq!(swept, vec![t.id.clone()]);
4706
4707        let reclaimed = reclaim_orphaned_running(&queue, 2);
4708        assert_eq!(reclaimed, vec![t.id.clone()]);
4709        let after = queue.get(&t.id).unwrap();
4710        assert_eq!(
4711            after.status,
4712            TaskStatus::Held,
4713            "no run.json to recover from, so a human is asked"
4714        );
4715        assert_eq!(
4716            after.runs,
4717            vec!["20260904-000000-4043".to_owned()],
4718            "the crashed run's id is kept as evidence, not discarded"
4719        );
4720    }
4721
4722    #[test]
4723    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
4724        let dir = tempfile::tempdir().unwrap();
4725        let queue = Queue::at(dir.path().to_path_buf());
4726        let mut t = task();
4727        t.id = "20260101-000000-unknown".to_owned();
4728        queue.put(&mut t).unwrap();
4729        let dead_pid = injected_dead_pid();
4730        std::fs::write(
4731            dir.path().join(format!("{}.lock", t.id)),
4732            dead_pid.to_string(),
4733        )
4734        .unwrap();
4735
4736        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
4737        assert!(swept.is_empty(), "an unknown pid must keep its lock");
4738        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
4739    }
4740
4741    fn run_state(status: RunStatus) -> RunState {
4742        let mut state = RunState::new(
4743            PathBuf::from("/repo"),
4744            "main".to_owned(),
4745            "abc1234def".to_owned(),
4746            "add retries".to_owned(),
4747            Config::default(),
4748        );
4749        state.status = status;
4750        state
4751    }
4752
4753    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
4754        Candidate {
4755            index: 0,
4756            label,
4757            agent: "claude".to_owned(),
4758            branch: format!("magi/x/{label}"),
4759            worktree: PathBuf::from("/repo"),
4760            summary: summary.to_owned(),
4761            stat: String::new(),
4762            files: 0,
4763            commits: usize::from(!empty),
4764            empty,
4765            failed: failed.map(str::to_owned),
4766            verified_noop: None,
4767            duration_ms: 0,
4768            folded: false,
4769        }
4770    }
4771
4772    #[test]
4773    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
4774        let mut state = run_state(RunStatus::Blocked);
4775        state.gate = vec![
4776            CommandOutcome {
4777                command: "cargo make check".to_owned(),
4778                code: Some(0),
4779                output_tail: "ok".to_owned(),
4780                duration_ms: 0,
4781                resource_blocked: false,
4782            },
4783            CommandOutcome {
4784                command: "cargo test".to_owned(),
4785                code: Some(101),
4786                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
4787                duration_ms: 0,
4788                resource_blocked: false,
4789            },
4790        ];
4791        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
4792        assert!(d.contains("cargo test"), "{d}");
4793        assert!(
4794            !d.contains("cargo make check"),
4795            "a passing check is not a diagnostic: {d}"
4796        );
4797        assert!(d.contains("assertion failed"), "{d}");
4798    }
4799
4800    #[test]
4801    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
4802        let mut state = run_state(RunStatus::Blocked);
4803        state.event(
4804            "land",
4805            "stopped: the fixer produced no commit while 2 check(s) were failing \
4806             (build, lint); stopping instead of looping on an unchanged tree",
4807        );
4808        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
4809        assert!(d.contains("build"), "{d}");
4810        assert!(d.contains("lint"), "{d}");
4811        assert!(d.contains("fixer produced no commit"), "{d}");
4812    }
4813
4814    #[test]
4815    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
4816        // `describe`'s output becomes `Task::last_error` verbatim, and the
4817        // phone renders that in the same alarm-styled box an ordinary
4818        // failure gets. A bare `verified_noop` there would read exactly like
4819        // the failure this status exists to be told apart from.
4820        let state = run_state(RunStatus::VerifiedNoop);
4821        let d = describe(&state);
4822        assert!(
4823            d.contains("agent-verified no-op"),
4824            "expected the display label, not the wire spelling: {d}"
4825        );
4826        assert!(!d.contains("verified_noop"), "{d}");
4827    }
4828
4829    #[test]
4830    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
4831        // The whole point of the feature: a run held as "no candidate produced
4832        // a change" can mean the implementer actually finished the task and
4833        // only left a clean local tree behind - see AGENTS.md on this exact
4834        // failure mode. The diagnostic has to carry what the agent actually
4835        // said, not just the fact that nothing was there to judge.
4836        let mut state = run_state(RunStatus::Failed);
4837        state.candidates = vec![candidate(
4838            'A',
4839            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
4840            true,
4841            None,
4842        )];
4843        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
4844        assert!(d.contains("candidate A"), "{d}");
4845        assert!(d.contains("tagged v1.2.3"), "{d}");
4846    }
4847
4848    #[test]
4849    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
4850        let mut state = run_state(RunStatus::Failed);
4851        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
4852        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
4853        assert!(d.contains("candidate A"), "{d}");
4854        assert!(d.contains("agent timed out"), "{d}");
4855    }
4856
4857    #[test]
4858    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
4859        // A viable candidate existed, the gate never ran, and nothing land
4860        // said matches - `Task::last_error` is left to explain this one alone.
4861        let mut state = run_state(RunStatus::Failed);
4862        state.candidates = vec![candidate('A', "did the work", false, None)];
4863        assert!(diagnostic(&state).is_none());
4864    }
4865
4866    #[test]
4867    fn diagnostic_is_bounded_however_much_a_run_printed() {
4868        let mut state = run_state(RunStatus::Blocked);
4869        state.gate = vec![
4870            CommandOutcome {
4871                command: "cargo test".to_owned(),
4872                code: Some(101),
4873                output_tail: "x".repeat(50_000),
4874                duration_ms: 0,
4875                resource_blocked: false,
4876            },
4877            CommandOutcome {
4878                command: "cargo clippy".to_owned(),
4879                code: Some(1),
4880                output_tail: "y".repeat(50_000),
4881                duration_ms: 0,
4882                resource_blocked: false,
4883            },
4884        ];
4885        state.candidates = vec![
4886            candidate('A', &"z".repeat(50_000), true, None),
4887            candidate('B', &"w".repeat(50_000), true, None),
4888        ];
4889        let d = diagnostic(&state).expect("plenty here to diagnose");
4890        assert!(
4891            d.len() <= DIAGNOSTIC_MAX,
4892            "diagnostic grew to {} bytes, unbounded",
4893            d.len()
4894        );
4895    }
4896
4897    #[test]
4898    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
4899        let mut state = run_state(RunStatus::Blocked);
4900        state.gate = vec![CommandOutcome {
4901            command: "cargo test".to_owned(),
4902            code: Some(101),
4903            output_tail: "assertion failed".to_owned(),
4904            duration_ms: 0,
4905            resource_blocked: false,
4906        }];
4907        let verdict = Verdict {
4908            status: RunStatus::Blocked,
4909            left_pr: false,
4910            quota_hit: false,
4911            parked: false,
4912            no_viable_candidates: false,
4913        };
4914
4915        // Attempt one of two still has a retry coming: no diagnostic yet, the
4916        // task is going to run again and this run's evidence would go stale.
4917        let mut t = task();
4918        t.start("run-1".to_owned());
4919        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4920        assert_eq!(t.status, TaskStatus::Failed);
4921        assert!(t.diagnostic.is_none());
4922
4923        // Attempt two exhausts the budget: now it is held, and the
4924        // diagnostic is what `magi task show` has to say more than one line.
4925        t.start("run-2".to_owned());
4926        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4927        assert_eq!(t.status, TaskStatus::Held);
4928        let d = t.diagnostic.expect("a held task must carry its diagnostic");
4929        assert!(d.contains("cargo test"), "{d}");
4930    }
4931
4932    #[test]
4933    fn a_held_task_names_the_open_question_it_is_waiting_on() {
4934        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
4935        // `magi ask` question settled Held with `hold_reason: null`, so the
4936        // notification said nothing actionable. `note_open_question` should
4937        // append the question id to whatever `handed_off` already wrote.
4938        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4939        let home = crate::run::home();
4940        let state = run_state(RunStatus::VerifiedNoop);
4941        let mut q = ask::Question::new(
4942            state.id.clone(),
4943            "implement".to_owned(),
4944            "impl-A".to_owned(),
4945            "is this really a no-op?".to_owned(),
4946            String::new(),
4947            Vec::new(),
4948        );
4949        Questions::at(home.join("questions")).put(&mut q).unwrap();
4950
4951        let verdict = Verdict {
4952            status: RunStatus::VerifiedNoop,
4953            left_pr: false,
4954            quota_hit: false,
4955            parked: false,
4956            no_viable_candidates: false,
4957        };
4958        let mut t = task();
4959        t.start(state.id.clone());
4960        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
4961
4962        assert_eq!(t.status, TaskStatus::Held);
4963        let reason = t.hold_reason.expect("a held task must record why");
4964        assert!(
4965            reason.starts_with("run ended agent-verified no-op"),
4966            "the original settle reason must survive unchanged: {reason}"
4967        );
4968        assert!(
4969            reason.contains(q.short()),
4970            "the open question's id must be named so the notice is actionable: {reason}"
4971        );
4972    }
4973
4974    #[test]
4975    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
4976        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4977        let state = run_state(RunStatus::VerifiedNoop);
4978
4979        let verdict = Verdict {
4980            status: RunStatus::VerifiedNoop,
4981            left_pr: false,
4982            quota_hit: false,
4983            parked: false,
4984            no_viable_candidates: false,
4985        };
4986        let mut t = task();
4987        t.start(state.id.clone());
4988        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
4989
4990        assert_eq!(t.status, TaskStatus::Held);
4991        assert_eq!(
4992            t.hold_reason.as_deref(),
4993            Some("run ended agent-verified no-op"),
4994            "nothing to append when the question was already answered or never asked"
4995        );
4996    }
4997
4998    #[test]
4999    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
5000        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5001        let mut first = run_state(RunStatus::Blocked);
5002        first.id = "20260101-000000-sup1".to_owned();
5003        first.save().unwrap();
5004        let mut second = run_state(RunStatus::Merged);
5005        second.id = "20260101-000000-sup2".to_owned();
5006        second.save().unwrap();
5007
5008        let mut t = task();
5009        t.runs = vec![first.id.clone(), second.id.clone()];
5010        t.status = TaskStatus::Done;
5011
5012        supersede_prior_runs(&t, &crate::run::home());
5013
5014        assert_eq!(
5015            RunState::load(&first.id).unwrap().status,
5016            RunStatus::Superseded,
5017            "the first attempt's Blocked no longer needs anyone's attention"
5018        );
5019        assert_eq!(
5020            RunState::load(&second.id).unwrap().status,
5021            RunStatus::Merged,
5022            "the run that actually succeeded is left exactly as it was"
5023        );
5024    }
5025
5026    #[test]
5027    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
5028        // `is_working_on` alone only proves a *daemon* claim; a `magi run
5029        // --resume` invoked by hand outside the daemon never touches
5030        // `daemon.json` at all, so it would look identical to a genuinely
5031        // idle run without also consulting `RunState::liveness`, which reads
5032        // this run's own recorded `driver_pid` instead.
5033        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5034        let mut first = run_state(RunStatus::Blocked);
5035        first.id = "20260101-000000-sup9".to_owned();
5036        // This test process's own pid: guaranteed alive without needing a
5037        // real second process or daemon.
5038        first.driver_pid = Some(std::process::id());
5039        first.driver_started_at = Some(
5040            crate::proc::process_started_at(std::process::id())
5041                .expect("this test process's own start time must be queryable"),
5042        );
5043        first.save().unwrap();
5044        let mut second = run_state(RunStatus::Merged);
5045        second.id = "20260101-000000-supa".to_owned();
5046        second.save().unwrap();
5047
5048        let mut t = task();
5049        t.runs = vec![first.id.clone(), second.id.clone()];
5050        t.status = TaskStatus::Done;
5051
5052        supersede_prior_runs(&t, &crate::run::home());
5053
5054        assert_eq!(
5055            RunState::load(&first.id).unwrap().status,
5056            RunStatus::Blocked,
5057            "a live driver_pid means something is still actually working this run, \
5058             even though no daemon claims it - rewriting under it would just be \
5059             undone the next time that process saves"
5060        );
5061    }
5062
5063    #[test]
5064    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
5065        // The first resweep must skip a still-live attempt exactly like
5066        // `supersede_prior_runs` itself does; a later resweep, once that
5067        // process is no longer actually driving it, is what closes the gap
5068        // `supersede_prior_runs` alone leaves - a task only ever reaches
5069        // `Done` once, so nothing else would ever look at this run again.
5070        let dir = tempfile::tempdir().unwrap();
5071        let home = dir.path().to_path_buf();
5072        let queue = Queue::at(dir.path().join("queue"));
5073
5074        let mut first = run_state(RunStatus::Blocked);
5075        first.id = "20260101-000000-supd".to_owned();
5076        first.driver_pid = Some(std::process::id());
5077        first.driver_started_at = Some(
5078            crate::proc::process_started_at(std::process::id())
5079                .expect("this test process's own start time must be queryable"),
5080        );
5081        first.save_under(&home).unwrap();
5082        let mut second = run_state(RunStatus::Merged);
5083        second.id = "20260101-000000-supe".to_owned();
5084        second.save_under(&home).unwrap();
5085
5086        let mut t = task();
5087        t.runs = vec![first.id.clone(), second.id.clone()];
5088        t.status = TaskStatus::Done;
5089        queue.put(&mut t).unwrap();
5090
5091        resweep_superseded_attempts(&queue, &home);
5092        assert_eq!(
5093            RunState::load_under(&first.id, &home).unwrap().status,
5094            RunStatus::Blocked,
5095            "still live on the first pass, so still untouched"
5096        );
5097
5098        // Stand in for the manual process no longer being the one driving
5099        // this run: same pid (this test process really is still alive), but
5100        // an identity marker that no longer matches it - see
5101        // `RunState::liveness`'s own doc for why a mismatched
5102        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
5103        let mut stale = RunState::load_under(&first.id, &home).unwrap();
5104        stale.driver_started_at = Some("not-this-processes-real-start-time".to_owned());
5105        stale.save_under(&home).unwrap();
5106
5107        resweep_superseded_attempts(&queue, &home);
5108        assert_eq!(
5109            RunState::load_under(&first.id, &home).unwrap().status,
5110            RunStatus::Superseded,
5111            "the second pass catches up what the first one correctly skipped"
5112        );
5113    }
5114
5115    #[test]
5116    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
5117        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5118        let mut first = run_state(RunStatus::Blocked);
5119        first.id = "20260101-000000-sup3".to_owned();
5120        first.save().unwrap();
5121        let mut second = run_state(RunStatus::Blocked);
5122        second.id = "20260101-000000-sup4".to_owned();
5123        second.save().unwrap();
5124
5125        let mut t = task();
5126        t.runs = vec![first.id.clone(), second.id.clone()];
5127        // Still retrying: nothing about this task's story is settled yet, so
5128        // neither Blocked run may be relabelled, even though a later attempt
5129        // already exists.
5130        t.status = TaskStatus::Failed;
5131
5132        supersede_prior_runs(&t, &crate::run::home());
5133
5134        assert_eq!(
5135            RunState::load(&first.id).unwrap().status,
5136            RunStatus::Blocked
5137        );
5138        assert_eq!(
5139            RunState::load(&second.id).unwrap().status,
5140            RunStatus::Blocked
5141        );
5142    }
5143
5144    #[test]
5145    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
5146        // `magi task done` (or the API's equivalent) can close a task with no
5147        // run of its own ever having succeeded - there is nothing here that
5148        // counts as "the attempt that finished it", so nothing is rewritten.
5149        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5150        let mut first = run_state(RunStatus::Blocked);
5151        first.id = "20260101-000000-sup5".to_owned();
5152        first.save().unwrap();
5153
5154        let mut t = task();
5155        t.runs = vec![first.id.clone()];
5156        t.status = TaskStatus::Done;
5157
5158        supersede_prior_runs(&t, &crate::run::home());
5159
5160        assert_eq!(
5161            RunState::load(&first.id).unwrap().status,
5162            RunStatus::Blocked,
5163            "a single-attempt task has no earlier run to supersede"
5164        );
5165    }
5166
5167    #[test]
5168    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
5169        // `magi task done` (or the web/conductor equivalents) can close a
5170        // task in any status, including one whose *last* recorded attempt is
5171        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
5172        // never watched, say. `runs.last()` being `Done`-adjacent is not
5173        // proof it actually succeeded, so nothing earlier may be relabelled
5174        // on its say-so alone.
5175        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5176        let mut first = run_state(RunStatus::Blocked);
5177        first.id = "20260101-000000-supb".to_owned();
5178        first.save().unwrap();
5179        let mut second = run_state(RunStatus::Failed);
5180        second.id = "20260101-000000-supc".to_owned();
5181        second.save().unwrap();
5182
5183        let mut t = task();
5184        t.runs = vec![first.id.clone(), second.id.clone()];
5185        t.status = TaskStatus::Done;
5186
5187        supersede_prior_runs(&t, &crate::run::home());
5188
5189        assert_eq!(
5190            RunState::load(&first.id).unwrap().status,
5191            RunStatus::Blocked,
5192            "the task's last attempt never landed, so there is nothing here \
5193             actually superseding it"
5194        );
5195    }
5196
5197    #[test]
5198    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
5199        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
5200        // to look" - `Failed` and `VerifiedNoop` are already their own
5201        // terminal answers and must not be relabelled into a third one.
5202        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5203        let mut failed = run_state(RunStatus::Failed);
5204        failed.id = "20260101-000000-sup6".to_owned();
5205        failed.save().unwrap();
5206        let mut noop = run_state(RunStatus::VerifiedNoop);
5207        noop.id = "20260101-000000-sup7".to_owned();
5208        noop.save().unwrap();
5209        let mut winner = run_state(RunStatus::Ready);
5210        winner.id = "20260101-000000-sup8".to_owned();
5211        winner.save().unwrap();
5212
5213        let mut t = task();
5214        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
5215        t.status = TaskStatus::Done;
5216
5217        supersede_prior_runs(&t, &crate::run::home());
5218
5219        assert_eq!(
5220            RunState::load(&failed.id).unwrap().status,
5221            RunStatus::Failed
5222        );
5223        assert_eq!(
5224            RunState::load(&noop.id).unwrap().status,
5225            RunStatus::VerifiedNoop
5226        );
5227    }
5228
5229    fn approval_question(run: &str) -> ask::Question {
5230        ask::Question::new(
5231            run.to_owned(),
5232            land::APPROVAL_NODE.to_owned(),
5233            "land".to_owned(),
5234            "merge?".to_owned(),
5235            String::new(),
5236            vec!["merge".to_owned(), "hold".to_owned()],
5237        )
5238    }
5239
5240    #[test]
5241    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
5242        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5243        let mut state = run_state(RunStatus::Landing);
5244        state.id = "20260101-000000-fre1".to_owned();
5245        state.parked = true;
5246        state.save().unwrap();
5247        ask::Questions::open()
5248            .put(&mut approval_question(&state.id))
5249            .unwrap();
5250
5251        let mut t = task();
5252        t.runs.push(state.id.clone());
5253        assert_eq!(
5254            land_resume_state(&t),
5255            LandResume::StillWaiting,
5256            "nobody has answered and the timeout has not passed"
5257        );
5258    }
5259
5260    #[test]
5261    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
5262        // `ask::ask_and_wait`'s own deadline used to retire a question
5263        // nobody answered; land's approval bypasses that wait (see
5264        // `land::approval_gate`), so this is now the only place
5265        // `graph.answer_timeout` is enforced for a land approval at all.
5266        crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5267        let mut state = run_state(RunStatus::Landing);
5268        state.id = "20260101-000000-exp1".to_owned();
5269        state.parked = true;
5270        state.config.graph.answer_timeout = 60;
5271        state.save().unwrap();
5272
5273        let store = ask::Questions::open();
5274        let mut q = approval_question(&state.id);
5275        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
5276        store.put(&mut q).unwrap();
5277
5278        let mut t = task();
5279        t.runs.push(state.id.clone());
5280        assert_eq!(
5281            land_resume_state(&t),
5282            LandResume::Ready,
5283            "an expired question must not be waited on forever"
5284        );
5285
5286        let after = store.get(&q.id).unwrap();
5287        assert!(
5288            !after.status.open(),
5289            "the question is abandoned, not silently ignored"
5290        );
5291        assert!(
5292            after.resolution().is_none(),
5293            "an abandoned question is not read as a decision"
5294        );
5295    }
5296
5297    #[test]
5298    fn reclaim_settles_a_running_task_against_its_last_run() {
5299        let mut t = task();
5300        t.start("20260904-000000-4043".to_owned());
5301        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
5302        assert_eq!(
5303            t.status,
5304            TaskStatus::Done,
5305            "a run that actually finished must not stay `running` forever"
5306        );
5307    }
5308
5309    #[test]
5310    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
5311        // A blocked run with attempts left goes back to `Failed`, exactly as
5312        // it would from `attempt` itself - `reclaim` must not invent a second
5313        // policy for a task a daemon merely stopped without reporting.
5314        let mut t = task();
5315        t.start("20260904-000000-4043".to_owned());
5316        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
5317        assert_eq!(t.status, TaskStatus::Failed);
5318        assert!(t.status.runnable());
5319    }
5320
5321    #[test]
5322    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
5323        let mut t = task();
5324        t.start("20260904-000000-4043".to_owned());
5325        reclaim(&mut t, None, 2);
5326        assert_eq!(t.status, TaskStatus::Held);
5327        assert!(
5328            t.last_error
5329                .as_deref()
5330                .is_some_and(|e| e.contains("running")),
5331            "the operator needs to know why this task was held"
5332        );
5333    }
5334
5335    #[test]
5336    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
5337        let dir = tempfile::tempdir().unwrap();
5338        let queue = Queue::at(dir.path().to_path_buf());
5339
5340        // No run recorded, so this never has to touch `RunState::load`.
5341        let mut orphaned = task();
5342        orphaned.id = "20260904-000000-orph".to_owned();
5343        orphaned.status = TaskStatus::Running;
5344        orphaned.attempts = 1;
5345        queue.put(&mut orphaned).unwrap();
5346
5347        let mut alive = task();
5348        alive.id = "20260904-000000-live".to_owned();
5349        alive.status = TaskStatus::Running;
5350        alive.attempts = 1;
5351        queue.put(&mut alive).unwrap();
5352        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
5353
5354        let mut queued = task();
5355        queued.id = "20260904-000000-wait".to_owned();
5356        queue.put(&mut queued).unwrap();
5357
5358        let reclaimed = reclaim_orphaned_running(&queue, 2);
5359        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
5360
5361        assert_eq!(
5362            queue.get(&orphaned.id).unwrap().status,
5363            TaskStatus::Held,
5364            "nothing was driving it and there was no run to recover"
5365        );
5366        assert_eq!(
5367            queue.get(&alive.id).unwrap().status,
5368            TaskStatus::Running,
5369            "a live claim must protect the task it belongs to"
5370        );
5371        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
5372    }
5373
5374    /// Read a run.json back from an explicit `home`, the same way
5375    /// `reclaim_abandoned_runs` itself does - never through the
5376    /// process-global `RunState::load`, which this test's own `home` (an
5377    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
5378    /// use at all.
5379    fn read_run_under(home: &Path, id: &str) -> RunState {
5380        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
5381        serde_json::from_str(&body).unwrap()
5382    }
5383
5384    #[test]
5385    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
5386        let dir = tempfile::tempdir().unwrap();
5387        let home = dir.path().to_path_buf();
5388        let now = Timestamp::now();
5389        let overrun_seat = || crate::run::ActiveSeat {
5390            node: "implement".to_owned(),
5391            started_at: now - jiff::SignedDuration::new(21_000, 0),
5392            timeout_secs: 3_600,
5393            attempt: 0,
5394            task: None,
5395            command: None,
5396            index: None,
5397            total: None,
5398        };
5399
5400        let mut dead = run_state(RunStatus::Implementing);
5401        dead.id = "20260101-000000-dead".to_owned();
5402        dead.active.insert("impl-A".to_owned(), overrun_seat());
5403        // A `driver_pid` the injected query below confirms gone outright —
5404        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
5405        dead.driver_pid = Some(4242);
5406        dead.save_under(&home).unwrap();
5407
5408        // Same shape, but a live daemon's heartbeat names it: must be left
5409        // exactly alone, however far past its own timeout the seat sits.
5410        let mut alive = run_state(RunStatus::Implementing);
5411        alive.id = "20260101-000000-aliv".to_owned();
5412        alive.active.insert("impl-A".to_owned(), overrun_seat());
5413        alive.save_under(&home).unwrap();
5414        let mut status = Status::new();
5415        status.current = vec![Current {
5416            task: "20260101-000000-task".to_owned(),
5417            run: alive.id.clone(),
5418        }];
5419        write_status_to(&home.join("daemon.json"), &status).unwrap();
5420
5421        // The abandoned seat left an open question behind: nobody is left to
5422        // read an answer once the run is failed, and this must not wait for
5423        // some later daemon startup's own sweep to notice that.
5424        let questions = Questions::at(home.join("questions"));
5425        let mut q = ask::Question::new(
5426            dead.id.clone(),
5427            "implement".to_owned(),
5428            "impl-A".to_owned(),
5429            "Which storage backend?".to_owned(),
5430            String::new(),
5431            vec!["SQLite".to_owned(), "Redis".to_owned()],
5432        );
5433        questions.put(&mut q).unwrap();
5434
5435        let abandoned = reclaim_abandoned_runs_with(
5436            &home,
5437            now,
5438            |pid| if pid == 4242 { Some(false) } else { None },
5439            |_| panic!("a query answering Dead outright needs no identity corroboration"),
5440        );
5441        assert_eq!(abandoned, vec![dead.id.clone()]);
5442
5443        let reloaded = read_run_under(&home, &dead.id);
5444        assert_eq!(reloaded.status, RunStatus::Failed);
5445        assert!(reloaded.active.is_empty());
5446        assert!(
5447            !questions.get(&q.id).unwrap().status.open(),
5448            "the failed run's own open question must be settled in the same pass"
5449        );
5450
5451        let still_alive = read_run_under(&home, &alive.id);
5452        assert_eq!(
5453            still_alive.status,
5454            RunStatus::Implementing,
5455            "a live daemon's claim protects it"
5456        );
5457        assert!(!still_alive.active.is_empty());
5458    }
5459
5460    /// The exact shape a review round flagged as broken: `magi serve` running
5461    /// in this same `home` scans *every* run on disk, including a manual
5462    /// `magi review` / `magi run` this daemon never started and that
5463    /// therefore claims no heartbeat of its own. Before this scan asked
5464    /// `liveness` rather than just `is_working_on`, a manual run whose active
5465    /// seat merely ran a little past its own timeout — the CLI finishing up,
5466    /// its result still being collected — got wiped and failed by a daemon
5467    /// that had nothing to do with it, out from under a process that was
5468    /// still very much running.
5469    #[test]
5470    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
5471        let dir = tempfile::tempdir().unwrap();
5472        let home = dir.path().to_path_buf();
5473        let now = Timestamp::now();
5474
5475        let mut manual = run_state(RunStatus::Reviewing);
5476        manual.id = "20260101-000000-manl".to_owned();
5477        manual.active.insert(
5478            "review-1".to_owned(),
5479            crate::run::ActiveSeat {
5480                node: "review".to_owned(),
5481                started_at: now - jiff::SignedDuration::new(21_000, 0),
5482                timeout_secs: 3_600,
5483                attempt: 0,
5484                task: None,
5485                command: None,
5486                index: None,
5487                total: None,
5488            },
5489        );
5490        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
5491        // but a real, still-running process: `liveness` must corroborate this
5492        // as `Live`, not read the missing daemon claim as death.
5493        manual.driver_pid = Some(4242);
5494        manual.driver_started_at = Some("2026-09-22T10:00:00Z".to_owned());
5495        manual.save_under(&home).unwrap();
5496
5497        let abandoned = reclaim_abandoned_runs_with(
5498            &home,
5499            now,
5500            |pid| if pid == 4242 { Some(true) } else { None },
5501            |pid| {
5502                if pid == 4242 {
5503                    Some("2026-09-22T10:00:00Z".to_owned())
5504                } else {
5505                    None
5506                }
5507            },
5508        );
5509        assert!(
5510            abandoned.is_empty(),
5511            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
5512        );
5513
5514        let reloaded = read_run_under(&home, &manual.id);
5515        assert_eq!(reloaded.status, RunStatus::Reviewing);
5516        assert!(!reloaded.active.is_empty());
5517    }
5518
5519    #[test]
5520    fn an_already_claimed_task_is_skipped_rather_than_failed() {
5521        let dir = tempfile::tempdir().unwrap();
5522        let queue = Queue::at(dir.path().to_path_buf());
5523        let mut only = task();
5524        queue.put(&mut only).unwrap();
5525
5526        let _elsewhere = queue.claim(&only.id).unwrap();
5527        let candidates = runnable(&queue);
5528        assert_eq!(candidates.len(), 1, "the task is still runnable");
5529        assert!(
5530            queue.claim(&candidates[0].id).is_err(),
5531            "the loop cannot take a claim somebody else holds"
5532        );
5533
5534        let after = queue.get(&only.id).unwrap();
5535        assert_eq!(after.status, TaskStatus::Queued);
5536        assert_eq!(
5537            after.attempts, 0,
5538            "losing the race is not an attempt at the task"
5539        );
5540        assert_eq!(after.last_error, None);
5541    }
5542
5543    #[test]
5544    fn the_status_file_round_trips_and_its_heartbeat_advances() {
5545        let dir = tempfile::tempdir().unwrap();
5546        let path = dir.path().join("daemon.json");
5547
5548        let mut status = Status::new();
5549        status.idle = false;
5550        status.completed = 7;
5551        status.current = vec![Current {
5552            task: "20260902-000000-t111".to_owned(),
5553            run: "20260902-000001-r111".to_owned(),
5554        }];
5555        write_status_to(&path, &status).unwrap();
5556        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5557        assert_eq!(first.schema, SCHEMA);
5558        assert_eq!(first.pid, std::process::id());
5559        assert!(!first.idle);
5560        assert_eq!(first.completed, 7);
5561        assert_eq!(first.current, status.current);
5562        assert!(
5563            !path.with_extension("json.tmp").exists(),
5564            "the temp file is renamed, not left behind"
5565        );
5566
5567        std::thread::sleep(Duration::from_millis(5));
5568        status.updated_at = Timestamp::now();
5569        status.polls = 3;
5570        write_status_to(&path, &status).unwrap();
5571        let second: Status =
5572            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5573        assert!(
5574            second.updated_at > first.updated_at,
5575            "a reader can only detect staleness if the heartbeat moves"
5576        );
5577        assert_eq!(
5578            second.started_at, first.started_at,
5579            "the start time is not a heartbeat"
5580        );
5581        assert_eq!(second.polls, 3);
5582    }
5583
5584    #[test]
5585    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
5586        let dir = tempfile::tempdir().unwrap();
5587
5588        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
5589
5590        let mut status = Status::new();
5591        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
5592        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5593        let stale = read_status(dir.path()).unwrap();
5594        assert!(
5595            !stale.running(Timestamp::now()),
5596            "a minute without a heartbeat is a dead daemon, not a busy one"
5597        );
5598        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
5599
5600        status.updated_at = Timestamp::now();
5601        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5602        let fresh = read_status(dir.path()).unwrap();
5603        assert!(fresh.running(Timestamp::now()));
5604    }
5605
5606    #[test]
5607    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
5608        let dir = tempfile::tempdir().unwrap();
5609        let now = Timestamp::now();
5610        let mine = "20260903-080619-01c2";
5611
5612        assert!(
5613            !is_working_on(dir.path(), mine, now),
5614            "no status file means nobody is working on anything"
5615        );
5616
5617        let mut status = Status::new();
5618        status.current = vec![Current {
5619            task: "20260903-080340-0167".to_owned(),
5620            run: mine.to_owned(),
5621        }];
5622        status.updated_at = now;
5623        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5624        assert!(is_working_on(dir.path(), mine, now));
5625        assert!(
5626            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
5627            "a daemon busy with one run is not working on another"
5628        );
5629
5630        // A killed daemon stops writing heartbeats but leaves the file behind
5631        // naming the run it died in. That run must not be undeletable forever.
5632        status.updated_at = now - jiff::SignedDuration::from_secs(600);
5633        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5634        assert!(
5635            !is_working_on(dir.path(), mine, now),
5636            "a stale heartbeat is a dead daemon, so its run is a leftover"
5637        );
5638    }
5639
5640    #[test]
5641    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
5642        let dir = tempfile::tempdir().unwrap();
5643        let now = Timestamp::now();
5644
5645        assert!(
5646            !is_working_on_short(dir.path(), "01c2", now),
5647            "no status file means nobody is working on anything"
5648        );
5649
5650        let mut status = Status::new();
5651        status.current = vec![Current {
5652            task: "20260903-080340-0167".to_owned(),
5653            run: "20260903-080619-01c2".to_owned(),
5654        }];
5655        status.updated_at = now;
5656        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5657        assert!(
5658            is_working_on_short(dir.path(), "01c2", now),
5659            "the run's short id is the last block of its full id"
5660        );
5661        assert!(
5662            !is_working_on_short(dir.path(), "3cbf", now),
5663            "a daemon busy with one worktree bay is not working on another"
5664        );
5665    }
5666
5667    #[test]
5668    fn a_newer_status_file_still_yields_a_reading() {
5669        let dir = tempfile::tempdir().unwrap();
5670        // A field this build has never heard of must not turn the reading into
5671        // nothing at all; that is the whole reason the reader is permissive.
5672        std::fs::write(
5673            dir.path().join("daemon.json"),
5674            serde_json::json!({
5675                "schema": 2,
5676                "updated_at": Timestamp::now().to_string(),
5677                "idle": true,
5678                "surprise": { "nested": [1, 2, 3] },
5679            })
5680            .to_string(),
5681        )
5682        .unwrap();
5683
5684        let reading = read_status(dir.path()).expect("a forward-compatible read");
5685        assert!(reading.running(Timestamp::now()));
5686        assert!(reading.idle);
5687        assert!(reading.current.is_empty());
5688    }
5689
5690    #[test]
5691    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
5692        // A daemon started before `current` became a list keeps writing this
5693        // shape on every heartbeat until it is restarted. A rolling upgrade
5694        // - a newer `magi web` or `magi doctor` reading an older `magi
5695        // serve`'s heartbeat - must still see the run it is on, not "no
5696        // daemon" from a type mismatch failing the whole struct.
5697        let dir = tempfile::tempdir().unwrap();
5698        std::fs::write(
5699            dir.path().join("daemon.json"),
5700            serde_json::json!({
5701                "schema": 1,
5702                "pid": 4242,
5703                "updated_at": Timestamp::now().to_string(),
5704                "idle": false,
5705                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
5706                "completed": 3,
5707                "polls": 9,
5708            })
5709            .to_string(),
5710        )
5711        .unwrap();
5712
5713        let reading = read_status(dir.path()).expect("an older shape must still parse");
5714        assert!(reading.running(Timestamp::now()));
5715        assert_eq!(
5716            reading.current,
5717            vec![Current {
5718                task: "20260902-140501-aaaa".to_owned(),
5719                run: "20260902-140502-bbbb".to_owned(),
5720            }]
5721        );
5722    }
5723
5724    #[test]
5725    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
5726        let dir = tempfile::tempdir().unwrap();
5727        std::fs::write(
5728            dir.path().join("daemon.json"),
5729            serde_json::json!({
5730                "schema": 1,
5731                "updated_at": Timestamp::now().to_string(),
5732                "idle": true,
5733                "current": null,
5734            })
5735            .to_string(),
5736        )
5737        .unwrap();
5738        let with_null = read_status(dir.path()).expect("null must still parse");
5739        assert!(with_null.current.is_empty());
5740
5741        std::fs::write(
5742            dir.path().join("daemon.json"),
5743            serde_json::json!({
5744                "schema": 1,
5745                "updated_at": Timestamp::now().to_string(),
5746                "idle": true,
5747            })
5748            .to_string(),
5749        )
5750        .unwrap();
5751        let absent = read_status(dir.path()).expect("a missing field must still parse");
5752        assert!(absent.current.is_empty());
5753    }
5754
5755    #[test]
5756    fn a_task_without_a_repository_runs_in_the_daemons_default() {
5757        let fallback = Path::new("/default");
5758        let mut blank = task();
5759        blank.repo = PathBuf::new();
5760        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
5761        let mut dot = task();
5762        dot.repo = PathBuf::from(".");
5763        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
5764        assert_eq!(
5765            repo_for(&task(), fallback),
5766            PathBuf::from("/repo"),
5767            "a task that names a repository keeps it"
5768        );
5769    }
5770
5771    #[test]
5772    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
5773        // Three seats said out loud. What `solo` promises is one candidate
5774        // *whatever the config asks for*, so the contrast has to be a number
5775        // this test owns - it used to be `Config::default()`'s, which became
5776        // 1 when one implementation became the default and left the two
5777        // halves of this test asserting the same thing.
5778        let mut solo_cfg = Config::default();
5779        solo_cfg.graph.candidates = 3;
5780        let mut solo_task = task();
5781        solo_task.solo = true;
5782        apply_solo(&mut solo_cfg, &solo_task);
5783        assert_eq!(solo_cfg.graph.candidates, 1);
5784
5785        let mut plain_cfg = Config::default();
5786        plain_cfg.graph.candidates = 3;
5787        let plain_task = task();
5788        assert!(!plain_task.solo);
5789        apply_solo(&mut plain_cfg, &plain_task);
5790        assert_eq!(
5791            plain_cfg.graph.candidates, 3,
5792            "a task that did not ask to run alone keeps the config's candidates"
5793        );
5794    }
5795
5796    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
5797        QuotaLoss {
5798            seat: seat.into(),
5799            node: "judge".into(),
5800            at: at.parse().unwrap(),
5801            reset: reset.map(str::to_string),
5802        }
5803    }
5804
5805    #[test]
5806    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
5807        let old: Vec<QuotaLoss> = (1..=4)
5808            .map(|i| {
5809                loss(
5810                    &format!("judge-{i}"),
5811                    "2026-09-23T05:23:00Z",
5812                    Some("2:40pm (Asia/Tokyo)"),
5813                )
5814            })
5815            .collect();
5816        let fresh = losses_this_attempt(&old, &old);
5817        assert!(fresh.is_empty());
5818        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
5819        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
5820    }
5821
5822    #[test]
5823    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
5824        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
5825        let now = Timestamp::now();
5826        let mut after = old.clone();
5827        after.push(loss("judge-2", &now.to_string(), None));
5828        let fresh = losses_this_attempt(&old, &after);
5829        assert_eq!(fresh, vec![after[1].clone()]);
5830        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
5831        assert_eq!(
5832            until,
5833            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
5834        );
5835    }
5836
5837    #[test]
5838    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
5839        // `recover_stall` removes judge-1's loss and the retry then hits quota
5840        // again: the vector is the same length, so an index diff sees nothing.
5841        let before = vec![
5842            loss("judge-1", "2026-09-23T05:23:00Z", None),
5843            loss("judge-2", "2026-09-23T05:24:00Z", None),
5844        ];
5845        let after = vec![
5846            loss("judge-2", "2026-09-23T05:24:00Z", None),
5847            loss("judge-1", "2026-09-24T01:00:00Z", None),
5848        ];
5849        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
5850    }
5851
5852    #[test]
5853    fn merge_overrides_are_parsed_or_refused() {
5854        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
5855        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
5856        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
5857        assert!(merge_mode("squash").is_err());
5858    }
5859
5860    #[test]
5861    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
5862        let now = Timestamp::now();
5863        let fallback = Duration::from_secs(300);
5864        let cap = Duration::from_secs(1800);
5865
5866        // No reset hint at all: the fallback.
5867        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
5868
5869        // A reset ten minutes out, well inside the cap: waited for exactly.
5870        let soon = now + jiff::SignedDuration::from_secs(600);
5871        assert_eq!(
5872            quota_wait(Some(soon), now, fallback, cap),
5873            Duration::from_secs(600)
5874        );
5875
5876        // A reset already in the past is not trusted: the fallback, not a
5877        // zero or negative wait that would spin the loop right back around.
5878        let past = now - jiff::SignedDuration::from_secs(60);
5879        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
5880
5881        // A reset further out than the cap is trusted for direction but not
5882        // for magnitude: a parsing slip must not sleep the loop for a day.
5883        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
5884        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
5885    }
5886
5887    #[test]
5888    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
5889        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5890
5891        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
5892        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
5893
5894        // Same clock reading, but it has already gone by today: read as
5895        // tomorrow's, since the CLI would not still be reporting a limit past
5896        // its own stated reset.
5897        let already_past =
5898            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
5899        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
5900
5901        assert!(
5902            parse_reset_hint("session limit reached", now, now).is_none(),
5903            "free text with no recognised shape is not guessed at"
5904        );
5905        assert!(
5906            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
5907            "an unresolvable zone name is not guessed at either"
5908        );
5909    }
5910
5911    #[test]
5912    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
5913        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5914
5915        let at = parse_reset_hint(
5916            "You've hit your usage limit. Visit \
5917             https://chatgpt.com/codex/settings/usage to purchase more \
5918             credits or try again at Sep 19th, 2026 5:10 PM.",
5919            now,
5920            now,
5921        )
5922        .expect("the codex reset wording is a recognised shape");
5923        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
5924
5925        // The month is explicit, so a date already earlier in the same
5926        // sentence-implied year than `now` is trusted as written rather than
5927        // rolled forward a year the way the bracketed shape rolls a
5928        // same-day clock reading to tomorrow.
5929        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
5930            .expect("an explicit year needs no rollover");
5931        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
5932
5933        assert!(
5934            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
5935            "a two-digit year is not the documented shape and is not guessed at"
5936        );
5937        assert!(
5938            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
5939            "a four-letter month name is not the documented three-letter abbreviation"
5940        );
5941        assert!(
5942            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
5943            "an explicit zone on the dated shape is a format nobody has \
5944             documented, and is refused rather than guessed at as UTC"
5945        );
5946    }
5947
5948    #[test]
5949    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
5950        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
5951        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
5952
5953        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
5954        assert_eq!(at.as_second() - recorded.as_second(), 3769);
5955
5956        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
5957        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
5958
5959        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
5960            assert!(
5961                parse_reset_hint(bad, now, recorded).is_none(),
5962                "{bad:?} must not be guessed at"
5963            );
5964        }
5965    }
5966
5967    /// A loop whose queue lives in a temp tree and whose poll interval is far
5968    /// longer than the test's patience, so anything that waits out a poll
5969    /// instead of noticing the stop fails rather than merely being slow.
5970    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
5971        let config = dir.join("magi.toml");
5972        std::fs::write(
5973            &config,
5974            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
5975        )
5976        .unwrap();
5977        let opts = Opts {
5978            poll: Duration::from_secs(30),
5979            config: Some(config),
5980            // The explicit fixture config keeps startup cleanup from reading
5981            // machine configuration. This fictional repository likewise
5982            // keeps any best-effort git cleanup away from this checkout.
5983            repo: dir.join("repo"),
5984            ..Opts::default()
5985        };
5986        // The status file goes in a directory that does not exist yet, so its
5987        // creation is itself evidence the loop published one. `worktrees`
5988        // must be just as fictional: the janitor reclaims worktrees under it
5989        // for real, and a test that let it fall through to
5990        // `crate::run::default_worktree_root()` would have it reclaim
5991        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
5992        // which is exactly what happened before this function took the
5993        // parameter at all.
5994        let home = dir.join("home");
5995        let worktrees = dir.join("wt");
5996        (
5997            opts,
5998            Queue::at(dir.join("queue")),
5999            home.join("daemon.json"),
6000            home,
6001            worktrees,
6002        )
6003    }
6004
6005    #[test]
6006    fn a_stop_is_idempotent_and_once_set_stays_set() {
6007        let stop = Stop::new();
6008        assert!(!stop.stopped());
6009
6010        stop.stop();
6011        assert!(stop.stopped());
6012        stop.stop();
6013        assert!(stop.stopped(), "a second stop is not a toggle");
6014
6015        let shared = stop.clone();
6016        assert!(
6017            shared.stopped(),
6018            "a clone is the same stop; that is how the loop and its caller share one"
6019        );
6020    }
6021
6022    #[test]
6023    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
6024        let stop = Stop::new();
6025        stop.enter();
6026        assert!(
6027            !stop.finishing(),
6028            "a busy loop nobody has asked to stop is just running"
6029        );
6030
6031        stop.stop();
6032        assert!(
6033            stop.finishing(),
6034            "a stop asked for mid-run has not landed until the run is settled"
6035        );
6036
6037        stop.exit();
6038        assert!(
6039            !stop.finishing(),
6040            "once the run is settled the stop has landed and there is nothing to finish"
6041        );
6042    }
6043
6044    #[test]
6045    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
6046        let stop = Stop::new();
6047        stop.enter();
6048        stop.enter();
6049        stop.stop();
6050        assert!(stop.finishing(), "two runs still in flight");
6051
6052        stop.exit();
6053        assert!(
6054            stop.finishing(),
6055            "one run finished, but a sibling is still working"
6056        );
6057
6058        stop.exit();
6059        assert!(
6060            !stop.finishing(),
6061            "the last run out is what actually lands the stop"
6062        );
6063    }
6064
6065    #[tokio::test]
6066    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
6067        let dir = tempfile::tempdir().unwrap();
6068        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6069        let stop = Stop::new();
6070        stop.stop();
6071
6072        let began = std::time::Instant::now();
6073        tokio::time::timeout(
6074            Duration::from_secs(2),
6075            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6076        )
6077        .await
6078        .expect("a stopped loop must return, not sit out its poll interval")
6079        .expect("the loop's own setup and teardown must not fail");
6080        assert!(
6081            began.elapsed() < opts.poll,
6082            "returned only after {:?}, which is a poll interval, not a stop",
6083            began.elapsed()
6084        );
6085    }
6086
6087    #[tokio::test]
6088    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
6089        let dir = tempfile::tempdir().unwrap();
6090        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6091        let stop = Stop::new();
6092
6093        // Asked for after the loop is already parked on its empty queue, which
6094        // is the case an operator tapping stop on a phone actually hits.
6095        let asker = {
6096            let stop = stop.clone();
6097            tokio::spawn(async move {
6098                tokio::time::sleep(Duration::from_millis(20)).await;
6099                stop.stop();
6100            })
6101        };
6102
6103        let began = std::time::Instant::now();
6104        tokio::time::timeout(
6105            Duration::from_secs(2),
6106            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6107        )
6108        .await
6109        .expect("a stop asked for while idle must wake the wait")
6110        .expect("the loop's own setup and teardown must not fail");
6111        asker.await.unwrap();
6112        assert!(
6113            began.elapsed() < opts.poll,
6114            "returned only after {:?}, so the stop waited on the sleep",
6115            began.elapsed()
6116        );
6117    }
6118
6119    #[tokio::test]
6120    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
6121        let dir = tempfile::tempdir().unwrap();
6122        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6123        let stop = Stop::new();
6124        stop.stop();
6125
6126        tokio::time::timeout(
6127            Duration::from_secs(2),
6128            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6129        )
6130        .await
6131        .expect("a stopped loop must return")
6132        .expect("the loop's own setup and teardown must not fail");
6133
6134        assert!(
6135            home.is_dir(),
6136            "the loop did publish a status file, so its removal is the teardown and not an absence"
6137        );
6138        assert!(
6139            !status_file.exists(),
6140            "a stopped loop clears its status file"
6141        );
6142        assert!(
6143            read_status(&home).is_none(),
6144            "a reader must see no daemon at all, not a heartbeat that merely stopped"
6145        );
6146    }
6147
6148    #[tokio::test]
6149    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
6150        let dir = tempfile::tempdir().unwrap();
6151        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6152        opts.once = true;
6153
6154        let mut settled = RunState::new(
6155            dir.path().join("repo"),
6156            "main".to_owned(),
6157            "abc1234".to_owned(),
6158            "fixture".to_owned(),
6159            Config::default(),
6160        );
6161        settled.status = RunStatus::Ready;
6162        let run_dir = home.join("runs").join(&settled.id);
6163        std::fs::create_dir_all(&run_dir).unwrap();
6164        std::fs::write(
6165            run_dir.join("run.json"),
6166            serde_json::to_string_pretty(&settled).unwrap(),
6167        )
6168        .unwrap();
6169        let questions = Questions::at(home.join("questions"));
6170        let mut question = ask::Question::new(
6171            settled.id.clone(),
6172            "review".to_owned(),
6173            "reviewer-1".to_owned(),
6174            "Continue?".to_owned(),
6175            String::new(),
6176            Vec::new(),
6177        );
6178        questions.put(&mut question).unwrap();
6179
6180        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
6181            .await
6182            .unwrap();
6183
6184        assert_eq!(
6185            questions.get(&question.id).unwrap().status,
6186            ask::QuestionStatus::Abandoned,
6187            "an empty --once drain still performs startup question cleanup"
6188        );
6189    }
6190
6191    #[test]
6192    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
6193        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6194
6195        assert!(
6196            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
6197            "never checked before: due at once"
6198        );
6199
6200        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
6201        assert!(
6202            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
6203            "well inside the interval: not due yet"
6204        );
6205
6206        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
6207        assert!(
6208            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
6209            "exactly at the edge: not yet due, same convention as `clean::due`"
6210        );
6211
6212        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
6213        assert!(
6214            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
6215            "past the interval: due again"
6216        );
6217    }
6218
6219    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
6220    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
6221    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
6222    /// and the congestion test below both need, and must not drift apart.
6223    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
6224        let config = dir.join("magi.toml");
6225        // A literal (single-quoted) TOML string, not a basic one: the cache
6226        // path is a Windows path full of backslashes, and a basic string
6227        // would have TOML try to interpret `\U` (from `\Users\...`) as a
6228        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
6229        // `{{ vars.cache }}` rendering documents.
6230        std::fs::write(
6231            &config,
6232            format!(
6233                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
6234                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
6235                cache_dir.display()
6236            ),
6237        )
6238        .unwrap();
6239        Opts {
6240            config: Some(config),
6241            repo: dir.join("repo"),
6242            ..Opts::default()
6243        }
6244    }
6245
6246    #[tokio::test]
6247    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
6248        let dir = tempfile::tempdir().unwrap();
6249        let home = dir.path().join("home");
6250        let cache_dir = dir.path().join("cache");
6251        std::fs::create_dir_all(&cache_dir).unwrap();
6252        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
6253        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
6254
6255        // Nobody has asked this daemon to stop, which is the ordinary case;
6256        // the skip that a stop buys is asserted by its own test below.
6257        let running = Stop::new();
6258        let mut last_checked = None;
6259        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6260        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
6261            .await;
6262        assert_eq!(
6263            crate::disk::dir_size(&cache_dir),
6264            0,
6265            "over the cap on the first check ever: pruned at once, no idle queue required"
6266        );
6267        assert_eq!(last_checked, Some(t0));
6268
6269        // A fresh oversized file lands, but the next check is not due yet.
6270        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
6271        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
6272        maybe_prune_cache_between_runs(
6273            &opts.repo,
6274            &opts,
6275            &home,
6276            &running,
6277            &mut last_checked,
6278            too_soon,
6279        )
6280        .await;
6281        assert_eq!(
6282            crate::disk::dir_size(&cache_dir),
6283            10,
6284            "too soon since the last check: left alone rather than rescanned every call"
6285        );
6286        assert_eq!(
6287            last_checked,
6288            Some(t0),
6289            "an idle check does not reset the clock"
6290        );
6291
6292        // Once the interval elapses, the same oversized cache is caught again.
6293        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
6294        maybe_prune_cache_between_runs(
6295            &opts.repo,
6296            &opts,
6297            &home,
6298            &running,
6299            &mut last_checked,
6300            due_again,
6301        )
6302        .await;
6303        assert_eq!(
6304            crate::disk::dir_size(&cache_dir),
6305            0,
6306            "due again: pruned back under the cap"
6307        );
6308    }
6309
6310    /// A stop must not queue behind housekeeping. The prune below is a
6311    /// synchronous walk of the whole cache with no await point in it, so a
6312    /// loop that entered it could not get back to its own `stopped()` test
6313    /// until the walk finished - and because no run is in flight at this
6314    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
6315    /// the stop had already landed. The idle branch has always made this same
6316    /// check before reaching `janitor`; the between-runs path makes it too.
6317    #[tokio::test]
6318    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
6319        let dir = tempfile::tempdir().unwrap();
6320        let home = dir.path().join("home");
6321        let cache_dir = dir.path().join("cache");
6322        std::fs::create_dir_all(&cache_dir).unwrap();
6323        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
6324        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
6325
6326        let stop = Stop::new();
6327        stop.stop();
6328        assert!(
6329            !stop.finishing(),
6330            "no run is in flight at a between-runs boundary, so nothing else \
6331             would tell the operator this stop had not taken effect yet"
6332        );
6333
6334        let mut last_checked = None;
6335        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6336        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
6337            .await;
6338        assert_eq!(
6339            crate::disk::dir_size(&cache_dir),
6340            10,
6341            "over its cap, and due for the first check ever, but a stop outranks \
6342             it: the cap is a standing policy the next start measures again"
6343        );
6344        assert_eq!(
6345            last_checked, None,
6346            "a check that never happened must not claim the interval"
6347        );
6348    }
6349
6350    /// The regression this whole change exists for: gate timeouts on runs
6351    /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
6352    /// GiB against a 10 GiB cap, because the operator's queue never had a
6353    /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
6354    /// `janitor` pass.
6355    ///
6356    /// Reproduced here with a task whose repository is never created:
6357    /// `Runner::start` fails at `git::toplevel` in a few milliseconds,
6358    /// spawning no agent CLI, so the task keeps failing and re-queuing
6359    /// (`Task::fail` with attempts still under the budget leaves it
6360    /// `Failed`, which `TaskStatus::runnable` still offers) for as long as
6361    /// the loop keeps polling - exactly the "queue with no idle moment"
6362    /// this task describes, produced without a real competition.
6363    #[tokio::test]
6364    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
6365        let dir = tempfile::tempdir().unwrap();
6366        let cache_dir = dir.path().join("cache");
6367        std::fs::create_dir_all(&cache_dir).unwrap();
6368        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
6369
6370        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
6371        opts.poll = Duration::from_millis(20);
6372        opts.max_attempts = 1_000;
6373
6374        let queue = Queue::at(dir.path().join("queue"));
6375        let mut t = Task::new(
6376            "x".to_owned(),
6377            "x".to_owned(),
6378            opts.repo.clone(),
6379            Source::Human,
6380        );
6381        queue.put(&mut t).unwrap();
6382
6383        let home = dir.path().join("home");
6384        let worktrees = dir.path().join("wt");
6385        let status_file = home.join("daemon.json");
6386        let stop = Stop::new();
6387        let stopper = {
6388            let stop = stop.clone();
6389            tokio::spawn(async move {
6390                tokio::time::sleep(Duration::from_millis(400)).await;
6391                stop.stop();
6392            })
6393        };
6394
6395        tokio::time::timeout(
6396            Duration::from_secs(10),
6397            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6398        )
6399        .await
6400        .expect("the loop must not hang on a queue that keeps producing failing work")
6401        .expect("the loop's own setup and teardown must not fail");
6402        stopper.await.unwrap();
6403
6404        let after = queue.get(&t.id).unwrap();
6405        assert!(
6406            after.attempts >= 2,
6407            "the harness must actually have retried more than once, or this is not \
6408             exercising a busy queue at all (got {} attempt(s))",
6409            after.attempts
6410        );
6411        assert!(
6412            after.status.runnable(),
6413            "still under its attempt budget: the queue never reached a natural idle \
6414             on its own, only the external stop ended the test"
6415        );
6416
6417        assert_eq!(
6418            crate::disk::dir_size(&cache_dir),
6419            0,
6420            "an oversized cache must not be left to grow unboundedly just because the \
6421             queue kept the loop busy the whole time"
6422        );
6423    }
6424
6425    #[test]
6426    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
6427        let dir = tempfile::tempdir().unwrap();
6428        let queue = Queue::at(dir.path().join("queue"));
6429        let questions = Questions::at(dir.path().join("questions"));
6430        let mut task = task();
6431        queue.put(&mut task).unwrap();
6432
6433        let mut task_question = ask::Question::new(
6434            task.id.clone(),
6435            crate::conduct::NODE.to_owned(),
6436            "conduct".to_owned(),
6437            "Which backend?".to_owned(),
6438            String::new(),
6439            Vec::new(),
6440        );
6441        questions.put(&mut task_question).unwrap();
6442        task.block(vec![task_question.id.clone()], None);
6443        queue.put(&mut task).unwrap();
6444
6445        let mut run_question = ask::Question::new(
6446            "20260101-000000-run1".to_owned(),
6447            "review".to_owned(),
6448            "reviewer-1".to_owned(),
6449            "Run question".to_owned(),
6450            String::new(),
6451            Vec::new(),
6452        );
6453        questions.put(&mut run_question).unwrap();
6454
6455        // A question from another node whose `run` happens to equal this
6456        // task's id — the same field, filled in for an unrelated reason. Only
6457        // `crate::conduct::NODE` questions use `run` as a task id; this one
6458        // must never be touched by this reconciliation, even after release.
6459        let mut coincidental = ask::Question::new(
6460            task.id.clone(),
6461            "review".to_owned(),
6462            "reviewer-1".to_owned(),
6463            "Unrelated review question".to_owned(),
6464            String::new(),
6465            Vec::new(),
6466        );
6467        questions.put(&mut coincidental).unwrap();
6468
6469        reconcile_task_questions(&queue, &questions);
6470        assert!(questions.get(&task_question.id).unwrap().status.open());
6471        assert!(questions.get(&run_question.id).unwrap().status.open());
6472        assert!(questions.get(&coincidental.id).unwrap().status.open());
6473
6474        task.release();
6475        queue.put(&mut task).unwrap();
6476        reconcile_task_questions(&queue, &questions);
6477        assert_eq!(
6478            questions.get(&task_question.id).unwrap().status,
6479            ask::QuestionStatus::Abandoned
6480        );
6481        assert!(
6482            questions.get(&run_question.id).unwrap().status.open(),
6483            "run questions remain the run janitor's responsibility"
6484        );
6485        assert!(
6486            questions.get(&coincidental.id).unwrap().status.open(),
6487            "a non-conductor question must not be abandoned just because its \
6488             run id coincides with a task id"
6489        );
6490    }
6491
6492    #[test]
6493    fn a_freshly_started_running_task_is_never_stalled() {
6494        let dir = tempfile::tempdir().unwrap();
6495        let mut t = task();
6496        t.start("run-1".to_owned());
6497        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
6498        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
6499        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
6500    }
6501
6502    #[test]
6503    fn a_long_running_task_with_no_live_daemon_is_stalled() {
6504        let dir = tempfile::tempdir().unwrap();
6505        let mut t = task();
6506        t.start("run-1".to_owned());
6507        t.updated_at = Timestamp::now()
6508            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6509        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
6510        assert_eq!(
6511            stalled_tasks(
6512                &Queue::at(dir.path().join("q")),
6513                dir.path(),
6514                Timestamp::now()
6515            )
6516            .len(),
6517            0,
6518            "the task was never written to this queue"
6519        );
6520    }
6521
6522    #[test]
6523    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
6524        let dir = tempfile::tempdir().unwrap();
6525        let mut t = task();
6526        t.id = "20260903-080340-0167".to_owned();
6527        t.start("20260903-080619-01c2".to_owned());
6528        t.updated_at = Timestamp::now()
6529            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6530
6531        let mut status = Status::new();
6532        status.current = vec![Current {
6533            task: t.id.clone(),
6534            run: "20260903-080619-01c2".to_owned(),
6535        }];
6536        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6537
6538        assert!(
6539            !is_stalled(&t, dir.path(), Timestamp::now()),
6540            "a live daemon's own heartbeat rules out stalled, however long the task has run"
6541        );
6542    }
6543
6544    /// Rewrite a task's `updated_at` on disk directly, bypassing
6545    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
6546    /// a fixture look like it has genuinely been `running` for a while.
6547    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
6548        let path = queue.path_of(id);
6549        let body = std::fs::read_to_string(&path).unwrap();
6550        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
6551        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
6552        v["updated_at"] = serde_json::Value::String(old.to_string());
6553        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
6554    }
6555
6556    #[test]
6557    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
6558        // The realistic `poll()` ordering, not `is_stalled` in isolation:
6559        // `reclaim_orphaned_running` runs first, on every poll, and settles
6560        // any `running` task whose claim it can actually take. For most
6561        // crashes that is immediate - a dead pid is proof enough for
6562        // `sweep_stale_claims` to drop the lock the same tick, and the very
6563        // next claim attempt succeeds. But a lock whose pid cannot be parsed
6564        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
6565        // `sweep_stale_claims`'s own doc), so the lock - and the claim
6566        // failure behind it - can legitimately outlive many polls. This is
6567        // exactly the gap `stalled_tasks` exists to surface well before that
6568        // six-hour sweep would: reclaim leaves the task `running`, and it
6569        // must still reach the conductor as stalled.
6570        let dir = tempfile::tempdir().unwrap();
6571        let queue = Queue::at(dir.path().join("queue"));
6572        let home = dir.path().join("home");
6573
6574        let mut t = task();
6575        t.id = "20260101-000001-lock".to_owned();
6576        t.start("run-1".to_owned());
6577        queue.put(&mut t).unwrap();
6578        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6579        std::fs::write(
6580            dir.path().join("queue").join(format!("{}.lock", t.id)),
6581            "not a pid",
6582        )
6583        .unwrap();
6584
6585        let now = Timestamp::now();
6586        assert!(
6587            reclaim_orphaned_running(&queue, 2).is_empty(),
6588            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
6589             and reclaim must leave the task alone"
6590        );
6591        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6592
6593        let stalled = stalled_tasks(&queue, &home, now);
6594        assert_eq!(
6595            stalled.len(),
6596            1,
6597            "reclaim's inability to claim it yet must not hide it from the conductor"
6598        );
6599        assert_eq!(stalled[0].id, t.id);
6600    }
6601
6602    #[test]
6603    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
6604        let dir = tempfile::tempdir().unwrap();
6605        crate::run::set_home(dir.path().join("run-home"));
6606        let queue = Queue::at(dir.path().join("queue"));
6607        let home = dir.path().join("home");
6608        let questions = Questions::at(dir.path().join("questions"));
6609
6610        let mut t = task();
6611        t.id = "20260101-000003-dead".to_owned();
6612        t.start("missing-run".to_owned());
6613        queue.put(&mut t).unwrap();
6614        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6615
6616        // This is the real poll ordering: retain the deterministic stalled
6617        // input before a claim proves the owner is gone and reclaims it.
6618        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6619        assert_eq!(
6620            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
6621            [&t.id]
6622        );
6623        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
6624        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
6625
6626        // Reclaim drops its guard before conductor decisions are applied, so
6627        // the decision for the captured stalled input has a real write path.
6628        crate::conduct::apply(
6629            &queue,
6630            &questions,
6631            &crate::conduct::Verdict {
6632                decisions: vec![crate::conduct::Decision {
6633                    id: t.id.clone(),
6634                    recovery: Some(crate::conduct::Recovery::Requeue),
6635                    ..crate::conduct::Decision::default()
6636                }],
6637            },
6638        )
6639        .unwrap();
6640        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
6641    }
6642
6643    #[test]
6644    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
6645        let dir = tempfile::tempdir().unwrap();
6646        let queue = Queue::at(dir.path().join("queue"));
6647        let home = dir.path().join("home");
6648
6649        let mut fresh = task();
6650        fresh.id = "20260101-000001-aaaa".to_owned();
6651        fresh.start("run-1".to_owned());
6652        queue.put(&mut fresh).unwrap();
6653
6654        let mut old = task();
6655        old.id = "20260101-000002-bbbb".to_owned();
6656        old.start("run-2".to_owned());
6657        queue.put(&mut old).unwrap();
6658        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
6659
6660        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6661        assert_eq!(stalled.len(), 1);
6662        assert_eq!(stalled[0].id, old.id);
6663    }
6664
6665    #[test]
6666    fn queued_and_finished_task_views_partition_by_status() {
6667        let dir = tempfile::tempdir().unwrap();
6668        let queue = Queue::at(dir.path().join("queue"));
6669
6670        let mut queued = task();
6671        queued.id = "20260101-000001-aaaa".to_owned();
6672        queue.put(&mut queued).unwrap();
6673
6674        let mut failed = task();
6675        failed.id = "20260101-000002-bbbb".to_owned();
6676        failed.start("run-1".to_owned());
6677        failed.fail("gate red", 5);
6678        queue.put(&mut failed).unwrap();
6679
6680        let mut held = task();
6681        held.id = "20260101-000003-cccc".to_owned();
6682        held.hold_machine(None);
6683        queue.put(&mut held).unwrap();
6684
6685        let mut running = task();
6686        running.id = "20260101-000004-dddd".to_owned();
6687        running.start("run-2".to_owned());
6688        queue.put(&mut running).unwrap();
6689
6690        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
6691        assert_eq!(queued_ids, [queued.id.clone()]);
6692
6693        let mut finished_ids: Vec<String> =
6694            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
6695        finished_ids.sort_unstable();
6696        let mut want = vec![failed.id.clone(), held.id.clone()];
6697        want.sort_unstable();
6698        assert_eq!(finished_ids, want);
6699    }
6700
6701    #[test]
6702    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
6703        let dir = tempfile::tempdir().unwrap();
6704        let queue = Queue::at(dir.path().join("queue"));
6705        let questions = ask::Questions::at(dir.path().join("questions"));
6706
6707        let mut dep = task();
6708        dep.id = "20260101-000001-dep0".to_owned();
6709        dep.succeed();
6710        queue.put(&mut dep).unwrap();
6711
6712        let mut still_going = task();
6713        still_going.id = "20260101-000002-dep1".to_owned();
6714        queue.put(&mut still_going).unwrap();
6715
6716        let mut blocked = task();
6717        blocked.id = "20260101-000003-main".to_owned();
6718        blocked.block(
6719            vec![dep.id.clone(), still_going.id.clone()],
6720            Some("waits on both".to_owned()),
6721        );
6722        queue.put(&mut blocked).unwrap();
6723
6724        resolve_blockers(&queue, &questions);
6725
6726        let after = queue.get(&blocked.id).unwrap();
6727        assert_eq!(
6728            after.status,
6729            TaskStatus::Blocked,
6730            "one dependency is still outstanding"
6731        );
6732        assert_eq!(after.blocked_by, [still_going.id.clone()]);
6733    }
6734
6735    #[test]
6736    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
6737        let dir = tempfile::tempdir().unwrap();
6738        let queue = Queue::at(dir.path().join("queue"));
6739        let questions = ask::Questions::at(dir.path().join("questions"));
6740
6741        let mut q = crate::ask::Question::new(
6742            "20260101-000001-main".to_owned(),
6743            crate::conduct::NODE.to_owned(),
6744            "conduct".to_owned(),
6745            "Which backend?".to_owned(),
6746            String::new(),
6747            Vec::new(),
6748        );
6749        questions.put(&mut q).unwrap();
6750        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
6751            .unwrap();
6752        questions.put(&mut q).unwrap();
6753
6754        let mut blocked = task();
6755        blocked.id = "20260101-000001-main".to_owned();
6756        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
6757        queue.put(&mut blocked).unwrap();
6758
6759        resolve_blockers(&queue, &questions);
6760
6761        let after = queue.get(&blocked.id).unwrap();
6762        assert_eq!(
6763            after.status,
6764            TaskStatus::Queued,
6765            "the only blocker resolved"
6766        );
6767        assert_eq!(after.answers.len(), 1);
6768        assert_eq!(after.answers[0].question, "Which backend?");
6769        assert_eq!(after.answers[0].answer, "SQLite");
6770
6771        // And the run this task starts next is told about it.
6772        let instruction = instruction_for(&after);
6773        assert!(instruction.contains("Which backend?"));
6774        assert!(instruction.contains("SQLite"));
6775    }
6776
6777    #[test]
6778    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
6779        // Reproduces the reported bug (task 3958): a task held out of
6780        // attempts, blocked on a `crate::conduct` follow-up question, must
6781        // come back `held` once that question is answered - never `queued`,
6782        // whatever the answer said - or it silently re-enters the
6783        // competition queue with its attempts already exhausted.
6784        let dir = tempfile::tempdir().unwrap();
6785        let queue = Queue::at(dir.path().join("queue"));
6786        let questions = ask::Questions::at(dir.path().join("questions"));
6787
6788        let mut q = crate::ask::Question::new(
6789            "20260101-000001-main".to_owned(),
6790            crate::conduct::NODE.to_owned(),
6791            "conduct".to_owned(),
6792            "How should this be handled?".to_owned(),
6793            String::new(),
6794            Vec::new(),
6795        );
6796        questions.put(&mut q).unwrap();
6797        q.answer(crate::ask::Answer::Text(
6798            "leave it held, a human will look at it later".to_owned(),
6799        ))
6800        .unwrap();
6801        questions.put(&mut q).unwrap();
6802
6803        let mut held = task();
6804        held.id = "20260101-000001-main".to_owned();
6805        held.hold_machine(Some("out of attempts".to_owned()));
6806        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
6807        queue.put(&mut held).unwrap();
6808
6809        resolve_blockers(&queue, &questions);
6810
6811        let after = queue.get(&held.id).unwrap();
6812        assert_eq!(after.status, TaskStatus::Held);
6813        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
6814        assert_eq!(
6815            after.answers[0].answer,
6816            "leave it held, a human will look at it later"
6817        );
6818    }
6819
6820    #[test]
6821    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
6822        // Reproduces the reported bug: a task blocked on a task id that was
6823        // removed (`magi task rm`, or deleted by hand) can never see that id
6824        // reach `Done`, so the ordinary per-id loop has nothing to notice and
6825        // would otherwise leave the task `blocked` forever with no way for an
6826        // operator to find out why.
6827        let dir = tempfile::tempdir().unwrap();
6828        let queue = Queue::at(dir.path().join("queue"));
6829        let questions = ask::Questions::at(dir.path().join("questions"));
6830
6831        let mut still_going = task();
6832        still_going.id = "20260101-000002-dep1".to_owned();
6833        queue.put(&mut still_going).unwrap();
6834
6835        let mut blocked = task();
6836        blocked.id = "20260101-000003-main".to_owned();
6837        blocked.block(
6838            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
6839            Some("waits on both".to_owned()),
6840        );
6841        queue.put(&mut blocked).unwrap();
6842
6843        resolve_blockers(&queue, &questions);
6844
6845        let after = queue.get(&blocked.id).unwrap();
6846        assert_eq!(
6847            after.status,
6848            TaskStatus::Held,
6849            "a missing dependency must not leave the task blocked forever"
6850        );
6851        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
6852        assert!(after.blocked_by.is_empty());
6853        let reason = after.hold_reason.as_deref().unwrap_or_default();
6854        assert!(
6855            reason.contains("20260101-000001-gone"),
6856            "the missing id must be named so an operator can tell what happened: {reason}"
6857        );
6858        assert!(
6859            reason.contains(&still_going.id),
6860            "the still-valid dependency must not silently vanish from the record: {reason}"
6861        );
6862    }
6863
6864    #[test]
6865    fn instruction_for_is_unchanged_without_any_answers() {
6866        let t = task();
6867        assert_eq!(instruction_for(&t), t.instruction);
6868    }
6869
6870    #[test]
6871    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
6872        let dir = tempfile::tempdir().unwrap();
6873        let q = Queue::at(dir.path().join("queue"));
6874        let src = dir.path().join("shot.png");
6875        std::fs::write(&src, "x").unwrap();
6876        let mut t = task();
6877        q.attach(&mut t, &[src]).unwrap();
6878        let paths = task_attachments(&q, &t).unwrap();
6879        assert_eq!(paths.len(), 1);
6880        assert!(paths[0].is_absolute() && paths[0].is_file());
6881        std::fs::remove_file(&paths[0]).unwrap();
6882        let err = task_attachments(&q, &t).unwrap_err().to_string();
6883        assert!(err.contains("shot.png"), "{err}");
6884    }
6885
6886    #[test]
6887    fn resumed_instruction_is_unchanged_without_any_answers() {
6888        let t = task();
6889        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
6890    }
6891
6892    #[test]
6893    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
6894        let mut t = task();
6895        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6896        // The run's own instruction on disk predates the answer: it is the
6897        // plain original text `Runner::start` saved before the operator was
6898        // ever asked anything.
6899        let old = t.instruction.clone();
6900
6901        let refreshed = resumed_instruction(&old, &t);
6902        assert!(refreshed.starts_with(&old), "the original text is kept");
6903        assert!(refreshed.contains("Which backend?"));
6904        assert!(refreshed.contains("SQLite"));
6905    }
6906
6907    #[test]
6908    fn resumed_instruction_keeps_an_original_answers_heading() {
6909        let mut t = task();
6910        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
6911        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6912
6913        let refreshed = resumed_instruction(&t.instruction, &t);
6914
6915        assert!(
6916            refreshed.starts_with(&t.instruction),
6917            "an answers heading in the original instruction is not the appended block"
6918        );
6919        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
6920        assert!(refreshed.contains("Which backend?"));
6921        assert!(refreshed.contains("SQLite"));
6922
6923        let repeated = resumed_instruction(&refreshed, &t);
6924        assert_eq!(
6925            repeated, refreshed,
6926            "only the final appended block is refreshed"
6927        );
6928    }
6929
6930    #[test]
6931    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
6932        let mut t = task();
6933        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6934
6935        // A first resume appends the block; a second resume of the same run,
6936        // with no new answer in between, must reproduce exactly the same
6937        // text rather than appending the block a second time.
6938        let once = resumed_instruction(&t.instruction, &t);
6939        let twice = resumed_instruction(&once, &t);
6940        assert_eq!(once, twice);
6941        assert_eq!(once.matches("Which backend?").count(), 1);
6942
6943        // A later answer replaces the block wholesale rather than growing it.
6944        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
6945        let refreshed = resumed_instruction(&once, &t);
6946        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
6947        assert!(refreshed.contains("Which backend?"));
6948        assert!(refreshed.contains("Which cache?"));
6949    }
6950
6951    #[test]
6952    fn prepare_instruction_covers_all_three_starters() {
6953        let mut t = task();
6954        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6955
6956        // Start: a fresh run gets the task text plus every answer so far —
6957        // exactly `instruction_for`.
6958        assert_eq!(
6959            prepare_instruction(&Starter::Start, None, &t),
6960            Some(instruction_for(&t))
6961        );
6962
6963        // Resume: the run's prior instruction is refreshed with the answer,
6964        // not discarded and not left stale.
6965        let old = t.instruction.clone();
6966        assert_eq!(
6967            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
6968            Some(resumed_instruction(&old, &t))
6969        );
6970
6971        // Review: a review-only pass builds its own instruction from the
6972        // branch's history in `crate::graph`, with no task statement at all -
6973        // this boundary must leave it alone.
6974        assert_eq!(
6975            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
6976            None
6977        );
6978    }
6979
6980    #[test]
6981    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
6982        assert_eq!(
6983            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
6984            Starter::Review("magi/eba2/A".to_owned())
6985        );
6986    }
6987
6988    #[test]
6989    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
6990        assert_eq!(
6991            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
6992            Starter::Start,
6993            "a vanished review branch must not fall back to resuming the old run either"
6994        );
6995    }
6996
6997    #[test]
6998    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
6999        assert_eq!(
7000            choose_starter(None, false, Some("some-run")),
7001            Starter::Resume("some-run".to_owned())
7002        );
7003        assert_eq!(choose_starter(None, false, None), Starter::Start);
7004    }
7005
7006    #[test]
7007    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
7008        let mut released = task();
7009        released.start("stalled-run".to_owned());
7010        released.requeue();
7011        let unfinished = (!released.fresh_start)
7012            .then(|| Some("stalled-run".to_owned()))
7013            .flatten();
7014        assert_eq!(
7015            choose_starter(None, false, unfinished.as_deref()),
7016            Starter::Start,
7017            "release keeps run history but must not resume it"
7018        );
7019        assert_eq!(released.runs, ["stalled-run"]);
7020    }
7021
7022    #[test]
7023    fn an_ordinary_release_keeps_a_resumable_run_available() {
7024        let mut released = task();
7025        released.start("stalled-run".to_owned());
7026        released.release();
7027        let unfinished = (!released.fresh_start)
7028            .then(|| Some("stalled-run".to_owned()))
7029            .flatten();
7030        assert_eq!(
7031            choose_starter(None, false, unfinished.as_deref()),
7032            Starter::Resume("stalled-run".to_owned()),
7033            "manual release must preserve the normal resume path"
7034        );
7035    }
7036
7037    #[test]
7038    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
7039        let mut state = run_state(RunStatus::Blocked);
7040        state.config.graph.review_rounds = 3;
7041        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
7042        assert!(exhausted_review_budget(&state));
7043
7044        // One round still unused: resuming can still ask a reviewer something.
7045        state.reviews.pop();
7046        assert!(!exhausted_review_budget(&state));
7047
7048        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
7049        // count: only a `Blocked` run re-enters the review loop on resume.
7050        let mut stalled = run_state(RunStatus::Stalled);
7051        stalled.config.graph.review_rounds = 1;
7052        stalled.reviews = vec![review_round(1)];
7053        assert!(!exhausted_review_budget(&stalled));
7054    }
7055
7056    fn review_round(round: usize) -> crate::run::ReviewRound {
7057        crate::run::ReviewRound {
7058            round,
7059            head: "deadbeef".to_owned(),
7060            verified_head: None,
7061            verified_at: None,
7062            reviews: Vec::new(),
7063            e2e: Vec::new(),
7064            verify_retried: false,
7065            e2e_deferred: false,
7066            e2e_defer_reason: None,
7067            fix: None,
7068            blocking: 0,
7069            answered: 1,
7070            expected: 1,
7071            clean: false,
7072            progressed: true,
7073            vote_split: false,
7074            reconsideration: Vec::new(),
7075            verdict: None,
7076        }
7077    }
7078
7079    #[test]
7080    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
7081        let mut run = RunState::new(
7082            PathBuf::from("/repo"),
7083            "main".to_owned(),
7084            "abc1234def".to_owned(),
7085            "add retries".to_owned(),
7086            Config::default(),
7087        );
7088        run.status = RunStatus::Judging;
7089        run.parked = true;
7090        let mut task = Task::new(
7091            "add retries".to_owned(),
7092            "add retries".to_owned(),
7093            PathBuf::from("/repo"),
7094            crate::queue::Source::Human,
7095        );
7096        task.status = TaskStatus::Failed;
7097        task.runs = vec![run.id.clone()];
7098        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
7099        assert!(with(&task, &run), "parked after judging is the case");
7100
7101        let mut not_parked = run.clone();
7102        not_parked.parked = false;
7103        not_parked.status = RunStatus::Stalled;
7104        assert!(!with(&task, &not_parked), "a stall is the conductor's");
7105
7106        let mut fresh = task.clone();
7107        fresh.fresh_start = true;
7108        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
7109
7110        let mut review = task.clone();
7111        review.review_branch = Some("magi/x/A".to_owned());
7112        assert!(!with(&review, &run), "review is ranked before resume");
7113
7114        let mut held = task.clone();
7115        held.status = TaskStatus::Held;
7116        assert!(!with(&held, &run), "a hold stays visible to the conductor");
7117
7118        let mut released = run.clone();
7119        released.released_to = Some("20260901-000000-new1".to_owned());
7120        assert!(!with(&task, &released), "nothing left to resume into");
7121
7122        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
7123            "unreadable"
7124        )));
7125    }
7126
7127    #[test]
7128    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
7129        let mut released = RunState::new(
7130            PathBuf::from("/repo"),
7131            "main".to_owned(),
7132            "abc1234def".to_owned(),
7133            "add retries".to_owned(),
7134            Config::default(),
7135        );
7136        released.status = RunStatus::Blocked;
7137        assert_eq!(
7138            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
7139            Some(released.id.clone())
7140        );
7141        released.released_to = Some("20260901-000000-new1".to_owned());
7142        assert_eq!(
7143            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
7144            None,
7145            "there is nothing left to resume it into"
7146        );
7147    }
7148
7149    #[test]
7150    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
7151        // Mirrors the failure this exists to close: a task's last run ended
7152        // `Blocked` with the review budget spent, `crate::conduct` chose
7153        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
7154        // evidence), and without this check `attempt` would go on treating
7155        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
7156        // review loop iterates zero times over an already-spent budget, so
7157        // the resumed run settles right back to `Blocked` having asked nobody
7158        // anything, and `Requeue`'s promised fresh competition never happens.
7159        let mut exhausted = RunState::new(
7160            PathBuf::from("/repo"),
7161            "main".to_owned(),
7162            "abc1234def".to_owned(),
7163            "add retries".to_owned(),
7164            Config::default(),
7165        );
7166        exhausted.status = RunStatus::Blocked;
7167        exhausted.config.graph.review_rounds = 1;
7168        exhausted.reviews = vec![review_round(1)];
7169
7170        assert_eq!(
7171            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
7172            None,
7173            "an exhausted `Blocked` run must not be offered as resumable"
7174        );
7175
7176        // A `Blocked` run with rounds still unused is genuinely worth
7177        // resuming, and must still be found.
7178        let mut has_budget_left = RunState::new(
7179            PathBuf::from("/repo"),
7180            "main".to_owned(),
7181            "abc1234def".to_owned(),
7182            "add retries".to_owned(),
7183            Config::default(),
7184        );
7185        has_budget_left.status = RunStatus::Blocked;
7186        has_budget_left.config.graph.review_rounds = 3;
7187        has_budget_left.reviews = vec![review_round(1)];
7188
7189        assert_eq!(
7190            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
7191                Ok(has_budget_left.clone())
7192            }),
7193            Some(has_budget_left.id.clone())
7194        );
7195    }
7196
7197    #[test]
7198    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
7199        // A task whose history holds an *older* run that still looks
7200        // resumable (say, a competition `Runner::review` was started
7201        // alongside after that older run went `Stalled`) and a *newest* run
7202        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
7203        // on this task must mean a fresh competition — falling back to the
7204        // stale, superseded `Stalled` run instead would resurrect history
7205        // nothing asked to revisit and silently defeat the requeue.
7206        let mut older_stalled = RunState::new(
7207            PathBuf::from("/repo"),
7208            "main".to_owned(),
7209            "abc1234def".to_owned(),
7210            "add retries".to_owned(),
7211            Config::default(),
7212        );
7213        older_stalled.status = RunStatus::Stalled;
7214
7215        let mut newest_exhausted = RunState::new(
7216            PathBuf::from("/repo"),
7217            "main".to_owned(),
7218            "abc1234def".to_owned(),
7219            "add retries".to_owned(),
7220            Config::default(),
7221        );
7222        newest_exhausted.status = RunStatus::Blocked;
7223        newest_exhausted.config.graph.review_rounds = 1;
7224        newest_exhausted.reviews = vec![review_round(1)];
7225
7226        assert_eq!(
7227            unfinished_run_with(
7228                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
7229                "t",
7230                |_| Ok(newest_exhausted.clone())
7231            ),
7232            None,
7233            "the newest run is exhausted, so nothing here is worth resuming - \
7234             least of all the older, already-superseded run"
7235        );
7236    }
7237
7238    #[test]
7239    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
7240        assert_eq!(
7241            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
7242                Err(anyhow::anyhow!("fixture is absent"))
7243            }),
7244            None
7245        );
7246    }
7247
7248    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
7249        let mut q = ask::Question::new(
7250            run.to_owned(),
7251            "implement".to_owned(),
7252            "impl-A".to_owned(),
7253            "continue?".to_owned(),
7254            String::new(),
7255            vec!["resume で続行する".to_owned(), "other".to_owned()],
7256        );
7257        q.actions.insert("resume で続行する".to_owned(), action);
7258        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
7259            .unwrap();
7260        q
7261    }
7262
7263    fn held_task_with(run: &str) -> Task {
7264        let mut t = task();
7265        t.runs = vec![run.to_owned()];
7266        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
7267        t
7268    }
7269
7270    fn resume_action(run: &str) -> ask::ChoiceAction {
7271        ask::ChoiceAction::Resume { run: run.into() }
7272    }
7273
7274    #[test]
7275    fn decide_action_resumes_only_the_latest_resumable_run() {
7276        let t = held_task_with("r1");
7277        let q = action_question("r1", resume_action("r1"));
7278        let load = |s: RunState| move |_: &str| Ok(s);
7279        assert_eq!(
7280            decide_action(&t, &q, load(run_state(RunStatus::Blocked))),
7281            ActionDecision::Resume("r1".into())
7282        );
7283        // Not the latest run of the task.
7284        let q_other = action_question("r1", resume_action("r0"));
7285        assert!(matches!(
7286            decide_action(&t, &q_other, load(run_state(RunStatus::Blocked))),
7287            ActionDecision::Refuse(_)
7288        ));
7289        // A finished run cannot make progress.
7290        assert!(matches!(
7291            decide_action(&t, &q, load(run_state(RunStatus::Ready))),
7292            ActionDecision::Refuse(_)
7293        ));
7294        // A released one either.
7295        let mut released = run_state(RunStatus::Blocked);
7296        released.released_to = Some("elsewhere".into());
7297        assert!(matches!(
7298            decide_action(&t, &q, load(released)),
7299            ActionDecision::Refuse(_)
7300        ));
7301        // Unreadable state is a refusal, never a fresh competition.
7302        assert!(matches!(
7303            decide_action(&t, &q, |_: &str| bail!("gone")),
7304            ActionDecision::Refuse(_)
7305        ));
7306    }
7307
7308    #[test]
7309    fn decide_action_ignores_a_question_about_an_earlier_run() {
7310        let mut t = held_task_with("r1");
7311        t.runs.push("r2".to_owned());
7312        let never = |_: &str| -> Result<RunState> { bail!("not read") };
7313        assert_eq!(
7314            decide_action(&t, &action_question("r1", ask::ChoiceAction::Done), never),
7315            ActionDecision::Stale
7316        );
7317    }
7318
7319    #[test]
7320    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
7321        let mut t = held_task_with("r1");
7322        let never = |_: &str| -> Result<RunState> { bail!("not read") };
7323        assert_eq!(
7324            decide_action(
7325                &t,
7326                &action_question("r1", ask::ChoiceAction::Requeue),
7327                never
7328            ),
7329            ActionDecision::Requeue
7330        );
7331        let done_q = action_question("r1", ask::ChoiceAction::Done);
7332        assert_eq!(decide_action(&t, &done_q, never), ActionDecision::Done);
7333        t.mark_action_applied(&done_q.id);
7334        assert_eq!(decide_action(&t, &done_q, never), ActionDecision::Skip);
7335
7336        // A plain answer (no action for that label) does nothing.
7337        let mut plain = action_question("r1", ask::ChoiceAction::Done);
7338        plain.actions.clear();
7339        assert_eq!(
7340            decide_action(&held_task_with("r1"), &plain, never),
7341            ActionDecision::Skip
7342        );
7343        // A running task is left alone.
7344        let mut running = held_task_with("r1");
7345        running.status = TaskStatus::Running;
7346        assert_eq!(
7347            decide_action(
7348                &running,
7349                &action_question("r1", ask::ChoiceAction::Done),
7350                never
7351            ),
7352            ActionDecision::Skip
7353        );
7354    }
7355
7356    #[test]
7357    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
7358        let dir = tempfile::tempdir().unwrap();
7359        let queue = Queue::at(dir.path().join("queue"));
7360        let questions = Questions::at(dir.path().join("questions"));
7361        let home = dir.path().join("home");
7362        let mut state = run_state(RunStatus::Blocked);
7363        state.id = "20260101-000000-act1".to_owned();
7364        state.save_under(&home).unwrap();
7365
7366        let mut t = held_task_with(&state.id);
7367        queue.put(&mut t).unwrap();
7368        let mut q = action_question(&state.id, resume_action(&state.id));
7369        questions.put(&mut q).unwrap();
7370
7371        apply_choice_actions(&queue, &questions, &home);
7372        let after = queue.get(&t.id).unwrap();
7373        assert_eq!(after.status, TaskStatus::Queued);
7374        assert!(!after.fresh_start);
7375        assert!(after.action_applied(&q.id));
7376        let pin = after.resume_override.clone().unwrap();
7377        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
7378        assert!(pin.forced);
7379
7380        // Held again later: the same answer does not release it a second time.
7381        let mut again = queue.get(&t.id).unwrap();
7382        again.hold_machine(Some("later".into()));
7383        queue.put(&mut again).unwrap();
7384        apply_choice_actions(&queue, &questions, &home);
7385        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7386    }
7387
7388    #[test]
7389    fn an_answer_the_waiter_already_delivered_is_not_acted_on_again() {
7390        let dir = tempfile::tempdir().unwrap();
7391        let queue = Queue::at(dir.path().join("queue"));
7392        let questions = Questions::at(dir.path().join("questions"));
7393        let home = dir.path().join("home");
7394        let mut state = run_state(RunStatus::Blocked);
7395        state.id = "20260101-000000-act2".to_owned();
7396        state.save_under(&home).unwrap();
7397
7398        let mut t = held_task_with(&state.id);
7399        queue.put(&mut t).unwrap();
7400        let mut q = action_question(&state.id, resume_action(&state.id));
7401        q.answer_delivered = true;
7402        questions.put(&mut q).unwrap();
7403
7404        apply_choice_actions(&queue, &questions, &home);
7405        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7406
7407        // Undelivered: the daemon takes the delivery itself, exactly once.
7408        let mut q2 = action_question(&state.id, resume_action(&state.id));
7409        questions.put(&mut q2).unwrap();
7410        apply_choice_actions(&queue, &questions, &home);
7411        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
7412        assert!(questions.get(&q2.id).unwrap().answer_delivered);
7413    }
7414}