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