Skip to main content

magi/
daemon.rs

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