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