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, cause: crate::run::ParkCause) {
347        self.pause.park_for(cause);
348        self.stop();
349    }
350
351    /// Has a park been asked for?
352    #[must_use]
353    pub fn parking(&self) -> bool {
354        self.pause.parked()
355    }
356
357    /// The pause handle to give a runner.
358    #[must_use]
359    pub fn pause(&self) -> crate::graph::Pause {
360        self.pause.clone()
361    }
362
363    /// Is any run in flight right now?
364    ///
365    /// `finishing` answers "a stop is waiting on a run", which is false until
366    /// someone asks to stop. An upgrade needs the plain question, because it
367    /// is about to be the one asking.
368    #[must_use]
369    pub fn busy_now(&self) -> bool {
370        self.busy.load(Ordering::SeqCst) > 0
371    }
372
373    /// Mark one more run as in flight, for [`Stop::finishing`].
374    fn enter(&self) {
375        self.busy.fetch_add(1, Ordering::SeqCst);
376    }
377
378    /// Mark one run as finished. The last one out is what makes
379    /// [`Stop::busy_now`] false again.
380    fn exit(&self) {
381        self.busy.fetch_sub(1, Ordering::SeqCst);
382    }
383
384    /// Wait out one poll interval, returning early once a stop is asked for.
385    async fn idle(&self, poll: Duration) {
386        tokio::select! {
387            () = tokio::time::sleep(poll) => {}
388            () = self.wake.notified() => {}
389        }
390    }
391}
392
393/// The daemon's published state, read permissively.
394///
395/// This mirrors [`Status`], but is a separate declaration on purpose: every
396/// field defaults, so a status file from an older or newer magi still yields
397/// a usable reading — one this build has never heard of — instead of a parse
398/// error that hides the daemon entirely.
399#[derive(Debug, Clone, Default, Deserialize)]
400#[serde(default)]
401pub struct Reading {
402    /// Format version the daemon claims.
403    pub schema: u32,
404    /// Daemon process id, for an operator who wants to stop it.
405    pub pid: Option<u32>,
406    /// When that process started.
407    pub started_at: Option<Timestamp>,
408    /// Last heartbeat. Absent means the file is unusable, hence not running.
409    pub updated_at: Option<Timestamp>,
410    /// True when the queue had nothing runnable at the last poll.
411    pub idle: bool,
412    /// What the daemon is working on. Empty means idle; more than one entry
413    /// means more than one run is in flight at once.
414    ///
415    /// `deserialize_with` rather than the plain derive: a daemon started
416    /// before this field became a list is still out there writing the old
417    /// shape — a single `{"task":...,"run":...}` object, or its absence —
418    /// on every heartbeat until it is restarted, and a live process reading
419    /// that file during the rollout must still see it as running rather than
420    /// as absent. A bare type change here would fail the whole struct's
421    /// deserialization on a type mismatch, defeating the permissiveness this
422    /// type exists for.
423    #[serde(deserialize_with = "de_current")]
424    pub current: Vec<Current>,
425    /// Tasks this daemon process has finished.
426    pub completed: u64,
427    /// Queue polls this daemon process has made.
428    pub polls: u64,
429}
430
431/// Accept the old single-`Current`-or-absent shape as well as the current
432/// list, so a reader never has to know which build wrote the file.
433fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
434where
435    D: serde::Deserializer<'de>,
436{
437    #[derive(Deserialize)]
438    #[serde(untagged)]
439    enum Shape {
440        Many(Vec<Current>),
441        One(Current),
442    }
443    Ok(
444        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
445            Shape::Many(v) => v,
446            Shape::One(c) => vec![c],
447        }),
448    )
449}
450
451impl Reading {
452    /// Seconds since the last heartbeat, or `None` when there has never been
453    /// one.
454    #[must_use]
455    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
456        self.updated_at
457            .map(|at| (now.as_second() - at.as_second()).max(0))
458    }
459
460    /// Whether the loop counts as running: a heartbeat no older than
461    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
462    /// progress hours after the daemon that owned it was killed.
463    #[must_use]
464    pub fn running(&self, now: Timestamp) -> bool {
465        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
466    }
467}
468
469/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
470/// usable there.
471///
472/// Missing, half-written and unparseable all collapse to `None`, because the
473/// only question a reader asks is whether a daemon is alive, and a file it
474/// cannot read is not evidence that one is.
475#[must_use]
476pub fn read_status(home: &Path) -> Option<Reading> {
477    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
478    serde_json::from_str(&body).ok()
479}
480
481/// Every run a live daemon is working on right now.
482///
483/// One definition of liveness, because deleting a task and deleting a run are
484/// both gated on it from both the CLI and the web UI - four callers that must
485/// never disagree about whether the same thing is in flight. A stale heartbeat
486/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
487/// left at `running` or a run left at `implementing` by a killed daemon is a
488/// leftover record rather than work in progress. More than one entry once
489/// [`crate::config::Daemon::max_concurrent_runs`] is more than one - a caller
490/// after "the one thing in flight" wants [`is_working_on`] or
491/// [`is_working_on_task`], not this directly.
492#[must_use]
493pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
494    read_status(home)
495        .filter(|reading| reading.running(now))
496        .map(|reading| reading.current)
497        .unwrap_or_default()
498}
499
500/// Whether a live daemon is working on this run at this moment.
501#[must_use]
502pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
503    current_work(home, now).iter().any(|c| c.run == run)
504}
505
506/// Whether a live daemon is working on a run whose short id is this one.
507///
508/// For a worktree that has no run record to compare against at all -
509/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
510/// id is not available to hand to [`is_working_on`]. The short id is: a run's
511/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
512/// and it is exactly the gap between the daemon claiming a task and
513/// `RunState::new` saving the first `run.json` that this exists to protect -
514/// a run genuinely in flight but invisible to a scan of `runs/`.
515#[must_use]
516pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
517    current_work(home, now)
518        .iter()
519        .any(|c| crate::run::short_of(&c.run) == short)
520}
521
522/// Whether a live daemon is working on this task at this moment.
523#[must_use]
524pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
525    current_work(home, now).iter().any(|c| c.task == task)
526}
527
528/// Remove claim files whose owner is provably dead, or that have simply
529/// outlived `older_than`, and return the task ids swept.
530///
531/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
532/// destructor, and the orphaned `.lock` file would make its task permanently
533/// unclaimable — the backlog would stop for good at exactly the task that was
534/// in flight when the machine went down.
535///
536/// The pid recorded in the lock is the authority whenever it can be read at
537/// all; age is only a fallback for when it cannot be.
538///
539/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
540///   full stop — dead sweeps the lock immediately, regardless of age; alive
541///   protects it, regardless of age. This is what lets a lock be reclaimed in
542///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
543///   before this daemon even started, next to a `queued` task, no longer has
544///   to sit for six hours before anything notices its owner is gone.
545/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
546///   falls back to `older_than`, since there is nothing else to check.
547///
548/// Age must never override a *positive* liveness confirmation. `sweep`
549/// [`poll`]s concurrently with every attempt this daemon itself has spawned —
550/// see [`InFlightGuard`] — not only between them the way a single sequential
551/// loop once did, so a run that legitimately runs longer than `older_than`
552/// (a multi-round review, a long land wait carried across several resumed
553/// attempts) still has this very process's own live pid sitting in its own
554/// lock file on every later sweep. Deciding by age alone in that case would
555/// delete this daemon's own still-valid claim on its own in-flight task,
556/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
557/// to a second attempt — two `Runner`s writing the same `run.json` and the
558/// same worktree at once. `pid_alive` answering "alive" for anything it
559/// cannot determine (a live process, a pid this build cannot check, one
560/// under another account) is exactly what keeps that path from ever
561/// firing on a guess.
562///
563/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
564/// output unreadable must not be license to guess, and the risk of an
565/// unparseable lock outliving a genuinely dead owner is bounded by an order
566/// of magnitude above any plausible run rather than by a positive check.
567///
568/// Runs on every poll, not only at startup — a daemon up for days must keep
569/// noticing a lock some other, now-dead, daemon left behind just as readily
570/// as one it trips over on the way up.
571pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
572    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
573}
574
575/// [`sweep_stale_claims`] with its process-query boundary supplied by the
576/// caller. This keeps the lock policy testable where process listing is
577/// unavailable, while production still uses the platform query above.
578fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
579where
580    F: Fn(u32) -> bool,
581{
582    let this_process = std::process::id();
583    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
584        .into_iter()
585        .flatten()
586        .flatten()
587        .map(|e| e.path())
588        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
589        .filter(|p| {
590            match std::fs::read_to_string(p)
591                .ok()
592                .and_then(|body| body.trim().parse::<u32>().ok())
593            {
594                // This process wrote it and is asking the question right
595                // now, so it is definitionally still alive - settled without
596                // spawning a helper process at all.
597                Some(pid) if pid == this_process => false,
598                Some(pid) => !pid_alive(pid),
599                None => p
600                    .metadata()
601                    .and_then(|m| m.modified())
602                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
603                    .is_ok_and(|age| age >= older_than),
604            }
605        })
606        .filter(|p| std::fs::remove_file(p).is_ok())
607        .filter_map(|p| {
608            p.file_stem()
609                .and_then(|s| s.to_str())
610                .map(std::borrow::ToOwned::to_owned)
611        })
612        .collect();
613    swept.sort_unstable();
614    swept
615}
616
617/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
618/// no live daemon's heartbeat naming it? Deterministic — no model call, and
619/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
620/// shown.
621fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
622    task.status == TaskStatus::Running
623        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
624        && !is_working_on_task(home, &task.id, now)
625}
626
627/// Every task [`is_stalled`] right now — "止まったタスク" in
628/// `crate::conduct`'s vocabulary.
629fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
630    queue
631        .list()
632        .into_iter()
633        .filter(|t| is_stalled(t, home, now))
634        .collect()
635}
636
637/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
638/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
639/// `Failed`-and-so-also-runnable: a task that already attempted and lost
640/// belongs in [`finished_tasks`], where the question is a recovery, not a
641/// dependency.
642fn queued_tasks(queue: &Queue) -> Vec<Task> {
643    queue
644        .list()
645        .into_iter()
646        .filter(|t| t.status == TaskStatus::Queued)
647        .collect()
648}
649
650/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
651/// タスク" in `crate::conduct`'s vocabulary.
652fn finished_tasks(queue: &Queue) -> Vec<Task> {
653    queue
654        .list()
655        .into_iter()
656        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
657        .collect()
658}
659
660/// Deterministically resolve `Task::blocked_by`: a dependency task that
661/// reached `Done`, or a question that was answered, is removed — no model
662/// involved, on every poll. An answered question's content is copied onto
663/// the task ([`Task::record_answer`]) before its id is dropped, so it
664/// reaches the next `crate::conduct` prompt and the next run's instruction
665/// (see [`instruction_for`]) rather than only clearing the block.
666///
667/// A `blocked_by` id that names neither an existing task nor an existing
668/// question - `magi task rm` (or an operator by hand) deleted it while this
669/// task was still waiting - is caught before any of that: it can never
670/// become `Done` or `Answered`, so the ordinary loop below would otherwise
671/// leave the task `blocked` forever with nothing to notice. Such a task is
672/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
673/// which puts it in front of `crate::triage::run_once`'s own walk the next
674/// time it runs - see that module's doc for why the choice is "ask a human",
675/// never "assume the missing dependency was satisfied and unblock anyway".
676fn resolve_blockers(queue: &Queue, questions: &Questions) {
677    for listed in queue.list() {
678        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
679            continue;
680        }
681        let Ok(_claim) = queue.claim(&listed.id) else {
682            continue;
683        };
684        let Ok(mut task) = queue.get(&listed.id) else {
685            continue;
686        };
687        if task.status != TaskStatus::Blocked {
688            continue;
689        }
690        // A dependency deleted on purpose is released, not held - and before
691        // the missing check, so a pass that races the delete (or a claim that
692        // made `Queue::remove` skip this task) settles it quietly.
693        let deleted = queue.apply_deleted_blockers(&mut task);
694        if !deleted.is_empty() {
695            record(queue, &mut task);
696            for id in &deleted {
697                queue.note_dependency_deleted(&task, id);
698            }
699            if task.status != TaskStatus::Blocked {
700                continue;
701            }
702        }
703        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
704        if !missing.is_empty() {
705            let language = language_of(&task, Path::new("."));
706            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
707                &task.blocked_by,
708                &missing,
709                &language,
710            )));
711            record(queue, &mut task);
712            continue;
713        }
714        // A conductor question nobody answered in time is retired by the
715        // waiter, and nothing else would ever move the task it blocks.
716        if let Some(q) = task.blocked_by.iter().find_map(|id| {
717            questions.get(id).ok().filter(|q| {
718                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
719            })
720        }) {
721            let language = language_of(&task, Path::new("."));
722            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
723            record(queue, &mut task);
724            continue;
725        }
726        let mut changed = false;
727        for id in task.blocked_by.clone() {
728            if let Ok(dep) = queue.get(&id) {
729                if dep.status == TaskStatus::Done {
730                    task.unblock(&id);
731                    changed = true;
732                }
733                continue;
734            }
735            if let Ok(q) = questions.get(&id)
736                && q.status == ask::QuestionStatus::Answered
737            {
738                let answer = match &q.answer {
739                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
740                    None => String::new(),
741                };
742                task.record_answer(q.summary.clone(), answer);
743                task.unblock(&id);
744                changed = true;
745            }
746        }
747        if changed {
748            record(queue, &mut task);
749        }
750    }
751}
752
753/// The `hold_reason` of a task whose conductor question went unanswered.
754fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
755    if crate::lang::is_japanese(language) {
756        format!(
757            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
758            q.short(),
759            q.summary
760        )
761    } else {
762        format!(
763            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
764            q.short(),
765            q.summary
766        )
767    }
768}
769
770/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
771/// for several unrelated reasons, and the waiter must not read them alike.
772#[derive(Debug, Clone, Copy, PartialEq, Eq)]
773pub(crate) enum ActionStanding {
774    /// The answer carries no action: the waiter delivers it as before.
775    NoAction,
776    /// The daemon will apply it (not applied, task idle, current attempt).
777    Pending,
778    /// Already applied (`Task::actions_applied`): the daemon has acted, so
779    /// delivering the word to the old seat would run it beside the new work.
780    Applied,
781    /// The question is about an earlier attempt than the task's latest.
782    Stale,
783    /// The task is running / blocked / done: the daemon defers for now.
784    Busy,
785}
786
787impl ActionStanding {
788    /// The daemon has acted or will act: the waiter must not deliver.
789    pub(crate) fn daemon_owns(self) -> bool {
790        matches!(self, Self::Pending | Self::Applied | Self::Stale)
791    }
792}
793
794/// Classify `q`'s chosen action against `task`. `Stale` is judged before
795/// `Busy`: a question about an earlier attempt must be stopped even while a
796/// newer competition is running.
797pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
798    if q.chosen_action().is_none() {
799        ActionStanding::NoAction
800    } else if task.action_applied(&q.id) {
801        ActionStanding::Applied
802    } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
803        ActionStanding::Stale
804    } else if matches!(
805        task.status,
806        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
807    ) {
808        ActionStanding::Busy
809    } else {
810        ActionStanding::Pending
811    }
812}
813
814/// What [`decide_action`] concluded about one answered question.
815#[derive(Debug, Clone, PartialEq, Eq)]
816enum ActionDecision {
817    /// Nothing to do now (no action, already applied, or the task is busy).
818    Skip,
819    /// Continue the named run instead of competing again.
820    Resume(String),
821    /// Requeue as a fresh competition.
822    Requeue,
823    /// Close the task as done.
824    Done,
825    /// The question is about an earlier attempt than the task's latest; it
826    /// is recorded as handled and changes nothing.
827    Stale,
828    /// The action cannot be carried out; hold the task and say why. Never
829    /// falls back to something else, because the operator chose this one.
830    Refuse(String),
831}
832
833/// Decide what the choice answered on `q` means for `task`. Pure: `load`
834/// reads a run's state, as with [`unfinished_run_with`].
835///
836/// `Resume` only fires on the task's *latest* run, and only while that run
837/// could actually make progress ([`RunStatus::resumable`], not released, review
838/// budget left); an answer naming anything else is refused rather than
839/// reinterpreted as a fresh competition.
840fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
841where
842    F: FnOnce(&str) -> Result<RunState>,
843{
844    let Some(action) = q.chosen_action() else {
845        return ActionDecision::Skip;
846    };
847    if task.action_applied(&q.id)
848        || matches!(
849            task.status,
850            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
851        )
852    {
853        return ActionDecision::Skip;
854    }
855    if task.operator_decided_at.is_some_and(|at| at > q.asked_at) {
856        return ActionDecision::Stale;
857    }
858    // A question about an earlier attempt must not act on a newer one. A
859    // conductor question is keyed by the task id, not a run, so it is exempt.
860    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
861        return ActionDecision::Stale;
862    }
863    match action {
864        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
865        ask::ChoiceAction::Done => ActionDecision::Done,
866        ask::ChoiceAction::Resume { run } => {
867            if task.runs.last() != Some(run) {
868                return ActionDecision::Refuse((p.resume_not_latest)(
869                    q.short(),
870                    ask::short_id(run),
871                ));
872            }
873            match load(run) {
874                Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
875                    ActionDecision::Resume(run.clone())
876                }
877                Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
878                    q.short(),
879                    ask::short_id(run),
880                )),
881                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
882                    q.short(),
883                    ask::short_id(run),
884                    &format!("{e:#}"),
885                )),
886            }
887        }
888    }
889}
890
891/// The fixed prose the daemon writes into [`Task::last_error`] and
892/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
893/// `triage::Wording` and `land::Words`: only English and Japanese are
894/// translated, anything else falls back to English.
895///
896/// Rendered when the reason is *generated*, so a reason keeps the language it
897/// was written in if the setting changes later. The notification frame
898/// (`Task <id> is held:`) is not here and stays English.
899///
900/// Deliberately **not** translated, because other code reads them back by
901/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
902/// and `gate red`. IDs, node names, paths and external error text are embedded
903/// as they are.
904struct Phrases {
905    /// `{}` = status label, then the detail.
906    graph_stopped: fn(&str, &str) -> String,
907    quorum_lost: &'static str,
908    /// Followed by the seats' names.
909    quota_took_out: &'static str,
910    /// Followed by the status label.
911    run_ended: &'static str,
912    /// Followed by the question's short id.
913    waiting_for_answer: &'static str,
914    recovered_running: &'static str,
915    no_run_to_recover: &'static str,
916    could_not_start: &'static str,
917    resume_not_latest: fn(&str, &str) -> String,
918    resume_cannot_progress: fn(&str, &str) -> String,
919    resume_unreadable: fn(&str, &str, &str) -> String,
920    /// A takeover refusal: the operator-facing text. English is the error's own
921    /// `Display`; a translation keeps the machine detail apart in parentheses.
922    handover_refused: fn(&crate::handover::Refused) -> String,
923    /// Appended to a refused handover's hold reason (leading space included).
924    handover_hint: &'static str,
925    /// (seats that never answered, review rounds) for the review loop's
926    /// "refusing to call it clean" stop.
927    reviewers_never_answered: fn(usize, usize) -> String,
928}
929
930const PHRASES_EN: Phrases = Phrases {
931    graph_stopped: |status, detail| {
932        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
933    },
934    quorum_lost: "the judging panel lost its quorum",
935    quota_took_out: "; quota took out ",
936    run_ended: "run ended ",
937    waiting_for_answer: " - waiting for operator answer to question ",
938    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
939    no_run_to_recover: "task was `running` with no live daemon and no readable \
940                        run to recover; held for a human to check what happened",
941    could_not_start: "could not start the run: ",
942    resume_not_latest: |q, run| {
943        format!("question {q} asked to resume run {run}, which is not this task's latest run")
944    },
945    resume_cannot_progress: |q, run| {
946        format!("question {q} asked to resume run {run}, which cannot make progress")
947    },
948    resume_unreadable: |q, run, e| {
949        format!("question {q} asked to resume run {run}, which could not be read: {e}")
950    },
951    handover_refused: |r| r.to_string(),
952    handover_hint: " (clean up the other worktree, then release the task from the queue)",
953    reviewers_never_answered: |missing, rounds| {
954        format!(
955            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
956             refusing to call it clean"
957        )
958    },
959};
960
961const PHRASES_JA: Phrases = Phrases {
962    graph_stopped: |status, detail| {
963        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
964    },
965    quorum_lost: "審査パネルが定足数を失いました",
966    quota_took_out: "。クォータで脱落: ",
967    run_ended: "run 終了: ",
968    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
969    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
970    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
971                        何が起きたか人が確認するため保留にしました",
972    could_not_start: "run を開始できませんでした: ",
973    resume_not_latest: |q, run| {
974        format!(
975            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
976        )
977    },
978    resume_cannot_progress: |q, run| {
979        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
980    },
981    resume_unreadable: |q, run, e| {
982        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
983    },
984    handover_refused: |r| {
985        use crate::handover::Refused;
986        match r {
987            Refused::Foreign { branch, path, why } => format!(
988                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
989                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
990                 から、やり直してください(詳細: {why})"
991            ),
992            Refused::Unsafe { branch, path, why } => format!(
993                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
994                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
995                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
996            ),
997            Refused::ReleaseFailed { branch, path, run } => format!(
998                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
999                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1000                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1001            ),
1002        }
1003    },
1004    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1005    reviewers_never_answered: |missing, rounds| {
1006        format!(
1007            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1008             クリーンとは認めません"
1009        )
1010    },
1011};
1012
1013fn phrases(language: &str) -> &'static Phrases {
1014    if crate::lang::is_japanese(language) {
1015        &PHRASES_JA
1016    } else {
1017        &PHRASES_EN
1018    }
1019}
1020
1021/// The language of the repository a task belongs to, read best-effort for the
1022/// paths that have no run (and so no config of their own) to ask. An unreadable
1023/// config is English, not an error: a hold reason must still get written.
1024fn language_of(task: &Task, fallback: &Path) -> String {
1025    crate::lang::of_repo(&repo_for(task, fallback))
1026}
1027
1028/// The task an answered question speaks for: the one whose runs include the
1029/// question's run, or - for a conductor question, filed under the task's own
1030/// id - the task with that id.
1031pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1032    if q.node == crate::conduct::NODE {
1033        return tasks.iter().find(|t| t.id == q.run);
1034    }
1035    tasks.iter().find(|t| t.runs.contains(&q.run))
1036}
1037
1038/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1039///
1040/// Runs on every poll before the conductor looks at the queue. The task is
1041/// re-read under its claim, so a task somebody completed or held by hand in
1042/// the meantime is judged on what it is now. `Resume` releases the task and
1043/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1044/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1045/// ordinary `unfinished_run` logic resumes that same run.
1046fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1047    let tasks = queue.list();
1048    for q in questions.list() {
1049        if q.chosen_action().is_none() {
1050            continue;
1051        }
1052        let Some(listed) = task_of_question(&tasks, &q) else {
1053            continue;
1054        };
1055        if listed.action_applied(&q.id) {
1056            continue;
1057        }
1058        let Ok(_claim) = queue.claim(&listed.id) else {
1059            continue;
1060        };
1061        let Ok(mut task) = queue.get(&listed.id) else {
1062            continue;
1063        };
1064        let language = language_of(&task, Path::new("."));
1065        let decision = decide_action(&task, &q, phrases(&language), |id| {
1066            RunState::load_under(id, home)
1067        });
1068        let ran = matches!(
1069            decision,
1070            ActionDecision::Resume(_) | ActionDecision::Requeue | ActionDecision::Done
1071        );
1072        if ran && asker_may_still_read(questions, &q, home) {
1073            // The asking process or its seat can still take the word; act
1074            // once it has gone quiet. Bound on the remaining window: the
1075            // check is not atomic with the write below, so an asker that
1076            // takes the word in between (at most one poll, never more than
1077            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1078            // and `Task::actions_applied` under the claim keeps the action to
1079            // one application. The waiter does not deliver an answer that
1080            // carries an action (`waiter::decide_owned`), so it cannot race.
1081            continue;
1082        }
1083        let done = matches!(decision, ActionDecision::Done);
1084        match decision {
1085            ActionDecision::Skip => continue,
1086            ActionDecision::Resume(run) => {
1087                task.release_operator("choice", Some(&q.id));
1088                task.resume_override = Some(crate::queue::OperatorResume {
1089                    question_id: q.id.clone(),
1090                    at: Timestamp::now(),
1091                    conductor_rehold: None,
1092                    forced: true,
1093                    pinned_run: Some(run),
1094                });
1095            }
1096            ActionDecision::Stale => {}
1097            ActionDecision::Requeue => {
1098                task.release_operator("choice-requeue", Some(&q.id));
1099                task.requeue();
1100            }
1101            ActionDecision::Done => task.succeed(),
1102            ActionDecision::Refuse(why) => {
1103                task.hold_machine(Some(why));
1104                notices::raise(
1105                    Notice::warn(
1106                        &format!("action:{}", q.id),
1107                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1108                    )
1109                    .link(Link::Task {
1110                        id: task.id.clone(),
1111                    }),
1112                );
1113            }
1114        }
1115        task.mark_action_applied(&q.id);
1116        // The applied id travels with the transition, so a failed save loses
1117        // neither and the answer is acted on at the next poll.
1118        record(queue, &mut task);
1119        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1120            supersede_prior_runs(&task, home);
1121        }
1122        // Delivery is only a note of who has read the answer; the task's own
1123        // mark above is the authority. Best effort.
1124        let _ = questions.update(&q.id, |r| {
1125            r.answer_delivered = true;
1126            Ok(())
1127        });
1128    }
1129}
1130
1131/// Whether something may still read the answer to `q`: a fresh lease, or the
1132/// asking seat still listed as active in its run (its CLI can outlive the
1133/// `magi ask` that was killed).
1134fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1135    let now = Timestamp::now();
1136    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1137        return true;
1138    }
1139    q.node != crate::conduct::NODE
1140        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1141            s.seats_active()
1142                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1143        })
1144}
1145
1146/// Retire an unanswered conductor question after its task no longer refers to
1147/// it. Conductor questions use the task id in `Question::run`, so run-based
1148/// cleanup cannot observe a manual release or completion.
1149///
1150/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1151/// own question also carries a `run`, and a run id that happens to collide
1152/// with some task's id is not this loop's business — only a conductor
1153/// question actually uses the task id that way. One `Questions::list()` scan
1154/// is taken up front and matched against the in-memory task set, rather than
1155/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1156fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1157    let tasks = queue.list();
1158    let by_id: std::collections::BTreeMap<&str, &Task> =
1159        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1160    let referenced: std::collections::BTreeSet<&str> = tasks
1161        .iter()
1162        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1163        .collect();
1164
1165    for mut question in questions.list() {
1166        if !question.status.open() || question.node != crate::conduct::NODE {
1167            continue;
1168        }
1169        // Keep questions a task still names, including when the reference
1170        // moved to a dependent task.
1171        if referenced.contains(question.id.as_str()) {
1172            continue;
1173        }
1174        let Some(task) = by_id.get(question.run.as_str()) else {
1175            continue;
1176        };
1177        question.abandon(format!(
1178            "task {} no longer waits for this answer",
1179            task.short()
1180        ));
1181        if let Err(e) = questions.put(&mut question) {
1182            tracing::warn!(
1183                "could not retire question {} for task {}: {e:#}",
1184                question.short(),
1185                task.short()
1186            );
1187        }
1188    }
1189}
1190
1191/// What a finished run tells the queue about the task it came from.
1192///
1193/// A struct rather than a fourth and fifth boolean argument: the two flags
1194/// answer different questions about the same run, and a call site passing
1195/// `(…, true, false)` is one transposition away from refunding attempts
1196/// forever.
1197#[derive(Debug, Clone, Copy)]
1198pub struct Verdict {
1199    /// Where the graph stopped.
1200    pub status: RunStatus,
1201    /// The run opened a pull request.
1202    pub left_pr: bool,
1203    /// At least one seat was lost to a rate limit.
1204    pub quota_hit: bool,
1205    /// The run parked at a node boundary because it was asked to.
1206    pub parked: bool,
1207    /// The run never produced a single candidate a judge could look at.
1208    ///
1209    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1210    /// still have another candidate worth judging, in which case the loss was
1211    /// not the reason nothing came of the run. This is `true` only when the
1212    /// implement wave ended with nothing viable at all.
1213    pub no_viable_candidates: bool,
1214}
1215
1216/// Record a finished run against the task it came from.
1217///
1218/// Kept pure and separate from the loop because this mapping *is* the retry
1219/// policy, and a policy that can only be exercised by spawning a graph is a
1220/// policy nobody checks. The table:
1221///
1222/// | run status                           | task becomes        | attempt spent |
1223/// |---------------------------------------|---------------------|---------------|
1224/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1225/// | `Merged`, `Ready`                      | `Done`               | yes          |
1226/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1227/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1228/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1229/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1230/// | `Blocked` with a PR                    | `Held`               | yes          |
1231/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1232/// | `VerifiedNoop`                          | `Held`               | yes          |
1233/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1234///
1235/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1236/// deliberately: every candidate agreeing there is nothing to write is not a
1237/// machine fact about a rate limit, it is an unverified claim about the
1238/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1239/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1240/// claim could be wrong (a misread instruction, a stale check), and closing
1241/// the task automatically on an implementer's say-so would be the exact
1242/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1243/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1244/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1245/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1246/// claim regardless of whether the one already-spent attempt is refunded, and
1247/// [`Task::release`] resets the count to zero anyway the moment a human looks
1248/// at the evidence and lets it run again.
1249///
1250/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1251/// twice, together. A quorum lost to rate limits is a property of the machine
1252/// and not of the task, so the attempt is refunded and a reset quota picks
1253/// the work up where it stopped — and that is just as true when every
1254/// implement seat lost the same race and `after_implement` bails with nothing
1255/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1256/// machine fact. The `no_viable_candidates` guard is what keeps that row
1257/// narrow: a `Failed` run that produced a real candidate which then lost for
1258/// some other reason still spends the attempt, exactly like the quorum lost
1259/// to judges that answered with the wrong shape is ordinary flakiness, and
1260/// refunding *that* takes the bound off the retry loop entirely: run e633
1261/// stalled with `quota: []` after two judges wrote unusable JSON, was
1262/// refunded, and the next attempt paid for a fresh hour-long implement wave
1263/// before it could fail the same way. `max_attempts` exists precisely so
1264/// that cannot repeat forever.
1265///
1266/// A non-terminal status means `execute` returned while the graph was still
1267/// mid-flight, which is a bug rather than a verdict; it is treated as a
1268/// failure so that a task cannot loop on it either.
1269///
1270/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1271/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1272pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1273    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1274}
1275
1276/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1277fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1278    // A parked run is the operator's own doing, and its work is intact on
1279    // disk. The task goes back in line with its attempt refunded so the next
1280    // loop resumes the same run - which `one_task` prefers over competing
1281    // again - and so that swapping the binary a few times cannot exhaust a
1282    // budget meant for agents that actually misbehaved.
1283    if verdict.parked {
1284        task.park(detail);
1285        return;
1286    }
1287    match verdict.status {
1288        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1289        RunStatus::AlreadyInBase => task.already_landed(detail),
1290        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1291        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1292            task.stall(detail)
1293        }
1294        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1295        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1296        RunStatus::Blocked => task.fail(detail, max_attempts),
1297        RunStatus::VerifiedNoop => task.handed_off(detail),
1298        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1299    }
1300}
1301
1302/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1303/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1304/// itself has actually finished *and* its own last attempt is provably why:
1305/// this loads that run and requires `Merged`/`Ready` before touching
1306/// anything earlier in `runs`, since `Task::succeed` can also be called
1307/// directly on a task whose last attempt never landed at all.
1308///
1309/// Called right after whatever call set `task.status` to
1310/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1311/// `reclaim`'s, but also every other place a task can be closed by hand
1312/// without the loop ever settling it itself: `magi task done`
1313/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1314/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1315/// GitHub merge, say, exactly the workflow this repository's own
1316/// "Landing a run's winner by hand" documents — is just as much "this task's
1317/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1318/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1319/// forever, which is the exact backlog this status exists to clear. `pub`
1320/// for those two out-of-module callers; everything else about this stays
1321/// internal bookkeeping.
1322///
1323/// A run something is still actually driving is left alone: a
1324/// task cannot be `Done` while one of its *own* attempts is still in flight,
1325/// so a live one at this point can only be an unrelated process — a manual
1326/// `--resume` of this old, now-moot run — and rewriting under it would just
1327/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1328/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1329/// pair `run_report`/`run_detail` use for the same question elsewhere:
1330/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1331/// --resume` invoked by hand outside it, which `liveness` also checks via
1332/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1333/// (already terminal in some other way, or itself mid-run) is left untouched
1334/// too.
1335///
1336/// Best-effort, like the rest of this module's bookkeeping: a load or save
1337/// failure here is a `tracing::warn`, not a failed settle, and the next time
1338/// this same task's completion is recorded — or a daemon restart replays
1339/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1340/// separate reconciliation pass; if that gap ever matters in practice, one
1341/// can be added then.
1342///
1343/// `home` is a parameter, not the process-global [`crate::run::home`], for
1344/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1345/// calls this with `ui.home`, which is `crate::run::home()` in a real
1346/// process but a fixture's own directory under test — falling through to
1347/// the global there would read and write through whichever home some other
1348/// test in the same binary happened to pin into that `OnceLock` first, not
1349/// the run this call actually means.
1350pub fn supersede_prior_runs(task: &Task, home: &Path) {
1351    let now = Timestamp::now();
1352    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1353    // right behind a `Merged`/`Ready` verdict) from one set directly by
1354    // `magi task done`/its web equivalent/the conductor on a task whose last
1355    // recorded attempt never actually landed - that requires reading the
1356    // run itself, which is exactly what this does before trusting anything
1357    // in `runs` is safe to relabel.
1358    let last_run_succeeded = task
1359        .runs
1360        .last()
1361        .and_then(|id| RunState::load_under(id, home).ok())
1362        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1363    for id in task.superseded_attempts(last_run_succeeded) {
1364        let mut state = match RunState::load_under(id, home) {
1365            Ok(s) => s,
1366            Err(e) => {
1367                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1368                continue;
1369            }
1370        };
1371        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1372            continue;
1373        }
1374        let daemon_claims = is_working_on(home, id, now);
1375        if state.liveness(daemon_claims) == Liveness::Live {
1376            continue;
1377        }
1378        state.status = RunStatus::Superseded;
1379        if let Err(e) = state.save_under(home) {
1380            tracing::warn!("could not mark run {id} superseded: {e:#}");
1381        }
1382    }
1383}
1384
1385/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1386/// finish the moment it was called, because one of its earlier attempts was
1387/// still live then - a `magi run --resume` invoked by hand on an old run,
1388/// most likely.
1389///
1390/// That skip is correct at the time (rewriting under a run something is
1391/// still actively saving would just be undone), but a task only ever
1392/// reaches `Done` once, so without this nothing would ever look at it
1393/// again: if that manual process later ends anywhere other than
1394/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1395/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1396/// backlog this status exists to clear. Called on the same idle-only
1397/// cadence as [`janitor`], next to it rather than folded into it: this
1398/// walks `queue` and `janitor` never otherwise needs one.
1399///
1400/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1401/// more than one attempt, every pass: each call is a handful of local file
1402/// reads bounded by that task's own attempt count, the same order of cost
1403/// [`clean::fold_due`] already pays scanning every run on disk on the same
1404/// cadence, and a task already fully resolved costs one failed liveness
1405/// check turned no-op the moment its lingering attempt is no longer live.
1406fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1407    for task in queue.list() {
1408        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1409            continue;
1410        }
1411        supersede_prior_runs(&task, home);
1412    }
1413}
1414
1415/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1416/// task ends up held.
1417///
1418/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1419/// dead daemon never got back to) share this, so the two cannot drift into
1420/// disagreeing about which held tasks get a diagnostic.
1421fn settle_and_diagnose(
1422    task: &mut Task,
1423    verdict: Verdict,
1424    detail: &str,
1425    max_attempts: usize,
1426    state: &RunState,
1427) {
1428    let p = phrases(&state.config.graph.language);
1429    let attempts_before = task.attempts;
1430    // A run that stopped because a shared resource stayed busy was never a
1431    // failure of the task or of any agent: nothing was asked. The attempt is
1432    // refunded and the task is held by the machine, under a reason `triage`
1433    // can re-check, so the same run resumes with the same agents once the
1434    // resource is free. A park request still wins (it is the operator's).
1435    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1436        task.last_error = Some(detail.to_owned());
1437        task.diagnostic = None;
1438        task.attempts = task.attempts.saturating_sub(1);
1439        task.hold_machine(Some(format!(
1440            "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1441             no agent was asked and no attempt was spent",
1442            crate::cache::RESOURCE_HOLD,
1443            block.kind,
1444            block.node
1445        )));
1446        if let Some(pass) = state.passes.last() {
1447            task.record_pass(&state.id, pass.index, attempts_before, None);
1448        }
1449        return;
1450    }
1451    settle_in(task, verdict, detail, max_attempts, p);
1452    // Written here, where the refund (or not) is decided, so the history is a
1453    // fact and not a later guess from the run's status.
1454    if let Some(pass) = state.passes.last() {
1455        let parked = match &pass.end {
1456            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
1457            _ => None,
1458        };
1459        task.record_pass(&state.id, pass.index, attempts_before, parked);
1460    }
1461    if task.status == TaskStatus::Held {
1462        task.diagnostic = diagnostic(state);
1463        note_open_question(task, &state.id, p);
1464    }
1465}
1466
1467/// If `task` is held with a `magi ask` question still open on `run`, name the
1468/// question in [`Task::hold_reason`] rather than leaving the hold reading
1469/// only [`describe`]'s run summary.
1470///
1471/// This is the shape task 20260928-191407-05fd left underspecified: an
1472/// implementer settled a verified no-op and filed a question for the
1473/// operator, and the hold that followed said nothing about the question
1474/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
1475/// existing text ([`is_disk_hold`](crate::triage), the answered-question
1476/// marker) and must keep seeing it unchanged.
1477///
1478/// Best-effort: an unreadable question store must not stop a run from
1479/// settling, so this is a no-op rather than a propagated error when
1480/// [`crate::run::try_home`] has nothing to offer or the store is empty.
1481fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
1482    let Some(home) = crate::run::try_home() else {
1483        return;
1484    };
1485    let open = Questions::at(home.join("questions")).open_for(run);
1486    let Some(q) = open.first() else {
1487        return;
1488    };
1489    let base = task.hold_reason.clone().unwrap_or_default();
1490    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
1491}
1492
1493/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
1494/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
1495/// by some other means entirely, like a manual `magi run` resume that
1496/// finishes the graph outside the queue's bookkeeping.
1497///
1498/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
1499/// `settle` is separate from `attempt`: a task recovered this way must land
1500/// exactly where a live daemon would have put it — the same policy table,
1501/// not a second one that quietly drifts from it — and that is only checkable
1502/// without spawning a real run.
1503fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
1504    match last_run {
1505        Some(state) => {
1506            let verdict = Verdict {
1507                status: state.status,
1508                left_pr: state.pr.is_some(),
1509                quota_hit: !state.quota.is_empty(),
1510                parked: state.parked,
1511                no_viable_candidates: state.viable().is_empty(),
1512            };
1513            let detail = format!(
1514                "{}{}",
1515                phrases(&state.config.graph.language).recovered_running,
1516                describe(&state)
1517            );
1518            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1519        }
1520        None => {
1521            // No run, so no config of its own: `language` is the task's
1522            // repository's setting, read by the caller.
1523            let why = phrases(language).no_run_to_recover;
1524            task.last_error = Some(why.to_owned());
1525            // The phone shows `hold_reason`, so a task held by the machine
1526            // says why there too and not only in `last_error`.
1527            task.hold_machine(Some(why.to_owned()));
1528        }
1529    }
1530}
1531
1532/// Find every task left at `running` that no live process is actually
1533/// driving, and settle each one against whatever its last run became.
1534///
1535/// # Why a claim is proof, not a guess
1536///
1537/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
1538/// `running`, and the guard is held for the task's whole time in that status:
1539/// `attempt` does not return, and the loop does not move past the scope
1540/// holding the claim, until the run has settled. So a `running` task whose
1541/// lock is gone cannot have a live owner — this process or any other —
1542/// without needing a staleness threshold or a pid check the way
1543/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
1544/// task that never got as far as `running` at all. Taking the claim here is
1545/// the whole test: it either fails, because something really does hold it
1546/// and the task is left alone, or it succeeds, which is the proof — and it is
1547/// kept for the rest of the decision so nothing else can start a competing
1548/// run while this one is being written.
1549///
1550/// Called on every poll, not only at startup, for the reason
1551/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
1552/// keep noticing this, not only on the one morning it happened to restart.
1553fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1554    let mut reclaimed = Vec::new();
1555    for listed in queue.list() {
1556        if listed.status != TaskStatus::Running {
1557            continue;
1558        }
1559        let Ok(_claim) = queue.claim(&listed.id) else {
1560            continue;
1561        };
1562        // Re-read under the claim: a release or an edit landed by a human
1563        // between the listing above and the claim just taken must not be
1564        // clobbered by a decision based on the stale copy.
1565        let Ok(mut task) = queue.get(&listed.id) else {
1566            continue;
1567        };
1568        if task.status != TaskStatus::Running {
1569            continue;
1570        }
1571        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1572        // `execute` normally abandons a run's own open questions the moment
1573        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
1574        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
1575        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
1576        // with the question still `open`, because the process died before
1577        // reaching that call. `reclaim` itself stays pure on purpose (see its
1578        // own doc), so the same cleanup runs here instead, against the run
1579        // this reclaim is already reading. `settle_run` costs nothing when
1580        // `execute` already got there first.
1581        if let Some(state) = &last_run
1582            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1583        {
1584            tracing::warn!("abandon questions for {}: {e:#}", state.id);
1585        }
1586        let language = if last_run.is_none() {
1587            language_of(&task, Path::new("."))
1588        } else {
1589            String::new()
1590        };
1591        reclaim(&mut task, last_run, max_attempts, &language);
1592        if task.status == TaskStatus::Done {
1593            supersede_prior_runs(&task, &crate::run::home());
1594        }
1595        record(queue, &mut task);
1596        reclaimed.push(task.id.clone());
1597    }
1598    reclaimed
1599}
1600
1601/// Find every run whose `run.json` is provably dead — every seat it still
1602/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
1603/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
1604/// not merely "no daemon claims it" — and fail it, clearing the leftover
1605/// active seats so the run stops reading as `implementing` (or whichever
1606/// node) forever.
1607///
1608/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
1609/// `running`, using whatever `run.json` already says — but nothing in that
1610/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
1611/// stays pure on purpose, see its own doc), so a `run.json` a killed process
1612/// never got back to sits exactly where it was left: `active` full of seats
1613/// nobody will ever answer for, `status` stuck on whatever node was in
1614/// flight. `magi show` already tells an operator this in prose (`no live
1615/// daemon claims this run right now`); this is what makes that fact durable
1616/// on disk, the same way a task's own `TaskStatus::Running` does not get to
1617/// stay stuck once nothing is driving it.
1618///
1619/// Runs on every poll, not only at startup, for the reason
1620/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
1621/// daemon up for days must keep noticing a run some other, now-dead, daemon
1622/// left behind just as readily as one it trips over on the way up.
1623///
1624/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
1625/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
1626/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
1627/// `runs` directory instead: `home` here is a parameter precisely so a test
1628/// can point it away from the operator's real history (see [`drive`]'s own
1629/// doc), and a scan that fell through to the global home anyway would walk
1630/// whichever directory some *other* process or test pinned into that
1631/// `OnceLock` first — mutating runs this call was never handed.
1632fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1633    reclaim_abandoned_runs_with(
1634        home,
1635        now,
1636        crate::proc::pid_status,
1637        crate::proc::process_started_at,
1638    )
1639}
1640
1641/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
1642/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
1643/// for the identical reason: this sweep's real damage (wiping a run's active
1644/// seats and failing it) has to be provable against an injected answer in a
1645/// test, not just the real process table.
1646fn reclaim_abandoned_runs_with<F, G>(
1647    home: &Path,
1648    now: Timestamp,
1649    query: F,
1650    identity: G,
1651) -> Vec<String>
1652where
1653    F: Fn(u32) -> Option<bool>,
1654    G: Fn(u32) -> Option<String>,
1655{
1656    let mut abandoned = Vec::new();
1657    for entry in std::fs::read_dir(home.join("runs"))
1658        .into_iter()
1659        .flatten()
1660        .flatten()
1661    {
1662        let id = entry.file_name().to_string_lossy().into_owned();
1663        if !crate::run::is_run_id(&id) {
1664            continue;
1665        }
1666        // Unreadable is `clean::fold_due`'s problem, not this one's — see
1667        // that module's docs for why a run this cannot parse is left alone
1668        // rather than guessed at. A different schema number is not that: this
1669        // touches only `status` and `active`, never a field whose meaning a
1670        // schema bump changed, so an old record's values serve this exactly
1671        // as well as a current one's (see `clean::read_state`'s own doc for
1672        // the same reasoning applied to folding).
1673        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1674            continue;
1675        };
1676        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1677            continue;
1678        };
1679        if state.status.done() || !state.active_all_overrun(now) {
1680            continue;
1681        }
1682        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
1683        // it", which is also the normal, healthy shape of a manual `magi
1684        // run` / `magi review` sharing this same home — this scan walks
1685        // every run on disk, not only ones this daemon itself started. Such
1686        // a run's active seats can legitimately sit past their own timeout
1687        // for a little while (the CLI finishing up, its result still being
1688        // collected) without the process driving it having died. `liveness`
1689        // is what actually tells the two apart, by corroborating
1690        // `driver_pid` against the process it names — see its own doc. Only
1691        // its strongest, provable answer licenses wiping this run's active
1692        // seats and failing it out from under whatever is still running it.
1693        let daemon_claims = is_working_on(home, &id, now);
1694        if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1695            continue;
1696        }
1697        state.abandon("daemon");
1698        if let Err(e) = state.save_under(home) {
1699            tracing::warn!("could not persist abandoned run {id}: {e:#}");
1700            continue;
1701        }
1702        // This run never passes through `Runner::execute` again, so its end
1703        // is announced here.
1704        if let Some(notice) = notices::run_ended(&state) {
1705            notices::raise_in(home, notice);
1706        }
1707        // The seat that asked is gone for good now, exactly like any other
1708        // door `graph::Runner::settle_questions` closes the moment `status`
1709        // lands somewhere non-resumable - see that method's own doc. Nothing
1710        // else reaches this one before the next `janitor()` startup pass
1711        // (`clean::abandon_settled_questions`), and a daemon that stays up
1712        // for days must not leave an open question badging the operator
1713        // until it happens to restart.
1714        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1715            tracing::warn!("abandon questions for {id}: {e:#}");
1716        }
1717        abandoned.push(id);
1718    }
1719    abandoned
1720}
1721
1722/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
1723///
1724/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
1725/// sets, so there is one loop body rather than two that drift apart the first
1726/// time the retry policy changes on only one of them.
1727pub async fn serve(opts: Opts) -> Result<()> {
1728    serve_until(opts, Stop::new()).await
1729}
1730
1731/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
1732///
1733/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
1734/// mid-node leaves worktrees, branches and agent sessions behind, and every
1735/// agent call already paid for is lost; finishing the run costs the operator a
1736/// wait and saves them a cleanup. A stop therefore only sets a flag: the
1737/// current `execute` runs to its terminal status, the task's outcome is
1738/// recorded, and only then does the loop return. That window is what
1739/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
1740/// still has a second Ctrl-C, which the runtime turns into a process kill —
1741/// and the task left `Running` then tells the next daemon, and the next human,
1742/// where to look.
1743///
1744/// While the queue is empty the stop is honoured within one wakeup rather than
1745/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
1746/// caller that taps stop does not sit through the remainder of a sleep.
1747pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1748    let signal = {
1749        let stop = stop.clone();
1750        tokio::spawn(async move {
1751            if tokio::signal::ctrl_c().await.is_ok() {
1752                stop.stop();
1753                tracing::info!("shutdown requested; a run in flight will be finished first");
1754            }
1755        })
1756    };
1757
1758    let worktrees_root = opts
1759        .worktrees_root
1760        .clone()
1761        .unwrap_or_else(crate::run::default_worktree_root);
1762    let outcome = drive(
1763        &opts,
1764        &Queue::open(),
1765        &status_path(),
1766        &crate::run::home(),
1767        &worktrees_root,
1768        &stop,
1769    )
1770    .await;
1771
1772    signal.abort();
1773    outcome
1774}
1775
1776/// The loop proper: setup, poll, teardown, with the queue and the status file
1777/// supplied rather than discovered.
1778///
1779/// All three of `home`, `worktrees_root` and the queue/status paths are
1780/// parameters rather than resolved here, for the same reason:
1781/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
1782/// so a unit test that pinned it would fight every other test in the binary,
1783/// and a loop that resolved its own worktree bay could only be exercised
1784/// against the operator's real `~/wt/<repo>` - publishing over a live
1785/// daemon's status file, claiming tasks out of a live backlog, and, since
1786/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
1787/// whatever the operator actually has on disk.
1788async fn drive(
1789    opts: &Opts,
1790    queue: &Queue,
1791    status_file: &Path,
1792    home: &Path,
1793    worktrees_root: &Path,
1794    stop: &Stop,
1795) -> Result<()> {
1796    // The status file is a *snapshot*, not a stream of events: a reader only
1797    // ever wants the latest values, and every tick rewrites the whole file
1798    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
1799    // while an mpsc channel would force the loop to re-send unchanged fields on
1800    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
1801    // for no gain. The lock is only ever held across a field assignment, never
1802    // across an await.
1803    let status = Arc::new(Mutex::new(Status::new()));
1804    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1805    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1806
1807    // Read once at startup, not per task: how many runs this loop drives at
1808    // once is a property of the machine running it, not of whichever
1809    // repository a given task happens to name - see
1810    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
1811    // fact in the same sense the agent roster is.
1812    let daemon_cfg = prepare(&opts.repo, opts)
1813        .map(|c| c.daemon)
1814        .unwrap_or_default();
1815    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1816
1817    // Something has to be waiting on every question for as long as it is open,
1818    // whether or not the agent's own `magi ask` survived. Its own task rather
1819    // than a step of the poll loop: the poll loop is busy for the whole of a
1820    // run, and an owner's reply must not queue behind one.
1821    let waiter = tokio::spawn(crate::waiter::run(
1822        crate::waiter::Waiter::new(
1823            crate::ask::Questions::at(home.join("questions")),
1824            home.to_path_buf(),
1825            prepare(&opts.repo, opts).ok(),
1826        ),
1827        stop.clone(),
1828    ));
1829
1830    // The follow-up seats for the conductor's questions: the conductor files a
1831    // question and moves on, and each open one gets a deputy that reads the
1832    // owner's reply. Its own task for the same reason the waiter's is.
1833    let deputies = tokio::spawn(crate::deputy::run(
1834        crate::deputy::Deputies::new(
1835            crate::ask::Questions::at(home.join("questions")),
1836            home.to_path_buf(),
1837            prepare(&opts.repo, opts).ok(),
1838            opts.repo.clone(),
1839            daemon_cfg.max_deputies,
1840            {
1841                let stop = stop.clone();
1842                Arc::new(move || stop.parking())
1843            },
1844        ),
1845        stop.clone(),
1846    ));
1847
1848    // Keeps every checkout's origin/main fresh; its own task so a slow remote
1849    // never holds up the poll loop.
1850    let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
1851
1852    // Watches the release-bump pull requests until they land; its own task, not
1853    // tied to any run, because a pending bump outlives the run that opened it.
1854    let release_watch = tokio::spawn(crate::release_watch::run(
1855        crate::release_watch::Watcher::new(
1856            Box::new(crate::release_watch::GhForge),
1857            home.to_path_buf(),
1858        ),
1859        {
1860            let (repo, opts) = (opts.repo.clone(), opts.clone());
1861            move || release_watch_settings(&repo, &opts)
1862        },
1863        stop.clone(),
1864    ));
1865
1866    tracing::info!(
1867        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1868        queue.root().display(),
1869        opts.poll.as_secs(),
1870        opts.max_attempts,
1871        concurrency,
1872        if daemon_cfg.pause_for_interrupts {
1873            ", interrupts enabled"
1874        } else {
1875            ""
1876        }
1877    );
1878
1879    // `--once` drains an already-idle queue without reaching the idle wait,
1880    // but must still perform the startup cleanup.
1881    janitor(&opts.repo, opts, home, worktrees_root).await;
1882    resweep_superseded_attempts(queue, home);
1883
1884    let outcome = poll(
1885        opts,
1886        queue,
1887        &status,
1888        home,
1889        worktrees_root,
1890        stop,
1891        DispatchLimits {
1892            max_concurrent: concurrency,
1893            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1894        },
1895    )
1896    .await;
1897
1898    beat.abort();
1899    waiter.abort();
1900    deputies.abort();
1901    fetcher.abort();
1902    release_watch.abort();
1903    clear_status_at(status_file);
1904    outcome
1905}
1906
1907/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
1908/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
1909fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
1910    let Ok(cfg) = prepare(repo, opts) else {
1911        return (Vec::new(), 0);
1912    };
1913    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
1914        .into_iter()
1915        .map(|r| r.path)
1916        .collect();
1917    // Repositories the daemon has worked in, wherever they live: a task may
1918    // name one outside `[repos] roots`, and its release PR must be watched too.
1919    let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
1920    let runs = crate::run::home().join("runs");
1921    for id in crate::run::list_ids_in(&runs) {
1922        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
1923            .ok()
1924            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1925            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
1926        known.extend(repo);
1927    }
1928    for k in known {
1929        let k = k.canonicalize().unwrap_or(k);
1930        if k.join(".git").exists() && !paths.contains(&k) {
1931            paths.push(k);
1932        }
1933    }
1934    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
1935    if !paths.contains(&own) {
1936        paths.push(own);
1937    }
1938    (paths, cfg.daemon.release_stall_minutes)
1939}
1940
1941/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
1942const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
1943
1944/// Run [`crate::clean::fetch_origins`] every `[repos] fetch_interval` seconds
1945/// until `stop`. The config is re-read each lap; `0` (or an unreadable config)
1946/// disables the fetch for that lap. Never fails.
1947async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
1948    while !stop.stopped() {
1949        let (interval, roots) = match prepare(&repo, &opts) {
1950            Ok(c) => (c.repos.fetch_interval, c.repos.roots),
1951            Err(_) => (0, Vec::new()),
1952        };
1953        if interval > 0 && !roots.is_empty() {
1954            let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
1955            tracing::debug!("fetch origins: {r:?}");
1956        }
1957        // Sleep in slices so a stop or a config change is noticed promptly.
1958        let wait = if interval > 0 { interval } else { 60 };
1959        let mut slept = 0;
1960        while slept < wait && !stop.stopped() {
1961            tokio::time::sleep(Duration::from_secs(1)).await;
1962            slept += 1;
1963        }
1964    }
1965}
1966
1967/// Refresh the status file on a fixed tick.
1968///
1969/// Separate from the loop because a run takes tens of minutes: a status file
1970/// written only between tasks would look stale for the whole of every run, and
1971/// a reader would report the daemon dead exactly while it was busiest.
1972async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1973    loop {
1974        tokio::time::sleep(HEARTBEAT).await;
1975        let snapshot = {
1976            let mut guard = lock(&status);
1977            guard.updated_at = Timestamp::now();
1978            guard.clone()
1979        };
1980        if let Err(e) = write_status_to(&path, &snapshot) {
1981            // A failed heartbeat must not take the daemon down: the loop is the
1982            // product, the status file is only the window onto it.
1983            tracing::warn!("could not refresh the daemon status file: {e:#}");
1984        }
1985    }
1986}
1987
1988/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
1989/// if so, whether that wait is over.
1990#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1991enum LandResume {
1992    /// The task's last run is not parked on a land approval; schedule it
1993    /// like any other candidate.
1994    NotLanding,
1995    /// Parked in `land`, waiting on a question nobody has answered yet.
1996    /// Left alone: attempting it now would only re-observe the same pull
1997    /// request and park again, spending a `gh` call on a decision that has
1998    /// not changed since the last time this was checked.
1999    StillWaiting,
2000    /// Parked in `land`, and the question is settled - answered or
2001    /// abandoned. Resuming this is the one kind of candidate that must not
2002    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2003    Ready,
2004}
2005
2006/// Classify a runnable candidate by whether it is parked on a land-merge
2007/// approval. Read-only - no claim taken, nothing written - so it is cheap
2008/// enough to call on every candidate, every poll.
2009fn land_resume_state(task: &Task) -> LandResume {
2010    let Some(run_id) = task.runs.last() else {
2011        return LandResume::NotLanding;
2012    };
2013    let Ok(state) = RunState::load(run_id) else {
2014        return LandResume::NotLanding;
2015    };
2016    if !implementers_match(task, &state) || !state.parked {
2017        return LandResume::NotLanding;
2018    }
2019    // Parked in `land` on the merge approval, or at `merge` on the owner's
2020    // word about a title/body the posting gate withheld. Told apart by the
2021    // run's own record, not by a status both can share.
2022    let node = if state.status == RunStatus::Landing {
2023        land::APPROVAL_NODE
2024    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2025        crate::github_text::ASK_NODE
2026    } else {
2027        return LandResume::NotLanding;
2028    };
2029    let store = ask::Questions::open();
2030    let waiting = store
2031        .list()
2032        .into_iter()
2033        .filter(|q| &q.run == run_id && q.node == node)
2034        .max_by(|a, b| a.id.cmp(&b.id));
2035    let Some(mut q) = waiting else {
2036        return LandResume::Ready;
2037    };
2038    if !q.status.open() {
2039        return LandResume::Ready;
2040    }
2041    // `ask::ask_and_wait`'s own deadline is what used to retire a question
2042    // nobody ever answered; land's approval bypasses that wait entirely (see
2043    // `land::approval_gate`), so the same deadline has to be enforced here
2044    // instead, or `graph.answer_timeout` silently stops meaning anything for
2045    // a land approval and a run can sit `StillWaiting` forever with nobody
2046    // told to look at it.
2047    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2048    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2049    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2050        q.abandon(format!(
2051            "no answer within {}s of asking",
2052            timeout.as_secs().max(1)
2053        ));
2054        // If this can't be persisted, do not treat the wait as settled on a
2055        // guess: fall through and try again next poll.
2056        if store.put(&mut q).is_ok() {
2057            return LandResume::Ready;
2058        }
2059    }
2060    LandResume::StillWaiting
2061}
2062
2063/// How often the loop rechecks for new work while something it already
2064/// started is still running, rather than sleeping out the whole
2065/// [`Opts::poll`] interval.
2066///
2067/// Short on purpose: this is what lets a land-merge approval that comes back
2068/// while another task is mid-competition be noticed and resumed within a
2069/// fraction of a second, not within the next multi-second poll.
2070const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2071
2072/// How often [`poll`] rechecks the shared build cache against its cap at a
2073/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
2074/// waiting for the queue to run dry.
2075///
2076/// A queue that never empties means the `janitor` call at the bottom of this
2077/// loop's fully-idle branch can go unreached for as long as the backlog
2078/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
2079/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
2080/// 81.8 GiB an idle-only check let it reach before this existed, and it is
2081/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
2082/// backlog of short tasks does not pay for that walk on every poll.
2083const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2084
2085/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
2086/// in `Status::current` - on drop, so both are released even if the attempt
2087/// panics rather than returning.
2088///
2089/// A `Drop` impl rather than statements written after the `.await` it
2090/// guards: a panic unwinds straight past code placed "after" a call, and
2091/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
2092/// that ruling a panic out there is not a bet this loop can make. Without
2093/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
2094/// forever - the idle branch in [`poll`], and with it the janitor, would
2095/// never run again - and a ghost entry in `Status::current` naming a task
2096/// nothing is still working on.
2097struct InFlightGuard<'a> {
2098    status: &'a Arc<Mutex<Status>>,
2099    stop: &'a Stop,
2100    task_id: &'a str,
2101}
2102
2103impl Drop for InFlightGuard<'_> {
2104    fn drop(&mut self) {
2105        lock(self.status).current.retain(|c| c.task != self.task_id);
2106        self.stop.exit();
2107    }
2108}
2109
2110/// State of [`poll`]'s own interrupt-scheduling sequence - see
2111/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
2112/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
2113/// both kept free of `Task`'s non-identity fields on purpose: every decision
2114/// here turns only on task ids and which ones are in flight, so the "never
2115/// more than one run at once" and "exactly one resume" invariants can be
2116/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
2117/// queue - which is exactly the coverage this feature's first two attempts
2118/// were missing.
2119///
2120/// Deliberately in-memory only, not written to disk anywhere: a daemon
2121/// restart mid-sequence loses track of which run it had asked to park and
2122/// which task was meant to run first, and simply falls back to `Idle` -
2123/// see [`drive`]'s own setup. The parked run itself is not lost - it is
2124/// sitting in the queue exactly like any other resumable, interrupted task,
2125/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
2126/// just resumes on the ordinary priority order rather than guaranteed to go
2127/// first. Giving that guarantee a crash-proof memory would mean a new queue
2128/// field and a recovery ordering to go with it, which is exactly the
2129/// complexity this feature's constraints rule out for the one property that
2130/// actually matters: at most one run, ever, at once.
2131#[derive(Debug, Clone, PartialEq, Eq)]
2132enum Interrupt {
2133    /// No interrupt sequence in progress. Ordinary dispatch applies.
2134    Idle,
2135    /// `interrupt_task` is runnable and exactly one other run is in flight;
2136    /// `parked` names that one task's id. Dispatch is withheld from
2137    /// everyone, including `interrupt_task` itself, until it has left
2138    /// flight - only then is `interrupt_task` let through.
2139    ///
2140    /// `parked` is a `Vec` rather than a bare id for symmetry with
2141    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
2142    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
2143    /// when exactly one run is in flight, so it is guaranteed to hold
2144    /// exactly one entry in practice - see that branch's own doc for why
2145    /// more than one is deliberately never attempted.
2146    Parking {
2147        parked: Vec<String>,
2148        interrupt_task: String,
2149    },
2150    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
2151    /// withheld from everyone until it leaves flight - merged, failed, held,
2152    /// it makes no difference - at which point the sequence moves to
2153    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
2154    /// going straight to `Idle` would hand `parked` back to ordinary
2155    /// priority-order dispatch, where a higher-priority task filed in the
2156    /// meantime could start ahead of it.
2157    Running {
2158        parked: Vec<String>,
2159        interrupt_task: String,
2160    },
2161    /// `interrupt_task` left flight; `parked` still names the one run this
2162    /// sequence owes a resume. Dispatch is withheld from everyone except
2163    /// that task - see [`interrupt_gate`] - so the resume this feature
2164    /// promises is never raced by, or run alongside, an unrelated candidate.
2165    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
2166    /// own doc on abandonment - the moment it is no longer runnable at all.
2167    Resuming { parked: Vec<String> },
2168}
2169
2170/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
2171/// and `runnable` are read-only snapshots of this tick's reality, and the
2172/// only side effect the caller still owes the world is asking whichever
2173/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
2174/// site.
2175///
2176/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
2177/// accepted rather than a narrower type because that is what [`poll`] already
2178/// has on hand from [`runnable`], and building a second, smaller list on
2179/// every tick just to satisfy this signature would cost more than it proves.
2180///
2181/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
2182/// back to a task they are waiting on no longer being [`runnable`] - held,
2183/// blocked, deleted, or finished by some other means entirely, all of which
2184/// an operator can do to a task sitting in the queue with no claim on it at
2185/// all, at any moment, interrupt sequence or not. Without this check the
2186/// sequence would wait forever for a dispatch that can never come, and
2187/// `interrupt_gate` would withhold every other task in the queue right along
2188/// with it - a single `magi task hold` on the wrong id turning into a
2189/// daemon that never dispatches anything again.
2190fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2191    match state {
2192        Interrupt::Idle => {
2193            // Not just "something to interrupt": exactly one thing. More
2194            // than one run in flight only happens above the default
2195            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
2196            // one resume, never run alongside anything else" only because
2197            // it is only ever seeded with exactly one id - see
2198            // `Interrupt::Resuming`'s own doc on why releasing more than one
2199            // parked id back to ordinary dispatch cannot be made safe
2200            // against that same setting's own extra concurrency slots.
2201            // Waiting here for the herd to settle to one is the
2202            // simplification this feature's own constraints ask for rather
2203            // than a second concurrency model to reconcile with the first.
2204            if in_flight.len() != 1 {
2205                return Interrupt::Idle;
2206            }
2207            match runnable.iter().find(|t| t.interrupt) {
2208                Some(t) => Interrupt::Parking {
2209                    parked: in_flight.to_vec(),
2210                    interrupt_task: t.id.clone(),
2211                },
2212                None => Interrupt::Idle,
2213            }
2214        }
2215        Interrupt::Parking {
2216            parked,
2217            interrupt_task,
2218        } => {
2219            if in_flight.iter().any(|id| parked.contains(id)) {
2220                // Still waiting for what was in flight to actually stop.
2221                Interrupt::Parking {
2222                    parked,
2223                    interrupt_task,
2224                }
2225            } else if in_flight.contains(&interrupt_task) {
2226                Interrupt::Running {
2227                    parked,
2228                    interrupt_task,
2229                }
2230            } else if runnable.iter().any(|t| t.id == interrupt_task) {
2231                // The parked run(s) are gone, but the interrupt task has not
2232                // been dispatched yet on this tick - `interrupt_gate` is
2233                // what lets it through next.
2234                Interrupt::Parking {
2235                    parked,
2236                    interrupt_task,
2237                }
2238            } else {
2239                // The interrupt task itself is no longer runnable - see this
2240                // function's own doc on abandonment. The parked run(s) still
2241                // get their guaranteed resume; there is simply no interrupt
2242                // to run ahead of them any longer.
2243                Interrupt::Resuming { parked }
2244            }
2245        }
2246        Interrupt::Running {
2247            parked,
2248            interrupt_task,
2249        } => {
2250            if in_flight.contains(&interrupt_task) {
2251                Interrupt::Running {
2252                    parked,
2253                    interrupt_task,
2254                }
2255            } else {
2256                // The interrupt task's own run reached a terminal status,
2257                // whichever one - this is the *only* trigger that moves the
2258                // sequence on, driven straight off the same in-flight
2259                // bookkeeping `poll` already reaps every tick, not a second,
2260                // independent poll of anything.
2261                Interrupt::Resuming { parked }
2262            }
2263        }
2264        Interrupt::Resuming { parked } => {
2265            if in_flight.iter().any(|id| parked.contains(id)) {
2266                // One of the parked runs has been dispatched - the resume
2267                // this sequence owed is fulfilled. Whatever else is left in
2268                // `parked` (ordinarily nothing, at the default concurrency
2269                // of one) rejoins ordinary priority-order dispatch, same as
2270                // any other runnable task.
2271                Interrupt::Idle
2272            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2273                Interrupt::Resuming { parked }
2274            } else {
2275                // Abandonment (see this function's own doc): nothing left in
2276                // `parked` is even runnable any longer.
2277                Interrupt::Idle
2278            }
2279        }
2280    }
2281}
2282
2283/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
2284/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
2285/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
2286/// indistinguishable from any other runnable task - exactly the "off does
2287/// nothing" this feature promises.
2288fn advance_interrupt_tick(
2289    enabled: bool,
2290    state: Interrupt,
2291    in_flight: &[String],
2292    runnable: &[Task],
2293) -> Interrupt {
2294    if !enabled {
2295        return Interrupt::Idle;
2296    }
2297    advance_interrupt(state, in_flight, runnable)
2298}
2299
2300/// Which of this tick's runnable candidates the interrupt sequence actually
2301/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
2302/// each half is assertable on its own: this is the half that keeps a
2303/// competition and an interrupt from ever running at the same moment.
2304fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2305    match state {
2306        Interrupt::Idle => candidates,
2307        Interrupt::Parking {
2308            parked,
2309            interrupt_task,
2310        } => {
2311            if in_flight.iter().any(|id| parked.contains(id)) {
2312                Vec::new()
2313            } else {
2314                candidates
2315                    .into_iter()
2316                    .filter(|t| &t.id == interrupt_task)
2317                    .collect()
2318            }
2319        }
2320        Interrupt::Running { .. } => Vec::new(),
2321        // At most one: even if `parked` names more than one id (more than
2322        // one run was in flight when the sequence began, only possible
2323        // above the default `max_concurrent_runs = 1`), only the first match
2324        // is offered. Capping this to a single candidate - not merely to
2325        // `parked`'s own ids - is what makes "exactly one resume, never two
2326        // dispatched together" true regardless of how many ordinary slots
2327        // happen to be free this tick.
2328        Interrupt::Resuming { parked } => candidates
2329            .into_iter()
2330            .find(|t| parked.contains(&t.id))
2331            .into_iter()
2332            .collect(),
2333    }
2334}
2335
2336/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
2337/// bundled into one parameter so `poll`'s own signature stays readable -
2338/// see [`drive`]'s call site for where these are actually read.
2339struct DispatchLimits {
2340    /// How many *ordinary* candidates run at once. See
2341    /// [`crate::config::Daemon::max_concurrent_runs`].
2342    max_concurrent: usize,
2343    /// See [`crate::config::Daemon::pause_for_interrupts`].
2344    pause_for_interrupts: bool,
2345}
2346
2347/// Which semaphore, if any, dispatching a candidate should draw its permit
2348/// from.
2349///
2350/// Pure and separate from [`poll`]'s loop body for the same reason
2351/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
2352/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
2353/// exactly the policy this feature adds, and a policy only exercisable by
2354/// running the whole loop is a policy nobody checks.
2355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2356enum PermitKind {
2357    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
2358    /// Checked first - a task can be both a land resume and marked
2359    /// [`Task::urgent`], and the resume's own "must not queue behind
2360    /// anything" guarantee takes precedence.
2361    None,
2362    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
2363    /// (never in addition to trying) the ordinary pool. This is what lets
2364    /// an urgent task dispatch while every ordinary slot is already checked
2365    /// out, and what stops a second urgent task from opening a third run: it
2366    /// waits on this same one-slot semaphore rather than falling through to
2367    /// the ordinary one.
2368    Urgent,
2369    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
2370    /// above.
2371    Ordinary,
2372}
2373
2374/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
2375/// own boolean, already computed by the caller from [`land_resume_state`].
2376fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2377    if priority {
2378        PermitKind::None
2379    } else if urgent {
2380        PermitKind::Urgent
2381    } else {
2382        PermitKind::Ordinary
2383    }
2384}
2385
2386struct DispatchClaim {
2387    task: Task,
2388    claim: crate::queue::Claim,
2389    permit: Option<tokio::sync::OwnedSemaphorePermit>,
2390}
2391
2392/// Claim and re-read before choosing a lane: a queue listing may predate an
2393/// urgent toggle. All unsuccessful paths release the claim without an attempt.
2394fn claim_dispatch(
2395    queue: &Queue,
2396    candidate: &Task,
2397    cooling_down: bool,
2398    ordinary: &Arc<tokio::sync::Semaphore>,
2399    urgent: &Arc<tokio::sync::Semaphore>,
2400) -> Option<DispatchClaim> {
2401    let Ok(claim) = queue.claim(&candidate.id) else {
2402        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2403        return None;
2404    };
2405    let task = match queue.get(&candidate.id) {
2406        Ok(t) if t.status.runnable() => t,
2407        Ok(_) => return None,
2408        Err(e) => {
2409            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2410            return None;
2411        }
2412    };
2413    let resume = land_resume_state(&task);
2414    if resume == LandResume::StillWaiting {
2415        return None;
2416    }
2417    let priority = resume == LandResume::Ready;
2418    if !priority && cooling_down {
2419        return None;
2420    }
2421    // Never borrow an ordinary slot when the single urgent slot is busy.
2422    // Keep scanning other candidates when either pool has no free slot.
2423    let permit = match permit_kind(priority, task.urgent) {
2424        PermitKind::None => None,
2425        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
2426        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
2427    };
2428    Some(DispatchClaim {
2429        task,
2430        claim,
2431        permit,
2432    })
2433}
2434
2435/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
2436/// teardown and cannot skip the teardown on an early return.
2437///
2438/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
2439/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
2440/// land approval that has since been answered is dispatched outside that
2441/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
2442/// the whole point of parking there is that it must not queue behind
2443/// whatever else the loop happens to be running, even at the default of one.
2444/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
2445/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
2446/// these exemptions is still subject to the interrupt gate below, urgent
2447/// included: a land-resume or urgent candidate is exactly as much "something
2448/// else running" as an ordinary one from the interrupt sequence's point of
2449/// view, and letting either slip through while a run is being parked, or
2450/// while the interrupt task itself has the floor, is precisely the second
2451/// run 75dd's own "at most one run, ever, at once" guarantee must never
2452/// allow - see [`Interrupt`]'s own doc.
2453async fn poll(
2454    opts: &Opts,
2455    queue: &Queue,
2456    status: &Arc<Mutex<Status>>,
2457    home: &Path,
2458    worktrees_root: &Path,
2459    stop: &Stop,
2460    limits: DispatchLimits,
2461) -> Result<()> {
2462    let DispatchLimits {
2463        max_concurrent,
2464        pause_for_interrupts,
2465    } = limits;
2466    // Only consulted by `once`, where a task that just failed is still
2467    // `runnable` and would otherwise be picked up again inside the same drain.
2468    // In the long-running mode a later poll retrying a failed task is the point,
2469    // and the attempt counter is what bounds it.
2470    let mut attempted: Vec<String> = Vec::new();
2471    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2472    // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
2473    // entirely separate from `sem`: an urgent candidate must dispatch
2474    // alongside whatever `sem` already has checked out, never by waiting for
2475    // one of those ordinary slots to free up and never by growing
2476    // `max_concurrent_runs` itself. Sized at one, not unbounded - see
2477    // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
2478    // first on this same slot rather than opening a third run.
2479    let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2480    // A quota hit is a fact about the machine, not the task that happened to
2481    // surface it, and every other *ordinary* candidate is no less likely to
2482    // hit the same wall - see the warning below. A land-merge resume is
2483    // exempt: it is a human decision finishing, not a fresh competition, and
2484    // must not sit out a quota cooldown it did not cause.
2485    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2486    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2487    let mut conductor = Conductor::new();
2488    // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
2489    // a congested queue would otherwise starve of the fully-idle branch below.
2490    let mut cache_last_checked: Option<Timestamp> = None;
2491    // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
2492    let mut interrupt = Interrupt::Idle;
2493    // The `Pause` handed to each dispatched candidate's own `Runner` - see
2494    // `attempt`'s new parameter - kept here so the tick that decides to park
2495    // a run for an interrupt can reach that specific run's handle and no
2496    // other's. Pruned to whatever is still in flight at the top of every
2497    // tick, so a finished attempt's handle does not linger.
2498    let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2499        std::collections::HashMap::new();
2500
2501    while !stop.stopped() {
2502        lock(status).polls += 1;
2503
2504        // Reap whatever finished since the last tick without blocking on
2505        // anything still running. `InFlightGuard` already released the slot
2506        // even if the spawned attempt panicked; this only surfaces that it
2507        // happened, since a panic swallowed here otherwise leaves no trace.
2508        while let Some(result) = inflight.try_join_next() {
2509            if let Err(e) = result {
2510                tracing::error!("a spawned attempt did not finish cleanly: {e}");
2511                notices::raise(Notice::error(
2512                    "loop:attempt",
2513                    "A queued attempt ended abnormally; check the task it was running.",
2514                ));
2515            }
2516        }
2517
2518        let swept = sweep_stale_claims(queue, STALE_CLAIM);
2519        if !swept.is_empty() {
2520            tracing::warn!(
2521                "swept {} stale claim(s) left behind by an earlier daemon: {}",
2522                swept.len(),
2523                swept.join(", ")
2524            );
2525        }
2526        // Capture stalled work before reclaiming it. A dead daemon's ordinary
2527        // lock is swept and reclaimed in this same poll, but the conductor
2528        // must still see that it was stranded rather than only its mechanical
2529        // terminal state.
2530        let now = Timestamp::now();
2531
2532        // No run this daemon spawned is mid-compile right now, whether or
2533        // not another candidate is about to start - see
2534        // `maybe_prune_cache_between_runs`'s own doc for why this cannot
2535        // wait for the queue to run dry.
2536        if !stop.busy_now() {
2537            maybe_prune_cache_between_runs(
2538                &opts.repo,
2539                opts,
2540                home,
2541                stop,
2542                &mut cache_last_checked,
2543                now,
2544            )
2545            .await;
2546        }
2547
2548        let stalled = stalled_tasks(queue, home, now);
2549        let stalled_ids: std::collections::BTreeSet<_> =
2550            stalled.iter().map(|task| task.id.clone()).collect();
2551        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2552        if !reclaimed.is_empty() {
2553            tracing::warn!(
2554                "reclaimed {} task(s) left `running` by a daemon that never \
2555                 recorded the outcome: {}",
2556                reclaimed.len(),
2557                reclaimed.join(", ")
2558            );
2559        }
2560        let abandoned_runs = reclaim_abandoned_runs(home, now);
2561        if !abandoned_runs.is_empty() {
2562            tracing::warn!(
2563                "failed {} run(s) left behind by a killed process, past every \
2564                 active seat's own timeout: {}",
2565                abandoned_runs.len(),
2566                abandoned_runs.join(", ")
2567            );
2568        }
2569
2570        // `home`, not `ask::Questions::open()`'s own process-global default:
2571        // `poll` is handed its home explicitly precisely so a test can point
2572        // it elsewhere, the same reason `Queue::at` and the status file path
2573        // are parameters rather than resolved here - see `drive`'s own doc.
2574        let questions = Questions::at(home.join("questions"));
2575
2576        // Deterministic: no model, run before the conductor sees anything so
2577        // its input reflects the queue's current, already-resolved state.
2578        resolve_blockers(queue, &questions);
2579        apply_choice_actions(queue, &questions, home);
2580        triage::apply_answers(queue, &questions);
2581        reconcile_task_questions(queue, &questions);
2582        // Tell the chat a filed task or watched command has ended. Reconciled
2583        // here regardless of how it ended, and started only when no
2584        // upgrade is parking (the draft then waits for a manual resume).
2585        {
2586            let talks = crate::talk::Talks::at(home.join("talks"));
2587            crate::chat_notify::sweep(queue, &talks, home);
2588            crate::chat_watch::sweep(home, &talks);
2589            crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
2590        }
2591
2592        // The conductor gets one look per cycle, right before the loop takes
2593        // its next task, and only when there is something new to look at -
2594        // see `Conductor::worth_a_look`'s own doc for why "stalled is
2595        // non-empty" is the wrong test. Checked before `prepare` so an
2596        // unchanged cycle never pays for a synchronous config load.
2597        let finished: Vec<Task> = finished_tasks(queue)
2598            .into_iter()
2599            .filter(|task| !stalled_ids.contains(&task.id))
2600            // A parked run is waiting for this loop, not for a decision: the
2601            // conductor must not get to hold it or requeue it (a requeue
2602            // sets `fresh_start` and re-competes) before `attempt` resumes.
2603            .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2604            .collect();
2605        let queued = queued_tasks(queue);
2606        // An empty queue has nothing to arrange. In particular, do not let
2607        // the conductor's initial snapshot cause synchronous config I/O
2608        // between the caller's stop notification and the idle wait below.
2609        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2610            && conductor.worth_a_look(queue, &stalled, &finished)
2611        {
2612            match prepare(&opts.repo, opts) {
2613                Ok(cfg) => {
2614                    conductor
2615                        .maybe_run(
2616                            &cfg,
2617                            &opts.repo,
2618                            queue,
2619                            &questions,
2620                            home,
2621                            &queued,
2622                            &stalled,
2623                            &finished,
2624                            opts.max_attempts,
2625                        )
2626                        .await;
2627                }
2628                Err(e) => {
2629                    tracing::warn!("conductor: no config: {e:#}");
2630                    notices::raise(Notice::warn(
2631                        "loop:no-config",
2632                        "The loop could not read this repository's config, so held tasks are not being triaged.",
2633                    ));
2634                }
2635            }
2636        }
2637
2638        let candidates: Vec<Task> = runnable(queue)
2639            .into_iter()
2640            .filter(|t| !opts.once || !attempted.contains(&t.id))
2641            .collect();
2642
2643        // A task id only stays a key here while its attempt is genuinely in
2644        // flight; `status.current` is the same liveness fact `InFlightGuard`
2645        // maintains for the phone's own status file, so this piggybacks on
2646        // it rather than tracking a second copy of the same thing.
2647        let in_flight: Vec<String> = lock(status)
2648            .current
2649            .iter()
2650            .map(|c| c.task.clone())
2651            .collect();
2652        interrupt_pauses.retain(|id, _| in_flight.contains(id));
2653
2654        interrupt =
2655            advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2656        if let Interrupt::Parking {
2657            parked,
2658            interrupt_task,
2659        } = &interrupt
2660        {
2661            let reason = format!(
2662                "task {} asked to run first",
2663                crate::run::short_of(interrupt_task)
2664            );
2665            for id in parked {
2666                if let Some(pause) = interrupt_pauses.get(id) {
2667                    pause.park_because(reason.clone());
2668                }
2669            }
2670        }
2671        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2672
2673        let cooling_down =
2674            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2675
2676        let mut started_any = false;
2677        for candidate in candidates {
2678            if stop.stopped() {
2679                break;
2680            }
2681
2682            let Some(DispatchClaim {
2683                mut task,
2684                claim,
2685                permit,
2686            }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
2687            else {
2688                continue;
2689            };
2690
2691            let task_id = task.id.clone();
2692            attempted.push(task_id.clone());
2693            lock(status).idle = false;
2694            // A stop asked for from here on is "finishing", not "stopped": the
2695            // run gets to reach a terminal status before the loop returns.
2696            stop.enter();
2697            started_any = true;
2698
2699            // A fresh, unshared handle - never `stop.pause()` - so parking
2700            // this run for an interrupt cannot leak into any other run this
2701            // loop ever drives. See `Pause`'s own doc.
2702            let run_pause = crate::graph::Pause::new();
2703            interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2704
2705            let opts = opts.clone();
2706            let queue = queue.clone();
2707            let status = Arc::clone(status);
2708            let stop = stop.clone();
2709            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
2710            inflight.spawn(async move {
2711                // Held for the whole attempt: dropping either at the end of
2712                // this task is what releases the claim and, for an ordinary
2713                // candidate, frees its concurrency slot back to the loop.
2714                let _claim = claim;
2715                let _permit = permit;
2716                // See `InFlightGuard`: this must survive a panic inside `attempt`.
2717                let _inflight = InFlightGuard {
2718                    status: &status,
2719                    stop: &stop,
2720                    task_id: &task_id,
2721                };
2722                let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2723                lock(&status).completed += 1;
2724                // A quota loss is a fact about the machine, not this task, and
2725                // the next ordinary candidate the loop offers is no less
2726                // likely to hit the same wall: without a cooldown here a
2727                // whole backlog can be run - and failed - in the seconds it
2728                // takes each attempt to notice the CLI is out of quota.
2729                let now = Timestamp::now();
2730                if let Some(until) = cooldown_until(&quota, now) {
2731                    let wait = until.as_second() - now.as_second();
2732                    *lock(&quota_cooldown_until) = Some(until);
2733                    let hint = quota
2734                        .iter()
2735                        .find(|q| q.reset.is_some())
2736                        .and_then(|q| q.reset.as_deref());
2737                    match hint {
2738                        Some(h) => tracing::warn!(
2739                            "quota hit; waiting {wait}s before taking another ordinary task \
2740                             (CLI reported reset: {h})"
2741                        ),
2742                        None => tracing::warn!(
2743                            "quota hit; waiting {wait}s before taking another ordinary task \
2744                             (no reset hint reported)"
2745                        ),
2746                    }
2747                }
2748            });
2749        }
2750
2751        if started_any {
2752            continue;
2753        }
2754
2755        if stop.busy_now() {
2756            // Something started on an earlier tick is still running. Recheck
2757            // soon rather than sleeping out the whole poll interval - a freed
2758            // slot, or a land approval answered mid-run, must not sit idle
2759            // for it.
2760            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2761            continue;
2762        }
2763
2764        // Truly idle: nothing new to start and nothing still running.
2765        lock(status).idle = true;
2766        if opts.once {
2767            // A one-shot drain must perform the same post-work cleanup as a
2768            // daemon that reached a normal idle interval. The startup pass
2769            // cannot see runs or cache files produced by this drain.
2770            janitor(&opts.repo, opts, home, worktrees_root).await;
2771            resweep_superseded_attempts(queue, home);
2772            triage_held(queue, home, opts).await;
2773            break;
2774        }
2775        stop.idle(opts.poll).await;
2776        if stop.stopped() {
2777            continue;
2778        }
2779        // Housekeeping only after a full quiet interval. Running it before
2780        // the first idle wait can block the executor while an operator's
2781        // stop request is waiting to be scheduled, defeating Stop's retained
2782        // wake permit. No run can start while this branch is active, so the
2783        // janitor still never races an in-flight compile.
2784        janitor(&opts.repo, opts, home, worktrees_root).await;
2785        resweep_superseded_attempts(queue, home);
2786        triage_held(queue, home, opts).await;
2787    }
2788
2789    // Never return while a run is still in flight, whichever way the loop
2790    // above exited: a stop only sets a flag - see `serve_until` - and
2791    // returning here while `inflight` still holds spawned work would abandon
2792    // it exactly as a mid-node kill would.
2793    while let Some(result) = inflight.join_next().await {
2794        if let Err(e) = result {
2795            tracing::error!("a spawned attempt did not finish cleanly: {e}");
2796            notices::raise(Notice::error(
2797                "loop:attempt",
2798                "A queued attempt ended abnormally; check the task it was running.",
2799            ));
2800        }
2801    }
2802    Ok(())
2803}
2804
2805/// Run one claimed task to a terminal status and record the outcome.
2806///
2807/// Every transition is flushed to the queue as it happens, so the state on disk
2808/// is what actually occurred rather than what this process still intends to
2809/// write.
2810async fn attempt(
2811    opts: &Opts,
2812    queue: &Queue,
2813    status: &Arc<Mutex<Status>>,
2814    stop: &Stop,
2815    interrupt_pause: crate::graph::Pause,
2816    task: &mut Task,
2817) -> Vec<QuotaLoss> {
2818    let repo = repo_for(task, &opts.repo);
2819    tracing::info!(
2820        "task {} — {} (repo {})",
2821        task.short(),
2822        task.title,
2823        repo.display()
2824    );
2825
2826    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
2827    // failure here is the network's or the operator's, not the task's: hold
2828    // without spending an attempt, never fall back to a possibly stale copy.
2829    let explicit = match &task.overrides {
2830        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
2831        Some(_) => opts.config.as_deref(),
2832        None => opts.config.as_deref(),
2833    };
2834    if let Err(e) = Config::discover_fetched(&repo, explicit).await {
2835        let reason = format!("[config] {e:#}");
2836        task.last_error = Some(reason.clone());
2837        task.hold_machine(Some(reason.clone()));
2838        record(queue, task);
2839        tracing::warn!("holding {}: {reason}", task.short());
2840        return Vec::new();
2841    }
2842    let mut config = match prepare_for(&repo, opts, task) {
2843        Ok(c) => c,
2844        Err(e) => {
2845            // A setup failure spends an attempt even though no run was minted.
2846            // Without that, a task naming a repository that does not exist
2847            // would be retried at every poll for as long as the daemon lives.
2848            task.attempts += 1;
2849            task.fail(format!("config: {e:#}"), opts.max_attempts);
2850            record(queue, task);
2851            return Vec::new();
2852        }
2853    };
2854    apply_task_implementers(&mut config, task);
2855    let p = phrases(&config.graph.language);
2856    let start_failed = p.could_not_start;
2857
2858    // The free-space gate, checked *before* anything is minted: a task that
2859    // waits out a full disk costs nothing yet, and must not spend an attempt
2860    // or start a run the machine cannot finish. Held tasks stay in the list
2861    // for the human to see, and `magi task release` re-queues them when space
2862    // comes back - the same recovery as any other hold. A volume whose free
2863    // space cannot be measured closes the gate too: starting a run blind on a
2864    // disk that may be full is how the machine ends up with 6.7 GB free.
2865    if let Some(reason) = disk_gate(&repo, &config) {
2866        task.last_error = Some(reason.clone());
2867        task.hold_machine(Some(reason.clone()));
2868        record(queue, task);
2869        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2870        // Stable wording - the free-space figures live in the task's hold
2871        // reason, and changing numbers would relight the bell every poll.
2872        notices::raise(
2873            Notice::warn(
2874                &format!("disk:{}", repo.display()),
2875                "A task was held for want of free disk space; free some, then release it from the queue.",
2876            )
2877            .link(Link::Task {
2878                id: task.id.clone(),
2879            }),
2880        );
2881        return Vec::new();
2882    }
2883
2884    // A resumable run of this task is carried on, never re-competed. The
2885    // candidates are built and paid for, and a fresh competition races a
2886    // second implementation against them.
2887    //
2888    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
2889    // started 3cbf on the same task a moment later, duplicating two and a
2890    // half hours of agent work. Then b25f stalled on a judge that timed out
2891    // and one that answered with no JSON - `quota: 0`, so nothing the machine
2892    // was to blame for - and 4043 started **one second** later, buying three
2893    // fresh implementations to reach the same panel. `RunStatus::resumable`
2894    // rather than `!done()` is what catches the second case: a stall is
2895    // terminal, and its cheap recovery re-asks only the absent seats.
2896    //
2897    // A load failure is warned about rather than silently read as "not
2898    // resumable": the alternative is exactly what let a schema mismatch on
2899    // run `eba2` fall through to a full re-competition with nobody told why.
2900    // `crate::conduct` is what actually offers a better answer than
2901    // `Runner::start` here (see `Recovery::Review`), once this task's next
2902    // failure shows it up as `held`/`failed` with the run state unreadable.
2903    let unfinished = (!task.fresh_start)
2904        .then(|| unfinished_run(&task.runs, task.short()))
2905        .flatten()
2906        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
2907    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
2908    // branch survived, and this reopens exactly that branch as a
2909    // review-only pass rather than resuming or competing again. Consumed
2910    // (cleared) here whichever way this goes, so it never outlives this one
2911    // attempt - see `queue::Task::review_branch`.
2912    let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
2913    let review_branch = take_review_branch(task, previous.as_ref());
2914    let branch_exists = match &review_branch {
2915        Some(branch) => crate::git::branch_exists(&repo, branch)
2916            .await
2917            .unwrap_or(false),
2918        None => false,
2919    };
2920    // An explicit `magi review <branch>` is reviewed whatever happens to the
2921    // branch unless an explicit implementer change requires fresh work. An
2922    // unfinished run of the same task still wins, so a retry resumes.
2923    let proposed = match (&review_branch, &unfinished, &task.review_of) {
2924        (None, None, Some(branch)) => Starter::Review(branch.clone()),
2925        _ => choose_starter(
2926            review_branch.as_deref(),
2927            branch_exists,
2928            unfinished.as_deref(),
2929        ),
2930    };
2931    let starter = if let Some(selected) = &task.pr_recovery {
2932        if selected.check_task(&task.id, &task.instruction).is_ok() {
2933            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
2934        } else {
2935            Starter::Review(selected.branch.clone())
2936        }
2937    } else {
2938        starter_with_implementers(task, previous.as_ref(), proposed)
2939    };
2940    // Absolute paths of the files the task was filed with, re-read from the
2941    // task now so a file attached while it was held reaches a resumed run
2942    // too. A stored name whose file has gone is an error before any agent is
2943    // paid for, never a silent omission the implementer cannot notice.
2944    let attachments = match task_attachments(queue, task) {
2945        Ok(a) => a,
2946        Err(e) => {
2947            task.attempts += 1;
2948            task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
2949            record(queue, task);
2950            return Vec::new();
2951        }
2952    };
2953    let started = match &starter {
2954        Starter::Review(_) if task.pr_recovery.is_some() => {
2955            let selected = task.pr_recovery.clone().expect("selected recovery");
2956            match selected.check_task(&task.id, &task.instruction) {
2957                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
2958                    .await
2959                    .map(|mut r| {
2960                        r.state.attachments = attachments.clone();
2961                        r
2962                    }),
2963                Err(e) => Err(e),
2964            }
2965        }
2966        Starter::Review(branch) => {
2967            tracing::info!(
2968                "task {} reopens `{branch}` as a review-only pass",
2969                task.short()
2970            );
2971            // Every earlier attempt is superseded by the one being minted
2972            // now, so a branch one of them still holds may be taken over.
2973            let takeover = crate::handover::Takeover {
2974                earlier: task.earlier_attempts().to_vec(),
2975                home: crate::run::home(),
2976                choice: take_divergence_answer(branch, &config.merge.remote, task),
2977                task_instruction: Some(instruction_for(task)),
2978            };
2979            Runner::review_taking_over(
2980                &repo,
2981                branch,
2982                config,
2983                Some(takeover),
2984                crate::run::Origin::queue(&task.id),
2985            )
2986            .await
2987        }
2988        Starter::Resume(id) => {
2989            tracing::info!("resuming run {id} rather than competing again");
2990            Runner::resume(id).and_then(|mut r| {
2991                if r.state.prep_failure.is_some() {
2992                    let approval = task
2993                        .resumption
2994                        .as_ref()
2995                        .context("preparation retry requires an explicit task release")?;
2996                    r.retry_preparation(approval.at)?;
2997                }
2998                if let Some(instruction) =
2999                    prepare_instruction(&starter, Some(&r.state.instruction), task)
3000                {
3001                    r.state.instruction = instruction;
3002                }
3003                r.state.attachments = attachments.clone();
3004                // The merge choice of a hand-started task still holds when the
3005                // run it resumes was started under another one.
3006                if let Some(mode) = task
3007                    .overrides
3008                    .as_ref()
3009                    .and_then(|o| o.merge.as_deref())
3010                    .and_then(|m| merge_mode(m).ok())
3011                {
3012                    r.state.config.merge.mode = mode;
3013                }
3014                Ok(r)
3015            })
3016        }
3017        Starter::Start => {
3018            if let Some(branch) = &review_branch {
3019                tracing::warn!(
3020                    "conductor chose review for task {} but branch `{branch}` no longer \
3021                     exists; requeuing as a fresh competition instead",
3022                    task.short()
3023                );
3024            }
3025            let instruction = prepare_instruction(&starter, None, task)
3026                .unwrap_or_else(|| task.instruction.clone());
3027            Runner::start_naming(
3028                &repo,
3029                instruction,
3030                &task.title,
3031                config,
3032                crate::run::Origin::queue(&task.id),
3033            )
3034            .await
3035            .map(|mut r| {
3036                r.state.attachments = attachments.clone();
3037                r
3038            })
3039        }
3040    };
3041    let mut runner = match started {
3042        Ok(r) => r,
3043        // A branch an earlier attempt still holds and magi will not release
3044        // by itself is the operator's call, not a failed attempt: hold the
3045        // task with the reason, spend nothing, and say so on the bell.
3046        Err(e) if task.pr_recovery.is_some() => {
3047            task.attempts += 1;
3048            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3049                task.link_run(&partial.run);
3050                task.record_pass(&partial.run, 0, task.attempts, None);
3051            }
3052            task.last_error = Some(format!("{start_failed}{e:#}"));
3053            task.hold_unrequested_retry(Some(format!(
3054                "Selected public-head recovery could not start: {e:#}. Correct the cause and use `magi task recover-pr` with the approved public head; automatic recovery is stopped."
3055            )));
3056            record(queue, task);
3057            return Vec::new();
3058        }
3059        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
3060            let detail = match e.downcast_ref::<crate::handover::Refused>() {
3061                Some(r) => (p.handover_refused)(r),
3062                None => format!("{e:#}"),
3063            };
3064            let reason = format!("{start_failed}{detail}");
3065            task.last_error = Some(reason.clone());
3066            // Consumed above by `take`; keep it so the released task retries
3067            // as a review of this same branch.
3068            let branch = match &starter {
3069                Starter::Review(branch) => Some(branch.clone()),
3070                _ => None,
3071            };
3072            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
3073            // one page; the guidance rides in the reason, fixed per state so a
3074            // re-put never changes the wording and relights it.
3075            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
3076            record(queue, task);
3077            tracing::warn!(
3078                "holding {} for a branch it cannot take over: {e:#}",
3079                task.short()
3080            );
3081            return Vec::new();
3082        }
3083        // A branch that differs between here and the remote in ways magi
3084        // cannot prove are the same change is a decision for the owner, not a
3085        // failed attempt: ask with both sides laid out, spend no attempt, and
3086        // let the answer requeue the task.
3087        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
3088            let d = e
3089                .downcast_ref::<crate::reconcile::Diverged>()
3090                .expect("checked by the guard");
3091            let mut q = ask::Question::new(
3092                task.id.clone(),
3093                crate::reconcile::NODE.to_owned(),
3094                crate::reconcile::SEAT.to_owned(),
3095                d.summary(),
3096                d.detail(),
3097                d.choices(),
3098            );
3099            match Questions::open().put(&mut q) {
3100                Ok(()) => {
3101                    task.last_error = Some(format!("{e:#}"));
3102                    // Consumed above by `take`; the answer has to reach a review
3103                    // of this same branch, so keep pointing the task at it.
3104                    task.review_branch = Some(d.branch.clone());
3105                    task.review_instruction = Some(task.instruction.clone());
3106                    task.block(vec![q.id.clone()], Some(d.summary()));
3107                }
3108                Err(put) => {
3109                    tracing::warn!("could not file the divergence question: {put:#}");
3110                    task.attempts += 1;
3111                    task.fail(format!("{start_failed}{e:#}"), opts.max_attempts);
3112                }
3113            }
3114            record(queue, task);
3115            return Vec::new();
3116        }
3117        Err(e) => {
3118            // The answer was stale and nothing was applied: keep pointing at
3119            // the branch so the next attempt asks again against its new tips.
3120            // Nothing went wrong with the task, so no attempt is spent: a
3121            // budget one short of its limit must not hold it instead of
3122            // letting the question be asked again.
3123            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3124                && let Starter::Review(branch) = &starter
3125            {
3126                task.review_branch = Some(branch.clone());
3127                task.review_instruction = Some(task.instruction.clone());
3128                task.last_error = Some(format!("{start_failed}{e:#}"));
3129                task.status = crate::queue::TaskStatus::Failed;
3130                record(queue, task);
3131                return Vec::new();
3132            }
3133            task.attempts += 1;
3134            task.last_error = Some(format!("{start_failed}{e:#}"));
3135            task.hold_unrequested_retry(Some(format!(
3136                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
3137            )));
3138            record(queue, task);
3139            return Vec::new();
3140        }
3141    };
3142    runner.state.task_instruction = Some(task.instruction.clone());
3143    // The follow-up depth is fixed now, while the task certainly exists:
3144    // deleting it later must not reset the cap (`crate::followup`).
3145    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3146    if runner.state.origin_chat.is_none() {
3147        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
3148    }
3149    // A stop that means "park" reaches the graph through this handle.
3150    runner.on_pause(stop.pause());
3151    // `poll`'s interrupt scheduler reaches this one run - and no other -
3152    // through this handle. See `Pause`'s own doc for why these are never
3153    // the same one.
3154    runner.watch_interrupt(interrupt_pause);
3155
3156    // `start` has minted the run, so the task can now point at it. Persisting
3157    // `Running` before `execute` is what makes a crash mid-run legible.
3158    let run = runner.state.id.clone();
3159    task.start(run.clone());
3160    record(queue, task);
3161    lock(status).current.push(Current {
3162        task: task.id.clone(),
3163        run,
3164    });
3165
3166    // `RunState::quota` is the run's whole history across every resume, so
3167    // only what this execution added may arm the cooldown or earn a refund.
3168    let quota_before = runner.state.quota.clone();
3169    runner.state.next_pass_task_entry = true;
3170    let result = runner.execute().await;
3171    finish_attempt(
3172        opts.max_attempts,
3173        queue,
3174        task,
3175        &runner.state,
3176        &quota_before,
3177        result,
3178    )
3179}
3180
3181/// Settle `task` after its run executed: the verdict, the diagnosis, the
3182/// supersession of earlier attempts and the save. Shared by the loop and by
3183/// `magi run --resume`, so an attempt is counted one way wherever it ran.
3184/// Returns the quota losses this execution added to the run.
3185pub fn finish_attempt(
3186    max_attempts: usize,
3187    queue: &Queue,
3188    task: &mut Task,
3189    state: &RunState,
3190    quota_before: &[QuotaLoss],
3191    result: Result<()>,
3192) -> Vec<QuotaLoss> {
3193    let detail = match result {
3194        Ok(()) => describe(state),
3195        Err(e) => format!("{e:#}"),
3196    };
3197    let fresh = losses_this_attempt(quota_before, &state.quota);
3198    let verdict = Verdict {
3199        status: state.status,
3200        // A run that opened a pull request handed its work over, whatever the
3201        // gate then decided about merging it.
3202        left_pr: state.pr.is_some(),
3203        // Only a rate limit earns the task its attempt back - and only one
3204        // suffered now: a refund justified by a previous session's loss is
3205        // the same mistake as re-arming the cooldown from it. A stalled run
3206        // resumed without hitting quota again therefore spends its attempt,
3207        // like any other failure of the task's own.
3208        quota_hit: !fresh.is_empty(),
3209        // A run that parked was asked to stop; that is not a failure and must
3210        // not spend an attempt, or replacing the binary a few times would
3211        // exhaust a task's budget without an agent ever misbehaving.
3212        parked: state.parked,
3213        // A quota loss that left nothing viable is the same machine fact as a
3214        // `Stalled` quota loss; see `settle`'s doc table.
3215        no_viable_candidates: state.viable().is_empty(),
3216    };
3217    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3218    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
3219        task.hold_unrequested_retry(Some(format!(
3220            "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
3221        )));
3222    }
3223    if task.status == TaskStatus::Done {
3224        supersede_prior_runs(task, &crate::run::home());
3225    }
3226    record(queue, task);
3227    tracing::info!(
3228        "task {} is {} after run {} ({})",
3229        task.short(),
3230        task.status.as_str(),
3231        state.short(),
3232        label(state.status)
3233    );
3234    fresh
3235}
3236
3237/// A task a hand-started run leaves runnable (failed with attempts to spare,
3238/// or requeued) is **held**: nobody asked for a retry, and a loop starting
3239/// later must not spend agent calls on it. `magi task release` retries.
3240pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3241    // A run parked on the owner's word about a withheld PR title/body is not a
3242    // failure nobody asked to retry: it resumes (answer, or the neutral text on
3243    // the deadline) the moment a loop serves the queue, via `land_resume_state`.
3244    // Holding it would keep it from ever being a candidate.
3245    let waits_on_owner = withheld_text_wait(task).is_some();
3246    if task.status.runnable() && !waits_on_owner {
3247        let why = task.last_error.clone().map_or_else(
3248            || "the run did not finish".to_owned(),
3249            |e| format!("the run did not finish: {e}"),
3250        );
3251        task.hold_unrequested_retry(Some(format!(
3252            "{why}. It was started by hand, so it is not retried \
3253             automatically; `magi task release` retries it."
3254        )));
3255        record(queue, task);
3256    }
3257}
3258
3259/// Whether an attempt at a task whose newest run is `run` would resume that
3260/// run rather than start a fresh competition. `magi run --resume` hands a run
3261/// to a live loop only when this holds.
3262#[must_use]
3263pub fn loop_would_resume(run: &str) -> bool {
3264    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3265}
3266
3267/// A loop in another process that is alive right now: a fresh heartbeat in
3268/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
3269/// carries the pid it published (`None` inside when it published none - a
3270/// fresh heartbeat is still evidence of a live loop).
3271///
3272/// The one judgement of "is somebody else serving this queue", shared by the
3273/// web UI's refusal to start a second loop and by `magi run` / `magi review`
3274/// deciding whether to hand a task to the loop. A claim file proves nothing
3275/// here: whether a claim succeeds says nothing about whether its owner lives.
3276#[must_use]
3277pub fn foreign_loop(
3278    reading: Option<&Reading>,
3279    now: Timestamp,
3280    own_pid: u32,
3281) -> Option<Option<u32>> {
3282    let reading = reading.filter(|r| r.running(now))?;
3283    match reading.pid {
3284        Some(pid) if pid == own_pid => None,
3285        pid => Some(pid),
3286    }
3287}
3288
3289/// Run one task this process has claimed, in this process, through exactly the
3290/// attempt a daemon would make: the same starter choice (start, resume,
3291/// review), the same `Task::start` / `settle` transitions, attempt counting,
3292/// quota refund and parking. No second dispatcher - `magi run` and `magi
3293/// review` call this when no daemon is alive.
3294///
3295/// The caller holds the [`Queue::claim`] for the whole call, which is what
3296/// keeps a daemon that starts meanwhile from taking the task.
3297///
3298/// The one deliberate difference from the loop: a task the attempt leaves
3299/// runnable (failed with attempts to spare, or requeued) is **held** instead.
3300/// Nobody asked for a retry, and a daemon starting later must not spend agent
3301/// calls re-running a hand-started task behind the operator's back;
3302/// `magi task release` is the explicit retry.
3303pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3304    let status = Arc::new(Mutex::new(Status::new()));
3305    let stop = Stop::new();
3306    attempt(
3307        opts,
3308        queue,
3309        &status,
3310        &stop,
3311        crate::graph::Pause::new(),
3312        task,
3313    )
3314    .await;
3315    // A run parked on the owner's word about a withheld PR title/body has no
3316    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
3317    // here with the claim still held, and resume once the question is settled
3318    // (answered, or abandoned at its deadline -> the neutral text).
3319    // A rejected reply files one more question (the gate asks at most twice),
3320    // so after a resume the run may be waiting again: keep going, with a fresh
3321    // limit for the new question. `resumes` bounds it even if a resume parks
3322    // without asking anything new.
3323    let mut resumes = 0;
3324    while resumes < MAX_WITHHELD_RESUMES {
3325        let Some(timeout) = withheld_text_wait(task) else {
3326            break;
3327        };
3328        eprintln!(
3329            "waiting for the owner's answer on a withheld pull request text \
3330             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
3331        );
3332        // The deadline abandons the question itself; the extra margin only
3333        // covers an abandon that could not be saved.
3334        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
3335        let ready = loop {
3336            match land_resume_state(task) {
3337                LandResume::StillWaiting if std::time::Instant::now() < limit => {
3338                    tokio::time::sleep(WITHHELD_POLL).await;
3339                }
3340                LandResume::Ready => break true,
3341                _ => break false,
3342            }
3343        };
3344        if !ready {
3345            break;
3346        }
3347        resumes += 1;
3348        attempt(
3349            opts,
3350            queue,
3351            &status,
3352            &stop,
3353            crate::graph::Pause::new(),
3354            task,
3355        )
3356        .await;
3357    }
3358    hold_if_runnable(queue, task);
3359}
3360
3361/// Resumes an in-process run makes for withheld-text questions: the gate asks
3362/// at most twice, plus one for a resume that asks nothing new.
3363const MAX_WITHHELD_RESUMES: u32 = 3;
3364
3365/// How often an in-process run rechecks its withheld-text question.
3366const WITHHELD_POLL: Duration = Duration::from_secs(15);
3367
3368/// The `answer_timeout` (seconds) of the task's last run when that run is
3369/// parked on an unresolved withheld-text question; `None` otherwise.
3370fn withheld_text_wait(task: &Task) -> Option<u64> {
3371    let id = task.runs.last()?;
3372    let s = RunState::load(id).ok()?;
3373    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
3374        .then_some(s.config.graph.answer_timeout)
3375}
3376
3377/// The quota losses `after` holds that `before` did not: what one execution
3378/// suffered, as opposed to the run's history.
3379///
3380/// Compared by value rather than by length or position because
3381/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
3382/// the vector can shrink and shift under a resume. A retried seat that hits
3383/// quota again is a `push` with a new `at`, so it shows up as new here.
3384/// `reclaim` deliberately keeps reading the whole history: after a crash there
3385/// is no attempt boundary to diff against.
3386fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3387    after
3388        .iter()
3389        .filter(|q| !before.contains(q))
3390        .cloned()
3391        .collect()
3392}
3393
3394/// When the loop-wide quota cooldown should end, given this attempt's losses;
3395/// `None` when there were none. Reset-hint parsing and the cap live here.
3396fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3397    if quota.is_empty() {
3398        return None;
3399    }
3400    let with_hint = quota.iter().find(|q| q.reset.is_some());
3401    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3402    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3403    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3404    Some(
3405        now.checked_add(jiff::SignedDuration::from_secs(secs))
3406            .unwrap_or(Timestamp::MAX),
3407    )
3408}
3409
3410/// An explicit task count must agree with a run before any resume.
3411fn implementers_match(task: &Task, state: &RunState) -> bool {
3412    task.implementers()
3413        .is_none_or(|n| n == state.config.graph.implementers)
3414}
3415
3416/// Never resume or take over candidate work built for a different seat count.
3417fn starter_with_implementers(
3418    task: &Task,
3419    previous: Option<&RunState>,
3420    proposed: Starter,
3421) -> Starter {
3422    if previous.is_some_and(|s| !implementers_match(task, s)) {
3423        task.review_of
3424            .as_ref()
3425            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
3426    } else {
3427        proposed
3428    }
3429}
3430
3431/// Apply this task's explicit count to the new attempt, without changing defaults.
3432fn apply_task_implementers(config: &mut Config, task: &Task) {
3433    if let Some(n) = task.implementers() {
3434        config.graph.implementers = n;
3435    }
3436}
3437
3438/// [`prepare`] for one task: its own `--config` and command-line overrides
3439/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
3440/// over the loop's, so handing a hand-started task to a daemon changes nothing
3441/// about what it does.
3442fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3443    let Some(o) = &task.overrides else {
3444        return prepare(repo, opts);
3445    };
3446    // A task filed by `magi run` / `magi review` was configured by that
3447    // command line alone: the loop's own `--config` / `--merge` must not leak
3448    // in, or the same command would behave differently with a loop alive.
3449    let own = Opts {
3450        config: o.config.clone(),
3451        merge: None,
3452        ..opts.clone()
3453    };
3454    let mut config = prepare(repo, if o.inherit_daemon_options { opts } else { &own })?;
3455    o.apply(&mut config);
3456    Ok(config)
3457}
3458
3459/// Load the config for a task's repository, with the merge override applied.
3460fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3461    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3462    if let Some(mode) = &opts.merge {
3463        config.merge.mode = merge_mode(mode)?;
3464    }
3465    Ok(config)
3466}
3467
3468/// Prune the shared build cache back under its cap at a safe boundary
3469/// between runs, so a queue that never empties - and so never reaches
3470/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
3471/// does not leave the cache to grow unchecked for as long as the backlog
3472/// lasts.
3473///
3474/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
3475/// same liveness fact the idle branch's own janitor call rests on - no run
3476/// this daemon spawned is still mid-compile - so pruning here races nothing.
3477/// The caller must not call this while a run is in flight; there is no
3478/// second `busy_now()` check inside this function, on purpose, because there
3479/// is nothing left to check that `busy_now()` has not already answered.
3480///
3481/// A stop that has already been asked for *is* checked here, for a different
3482/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
3483/// synchronously before it decides anything, so the poll loop cannot get back
3484/// to its own `stopped()` test until that walk is over — and a loop already
3485/// on its way out must not make the operator wait out housekeeping it is
3486/// about to stop needing. This is the same call the idle branch makes when it
3487/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
3488/// it matters more here: `busy_now()` is false throughout, so
3489/// [`Stop::finishing`] would report a stop as already landed while the walk
3490/// still held the loop. Nothing is lost by skipping — the cap is a standing
3491/// policy, and the next daemon's startup pass measures the same cache.
3492///
3493/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
3494/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
3495/// and the next has not yet claimed a task, which can be every few
3496/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
3497/// more than the growth it is guarding against.
3498async fn maybe_prune_cache_between_runs(
3499    repo: &Path,
3500    opts: &Opts,
3501    home: &Path,
3502    stop: &Stop,
3503    last_checked: &mut Option<Timestamp>,
3504    now: Timestamp,
3505) {
3506    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
3507        return;
3508    }
3509    *last_checked = Some(now);
3510    let cfg = match prepare(repo, opts) {
3511        Ok(cfg) => cfg,
3512        Err(e) => {
3513            tracing::warn!("cache check: no config: {e:#}");
3514            return;
3515        }
3516    };
3517    match clean::prune_cache_if_over_limit(&cfg, home) {
3518        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
3519            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
3520            pruned.files,
3521            pruned.freed
3522        ),
3523        Ok(_) => {}
3524        Err(e) => {
3525            tracing::warn!("housekeep: prune cache: {e:#}");
3526            notices::raise_in(
3527                home,
3528                Notice::warn(
3529                    "housekeep:cache",
3530                    "Pruning the shared build cache failed; disk usage may keep growing.",
3531                ),
3532            );
3533        }
3534    }
3535}
3536
3537/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
3538/// now, given when it last did (if ever). Pure, so the cadence is asserted
3539/// directly rather than by waiting out real minutes in a test.
3540fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
3541    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
3542}
3543
3544/// The disk janitor, with its housekeeping logged rather than fatal.
3545///
3546/// Called only at the loop's idle points, for the reason the caller documents:
3547/// a prune racing a live compile would delete files mid-build. The config is
3548/// re-read on every call because the repository that just ran may not be the
3549/// daemon's own default, and the cache directory is a repository fact.
3550///
3551/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
3552/// and [`crate::run::default_worktree_root`] read here, for the same reason
3553/// [`drive`] takes its queue and status file rather than resolving them: a
3554/// test driving the loop must not reach through to the operator's real home
3555/// or worktree bay just because the janitor runs on every idle tick.
3556/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
3557/// to get wrong silently - a test's `home` was already isolated, but nothing
3558/// exercised the parameter next to it, so a real worktree bay stayed wired in
3559/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
3560/// it for real, every test in this file that drives the loop at all started
3561/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
3562async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
3563    let cfg = match prepare(repo, opts) {
3564        Ok(cfg) => cfg,
3565        Err(e) => {
3566            tracing::warn!("housekeep: no config: {e:#}");
3567            return;
3568        }
3569    };
3570    // A run's own worktree lives under `config.graph.worktree_root` when the
3571    // repository sets one - the same precedence `RunState::worktree_root`
3572    // uses - and `worktrees_root` only stands in for the *default* an
3573    // unconfigured repository resolves to (see this function's own
3574    // parameter, or the test fixture wiring one to a fake path). Housekeeping
3575    // that always swept the default regardless of this override would never
3576    // see, and so never reclaim, a single worktree for a repository that
3577    // relocated them elsewhere.
3578    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
3579    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
3580    // Reported whenever there is anything to say, not only when `folded > 0`:
3581    // the incident this exists to prevent was 90 of 93 runs skipped and 0
3582    // folded, on every single pass, for months - a report gated on `folded`
3583    // would have stayed silent through every one of them.
3584    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
3585        let mut extra = Vec::new();
3586        if out.unreadable > 0 {
3587            extra.push(format!("{} unreadable", out.unreadable));
3588        }
3589        if out.orphaned_worktrees > 0 {
3590            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
3591        }
3592        let detail = if extra.is_empty() {
3593            String::new()
3594        } else {
3595            format!(" ({})", extra.join(", "))
3596        };
3597        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
3598    }
3599    if out.external_merges_recorded > 0 {
3600        tracing::info!(
3601            "housekeep: recorded {} run(s) as merged externally",
3602            out.external_merges_recorded
3603        );
3604    }
3605    if out.stale_pr_states_repaired > 0 {
3606        tracing::info!(
3607            "housekeep: rewrote {} run record(s) whose pull request had already settled",
3608            out.stale_pr_states_repaired
3609        );
3610    }
3611    if out.cache_files > 0 {
3612        tracing::info!(
3613            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
3614            out.cache_files,
3615            out.cache_freed
3616        );
3617    }
3618    if out.questions_abandoned > 0 {
3619        tracing::info!(
3620            "housekeep: abandoned {} question(s) left open by a finished run",
3621            out.questions_abandoned
3622        );
3623    }
3624}
3625
3626/// Run [`triage::run_once`] and log whatever it did, the same "only when
3627/// there is something to say" rule [`janitor`] follows for its own report.
3628///
3629/// Called at the same idle points as [`janitor`] - once per full poll
3630/// interval, never mid-attempt - for the same reason: it is not liveness
3631/// critical, and a task's own `hold_reason` string is the one thing this
3632/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
3633/// tick for no benefit.
3634async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
3635    let questions = Questions::at(home.join("questions"));
3636    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
3637    if report.is_empty() {
3638        return;
3639    }
3640    if !report.quarantined.is_empty() {
3641        tracing::info!(
3642            "triage: held {} blocked task(s) whose blocked-on task or \
3643             question no longer exists: {}",
3644            report.quarantined.len(),
3645            report.quarantined.join(", ")
3646        );
3647    }
3648    if !report.resumed.is_empty() {
3649        tracing::info!(
3650            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
3651            report.resumed.len(),
3652            report.resumed.join(", ")
3653        );
3654    }
3655    if !report.asked.is_empty() {
3656        tracing::info!(
3657            "triage: asked about {} held task(s): {}",
3658            report.asked.len(),
3659            report.asked.join(", ")
3660        );
3661    }
3662    if !report.answered.is_empty() {
3663        tracing::info!(
3664            "triage: applied {} operator answer(s): {}",
3665            report.answered.len(),
3666            report.answered.join(", ")
3667        );
3668    }
3669}
3670
3671/// The free-space gate: what stands between this task and a new run, if
3672/// anything. `Some(reason)` holds the task; `None` lets it start.
3673///
3674/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
3675/// the operator opted out. A measurement failure is a gate, not a pass: both
3676/// sides of "cannot tell" are served by not starting.
3677fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
3678    disk_gate_with(repo, config, crate::disk::free_bytes)
3679}
3680
3681/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
3682/// test can assert the exact wiring `attempt` runs - config's threshold in,
3683/// task-holding reason out - without asking the real machine's disk anything.
3684fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
3685    repo: &Path,
3686    config: &Config,
3687    free_bytes: F,
3688) -> Option<String> {
3689    let min = config.disk.min_free_bytes;
3690    if min == 0 {
3691        return None;
3692    }
3693    match free_bytes(repo) {
3694        Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
3695        Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
3696    }
3697}
3698
3699/// How long to wait before offering another task when a run lost a seat to a
3700/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
3701/// could read, or carried nothing at all. Long enough that a quota outage
3702/// cannot burn through a whole backlog in the few seconds each doomed attempt
3703/// takes to fail; short enough that a quota which clears early is not left
3704/// idle for the fallback's sake.
3705const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
3706
3707/// Longest a parsed reset hint may push the wait out to. The hint comes from
3708/// the CLI's own words, not a contract, so a parsing slip that lands a day
3709/// away must not leave the loop asleep for a day.
3710const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
3711
3712/// How long [`poll`] should wait before offering the next task, after a run
3713/// lost at least one seat to a rate limit.
3714///
3715/// Pure and separate from the loop so the policy can be exercised without a
3716/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
3717/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
3718/// nothing to parse, or the parsed time has already passed; `cap` bounds how
3719/// far a parsed hint is trusted to push the wait out.
3720fn quota_wait(
3721    reset_at: Option<Timestamp>,
3722    now: Timestamp,
3723    fallback: Duration,
3724    cap: Duration,
3725) -> Duration {
3726    match reset_at {
3727        Some(at) if at > now => {
3728            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3729            Duration::from_secs(secs).min(cap)
3730        }
3731        _ => fallback,
3732    }
3733}
3734
3735/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
3736///
3737/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
3738/// explains why parsing it exactly "would be a bug factory" — so this only
3739/// recognises the shapes actually observed in the wild, and returns `None`
3740/// for anything else rather than guess at a format nobody has seen.
3741///
3742/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
3743/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
3744/// said it, not from whenever this loop happens to read it: anchoring on `now`
3745/// would push the reset later on every read and would read an already-elapsed
3746/// reset as still in the future. (A long hint is still clamped by
3747/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
3748fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3749    parse_reset_hint_zoned(text, now)
3750        .or_else(|| parse_reset_hint_dated(text))
3751        .or_else(|| parse_reset_hint_relative(text, recorded))
3752}
3753
3754/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
3755/// optional but at least one required, in that order. A bare number or any
3756/// unknown unit is refused.
3757fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3758    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3759    let mut rest = rest.trim();
3760    if rest.is_empty() {
3761        return None;
3762    }
3763    let mut total: i64 = 0;
3764    let mut matched = false;
3765    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3766        if let Some((digits, tail)) = rest.split_once(unit)
3767            && !digits.is_empty()
3768            && digits.bytes().all(|b| b.is_ascii_digit())
3769        {
3770            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3771            rest = tail;
3772            matched = true;
3773        }
3774    }
3775    if !rest.is_empty() || !matched {
3776        return None;
3777    }
3778    recorded
3779        .checked_add(jiff::SignedDuration::from_secs(total))
3780        .ok()
3781}
3782
3783/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
3784/// case-insensitive) into a 24-hour hour and minute. Shared by every
3785/// reset-hint shape below.
3786fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3787    let clock = clock.trim().to_lowercase();
3788    let (digits, pm) = clock
3789        .strip_suffix("am")
3790        .map(|d| (d, false))
3791        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3792    let (h, m) = digits.trim().split_once(':')?;
3793    let mut hour: i8 = h.trim().parse().ok()?;
3794    let minute: i8 = m.trim().parse().ok()?;
3795    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3796        return None;
3797    }
3798    if pm && hour != 12 {
3799        hour += 12;
3800    } else if !pm && hour == 12 {
3801        hour = 0;
3802    }
3803    Some((hour, minute))
3804}
3805
3806/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
3807/// and a zone, never a date. A clock reading already past today is read as
3808/// tomorrow's: a CLI naming a same-day reset that has already gone by means
3809/// the window rolled over while nothing was watching.
3810fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3811    let open = text.find('(')?;
3812    let close = text.rfind(')')?;
3813    if close <= open {
3814        return None;
3815    }
3816    let zone = text[open + 1..close].trim();
3817    let (hour, minute) = parse_12h_clock(&text[..open])?;
3818    let tz = jiff::tz::TimeZone::get(zone).ok()?;
3819    let candidate = now
3820        .to_zoned(tz)
3821        .with()
3822        .hour(hour)
3823        .minute(minute)
3824        .second(0)
3825        .millisecond(0)
3826        .microsecond(0)
3827        .nanosecond(0)
3828        .build()
3829        .ok()?;
3830    let mut at = candidate.timestamp();
3831    if at <= now {
3832        at += jiff::SignedDuration::from_hours(24);
3833    }
3834    Some(at)
3835}
3836
3837/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
3838/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
3839/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
3840/// "already past today" correction to make: the year already disambiguates
3841/// it. Scanned as a five-word window so it can be pulled out of the middle
3842/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
3843/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
3844/// any other timestamp with no zone attached.
3845fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
3846    let words: Vec<&str> = text.split_whitespace().collect();
3847    if words.len() < 5 {
3848        return None;
3849    }
3850    (0..=words.len() - 5)
3851        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
3852}
3853
3854/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
3855/// parenthesis right after the window is refused rather than ignored — it
3856/// reads as an explicit zone annotation on a shape that otherwise carries
3857/// none, and guessing UTC anyway would be exactly the silent misread this
3858/// module's parsing otherwise avoids.
3859fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
3860    if trailing.is_some_and(|next| next.starts_with('(')) {
3861        return None;
3862    }
3863    let month = month_number(window[0])?;
3864    let day_token = window[1].strip_suffix(',')?.to_lowercase();
3865    let day_digits = ["st", "nd", "rd", "th"]
3866        .iter()
3867        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
3868    let day: i8 = day_digits.parse().ok()?;
3869    let year_token = window[2];
3870    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
3871        return None;
3872    }
3873    let year: i16 = year_token.parse().ok()?;
3874    // The am/pm word carries the sentence's own trailing punctuation, e.g.
3875    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
3876    // reusing the same 12-hour clock reader the bracketed shape uses.
3877    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
3878    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
3879    let date = jiff::civil::Date::new(year, month, day).ok()?;
3880    let candidate = date
3881        .at(hour, minute, 0, 0)
3882        .to_zoned(jiff::tz::TimeZone::UTC)
3883        .ok()?;
3884    Some(candidate.timestamp())
3885}
3886
3887/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
3888/// case-insensitively, into a 1-based month number.
3889fn month_number(name: &str) -> Option<i8> {
3890    const NAMES: [&str; 12] = [
3891        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
3892    ];
3893    let lower = name.to_lowercase();
3894    NAMES
3895        .iter()
3896        .position(|n| *n == lower.as_str())
3897        .map(|i| i as i8 + 1)
3898}
3899
3900/// Resuming a `Blocked` run that already spent every review round its own
3901/// config allowed cannot make progress: `graph::Runner`'s review loop walks
3902/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
3903/// reached `max_rounds`, so `execute` would settle straight back to
3904/// `Blocked` without asking anyone anything. Read-only against a state this
3905/// build never mutates — `src/graph.rs` stays untouched — but without this
3906/// check, [`unfinished_run`] would keep reporting such a run as still
3907/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
3908/// promise is a fresh competition when a design needs to change) would
3909/// silently resume the exhausted run instead, spending an attempt on a
3910/// cycle that cannot change anything.
3911fn exhausted_review_budget(state: &RunState) -> bool {
3912    // A run whose task-head publication failed has nothing left to review:
3913    // resuming it only retries the publication, so it is never "exhausted".
3914    state.status == RunStatus::Blocked
3915        && !state.pr_publication_pending
3916        && state.reviews.len() >= state.config.graph.review_rounds
3917}
3918
3919/// This task's *most recent* run, if resuming it would actually make
3920/// progress. `short` is only for the warning's own message.
3921///
3922/// Only ever `runs.last()` — never a search back through older history.
3923/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
3924/// mint, oldest first, and every entry before the last one was already
3925/// superseded at the moment it was minted: the daemon only ever starts a new
3926/// run when the previous one was not worth resuming (unresumable, exhausted,
3927/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
3928/// opens a fresh review-only run alongside an older, already-failed
3929/// competition. Searching further back would let an old run that merely
3930/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
3931/// behind, say — get resumed instead of the fresh competition
3932/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
3933/// nothing asked to revisit.
3934///
3935/// Two runs paid for the "prefer resuming over restarting" half of this
3936/// lesson, which is why this still checks `runs.last()` rather than always
3937/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
3938/// task a moment later, duplicating two and a half hours of agent work. Then
3939/// b25f stalled on a judge that timed out and one that answered with no JSON
3940/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
3941/// **one second** later, buying three fresh implementations to reach the
3942/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
3943/// the second case: a stall is terminal, and its cheap recovery re-asks only
3944/// the absent seats. [`exhausted_review_budget`] is the other half: a run
3945/// that is technically `resumable()` but provably cannot progress must not
3946/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
3947/// no-op instead of the fresh competition it promises.
3948///
3949/// A load failure is warned about rather than silently read as "not
3950/// resumable": the alternative is exactly what let a schema mismatch on run
3951/// `eba2` fall through to a full re-competition with nobody told why.
3952/// `crate::conduct` is what actually offers a better answer than
3953/// `Runner::start` here (see `Recovery::Review`), once this task's next
3954/// failure shows it up as `held`/`failed` with the run state unreadable.
3955fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
3956    unfinished_run_with(runs, short, RunState::load)
3957}
3958
3959/// [`unfinished_run`] with an injected state reader. Tests provide their
3960/// fixtures directly rather than touching the process-global run home.
3961fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
3962where
3963    F: FnOnce(&str) -> Result<RunState>,
3964{
3965    let id = runs.last()?;
3966    match load(id) {
3967        // A run some process is driving right now is not "unfinished" in the
3968        // sense of waiting to be picked up: a run started by hand is in
3969        // `runs` while it is still executing, and resuming it here
3970        // would put a second driver on the same worktrees.
3971        Ok(s)
3972            if s.status.resumable()
3973                && !s.released()
3974                && !exhausted_review_budget(&s)
3975                && s.liveness(false) != crate::run::Liveness::Live =>
3976        {
3977            Some(id.clone())
3978        }
3979        Ok(_) => None,
3980        Err(e) => {
3981            tracing::warn!("could not read run {id} for task {short}: {e:#}");
3982            None
3983        }
3984    }
3985}
3986
3987/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
3988/// that [`attempt`] will resume it on its own?
3989///
3990/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
3991/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
3992/// injected reader like its sibling. An unreadable run is not awaiting
3993/// anything: it keeps going to the conductor as before.
3994fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
3995where
3996    F: FnOnce(&str) -> Result<RunState>,
3997{
3998    // `Failed` stays: a record an older build wrote for a parked run.
3999    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
4000        || task.fresh_start
4001        || task.review_branch.is_some()
4002    {
4003        return false;
4004    }
4005    let Some(id) = task.runs.last() else {
4006        return false;
4007    };
4008    load(id).is_ok_and(|s| {
4009        s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
4010    })
4011}
4012
4013/// Which of the three ways [`attempt`] can mint or continue a run this task
4014/// should use.
4015#[derive(Debug, Clone, PartialEq, Eq)]
4016enum Starter {
4017    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
4018    /// and that still exists.
4019    Review(String),
4020    /// `crate::graph::Runner::resume` on an unfinished run of this task.
4021    Resume(String),
4022    /// `crate::graph::Runner::start`: a fresh competition.
4023    Start,
4024}
4025
4026/// A selected public implementation overrides every historical candidate and pin.
4027fn selected_starter(
4028    selected: &crate::pr_recovery::Selection,
4029    previous: Option<&RunState>,
4030    unfinished: Option<&str>,
4031) -> Starter {
4032    if let Some(id) = unfinished
4033        && previous.is_some_and(|r| {
4034            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
4035        })
4036    {
4037        Starter::Resume(id.to_owned())
4038    } else {
4039        Starter::Review(selected.branch.clone())
4040    }
4041}
4042
4043/// The owner's answer to this branch's divergence question, consumed from the
4044/// task so a later, different divergence asks again. The runner applies it
4045/// (see `Runner::review_taking_over`), after the earlier worktree is released.
4046fn take_divergence_answer(
4047    branch: &str,
4048    remote: &str,
4049    task: &mut Task,
4050) -> Option<crate::reconcile::Choice> {
4051    let summary = crate::reconcile::summary_for(branch, remote);
4052    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
4053        (a.question == summary)
4054            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
4055            .flatten()
4056            .map(|c| (i, c))
4057    })?;
4058    task.answers.remove(idx);
4059    Some(choice)
4060}
4061
4062/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
4063/// this attempt should use. Pure, and separate from [`attempt`], so the
4064/// routing itself is assertable without spawning a real graph or a git
4065/// process: `attempt`'s own `crate::git::branch_exists` call has already
4066/// happened by the time this is called.
4067///
4068/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
4069/// whose branch is gone falls all the way through to [`Starter::Start`], not
4070/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
4071/// old (likely `Blocked`) run in the first place, and a branch that vanished
4072/// out from under that choice is not evidence resuming it would fare better.
4073fn choose_starter(
4074    review_branch: Option<&str>,
4075    branch_exists: bool,
4076    unfinished: Option<&str>,
4077) -> Starter {
4078    match review_branch {
4079        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
4080        Some(_) => Starter::Start,
4081        None => match unfinished {
4082            Some(id) => Starter::Resume(id.to_owned()),
4083            None => Starter::Start,
4084        },
4085    }
4086}
4087
4088/// Consume a retained review only while its authored criteria still match.
4089fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
4090    let branch = task.review_branch.take();
4091    let instruction = task.review_instruction.take();
4092    branch.filter(|branch| match &instruction {
4093        Some(authored) => *authored == task.instruction,
4094        // Legacy retained branches must agree with their prior run; only an
4095        // explicitly pinned review can proceed without recoverable provenance.
4096        None => previous.map_or_else(
4097            || task.review_of.as_ref() == Some(branch),
4098            |run| compatible_run_instruction(run, task),
4099        ),
4100    })
4101}
4102
4103/// A current explicit pin can select an otherwise incompatible run. Edits
4104/// and subsequent approvals invalidate pins selected for earlier criteria.
4105fn may_resume_run(run: &RunState, task: &Task) -> bool {
4106    task.resume_override
4107        .as_ref()
4108        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
4109        || compatible_run_instruction(run, task)
4110}
4111
4112/// Review scaffolding is execution context, not evidence of an operator edit.
4113pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
4114    if let Some(authored) = &run.task_instruction {
4115        return compatible_instruction(authored, task);
4116    }
4117    if compatible_instruction(&run.instruction, task) {
4118        return true;
4119    }
4120    // Recognize only the existing generated review shapes on legacy runs.
4121    // Ordinary authored text with a similar heading is left intact.
4122    if run.reviewed_commits.is_some() {
4123        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
4124            return strip_answers_block(authored, task).trim() == task.instruction.trim();
4125        }
4126        if let Some(branch) = &task.review_of {
4127            let canonical = format!(
4128                "Review the branch `{branch}` (review-only: no implementation, no judging)."
4129            );
4130            let generated = format!(
4131                "Review the work already on branch `{branch}`. There is no task statement: what the change claims to do is whatever its commits say.\n\n"
4132            );
4133            return task.instruction == canonical && run.instruction.starts_with(&generated);
4134        }
4135    }
4136    false
4137}
4138
4139/// Compare authored instructions, excluding answer blocks appended by the daemon.
4140pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
4141    strip_answers_block(old, task) == task.instruction
4142}
4143
4144/// Which repository a task runs in. A task that names none — the normal case
4145/// for one filed from a phone — runs in the daemon's own default.
4146fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
4147    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
4148        return fallback.to_path_buf();
4149    }
4150    task.repo.clone()
4151}
4152
4153/// The header [`append_answers`] appends operator answers under. Shared with
4154/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
4155/// rather than grown a new block on every resume.
4156const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
4157
4158/// Render the first `count` answers in the block appended to an instruction.
4159fn answers_block(task: &Task, count: usize) -> String {
4160    let mut s = ANSWERS_HEADER.to_owned();
4161    for a in &task.answers[..count] {
4162        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
4163    }
4164    s
4165}
4166
4167/// Render the approval independently of transient task state, so historical
4168/// suffixes remain recognizable after another explicit release.
4169fn resumption_block(r: &crate::queue::Resumption) -> String {
4170    format!(
4171        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
4172         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
4173        r.generation, r.at, r.instruction, r.answers_through,
4174    )
4175}
4176
4177/// Append audit answers and the latest explicit approval to the instruction.
4178fn append_answers(base: &str, task: &Task) -> String {
4179    let mut s = base.to_owned();
4180    if !task.answers.is_empty() {
4181        s.push_str(&answers_block(task, task.answers.len()));
4182    }
4183    if let Some(r) = &task.resumption {
4184        s.push_str(&resumption_block(r));
4185    }
4186    s
4187}
4188
4189/// Drop the prior answer block only when it is exactly the suffix this task
4190/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
4191/// the task author is ordinary instruction text, not a block to remove.
4192fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
4193    let mut instruction = instruction;
4194    for approval in task
4195        .resumption
4196        .iter()
4197        .chain(task.resumption_history.iter().rev())
4198    {
4199        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
4200            instruction = base;
4201            break;
4202        }
4203    }
4204    for count in (1..=task.answers.len()).rev() {
4205        let block = answers_block(task, count);
4206        if let Some(base) = instruction.strip_suffix(&block) {
4207            return base;
4208        }
4209    }
4210    instruction
4211}
4212
4213/// The instruction handed to `Runner::start`: the task's own text, plus any
4214/// operator answers `crate::conduct` collected for it (see
4215/// [`Task::answers`]), so a decision the operator actually made reaches the
4216/// implementers rather than only clearing the block that was waiting on it.
4217///
4218/// Appended rather than merged into [`Task::instruction`] itself, so the
4219/// task's own record stays exactly what its author wrote.
4220fn instruction_for(task: &Task) -> String {
4221    append_answers(&task.instruction, task)
4222}
4223
4224/// The instruction a resumed run should carry on with: whatever it already
4225/// had, refreshed with the task's *current* operator answers.
4226///
4227/// A resumable run's own `RunState::instruction` predates any answer
4228/// `crate::conduct` collects after the run parks, so resuming it unchanged —
4229/// the behaviour before this function existed — silently drops the very
4230/// decision the operator made to unblock it. Re-stripping any block this
4231/// function appended on an earlier resume before re-appending the current
4232/// list (rather than blindly appending again) is what keeps a task resumed
4233/// three times over three answered questions from carrying the same answer
4234/// three times.
4235fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
4236    append_answers(strip_answers_block(old_instruction, task), task)
4237}
4238
4239/// The task's attachments as absolute paths, each checked to still exist.
4240fn task_attachments(queue: &Queue, task: &Task) -> Result<Vec<PathBuf>> {
4241    let paths = queue.attachment_paths(task);
4242    for (name, path) in task.attachments.iter().zip(&paths) {
4243        if !path.is_file() {
4244            bail!(
4245                "attachment `{name}` is recorded on the task but {} is missing",
4246                path.display()
4247            );
4248        }
4249    }
4250    Ok(paths)
4251}
4252
4253/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
4254/// answers before handing it to `Runner` — the actual boundary between
4255/// [`choose_starter`]'s routing and the graph, factored out so it is
4256/// assertable without a real repository, git branch, or agent CLI.
4257///
4258/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
4259/// instruction from the reviewed branch's own commit log because there is no
4260/// task statement to speak of for hand-written work, and splicing operator
4261/// answers into that text would contradict the very message it sends
4262/// reviewers ("there is no task statement").
4263fn prepare_instruction(
4264    starter: &Starter,
4265    old_instruction: Option<&str>,
4266    task: &Task,
4267) -> Option<String> {
4268    match starter {
4269        Starter::Start => Some(instruction_for(task)),
4270        Starter::Resume(_) => Some(resumed_instruction(
4271            old_instruction.expect("a resumed run always has a prior instruction"),
4272            task,
4273        )),
4274        Starter::Review(_) => None,
4275    }
4276}
4277
4278/// Persist a transition. A queue write failure is logged rather than fatal: the
4279/// run already happened, and taking the daemon down would only add a lost
4280/// backlog to a full disk.
4281fn record(queue: &Queue, task: &mut Task) {
4282    if let Err(e) = queue.put(task) {
4283        tracing::error!("could not record task {}: {e:#}", task.short());
4284        let notice = Notice::error(
4285            "loop:record",
4286            "The loop could not save a task's state; check the disk.",
4287        )
4288        .link(Link::Task {
4289            id: task.id.clone(),
4290        });
4291        // The queue lives at `<home>/queue`, so its parent is the home.
4292        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
4293            Some(home) => notices::raise_in(home, notice),
4294            None => notices::raise(notice),
4295        }
4296    }
4297}
4298
4299/// Every runnable task, in the order the loop should try them.
4300///
4301/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
4302/// tail exists so that a claim somebody else holds costs the loop the next
4303/// candidate rather than a whole poll interval of idleness.
4304fn runnable(queue: &Queue) -> Vec<Task> {
4305    let mut tasks: Vec<Task> = queue
4306        .list()
4307        .into_iter()
4308        .filter(|t| t.status.runnable())
4309        .collect();
4310    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4311    tasks
4312}
4313
4314/// Why a run ended where it did, in one line, for [`Task::last_error`].
4315///
4316/// A stalled run names the seats the quota took out: "out of quota" is not
4317/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
4318/// agent to replace or which plan to top up.
4319///
4320/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
4321/// purpose: unlike `label`'s other callers (an internal log line, an
4322/// already-a-bug fallback message), this string becomes `Task::last_error`
4323/// verbatim, which the phone renders in the same alarm-styled box an
4324/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
4325/// `.err` styling. A bare `verified_noop` there would read exactly like the
4326/// failure this whole feature exists to tell apart from one.
4327fn describe(state: &RunState) -> String {
4328    let p = phrases(&state.config.graph.language);
4329    let mut detail = if state.status == RunStatus::Stalled {
4330        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4331        seats.sort_unstable();
4332        seats.dedup();
4333        if seats.is_empty() {
4334            p.quorum_lost.to_owned()
4335        } else {
4336            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4337        }
4338    } else {
4339        format!("{}{}", p.run_ended, state.status.display_label())
4340    };
4341    if let Some(last) = state.events.last() {
4342        // The review loop's "never answered" stop is the one event worth
4343        // translating; it is recognised from structured state, not by
4344        // matching the English event text (which stays as recorded).
4345        let unanswered = state
4346            .reviews
4347            .last()
4348            .filter(|r| {
4349                state.status == RunStatus::Blocked
4350                    && last.node == "review"
4351                    && r.incomplete()
4352                    && r.blocking == 0
4353                    && r.round == state.config.graph.review_rounds
4354                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4355            })
4356            .map(|r| (r.expected - r.answered, r.round));
4357        match unanswered {
4358            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4359                detail.push_str(&format!(
4360                    " ({}: {})",
4361                    last.node,
4362                    (p.reviewers_never_answered)(missing, rounds)
4363                ));
4364            }
4365            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4366        }
4367    }
4368    detail.push_str(&format!(" [run {}]", state.id));
4369    detail
4370}
4371
4372/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
4373///
4374/// The task file lives in the backlog indefinitely; a diagnostic is an
4375/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
4376/// stay small regardless of how much a gate command or a candidate printed.
4377const DIAGNOSTIC_MAX: usize = 4_000;
4378
4379/// Tail kept from a single failing command's output inside a diagnostic.
4380/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
4381/// pointer for a human deciding whether to go read the full artifact by hand,
4382/// not a replacement for reading it.
4383const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4384
4385/// Assemble a bounded diagnostic excerpt from a held task's own run, so
4386/// `magi task show` says more than the one-line reason in [`describe`].
4387///
4388/// The one-liner answers "where did the run stop"; this answers "what would a
4389/// human have found opening `artifacts/` by hand" — the point of the whole
4390/// feature is the case that one-liner actively misleads on: a run held as "no
4391/// candidate produced a change" can mean the implementer actually finished
4392/// the task (opened a PR, merged it, tagged a release) and only left a clean
4393/// local worktree behind, which reads as "nothing happened" unless someone
4394/// goes and reads what the agent actually said. `None` when the run carries
4395/// none of the three shapes this recognises — an ordinary run held for
4396/// something not diagnosable from `RunState` alone still explains itself
4397/// through `Task::last_error`.
4398fn diagnostic(state: &RunState) -> Option<String> {
4399    let mut parts: Vec<String> = Vec::new();
4400
4401    // Gate failure: which check(s), and the tail of what each printed.
4402    for o in state.gate.iter().filter(|o| !o.ok()) {
4403        parts.push(format!(
4404            "gate `{}` failed ({:?}):\n{}",
4405            o.command,
4406            o.code,
4407            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4408        ));
4409    }
4410
4411    // The land loop gave up because the fixer declined while checks were
4412    // still red: the message already names them (see `land::run`).
4413    if let Some(last) = state
4414        .events
4415        .iter()
4416        .rev()
4417        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4418    {
4419        parts.push(last.message.clone());
4420    }
4421
4422    // No viable candidate: every implementer's own final word, sanitized the
4423    // same way a judge would have read it, so a run that actually finished
4424    // the job does not read as an unexplained failure. A verified no-op is
4425    // called out ahead of its own summary and apart from an ordinary
4426    // failure's `why` — this is the one candidate shape whose diagnostic a
4427    // human is expected to actually judge, not just skim.
4428    if state.viable().is_empty() {
4429        for c in &state.candidates {
4430            if let Some(evidence) = &c.verified_noop {
4431                parts.push(format!(
4432                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4433                    c.label
4434                ));
4435            } else if !c.summary.trim().is_empty() {
4436                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4437            } else if let Some(why) = &c.failed {
4438                parts.push(format!("candidate {}: {why}", c.label));
4439            }
4440        }
4441    }
4442
4443    if parts.is_empty() {
4444        return None;
4445    }
4446    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
4447    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
4448    // back slightly over. Leave it enough room to always land under the
4449    // limit.
4450    Some(crate::run::tail(
4451        &parts.join("\n\n"),
4452        DIAGNOSTIC_MAX.saturating_sub(100),
4453    ))
4454}
4455
4456/// Stable lower-case name for a run status, for an internal log line and the
4457/// "graph stopped without reaching a terminal status" bug message in
4458/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
4459/// doc for why that one reads [`RunStatus::display_label`] instead. One
4460/// definition of a status's name, on the type that owns it: this table used
4461/// to live here as a second copy, and a status renamed in one place would
4462/// have gone on reading correctly in the other.
4463fn label(status: RunStatus) -> &'static str {
4464    status.as_str()
4465}
4466
4467/// Parse a merge mode override.
4468pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
4469    match mode {
4470        "none" => Ok(MergeMode::None),
4471        "local" => Ok(MergeMode::Local),
4472        "pr" => Ok(MergeMode::Pr),
4473        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
4474    }
4475}
4476
4477/// Take the status lock, recovering from a poisoned one.
4478///
4479/// A panic elsewhere must not silently stop the heartbeat: the status is plain
4480/// data, and the worst a poisoned lock can hold is a stale timestamp.
4481fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
4482    mutex
4483        .lock()
4484        .unwrap_or_else(std::sync::PoisonError::into_inner)
4485}
4486
4487#[cfg(test)]
4488mod tests {
4489    use super::*;
4490    use crate::queue::{Source, TaskStatus};
4491    use crate::run::{Candidate, CommandOutcome};
4492    use pretty_assertions::assert_eq;
4493
4494    fn task() -> Task {
4495        Task::new(
4496            "add retries".to_owned(),
4497            "add retries".to_owned(),
4498            PathBuf::from("/repo"),
4499            Source::Human,
4500        )
4501    }
4502
4503    #[test]
4504    fn selected_public_head_overrides_historical_resume_and_pin() {
4505        let mut t = task();
4506        let mut old = run_state(RunStatus::Blocked);
4507        let selection = crate::pr_recovery::Selection {
4508            url: "url".into(),
4509            branch: format!("magi/task-{}", t.id),
4510            head: "a".repeat(40),
4511            instruction: t.instruction.clone(),
4512            approved_at: Timestamp::now(),
4513        };
4514        t.resume_override = Some(crate::queue::OperatorResume {
4515            pinned_run: Some(old.id.clone()),
4516            question_id: "choice".into(),
4517            at: Timestamp::now(),
4518            conductor_rehold: None,
4519            forced: false,
4520        });
4521        assert_eq!(
4522            selected_starter(&selection, Some(&old), Some(&old.id)),
4523            Starter::Review(selection.branch.clone())
4524        );
4525        old.pr_recovery = Some(selection.clone());
4526        assert_eq!(
4527            selected_starter(&selection, Some(&old), Some(&old.id)),
4528            Starter::Review(selection.branch.clone())
4529        );
4530        old.reviewed_commits = Some(vec!["implementation".into()]);
4531        assert_eq!(
4532            selected_starter(&selection, Some(&old), Some(&old.id)),
4533            Starter::Resume(old.id.clone())
4534        );
4535        let mut changed = selection.clone();
4536        changed.head = "b".repeat(40);
4537        assert_eq!(
4538            selected_starter(&changed, Some(&old), Some(&old.id)),
4539            Starter::Review(changed.branch)
4540        );
4541    }
4542
4543    #[test]
4544    fn candidate_transplant_failure_is_one_actionable_hold() {
4545        let dir = tempfile::tempdir().unwrap();
4546        let q = Queue::at(dir.path().join("queue"));
4547        let mut t = task();
4548        let mut state = run_state(RunStatus::Blocked);
4549        state.event("prep", "cannot apply referenced commit: conflict");
4550        state.prep_failure = Some("conflict".into());
4551        t.start(state.id.clone());
4552        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
4553        assert_eq!(t.attempts, 1);
4554        assert_eq!(t.status, TaskStatus::Held);
4555        assert!(t.operator_held());
4556        assert!(!t.status.runnable());
4557        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
4558    }
4559
4560    #[test]
4561    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
4562        for source in ["cli", "web"] {
4563            let mut t = task();
4564            let mut run = run_state(RunStatus::Blocked);
4565            run.instruction = "Run A original criteria".into();
4566            run.task_instruction = Some(run.instruction.clone());
4567            t.start(run.id.clone());
4568            t.release_operator("choice", Some("resume-question"));
4569            t.resume_override = Some(crate::queue::OperatorResume {
4570                question_id: "resume-question".into(),
4571                at: Timestamp::now(),
4572                conductor_rehold: None,
4573                forced: true,
4574                pinned_run: Some(run.id.clone()),
4575            });
4576            t.hold_machine(Some("not enough free space to start a run".into()));
4577            let mut unchanged = t.clone();
4578            unchanged
4579                .edit("title changed".into(), unchanged.instruction.clone())
4580                .unwrap();
4581            unchanged.release_operator(source, None);
4582            assert_eq!(
4583                unchanged
4584                    .resume_override
4585                    .as_ref()
4586                    .unwrap()
4587                    .pinned_run
4588                    .as_deref(),
4589                Some(run.id.as_str())
4590            );
4591            assert!(!compatible_run_instruction(&run, &unchanged));
4592            assert!(may_resume_run(&run, &unchanged));
4593
4594            t.edit(
4595                "approved recovery".into(),
4596                "Reuse measured PR head B; fix Clippy; review".into(),
4597            )
4598            .unwrap();
4599            assert!(t.resume_override.is_none());
4600            t.release_operator(source, None);
4601            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
4602            assert!(reloaded.resume_override.is_none());
4603            assert!(!may_resume_run(&run, &reloaded));
4604            let unfinished =
4605                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
4606                    .filter(|_| may_resume_run(&run, &reloaded));
4607            assert_eq!(
4608                choose_starter(None, false, unfinished.as_deref()),
4609                Starter::Start
4610            );
4611            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
4612            assert_eq!(
4613                reloaded.resumption_history[0].question_id.as_deref(),
4614                Some("resume-question")
4615            );
4616
4617            // A revision already persisted with the old approval/pin is also
4618            // invalidated when the new operator release is recorded.
4619            unchanged.instruction = "Reuse measured PR head B".into();
4620            unchanged.hold_machine(Some("disk hold".into()));
4621            unchanged.release_operator(source, None);
4622            assert!(unchanged.resume_override.is_none());
4623            assert!(!may_resume_run(&run, &unchanged));
4624        }
4625    }
4626
4627    #[test]
4628    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
4629        let mut t = task();
4630        let mut run = run_state(RunStatus::Blocked);
4631        t.review_of = Some("approved-head".into());
4632        t.instruction =
4633            "Review the branch `approved-head` (review-only: no implementation, no judging)."
4634                .into();
4635        run.instruction = "Review the work already on branch `approved-head`. There is no task statement: what the change claims to do is whatever its commits say.\n\nCommit log".into();
4636        run.reviewed_commits = Some(vec!["Commit log".into()]);
4637        t.start(run.id.clone());
4638        t.hold_machine(Some("interrupted review".into()));
4639        t.release_operator("cli", None);
4640        assert!(
4641            compatible_run_instruction(&run, &t),
4642            "legacy explicit review remains resumable"
4643        );
4644        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
4645            .filter(|_| compatible_run_instruction(&run, &t));
4646        assert_eq!(
4647            choose_starter(None, false, unfinished.as_deref()),
4648            Starter::Resume(run.id.clone())
4649        );
4650        run.task_instruction = Some(t.instruction.clone());
4651        assert!(compatible_run_instruction(&run, &t));
4652        let reloaded: RunState =
4653            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
4654        assert!(compatible_run_instruction(&reloaded, &t));
4655        t.edit(
4656            "new approved head".into(),
4657            "Reuse measured PR head B".into(),
4658        )
4659        .unwrap();
4660        assert!(!compatible_run_instruction(&run, &t));
4661
4662        // Legacy recovery reviews retain the task criteria ahead of the log.
4663        t.review_of = None;
4664        t.instruction = "Fix Clippy on approved head".into();
4665        run.task_instruction = None;
4666        run.instruction = format!(
4667            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
4668            t.instruction
4669        );
4670        assert!(compatible_run_instruction(&run, &t));
4671        t.instruction.push('\n');
4672        assert!(
4673            compatible_run_instruction(&run, &t),
4674            "legacy generated review trimmed the original criteria"
4675        );
4676        t.hold_for_handover(Some("approved-head".into()), "refused".into());
4677        let mut unchanged = t.clone();
4678        assert_eq!(
4679            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
4680            Some("approved-head")
4681        );
4682        t.edit("new plan".into(), "Reuse measured PR head B".into())
4683            .unwrap();
4684        assert!(take_review_branch(&mut t, Some(&run)).is_none());
4685        assert!(!compatible_run_instruction(&run, &t));
4686        t.review_branch = Some("approved-head".into());
4687        t.review_instruction = None;
4688        assert!(
4689            take_review_branch(&mut t, Some(&run)).is_none(),
4690            "legacy retained candidate cannot replace a revised approved head"
4691        );
4692    }
4693
4694    #[test]
4695    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
4696        crate::run::pin_test_home();
4697        let dir = tempfile::tempdir().unwrap();
4698        let queue = Queue::at(dir.path().join("queue"));
4699        for resume in [true, false] {
4700            let state = run_state(RunStatus::Blocked);
4701            let mut t = task();
4702            t.start(state.id.clone());
4703            let action = if resume {
4704                ask::ChoiceAction::Resume {
4705                    run: state.id.clone(),
4706                }
4707            } else {
4708                ask::ChoiceAction::Requeue
4709            };
4710            let mut q = action_question(&state.id, action);
4711            q.status = ask::QuestionStatus::Open;
4712            q.answer = None;
4713            q.answered_at = None;
4714            t.fail("run stopped with a question", 3);
4715            hold_if_runnable(&queue, &mut t);
4716            assert!(t.operator_decided_at.is_none());
4717            assert!(t.operator_held());
4718            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
4719            let expected = if resume {
4720                ActionDecision::Resume(state.id.clone())
4721            } else {
4722                ActionDecision::Requeue
4723            };
4724            assert_eq!(
4725                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
4726                expected
4727            );
4728            t.hold_manual(Some("later explicit hold".into()));
4729            assert_eq!(
4730                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
4731                ActionDecision::Stale
4732            );
4733        }
4734    }
4735
4736    #[test]
4737    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
4738        let mut t = task();
4739        t.answers.push(crate::queue::AnsweredQuestion {
4740            question: "Inspect the remote?".into(),
4741            answer: "Inspect then wait".into(),
4742        });
4743        let old = instruction_for(&t);
4744        assert!(compatible_instruction(&old, &t));
4745        t.instruction = "Reuse approved PR head and review".into();
4746        t.release_operator("cli", None);
4747        assert!(!compatible_instruction(&old, &t));
4748        let approved = instruction_for(&t);
4749        assert!(approved.contains("waiting premises are superseded"));
4750        assert!(compatible_instruction(&approved, &t));
4751        assert_eq!(resumed_instruction(&approved, &t), approved);
4752        t.release_operator("web", None);
4753        assert!(compatible_instruction(&approved, &t));
4754        assert_eq!(t.resumption_history.len(), 1);
4755        t.start("run".into());
4756        assert!(instruction_for(&t).contains("Explicit operator resumption"));
4757    }
4758
4759    /// A run that stopped on an infrastructure wait asked no agent anything:
4760    /// the task is held by the machine under a `[resource]` reason (resumable,
4761    /// re-checked by triage), and the attempt it started is given back.
4762    #[test]
4763    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
4764        let mut state = RunState::new(
4765            PathBuf::from("/repo"),
4766            "main".to_owned(),
4767            "abc1234".to_owned(),
4768            "task".to_owned(),
4769            Config::default(),
4770        );
4771        state.status = RunStatus::Blocked;
4772        state.resource_block = Some(crate::run::ResourceBlock {
4773            node: "graft".to_owned(),
4774            kind: "shared build cache".to_owned(),
4775            detail: "timed out".to_owned(),
4776            at: jiff::Timestamp::now(),
4777        });
4778        let mut t = task();
4779        t.start("20260902-000000-aaaa".to_owned());
4780        assert_eq!(t.attempts, 1);
4781        let verdict = Verdict {
4782            status: RunStatus::Blocked,
4783            left_pr: false,
4784            quota_hit: false,
4785            parked: false,
4786            no_viable_candidates: false,
4787        };
4788        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
4789        assert_eq!(t.status, TaskStatus::Held);
4790        assert_eq!(t.attempts, 0, "the attempt is refunded");
4791        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
4792        assert!(
4793            !t.operator_held(),
4794            "a machine hold, released without a human"
4795        );
4796
4797        // A park request outranks it: still the operator's doing.
4798        let mut p = task();
4799        p.start("20260902-000000-bbbb".to_owned());
4800        settle_and_diagnose(
4801            &mut p,
4802            Verdict {
4803                parked: true,
4804                ..verdict
4805            },
4806            "parked",
4807            2,
4808            &state,
4809        );
4810        assert_eq!(p.status, TaskStatus::Parked);
4811    }
4812
4813    #[test]
4814    fn record_failure_notice_links_the_task() {
4815        let dir = tempfile::tempdir().unwrap();
4816        // A regular file where the queue directory should be makes every
4817        // `put` fail, on every platform and whoever runs the test.
4818        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
4819        let queue = Queue::at(dir.path().join("queue"));
4820        let mut t = interrupt_task("rec-fail-1");
4821        record(&queue, &mut t);
4822
4823        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
4824        assert_eq!(found.len(), 1);
4825        assert_eq!(found[0].key, "loop:record");
4826        assert_eq!(
4827            found[0].link,
4828            Some(Link::Task {
4829                id: "rec-fail-1".to_owned()
4830            })
4831        );
4832    }
4833
4834    /// A runnable task marked to interrupt, with an id fixed for assertions
4835    /// rather than the random one [`Task::new`] mints.
4836    fn interrupt_task(id: &str) -> Task {
4837        let mut t = task();
4838        t.id = id.to_owned();
4839        t.interrupt = true;
4840        t
4841    }
4842
4843    /// An ordinary runnable task with an id fixed for assertions.
4844    fn task_with_id(id: &str) -> Task {
4845        let mut t = task();
4846        t.id = id.to_owned();
4847        t
4848    }
4849
4850    /// A runnable task marked `--urgent`, with an id fixed for assertions.
4851    fn urgent_task(id: &str) -> Task {
4852        let mut t = task();
4853        t.id = id.to_owned();
4854        t.urgent = true;
4855        t
4856    }
4857
4858    #[test]
4859    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
4860        let dir = tempfile::tempdir().unwrap();
4861        let queue = Queue::at(dir.path().join("queue"));
4862        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
4863        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
4864        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
4865        let mut first = task();
4866        queue.put(&mut first).unwrap();
4867        let stale_plain = queue.get(&first.id).unwrap();
4868        first.set_urgent(true).unwrap();
4869        queue.put(&mut first).unwrap();
4870        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
4871        let mut second = urgent_task("second");
4872        queue.put(&mut second).unwrap();
4873        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
4874        drop(queue.claim(&second.id).unwrap());
4875        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
4876        drop(dispatched);
4877        let stale_urgent = queue.get(&first.id).unwrap();
4878        first.set_urgent(false).unwrap();
4879        queue.put(&mut first).unwrap();
4880        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
4881        assert_eq!(urgent.available_permits(), 1);
4882        drop(queue.claim(&first.id).unwrap());
4883        drop(occupied);
4884    }
4885
4886    #[test]
4887    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
4888        let dir = tempfile::tempdir().unwrap();
4889        let queue = Queue::at(dir.path().join("queue"));
4890        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
4891        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
4892        let mut t = task();
4893        queue.put(&mut t).unwrap();
4894        for enabled in [true, false] {
4895            let stale = queue.get(&t.id).unwrap();
4896            t.set_urgent(enabled).unwrap();
4897            queue.put(&mut t).unwrap();
4898            assert_ne!(stale.urgent, enabled);
4899            let DispatchClaim {
4900                task: fresh,
4901                claim,
4902                permit,
4903            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
4904            assert_eq!(fresh.urgent, enabled);
4905            assert_eq!(ordinary.available_permits(), usize::from(enabled));
4906            assert_eq!(urgent.available_permits(), usize::from(!enabled));
4907            assert!(queue.claim(&t.id).is_err());
4908            assert_eq!(fresh.attempts, stale.attempts);
4909            drop((claim, permit));
4910            assert_eq!(ordinary.available_permits(), 1);
4911            assert_eq!(urgent.available_permits(), 1);
4912        }
4913        t.set_urgent(true).unwrap();
4914        queue.put(&mut t).unwrap();
4915        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
4916        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
4917        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
4918        drop(queue.claim(&t.id).unwrap());
4919        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
4920        drop(occupied);
4921        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
4922        drop(queue.claim(&t.id).unwrap());
4923        let held = queue.claim(&t.id).unwrap();
4924        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
4925        drop(held);
4926        t.status = TaskStatus::Held;
4927        queue.put(&mut t).unwrap();
4928        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
4929        drop(queue.claim(&t.id).unwrap());
4930        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
4931        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
4932        drop(queue.claim(&t.id).unwrap());
4933        assert_eq!(urgent.available_permits(), 1);
4934    }
4935
4936    /// The land-resume exemption wins outright, whether or not the candidate
4937    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
4938    /// queue behind anything" guarantee cannot be weaker just because the
4939    /// same task was also filed with `--urgent`.
4940    #[test]
4941    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
4942        assert_eq!(permit_kind(true, false), PermitKind::None);
4943        assert_eq!(permit_kind(true, true), PermitKind::None);
4944    }
4945
4946    /// The one property this whole feature exists for: `--urgent` draws from
4947    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
4948    /// ordinary candidate draws from the ordinary pool exactly as before,
4949    /// untouched by the urgent slot's existence.
4950    #[test]
4951    fn permit_kind_separates_urgent_from_ordinary() {
4952        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
4953        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
4954    }
4955
4956    /// The exact wiring `attempt` runs before minting anything: a config's
4957    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
4958    /// Free space is injected rather than asked of the real disk - the point
4959    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
4960    /// is deterministic on every machine this test runs on, never dependent
4961    /// on how full the CI runner's own disk happens to be.
4962    #[test]
4963    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
4964        let cfg = Config::default();
4965        let repo = Path::new("/any/repo/path");
4966
4967        let reason =
4968            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
4969        assert!(reason.contains("1024"), "{reason}");
4970        assert!(
4971            reason.contains(&cfg.disk.min_free_bytes.to_string()),
4972            "{reason}"
4973        );
4974
4975        assert_eq!(
4976            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
4977            None,
4978            "exactly at the floor is open"
4979        );
4980        assert_eq!(
4981            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
4982            None,
4983            "comfortably above the floor is open"
4984        );
4985    }
4986
4987    #[test]
4988    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
4989        let mut cfg = Config::default();
4990        cfg.disk.min_free_bytes = 0;
4991        let repo = Path::new("/any/repo/path");
4992        assert_eq!(
4993            disk_gate_with(repo, &cfg, |_| Ok(0)),
4994            None,
4995            "a zero floor never measures at all"
4996        );
4997    }
4998
4999    #[test]
5000    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
5001        let cfg = Config::default();
5002        let repo = Path::new("/any/repo/path");
5003        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
5004            .expect("a measurement failure must close the gate, not open it");
5005        assert!(reason.contains("could not measure"), "{reason}");
5006    }
5007
5008    #[test]
5009    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
5010        let ordinary = task();
5011        let next = advance_interrupt(
5012            Interrupt::Idle,
5013            std::slice::from_ref(&ordinary.id),
5014            std::slice::from_ref(&ordinary),
5015        );
5016        assert_eq!(next, Interrupt::Idle);
5017    }
5018
5019    #[test]
5020    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
5021        // Nothing to interrupt - this is just an ordinary candidate, and the
5022        // loop's normal dispatch will pick it up like any other.
5023        let marked = interrupt_task("marked");
5024        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5025        assert_eq!(next, Interrupt::Idle);
5026    }
5027
5028    #[test]
5029    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
5030        let marked = interrupt_task("marked");
5031        let next = advance_interrupt(
5032            Interrupt::Idle,
5033            &["running".to_owned()],
5034            std::slice::from_ref(&marked),
5035        );
5036        assert_eq!(
5037            next,
5038            Interrupt::Parking {
5039                parked: vec!["running".to_owned()],
5040                interrupt_task: "marked".to_owned(),
5041            }
5042        );
5043    }
5044
5045    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
5046    /// one run can be in flight when a task becomes runnable and marked.
5047    /// Parking all of them would mean `Resuming` later has more than one id
5048    /// to release back to ordinary dispatch, which cannot be made safe
5049    /// against that same setting's own extra concurrency slots letting two
5050    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
5051    /// The simplification the task's own constraints ask for: do not begin
5052    /// a sequence at all until the herd settles back to exactly one.
5053    #[test]
5054    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
5055        let marked = interrupt_task("marked");
5056
5057        let two = advance_interrupt(
5058            Interrupt::Idle,
5059            &["a".to_owned(), "b".to_owned()],
5060            std::slice::from_ref(&marked),
5061        );
5062        assert_eq!(two, Interrupt::Idle);
5063
5064        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5065        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
5066    }
5067
5068    #[test]
5069    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
5070        let state = Interrupt::Parking {
5071            parked: vec!["running".to_owned()],
5072            interrupt_task: "marked".to_owned(),
5073        };
5074        // Still in flight: no change.
5075        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
5076        assert_eq!(still_going, state);
5077
5078        // Left flight, but the interrupt task has not been dispatched yet on
5079        // this tick - stays `Parking` so `interrupt_gate` can let it through,
5080        // as long as it is still runnable.
5081        let stopped_but_not_yet_dispatched =
5082            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
5083        assert_eq!(stopped_but_not_yet_dispatched, state);
5084
5085        // Left flight, and the interrupt task is now in flight itself.
5086        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
5087        assert_eq!(
5088            dispatched,
5089            Interrupt::Running {
5090                parked: vec!["running".to_owned()],
5091                interrupt_task: "marked".to_owned(),
5092            }
5093        );
5094    }
5095
5096    #[test]
5097    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
5098        let state = Interrupt::Running {
5099            parked: vec!["running".to_owned()],
5100            interrupt_task: "marked".to_owned(),
5101        };
5102        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
5103        assert_eq!(still_running, state);
5104
5105        // Whatever it ended as - merged, failed, held - is not this
5106        // function's concern: leaving flight is the only trigger, driven
5107        // straight off the same in-flight list `poll` already reaps. It does
5108        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
5109        // why that would let an unrelated task start ahead of, or alongside,
5110        // the guaranteed resume.
5111        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
5112        assert_eq!(
5113            ended,
5114            Interrupt::Resuming {
5115                parked: vec!["running".to_owned()]
5116            }
5117        );
5118    }
5119
5120    #[test]
5121    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
5122        let state = Interrupt::Resuming {
5123            parked: vec!["running".to_owned()],
5124        };
5125        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
5126        assert_eq!(still_waiting, state);
5127
5128        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
5129        assert_eq!(dispatched, Interrupt::Idle);
5130    }
5131
5132    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
5133    /// or otherwise moved on by an operator with no claim standing in the
5134    /// way - must not wedge the sequence (and so the whole loop's dispatch,
5135    /// via `interrupt_gate`) waiting forever for a dispatch that can never
5136    /// come. The parked run still gets its resume.
5137    #[test]
5138    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
5139    {
5140        let state = Interrupt::Parking {
5141            parked: vec!["running".to_owned()],
5142            interrupt_task: "marked".to_owned(),
5143        };
5144        // `marked` has been held/blocked/deleted since the sequence began:
5145        // it no longer appears in `runnable` at all.
5146        let next = advance_interrupt(state, &[], &[]);
5147        assert_eq!(
5148            next,
5149            Interrupt::Resuming {
5150                parked: vec!["running".to_owned()]
5151            },
5152            "abandoning the interrupt must not abandon the resume it owes"
5153        );
5154    }
5155
5156    /// The same abandonment, one step later: `Resuming` itself must not wait
5157    /// forever for a parked task that has since become unrunnable.
5158    #[test]
5159    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
5160        let state = Interrupt::Resuming {
5161            parked: vec!["running".to_owned()],
5162        };
5163        let next = advance_interrupt(state, &[], &[]);
5164        assert_eq!(
5165            next,
5166            Interrupt::Idle,
5167            "nothing is left to wait for; the loop must not stay wedged"
5168        );
5169    }
5170
5171    #[test]
5172    fn disabled_by_config_the_sequence_can_never_leave_idle() {
5173        let marked = interrupt_task("marked");
5174        let next = advance_interrupt_tick(
5175            false,
5176            Interrupt::Idle,
5177            &["running".to_owned()],
5178            std::slice::from_ref(&marked),
5179        );
5180        assert_eq!(
5181            next,
5182            Interrupt::Idle,
5183            "an unmarked, unconfigured daemon must behave exactly as before"
5184        );
5185    }
5186
5187    #[test]
5188    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
5189        let state = Interrupt::Parking {
5190            parked: vec!["running".to_owned()],
5191            interrupt_task: "marked".to_owned(),
5192        };
5193        let candidates = vec![interrupt_task("marked"), task()];
5194        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5195        assert!(
5196            allowed.is_empty(),
5197            "nothing may dispatch - not even the interrupt task itself - \
5198             until the parked run has actually stopped"
5199        );
5200    }
5201
5202    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
5203    /// grow a special case for it: an urgent candidate that is not the
5204    /// interrupt task withholds exactly like an ordinary one for as long as
5205    /// the parked run it is racing has not actually left flight. A version
5206    /// of this feature once bypassed the gate for urgent candidates, on the
5207    /// theory that a genuinely separate concurrency lane could not collide
5208    /// with 75dd's own; it could, and did - the bypassed task dispatched
5209    /// alongside a run 75dd's own state machine had only *asked* to park,
5210    /// not yet confirmed gone, which is exactly the second run
5211    /// `Interrupt::Parking`'s own doc says must never happen. There is no
5212    /// tick during Parking/Running/Resuming where letting an extra
5213    /// candidate through is safe, urgent or not - the parked run may still
5214    /// be genuinely mid-call.
5215    #[test]
5216    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
5217        for state in [
5218            Interrupt::Parking {
5219                parked: vec!["running".to_owned()],
5220                interrupt_task: "marked".to_owned(),
5221            },
5222            Interrupt::Running {
5223                parked: vec!["running".to_owned()],
5224                interrupt_task: "marked".to_owned(),
5225            },
5226            Interrupt::Resuming {
5227                parked: vec!["running".to_owned()],
5228            },
5229        ] {
5230            let candidates = vec![
5231                interrupt_task("marked"),
5232                urgent_task("hot"),
5233                task_with_id("ordinary"),
5234            ];
5235            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5236            assert!(
5237                !allowed.iter().any(|t| t.id == "hot"),
5238                "an urgent candidate must wait out the same gate as anything \
5239                 else while the run it would run alongside has not actually \
5240                 left flight, for state {state:?}: {allowed:?}"
5241            );
5242        }
5243    }
5244
5245    /// The one case where marking a task `--urgent` and `interrupt` at once
5246    /// is not redundant: once the interrupt sequence's own guaranteed
5247    /// resume/dispatch actually admits the task, it is unaffected by also
5248    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
5249    /// never on the urgent flag.
5250    #[test]
5251    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
5252        let state = Interrupt::Resuming {
5253            parked: vec!["hot".to_owned()],
5254        };
5255        let candidates = vec![urgent_task("hot"), task()];
5256        let allowed = interrupt_gate(&state, &[], candidates);
5257        assert_eq!(
5258            allowed.iter().filter(|t| t.id == "hot").count(),
5259            1,
5260            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
5261        );
5262    }
5263
5264    #[test]
5265    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
5266        let state = Interrupt::Parking {
5267            parked: vec!["running".to_owned()],
5268            interrupt_task: "marked".to_owned(),
5269        };
5270        let other = task();
5271        let candidates = vec![interrupt_task("marked"), other.clone()];
5272        let allowed = interrupt_gate(&state, &[], candidates);
5273        assert_eq!(allowed.len(), 1);
5274        assert_eq!(allowed[0].id, "marked");
5275    }
5276
5277    #[test]
5278    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
5279        let state = Interrupt::Running {
5280            parked: vec!["running".to_owned()],
5281            interrupt_task: "marked".to_owned(),
5282        };
5283        let candidates = vec![task(), task()];
5284        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
5285        assert!(allowed.is_empty());
5286    }
5287
5288    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
5289    /// sequence began (only reachable above the default
5290    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
5291    /// never both in the same tick, which is what "exactly one resume, no
5292    /// simultaneous run" actually requires structurally rather than by
5293    /// coincidence of how many ordinary slots happen to be free.
5294    #[test]
5295    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
5296        let state = Interrupt::Resuming {
5297            parked: vec!["a".to_owned(), "c".to_owned()],
5298        };
5299        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
5300        let allowed = interrupt_gate(&state, &[], candidates);
5301        assert_eq!(
5302            allowed.len(),
5303            1,
5304            "at most one candidate may be offered while resuming: {allowed:?}"
5305        );
5306        assert_eq!(allowed[0].id, "a");
5307    }
5308
5309    #[test]
5310    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
5311        let state = Interrupt::Resuming {
5312            parked: vec!["a".to_owned()],
5313        };
5314        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
5315        assert!(allowed.is_empty());
5316    }
5317
5318    /// The invariant the completion criteria ask for by name: across a whole
5319    /// simulated sequence, there is never a tick where the gate would let
5320    /// through both the parked run's resume and the interrupt task, and
5321    /// exactly one candidate resumes the instant the interrupt task's run
5322    /// ends - never zero, never more than one.
5323    #[test]
5324    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
5325        let running = task(); // id: whatever `Task::new` minted
5326        let marked = interrupt_task("marked");
5327
5328        let mut state = Interrupt::Idle;
5329        // Tick 1: `running` is in flight, `marked` becomes runnable.
5330        let in_flight = vec![running.id.clone()];
5331        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
5332        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
5333        assert!(gated.is_empty(), "still waiting on `running` to park");
5334
5335        // Tick 2: `running` parked and left flight; nothing dispatched yet.
5336        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
5337        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
5338        assert_eq!(
5339            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5340            vec!["marked"],
5341            "only the interrupt task may be offered to the dispatcher now"
5342        );
5343
5344        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
5345        state = advance_interrupt_tick(
5346            true,
5347            state,
5348            &["marked".to_owned()],
5349            std::slice::from_ref(&running),
5350        );
5351        let gated = interrupt_gate(
5352            &state,
5353            &["marked".to_owned()],
5354            vec![marked.clone(), running.clone()],
5355        );
5356        assert!(
5357            gated.is_empty(),
5358            "the parked run must not be offered back while the interrupt \
5359             task is still running"
5360        );
5361
5362        // Tick 4: `marked`'s run reached a terminal status and left flight.
5363        // A higher-priority ordinary task `other` is also runnable now - it
5364        // must not be let through instead of, or alongside, `running`.
5365        let other = task_with_id("other");
5366        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
5367        assert_eq!(
5368            state,
5369            Interrupt::Resuming {
5370                parked: vec![running.id.clone()]
5371            }
5372        );
5373        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
5374        assert_eq!(
5375            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5376            vec![running.id.as_str()],
5377            "exactly the parked run resumes - not the unrelated task, even \
5378             though it was offered first"
5379        );
5380
5381        // Tick 5: `running` is now in flight (dispatched from tick 4's
5382        // gate). Only now does the sequence end and ordinary dispatch fully
5383        // resume.
5384        state = advance_interrupt_tick(
5385            true,
5386            state,
5387            std::slice::from_ref(&running.id),
5388            std::slice::from_ref(&other),
5389        );
5390        assert_eq!(state, Interrupt::Idle);
5391        let gated = interrupt_gate(
5392            &state,
5393            std::slice::from_ref(&running.id),
5394            vec![other.clone()],
5395        );
5396        assert_eq!(
5397            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5398            vec![other.id.as_str()],
5399            "ordinary dispatch is unrestricted again"
5400        );
5401    }
5402
5403    #[test]
5404    fn every_run_status_settles_the_task_it_came_from() {
5405        // run status, resulting task status, attempts still standing after one
5406        let table = [
5407            (RunStatus::Merged, TaskStatus::Done, 1),
5408            (RunStatus::Ready, TaskStatus::Done, 1),
5409            (RunStatus::Stalled, TaskStatus::Failed, 0),
5410            (RunStatus::Blocked, TaskStatus::Failed, 1),
5411            (RunStatus::Failed, TaskStatus::Failed, 1),
5412            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
5413            (RunStatus::Prep, TaskStatus::Failed, 1),
5414            (RunStatus::Implementing, TaskStatus::Failed, 1),
5415            (RunStatus::Judging, TaskStatus::Failed, 1),
5416            (RunStatus::Deliberating, TaskStatus::Failed, 1),
5417            (RunStatus::Voting, TaskStatus::Failed, 1),
5418            (RunStatus::Reviewing, TaskStatus::Failed, 1),
5419            (RunStatus::Gating, TaskStatus::Failed, 1),
5420        ];
5421        for (run, want, attempts) in table {
5422            let mut t = task();
5423            t.start("20260902-000000-aaaa".to_owned());
5424            settle(
5425                &mut t,
5426                Verdict {
5427                    status: run,
5428                    left_pr: false,
5429                    parked: false,
5430                    quota_hit: matches!(run, RunStatus::Stalled),
5431                    no_viable_candidates: false,
5432                },
5433                "why",
5434                2,
5435            );
5436            assert_eq!(t.status, want, "task status after {}", label(run));
5437            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
5438        }
5439    }
5440
5441    #[test]
5442    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
5443        let mut stalled = task();
5444        stalled.start("20260902-000000-aaaa".to_owned());
5445        settle(
5446            &mut stalled,
5447            Verdict {
5448                status: RunStatus::Stalled,
5449                left_pr: false,
5450                parked: false,
5451                quota_hit: true,
5452                no_viable_candidates: false,
5453            },
5454            "quota",
5455            1,
5456        );
5457        assert_eq!(stalled.attempts, 0);
5458        assert!(
5459            stalled.status.runnable(),
5460            "a machine problem must leave the task in line"
5461        );
5462
5463        let mut blocked = task();
5464        blocked.start("20260902-000000-aaaa".to_owned());
5465        settle(
5466            &mut blocked,
5467            Verdict {
5468                status: RunStatus::Blocked,
5469                left_pr: false,
5470                parked: false,
5471                quota_hit: false,
5472                no_viable_candidates: false,
5473            },
5474            "findings open",
5475            1,
5476        );
5477        assert_eq!(blocked.attempts, 1);
5478        assert_eq!(
5479            blocked.status,
5480            TaskStatus::Held,
5481            "the last attempt hands the task to a human"
5482        );
5483    }
5484
5485    #[test]
5486    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
5487        // Attempts to spare: without the pull request this task would go
5488        // straight back in line and run the whole competition again.
5489        let mut delivered = task();
5490        delivered.start("20260903-080619-01c2".to_owned());
5491        settle(
5492            &mut delivered,
5493            Verdict {
5494                status: RunStatus::Blocked,
5495                left_pr: true,
5496                parked: false,
5497                quota_hit: false,
5498                no_viable_candidates: false,
5499            },
5500            "no check status",
5501            4,
5502        );
5503        assert_eq!(
5504            delivered.status,
5505            TaskStatus::Held,
5506            "a pull request waiting on CI or a person is not a retryable failure"
5507        );
5508        assert!(
5509            !delivered.status.runnable(),
5510            "the loop must not pick this task up again"
5511        );
5512        assert_eq!(
5513            delivered.last_error.as_deref(),
5514            Some("no check status"),
5515            "the operator needs to be told what the gate was waiting for"
5516        );
5517
5518        // The same status without a pull request is a plain failure, and with
5519        // attempts left it is retried.
5520        let mut empty_handed = task();
5521        empty_handed.start("20260903-080619-01c2".to_owned());
5522        settle(
5523            &mut empty_handed,
5524            Verdict {
5525                status: RunStatus::Blocked,
5526                left_pr: false,
5527                parked: false,
5528                quota_hit: false,
5529                no_viable_candidates: false,
5530            },
5531            "findings open",
5532            4,
5533        );
5534        assert_eq!(empty_handed.status, TaskStatus::Failed);
5535        assert!(empty_handed.status.runnable());
5536    }
5537
5538    #[test]
5539    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
5540        // Every candidate agreed, with evidence, that nothing belonged in the
5541        // worktree. That is not a confirmed success to close automatically -
5542        // a human still has to check the claim - and it is not an ordinary
5543        // failure either, so this settles exactly like a pull request nobody
5544        // merged yet: `Held`, same as `Blocked` with a PR.
5545        let mut noop = task();
5546        noop.start("20260912-131304-391f".to_owned());
5547        settle(
5548            &mut noop,
5549            Verdict {
5550                status: RunStatus::VerifiedNoop,
5551                left_pr: false,
5552                parked: false,
5553                quota_hit: false,
5554                no_viable_candidates: true,
5555            },
5556            "candidate A: already fixed by b32cfc4, on main",
5557            4,
5558        );
5559        assert_eq!(
5560            noop.status,
5561            TaskStatus::Held,
5562            "an unverified claim is a request for a human, not a failure"
5563        );
5564        assert!(
5565            !noop.status.runnable(),
5566            "the loop must not requeue this on the same unverified claim"
5567        );
5568        // `Task::release` resets attempts to zero the moment a human looks at
5569        // the evidence and lets it run again, so it does not matter here
5570        // whether the one attempt already spent stays spent - what matters is
5571        // that nothing retries this task unattended in the meantime.
5572        assert_eq!(noop.attempts, 1);
5573    }
5574
5575    #[test]
5576    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
5577        // Parking is the operator asking for the process back - to replace the
5578        // binary, most of all. The run's work is intact on disk, so this is
5579        // not a failed attempt, and charging for it would mean a few upgrades
5580        // could exhaust a budget meant for agents that misbehaved.
5581        let mut parked = task();
5582        parked.start("20260903-183634-2d98".to_owned());
5583        settle(
5584            &mut parked,
5585            Verdict {
5586                status: RunStatus::Implementing,
5587                left_pr: false,
5588                quota_hit: false,
5589                parked: true,
5590                no_viable_candidates: false,
5591            },
5592            "parked after `implementing`",
5593            2,
5594        );
5595        assert_eq!(parked.attempts, 0, "a park is refunded");
5596        assert!(
5597            parked.status.runnable(),
5598            "and the task stays in line so the next loop resumes its run"
5599        );
5600        assert_eq!(parked.status, TaskStatus::Parked);
5601        assert_eq!(
5602            parked.park_reason.as_deref(),
5603            Some("parked after `implementing`"),
5604            "the card says where it stopped"
5605        );
5606        assert_eq!(parked.last_error, None, "nothing failed");
5607
5608        // Without the park flag the same non-terminal status is what it always
5609        // was: `execute` returning mid-flight, which is a bug and spends an
5610        // attempt so a task cannot loop on it forever.
5611        let mut broken = task();
5612        broken.start("20260903-183634-2d98".to_owned());
5613        settle(
5614            &mut broken,
5615            Verdict {
5616                status: RunStatus::Implementing,
5617                left_pr: false,
5618                quota_hit: false,
5619                parked: false,
5620                no_viable_candidates: false,
5621            },
5622            "returned mid-flight",
5623            2,
5624        );
5625        assert_eq!(broken.attempts, 1);
5626    }
5627
5628    #[test]
5629    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
5630        // Run e633: quorum lost because two judges answered with the wrong
5631        // JSON shape, `quota: []`. Refunding that takes the bound off the
5632        // retry loop, and each retry pays for a fresh hour-long implement
5633        // wave before it can fail the same way.
5634        let mut flaky = task();
5635        flaky.start("20260903-123023-e633".to_owned());
5636        settle(
5637            &mut flaky,
5638            Verdict {
5639                status: RunStatus::Stalled,
5640                left_pr: false,
5641                parked: false,
5642                quota_hit: false,
5643                no_viable_candidates: false,
5644            },
5645            "verdict rests on 1 of 3 judges",
5646            2,
5647        );
5648        assert_eq!(
5649            flaky.attempts, 1,
5650            "flakiness spends an attempt, so `max_attempts` still bounds it"
5651        );
5652        assert!(flaky.status.runnable(), "and it is still worth retrying");
5653
5654        // The same status, lost to a rate limit, is the machine's fault.
5655        let mut limited = task();
5656        limited.start("20260903-123023-e633".to_owned());
5657        settle(
5658            &mut limited,
5659            Verdict {
5660                status: RunStatus::Stalled,
5661                left_pr: false,
5662                parked: false,
5663                quota_hit: true,
5664                no_viable_candidates: false,
5665            },
5666            "judge-2, judge-3 out of quota",
5667            2,
5668        );
5669        assert_eq!(limited.attempts, 0, "a quota window is refunded");
5670        assert!(limited.status.runnable());
5671
5672        // And the bound really binds: a task that keeps stalling on flakiness
5673        // reaches a human instead of running the roster forever.
5674        let mut worn = task();
5675        for _ in 0..2 {
5676            worn.release();
5677        }
5678        worn.start("20260903-123023-e633".to_owned());
5679        worn.attempts = 2;
5680        settle(
5681            &mut worn,
5682            Verdict {
5683                status: RunStatus::Stalled,
5684                left_pr: false,
5685                parked: false,
5686                quota_hit: false,
5687                no_viable_candidates: false,
5688            },
5689            "no quorum again",
5690            2,
5691        );
5692        assert_eq!(worn.status, TaskStatus::Held);
5693        assert!(!worn.status.runnable());
5694    }
5695
5696    #[test]
5697    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
5698        // The implement wave loses every seat to the same rate limit and
5699        // `after_implement` bails with nothing viable, which surfaces as
5700        // `Failed` rather than `Stalled`. That is the same machine fact the
5701        // `Stalled`-quota row already refunds, and must be refunded the same
5702        // way, or a quota outage quietly holds every task it touches instead
5703        // of leaving them in line for the reset.
5704        let mut wiped_out = task();
5705        wiped_out.start("20260907-025000-a1b2".to_owned());
5706        settle(
5707            &mut wiped_out,
5708            Verdict {
5709                status: RunStatus::Failed,
5710                left_pr: false,
5711                parked: false,
5712                quota_hit: true,
5713                no_viable_candidates: true,
5714            },
5715            "no candidate produced a change; nothing to judge",
5716            2,
5717        );
5718        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
5719        assert!(
5720            wiped_out.status.runnable(),
5721            "a machine problem must leave the task in line"
5722        );
5723
5724        // This is the exemption that must stay narrow: a candidate that did
5725        // produce a change, and then failed for some other reason, still
5726        // spends the attempt even though a seat elsewhere hit its quota.
5727        // Otherwise every ordinary failure that happens to share a run with
5728        // an unrelated rate limit would be refunded for free.
5729        let mut partial_progress = task();
5730        partial_progress.start("20260907-025500-c3d4".to_owned());
5731        settle(
5732            &mut partial_progress,
5733            Verdict {
5734                status: RunStatus::Failed,
5735                left_pr: false,
5736                parked: false,
5737                quota_hit: true,
5738                no_viable_candidates: false,
5739            },
5740            "gate failed on the winning candidate",
5741            2,
5742        );
5743        assert_eq!(
5744            partial_progress.attempts, 1,
5745            "a candidate that actually produced a change spends the attempt \
5746             even though some other seat hit its quota"
5747        );
5748        assert!(partial_progress.status.runnable());
5749    }
5750
5751    #[test]
5752    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
5753        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
5754        // disk, and that construction must reach the same conclusion as the
5755        // one `attempt` builds from a live run, or a crash at exactly the
5756        // wrong moment gives a recovered task a different policy than one a
5757        // daemon finished settling itself.
5758        let mut t = task();
5759        t.start("20260907-025000-a1b2".to_owned());
5760        let mut state = run_state(RunStatus::Failed);
5761        state.quota.push(QuotaLoss {
5762            seat: "cand-a".to_owned(),
5763            node: "implement".to_owned(),
5764            at: Timestamp::now(),
5765            reset: None,
5766        });
5767        assert!(
5768            state.viable().is_empty(),
5769            "no candidate was added, so nothing is viable"
5770        );
5771        reclaim(&mut t, Some(state), 2, "en");
5772        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
5773        assert!(t.status.runnable());
5774    }
5775
5776    #[test]
5777    fn a_held_task_is_never_offered_to_the_loop() {
5778        let dir = tempfile::tempdir().unwrap();
5779        let queue = Queue::at(dir.path().to_path_buf());
5780        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
5781            let mut t = task();
5782            t.id = format!("2026090{n}-000000-000{n}");
5783            t.priority = priority;
5784            queue.put(&mut t).unwrap();
5785        }
5786        let mut held = task();
5787        held.id = "20260909-000000-9999".to_owned();
5788        held.priority = 99;
5789        held.hold_machine(None);
5790        queue.put(&mut held).unwrap();
5791
5792        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
5793        assert_eq!(order.len(), 3);
5794        assert!(!order.contains(&held.id));
5795        assert_eq!(
5796            order.first().cloned(),
5797            queue.next_runnable().map(|t| t.id),
5798            "the loop's first candidate is exactly what the queue offers"
5799        );
5800        assert_eq!(
5801            order,
5802            vec![
5803                "20260902-000000-0002".to_owned(),
5804                "20260903-000000-0003".to_owned(),
5805                "20260901-000000-0001".to_owned(),
5806            ],
5807            "priority first, then oldest, so nothing starves"
5808        );
5809    }
5810
5811    #[test]
5812    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
5813        let dir = tempfile::tempdir().unwrap();
5814        let queue = Queue::at(dir.path().to_path_buf());
5815        let mut old = task();
5816        old.id = "20260101-000000-old0".to_owned();
5817        queue.put(&mut old).unwrap();
5818        let mut fresh = task();
5819        fresh.id = "20260101-000000-new0".to_owned();
5820        queue.put(&mut fresh).unwrap();
5821
5822        // No parseable pid at all, so age is the only signal there is to
5823        // check - unlike a real `Queue::claim`, which always names a real,
5824        // and therefore alive, pid this test cannot fake as dead.
5825        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
5826        std::thread::sleep(Duration::from_millis(60));
5827        let live = queue.claim(&fresh.id).unwrap();
5828
5829        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5830        assert_eq!(swept, vec![old.id.clone()]);
5831        assert!(
5832            queue.claim(&old.id).is_ok(),
5833            "an unparseable lock older than the threshold is swept"
5834        );
5835        assert!(
5836            queue.claim(&fresh.id).is_err(),
5837            "a live pid protects its lock regardless of age"
5838        );
5839        drop(live);
5840    }
5841
5842    #[test]
5843    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
5844        // The regression this guards: `sweep` now runs concurrently with
5845        // every attempt this daemon itself has spawned (see
5846        // `InFlightGuard`), not only between them the way a single
5847        // sequential loop once did. A run that legitimately outlives
5848        // `older_than` still has this very process's own live pid sitting in
5849        // its own lock file on every later sweep, and deciding by age alone
5850        // would delete that still-valid claim out from under the attempt
5851        // that holds it - which `reclaim_orphaned_running` would then read
5852        // as abandoned and hand to a second, competing attempt.
5853        let dir = tempfile::tempdir().unwrap();
5854        let queue = Queue::at(dir.path().to_path_buf());
5855        let mut t = task();
5856        t.id = "20260101-000000-live".to_owned();
5857        queue.put(&mut t).unwrap();
5858
5859        let claim = queue.claim(&t.id).unwrap();
5860        std::thread::sleep(Duration::from_millis(60));
5861
5862        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
5863        assert!(
5864            swept.is_empty(),
5865            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
5866        );
5867        assert!(
5868            queue.claim(&t.id).is_err(),
5869            "the lock still protects its task"
5870        );
5871        drop(claim);
5872    }
5873
5874    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
5875    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
5876    fn injected_dead_pid() -> u32 {
5877        std::process::id().checked_add(1).unwrap_or(1)
5878    }
5879
5880    #[test]
5881    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
5882        let dir = tempfile::tempdir().unwrap();
5883        let queue = Queue::at(dir.path().to_path_buf());
5884        let mut t = task();
5885        t.id = "20260101-000000-dead".to_owned();
5886        queue.put(&mut t).unwrap();
5887        let dead_pid = injected_dead_pid();
5888
5889        // Written directly rather than through `Queue::claim`, which would
5890        // stamp this test process's own very much alive pid and defeat the
5891        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
5892        // like moments after it died, not six hours later.
5893        std::fs::write(
5894            dir.path().join(format!("{}.lock", t.id)),
5895            dead_pid.to_string(),
5896        )
5897        .unwrap();
5898
5899        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5900            pid != dead_pid
5901        });
5902        assert_eq!(
5903            swept,
5904            vec![t.id.clone()],
5905            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
5906        );
5907        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
5908    }
5909
5910    #[test]
5911    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
5912        let dir = tempfile::tempdir().unwrap();
5913        let queue = Queue::at(dir.path().to_path_buf());
5914        let mut t = task();
5915        t.id = "20260101-000000-late".to_owned();
5916        queue.put(&mut t).unwrap();
5917        let dead_pid = injected_dead_pid();
5918
5919        // Tick one, standing in for the sweep `poll` already runs at
5920        // startup: nothing to find yet.
5921        assert!(
5922            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
5923            "nothing has claimed the task yet"
5924        );
5925
5926        // A second daemon claims the task and dies before it ever writes
5927        // `running`, well after this loop's own startup sweep already ran.
5928        std::fs::write(
5929            dir.path().join(format!("{}.lock", t.id)),
5930            dead_pid.to_string(),
5931        )
5932        .unwrap();
5933
5934        // Tick two, standing in for a poll long into this daemon's uptime:
5935        // the same function, called again, notices what only just appeared -
5936        // proving the sweep is not a one-shot startup check.
5937        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5938            pid != dead_pid
5939        });
5940        assert_eq!(swept, vec![t.id.clone()]);
5941    }
5942
5943    #[test]
5944    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
5945        // `reclaim_orphaned_running` looks up the task's last run, which
5946        // touches `run::home()`; the first call anywhere in this binary wins,
5947        // so this is a no-op if another test already pinned one, and either
5948        // way the run id below is never written under it.
5949        crate::run::pin_test_home();
5950        let dir = tempfile::tempdir().unwrap();
5951        let queue = Queue::at(dir.path().to_path_buf());
5952        let mut t = task();
5953        t.id = "20260101-000000-crsh".to_owned();
5954        t.status = TaskStatus::Running;
5955        t.attempts = 1;
5956        // No `run.json` behind this id: standing in for a run this test does
5957        // not need to make readable, since the point is the lock, not the
5958        // recovery table `reclaim` already has its own tests for.
5959        t.runs.push("20260904-000000-4043".to_owned());
5960        queue.put(&mut t).unwrap();
5961        let dead_pid = injected_dead_pid();
5962
5963        // The crashed daemon's own claim, naming a pid nothing on the
5964        // machine holds anymore.
5965        std::fs::write(
5966            dir.path().join(format!("{}.lock", t.id)),
5967            dead_pid.to_string(),
5968        )
5969        .unwrap();
5970
5971        // Before the lock is swept the task looks claimed, and
5972        // `reclaim_orphaned_running` must leave it alone - this is exactly
5973        // the bug: a `running` task stranded behind a dead daemon's lock,
5974        // invisible to the claim-as-proof check because the lock outlived
5975        // the process that wrote it.
5976        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
5977        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
5978
5979        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
5980            pid != dead_pid
5981        });
5982        assert_eq!(swept, vec![t.id.clone()]);
5983
5984        let reclaimed = reclaim_orphaned_running(&queue, 2);
5985        assert_eq!(reclaimed, vec![t.id.clone()]);
5986        let after = queue.get(&t.id).unwrap();
5987        assert_eq!(
5988            after.status,
5989            TaskStatus::Held,
5990            "no run.json to recover from, so a human is asked"
5991        );
5992        assert_eq!(
5993            after.runs,
5994            vec!["20260904-000000-4043".to_owned()],
5995            "the crashed run's id is kept as evidence, not discarded"
5996        );
5997    }
5998
5999    #[test]
6000    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
6001        let dir = tempfile::tempdir().unwrap();
6002        let queue = Queue::at(dir.path().to_path_buf());
6003        let mut t = task();
6004        t.id = "20260101-000000-unknown".to_owned();
6005        queue.put(&mut t).unwrap();
6006        let dead_pid = injected_dead_pid();
6007        std::fs::write(
6008            dir.path().join(format!("{}.lock", t.id)),
6009            dead_pid.to_string(),
6010        )
6011        .unwrap();
6012
6013        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
6014        assert!(swept.is_empty(), "an unknown pid must keep its lock");
6015        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
6016    }
6017
6018    fn run_state_in(status: RunStatus, language: &str) -> RunState {
6019        let mut s = run_state(status);
6020        s.config.graph.language = language.to_owned();
6021        s
6022    }
6023
6024    fn unstarted_verdict(status: RunStatus) -> Verdict {
6025        Verdict {
6026            status,
6027            left_pr: false,
6028            quota_hit: false,
6029            parked: false,
6030            no_viable_candidates: false,
6031        }
6032    }
6033
6034    #[test]
6035    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
6036        let mut t = task();
6037        t.attempts = 1;
6038        settle_in(
6039            &mut t,
6040            unstarted_verdict(RunStatus::AlreadyInBase),
6041            "already in main",
6042            1,
6043            phrases("en"),
6044        );
6045        assert_eq!(t.status, TaskStatus::Done);
6046        assert_eq!(t.attempts, 0);
6047    }
6048
6049    #[test]
6050    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
6051        let reason = |language: &str| {
6052            let mut t = task();
6053            settle_in(
6054                &mut t,
6055                unstarted_verdict(RunStatus::Judging),
6056                "boom",
6057                1,
6058                phrases(language),
6059            );
6060            t.last_error.or(t.hold_reason).unwrap_or_default()
6061        };
6062        assert!(
6063            reason("en").starts_with("the graph stopped at `"),
6064            "{}",
6065            reason("en")
6066        );
6067        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
6068        assert!(reason("日本語").contains("boom"));
6069        assert_eq!(reason("fr"), reason("en"));
6070    }
6071
6072    #[test]
6073    fn describe_follows_the_run_language_and_keeps_the_run_id() {
6074        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
6075        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
6076        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
6077        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
6078        assert!(ja.contains("[run "), "{ja}");
6079        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
6080        assert!(ended.starts_with("run 終了: "), "{ended}");
6081        let mut de = run_state_in(RunStatus::Failed, "de");
6082        let mut en = run_state_in(RunStatus::Failed, "en");
6083        de.id = "same".to_owned();
6084        en.id = "same".to_owned();
6085        assert_eq!(describe(&de), describe(&en));
6086    }
6087
6088    #[test]
6089    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
6090        use crate::handover::Refused;
6091        let cases = [
6092            Refused::Foreign {
6093                branch: "b".into(),
6094                path: "/w/x".into(),
6095                why: "made by hand".into(),
6096            },
6097            Refused::Unsafe {
6098                branch: "b".into(),
6099                path: "/w/x".into(),
6100                why: "its worktree has uncommitted changes (a.rs)".into(),
6101            },
6102            Refused::ReleaseFailed {
6103                branch: "b".into(),
6104                path: "/w/x".into(),
6105                run: "ab12".into(),
6106            },
6107        ];
6108        for r in &cases {
6109            let en = (phrases("en").handover_refused)(r);
6110            assert_eq!(en, r.to_string());
6111            let ja = (phrases("ja").handover_refused)(r);
6112            assert!(
6113                !ja.contains("is checked out") && !ja.contains("try again"),
6114                "{ja}"
6115            );
6116            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
6117            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
6118                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
6119            }
6120        }
6121        assert!(phrases("en").handover_hint.contains("release the task"));
6122        assert!(phrases("ja").handover_hint.contains("解放"));
6123    }
6124
6125    #[test]
6126    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
6127        let build = |lang: &str| {
6128            let mut s = run_state_in(RunStatus::Blocked, lang);
6129            s.id = "same".to_owned();
6130            s.config.graph.review_rounds = 3;
6131            let mut r = review_round(3);
6132            r.expected = 3;
6133            r.answered = 1;
6134            s.reviews.push(r);
6135            s.event(
6136                "review",
6137                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
6138            );
6139            s
6140        };
6141        let en = describe(&build("en"));
6142        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
6143        let ja = describe(&build("ja"));
6144        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
6145        assert!(!ja.contains("never answered"), "{ja}");
6146        assert!(ja.contains("[run "), "{ja}");
6147
6148        // An incomplete panel whose verification failed is a different stop:
6149        // the real event must survive in ja too.
6150        let mut failed = build("ja");
6151        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
6152            command: "cargo test".to_owned(),
6153            code: Some(1),
6154            output_tail: String::new(),
6155            duration_ms: 0,
6156            resource_blocked: false,
6157        });
6158        failed.event("review", "stopped; e2e failed: cargo test");
6159        let ja = describe(&failed);
6160        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
6161        assert!(!ja.contains("席のレビュアー"), "{ja}");
6162    }
6163
6164    #[test]
6165    fn refusals_and_recovery_prose_follow_the_language() {
6166        let t = held_task_with("r1");
6167        let q = action_question(
6168            "r1",
6169            ask::ChoiceAction::Resume {
6170                run: "r1".to_owned(),
6171            },
6172        );
6173        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
6174            ActionDecision::Refuse(s) => s,
6175            other => panic!("{other:?}"),
6176        };
6177        assert!(refuse(phrases("en")).contains("could not be read: gone"));
6178        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
6179        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
6180
6181        let mut held = task();
6182        reclaim(&mut held, None, 2, "ja");
6183        assert!(held.hold_reason.unwrap().contains("保留にしました"));
6184        let mut held = task();
6185        reclaim(&mut held, None, 2, "xx");
6186        assert!(held.hold_reason.unwrap().contains("held for a human"));
6187    }
6188
6189    fn run_state(status: RunStatus) -> RunState {
6190        let mut state = RunState::new(
6191            PathBuf::from("/repo"),
6192            "main".to_owned(),
6193            "abc1234def".to_owned(),
6194            "add retries".to_owned(),
6195            Config::default(),
6196        );
6197        state.status = status;
6198        state
6199    }
6200
6201    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
6202        Candidate {
6203            index: 0,
6204            label,
6205            agent: "claude".to_owned(),
6206            branch: format!("magi/x/{label}"),
6207            worktree: PathBuf::from("/repo"),
6208            summary: summary.to_owned(),
6209            stat: String::new(),
6210            files: 0,
6211            commits: usize::from(!empty),
6212            empty,
6213            failed: failed.map(str::to_owned),
6214            verified_noop: None,
6215            duration_ms: 0,
6216            folded: false,
6217        }
6218    }
6219
6220    #[test]
6221    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
6222        let mut state = run_state(RunStatus::Blocked);
6223        state.gate = vec![
6224            CommandOutcome {
6225                command: "cargo make check".to_owned(),
6226                code: Some(0),
6227                output_tail: "ok".to_owned(),
6228                duration_ms: 0,
6229                resource_blocked: false,
6230            },
6231            CommandOutcome {
6232                command: "cargo test".to_owned(),
6233                code: Some(101),
6234                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
6235                duration_ms: 0,
6236                resource_blocked: false,
6237            },
6238        ];
6239        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
6240        assert!(d.contains("cargo test"), "{d}");
6241        assert!(
6242            !d.contains("cargo make check"),
6243            "a passing check is not a diagnostic: {d}"
6244        );
6245        assert!(d.contains("assertion failed"), "{d}");
6246    }
6247
6248    #[test]
6249    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
6250        let mut state = run_state(RunStatus::Blocked);
6251        state.event(
6252            "land",
6253            "stopped: the fixer produced no commit while 2 check(s) were failing \
6254             (build, lint); stopping instead of looping on an unchanged tree",
6255        );
6256        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
6257        assert!(d.contains("build"), "{d}");
6258        assert!(d.contains("lint"), "{d}");
6259        assert!(d.contains("fixer produced no commit"), "{d}");
6260    }
6261
6262    #[test]
6263    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
6264        // `describe`'s output becomes `Task::last_error` verbatim, and the
6265        // phone renders that in the same alarm-styled box an ordinary
6266        // failure gets. A bare `verified_noop` there would read exactly like
6267        // the failure this status exists to be told apart from.
6268        let state = run_state(RunStatus::VerifiedNoop);
6269        let d = describe(&state);
6270        assert!(
6271            d.contains("agent-verified no-op"),
6272            "expected the display label, not the wire spelling: {d}"
6273        );
6274        assert!(!d.contains("verified_noop"), "{d}");
6275    }
6276
6277    #[test]
6278    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
6279        // The whole point of the feature: a run held as "no candidate produced
6280        // a change" can mean the implementer actually finished the task and
6281        // only left a clean local tree behind - see AGENTS.md on this exact
6282        // failure mode. The diagnostic has to carry what the agent actually
6283        // said, not just the fact that nothing was there to judge.
6284        let mut state = run_state(RunStatus::Failed);
6285        state.candidates = vec![candidate(
6286            'A',
6287            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
6288            true,
6289            None,
6290        )];
6291        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
6292        assert!(d.contains("candidate A"), "{d}");
6293        assert!(d.contains("tagged v1.2.3"), "{d}");
6294    }
6295
6296    #[test]
6297    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
6298        let mut state = run_state(RunStatus::Failed);
6299        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
6300        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
6301        assert!(d.contains("candidate A"), "{d}");
6302        assert!(d.contains("agent timed out"), "{d}");
6303    }
6304
6305    #[test]
6306    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
6307        // A viable candidate existed, the gate never ran, and nothing land
6308        // said matches - `Task::last_error` is left to explain this one alone.
6309        let mut state = run_state(RunStatus::Failed);
6310        state.candidates = vec![candidate('A', "did the work", false, None)];
6311        assert!(diagnostic(&state).is_none());
6312    }
6313
6314    #[test]
6315    fn diagnostic_is_bounded_however_much_a_run_printed() {
6316        let mut state = run_state(RunStatus::Blocked);
6317        state.gate = vec![
6318            CommandOutcome {
6319                command: "cargo test".to_owned(),
6320                code: Some(101),
6321                output_tail: "x".repeat(50_000),
6322                duration_ms: 0,
6323                resource_blocked: false,
6324            },
6325            CommandOutcome {
6326                command: "cargo clippy".to_owned(),
6327                code: Some(1),
6328                output_tail: "y".repeat(50_000),
6329                duration_ms: 0,
6330                resource_blocked: false,
6331            },
6332        ];
6333        state.candidates = vec![
6334            candidate('A', &"z".repeat(50_000), true, None),
6335            candidate('B', &"w".repeat(50_000), true, None),
6336        ];
6337        let d = diagnostic(&state).expect("plenty here to diagnose");
6338        assert!(
6339            d.len() <= DIAGNOSTIC_MAX,
6340            "diagnostic grew to {} bytes, unbounded",
6341            d.len()
6342        );
6343    }
6344
6345    #[test]
6346    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
6347        let mut state = run_state(RunStatus::Blocked);
6348        state.gate = vec![CommandOutcome {
6349            command: "cargo test".to_owned(),
6350            code: Some(101),
6351            output_tail: "assertion failed".to_owned(),
6352            duration_ms: 0,
6353            resource_blocked: false,
6354        }];
6355        let verdict = Verdict {
6356            status: RunStatus::Blocked,
6357            left_pr: false,
6358            quota_hit: false,
6359            parked: false,
6360            no_viable_candidates: false,
6361        };
6362
6363        // Attempt one of two still has a retry coming: no diagnostic yet, the
6364        // task is going to run again and this run's evidence would go stale.
6365        let mut t = task();
6366        t.start("run-1".to_owned());
6367        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6368        assert_eq!(t.status, TaskStatus::Failed);
6369        assert!(t.diagnostic.is_none());
6370
6371        // Attempt two exhausts the budget: now it is held, and the
6372        // diagnostic is what `magi task show` has to say more than one line.
6373        t.start("run-2".to_owned());
6374        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6375        assert_eq!(t.status, TaskStatus::Held);
6376        let d = t.diagnostic.expect("a held task must carry its diagnostic");
6377        assert!(d.contains("cargo test"), "{d}");
6378    }
6379
6380    #[test]
6381    fn a_held_task_names_the_open_question_it_is_waiting_on() {
6382        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
6383        // `magi ask` question settled Held with `hold_reason: null`, so the
6384        // notification said nothing actionable. `note_open_question` should
6385        // append the question id to whatever `handed_off` already wrote.
6386        crate::run::pin_test_home();
6387        let home = crate::run::home();
6388        let state = run_state(RunStatus::VerifiedNoop);
6389        let mut q = ask::Question::new(
6390            state.id.clone(),
6391            "implement".to_owned(),
6392            "impl-A".to_owned(),
6393            "is this really a no-op?".to_owned(),
6394            String::new(),
6395            Vec::new(),
6396        );
6397        Questions::at(home.join("questions")).put(&mut q).unwrap();
6398
6399        let verdict = Verdict {
6400            status: RunStatus::VerifiedNoop,
6401            left_pr: false,
6402            quota_hit: false,
6403            parked: false,
6404            no_viable_candidates: false,
6405        };
6406        let mut t = task();
6407        t.start(state.id.clone());
6408        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
6409
6410        assert_eq!(t.status, TaskStatus::Held);
6411        let reason = t.hold_reason.expect("a held task must record why");
6412        assert!(
6413            reason.starts_with("run ended agent-verified no-op"),
6414            "the original settle reason must survive unchanged: {reason}"
6415        );
6416        assert!(
6417            reason.contains(q.short()),
6418            "the open question's id must be named so the notice is actionable: {reason}"
6419        );
6420    }
6421
6422    #[test]
6423    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
6424        crate::run::pin_test_home();
6425        let state = run_state(RunStatus::VerifiedNoop);
6426
6427        let verdict = Verdict {
6428            status: RunStatus::VerifiedNoop,
6429            left_pr: false,
6430            quota_hit: false,
6431            parked: false,
6432            no_viable_candidates: false,
6433        };
6434        let mut t = task();
6435        t.start(state.id.clone());
6436        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
6437
6438        assert_eq!(t.status, TaskStatus::Held);
6439        assert_eq!(
6440            t.hold_reason.as_deref(),
6441            Some("run ended agent-verified no-op"),
6442            "nothing to append when the question was already answered or never asked"
6443        );
6444    }
6445
6446    #[test]
6447    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
6448        crate::run::pin_test_home();
6449        let mut first = run_state(RunStatus::Blocked);
6450        first.id = "20260101-000000-sup1".to_owned();
6451        first.save().unwrap();
6452        let mut second = run_state(RunStatus::Merged);
6453        second.id = "20260101-000000-sup2".to_owned();
6454        second.save().unwrap();
6455
6456        let mut t = task();
6457        t.runs = vec![first.id.clone(), second.id.clone()];
6458        t.status = TaskStatus::Done;
6459
6460        supersede_prior_runs(&t, &crate::run::home());
6461
6462        assert_eq!(
6463            RunState::load(&first.id).unwrap().status,
6464            RunStatus::Superseded,
6465            "the first attempt's Blocked no longer needs anyone's attention"
6466        );
6467        assert_eq!(
6468            RunState::load(&second.id).unwrap().status,
6469            RunStatus::Merged,
6470            "the run that actually succeeded is left exactly as it was"
6471        );
6472    }
6473
6474    #[test]
6475    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
6476        // `is_working_on` alone only proves a *daemon* claim; a `magi run
6477        // --resume` invoked by hand outside the daemon never touches
6478        // `daemon.json` at all, so it would look identical to a genuinely
6479        // idle run without also consulting `RunState::liveness`, which reads
6480        // this run's own recorded `driver_pid` instead.
6481        crate::run::pin_test_home();
6482        let mut first = run_state(RunStatus::Blocked);
6483        first.id = "20260101-000000-sup9".to_owned();
6484        // This test process's own pid: guaranteed alive without needing a
6485        // real second process or daemon.
6486        first.driver_pid = Some(std::process::id());
6487        first.driver_started_at = Some(
6488            crate::proc::process_started_at(std::process::id())
6489                .expect("this test process's own start time must be queryable"),
6490        );
6491        first.save().unwrap();
6492        let mut second = run_state(RunStatus::Merged);
6493        second.id = "20260101-000000-supa".to_owned();
6494        second.save().unwrap();
6495
6496        let mut t = task();
6497        t.runs = vec![first.id.clone(), second.id.clone()];
6498        t.status = TaskStatus::Done;
6499
6500        supersede_prior_runs(&t, &crate::run::home());
6501
6502        assert_eq!(
6503            RunState::load(&first.id).unwrap().status,
6504            RunStatus::Blocked,
6505            "a live driver_pid means something is still actually working this run, \
6506             even though no daemon claims it - rewriting under it would just be \
6507             undone the next time that process saves"
6508        );
6509    }
6510
6511    #[test]
6512    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
6513        // The first resweep must skip a still-live attempt exactly like
6514        // `supersede_prior_runs` itself does; a later resweep, once that
6515        // process is no longer actually driving it, is what closes the gap
6516        // `supersede_prior_runs` alone leaves - a task only ever reaches
6517        // `Done` once, so nothing else would ever look at this run again.
6518        let dir = tempfile::tempdir().unwrap();
6519        let home = dir.path().to_path_buf();
6520        let queue = Queue::at(dir.path().join("queue"));
6521
6522        let mut first = run_state(RunStatus::Blocked);
6523        first.id = "20260101-000000-supd".to_owned();
6524        first.driver_pid = Some(std::process::id());
6525        first.driver_started_at = Some(
6526            crate::proc::process_started_at(std::process::id())
6527                .expect("this test process's own start time must be queryable"),
6528        );
6529        first.save_under(&home).unwrap();
6530        let mut second = run_state(RunStatus::Merged);
6531        second.id = "20260101-000000-supe".to_owned();
6532        second.save_under(&home).unwrap();
6533
6534        let mut t = task();
6535        t.runs = vec![first.id.clone(), second.id.clone()];
6536        t.status = TaskStatus::Done;
6537        queue.put(&mut t).unwrap();
6538
6539        resweep_superseded_attempts(&queue, &home);
6540        assert_eq!(
6541            RunState::load_under(&first.id, &home).unwrap().status,
6542            RunStatus::Blocked,
6543            "still live on the first pass, so still untouched"
6544        );
6545
6546        // Stand in for the manual process no longer being the one driving
6547        // this run: same pid (this test process really is still alive), but
6548        // an identity marker that no longer matches it - see
6549        // `RunState::liveness`'s own doc for why a mismatched
6550        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
6551        let mut stale = RunState::load_under(&first.id, &home).unwrap();
6552        stale.driver_started_at = Some("1".to_owned());
6553        stale.save_under(&home).unwrap();
6554
6555        resweep_superseded_attempts(&queue, &home);
6556        assert_eq!(
6557            RunState::load_under(&first.id, &home).unwrap().status,
6558            RunStatus::Superseded,
6559            "the second pass catches up what the first one correctly skipped"
6560        );
6561    }
6562
6563    #[test]
6564    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
6565        crate::run::pin_test_home();
6566        let mut first = run_state(RunStatus::Blocked);
6567        first.id = "20260101-000000-sup3".to_owned();
6568        first.save().unwrap();
6569        let mut second = run_state(RunStatus::Blocked);
6570        second.id = "20260101-000000-sup4".to_owned();
6571        second.save().unwrap();
6572
6573        let mut t = task();
6574        t.runs = vec![first.id.clone(), second.id.clone()];
6575        // Still retrying: nothing about this task's story is settled yet, so
6576        // neither Blocked run may be relabelled, even though a later attempt
6577        // already exists.
6578        t.status = TaskStatus::Failed;
6579
6580        supersede_prior_runs(&t, &crate::run::home());
6581
6582        assert_eq!(
6583            RunState::load(&first.id).unwrap().status,
6584            RunStatus::Blocked
6585        );
6586        assert_eq!(
6587            RunState::load(&second.id).unwrap().status,
6588            RunStatus::Blocked
6589        );
6590    }
6591
6592    #[test]
6593    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
6594        // `magi task done` (or the API's equivalent) can close a task with no
6595        // run of its own ever having succeeded - there is nothing here that
6596        // counts as "the attempt that finished it", so nothing is rewritten.
6597        crate::run::pin_test_home();
6598        let mut first = run_state(RunStatus::Blocked);
6599        first.id = "20260101-000000-sup5".to_owned();
6600        first.save().unwrap();
6601
6602        let mut t = task();
6603        t.runs = vec![first.id.clone()];
6604        t.status = TaskStatus::Done;
6605
6606        supersede_prior_runs(&t, &crate::run::home());
6607
6608        assert_eq!(
6609            RunState::load(&first.id).unwrap().status,
6610            RunStatus::Blocked,
6611            "a single-attempt task has no earlier run to supersede"
6612        );
6613    }
6614
6615    #[test]
6616    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
6617        // `magi task done` (or the web/conductor equivalents) can close a
6618        // task in any status, including one whose *last* recorded attempt is
6619        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
6620        // never watched, say. `runs.last()` being `Done`-adjacent is not
6621        // proof it actually succeeded, so nothing earlier may be relabelled
6622        // on its say-so alone.
6623        crate::run::pin_test_home();
6624        let mut first = run_state(RunStatus::Blocked);
6625        first.id = "20260101-000000-supb".to_owned();
6626        first.save().unwrap();
6627        let mut second = run_state(RunStatus::Failed);
6628        second.id = "20260101-000000-supc".to_owned();
6629        second.save().unwrap();
6630
6631        let mut t = task();
6632        t.runs = vec![first.id.clone(), second.id.clone()];
6633        t.status = TaskStatus::Done;
6634
6635        supersede_prior_runs(&t, &crate::run::home());
6636
6637        assert_eq!(
6638            RunState::load(&first.id).unwrap().status,
6639            RunStatus::Blocked,
6640            "the task's last attempt never landed, so there is nothing here \
6641             actually superseding it"
6642        );
6643    }
6644
6645    #[test]
6646    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
6647        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
6648        // to look" - `Failed` and `VerifiedNoop` are already their own
6649        // terminal answers and must not be relabelled into a third one.
6650        crate::run::pin_test_home();
6651        let mut failed = run_state(RunStatus::Failed);
6652        failed.id = "20260101-000000-sup6".to_owned();
6653        failed.save().unwrap();
6654        let mut noop = run_state(RunStatus::VerifiedNoop);
6655        noop.id = "20260101-000000-sup7".to_owned();
6656        noop.save().unwrap();
6657        let mut winner = run_state(RunStatus::Ready);
6658        winner.id = "20260101-000000-sup8".to_owned();
6659        winner.save().unwrap();
6660
6661        let mut t = task();
6662        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
6663        t.status = TaskStatus::Done;
6664
6665        supersede_prior_runs(&t, &crate::run::home());
6666
6667        assert_eq!(
6668            RunState::load(&failed.id).unwrap().status,
6669            RunStatus::Failed
6670        );
6671        assert_eq!(
6672            RunState::load(&noop.id).unwrap().status,
6673            RunStatus::VerifiedNoop
6674        );
6675    }
6676
6677    fn approval_question(run: &str) -> ask::Question {
6678        ask::Question::new(
6679            run.to_owned(),
6680            land::APPROVAL_NODE.to_owned(),
6681            "land".to_owned(),
6682            "merge?".to_owned(),
6683            String::new(),
6684            vec!["merge".to_owned(), "hold".to_owned()],
6685        )
6686    }
6687
6688    #[test]
6689    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
6690        crate::run::pin_test_home();
6691        let mut state = run_state(RunStatus::Landing);
6692        state.id = "20260101-000000-fre1".to_owned();
6693        state.parked = true;
6694        state.save().unwrap();
6695        ask::Questions::open()
6696            .put(&mut approval_question(&state.id))
6697            .unwrap();
6698
6699        let mut t = task();
6700        t.runs.push(state.id.clone());
6701        assert_eq!(
6702            land_resume_state(&t),
6703            LandResume::StillWaiting,
6704            "nobody has answered and the timeout has not passed"
6705        );
6706    }
6707
6708    #[test]
6709    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
6710        crate::run::pin_test_home();
6711        let mut state = run_state(RunStatus::Gating);
6712        state.id = "20260101-000000-gt01".to_owned();
6713        state.parked = true;
6714        state.config.graph.answer_timeout = 60;
6715        state.github_text = Some(crate::run::GithubTextAsk {
6716            rewrite: None,
6717            fingerprint: "f".into(),
6718            title: true,
6719            body: false,
6720            categories: vec!["title-language".into()],
6721            question: None,
6722            asks: 1,
6723            resolved: false,
6724            chosen_title: None,
6725            choice: None,
6726        });
6727        state.save().unwrap();
6728        let store = ask::Questions::open();
6729        let mut q = ask::Question::new(
6730            state.id.clone(),
6731            crate::github_text::ASK_NODE.to_owned(),
6732            crate::github_text::ASK_SEAT.to_owned(),
6733            "s".into(),
6734            String::new(),
6735            vec!["use fallback".into()],
6736        );
6737        store.put(&mut q).unwrap();
6738        let mut t = task();
6739        t.runs.push(state.id.clone());
6740        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
6741        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6742        store.put(&mut q).unwrap();
6743        assert_eq!(land_resume_state(&t), LandResume::Ready);
6744        assert!(!store.get(&q.id).unwrap().status.open());
6745        // Once decided, a parked run is an ordinary candidate again.
6746        state.github_text.as_mut().unwrap().resolved = true;
6747        state.save().unwrap();
6748        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
6749    }
6750
6751    #[test]
6752    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
6753        // `ask::ask_and_wait`'s own deadline used to retire a question
6754        // nobody answered; land's approval bypasses that wait (see
6755        // `land::approval_gate`), so this is now the only place
6756        // `graph.answer_timeout` is enforced for a land approval at all.
6757        crate::run::pin_test_home();
6758        let mut state = run_state(RunStatus::Landing);
6759        state.id = "20260101-000000-exp1".to_owned();
6760        state.parked = true;
6761        state.config.graph.answer_timeout = 60;
6762        state.save().unwrap();
6763
6764        let store = ask::Questions::open();
6765        let mut q = approval_question(&state.id);
6766        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6767        store.put(&mut q).unwrap();
6768
6769        let mut t = task();
6770        t.runs.push(state.id.clone());
6771        assert_eq!(
6772            land_resume_state(&t),
6773            LandResume::Ready,
6774            "an expired question must not be waited on forever"
6775        );
6776
6777        let after = store.get(&q.id).unwrap();
6778        assert!(
6779            !after.status.open(),
6780            "the question is abandoned, not silently ignored"
6781        );
6782        assert!(
6783            after.resolution().is_none(),
6784            "an abandoned question is not read as a decision"
6785        );
6786    }
6787
6788    #[test]
6789    fn reclaim_settles_a_running_task_against_its_last_run() {
6790        let mut t = task();
6791        t.start("20260904-000000-4043".to_owned());
6792        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
6793        assert_eq!(
6794            t.status,
6795            TaskStatus::Done,
6796            "a run that actually finished must not stay `running` forever"
6797        );
6798    }
6799
6800    #[test]
6801    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
6802        let mut t = task();
6803        t.start("20260904-000000-4043".to_owned());
6804        t.last_error = Some("earlier trouble".to_owned());
6805        let mut state = run_state(RunStatus::Judging);
6806        state.parked = true;
6807        reclaim(&mut t, Some(state), 1, "en");
6808        assert_eq!(t.status, TaskStatus::Parked);
6809        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
6810        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6811        assert!(t.park_reason.is_some());
6812        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
6813        assert!(!t.fresh_start);
6814        assert!(t.status.runnable());
6815    }
6816
6817    #[test]
6818    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
6819        let mut t = task();
6820        t.start("20260904-000000-4043".to_owned());
6821        t.last_error = Some("earlier trouble".to_owned());
6822        settle(
6823            &mut t,
6824            Verdict {
6825                status: RunStatus::Judging,
6826                left_pr: false,
6827                quota_hit: false,
6828                parked: true,
6829                no_viable_candidates: false,
6830            },
6831            "parked after `judging`",
6832            1,
6833        );
6834        assert_eq!(t.status, TaskStatus::Parked);
6835        assert_eq!(t.attempts, 0);
6836        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
6837        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
6838        assert_eq!(t.schema, crate::queue::SCHEMA);
6839        assert!(
6840            crate::notices::task_held(&t).is_none(),
6841            "a park is not news"
6842        );
6843        t.start("20260904-000000-4043".to_owned());
6844        assert_eq!(t.park_reason, None);
6845    }
6846
6847    #[test]
6848    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
6849        // A blocked run with attempts left goes back to `Failed`, exactly as
6850        // it would from `attempt` itself - `reclaim` must not invent a second
6851        // policy for a task a daemon merely stopped without reporting.
6852        let mut t = task();
6853        t.start("20260904-000000-4043".to_owned());
6854        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
6855        assert_eq!(t.status, TaskStatus::Failed);
6856        assert!(t.status.runnable());
6857    }
6858
6859    #[test]
6860    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
6861        let mut t = task();
6862        t.start("20260904-000000-4043".to_owned());
6863        assert_eq!(t.attempts, 1);
6864        let mut run = run_state(RunStatus::Implementing);
6865        run.id = "20260904-000000-4043".to_owned();
6866        run.begin_pass();
6867        let cause = crate::run::ParkCause::Upgrade {
6868            from: "0.121.0".to_owned(),
6869            to: Some("0.121.1".to_owned()),
6870        };
6871        run.end_pass_parked(cause.clone());
6872        run.parked = true;
6873        let verdict = Verdict {
6874            status: run.status,
6875            left_pr: false,
6876            quota_hit: false,
6877            parked: true,
6878            no_viable_candidates: false,
6879        };
6880        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
6881        assert_eq!(t.attempts, 0);
6882        assert_eq!(t.passes.len(), 1);
6883        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6884        assert_eq!(t.passes[0].parked, Some(cause));
6885        assert_eq!(t.passes[0].pass_index, 0);
6886
6887        // A resumed pass that then fails spends its attempt, and the earlier
6888        // pass's entry is untouched.
6889        t.start("20260904-000000-4043".to_owned());
6890        run.begin_pass();
6891        run.status = RunStatus::Failed;
6892        let verdict = Verdict {
6893            status: RunStatus::Failed,
6894            left_pr: false,
6895            quota_hit: false,
6896            parked: false,
6897            no_viable_candidates: false,
6898        };
6899        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
6900        assert_eq!(t.passes.len(), 2);
6901        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6902        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
6903        assert_eq!(t.passes[1].pass_index, 1);
6904        assert_eq!(t.attempts, 1);
6905    }
6906
6907    #[test]
6908    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
6909        let mut t = task();
6910        t.start("20260904-000000-4043".to_owned());
6911        reclaim(&mut t, None, 2, "en");
6912        assert_eq!(t.status, TaskStatus::Held);
6913        assert!(
6914            t.last_error
6915                .as_deref()
6916                .is_some_and(|e| e.contains("running")),
6917            "the operator needs to know why this task was held"
6918        );
6919    }
6920
6921    #[test]
6922    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
6923        let dir = tempfile::tempdir().unwrap();
6924        let queue = Queue::at(dir.path().to_path_buf());
6925
6926        // No run recorded, so this never has to touch `RunState::load`.
6927        let mut orphaned = task();
6928        orphaned.id = "20260904-000000-orph".to_owned();
6929        orphaned.status = TaskStatus::Running;
6930        orphaned.attempts = 1;
6931        queue.put(&mut orphaned).unwrap();
6932
6933        let mut alive = task();
6934        alive.id = "20260904-000000-live".to_owned();
6935        alive.status = TaskStatus::Running;
6936        alive.attempts = 1;
6937        queue.put(&mut alive).unwrap();
6938        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
6939
6940        let mut queued = task();
6941        queued.id = "20260904-000000-wait".to_owned();
6942        queue.put(&mut queued).unwrap();
6943
6944        let reclaimed = reclaim_orphaned_running(&queue, 2);
6945        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
6946
6947        assert_eq!(
6948            queue.get(&orphaned.id).unwrap().status,
6949            TaskStatus::Held,
6950            "nothing was driving it and there was no run to recover"
6951        );
6952        assert_eq!(
6953            queue.get(&alive.id).unwrap().status,
6954            TaskStatus::Running,
6955            "a live claim must protect the task it belongs to"
6956        );
6957        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
6958    }
6959
6960    /// Read a run.json back from an explicit `home`, the same way
6961    /// `reclaim_abandoned_runs` itself does - never through the
6962    /// process-global `RunState::load`, which this test's own `home` (an
6963    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
6964    /// use at all.
6965    fn read_run_under(home: &Path, id: &str) -> RunState {
6966        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
6967        serde_json::from_str(&body).unwrap()
6968    }
6969
6970    #[test]
6971    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
6972        let dir = tempfile::tempdir().unwrap();
6973        let home = dir.path().to_path_buf();
6974        let now = Timestamp::now();
6975        let overrun_seat = || crate::run::ActiveSeat {
6976            node: "implement".to_owned(),
6977            started_at: now - jiff::SignedDuration::new(21_000, 0),
6978            timeout_secs: 3_600,
6979            attempt: 0,
6980            task: None,
6981            command: None,
6982            index: None,
6983            total: None,
6984        };
6985
6986        let mut dead = run_state(RunStatus::Implementing);
6987        dead.id = "20260101-000000-dead".to_owned();
6988        dead.active.insert("impl-A".to_owned(), overrun_seat());
6989        // A `driver_pid` the injected query below confirms gone outright —
6990        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
6991        dead.driver_pid = Some(4242);
6992        dead.save_under(&home).unwrap();
6993
6994        // Same shape, but a live daemon's heartbeat names it: must be left
6995        // exactly alone, however far past its own timeout the seat sits.
6996        let mut alive = run_state(RunStatus::Implementing);
6997        alive.id = "20260101-000000-aliv".to_owned();
6998        alive.active.insert("impl-A".to_owned(), overrun_seat());
6999        alive.save_under(&home).unwrap();
7000        let mut status = Status::new();
7001        status.current = vec![Current {
7002            task: "20260101-000000-task".to_owned(),
7003            run: alive.id.clone(),
7004        }];
7005        write_status_to(&home.join("daemon.json"), &status).unwrap();
7006
7007        // The abandoned seat left an open question behind: nobody is left to
7008        // read an answer once the run is failed, and this must not wait for
7009        // some later daemon startup's own sweep to notice that.
7010        let questions = Questions::at(home.join("questions"));
7011        let mut q = ask::Question::new(
7012            dead.id.clone(),
7013            "implement".to_owned(),
7014            "impl-A".to_owned(),
7015            "Which storage backend?".to_owned(),
7016            String::new(),
7017            vec!["SQLite".to_owned(), "Redis".to_owned()],
7018        );
7019        questions.put(&mut q).unwrap();
7020
7021        let abandoned = reclaim_abandoned_runs_with(
7022            &home,
7023            now,
7024            |pid| if pid == 4242 { Some(false) } else { None },
7025            |_| panic!("a query answering Dead outright needs no identity corroboration"),
7026        );
7027        assert_eq!(abandoned, vec![dead.id.clone()]);
7028
7029        let reloaded = read_run_under(&home, &dead.id);
7030        assert_eq!(reloaded.status, RunStatus::Failed);
7031        assert!(reloaded.active.is_empty());
7032        assert!(
7033            !questions.get(&q.id).unwrap().status.open(),
7034            "the failed run's own open question must be settled in the same pass"
7035        );
7036
7037        let still_alive = read_run_under(&home, &alive.id);
7038        assert_eq!(
7039            still_alive.status,
7040            RunStatus::Implementing,
7041            "a live daemon's claim protects it"
7042        );
7043        assert!(!still_alive.active.is_empty());
7044    }
7045
7046    /// The exact shape a review round flagged as broken: `magi serve` running
7047    /// in this same `home` scans *every* run on disk, including a manual
7048    /// `magi review` / `magi run` this daemon never started and that
7049    /// therefore claims no heartbeat of its own. Before this scan asked
7050    /// `liveness` rather than just `is_working_on`, a manual run whose active
7051    /// seat merely ran a little past its own timeout — the CLI finishing up,
7052    /// its result still being collected — got wiped and failed by a daemon
7053    /// that had nothing to do with it, out from under a process that was
7054    /// still very much running.
7055    #[test]
7056    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
7057        let dir = tempfile::tempdir().unwrap();
7058        let home = dir.path().to_path_buf();
7059        let now = Timestamp::now();
7060
7061        let mut manual = run_state(RunStatus::Reviewing);
7062        manual.id = "20260101-000000-manl".to_owned();
7063        manual.active.insert(
7064            "review-1".to_owned(),
7065            crate::run::ActiveSeat {
7066                node: "review".to_owned(),
7067                started_at: now - jiff::SignedDuration::new(21_000, 0),
7068                timeout_secs: 3_600,
7069                attempt: 0,
7070                task: None,
7071                command: None,
7072                index: None,
7073                total: None,
7074            },
7075        );
7076        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
7077        // but a real, still-running process: `liveness` must corroborate this
7078        // as `Live`, not read the missing daemon claim as death.
7079        manual.driver_pid = Some(4242);
7080        manual.driver_started_at = Some("1790000000".to_owned());
7081        manual.save_under(&home).unwrap();
7082
7083        let abandoned = reclaim_abandoned_runs_with(
7084            &home,
7085            now,
7086            |pid| if pid == 4242 { Some(true) } else { None },
7087            |pid| {
7088                if pid == 4242 {
7089                    Some("1790000000".to_owned())
7090                } else {
7091                    None
7092                }
7093            },
7094        );
7095        assert!(
7096            abandoned.is_empty(),
7097            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
7098        );
7099
7100        let reloaded = read_run_under(&home, &manual.id);
7101        assert_eq!(reloaded.status, RunStatus::Reviewing);
7102        assert!(!reloaded.active.is_empty());
7103    }
7104
7105    #[test]
7106    fn an_already_claimed_task_is_skipped_rather_than_failed() {
7107        let dir = tempfile::tempdir().unwrap();
7108        let queue = Queue::at(dir.path().to_path_buf());
7109        let mut only = task();
7110        queue.put(&mut only).unwrap();
7111
7112        let _elsewhere = queue.claim(&only.id).unwrap();
7113        let candidates = runnable(&queue);
7114        assert_eq!(candidates.len(), 1, "the task is still runnable");
7115        assert!(
7116            queue.claim(&candidates[0].id).is_err(),
7117            "the loop cannot take a claim somebody else holds"
7118        );
7119
7120        let after = queue.get(&only.id).unwrap();
7121        assert_eq!(after.status, TaskStatus::Queued);
7122        assert_eq!(
7123            after.attempts, 0,
7124            "losing the race is not an attempt at the task"
7125        );
7126        assert_eq!(after.last_error, None);
7127    }
7128
7129    #[test]
7130    fn the_status_file_round_trips_and_its_heartbeat_advances() {
7131        let dir = tempfile::tempdir().unwrap();
7132        let path = dir.path().join("daemon.json");
7133
7134        let mut status = Status::new();
7135        status.idle = false;
7136        status.completed = 7;
7137        status.current = vec![Current {
7138            task: "20260902-000000-t111".to_owned(),
7139            run: "20260902-000001-r111".to_owned(),
7140        }];
7141        write_status_to(&path, &status).unwrap();
7142        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7143        assert_eq!(first.schema, SCHEMA);
7144        assert_eq!(first.pid, std::process::id());
7145        assert!(!first.idle);
7146        assert_eq!(first.completed, 7);
7147        assert_eq!(first.current, status.current);
7148        assert!(
7149            !path.with_extension("json.tmp").exists(),
7150            "the temp file is renamed, not left behind"
7151        );
7152
7153        std::thread::sleep(Duration::from_millis(5));
7154        status.updated_at = Timestamp::now();
7155        status.polls = 3;
7156        write_status_to(&path, &status).unwrap();
7157        let second: Status =
7158            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7159        assert!(
7160            second.updated_at > first.updated_at,
7161            "a reader can only detect staleness if the heartbeat moves"
7162        );
7163        assert_eq!(
7164            second.started_at, first.started_at,
7165            "the start time is not a heartbeat"
7166        );
7167        assert_eq!(second.polls, 3);
7168    }
7169
7170    #[test]
7171    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
7172        let dir = tempfile::tempdir().unwrap();
7173
7174        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
7175
7176        let mut status = Status::new();
7177        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
7178        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7179        let stale = read_status(dir.path()).unwrap();
7180        assert!(
7181            !stale.running(Timestamp::now()),
7182            "a minute without a heartbeat is a dead daemon, not a busy one"
7183        );
7184        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
7185
7186        status.updated_at = Timestamp::now();
7187        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7188        let fresh = read_status(dir.path()).unwrap();
7189        assert!(fresh.running(Timestamp::now()));
7190    }
7191
7192    #[test]
7193    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
7194        let dir = tempfile::tempdir().unwrap();
7195        let now = Timestamp::now();
7196        let mine = "20260903-080619-01c2";
7197
7198        assert!(
7199            !is_working_on(dir.path(), mine, now),
7200            "no status file means nobody is working on anything"
7201        );
7202
7203        let mut status = Status::new();
7204        status.current = vec![Current {
7205            task: "20260903-080340-0167".to_owned(),
7206            run: mine.to_owned(),
7207        }];
7208        status.updated_at = now;
7209        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7210        assert!(is_working_on(dir.path(), mine, now));
7211        assert!(
7212            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
7213            "a daemon busy with one run is not working on another"
7214        );
7215
7216        // A killed daemon stops writing heartbeats but leaves the file behind
7217        // naming the run it died in. That run must not be undeletable forever.
7218        status.updated_at = now - jiff::SignedDuration::from_secs(600);
7219        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7220        assert!(
7221            !is_working_on(dir.path(), mine, now),
7222            "a stale heartbeat is a dead daemon, so its run is a leftover"
7223        );
7224    }
7225
7226    #[test]
7227    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
7228        let dir = tempfile::tempdir().unwrap();
7229        let now = Timestamp::now();
7230
7231        assert!(
7232            !is_working_on_short(dir.path(), "01c2", now),
7233            "no status file means nobody is working on anything"
7234        );
7235
7236        let mut status = Status::new();
7237        status.current = vec![Current {
7238            task: "20260903-080340-0167".to_owned(),
7239            run: "20260903-080619-01c2".to_owned(),
7240        }];
7241        status.updated_at = now;
7242        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7243        assert!(
7244            is_working_on_short(dir.path(), "01c2", now),
7245            "the run's short id is the last block of its full id"
7246        );
7247        assert!(
7248            !is_working_on_short(dir.path(), "3cbf", now),
7249            "a daemon busy with one worktree bay is not working on another"
7250        );
7251    }
7252
7253    #[test]
7254    fn a_newer_status_file_still_yields_a_reading() {
7255        let dir = tempfile::tempdir().unwrap();
7256        // A field this build has never heard of must not turn the reading into
7257        // nothing at all; that is the whole reason the reader is permissive.
7258        std::fs::write(
7259            dir.path().join("daemon.json"),
7260            serde_json::json!({
7261                "schema": 2,
7262                "updated_at": Timestamp::now().to_string(),
7263                "idle": true,
7264                "surprise": { "nested": [1, 2, 3] },
7265            })
7266            .to_string(),
7267        )
7268        .unwrap();
7269
7270        let reading = read_status(dir.path()).expect("a forward-compatible read");
7271        assert!(reading.running(Timestamp::now()));
7272        assert!(reading.idle);
7273        assert!(reading.current.is_empty());
7274    }
7275
7276    #[test]
7277    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
7278        // A daemon started before `current` became a list keeps writing this
7279        // shape on every heartbeat until it is restarted. A rolling upgrade
7280        // - a newer `magi web` or `magi doctor` reading an older `magi
7281        // serve`'s heartbeat - must still see the run it is on, not "no
7282        // daemon" from a type mismatch failing the whole struct.
7283        let dir = tempfile::tempdir().unwrap();
7284        std::fs::write(
7285            dir.path().join("daemon.json"),
7286            serde_json::json!({
7287                "schema": 1,
7288                "pid": 4242,
7289                "updated_at": Timestamp::now().to_string(),
7290                "idle": false,
7291                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
7292                "completed": 3,
7293                "polls": 9,
7294            })
7295            .to_string(),
7296        )
7297        .unwrap();
7298
7299        let reading = read_status(dir.path()).expect("an older shape must still parse");
7300        assert!(reading.running(Timestamp::now()));
7301        assert_eq!(
7302            reading.current,
7303            vec![Current {
7304                task: "20260902-140501-aaaa".to_owned(),
7305                run: "20260902-140502-bbbb".to_owned(),
7306            }]
7307        );
7308    }
7309
7310    #[test]
7311    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
7312        let dir = tempfile::tempdir().unwrap();
7313        std::fs::write(
7314            dir.path().join("daemon.json"),
7315            serde_json::json!({
7316                "schema": 1,
7317                "updated_at": Timestamp::now().to_string(),
7318                "idle": true,
7319                "current": null,
7320            })
7321            .to_string(),
7322        )
7323        .unwrap();
7324        let with_null = read_status(dir.path()).expect("null must still parse");
7325        assert!(with_null.current.is_empty());
7326
7327        std::fs::write(
7328            dir.path().join("daemon.json"),
7329            serde_json::json!({
7330                "schema": 1,
7331                "updated_at": Timestamp::now().to_string(),
7332                "idle": true,
7333            })
7334            .to_string(),
7335        )
7336        .unwrap();
7337        let absent = read_status(dir.path()).expect("a missing field must still parse");
7338        assert!(absent.current.is_empty());
7339    }
7340
7341    #[test]
7342    fn a_task_without_a_repository_runs_in_the_daemons_default() {
7343        let fallback = Path::new("/default");
7344        let mut blank = task();
7345        blank.repo = PathBuf::new();
7346        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
7347        let mut dot = task();
7348        dot.repo = PathBuf::from(".");
7349        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
7350        assert_eq!(
7351            repo_for(&task(), fallback),
7352            PathBuf::from("/repo"),
7353            "a task that names a repository keeps it"
7354        );
7355    }
7356
7357    #[test]
7358    fn task_implementers_edit_inherits_daemon_config_and_merge() {
7359        let dir = tempfile::tempdir().unwrap();
7360        let path = dir.path().join("explicit.toml");
7361        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
7362        let opts = Opts {
7363            config: Some(path),
7364            merge: Some("none".into()),
7365            ..Default::default()
7366        };
7367        let mut t = task();
7368        t.set_implementers(
7369            2,
7370            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7371                .unwrap(),
7372        )
7373        .unwrap();
7374        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
7375        assert_eq!(cfg.graph.implementers, 2);
7376        assert_eq!(cfg.graph.judges, 1);
7377        assert_eq!(cfg.merge.mode, MergeMode::None);
7378        t.set_implementers(1, &cfg).unwrap();
7379        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
7380        apply_task_implementers(&mut cfg, &t);
7381        assert_eq!(cfg.graph.implementers, 1);
7382        assert_eq!(cfg.graph.judges, 1);
7383        assert_eq!(cfg.merge.mode, MergeMode::None);
7384    }
7385
7386    #[test]
7387    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
7388        let dir = tempfile::tempdir().unwrap();
7389        let repo = dir.path().join("repo");
7390        std::fs::create_dir(&repo).unwrap();
7391        std::fs::write(
7392            repo.join("magi.toml"),
7393            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
7394        )
7395        .unwrap();
7396        let daemon_config = dir.path().join("daemon.toml");
7397        std::fs::write(
7398            &daemon_config,
7399            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
7400        )
7401        .unwrap();
7402        let opts = Opts {
7403            config: Some(daemon_config),
7404            merge: Some("pr".into()),
7405            ..Default::default()
7406        };
7407        let q = Queue::at(dir.path().join("queue"));
7408        let validation: Config =
7409            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7410                .unwrap();
7411        // No provenance field on legacy direct tasks: both shapes stay isolated.
7412        for record in ["{}", r#"{"candidates":2}"#] {
7413            let overrides = serde_json::from_str(record).unwrap();
7414            let filing = crate::direct::Filing {
7415                instruction: "work".into(),
7416                title: "direct".into(),
7417                repo: repo.clone(),
7418                source: crate::queue::Source::Human,
7419                solo: false,
7420                overrides,
7421                review_of: None,
7422            };
7423            let filed =
7424                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
7425            let crate::direct::Filed::Standalone {
7426                mut task,
7427                claim: _claim,
7428            } = filed
7429            else {
7430                panic!("local filing")
7431            };
7432            let before = prepare_for(&repo, &opts, &task).unwrap();
7433            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
7434            assert_eq!(
7435                before.merge.mode,
7436                MergeMode::None,
7437                "daemon --merge must not leak"
7438            );
7439            for n in [2, 1, 2] {
7440                task.set_implementers(n, &validation).unwrap();
7441                q.put(&mut task).unwrap();
7442                task = q.get(&task.id).unwrap();
7443                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
7444                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
7445                apply_task_implementers(&mut cfg, &task);
7446                assert_eq!(cfg.graph.implementers, usize::from(n));
7447                assert_eq!(cfg.graph.judges, 2);
7448                assert_eq!(cfg.merge.mode, MergeMode::None);
7449            }
7450        }
7451    }
7452
7453    #[test]
7454    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
7455        let cfg: Config =
7456            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7457                .unwrap();
7458        let mut t = task();
7459        t.review_of = Some("review-target".into());
7460        t.hold_manual(Some("retry".into()));
7461        let mut previous = RunState::new(
7462            PathBuf::from("/repo"),
7463            "main".into(),
7464            "abc1234".into(),
7465            "review".into(),
7466            cfg.clone(),
7467        );
7468        previous.config.graph.implementers = 2;
7469        for count in [1, 3] {
7470            t.set_implementers(count, &cfg).unwrap();
7471            t.release();
7472            assert_eq!(t.review_of.as_deref(), Some("review-target"));
7473            for proposed in [
7474                Starter::Resume(previous.id.clone()),
7475                Starter::Review("recovery-target".into()),
7476            ] {
7477                assert_eq!(
7478                    starter_with_implementers(&t, Some(&previous), proposed),
7479                    Starter::Review("review-target".into())
7480                );
7481            }
7482            let mut configured = cfg.clone();
7483            apply_task_implementers(&mut configured, &t);
7484            assert_eq!(configured.graph.implementers, usize::from(count));
7485            assert_eq!(previous.config.graph.implementers, 2);
7486        }
7487    }
7488
7489    #[test]
7490    fn task_implementers_dispatch_and_resume_agree() {
7491        let mut t = task();
7492        let cfg: crate::config::Config =
7493            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7494                .unwrap();
7495        let mut run = RunState::new(
7496            PathBuf::from("/repo"),
7497            "main".into(),
7498            "abc1234".into(),
7499            "work".into(),
7500            cfg.clone(),
7501        );
7502        run.config.graph.implementers = 2;
7503        for n in [2, 1, 3, 2] {
7504            t.set_implementers(n, &cfg).unwrap();
7505            let mut dispatched = cfg.clone();
7506            apply_task_implementers(&mut dispatched, &t);
7507            assert_eq!(dispatched.graph.implementers, usize::from(n));
7508            assert_eq!(implementers_match(&t, &run), n == 2);
7509            for proposed in [
7510                Starter::Resume(run.id.clone()),
7511                Starter::Review("old-branch".into()),
7512            ] {
7513                let expected = if n == 2 {
7514                    proposed.clone()
7515                } else {
7516                    Starter::Start
7517                };
7518                assert_eq!(
7519                    starter_with_implementers(&t, Some(&run), proposed),
7520                    expected
7521                );
7522            }
7523            assert_eq!(
7524                run.config.graph.implementers, 2,
7525                "history must not be rewritten"
7526            );
7527        }
7528        t.solo = false;
7529        t.overrides = None;
7530        assert!(implementers_match(&t, &run));
7531    }
7532
7533    #[test]
7534    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
7535        // Three seats said out loud. What `solo` promises is one candidate
7536        // *whatever the config asks for*, so the contrast has to be a number
7537        // this test owns - it used to be `Config::default()`'s, which became
7538        // 1 when one implementation became the default and left the two
7539        // halves of this test asserting the same thing.
7540        let mut solo_cfg = Config::default();
7541        solo_cfg.graph.implementers = 3;
7542        let mut solo_task = task();
7543        solo_task.solo = true;
7544        apply_task_implementers(&mut solo_cfg, &solo_task);
7545        assert_eq!(solo_cfg.graph.implementers, 1);
7546
7547        let mut plain_cfg = Config::default();
7548        plain_cfg.graph.implementers = 3;
7549        let plain_task = task();
7550        assert!(!plain_task.solo);
7551        apply_task_implementers(&mut plain_cfg, &plain_task);
7552        assert_eq!(
7553            plain_cfg.graph.implementers, 3,
7554            "a task that did not ask to run alone keeps the config's candidates"
7555        );
7556    }
7557
7558    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
7559        QuotaLoss {
7560            seat: seat.into(),
7561            node: "judge".into(),
7562            at: at.parse().unwrap(),
7563            reset: reset.map(str::to_string),
7564        }
7565    }
7566
7567    #[test]
7568    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
7569        let old: Vec<QuotaLoss> = (1..=4)
7570            .map(|i| {
7571                loss(
7572                    &format!("judge-{i}"),
7573                    "2026-09-23T05:23:00Z",
7574                    Some("2:40pm (Asia/Tokyo)"),
7575                )
7576            })
7577            .collect();
7578        let fresh = losses_this_attempt(&old, &old);
7579        assert!(fresh.is_empty());
7580        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
7581        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
7582    }
7583
7584    #[test]
7585    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
7586        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
7587        let now = Timestamp::now();
7588        let mut after = old.clone();
7589        after.push(loss("judge-2", &now.to_string(), None));
7590        let fresh = losses_this_attempt(&old, &after);
7591        assert_eq!(fresh, vec![after[1].clone()]);
7592        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
7593        assert_eq!(
7594            until,
7595            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
7596        );
7597    }
7598
7599    #[test]
7600    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
7601        // `recover_stall` removes judge-1's loss and the retry then hits quota
7602        // again: the vector is the same length, so an index diff sees nothing.
7603        let before = vec![
7604            loss("judge-1", "2026-09-23T05:23:00Z", None),
7605            loss("judge-2", "2026-09-23T05:24:00Z", None),
7606        ];
7607        let after = vec![
7608            loss("judge-2", "2026-09-23T05:24:00Z", None),
7609            loss("judge-1", "2026-09-24T01:00:00Z", None),
7610        ];
7611        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
7612    }
7613
7614    #[test]
7615    fn merge_overrides_are_parsed_or_refused() {
7616        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
7617        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
7618        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
7619        assert!(merge_mode("squash").is_err());
7620    }
7621
7622    #[test]
7623    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
7624        let now = Timestamp::now();
7625        let fallback = Duration::from_secs(300);
7626        let cap = Duration::from_secs(1800);
7627
7628        // No reset hint at all: the fallback.
7629        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
7630
7631        // A reset ten minutes out, well inside the cap: waited for exactly.
7632        let soon = now + jiff::SignedDuration::from_secs(600);
7633        assert_eq!(
7634            quota_wait(Some(soon), now, fallback, cap),
7635            Duration::from_secs(600)
7636        );
7637
7638        // A reset already in the past is not trusted: the fallback, not a
7639        // zero or negative wait that would spin the loop right back around.
7640        let past = now - jiff::SignedDuration::from_secs(60);
7641        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
7642
7643        // A reset further out than the cap is trusted for direction but not
7644        // for magnitude: a parsing slip must not sleep the loop for a day.
7645        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
7646        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
7647    }
7648
7649    #[test]
7650    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
7651        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7652
7653        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
7654        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
7655
7656        // Same clock reading, but it has already gone by today: read as
7657        // tomorrow's, since the CLI would not still be reporting a limit past
7658        // its own stated reset.
7659        let already_past =
7660            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
7661        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
7662
7663        assert!(
7664            parse_reset_hint("session limit reached", now, now).is_none(),
7665            "free text with no recognised shape is not guessed at"
7666        );
7667        assert!(
7668            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
7669            "an unresolvable zone name is not guessed at either"
7670        );
7671    }
7672
7673    #[test]
7674    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
7675        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7676
7677        let at = parse_reset_hint(
7678            "You've hit your usage limit. Visit \
7679             https://chatgpt.com/codex/settings/usage to purchase more \
7680             credits or try again at Sep 19th, 2026 5:10 PM.",
7681            now,
7682            now,
7683        )
7684        .expect("the codex reset wording is a recognised shape");
7685        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
7686
7687        // The month is explicit, so a date already earlier in the same
7688        // sentence-implied year than `now` is trusted as written rather than
7689        // rolled forward a year the way the bracketed shape rolls a
7690        // same-day clock reading to tomorrow.
7691        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
7692            .expect("an explicit year needs no rollover");
7693        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
7694
7695        assert!(
7696            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
7697            "a two-digit year is not the documented shape and is not guessed at"
7698        );
7699        assert!(
7700            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
7701            "a four-letter month name is not the documented three-letter abbreviation"
7702        );
7703        assert!(
7704            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
7705            "an explicit zone on the dated shape is a format nobody has \
7706             documented, and is refused rather than guessed at as UTC"
7707        );
7708    }
7709
7710    #[test]
7711    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
7712        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
7713        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
7714
7715        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
7716        assert_eq!(at.as_second() - recorded.as_second(), 3769);
7717
7718        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
7719        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
7720
7721        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
7722            assert!(
7723                parse_reset_hint(bad, now, recorded).is_none(),
7724                "{bad:?} must not be guessed at"
7725            );
7726        }
7727    }
7728
7729    /// A loop whose queue lives in a temp tree and whose poll interval is far
7730    /// longer than the test's patience, so anything that waits out a poll
7731    /// instead of noticing the stop fails rather than merely being slow.
7732    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
7733        let config = dir.join("magi.toml");
7734        std::fs::write(
7735            &config,
7736            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
7737        )
7738        .unwrap();
7739        let opts = Opts {
7740            poll: Duration::from_secs(30),
7741            config: Some(config),
7742            // The explicit fixture config keeps startup cleanup from reading
7743            // machine configuration. This fictional repository likewise
7744            // keeps any best-effort git cleanup away from this checkout.
7745            repo: dir.join("repo"),
7746            ..Opts::default()
7747        };
7748        // The status file goes in a directory that does not exist yet, so its
7749        // creation is itself evidence the loop published one. `worktrees`
7750        // must be just as fictional: the janitor reclaims worktrees under it
7751        // for real, and a test that let it fall through to
7752        // `crate::run::default_worktree_root()` would have it reclaim
7753        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
7754        // which is exactly what happened before this function took the
7755        // parameter at all.
7756        let home = dir.join("home");
7757        let worktrees = dir.join("wt");
7758        (
7759            opts,
7760            Queue::at(dir.join("queue")),
7761            home.join("daemon.json"),
7762            home,
7763            worktrees,
7764        )
7765    }
7766
7767    #[test]
7768    fn a_stop_is_idempotent_and_once_set_stays_set() {
7769        let stop = Stop::new();
7770        assert!(!stop.stopped());
7771
7772        stop.stop();
7773        assert!(stop.stopped());
7774        stop.stop();
7775        assert!(stop.stopped(), "a second stop is not a toggle");
7776
7777        let shared = stop.clone();
7778        assert!(
7779            shared.stopped(),
7780            "a clone is the same stop; that is how the loop and its caller share one"
7781        );
7782    }
7783
7784    #[test]
7785    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
7786        let stop = Stop::new();
7787        stop.enter();
7788        assert!(
7789            !stop.finishing(),
7790            "a busy loop nobody has asked to stop is just running"
7791        );
7792
7793        stop.stop();
7794        assert!(
7795            stop.finishing(),
7796            "a stop asked for mid-run has not landed until the run is settled"
7797        );
7798
7799        stop.exit();
7800        assert!(
7801            !stop.finishing(),
7802            "once the run is settled the stop has landed and there is nothing to finish"
7803        );
7804    }
7805
7806    #[test]
7807    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
7808        let stop = Stop::new();
7809        stop.enter();
7810        stop.enter();
7811        stop.stop();
7812        assert!(stop.finishing(), "two runs still in flight");
7813
7814        stop.exit();
7815        assert!(
7816            stop.finishing(),
7817            "one run finished, but a sibling is still working"
7818        );
7819
7820        stop.exit();
7821        assert!(
7822            !stop.finishing(),
7823            "the last run out is what actually lands the stop"
7824        );
7825    }
7826
7827    #[tokio::test]
7828    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
7829        let dir = tempfile::tempdir().unwrap();
7830        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7831        let stop = Stop::new();
7832        stop.stop();
7833
7834        let began = std::time::Instant::now();
7835        tokio::time::timeout(
7836            Duration::from_secs(2),
7837            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7838        )
7839        .await
7840        .expect("a stopped loop must return, not sit out its poll interval")
7841        .expect("the loop's own setup and teardown must not fail");
7842        assert!(
7843            began.elapsed() < opts.poll,
7844            "returned only after {:?}, which is a poll interval, not a stop",
7845            began.elapsed()
7846        );
7847    }
7848
7849    #[tokio::test]
7850    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
7851        let dir = tempfile::tempdir().unwrap();
7852        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7853        let stop = Stop::new();
7854
7855        // Asked for after the loop is already parked on its empty queue, which
7856        // is the case an operator tapping stop on a phone actually hits.
7857        let asker = {
7858            let stop = stop.clone();
7859            tokio::spawn(async move {
7860                tokio::time::sleep(Duration::from_millis(20)).await;
7861                stop.stop();
7862            })
7863        };
7864
7865        let began = std::time::Instant::now();
7866        tokio::time::timeout(
7867            Duration::from_secs(2),
7868            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7869        )
7870        .await
7871        .expect("a stop asked for while idle must wake the wait")
7872        .expect("the loop's own setup and teardown must not fail");
7873        asker.await.unwrap();
7874        assert!(
7875            began.elapsed() < opts.poll,
7876            "returned only after {:?}, so the stop waited on the sleep",
7877            began.elapsed()
7878        );
7879    }
7880
7881    #[tokio::test]
7882    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
7883        let dir = tempfile::tempdir().unwrap();
7884        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7885        let stop = Stop::new();
7886        stop.stop();
7887
7888        tokio::time::timeout(
7889            Duration::from_secs(2),
7890            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
7891        )
7892        .await
7893        .expect("a stopped loop must return")
7894        .expect("the loop's own setup and teardown must not fail");
7895
7896        assert!(
7897            home.is_dir(),
7898            "the loop did publish a status file, so its removal is the teardown and not an absence"
7899        );
7900        assert!(
7901            !status_file.exists(),
7902            "a stopped loop clears its status file"
7903        );
7904        assert!(
7905            read_status(&home).is_none(),
7906            "a reader must see no daemon at all, not a heartbeat that merely stopped"
7907        );
7908    }
7909
7910    #[tokio::test]
7911    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
7912        let dir = tempfile::tempdir().unwrap();
7913        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
7914        opts.once = true;
7915
7916        let mut settled = RunState::new(
7917            dir.path().join("repo"),
7918            "main".to_owned(),
7919            "abc1234".to_owned(),
7920            "fixture".to_owned(),
7921            Config::default(),
7922        );
7923        settled.status = RunStatus::Ready;
7924        let run_dir = home.join("runs").join(&settled.id);
7925        std::fs::create_dir_all(&run_dir).unwrap();
7926        std::fs::write(
7927            run_dir.join("run.json"),
7928            serde_json::to_string_pretty(&settled).unwrap(),
7929        )
7930        .unwrap();
7931        let questions = Questions::at(home.join("questions"));
7932        let mut question = ask::Question::new(
7933            settled.id.clone(),
7934            "review".to_owned(),
7935            "reviewer-1".to_owned(),
7936            "Continue?".to_owned(),
7937            String::new(),
7938            Vec::new(),
7939        );
7940        questions.put(&mut question).unwrap();
7941
7942        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
7943            .await
7944            .unwrap();
7945
7946        assert_eq!(
7947            questions.get(&question.id).unwrap().status,
7948            ask::QuestionStatus::Abandoned,
7949            "an empty --once drain still performs startup question cleanup"
7950        );
7951    }
7952
7953    #[test]
7954    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
7955        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
7956
7957        assert!(
7958            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
7959            "never checked before: due at once"
7960        );
7961
7962        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
7963        assert!(
7964            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
7965            "well inside the interval: not due yet"
7966        );
7967
7968        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
7969        assert!(
7970            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
7971            "exactly at the edge: not yet due, same convention as `clean::due`"
7972        );
7973
7974        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
7975        assert!(
7976            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
7977            "past the interval: due again"
7978        );
7979    }
7980
7981    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
7982    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
7983    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
7984    /// and the congestion test below both need, and must not drift apart.
7985    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
7986        let config = dir.join("magi.toml");
7987        // A literal (single-quoted) TOML string, not a basic one: the cache
7988        // path is a Windows path full of backslashes, and a basic string
7989        // would have TOML try to interpret `\U` (from `\Users\...`) as a
7990        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
7991        // `{{ vars.cache }}` rendering documents.
7992        std::fs::write(
7993            &config,
7994            format!(
7995                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
7996                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
7997                cache_dir.display()
7998            ),
7999        )
8000        .unwrap();
8001        Opts {
8002            config: Some(config),
8003            repo: dir.join("repo"),
8004            ..Opts::default()
8005        }
8006    }
8007
8008    #[tokio::test]
8009    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
8010        let dir = tempfile::tempdir().unwrap();
8011        let home = dir.path().join("home");
8012        let cache_dir = dir.path().join("cache");
8013        std::fs::create_dir_all(&cache_dir).unwrap();
8014        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8015        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8016
8017        // Nobody has asked this daemon to stop, which is the ordinary case;
8018        // the skip that a stop buys is asserted by its own test below.
8019        let running = Stop::new();
8020        let mut last_checked = None;
8021        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8022        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
8023            .await;
8024        assert_eq!(
8025            crate::disk::dir_size(&cache_dir),
8026            0,
8027            "over the cap on the first check ever: pruned at once, no idle queue required"
8028        );
8029        assert_eq!(last_checked, Some(t0));
8030
8031        // A fresh oversized file lands, but the next check is not due yet.
8032        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
8033        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
8034        maybe_prune_cache_between_runs(
8035            &opts.repo,
8036            &opts,
8037            &home,
8038            &running,
8039            &mut last_checked,
8040            too_soon,
8041        )
8042        .await;
8043        assert_eq!(
8044            crate::disk::dir_size(&cache_dir),
8045            10,
8046            "too soon since the last check: left alone rather than rescanned every call"
8047        );
8048        assert_eq!(
8049            last_checked,
8050            Some(t0),
8051            "an idle check does not reset the clock"
8052        );
8053
8054        // Once the interval elapses, the same oversized cache is caught again.
8055        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8056        maybe_prune_cache_between_runs(
8057            &opts.repo,
8058            &opts,
8059            &home,
8060            &running,
8061            &mut last_checked,
8062            due_again,
8063        )
8064        .await;
8065        assert_eq!(
8066            crate::disk::dir_size(&cache_dir),
8067            0,
8068            "due again: pruned back under the cap"
8069        );
8070    }
8071
8072    /// A stop must not queue behind housekeeping. The prune below is a
8073    /// synchronous walk of the whole cache with no await point in it, so a
8074    /// loop that entered it could not get back to its own `stopped()` test
8075    /// until the walk finished - and because no run is in flight at this
8076    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
8077    /// the stop had already landed. The idle branch has always made this same
8078    /// check before reaching `janitor`; the between-runs path makes it too.
8079    #[tokio::test]
8080    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
8081        let dir = tempfile::tempdir().unwrap();
8082        let home = dir.path().join("home");
8083        let cache_dir = dir.path().join("cache");
8084        std::fs::create_dir_all(&cache_dir).unwrap();
8085        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8086        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8087
8088        let stop = Stop::new();
8089        stop.stop();
8090        assert!(
8091            !stop.finishing(),
8092            "no run is in flight at a between-runs boundary, so nothing else \
8093             would tell the operator this stop had not taken effect yet"
8094        );
8095
8096        let mut last_checked = None;
8097        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8098        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
8099            .await;
8100        assert_eq!(
8101            crate::disk::dir_size(&cache_dir),
8102            10,
8103            "over its cap, and due for the first check ever, but a stop outranks \
8104             it: the cap is a standing policy the next start measures again"
8105        );
8106        assert_eq!(
8107            last_checked, None,
8108            "a check that never happened must not claim the interval"
8109        );
8110    }
8111
8112    /// The regression this whole change exists for: gate timeouts on runs
8113    /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
8114    /// GiB against a 10 GiB cap, because the operator's queue never had a
8115    /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
8116    /// `janitor` pass.
8117    ///
8118    /// Reproduced with a backlog whose repository is never created:
8119    /// `Runner::start` fails at `git::toplevel`, spawning no agent CLI.
8120    /// Each task is held after one startup failure, but the remaining tasks
8121    /// keep the queue busy until an external stop ends the loop.
8122    #[tokio::test]
8123    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
8124        let dir = tempfile::tempdir().unwrap();
8125        let cache_dir = dir.path().join("cache");
8126        std::fs::create_dir_all(&cache_dir).unwrap();
8127        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
8128
8129        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
8130        opts.poll = Duration::from_millis(20);
8131        opts.max_attempts = 1_000;
8132
8133        let queue = Queue::at(dir.path().join("queue"));
8134        for i in 0..128 {
8135            let mut task = Task::new(
8136                format!("queued work {i}"),
8137                format!("queued work {i}"),
8138                opts.repo.clone(),
8139                Source::Human,
8140            );
8141            queue.put(&mut task).unwrap();
8142        }
8143
8144        let home = dir.path().join("home");
8145        let worktrees = dir.path().join("wt");
8146        let status_file = home.join("daemon.json");
8147        let stop = Stop::new();
8148        let stopper = {
8149            let stop = stop.clone();
8150            let queue = Queue::at(dir.path().join("queue"));
8151            tokio::spawn(async move {
8152                // Observe completed work rather than rely on a wall-clock
8153                // delay. Every startup failure holds only its own task; the
8154                // backlog keeps offering work at the next boundary.
8155                for _ in 0..2_000 {
8156                    if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
8157                        break;
8158                    }
8159                    tokio::time::sleep(Duration::from_millis(5)).await;
8160                }
8161                stop.stop();
8162            })
8163        };
8164
8165        tokio::time::timeout(
8166            Duration::from_secs(20),
8167            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8168        )
8169        .await
8170        .expect("the loop must not hang on a queue that keeps producing failing work")
8171        .expect("the loop's own setup and teardown must not fail");
8172        stopper.await.unwrap();
8173
8174        let after = queue.list();
8175        let completed = after.iter().filter(|t| t.attempts == 1).count();
8176        assert!(
8177            completed >= 2,
8178            "the harness must have processed multiple tasks to exercise a busy queue \
8179             (got {completed} completed task(s))"
8180        );
8181        assert!(
8182            after.iter().any(|t| t.status.runnable()),
8183            "unprocessed tasks must remain: the external stop, rather than an \
8184             exhausted backlog, must end the test"
8185        );
8186        assert!(
8187            after
8188                .iter()
8189                .filter(|t| t.attempts > 0)
8190                .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
8191            "a busy backlog must not retry a task's unchanged startup failure"
8192        );
8193
8194        assert_eq!(
8195            crate::disk::dir_size(&cache_dir),
8196            0,
8197            "an oversized cache must not be left to grow unboundedly just because the \
8198             queue kept the loop busy the whole time"
8199        );
8200    }
8201
8202    #[test]
8203    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
8204        let dir = tempfile::tempdir().unwrap();
8205        let queue = Queue::at(dir.path().join("queue"));
8206        let questions = Questions::at(dir.path().join("questions"));
8207        let mut task = task();
8208        queue.put(&mut task).unwrap();
8209
8210        let mut task_question = ask::Question::new(
8211            task.id.clone(),
8212            crate::conduct::NODE.to_owned(),
8213            "conduct".to_owned(),
8214            "Which backend?".to_owned(),
8215            String::new(),
8216            Vec::new(),
8217        );
8218        questions.put(&mut task_question).unwrap();
8219        task.block(vec![task_question.id.clone()], None);
8220        queue.put(&mut task).unwrap();
8221
8222        let mut run_question = ask::Question::new(
8223            "20260101-000000-run1".to_owned(),
8224            "review".to_owned(),
8225            "reviewer-1".to_owned(),
8226            "Run question".to_owned(),
8227            String::new(),
8228            Vec::new(),
8229        );
8230        questions.put(&mut run_question).unwrap();
8231
8232        // A question from another node whose `run` happens to equal this
8233        // task's id — the same field, filled in for an unrelated reason. Only
8234        // `crate::conduct::NODE` questions use `run` as a task id; this one
8235        // must never be touched by this reconciliation, even after release.
8236        let mut coincidental = ask::Question::new(
8237            task.id.clone(),
8238            "review".to_owned(),
8239            "reviewer-1".to_owned(),
8240            "Unrelated review question".to_owned(),
8241            String::new(),
8242            Vec::new(),
8243        );
8244        questions.put(&mut coincidental).unwrap();
8245
8246        reconcile_task_questions(&queue, &questions);
8247        assert!(questions.get(&task_question.id).unwrap().status.open());
8248        assert!(questions.get(&run_question.id).unwrap().status.open());
8249        assert!(questions.get(&coincidental.id).unwrap().status.open());
8250
8251        task.release();
8252        queue.put(&mut task).unwrap();
8253        reconcile_task_questions(&queue, &questions);
8254        assert_eq!(
8255            questions.get(&task_question.id).unwrap().status,
8256            ask::QuestionStatus::Abandoned
8257        );
8258        assert!(
8259            questions.get(&run_question.id).unwrap().status.open(),
8260            "run questions remain the run janitor's responsibility"
8261        );
8262        assert!(
8263            questions.get(&coincidental.id).unwrap().status.open(),
8264            "a non-conductor question must not be abandoned just because its \
8265             run id coincides with a task id"
8266        );
8267    }
8268
8269    #[test]
8270    fn a_freshly_started_running_task_is_never_stalled() {
8271        let dir = tempfile::tempdir().unwrap();
8272        let mut t = task();
8273        t.start("run-1".to_owned());
8274        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
8275        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
8276        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
8277    }
8278
8279    #[test]
8280    fn a_long_running_task_with_no_live_daemon_is_stalled() {
8281        let dir = tempfile::tempdir().unwrap();
8282        let mut t = task();
8283        t.start("run-1".to_owned());
8284        t.updated_at = Timestamp::now()
8285            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8286        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
8287        assert_eq!(
8288            stalled_tasks(
8289                &Queue::at(dir.path().join("q")),
8290                dir.path(),
8291                Timestamp::now()
8292            )
8293            .len(),
8294            0,
8295            "the task was never written to this queue"
8296        );
8297    }
8298
8299    #[test]
8300    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
8301        let dir = tempfile::tempdir().unwrap();
8302        let mut t = task();
8303        t.id = "20260903-080340-0167".to_owned();
8304        t.start("20260903-080619-01c2".to_owned());
8305        t.updated_at = Timestamp::now()
8306            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8307
8308        let mut status = Status::new();
8309        status.current = vec![Current {
8310            task: t.id.clone(),
8311            run: "20260903-080619-01c2".to_owned(),
8312        }];
8313        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8314
8315        assert!(
8316            !is_stalled(&t, dir.path(), Timestamp::now()),
8317            "a live daemon's own heartbeat rules out stalled, however long the task has run"
8318        );
8319    }
8320
8321    /// Rewrite a task's `updated_at` on disk directly, bypassing
8322    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
8323    /// a fixture look like it has genuinely been `running` for a while.
8324    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
8325        let path = queue.path_of(id);
8326        let body = std::fs::read_to_string(&path).unwrap();
8327        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
8328        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
8329        v["updated_at"] = serde_json::Value::String(old.to_string());
8330        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
8331    }
8332
8333    #[test]
8334    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
8335        // The realistic `poll()` ordering, not `is_stalled` in isolation:
8336        // `reclaim_orphaned_running` runs first, on every poll, and settles
8337        // any `running` task whose claim it can actually take. For most
8338        // crashes that is immediate - a dead pid is proof enough for
8339        // `sweep_stale_claims` to drop the lock the same tick, and the very
8340        // next claim attempt succeeds. But a lock whose pid cannot be parsed
8341        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
8342        // `sweep_stale_claims`'s own doc), so the lock - and the claim
8343        // failure behind it - can legitimately outlive many polls. This is
8344        // exactly the gap `stalled_tasks` exists to surface well before that
8345        // six-hour sweep would: reclaim leaves the task `running`, and it
8346        // must still reach the conductor as stalled.
8347        let dir = tempfile::tempdir().unwrap();
8348        let queue = Queue::at(dir.path().join("queue"));
8349        let home = dir.path().join("home");
8350
8351        let mut t = task();
8352        t.id = "20260101-000001-lock".to_owned();
8353        t.start("run-1".to_owned());
8354        queue.put(&mut t).unwrap();
8355        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8356        std::fs::write(
8357            dir.path().join("queue").join(format!("{}.lock", t.id)),
8358            "not a pid",
8359        )
8360        .unwrap();
8361
8362        let now = Timestamp::now();
8363        assert!(
8364            reclaim_orphaned_running(&queue, 2).is_empty(),
8365            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
8366             and reclaim must leave the task alone"
8367        );
8368        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8369
8370        let stalled = stalled_tasks(&queue, &home, now);
8371        assert_eq!(
8372            stalled.len(),
8373            1,
8374            "reclaim's inability to claim it yet must not hide it from the conductor"
8375        );
8376        assert_eq!(stalled[0].id, t.id);
8377    }
8378
8379    #[test]
8380    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
8381        let dir = tempfile::tempdir().unwrap();
8382        crate::run::set_home(dir.path().join("run-home"));
8383        let queue = Queue::at(dir.path().join("queue"));
8384        let home = dir.path().join("home");
8385        let questions = Questions::at(dir.path().join("questions"));
8386
8387        let mut t = task();
8388        t.id = "20260101-000003-dead".to_owned();
8389        t.start("missing-run".to_owned());
8390        queue.put(&mut t).unwrap();
8391        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8392
8393        // This is the real poll ordering: retain the deterministic stalled
8394        // input before a claim proves the owner is gone and reclaims it.
8395        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
8396        assert_eq!(
8397            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
8398            [&t.id]
8399        );
8400        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
8401        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8402
8403        // Reclaim drops its guard before conductor decisions are applied, so
8404        // the decision for the captured stalled input has a real write path.
8405        crate::conduct::apply(
8406            &queue,
8407            &questions,
8408            &crate::conduct::Verdict {
8409                decisions: vec![crate::conduct::Decision {
8410                    id: t.id.clone(),
8411                    recovery: Some(crate::conduct::Recovery::Requeue),
8412                    ..crate::conduct::Decision::default()
8413                }],
8414            },
8415        )
8416        .unwrap();
8417        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8418    }
8419
8420    #[test]
8421    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
8422        let dir = tempfile::tempdir().unwrap();
8423        let queue = Queue::at(dir.path().join("queue"));
8424        let home = dir.path().join("home");
8425
8426        let mut fresh = task();
8427        fresh.id = "20260101-000001-aaaa".to_owned();
8428        fresh.start("run-1".to_owned());
8429        queue.put(&mut fresh).unwrap();
8430
8431        let mut old = task();
8432        old.id = "20260101-000002-bbbb".to_owned();
8433        old.start("run-2".to_owned());
8434        queue.put(&mut old).unwrap();
8435        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
8436
8437        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
8438        assert_eq!(stalled.len(), 1);
8439        assert_eq!(stalled[0].id, old.id);
8440    }
8441
8442    #[test]
8443    fn queued_and_finished_task_views_partition_by_status() {
8444        let dir = tempfile::tempdir().unwrap();
8445        let queue = Queue::at(dir.path().join("queue"));
8446
8447        let mut queued = task();
8448        queued.id = "20260101-000001-aaaa".to_owned();
8449        queue.put(&mut queued).unwrap();
8450
8451        let mut failed = task();
8452        failed.id = "20260101-000002-bbbb".to_owned();
8453        failed.start("run-1".to_owned());
8454        failed.fail("gate red", 5);
8455        queue.put(&mut failed).unwrap();
8456
8457        let mut held = task();
8458        held.id = "20260101-000003-cccc".to_owned();
8459        held.hold_machine(None);
8460        queue.put(&mut held).unwrap();
8461
8462        let mut running = task();
8463        running.id = "20260101-000004-dddd".to_owned();
8464        running.start("run-2".to_owned());
8465        queue.put(&mut running).unwrap();
8466
8467        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
8468        assert_eq!(queued_ids, [queued.id.clone()]);
8469
8470        let mut finished_ids: Vec<String> =
8471            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
8472        finished_ids.sort_unstable();
8473        let mut want = vec![failed.id.clone(), held.id.clone()];
8474        want.sort_unstable();
8475        assert_eq!(finished_ids, want);
8476    }
8477
8478    #[test]
8479    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
8480        let dir = tempfile::tempdir().unwrap();
8481        let queue = Queue::at(dir.path().join("queue"));
8482        let questions = ask::Questions::at(dir.path().join("questions"));
8483
8484        let mut dep = task();
8485        dep.id = "20260101-000001-dep0".to_owned();
8486        dep.succeed();
8487        queue.put(&mut dep).unwrap();
8488
8489        let mut still_going = task();
8490        still_going.id = "20260101-000002-dep1".to_owned();
8491        queue.put(&mut still_going).unwrap();
8492
8493        let mut blocked = task();
8494        blocked.id = "20260101-000003-main".to_owned();
8495        blocked.block(
8496            vec![dep.id.clone(), still_going.id.clone()],
8497            Some("waits on both".to_owned()),
8498        );
8499        queue.put(&mut blocked).unwrap();
8500
8501        resolve_blockers(&queue, &questions);
8502
8503        let after = queue.get(&blocked.id).unwrap();
8504        assert_eq!(
8505            after.status,
8506            TaskStatus::Blocked,
8507            "one dependency is still outstanding"
8508        );
8509        assert_eq!(after.blocked_by, [still_going.id.clone()]);
8510    }
8511
8512    #[test]
8513    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
8514        let dir = tempfile::tempdir().unwrap();
8515        let queue = Queue::at(dir.path().join("queue"));
8516        let questions = ask::Questions::at(dir.path().join("questions"));
8517
8518        let mut q = crate::ask::Question::new(
8519            "20260101-000001-main".to_owned(),
8520            crate::conduct::NODE.to_owned(),
8521            "conduct".to_owned(),
8522            "Which backend?".to_owned(),
8523            String::new(),
8524            Vec::new(),
8525        );
8526        questions.put(&mut q).unwrap();
8527        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
8528            .unwrap();
8529        questions.put(&mut q).unwrap();
8530
8531        let mut blocked = task();
8532        blocked.id = "20260101-000001-main".to_owned();
8533        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
8534        queue.put(&mut blocked).unwrap();
8535
8536        resolve_blockers(&queue, &questions);
8537
8538        let after = queue.get(&blocked.id).unwrap();
8539        assert_eq!(
8540            after.status,
8541            TaskStatus::Queued,
8542            "the only blocker resolved"
8543        );
8544        assert_eq!(after.answers.len(), 1);
8545        assert_eq!(after.answers[0].question, "Which backend?");
8546        assert_eq!(after.answers[0].answer, "SQLite");
8547
8548        // And the run this task starts next is told about it.
8549        let instruction = instruction_for(&after);
8550        assert!(instruction.contains("Which backend?"));
8551        assert!(instruction.contains("SQLite"));
8552    }
8553
8554    #[test]
8555    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
8556        let dir = tempfile::tempdir().unwrap();
8557        let queue = Queue::at(dir.path().join("queue"));
8558        let questions = ask::Questions::at(dir.path().join("questions"));
8559
8560        let mut q = crate::ask::Question::new(
8561            "20260101-000001-main".to_owned(),
8562            crate::conduct::NODE.to_owned(),
8563            "conduct".to_owned(),
8564            "Is the setup done?".to_owned(),
8565            String::new(),
8566            Vec::new(),
8567        );
8568        q.abandon("no answer within 60s of asking");
8569        questions.put(&mut q).unwrap();
8570
8571        let mut blocked = task();
8572        blocked.id = "20260101-000001-main".to_owned();
8573        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
8574        queue.put(&mut blocked).unwrap();
8575
8576        resolve_blockers(&queue, &questions);
8577
8578        let after = queue.get(&blocked.id).unwrap();
8579        assert_eq!(
8580            after.status,
8581            TaskStatus::Held,
8582            "never left blocked on nothing"
8583        );
8584        assert!(!after.operator_held(), "a machine hold, for triage");
8585        assert!(
8586            after
8587                .hold_reason
8588                .as_deref()
8589                .unwrap_or_default()
8590                .contains("went unanswered")
8591        );
8592    }
8593
8594    #[test]
8595    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
8596        // Reproduces the reported bug (task 3958): a task held out of
8597        // attempts, blocked on a `crate::conduct` follow-up question, must
8598        // come back `held` once that question is answered - never `queued`,
8599        // whatever the answer said - or it silently re-enters the
8600        // competition queue with its attempts already exhausted.
8601        let dir = tempfile::tempdir().unwrap();
8602        let queue = Queue::at(dir.path().join("queue"));
8603        let questions = ask::Questions::at(dir.path().join("questions"));
8604
8605        let mut q = crate::ask::Question::new(
8606            "20260101-000001-main".to_owned(),
8607            crate::conduct::NODE.to_owned(),
8608            "conduct".to_owned(),
8609            "How should this be handled?".to_owned(),
8610            String::new(),
8611            Vec::new(),
8612        );
8613        questions.put(&mut q).unwrap();
8614        q.answer(crate::ask::Answer::Text(
8615            "leave it held, a human will look at it later".to_owned(),
8616        ))
8617        .unwrap();
8618        questions.put(&mut q).unwrap();
8619
8620        let mut held = task();
8621        held.id = "20260101-000001-main".to_owned();
8622        held.hold_machine(Some("out of attempts".to_owned()));
8623        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
8624        queue.put(&mut held).unwrap();
8625
8626        resolve_blockers(&queue, &questions);
8627
8628        let after = queue.get(&held.id).unwrap();
8629        assert_eq!(after.status, TaskStatus::Held);
8630        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
8631        assert_eq!(
8632            after.answers[0].answer,
8633            "leave it held, a human will look at it later"
8634        );
8635    }
8636
8637    #[test]
8638    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
8639        let dir = tempfile::tempdir().unwrap();
8640        let queue = Queue::at(dir.path().join("queue"));
8641        let questions = ask::Questions::at(dir.path().join("questions"));
8642        let mut dep = task();
8643        dep.id = "20260101-000001-gone".to_owned();
8644        queue.put(&mut dep).unwrap();
8645        let mut blocked = task();
8646        blocked.id = "20260101-000003-main".to_owned();
8647        blocked.block(vec![dep.id.clone()], None);
8648        queue.put(&mut blocked).unwrap();
8649
8650        // Claimed, so `remove` cannot rewrite it and the resolver must.
8651        let claim = queue.claim(&blocked.id).unwrap();
8652        queue.remove(&dep.id, false, &questions).unwrap();
8653        drop(claim);
8654        resolve_blockers(&queue, &questions);
8655
8656        let after = queue.get(&blocked.id).unwrap();
8657        assert_eq!(after.status, TaskStatus::Queued);
8658        assert!(after.blocked_by.is_empty());
8659    }
8660
8661    #[test]
8662    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
8663        // Reproduces the reported bug: a task blocked on a task id that was
8664        // removed (`magi task rm`, or deleted by hand) can never see that id
8665        // reach `Done`, so the ordinary per-id loop has nothing to notice and
8666        // would otherwise leave the task `blocked` forever with no way for an
8667        // operator to find out why.
8668        let dir = tempfile::tempdir().unwrap();
8669        let queue = Queue::at(dir.path().join("queue"));
8670        let questions = ask::Questions::at(dir.path().join("questions"));
8671
8672        let mut still_going = task();
8673        still_going.id = "20260101-000002-dep1".to_owned();
8674        queue.put(&mut still_going).unwrap();
8675
8676        let mut blocked = task();
8677        blocked.id = "20260101-000003-main".to_owned();
8678        blocked.block(
8679            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
8680            Some("waits on both".to_owned()),
8681        );
8682        queue.put(&mut blocked).unwrap();
8683
8684        resolve_blockers(&queue, &questions);
8685
8686        let after = queue.get(&blocked.id).unwrap();
8687        assert_eq!(
8688            after.status,
8689            TaskStatus::Held,
8690            "a missing dependency must not leave the task blocked forever"
8691        );
8692        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
8693        assert!(after.blocked_by.is_empty());
8694        let reason = after.hold_reason.as_deref().unwrap_or_default();
8695        assert!(
8696            reason.contains("20260101-000001-gone"),
8697            "the missing id must be named so an operator can tell what happened: {reason}"
8698        );
8699        assert!(
8700            reason.contains(&still_going.id),
8701            "the still-valid dependency must not silently vanish from the record: {reason}"
8702        );
8703    }
8704
8705    #[test]
8706    fn instruction_for_is_unchanged_without_any_answers() {
8707        let t = task();
8708        assert_eq!(instruction_for(&t), t.instruction);
8709    }
8710
8711    #[test]
8712    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
8713        let dir = tempfile::tempdir().unwrap();
8714        let q = Queue::at(dir.path().join("queue"));
8715        let src = dir.path().join("shot.png");
8716        std::fs::write(&src, "x").unwrap();
8717        let mut t = task();
8718        q.attach(&mut t, &[src]).unwrap();
8719        let paths = task_attachments(&q, &t).unwrap();
8720        assert_eq!(paths.len(), 1);
8721        assert!(paths[0].is_absolute() && paths[0].is_file());
8722        std::fs::remove_file(&paths[0]).unwrap();
8723        let err = task_attachments(&q, &t).unwrap_err().to_string();
8724        assert!(err.contains("shot.png"), "{err}");
8725    }
8726
8727    #[test]
8728    fn resumed_instruction_is_unchanged_without_any_answers() {
8729        let t = task();
8730        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
8731    }
8732
8733    #[test]
8734    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
8735        let mut t = task();
8736        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8737        // The run's own instruction on disk predates the answer: it is the
8738        // plain original text `Runner::start` saved before the operator was
8739        // ever asked anything.
8740        let old = t.instruction.clone();
8741
8742        let refreshed = resumed_instruction(&old, &t);
8743        assert!(refreshed.starts_with(&old), "the original text is kept");
8744        assert!(refreshed.contains("Which backend?"));
8745        assert!(refreshed.contains("SQLite"));
8746    }
8747
8748    #[test]
8749    fn resumed_instruction_keeps_an_original_answers_heading() {
8750        let mut t = task();
8751        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
8752        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8753
8754        let refreshed = resumed_instruction(&t.instruction, &t);
8755
8756        assert!(
8757            refreshed.starts_with(&t.instruction),
8758            "an answers heading in the original instruction is not the appended block"
8759        );
8760        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
8761        assert!(refreshed.contains("Which backend?"));
8762        assert!(refreshed.contains("SQLite"));
8763
8764        let repeated = resumed_instruction(&refreshed, &t);
8765        assert_eq!(
8766            repeated, refreshed,
8767            "only the final appended block is refreshed"
8768        );
8769    }
8770
8771    #[test]
8772    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
8773        let mut t = task();
8774        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8775
8776        // A first resume appends the block; a second resume of the same run,
8777        // with no new answer in between, must reproduce exactly the same
8778        // text rather than appending the block a second time.
8779        let once = resumed_instruction(&t.instruction, &t);
8780        let twice = resumed_instruction(&once, &t);
8781        assert_eq!(once, twice);
8782        assert_eq!(once.matches("Which backend?").count(), 1);
8783
8784        // A later answer replaces the block wholesale rather than growing it.
8785        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
8786        let refreshed = resumed_instruction(&once, &t);
8787        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
8788        assert!(refreshed.contains("Which backend?"));
8789        assert!(refreshed.contains("Which cache?"));
8790    }
8791
8792    #[test]
8793    fn prepare_instruction_covers_all_three_starters() {
8794        let mut t = task();
8795        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
8796
8797        // Start: a fresh run gets the task text plus every answer so far —
8798        // exactly `instruction_for`.
8799        assert_eq!(
8800            prepare_instruction(&Starter::Start, None, &t),
8801            Some(instruction_for(&t))
8802        );
8803
8804        // Resume: the run's prior instruction is refreshed with the answer,
8805        // not discarded and not left stale.
8806        let old = t.instruction.clone();
8807        assert_eq!(
8808            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
8809            Some(resumed_instruction(&old, &t))
8810        );
8811
8812        // Review: a review-only pass builds its own instruction from the
8813        // branch's history in `crate::graph`, with no task statement at all -
8814        // this boundary must leave it alone.
8815        assert_eq!(
8816            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
8817            None
8818        );
8819    }
8820
8821    #[test]
8822    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
8823        assert_eq!(
8824            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
8825            Starter::Review("magi/eba2/A".to_owned())
8826        );
8827    }
8828
8829    #[test]
8830    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
8831        assert_eq!(
8832            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
8833            Starter::Start,
8834            "a vanished review branch must not fall back to resuming the old run either"
8835        );
8836    }
8837
8838    #[test]
8839    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
8840        let mut t = task();
8841        t.start("old-run".to_owned());
8842        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
8843        t.release();
8844        let branch = t.review_branch.take();
8845        assert_eq!(
8846            choose_starter(branch.as_deref(), true, Some("old-run")),
8847            Starter::Review("magi/eba2/A".to_owned()),
8848            "a review wins over resuming the old run"
8849        );
8850    }
8851
8852    #[test]
8853    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
8854        assert_eq!(
8855            choose_starter(None, false, Some("some-run")),
8856            Starter::Resume("some-run".to_owned())
8857        );
8858        assert_eq!(choose_starter(None, false, None), Starter::Start);
8859    }
8860
8861    #[test]
8862    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
8863        let mut released = task();
8864        released.start("stalled-run".to_owned());
8865        released.requeue();
8866        let unfinished = (!released.fresh_start)
8867            .then(|| Some("stalled-run".to_owned()))
8868            .flatten();
8869        assert_eq!(
8870            choose_starter(None, false, unfinished.as_deref()),
8871            Starter::Start,
8872            "release keeps run history but must not resume it"
8873        );
8874        assert_eq!(released.runs, ["stalled-run"]);
8875    }
8876
8877    #[test]
8878    fn an_ordinary_release_keeps_a_resumable_run_available() {
8879        let mut released = task();
8880        released.start("stalled-run".to_owned());
8881        released.release();
8882        let unfinished = (!released.fresh_start)
8883            .then(|| Some("stalled-run".to_owned()))
8884            .flatten();
8885        assert_eq!(
8886            choose_starter(None, false, unfinished.as_deref()),
8887            Starter::Resume("stalled-run".to_owned()),
8888            "manual release must preserve the normal resume path"
8889        );
8890    }
8891
8892    #[test]
8893    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
8894        let mut state = run_state(RunStatus::Blocked);
8895        state.config.graph.review_rounds = 3;
8896        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
8897        assert!(exhausted_review_budget(&state));
8898
8899        // One round still unused: resuming can still ask a reviewer something.
8900        state.reviews.pop();
8901        assert!(!exhausted_review_budget(&state));
8902
8903        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
8904        // count: only a `Blocked` run re-enters the review loop on resume.
8905        let mut stalled = run_state(RunStatus::Stalled);
8906        stalled.config.graph.review_rounds = 1;
8907        stalled.reviews = vec![review_round(1)];
8908        assert!(!exhausted_review_budget(&stalled));
8909    }
8910
8911    fn review_round(round: usize) -> crate::run::ReviewRound {
8912        crate::run::ReviewRound {
8913            round,
8914            head: "deadbeef".to_owned(),
8915            verified_head: None,
8916            verified_at: None,
8917            reviews: Vec::new(),
8918            e2e: Vec::new(),
8919            verify_retried: false,
8920            e2e_deferred: false,
8921            e2e_defer_reason: None,
8922            fix: None,
8923            blocking: 0,
8924            answered: 1,
8925            expected: 1,
8926            clean: false,
8927            progressed: true,
8928            vote_split: false,
8929            reconsideration: Vec::new(),
8930            verdict: None,
8931        }
8932    }
8933
8934    #[test]
8935    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
8936        let mut run = RunState::new(
8937            PathBuf::from("/repo"),
8938            "main".to_owned(),
8939            "abc1234def".to_owned(),
8940            "add retries".to_owned(),
8941            Config::default(),
8942        );
8943        run.status = RunStatus::Judging;
8944        run.parked = true;
8945        let mut task = Task::new(
8946            "add retries".to_owned(),
8947            "add retries".to_owned(),
8948            PathBuf::from("/repo"),
8949            crate::queue::Source::Human,
8950        );
8951        task.status = TaskStatus::Failed;
8952        task.runs = vec![run.id.clone()];
8953        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
8954        assert!(with(&task, &run), "parked after judging is the case");
8955        let mut parked_task = task.clone();
8956        parked_task.status = TaskStatus::Parked;
8957        assert!(with(&parked_task, &run), "the Parked status is the case");
8958
8959        let mut not_parked = run.clone();
8960        not_parked.parked = false;
8961        not_parked.status = RunStatus::Stalled;
8962        assert!(!with(&task, &not_parked), "a stall is the conductor's");
8963
8964        let mut fresh = task.clone();
8965        fresh.fresh_start = true;
8966        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
8967
8968        let mut review = task.clone();
8969        review.review_branch = Some("magi/x/A".to_owned());
8970        assert!(!with(&review, &run), "review is ranked before resume");
8971
8972        let mut held = task.clone();
8973        held.status = TaskStatus::Held;
8974        assert!(!with(&held, &run), "a hold stays visible to the conductor");
8975
8976        let mut released = run.clone();
8977        released.released_to = Some("20260901-000000-new1".to_owned());
8978        assert!(!with(&task, &released), "nothing left to resume into");
8979
8980        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
8981            "unreadable"
8982        )));
8983    }
8984
8985    #[test]
8986    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
8987        let mut released = RunState::new(
8988            PathBuf::from("/repo"),
8989            "main".to_owned(),
8990            "abc1234def".to_owned(),
8991            "add retries".to_owned(),
8992            Config::default(),
8993        );
8994        released.status = RunStatus::Blocked;
8995        assert_eq!(
8996            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
8997            Some(released.id.clone())
8998        );
8999        released.released_to = Some("20260901-000000-new1".to_owned());
9000        assert_eq!(
9001            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9002            None,
9003            "there is nothing left to resume it into"
9004        );
9005    }
9006
9007    #[test]
9008    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
9009        // Mirrors the failure this exists to close: a task's last run ended
9010        // `Blocked` with the review budget spent, `crate::conduct` chose
9011        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
9012        // evidence), and without this check `attempt` would go on treating
9013        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
9014        // review loop iterates zero times over an already-spent budget, so
9015        // the resumed run settles right back to `Blocked` having asked nobody
9016        // anything, and `Requeue`'s promised fresh competition never happens.
9017        let mut exhausted = RunState::new(
9018            PathBuf::from("/repo"),
9019            "main".to_owned(),
9020            "abc1234def".to_owned(),
9021            "add retries".to_owned(),
9022            Config::default(),
9023        );
9024        exhausted.status = RunStatus::Blocked;
9025        exhausted.config.graph.review_rounds = 1;
9026        exhausted.reviews = vec![review_round(1)];
9027
9028        assert_eq!(
9029            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
9030            None,
9031            "an exhausted `Blocked` run must not be offered as resumable"
9032        );
9033
9034        // A `Blocked` run with rounds still unused is genuinely worth
9035        // resuming, and must still be found.
9036        let mut has_budget_left = RunState::new(
9037            PathBuf::from("/repo"),
9038            "main".to_owned(),
9039            "abc1234def".to_owned(),
9040            "add retries".to_owned(),
9041            Config::default(),
9042        );
9043        has_budget_left.status = RunStatus::Blocked;
9044        has_budget_left.config.graph.review_rounds = 3;
9045        has_budget_left.reviews = vec![review_round(1)];
9046
9047        assert_eq!(
9048            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
9049                Ok(has_budget_left.clone())
9050            }),
9051            Some(has_budget_left.id.clone())
9052        );
9053    }
9054
9055    #[test]
9056    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
9057        let mut run = RunState::new(
9058            PathBuf::from("/repo"),
9059            "main".to_owned(),
9060            "abc1234def".to_owned(),
9061            "add retries".to_owned(),
9062            Config::default(),
9063        );
9064        run.status = RunStatus::Blocked;
9065        run.config.graph.review_rounds = 1;
9066        run.reviews = vec![review_round(1)];
9067        run.pr_publication_pending = true;
9068        assert_eq!(
9069            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
9070            Some(run.id.clone()),
9071            "a spent review budget must not turn a failed publication into a re-competition"
9072        );
9073    }
9074
9075    #[test]
9076    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
9077        // A task whose history holds an *older* run that still looks
9078        // resumable (say, a competition `Runner::review` was started
9079        // alongside after that older run went `Stalled`) and a *newest* run
9080        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
9081        // on this task must mean a fresh competition — falling back to the
9082        // stale, superseded `Stalled` run instead would resurrect history
9083        // nothing asked to revisit and silently defeat the requeue.
9084        let mut older_stalled = RunState::new(
9085            PathBuf::from("/repo"),
9086            "main".to_owned(),
9087            "abc1234def".to_owned(),
9088            "add retries".to_owned(),
9089            Config::default(),
9090        );
9091        older_stalled.status = RunStatus::Stalled;
9092
9093        let mut newest_exhausted = RunState::new(
9094            PathBuf::from("/repo"),
9095            "main".to_owned(),
9096            "abc1234def".to_owned(),
9097            "add retries".to_owned(),
9098            Config::default(),
9099        );
9100        newest_exhausted.status = RunStatus::Blocked;
9101        newest_exhausted.config.graph.review_rounds = 1;
9102        newest_exhausted.reviews = vec![review_round(1)];
9103
9104        assert_eq!(
9105            unfinished_run_with(
9106                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
9107                "t",
9108                |_| Ok(newest_exhausted.clone())
9109            ),
9110            None,
9111            "the newest run is exhausted, so nothing here is worth resuming - \
9112             least of all the older, already-superseded run"
9113        );
9114    }
9115
9116    #[test]
9117    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
9118        assert_eq!(
9119            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
9120                Err(anyhow::anyhow!("fixture is absent"))
9121            }),
9122            None
9123        );
9124    }
9125
9126    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
9127        let mut q = ask::Question::new(
9128            run.to_owned(),
9129            "implement".to_owned(),
9130            "impl-A".to_owned(),
9131            "continue?".to_owned(),
9132            String::new(),
9133            vec!["resume で続行する".to_owned(), "other".to_owned()],
9134        );
9135        q.actions.insert("resume で続行する".to_owned(), action);
9136        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
9137            .unwrap();
9138        q
9139    }
9140
9141    fn held_task_with(run: &str) -> Task {
9142        let mut t = task();
9143        t.runs = vec![run.to_owned()];
9144        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
9145        t
9146    }
9147
9148    fn resume_action(run: &str) -> ask::ChoiceAction {
9149        ask::ChoiceAction::Resume { run: run.into() }
9150    }
9151
9152    #[test]
9153    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
9154        for parked in [false, true] {
9155            let mut t = task();
9156            t.start("A".into());
9157            t.start("B".into());
9158            assert_eq!(t.runs, vec!["A", "B"]);
9159            t.start("A".into());
9160            let mut resumed = run_state(RunStatus::Blocked);
9161            resumed.id = "A".into();
9162            resumed.parked = parked;
9163            resumed.driver_exited = true;
9164            t.hold_machine(Some("resumed run stopped".into()));
9165            let q = action_question("A", resume_action("A"));
9166            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
9167            assert_eq!(
9168                decide_action(&t, &q, &PHRASES_EN, |id| {
9169                    assert_eq!(id, "A");
9170                    Ok(resumed.clone())
9171                }),
9172                ActionDecision::Resume("A".into())
9173            );
9174            assert_eq!(
9175                action_standing(&t, &action_question("B", resume_action("B"))),
9176                ActionStanding::Stale
9177            );
9178            t.release_operator("cli", None);
9179            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
9180                assert_eq!(id, "A");
9181                Ok(resumed.clone())
9182            });
9183            assert_eq!(
9184                choose_starter(None, false, unfinished.as_deref()),
9185                Starter::Resume("A".into())
9186            );
9187            assert_eq!(t.runs, vec!["B", "A"]);
9188        }
9189    }
9190
9191    #[test]
9192    fn decide_action_resumes_only_the_latest_resumable_run() {
9193        let t = held_task_with("r1");
9194        let q = action_question("r1", resume_action("r1"));
9195        let load = |s: RunState| move |_: &str| Ok(s);
9196        assert_eq!(
9197            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
9198            ActionDecision::Resume("r1".into())
9199        );
9200        // Not the latest run of the task.
9201        let q_other = action_question("r1", resume_action("r0"));
9202        assert!(matches!(
9203            decide_action(
9204                &t,
9205                &q_other,
9206                &PHRASES_EN,
9207                load(run_state(RunStatus::Blocked))
9208            ),
9209            ActionDecision::Refuse(_)
9210        ));
9211        // A finished run cannot make progress.
9212        assert!(matches!(
9213            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
9214            ActionDecision::Refuse(_)
9215        ));
9216        // A released one either.
9217        let mut released = run_state(RunStatus::Blocked);
9218        released.released_to = Some("elsewhere".into());
9219        assert!(matches!(
9220            decide_action(&t, &q, &PHRASES_EN, load(released)),
9221            ActionDecision::Refuse(_)
9222        ));
9223        // Unreadable state is a refusal, never a fresh competition.
9224        assert!(matches!(
9225            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
9226            ActionDecision::Refuse(_)
9227        ));
9228    }
9229
9230    #[test]
9231    fn decide_action_ignores_a_question_about_an_earlier_run() {
9232        let mut t = held_task_with("r1");
9233        t.runs.push("r2".to_owned());
9234        let never = |_: &str| -> Result<RunState> { bail!("not read") };
9235        assert_eq!(
9236            decide_action(
9237                &t,
9238                &action_question("r1", ask::ChoiceAction::Done),
9239                &PHRASES_EN,
9240                never
9241            ),
9242            ActionDecision::Stale
9243        );
9244    }
9245
9246    #[test]
9247    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
9248        let mut t = held_task_with("r1");
9249        let never = |_: &str| -> Result<RunState> { bail!("not read") };
9250        assert_eq!(
9251            decide_action(
9252                &t,
9253                &action_question("r1", ask::ChoiceAction::Requeue),
9254                &PHRASES_EN,
9255                never
9256            ),
9257            ActionDecision::Requeue
9258        );
9259        let done_q = action_question("r1", ask::ChoiceAction::Done);
9260        assert_eq!(
9261            decide_action(&t, &done_q, &PHRASES_EN, never),
9262            ActionDecision::Done
9263        );
9264        t.mark_action_applied(&done_q.id);
9265        assert_eq!(
9266            decide_action(&t, &done_q, &PHRASES_EN, never),
9267            ActionDecision::Skip
9268        );
9269
9270        // A plain answer (no action for that label) does nothing.
9271        let mut plain = action_question("r1", ask::ChoiceAction::Done);
9272        plain.actions.clear();
9273        assert_eq!(
9274            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
9275            ActionDecision::Skip
9276        );
9277        // A running task is left alone.
9278        let mut running = held_task_with("r1");
9279        running.status = TaskStatus::Running;
9280        assert_eq!(
9281            decide_action(
9282                &running,
9283                &action_question("r1", ask::ChoiceAction::Done),
9284                &PHRASES_EN,
9285                never
9286            ),
9287            ActionDecision::Skip
9288        );
9289    }
9290
9291    #[test]
9292    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
9293        let dir = tempfile::tempdir().unwrap();
9294        let queue = Queue::at(dir.path().join("queue"));
9295        let questions = Questions::at(dir.path().join("questions"));
9296        let home = dir.path().join("home");
9297        let mut state = run_state(RunStatus::Blocked);
9298        state.id = "20260101-000000-act1".to_owned();
9299        state.save_under(&home).unwrap();
9300
9301        let mut t = held_task_with(&state.id);
9302        queue.put(&mut t).unwrap();
9303        let mut q = action_question(&state.id, resume_action(&state.id));
9304        questions.put(&mut q).unwrap();
9305
9306        apply_choice_actions(&queue, &questions, &home);
9307        let after = queue.get(&t.id).unwrap();
9308        assert_eq!(after.status, TaskStatus::Queued);
9309        assert!(!after.fresh_start);
9310        assert!(after.action_applied(&q.id));
9311        let pin = after.resume_override.clone().unwrap();
9312        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
9313        assert!(pin.forced);
9314
9315        // Held again later: the same answer does not release it a second time.
9316        let mut again = queue.get(&t.id).unwrap();
9317        again.hold_machine(Some("later".into()));
9318        queue.put(&mut again).unwrap();
9319        apply_choice_actions(&queue, &questions, &home);
9320        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9321    }
9322
9323    #[test]
9324    fn a_delivered_answer_is_still_acted_on_exactly_once() {
9325        let dir = tempfile::tempdir().unwrap();
9326        let queue = Queue::at(dir.path().join("queue"));
9327        let questions = Questions::at(dir.path().join("questions"));
9328        let home = dir.path().join("home");
9329        let mut state = run_state(RunStatus::Blocked);
9330        state.id = "20260101-000000-act2".to_owned();
9331        state.save_under(&home).unwrap();
9332
9333        let mut t = held_task_with(&state.id);
9334        queue.put(&mut t).unwrap();
9335        let mut q = action_question(&state.id, resume_action(&state.id));
9336        q.answer_delivered = true;
9337        questions.put(&mut q).unwrap();
9338
9339        // Delivered, and the agent then died: the task is still held, so the
9340        // chosen action applies.
9341        apply_choice_actions(&queue, &questions, &home);
9342        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9343        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
9344
9345        // Held again: the same answer does nothing a second time.
9346        let mut again = queue.get(&t.id).unwrap();
9347        again.hold_machine(Some("later".into()));
9348        queue.put(&mut again).unwrap();
9349        apply_choice_actions(&queue, &questions, &home);
9350        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9351    }
9352
9353    #[test]
9354    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
9355        let dir = tempfile::tempdir().unwrap();
9356        let queue = Queue::at(dir.path().join("queue"));
9357        let questions = Questions::at(dir.path().join("questions"));
9358        let home = dir.path().join("home");
9359        let mut state = run_state(RunStatus::Blocked);
9360        state.id = "20260101-000000-act3".to_owned();
9361        state.save_under(&home).unwrap();
9362        let mut t = held_task_with(&state.id);
9363        queue.put(&mut t).unwrap();
9364        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
9365        questions.put(&mut q).unwrap();
9366
9367        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
9368        apply_choice_actions(&queue, &questions, &home);
9369        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9370
9371        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
9372        apply_choice_actions(&queue, &questions, &home);
9373        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9374    }
9375
9376    #[test]
9377    fn action_standing_tells_the_reasons_apart() {
9378        let mut t = held_task_with("r1");
9379        let q = action_question("r1", ask::ChoiceAction::Requeue);
9380        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
9381        let mut plain = q.clone();
9382        plain.actions.clear();
9383        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
9384
9385        // Applied wins over everything, even a running task.
9386        t.mark_action_applied(&q.id);
9387        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
9388
9389        // A newer attempt running: the old question is Stale, not Busy.
9390        let mut t = held_task_with("r1");
9391        t.start("r2".to_owned());
9392        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
9393        // The same question about the latest run just waits.
9394        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
9395        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
9396        t.status = TaskStatus::Blocked;
9397        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
9398
9399        // A conductor question is keyed by the task, never stale.
9400        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
9401        c.node = crate::conduct::NODE.to_owned();
9402        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
9403        assert!(!ActionStanding::Busy.daemon_owns());
9404    }
9405
9406    #[test]
9407    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
9408        let dir = tempfile::tempdir().unwrap();
9409        let queue = Queue::at(dir.path().join("queue"));
9410        let questions = Questions::at(dir.path().join("questions"));
9411        let home = dir.path().join("home");
9412        let mut state = run_state(RunStatus::Blocked);
9413        state.id = "20260101-000000-act4".to_owned();
9414        state.save_under(&home).unwrap();
9415        let mut t = held_task_with(&state.id);
9416        t.status = TaskStatus::Running;
9417        queue.put(&mut t).unwrap();
9418        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
9419        q.cwd = Some(dir.path().display().to_string());
9420        questions.put(&mut q).unwrap();
9421
9422        // While the task runs the daemon will not act, so the waiter still
9423        // delivers the word to the dead asker's seat ...
9424        let running = queue.get(&t.id).unwrap();
9425        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
9426        assert!(matches!(
9427            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
9428            crate::waiter::Action::Deliver(_)
9429        ));
9430        // ... and the daemon waits while the task runs, then applies once.
9431        apply_choice_actions(&queue, &questions, &home);
9432        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9433        let mut back = queue.get(&t.id).unwrap();
9434        back.hold_machine(Some("later".into()));
9435        queue.put(&mut back).unwrap();
9436        apply_choice_actions(&queue, &questions, &home);
9437        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
9438        let mut again = queue.get(&t.id).unwrap();
9439        again.hold_machine(Some("again".into()));
9440        queue.put(&mut again).unwrap();
9441        apply_choice_actions(&queue, &questions, &home);
9442        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9443    }
9444}