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