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