Skip to main content

magi/
daemon.rs

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