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, questions);
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            let mut cause = missing.clone();
707            cause.sort();
708            cause.dedup();
709            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
710            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
711                &task.blocked_by,
712                &missing,
713                &language,
714            )));
715            record(queue, &mut task);
716            continue;
717        }
718        // A conductor question nobody answered in time is retired by the
719        // waiter, and nothing else would ever move the task it blocks.
720        if let Some(q) = task.blocked_by.iter().find_map(|id| {
721            let crate::queue::Dependency::Question(full) =
722                crate::queue::dependency(queue, questions, id)
723            else {
724                return None;
725            };
726            questions.get(&full).ok().filter(|q| {
727                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
728            })
729        }) {
730            let language = language_of(&task, Path::new("."));
731            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
732            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
733            record(queue, &mut task);
734            continue;
735        }
736        let mut changed = false;
737        for id in task.blocked_by.clone() {
738            let resolved = crate::queue::dependency(queue, questions, &id);
739            if let crate::queue::Dependency::Task(full) = &resolved {
740                if queue
741                    .get(full)
742                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
743                {
744                    task.unblock(&id);
745                    changed = true;
746                }
747                continue;
748            }
749            if let crate::queue::Dependency::Question(full) = resolved
750                && let Ok(q) = questions.get(&full)
751                && q.status == ask::QuestionStatus::Answered
752            {
753                let answer = match &q.answer {
754                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
755                    None => String::new(),
756                };
757                task.record_answer(q.summary.clone(), answer);
758                task.unblock(&id);
759                changed = true;
760            }
761        }
762        if changed {
763            record(queue, &mut task);
764        }
765    }
766}
767
768/// The `hold_reason` of a task whose conductor question went unanswered.
769fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
770    if crate::lang::is_japanese(language) {
771        format!(
772            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
773            q.short(),
774            q.summary
775        )
776    } else {
777        format!(
778            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
779            q.short(),
780            q.summary
781        )
782    }
783}
784
785/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
786/// for several unrelated reasons, and the waiter must not read them alike.
787#[derive(Debug, Clone, Copy, PartialEq, Eq)]
788pub(crate) enum ActionStanding {
789    /// The answer carries no action: the waiter delivers it as before.
790    NoAction,
791    /// The daemon will apply it (not applied, task idle, current attempt).
792    Pending,
793    /// Already applied (`Task::actions_applied`): the daemon has acted, so
794    /// delivering the word to the old seat would run it beside the new work.
795    Applied,
796    /// The question is about an earlier attempt than the task's latest.
797    Stale,
798    /// The task is running / blocked / done: the daemon defers for now.
799    Busy,
800}
801
802impl ActionStanding {
803    /// The daemon has acted or will act: the waiter must not deliver.
804    pub(crate) fn daemon_owns(self) -> bool {
805        matches!(self, Self::Pending | Self::Applied | Self::Stale)
806    }
807}
808
809/// Classify `q`'s chosen action against `task`. `Stale` is judged before
810/// `Busy`: a question about an earlier attempt must be stopped even while a
811/// newer competition is running.
812pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
813    if q.chosen_action().is_none() {
814        ActionStanding::NoAction
815    } else if task.action_applied(&q.id) {
816        ActionStanding::Applied
817    } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
818        ActionStanding::Stale
819    } else if matches!(
820        task.status,
821        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
822    ) {
823        ActionStanding::Busy
824    } else {
825        ActionStanding::Pending
826    }
827}
828
829/// What [`decide_action`] concluded about one answered question.
830#[derive(Debug, Clone, PartialEq, Eq)]
831enum ActionDecision {
832    /// Nothing to do now (no action, already applied, or the task is busy).
833    Skip,
834    /// Continue the named run instead of competing again.
835    Resume(String),
836    /// Requeue as a fresh competition.
837    Requeue,
838    /// Close the task as done.
839    Done,
840    /// The question is about an earlier attempt than the task's latest; it
841    /// is recorded as handled and changes nothing.
842    Stale,
843    /// The action cannot be carried out; hold the task and say why. Never
844    /// falls back to something else, because the operator chose this one.
845    Refuse(String),
846}
847
848/// Decide what the choice answered on `q` means for `task`. Pure: `load`
849/// reads a run's state, as with [`unfinished_run_with`].
850///
851/// `Resume` only fires on the task's *latest* run, and only while that run
852/// could actually make progress ([`RunStatus::resumable`], not released, review
853/// budget left); an answer naming anything else is refused rather than
854/// reinterpreted as a fresh competition.
855fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
856where
857    F: FnOnce(&str) -> Result<RunState>,
858{
859    let Some(action) = q.chosen_action() else {
860        return ActionDecision::Skip;
861    };
862    if task.action_applied(&q.id)
863        || matches!(
864            task.status,
865            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
866        )
867    {
868        return ActionDecision::Skip;
869    }
870    // A question about an earlier attempt must not act on a newer one. A
871    // conductor question is keyed by the task id, not a run, so it is exempt.
872    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
873        return ActionDecision::Stale;
874    }
875    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
876    // Repair is an explicit new decision on an existing approval card. A
877    // manual hold before that answer must not discard it just because the
878    // card predates the hold. Keep the older policy for other choice actions.
879    let decision_at = if repair {
880        q.answered_at.unwrap_or(q.asked_at)
881    } else {
882        q.asked_at
883    };
884    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
885        return if repair {
886            ActionDecision::Refuse(format!(
887                "repair answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if repair is still wanted, explicitly release the existing owner with `magi task release {}`",
888                q.id, q.run, task.id
889            ))
890        } else {
891            ActionDecision::Stale
892        };
893    }
894    match action {
895        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
896        ask::ChoiceAction::Done => ActionDecision::Done,
897        ask::ChoiceAction::Resume { run } => {
898            if task.runs.last() != Some(run) {
899                return ActionDecision::Refuse((p.resume_not_latest)(
900                    q.short(),
901                    ask::short_id(run),
902                ));
903            }
904            match load(run) {
905                Ok(s)
906                    if q.node == land::APPROVAL_NODE
907                        && q.resolution().as_deref() == Some(land::REPAIR) =>
908                {
909                    if s.merge_repairs.iter().any(|r| r.question == q.id)
910                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
911                    {
912                        // A live/manual driver already consumed or superseded
913                        // this answer. Do not hold its fresh approval wait.
914                        ActionDecision::Stale
915                    } else if s.liveness(false) == Liveness::Live {
916                        ActionDecision::Skip
917                    } else if s.status != RunStatus::Landing
918                        || s.released()
919                        || !land::repair_available(&s)
920                        || !implementers_match(task, &s)
921                        || !s
922                            .land_approval
923                            .as_ref()
924                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
925                    {
926                        ActionDecision::Refuse(format!(
927                            "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
928                            q.id, run, run
929                        ))
930                    } else {
931                        ActionDecision::Resume(run.clone())
932                    }
933                }
934                Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
935                    ActionDecision::Resume(run.clone())
936                }
937                Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
938                    q.short(),
939                    ask::short_id(run),
940                )),
941                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
942                    q.short(),
943                    ask::short_id(run),
944                    &format!("{e:#}"),
945                )),
946            }
947        }
948    }
949}
950
951/// The fixed prose the daemon writes into [`Task::last_error`] and
952/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
953/// `triage::Wording` and `land::Words`: only English and Japanese are
954/// translated, anything else falls back to English.
955///
956/// Rendered when the reason is *generated*, so a reason keeps the language it
957/// was written in if the setting changes later. The notification frame
958/// (`Task <id> is held:`) is not here and stays English.
959///
960/// Deliberately **not** translated, because other code reads them back by
961/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
962/// and `gate red`. IDs, node names, paths and external error text are embedded
963/// as they are.
964struct Phrases {
965    /// `{}` = status label, then the detail.
966    graph_stopped: fn(&str, &str) -> String,
967    quorum_lost: &'static str,
968    /// Followed by the seats' names.
969    quota_took_out: &'static str,
970    /// Followed by the status label.
971    run_ended: &'static str,
972    /// Followed by the question's short id.
973    waiting_for_answer: &'static str,
974    recovered_running: &'static str,
975    no_run_to_recover: &'static str,
976    could_not_start: &'static str,
977    resume_not_latest: fn(&str, &str) -> String,
978    resume_cannot_progress: fn(&str, &str) -> String,
979    resume_unreadable: fn(&str, &str, &str) -> String,
980    /// A takeover refusal: the operator-facing text. English is the error's own
981    /// `Display`; a translation keeps the machine detail apart in parentheses.
982    handover_refused: fn(&crate::handover::Refused) -> String,
983    /// Appended to a refused handover's hold reason (leading space included).
984    handover_hint: &'static str,
985    /// (seats that never answered, review rounds) for the review loop's
986    /// "refusing to call it clean" stop.
987    reviewers_never_answered: fn(usize, usize) -> String,
988}
989
990const PHRASES_EN: Phrases = Phrases {
991    graph_stopped: |status, detail| {
992        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
993    },
994    quorum_lost: "the judging panel lost its quorum",
995    quota_took_out: "; quota took out ",
996    run_ended: "run ended ",
997    waiting_for_answer: " - waiting for operator answer to question ",
998    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
999    no_run_to_recover: "task was `running` with no live daemon and no readable \
1000                        run to recover; held for a human to check what happened",
1001    could_not_start: "could not start the run: ",
1002    resume_not_latest: |q, run| {
1003        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1004    },
1005    resume_cannot_progress: |q, run| {
1006        format!("question {q} asked to resume run {run}, which cannot make progress")
1007    },
1008    resume_unreadable: |q, run, e| {
1009        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1010    },
1011    handover_refused: |r| r.to_string(),
1012    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1013    reviewers_never_answered: |missing, rounds| {
1014        format!(
1015            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1016             refusing to call it clean"
1017        )
1018    },
1019};
1020
1021const PHRASES_JA: Phrases = Phrases {
1022    graph_stopped: |status, detail| {
1023        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1024    },
1025    quorum_lost: "審査パネルが定足数を失いました",
1026    quota_took_out: "。クォータで脱落: ",
1027    run_ended: "run 終了: ",
1028    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1029    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1030    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1031                        何が起きたか人が確認するため保留にしました",
1032    could_not_start: "run を開始できませんでした: ",
1033    resume_not_latest: |q, run| {
1034        format!(
1035            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1036        )
1037    },
1038    resume_cannot_progress: |q, run| {
1039        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1040    },
1041    resume_unreadable: |q, run, e| {
1042        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1043    },
1044    handover_refused: |r| {
1045        use crate::handover::Refused;
1046        match r {
1047            Refused::Foreign { branch, path, why } => format!(
1048                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1049                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1050                 から、やり直してください(詳細: {why})"
1051            ),
1052            Refused::Unsafe { branch, path, why } => format!(
1053                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1054                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1055                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1056            ),
1057            Refused::ReleaseFailed { branch, path, run } => format!(
1058                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1059                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1060                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1061            ),
1062        }
1063    },
1064    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1065    reviewers_never_answered: |missing, rounds| {
1066        format!(
1067            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1068             クリーンとは認めません"
1069        )
1070    },
1071};
1072
1073fn phrases(language: &str) -> &'static Phrases {
1074    if crate::lang::is_japanese(language) {
1075        &PHRASES_JA
1076    } else {
1077        &PHRASES_EN
1078    }
1079}
1080
1081/// The language of the repository a task belongs to, read best-effort for the
1082/// paths that have no run (and so no config of their own) to ask. An unreadable
1083/// config is English, not an error: a hold reason must still get written.
1084fn language_of(task: &Task, fallback: &Path) -> String {
1085    crate::lang::of_repo(&repo_for(task, fallback))
1086}
1087
1088/// The task an answered question speaks for: the one whose runs include the
1089/// question's run, or - for a conductor question, filed under the task's own
1090/// id - the task with that id.
1091pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1092    if q.node == crate::conduct::NODE {
1093        return tasks.iter().find(|t| t.id == q.run);
1094    }
1095    tasks.iter().find(|t| t.runs.contains(&q.run))
1096}
1097
1098/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1099///
1100/// Runs on every poll before the conductor looks at the queue. The task is
1101/// re-read under its claim, so a task somebody completed or held by hand in
1102/// the meantime is judged on what it is now. `Resume` releases the task and
1103/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1104/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1105/// ordinary `unfinished_run` logic resumes that same run.
1106pub(crate) fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1107    let tasks = queue.list();
1108    for q in questions.list() {
1109        if q.chosen_action().is_none() {
1110            continue;
1111        }
1112        let Some(listed) = task_of_question(&tasks, &q) else {
1113            if q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR) {
1114                notices::raise_in(
1115                    home,
1116                    Notice::warn(
1117                        &format!("repair-owner:{}", q.id),
1118                        format!(
1119                            "Repair is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing repair task.",
1120                            q.run, q.run
1121                        ),
1122                    ),
1123                );
1124            }
1125            continue;
1126        };
1127        if listed.action_applied(&q.id) {
1128            continue;
1129        }
1130        let Ok(_claim) = queue.claim(&listed.id) else {
1131            continue;
1132        };
1133        let Ok(mut task) = queue.get(&listed.id) else {
1134            continue;
1135        };
1136        let language = language_of(&task, Path::new("."));
1137        let decision = decide_action(&task, &q, phrases(&language), |id| {
1138            RunState::load_under(id, home)
1139        });
1140        let ran = matches!(
1141            decision,
1142            ActionDecision::Resume(_) | ActionDecision::Requeue | ActionDecision::Done
1143        );
1144        if ran && asker_may_still_read(questions, &q, home) {
1145            // The asking process or its seat can still take the word; act
1146            // once it has gone quiet. Bound on the remaining window: the
1147            // check is not atomic with the write below, so an asker that
1148            // takes the word in between (at most one poll, never more than
1149            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1150            // and `Task::actions_applied` under the claim keeps the action to
1151            // one application. The waiter does not deliver an answer that
1152            // carries an action (`waiter::decide_owned`), so it cannot race.
1153            continue;
1154        }
1155        let done = matches!(decision, ActionDecision::Done);
1156        match decision {
1157            ActionDecision::Skip => continue,
1158            ActionDecision::Resume(run) => {
1159                task.release_operator("choice", Some(&q.id));
1160                task.resume_override = Some(crate::queue::OperatorResume {
1161                    question_id: q.id.clone(),
1162                    at: Timestamp::now(),
1163                    conductor_rehold: None,
1164                    forced: true,
1165                    pinned_run: Some(run),
1166                });
1167            }
1168            ActionDecision::Stale => {}
1169            ActionDecision::Requeue => {
1170                task.release_operator("choice-requeue", Some(&q.id));
1171                task.requeue();
1172            }
1173            ActionDecision::Done => task.succeed(),
1174            ActionDecision::Refuse(why) => {
1175                if task.operator_held() {
1176                    // A rejected answer does not release the operator's hold
1177                    // or reclassify it as recoverable by the conductor.
1178                    task.hold_reason = Some(match task.hold_reason.take() {
1179                        Some(reason) => format!("{reason}\n\n{why}"),
1180                        None => why,
1181                    });
1182                } else {
1183                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1184                    task.hold_machine(Some(why));
1185                }
1186                notices::raise(
1187                    Notice::warn(
1188                        &format!("action:{}", q.id),
1189                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1190                    )
1191                    .link(Link::Task {
1192                        id: task.id.clone(),
1193                    }),
1194                );
1195            }
1196        }
1197        task.mark_action_applied(&q.id);
1198        // The applied id travels with the transition, so a failed save loses
1199        // neither and the answer is acted on at the next poll.
1200        record(queue, &mut task);
1201        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1202            supersede_prior_runs(&task, home);
1203        }
1204        // Delivery is only a note of who has read the answer; the task's own
1205        // mark above is the authority. Best effort.
1206        let _ = questions.update(&q.id, |r| {
1207            r.answer_delivered = true;
1208            Ok(())
1209        });
1210    }
1211}
1212
1213/// Whether something may still read the answer to `q`: a fresh lease, or the
1214/// asking seat still listed as active in its run (its CLI can outlive the
1215/// `magi ask` that was killed).
1216fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1217    let now = Timestamp::now();
1218    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1219        return true;
1220    }
1221    q.node != crate::conduct::NODE
1222        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1223            s.seats_active()
1224                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1225        })
1226}
1227
1228/// Retire an unanswered conductor question after its task no longer refers to
1229/// it. Conductor questions use the task id in `Question::run`, so run-based
1230/// cleanup cannot observe a manual release or completion.
1231///
1232/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1233/// own question also carries a `run`, and a run id that happens to collide
1234/// with some task's id is not this loop's business — only a conductor
1235/// question actually uses the task id that way. One `Questions::list()` scan
1236/// is taken up front and matched against the in-memory task set, rather than
1237/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1238fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1239    let tasks = queue.list();
1240    let by_id: std::collections::BTreeMap<&str, &Task> =
1241        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1242    let referenced: Vec<&str> = tasks
1243        .iter()
1244        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1245        .collect();
1246
1247    for mut question in questions.list() {
1248        if !question.status.open() || question.node != crate::conduct::NODE {
1249            continue;
1250        }
1251        // Keep questions a task still names, including when the reference
1252        // moved to a dependent task.
1253        // Preserve even ambiguous references: retiring a possibly referenced
1254        // question is unsafe until the operator disambiguates it.
1255        if referenced
1256            .iter()
1257            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1258        {
1259            continue;
1260        }
1261        let Some(task) = by_id.get(question.run.as_str()) else {
1262            continue;
1263        };
1264        question.abandon(format!(
1265            "task {} no longer waits for this answer",
1266            task.short()
1267        ));
1268        if let Err(e) = questions.put(&mut question) {
1269            tracing::warn!(
1270                "could not retire question {} for task {}: {e:#}",
1271                question.short(),
1272                task.short()
1273            );
1274        }
1275    }
1276}
1277
1278/// What a finished run tells the queue about the task it came from.
1279///
1280/// A struct rather than a fourth and fifth boolean argument: the two flags
1281/// answer different questions about the same run, and a call site passing
1282/// `(…, true, false)` is one transposition away from refunding attempts
1283/// forever.
1284#[derive(Debug, Clone, Copy)]
1285pub struct Verdict {
1286    /// Where the graph stopped.
1287    pub status: RunStatus,
1288    /// The run opened a pull request.
1289    pub left_pr: bool,
1290    /// At least one seat was lost to a rate limit.
1291    pub quota_hit: bool,
1292    /// The run parked at a node boundary because it was asked to.
1293    pub parked: bool,
1294    /// The run never produced a single candidate a judge could look at.
1295    ///
1296    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1297    /// still have another candidate worth judging, in which case the loss was
1298    /// not the reason nothing came of the run. This is `true` only when the
1299    /// implement wave ended with nothing viable at all.
1300    pub no_viable_candidates: bool,
1301}
1302
1303/// Record a finished run against the task it came from.
1304///
1305/// Kept pure and separate from the loop because this mapping *is* the retry
1306/// policy, and a policy that can only be exercised by spawning a graph is a
1307/// policy nobody checks. The table:
1308///
1309/// | run status                           | task becomes        | attempt spent |
1310/// |---------------------------------------|---------------------|---------------|
1311/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1312/// | `Merged`, `Ready`                      | `Done`               | yes          |
1313/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1314/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1315/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1316/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1317/// | `Blocked` with a PR                    | `Held`               | yes          |
1318/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1319/// | `VerifiedNoop`                          | `Held`               | yes          |
1320/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1321///
1322/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1323/// deliberately: every candidate agreeing there is nothing to write is not a
1324/// machine fact about a rate limit, it is an unverified claim about the
1325/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1326/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1327/// claim could be wrong (a misread instruction, a stale check), and closing
1328/// the task automatically on an implementer's say-so would be the exact
1329/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1330/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1331/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1332/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1333/// claim regardless of whether the one already-spent attempt is refunded, and
1334/// [`Task::release`] resets the count to zero anyway the moment a human looks
1335/// at the evidence and lets it run again.
1336///
1337/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1338/// twice, together. A quorum lost to rate limits is a property of the machine
1339/// and not of the task, so the attempt is refunded and a reset quota picks
1340/// the work up where it stopped — and that is just as true when every
1341/// implement seat lost the same race and `after_implement` bails with nothing
1342/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1343/// machine fact. The `no_viable_candidates` guard is what keeps that row
1344/// narrow: a `Failed` run that produced a real candidate which then lost for
1345/// some other reason still spends the attempt, exactly like the quorum lost
1346/// to judges that answered with the wrong shape is ordinary flakiness, and
1347/// refunding *that* takes the bound off the retry loop entirely: run e633
1348/// stalled with `quota: []` after two judges wrote unusable JSON, was
1349/// refunded, and the next attempt paid for a fresh hour-long implement wave
1350/// before it could fail the same way. `max_attempts` exists precisely so
1351/// that cannot repeat forever.
1352///
1353/// A non-terminal status means `execute` returned while the graph was still
1354/// mid-flight, which is a bug rather than a verdict; it is treated as a
1355/// failure so that a task cannot loop on it either.
1356///
1357/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1358/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1359pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1360    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1361}
1362
1363/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1364fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1365    // A parked run is the operator's own doing, and its work is intact on
1366    // disk. The task goes back in line with its attempt refunded so the next
1367    // loop resumes the same run - which `one_task` prefers over competing
1368    // again - and so that swapping the binary a few times cannot exhaust a
1369    // budget meant for agents that actually misbehaved.
1370    if verdict.parked {
1371        task.park(detail);
1372        return;
1373    }
1374    match verdict.status {
1375        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1376        RunStatus::AlreadyInBase => task.already_landed(detail),
1377        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1378        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1379            task.stall(detail)
1380        }
1381        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1382        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1383        RunStatus::Blocked => task.fail(detail, max_attempts),
1384        RunStatus::VerifiedNoop => task.handed_off(detail),
1385        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1386    }
1387}
1388
1389/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1390/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1391/// itself has actually finished *and* its own last attempt is provably why:
1392/// this loads that run and requires `Merged`/`Ready` before touching
1393/// anything earlier in `runs`, since `Task::succeed` can also be called
1394/// directly on a task whose last attempt never landed at all.
1395///
1396/// Called right after whatever call set `task.status` to
1397/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1398/// `reclaim`'s, but also every other place a task can be closed by hand
1399/// without the loop ever settling it itself: `magi task done`
1400/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1401/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1402/// GitHub merge, say, exactly the workflow this repository's own
1403/// "Landing a run's winner by hand" documents — is just as much "this task's
1404/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1405/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1406/// forever, which is the exact backlog this status exists to clear. `pub`
1407/// for those two out-of-module callers; everything else about this stays
1408/// internal bookkeeping.
1409///
1410/// A run something is still actually driving is left alone: a
1411/// task cannot be `Done` while one of its *own* attempts is still in flight,
1412/// so a live one at this point can only be an unrelated process — a manual
1413/// `--resume` of this old, now-moot run — and rewriting under it would just
1414/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1415/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1416/// pair `run_report`/`run_detail` use for the same question elsewhere:
1417/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1418/// --resume` invoked by hand outside it, which `liveness` also checks via
1419/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1420/// (already terminal in some other way, or itself mid-run) is left untouched
1421/// too.
1422///
1423/// Best-effort, like the rest of this module's bookkeeping: a load or save
1424/// failure here is a `tracing::warn`, not a failed settle, and the next time
1425/// this same task's completion is recorded — or a daemon restart replays
1426/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1427/// separate reconciliation pass; if that gap ever matters in practice, one
1428/// can be added then.
1429///
1430/// `home` is a parameter, not the process-global [`crate::run::home`], for
1431/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1432/// calls this with `ui.home`, which is `crate::run::home()` in a real
1433/// process but a fixture's own directory under test — falling through to
1434/// the global there would read and write through whichever home some other
1435/// test in the same binary happened to pin into that `OnceLock` first, not
1436/// the run this call actually means.
1437pub fn supersede_prior_runs(task: &Task, home: &Path) {
1438    let now = Timestamp::now();
1439    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1440    // right behind a `Merged`/`Ready` verdict) from one set directly by
1441    // `magi task done`/its web equivalent/the conductor on a task whose last
1442    // recorded attempt never actually landed - that requires reading the
1443    // run itself, which is exactly what this does before trusting anything
1444    // in `runs` is safe to relabel.
1445    let last_run_succeeded = task
1446        .runs
1447        .last()
1448        .and_then(|id| RunState::load_under(id, home).ok())
1449        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1450    for id in task.superseded_attempts(last_run_succeeded) {
1451        let mut state = match RunState::load_under(id, home) {
1452            Ok(s) => s,
1453            Err(e) => {
1454                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1455                continue;
1456            }
1457        };
1458        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1459            continue;
1460        }
1461        let daemon_claims = is_working_on(home, id, now);
1462        if state.liveness(daemon_claims) == Liveness::Live {
1463            continue;
1464        }
1465        state.status = RunStatus::Superseded;
1466        if let Err(e) = state.save_under(home) {
1467            tracing::warn!("could not mark run {id} superseded: {e:#}");
1468        }
1469    }
1470}
1471
1472/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1473/// finish the moment it was called, because one of its earlier attempts was
1474/// still live then - a `magi run --resume` invoked by hand on an old run,
1475/// most likely.
1476///
1477/// That skip is correct at the time (rewriting under a run something is
1478/// still actively saving would just be undone), but a task only ever
1479/// reaches `Done` once, so without this nothing would ever look at it
1480/// again: if that manual process later ends anywhere other than
1481/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1482/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1483/// backlog this status exists to clear. Called on the same idle-only
1484/// cadence as [`janitor`], next to it rather than folded into it: this
1485/// walks `queue` and `janitor` never otherwise needs one.
1486///
1487/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1488/// more than one attempt, every pass: each call is a handful of local file
1489/// reads bounded by that task's own attempt count, the same order of cost
1490/// [`clean::fold_due`] already pays scanning every run on disk on the same
1491/// cadence, and a task already fully resolved costs one failed liveness
1492/// check turned no-op the moment its lingering attempt is no longer live.
1493fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1494    for task in queue.list() {
1495        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1496            continue;
1497        }
1498        supersede_prior_runs(&task, home);
1499    }
1500}
1501
1502/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1503/// task ends up held.
1504///
1505/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1506/// dead daemon never got back to) share this, so the two cannot drift into
1507/// disagreeing about which held tasks get a diagnostic.
1508fn settle_and_diagnose(
1509    task: &mut Task,
1510    verdict: Verdict,
1511    detail: &str,
1512    max_attempts: usize,
1513    state: &RunState,
1514) {
1515    let p = phrases(&state.config.graph.language);
1516    let attempts_before = task.attempts;
1517    // A run that stopped because a shared resource stayed busy was never a
1518    // failure of the task or of any agent: nothing was asked. The attempt is
1519    // refunded and the task is held by the machine, under a reason `triage`
1520    // can re-check, so the same run resumes with the same agents once the
1521    // resource is free. A park request still wins (it is the operator's).
1522    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1523        task.notice_cause(
1524            &format!("resource:{}:{}", block.kind, block.node),
1525            None,
1526            None,
1527        );
1528        task.last_error = Some(detail.to_owned());
1529        task.diagnostic = None;
1530        task.attempts = task.attempts.saturating_sub(1);
1531        task.hold_machine(Some(format!(
1532            "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1533             no agent was asked and no attempt was spent",
1534            crate::cache::RESOURCE_HOLD,
1535            block.kind,
1536            block.node
1537        )));
1538        if let Some(pass) = state.passes.last() {
1539            task.record_pass(&state.id, pass.index, attempts_before, None);
1540        }
1541        return;
1542    }
1543    let unresolved = task.hold_notice_cause.clone();
1544    settle_in(task, verdict, detail, max_attempts, p);
1545    if state.prep_failure.is_some() {
1546        // Minting a run whose candidates could not be prepared is not work
1547        // on a newly approved attempt. Keep the unresolved outcome anchor.
1548        task.hold_notice_cause = unresolved;
1549        task.startup_notice_cause("startup-candidates");
1550    }
1551    // Written here, where the refund (or not) is decided, so the history is a
1552    // fact and not a later guess from the run's status.
1553    if let Some(pass) = state.passes.last() {
1554        let parked = match &pass.end {
1555            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
1556            _ => None,
1557        };
1558        task.record_pass(&state.id, pass.index, attempts_before, parked);
1559    }
1560    if task.status == TaskStatus::Held {
1561        if state.prep_failure.is_none() {
1562            task.notice_cause(
1563                label(verdict.status),
1564                Some(&state.id),
1565                state.passes.last().map(|p| p.index),
1566            );
1567        }
1568        task.diagnostic = diagnostic(state);
1569        note_open_question(task, &state.id, p);
1570    }
1571}
1572
1573/// If `task` is held with a `magi ask` question still open on `run`, name the
1574/// question in [`Task::hold_reason`] rather than leaving the hold reading
1575/// only [`describe`]'s run summary.
1576///
1577/// This is the shape task 20260928-191407-05fd left underspecified: an
1578/// implementer settled a verified no-op and filed a question for the
1579/// operator, and the hold that followed said nothing about the question
1580/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
1581/// existing text ([`is_disk_hold`](crate::triage), the answered-question
1582/// marker) and must keep seeing it unchanged.
1583///
1584/// Best-effort: an unreadable question store must not stop a run from
1585/// settling, so this is a no-op rather than a propagated error when
1586/// [`crate::run::try_home`] has nothing to offer or the store is empty.
1587fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
1588    let Some(home) = crate::run::try_home() else {
1589        return;
1590    };
1591    let open = Questions::at(home.join("questions")).open_for(run);
1592    let Some(q) = open.first() else {
1593        return;
1594    };
1595    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
1596    decisions.sort_unstable();
1597    task.notice_cause(
1598        &format!("questions:{}", decisions.join(",")),
1599        Some(run),
1600        None,
1601    );
1602    let base = task.hold_reason.clone().unwrap_or_default();
1603    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
1604}
1605
1606/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
1607/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
1608/// by some other means entirely, like a manual `magi run` resume that
1609/// finishes the graph outside the queue's bookkeeping.
1610///
1611/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
1612/// `settle` is separate from `attempt`: a task recovered this way must land
1613/// exactly where a live daemon would have put it — the same policy table,
1614/// not a second one that quietly drifts from it — and that is only checkable
1615/// without spawning a real run.
1616fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
1617    match last_run {
1618        Some(state) => {
1619            let verdict = Verdict {
1620                status: state.status,
1621                left_pr: state.pr.is_some(),
1622                quota_hit: !state.quota.is_empty(),
1623                parked: state.parked,
1624                no_viable_candidates: state.viable().is_empty(),
1625            };
1626            let detail = format!(
1627                "{}{}",
1628                phrases(&state.config.graph.language).recovered_running,
1629                describe(&state)
1630            );
1631            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1632        }
1633        None => {
1634            // No run, so no config of its own: `language` is the task's
1635            // repository's setting, read by the caller.
1636            let why = phrases(language).no_run_to_recover;
1637            task.last_error = Some(why.to_owned());
1638            // The phone shows `hold_reason`, so a task held by the machine
1639            // says why there too and not only in `last_error`.
1640            task.notice_cause("missing-run", None, None);
1641            task.hold_machine(Some(why.to_owned()));
1642        }
1643    }
1644}
1645
1646/// Find every task left at `running` that no live process is actually
1647/// driving, and settle each one against whatever its last run became.
1648///
1649/// # Why a claim is proof, not a guess
1650///
1651/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
1652/// `running`, and the guard is held for the task's whole time in that status:
1653/// `attempt` does not return, and the loop does not move past the scope
1654/// holding the claim, until the run has settled. So a `running` task whose
1655/// lock is gone cannot have a live owner — this process or any other —
1656/// without needing a staleness threshold or a pid check the way
1657/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
1658/// task that never got as far as `running` at all. Taking the claim here is
1659/// the whole test: it either fails, because something really does hold it
1660/// and the task is left alone, or it succeeds, which is the proof — and it is
1661/// kept for the rest of the decision so nothing else can start a competing
1662/// run while this one is being written.
1663///
1664/// Called on every poll, not only at startup, for the reason
1665/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
1666/// keep noticing this, not only on the one morning it happened to restart.
1667fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1668    let mut reclaimed = Vec::new();
1669    for listed in queue.list() {
1670        if listed.status != TaskStatus::Running {
1671            continue;
1672        }
1673        let Ok(_claim) = queue.claim(&listed.id) else {
1674            continue;
1675        };
1676        // Re-read under the claim: a release or an edit landed by a human
1677        // between the listing above and the claim just taken must not be
1678        // clobbered by a decision based on the stale copy.
1679        let Ok(mut task) = queue.get(&listed.id) else {
1680            continue;
1681        };
1682        if task.status != TaskStatus::Running {
1683            continue;
1684        }
1685        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1686        // `execute` normally abandons a run's own open questions the moment
1687        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
1688        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
1689        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
1690        // with the question still `open`, because the process died before
1691        // reaching that call. `reclaim` itself stays pure on purpose (see its
1692        // own doc), so the same cleanup runs here instead, against the run
1693        // this reclaim is already reading. `settle_run` costs nothing when
1694        // `execute` already got there first.
1695        if let Some(state) = &last_run
1696            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1697        {
1698            tracing::warn!("abandon questions for {}: {e:#}", state.id);
1699        }
1700        let language = if last_run.is_none() {
1701            language_of(&task, Path::new("."))
1702        } else {
1703            String::new()
1704        };
1705        reclaim(&mut task, last_run, max_attempts, &language);
1706        if task.status == TaskStatus::Done {
1707            supersede_prior_runs(&task, &crate::run::home());
1708        }
1709        record(queue, &mut task);
1710        reclaimed.push(task.id.clone());
1711    }
1712    reclaimed
1713}
1714
1715/// Find every run whose `run.json` is provably dead — every seat it still
1716/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
1717/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
1718/// not merely "no daemon claims it" — and fail it, clearing the leftover
1719/// active seats so the run stops reading as `implementing` (or whichever
1720/// node) forever.
1721///
1722/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
1723/// `running`, using whatever `run.json` already says — but nothing in that
1724/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
1725/// stays pure on purpose, see its own doc), so a `run.json` a killed process
1726/// never got back to sits exactly where it was left: `active` full of seats
1727/// nobody will ever answer for, `status` stuck on whatever node was in
1728/// flight. `magi show` already tells an operator this in prose (`no live
1729/// daemon claims this run right now`); this is what makes that fact durable
1730/// on disk, the same way a task's own `TaskStatus::Running` does not get to
1731/// stay stuck once nothing is driving it.
1732///
1733/// Runs on every poll, not only at startup, for the reason
1734/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
1735/// daemon up for days must keep noticing a run some other, now-dead, daemon
1736/// left behind just as readily as one it trips over on the way up.
1737///
1738/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
1739/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
1740/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
1741/// `runs` directory instead: `home` here is a parameter precisely so a test
1742/// can point it away from the operator's real history (see [`drive`]'s own
1743/// doc), and a scan that fell through to the global home anyway would walk
1744/// whichever directory some *other* process or test pinned into that
1745/// `OnceLock` first — mutating runs this call was never handed.
1746fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1747    reclaim_abandoned_runs_with(
1748        home,
1749        now,
1750        crate::proc::pid_status,
1751        crate::proc::process_started_at,
1752    )
1753}
1754
1755/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
1756/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
1757/// for the identical reason: this sweep's real damage (wiping a run's active
1758/// seats and failing it) has to be provable against an injected answer in a
1759/// test, not just the real process table.
1760fn reclaim_abandoned_runs_with<F, G>(
1761    home: &Path,
1762    now: Timestamp,
1763    query: F,
1764    identity: G,
1765) -> Vec<String>
1766where
1767    F: Fn(u32) -> Option<bool>,
1768    G: Fn(u32) -> Option<String>,
1769{
1770    let mut abandoned = Vec::new();
1771    for entry in std::fs::read_dir(home.join("runs"))
1772        .into_iter()
1773        .flatten()
1774        .flatten()
1775    {
1776        let id = entry.file_name().to_string_lossy().into_owned();
1777        if !crate::run::is_run_id(&id) {
1778            continue;
1779        }
1780        // Unreadable is `clean::fold_due`'s problem, not this one's — see
1781        // that module's docs for why a run this cannot parse is left alone
1782        // rather than guessed at. A different schema number is not that: this
1783        // touches only `status` and `active`, never a field whose meaning a
1784        // schema bump changed, so an old record's values serve this exactly
1785        // as well as a current one's (see `clean::read_state`'s own doc for
1786        // the same reasoning applied to folding).
1787        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1788            continue;
1789        };
1790        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1791            continue;
1792        };
1793        if state.status.done() || !state.active_all_overrun(now) {
1794            continue;
1795        }
1796        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
1797        // it", which is also the normal, healthy shape of a manual `magi
1798        // run` / `magi review` sharing this same home — this scan walks
1799        // every run on disk, not only ones this daemon itself started. Such
1800        // a run's active seats can legitimately sit past their own timeout
1801        // for a little while (the CLI finishing up, its result still being
1802        // collected) without the process driving it having died. `liveness`
1803        // is what actually tells the two apart, by corroborating
1804        // `driver_pid` against the process it names — see its own doc. Only
1805        // its strongest, provable answer licenses wiping this run's active
1806        // seats and failing it out from under whatever is still running it.
1807        let daemon_claims = is_working_on(home, &id, now);
1808        if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1809            continue;
1810        }
1811        state.abandon("daemon");
1812        if let Err(e) = state.save_under(home) {
1813            tracing::warn!("could not persist abandoned run {id}: {e:#}");
1814            continue;
1815        }
1816        // This run never passes through `Runner::execute` again, so its end
1817        // is announced here.
1818        if let Some(notice) = notices::run_ended(&state) {
1819            notices::raise_in(home, notice);
1820        }
1821        // The seat that asked is gone for good now, exactly like any other
1822        // door `graph::Runner::settle_questions` closes the moment `status`
1823        // lands somewhere non-resumable - see that method's own doc. Nothing
1824        // else reaches this one before the next `janitor()` startup pass
1825        // (`clean::abandon_settled_questions`), and a daemon that stays up
1826        // for days must not leave an open question badging the operator
1827        // until it happens to restart.
1828        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1829            tracing::warn!("abandon questions for {id}: {e:#}");
1830        }
1831        abandoned.push(id);
1832    }
1833    abandoned
1834}
1835
1836/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
1837///
1838/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
1839/// sets, so there is one loop body rather than two that drift apart the first
1840/// time the retry policy changes on only one of them.
1841pub async fn serve(opts: Opts) -> Result<()> {
1842    serve_until(opts, Stop::new()).await
1843}
1844
1845/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
1846///
1847/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
1848/// mid-node leaves worktrees, branches and agent sessions behind, and every
1849/// agent call already paid for is lost; finishing the run costs the operator a
1850/// wait and saves them a cleanup. A stop therefore only sets a flag: the
1851/// current `execute` runs to its terminal status, the task's outcome is
1852/// recorded, and only then does the loop return. That window is what
1853/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
1854/// still has a second Ctrl-C, which the runtime turns into a process kill —
1855/// and the task left `Running` then tells the next daemon, and the next human,
1856/// where to look.
1857///
1858/// While the queue is empty the stop is honoured within one wakeup rather than
1859/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
1860/// caller that taps stop does not sit through the remainder of a sleep.
1861pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1862    let signal = {
1863        let stop = stop.clone();
1864        tokio::spawn(async move {
1865            if tokio::signal::ctrl_c().await.is_ok() {
1866                stop.stop();
1867                tracing::info!("shutdown requested; a run in flight will be finished first");
1868            }
1869        })
1870    };
1871
1872    let worktrees_root = opts
1873        .worktrees_root
1874        .clone()
1875        .unwrap_or_else(crate::run::default_worktree_root);
1876    let outcome = drive(
1877        &opts,
1878        &Queue::open(),
1879        &status_path(),
1880        &crate::run::home(),
1881        &worktrees_root,
1882        &stop,
1883    )
1884    .await;
1885
1886    signal.abort();
1887    outcome
1888}
1889
1890/// The loop proper: setup, poll, teardown, with the queue and the status file
1891/// supplied rather than discovered.
1892///
1893/// All three of `home`, `worktrees_root` and the queue/status paths are
1894/// parameters rather than resolved here, for the same reason:
1895/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
1896/// so a unit test that pinned it would fight every other test in the binary,
1897/// and a loop that resolved its own worktree bay could only be exercised
1898/// against the operator's real `~/wt/<repo>` - publishing over a live
1899/// daemon's status file, claiming tasks out of a live backlog, and, since
1900/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
1901/// whatever the operator actually has on disk.
1902async fn drive(
1903    opts: &Opts,
1904    queue: &Queue,
1905    status_file: &Path,
1906    home: &Path,
1907    worktrees_root: &Path,
1908    stop: &Stop,
1909) -> Result<()> {
1910    // The status file is a *snapshot*, not a stream of events: a reader only
1911    // ever wants the latest values, and every tick rewrites the whole file
1912    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
1913    // while an mpsc channel would force the loop to re-send unchanged fields on
1914    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
1915    // for no gain. The lock is only ever held across a field assignment, never
1916    // across an await.
1917    let status = Arc::new(Mutex::new(Status::new()));
1918    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1919    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1920
1921    // Read once at startup, not per task: how many runs this loop drives at
1922    // once is a property of the machine running it, not of whichever
1923    // repository a given task happens to name - see
1924    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
1925    // fact in the same sense the agent roster is.
1926    let daemon_cfg = prepare(&opts.repo, opts)
1927        .map(|c| c.daemon)
1928        .unwrap_or_default();
1929    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1930
1931    // Something has to be waiting on every question for as long as it is open,
1932    // whether or not the agent's own `magi ask` survived. Its own task rather
1933    // than a step of the poll loop: the poll loop is busy for the whole of a
1934    // run, and an owner's reply must not queue behind one.
1935    let waiter = tokio::spawn(crate::waiter::run(
1936        crate::waiter::Waiter::new(
1937            crate::ask::Questions::at(home.join("questions")),
1938            home.to_path_buf(),
1939            prepare(&opts.repo, opts).ok(),
1940        ),
1941        stop.clone(),
1942    ));
1943
1944    // The follow-up seats for the conductor's questions: the conductor files a
1945    // question and moves on, and each open one gets a deputy that reads the
1946    // owner's reply. Its own task for the same reason the waiter's is.
1947    let deputies = tokio::spawn(crate::deputy::run(
1948        crate::deputy::Deputies::new(
1949            crate::ask::Questions::at(home.join("questions")),
1950            home.to_path_buf(),
1951            prepare(&opts.repo, opts).ok(),
1952            opts.repo.clone(),
1953            daemon_cfg.max_deputies,
1954            {
1955                let stop = stop.clone();
1956                Arc::new(move || stop.parking())
1957            },
1958        ),
1959        stop.clone(),
1960    ));
1961
1962    // Keeps every checkout's origin/main fresh; its own task so a slow remote
1963    // never holds up the poll loop.
1964    let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
1965
1966    // Watches the release-bump pull requests until they land; its own task, not
1967    // tied to any run, because a pending bump outlives the run that opened it.
1968    let release_watch = tokio::spawn(crate::release_watch::run(
1969        crate::release_watch::Watcher::new(
1970            Box::new(crate::release_watch::GhForge),
1971            home.to_path_buf(),
1972        ),
1973        {
1974            let (repo, opts) = (opts.repo.clone(), opts.clone());
1975            move || release_watch_settings(&repo, &opts)
1976        },
1977        stop.clone(),
1978    ));
1979
1980    tracing::info!(
1981        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1982        queue.root().display(),
1983        opts.poll.as_secs(),
1984        opts.max_attempts,
1985        concurrency,
1986        if daemon_cfg.pause_for_interrupts {
1987            ", interrupts enabled"
1988        } else {
1989            ""
1990        }
1991    );
1992
1993    // `--once` drains an already-idle queue without reaching the idle wait,
1994    // but must still perform the startup cleanup.
1995    janitor(&opts.repo, opts, home, worktrees_root).await;
1996    resweep_superseded_attempts(queue, home);
1997
1998    let outcome = poll(
1999        opts,
2000        queue,
2001        &status,
2002        home,
2003        worktrees_root,
2004        stop,
2005        DispatchLimits {
2006            max_concurrent: concurrency,
2007            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2008        },
2009    )
2010    .await;
2011
2012    beat.abort();
2013    waiter.abort();
2014    deputies.abort();
2015    fetcher.abort();
2016    release_watch.abort();
2017    clear_status_at(status_file);
2018    outcome
2019}
2020
2021/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2022/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2023fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2024    let Ok(cfg) = prepare(repo, opts) else {
2025        return (Vec::new(), 0);
2026    };
2027    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2028        .into_iter()
2029        .map(|r| r.path)
2030        .collect();
2031    // Repositories the daemon has worked in, wherever they live: a task may
2032    // name one outside `[repos] roots`, and its release PR must be watched too.
2033    let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2034    let runs = crate::run::home().join("runs");
2035    for id in crate::run::list_ids_in(&runs) {
2036        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2037            .ok()
2038            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2039            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2040        known.extend(repo);
2041    }
2042    for k in known {
2043        let k = k.canonicalize().unwrap_or(k);
2044        if k.join(".git").exists() && !paths.contains(&k) {
2045            paths.push(k);
2046        }
2047    }
2048    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2049    if !paths.contains(&own) {
2050        paths.push(own);
2051    }
2052    (paths, cfg.daemon.release_stall_minutes)
2053}
2054
2055/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2056const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2057
2058/// Run [`crate::clean::fetch_origins`] every `[repos] fetch_interval` seconds
2059/// until `stop`. The config is re-read each lap; `0` (or an unreadable config)
2060/// disables the fetch for that lap. Never fails.
2061async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2062    while !stop.stopped() {
2063        let (interval, roots) = match prepare(&repo, &opts) {
2064            Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2065            Err(_) => (0, Vec::new()),
2066        };
2067        if interval > 0 && !roots.is_empty() {
2068            let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2069            tracing::debug!("fetch origins: {r:?}");
2070        }
2071        // Sleep in slices so a stop or a config change is noticed promptly.
2072        let wait = if interval > 0 { interval } else { 60 };
2073        let mut slept = 0;
2074        while slept < wait && !stop.stopped() {
2075            tokio::time::sleep(Duration::from_secs(1)).await;
2076            slept += 1;
2077        }
2078    }
2079}
2080
2081/// Refresh the status file on a fixed tick.
2082///
2083/// Separate from the loop because a run takes tens of minutes: a status file
2084/// written only between tasks would look stale for the whole of every run, and
2085/// a reader would report the daemon dead exactly while it was busiest.
2086async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2087    loop {
2088        tokio::time::sleep(HEARTBEAT).await;
2089        let snapshot = {
2090            let mut guard = lock(&status);
2091            guard.updated_at = Timestamp::now();
2092            guard.clone()
2093        };
2094        if let Err(e) = write_status_to(&path, &snapshot) {
2095            // A failed heartbeat must not take the daemon down: the loop is the
2096            // product, the status file is only the window onto it.
2097            tracing::warn!("could not refresh the daemon status file: {e:#}");
2098        }
2099    }
2100}
2101
2102/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2103/// if so, whether that wait is over.
2104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2105enum LandResume {
2106    /// The task's last run is not parked on a land approval; schedule it
2107    /// like any other candidate.
2108    NotLanding,
2109    /// Parked in `land`, waiting on a question nobody has answered yet.
2110    /// Left alone: attempting it now would only re-observe the same pull
2111    /// request and park again, spending a `gh` call on a decision that has
2112    /// not changed since the last time this was checked.
2113    StillWaiting,
2114    /// Parked in `land`, and the question is settled - answered or
2115    /// abandoned. Resuming this is the one kind of candidate that must not
2116    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2117    Ready,
2118}
2119
2120/// Classify a runnable candidate by whether it is parked on a land-merge
2121/// approval. Read-only - no claim taken, nothing written - so it is cheap
2122/// enough to call on every candidate, every poll.
2123fn land_resume_state(task: &Task) -> LandResume {
2124    let Some(run_id) = task.runs.last() else {
2125        return LandResume::NotLanding;
2126    };
2127    let Ok(state) = RunState::load(run_id) else {
2128        return LandResume::NotLanding;
2129    };
2130    if !implementers_match(task, &state) || !state.parked {
2131        return LandResume::NotLanding;
2132    }
2133    // Parked in `land` on the merge approval, or at `merge` on the owner's
2134    // word about a title/body the posting gate withheld. Told apart by the
2135    // run's own record, not by a status both can share.
2136    let node = if state.status == RunStatus::Landing {
2137        land::APPROVAL_NODE
2138    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2139        crate::github_text::ASK_NODE
2140    } else {
2141        return LandResume::NotLanding;
2142    };
2143    let store = ask::Questions::open();
2144    let waiting = store
2145        .list()
2146        .into_iter()
2147        .filter(|q| &q.run == run_id && q.node == node)
2148        .max_by(|a, b| a.id.cmp(&b.id));
2149    let Some(mut q) = waiting else {
2150        return LandResume::Ready;
2151    };
2152    if !q.status.open() {
2153        // Repair spends agent resources and must obey concurrency and quota
2154        // waits; only a merge/hold decision may use the decision-only lane.
2155        if q.resolution().as_deref() == Some(land::REPAIR) {
2156            return if state.liveness(false) == Liveness::Live {
2157                LandResume::StillWaiting
2158            } else {
2159                LandResume::NotLanding
2160            };
2161        }
2162        return LandResume::Ready;
2163    }
2164    // `ask::ask_and_wait`'s own deadline is what used to retire a question
2165    // nobody ever answered; land's approval bypasses that wait entirely (see
2166    // `land::approval_gate`), so the same deadline has to be enforced here
2167    // instead, or `graph.answer_timeout` silently stops meaning anything for
2168    // a land approval and a run can sit `StillWaiting` forever with nobody
2169    // told to look at it.
2170    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2171    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2172    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2173        q.abandon(format!(
2174            "no answer within {}s of asking",
2175            timeout.as_secs().max(1)
2176        ));
2177        // If this can't be persisted, do not treat the wait as settled on a
2178        // guess: fall through and try again next poll.
2179        if store.put(&mut q).is_ok() {
2180            return LandResume::Ready;
2181        }
2182    }
2183    LandResume::StillWaiting
2184}
2185
2186/// How often the loop rechecks for new work while something it already
2187/// started is still running, rather than sleeping out the whole
2188/// [`Opts::poll`] interval.
2189///
2190/// Short on purpose: this is what lets a land-merge approval that comes back
2191/// while another task is mid-competition be noticed and resumed within a
2192/// fraction of a second, not within the next multi-second poll.
2193const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2194
2195/// How often [`poll`] rechecks the shared build cache against its cap at a
2196/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
2197/// waiting for the queue to run dry.
2198///
2199/// A queue that never empties means the `janitor` call at the bottom of this
2200/// loop's fully-idle branch can go unreached for as long as the backlog
2201/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
2202/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
2203/// 81.8 GiB an idle-only check let it reach before this existed, and it is
2204/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
2205/// backlog of short tasks does not pay for that walk on every poll.
2206const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2207
2208/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
2209/// in `Status::current` - on drop, so both are released even if the attempt
2210/// panics rather than returning.
2211///
2212/// A `Drop` impl rather than statements written after the `.await` it
2213/// guards: a panic unwinds straight past code placed "after" a call, and
2214/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
2215/// that ruling a panic out there is not a bet this loop can make. Without
2216/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
2217/// forever - the idle branch in [`poll`], and with it the janitor, would
2218/// never run again - and a ghost entry in `Status::current` naming a task
2219/// nothing is still working on.
2220struct InFlightGuard<'a> {
2221    status: &'a Arc<Mutex<Status>>,
2222    stop: &'a Stop,
2223    task_id: &'a str,
2224}
2225
2226impl Drop for InFlightGuard<'_> {
2227    fn drop(&mut self) {
2228        lock(self.status).current.retain(|c| c.task != self.task_id);
2229        self.stop.exit();
2230    }
2231}
2232
2233/// State of [`poll`]'s own interrupt-scheduling sequence - see
2234/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
2235/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
2236/// both kept free of `Task`'s non-identity fields on purpose: every decision
2237/// here turns only on task ids and which ones are in flight, so the "never
2238/// more than one run at once" and "exactly one resume" invariants can be
2239/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
2240/// queue - which is exactly the coverage this feature's first two attempts
2241/// were missing.
2242///
2243/// Deliberately in-memory only, not written to disk anywhere: a daemon
2244/// restart mid-sequence loses track of which run it had asked to park and
2245/// which task was meant to run first, and simply falls back to `Idle` -
2246/// see [`drive`]'s own setup. The parked run itself is not lost - it is
2247/// sitting in the queue exactly like any other resumable, interrupted task,
2248/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
2249/// just resumes on the ordinary priority order rather than guaranteed to go
2250/// first. Giving that guarantee a crash-proof memory would mean a new queue
2251/// field and a recovery ordering to go with it, which is exactly the
2252/// complexity this feature's constraints rule out for the one property that
2253/// actually matters: at most one run, ever, at once.
2254#[derive(Debug, Clone, PartialEq, Eq)]
2255enum Interrupt {
2256    /// No interrupt sequence in progress. Ordinary dispatch applies.
2257    Idle,
2258    /// `interrupt_task` is runnable and exactly one other run is in flight;
2259    /// `parked` names that one task's id. Dispatch is withheld from
2260    /// everyone, including `interrupt_task` itself, until it has left
2261    /// flight - only then is `interrupt_task` let through.
2262    ///
2263    /// `parked` is a `Vec` rather than a bare id for symmetry with
2264    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
2265    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
2266    /// when exactly one run is in flight, so it is guaranteed to hold
2267    /// exactly one entry in practice - see that branch's own doc for why
2268    /// more than one is deliberately never attempted.
2269    Parking {
2270        parked: Vec<String>,
2271        interrupt_task: String,
2272    },
2273    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
2274    /// withheld from everyone until it leaves flight - merged, failed, held,
2275    /// it makes no difference - at which point the sequence moves to
2276    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
2277    /// going straight to `Idle` would hand `parked` back to ordinary
2278    /// priority-order dispatch, where a higher-priority task filed in the
2279    /// meantime could start ahead of it.
2280    Running {
2281        parked: Vec<String>,
2282        interrupt_task: String,
2283    },
2284    /// `interrupt_task` left flight; `parked` still names the one run this
2285    /// sequence owes a resume. Dispatch is withheld from everyone except
2286    /// that task - see [`interrupt_gate`] - so the resume this feature
2287    /// promises is never raced by, or run alongside, an unrelated candidate.
2288    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
2289    /// own doc on abandonment - the moment it is no longer runnable at all.
2290    Resuming { parked: Vec<String> },
2291}
2292
2293/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
2294/// and `runnable` are read-only snapshots of this tick's reality, and the
2295/// only side effect the caller still owes the world is asking whichever
2296/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
2297/// site.
2298///
2299/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
2300/// accepted rather than a narrower type because that is what [`poll`] already
2301/// has on hand from [`runnable`], and building a second, smaller list on
2302/// every tick just to satisfy this signature would cost more than it proves.
2303///
2304/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
2305/// back to a task they are waiting on no longer being [`runnable`] - held,
2306/// blocked, deleted, or finished by some other means entirely, all of which
2307/// an operator can do to a task sitting in the queue with no claim on it at
2308/// all, at any moment, interrupt sequence or not. Without this check the
2309/// sequence would wait forever for a dispatch that can never come, and
2310/// `interrupt_gate` would withhold every other task in the queue right along
2311/// with it - a single `magi task hold` on the wrong id turning into a
2312/// daemon that never dispatches anything again.
2313fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2314    match state {
2315        Interrupt::Idle => {
2316            // Not just "something to interrupt": exactly one thing. More
2317            // than one run in flight only happens above the default
2318            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
2319            // one resume, never run alongside anything else" only because
2320            // it is only ever seeded with exactly one id - see
2321            // `Interrupt::Resuming`'s own doc on why releasing more than one
2322            // parked id back to ordinary dispatch cannot be made safe
2323            // against that same setting's own extra concurrency slots.
2324            // Waiting here for the herd to settle to one is the
2325            // simplification this feature's own constraints ask for rather
2326            // than a second concurrency model to reconcile with the first.
2327            if in_flight.len() != 1 {
2328                return Interrupt::Idle;
2329            }
2330            match runnable.iter().find(|t| t.interrupt) {
2331                Some(t) => Interrupt::Parking {
2332                    parked: in_flight.to_vec(),
2333                    interrupt_task: t.id.clone(),
2334                },
2335                None => Interrupt::Idle,
2336            }
2337        }
2338        Interrupt::Parking {
2339            parked,
2340            interrupt_task,
2341        } => {
2342            if in_flight.iter().any(|id| parked.contains(id)) {
2343                // Still waiting for what was in flight to actually stop.
2344                Interrupt::Parking {
2345                    parked,
2346                    interrupt_task,
2347                }
2348            } else if in_flight.contains(&interrupt_task) {
2349                Interrupt::Running {
2350                    parked,
2351                    interrupt_task,
2352                }
2353            } else if runnable.iter().any(|t| t.id == interrupt_task) {
2354                // The parked run(s) are gone, but the interrupt task has not
2355                // been dispatched yet on this tick - `interrupt_gate` is
2356                // what lets it through next.
2357                Interrupt::Parking {
2358                    parked,
2359                    interrupt_task,
2360                }
2361            } else {
2362                // The interrupt task itself is no longer runnable - see this
2363                // function's own doc on abandonment. The parked run(s) still
2364                // get their guaranteed resume; there is simply no interrupt
2365                // to run ahead of them any longer.
2366                Interrupt::Resuming { parked }
2367            }
2368        }
2369        Interrupt::Running {
2370            parked,
2371            interrupt_task,
2372        } => {
2373            if in_flight.contains(&interrupt_task) {
2374                Interrupt::Running {
2375                    parked,
2376                    interrupt_task,
2377                }
2378            } else {
2379                // The interrupt task's own run reached a terminal status,
2380                // whichever one - this is the *only* trigger that moves the
2381                // sequence on, driven straight off the same in-flight
2382                // bookkeeping `poll` already reaps every tick, not a second,
2383                // independent poll of anything.
2384                Interrupt::Resuming { parked }
2385            }
2386        }
2387        Interrupt::Resuming { parked } => {
2388            if in_flight.iter().any(|id| parked.contains(id)) {
2389                // One of the parked runs has been dispatched - the resume
2390                // this sequence owed is fulfilled. Whatever else is left in
2391                // `parked` (ordinarily nothing, at the default concurrency
2392                // of one) rejoins ordinary priority-order dispatch, same as
2393                // any other runnable task.
2394                Interrupt::Idle
2395            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2396                Interrupt::Resuming { parked }
2397            } else {
2398                // Abandonment (see this function's own doc): nothing left in
2399                // `parked` is even runnable any longer.
2400                Interrupt::Idle
2401            }
2402        }
2403    }
2404}
2405
2406/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
2407/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
2408/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
2409/// indistinguishable from any other runnable task - exactly the "off does
2410/// nothing" this feature promises.
2411fn advance_interrupt_tick(
2412    enabled: bool,
2413    state: Interrupt,
2414    in_flight: &[String],
2415    runnable: &[Task],
2416) -> Interrupt {
2417    if !enabled {
2418        return Interrupt::Idle;
2419    }
2420    advance_interrupt(state, in_flight, runnable)
2421}
2422
2423/// Which of this tick's runnable candidates the interrupt sequence actually
2424/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
2425/// each half is assertable on its own: this is the half that keeps a
2426/// competition and an interrupt from ever running at the same moment.
2427fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2428    match state {
2429        Interrupt::Idle => candidates,
2430        Interrupt::Parking {
2431            parked,
2432            interrupt_task,
2433        } => {
2434            if in_flight.iter().any(|id| parked.contains(id)) {
2435                Vec::new()
2436            } else {
2437                candidates
2438                    .into_iter()
2439                    .filter(|t| &t.id == interrupt_task)
2440                    .collect()
2441            }
2442        }
2443        Interrupt::Running { .. } => Vec::new(),
2444        // At most one: even if `parked` names more than one id (more than
2445        // one run was in flight when the sequence began, only possible
2446        // above the default `max_concurrent_runs = 1`), only the first match
2447        // is offered. Capping this to a single candidate - not merely to
2448        // `parked`'s own ids - is what makes "exactly one resume, never two
2449        // dispatched together" true regardless of how many ordinary slots
2450        // happen to be free this tick.
2451        Interrupt::Resuming { parked } => candidates
2452            .into_iter()
2453            .find(|t| parked.contains(&t.id))
2454            .into_iter()
2455            .collect(),
2456    }
2457}
2458
2459/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
2460/// bundled into one parameter so `poll`'s own signature stays readable -
2461/// see [`drive`]'s call site for where these are actually read.
2462struct DispatchLimits {
2463    /// How many *ordinary* candidates run at once. See
2464    /// [`crate::config::Daemon::max_concurrent_runs`].
2465    max_concurrent: usize,
2466    /// See [`crate::config::Daemon::pause_for_interrupts`].
2467    pause_for_interrupts: bool,
2468}
2469
2470/// Which semaphore, if any, dispatching a candidate should draw its permit
2471/// from.
2472///
2473/// Pure and separate from [`poll`]'s loop body for the same reason
2474/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
2475/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
2476/// exactly the policy this feature adds, and a policy only exercisable by
2477/// running the whole loop is a policy nobody checks.
2478#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2479enum PermitKind {
2480    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
2481    /// Checked first - a task can be both a land resume and marked
2482    /// [`Task::urgent`], and the resume's own "must not queue behind
2483    /// anything" guarantee takes precedence.
2484    None,
2485    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
2486    /// (never in addition to trying) the ordinary pool. This is what lets
2487    /// an urgent task dispatch while every ordinary slot is already checked
2488    /// out, and what stops a second urgent task from opening a third run: it
2489    /// waits on this same one-slot semaphore rather than falling through to
2490    /// the ordinary one.
2491    Urgent,
2492    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
2493    /// above.
2494    Ordinary,
2495}
2496
2497/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
2498/// own boolean, already computed by the caller from [`land_resume_state`].
2499fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2500    if priority {
2501        PermitKind::None
2502    } else if urgent {
2503        PermitKind::Urgent
2504    } else {
2505        PermitKind::Ordinary
2506    }
2507}
2508
2509struct DispatchClaim {
2510    task: Task,
2511    claim: crate::queue::Claim,
2512    permit: Option<tokio::sync::OwnedSemaphorePermit>,
2513}
2514
2515/// Claim and re-read before choosing a lane: a queue listing may predate an
2516/// urgent toggle. All unsuccessful paths release the claim without an attempt.
2517fn claim_dispatch(
2518    queue: &Queue,
2519    candidate: &Task,
2520    cooling_down: bool,
2521    ordinary: &Arc<tokio::sync::Semaphore>,
2522    urgent: &Arc<tokio::sync::Semaphore>,
2523) -> Option<DispatchClaim> {
2524    let Ok(claim) = queue.claim(&candidate.id) else {
2525        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2526        return None;
2527    };
2528    let task = match queue.get(&candidate.id) {
2529        Ok(t) if t.status.runnable() => t,
2530        Ok(_) => return None,
2531        Err(e) => {
2532            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2533            return None;
2534        }
2535    };
2536    let resume = land_resume_state(&task);
2537    if resume == LandResume::StillWaiting {
2538        return None;
2539    }
2540    let priority = resume == LandResume::Ready;
2541    if !priority && cooling_down {
2542        return None;
2543    }
2544    // Never borrow an ordinary slot when the single urgent slot is busy.
2545    // Keep scanning other candidates when either pool has no free slot.
2546    let permit = match permit_kind(priority, task.urgent) {
2547        PermitKind::None => None,
2548        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
2549        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
2550    };
2551    Some(DispatchClaim {
2552        task,
2553        claim,
2554        permit,
2555    })
2556}
2557
2558/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
2559/// teardown and cannot skip the teardown on an early return.
2560///
2561/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
2562/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
2563/// land approval that has since been answered is dispatched outside that
2564/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
2565/// the whole point of parking there is that it must not queue behind
2566/// whatever else the loop happens to be running, even at the default of one.
2567/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
2568/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
2569/// these exemptions is still subject to the interrupt gate below, urgent
2570/// included: a land-resume or urgent candidate is exactly as much "something
2571/// else running" as an ordinary one from the interrupt sequence's point of
2572/// view, and letting either slip through while a run is being parked, or
2573/// while the interrupt task itself has the floor, is precisely the second
2574/// run 75dd's own "at most one run, ever, at once" guarantee must never
2575/// allow - see [`Interrupt`]'s own doc.
2576async fn poll(
2577    opts: &Opts,
2578    queue: &Queue,
2579    status: &Arc<Mutex<Status>>,
2580    home: &Path,
2581    worktrees_root: &Path,
2582    stop: &Stop,
2583    limits: DispatchLimits,
2584) -> Result<()> {
2585    let DispatchLimits {
2586        max_concurrent,
2587        pause_for_interrupts,
2588    } = limits;
2589    // Only consulted by `once`, where a task that just failed is still
2590    // `runnable` and would otherwise be picked up again inside the same drain.
2591    // In the long-running mode a later poll retrying a failed task is the point,
2592    // and the attempt counter is what bounds it.
2593    let mut attempted: Vec<String> = Vec::new();
2594    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2595    // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
2596    // entirely separate from `sem`: an urgent candidate must dispatch
2597    // alongside whatever `sem` already has checked out, never by waiting for
2598    // one of those ordinary slots to free up and never by growing
2599    // `max_concurrent_runs` itself. Sized at one, not unbounded - see
2600    // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
2601    // first on this same slot rather than opening a third run.
2602    let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2603    // A quota hit is a fact about the machine, not the task that happened to
2604    // surface it, and every other *ordinary* candidate is no less likely to
2605    // hit the same wall - see the warning below. A land-merge resume is
2606    // exempt: it is a human decision finishing, not a fresh competition, and
2607    // must not sit out a quota cooldown it did not cause.
2608    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2609    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2610    let mut conductor = Conductor::new();
2611    // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
2612    // a congested queue would otherwise starve of the fully-idle branch below.
2613    let mut cache_last_checked: Option<Timestamp> = None;
2614    // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
2615    let mut interrupt = Interrupt::Idle;
2616    // The `Pause` handed to each dispatched candidate's own `Runner` - see
2617    // `attempt`'s new parameter - kept here so the tick that decides to park
2618    // a run for an interrupt can reach that specific run's handle and no
2619    // other's. Pruned to whatever is still in flight at the top of every
2620    // tick, so a finished attempt's handle does not linger.
2621    let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2622        std::collections::HashMap::new();
2623
2624    while !stop.stopped() {
2625        lock(status).polls += 1;
2626
2627        // Reap whatever finished since the last tick without blocking on
2628        // anything still running. `InFlightGuard` already released the slot
2629        // even if the spawned attempt panicked; this only surfaces that it
2630        // happened, since a panic swallowed here otherwise leaves no trace.
2631        while let Some(result) = inflight.try_join_next() {
2632            if let Err(e) = result {
2633                tracing::error!("a spawned attempt did not finish cleanly: {e}");
2634                notices::raise(Notice::error(
2635                    "loop:attempt",
2636                    "A queued attempt ended abnormally; check the task it was running.",
2637                ));
2638            }
2639        }
2640
2641        let swept = sweep_stale_claims(queue, STALE_CLAIM);
2642        if !swept.is_empty() {
2643            tracing::warn!(
2644                "swept {} stale claim(s) left behind by an earlier daemon: {}",
2645                swept.len(),
2646                swept.join(", ")
2647            );
2648        }
2649        // Capture stalled work before reclaiming it. A dead daemon's ordinary
2650        // lock is swept and reclaimed in this same poll, but the conductor
2651        // must still see that it was stranded rather than only its mechanical
2652        // terminal state.
2653        let now = Timestamp::now();
2654
2655        // No run this daemon spawned is mid-compile right now, whether or
2656        // not another candidate is about to start - see
2657        // `maybe_prune_cache_between_runs`'s own doc for why this cannot
2658        // wait for the queue to run dry.
2659        if !stop.busy_now() {
2660            maybe_prune_cache_between_runs(
2661                &opts.repo,
2662                opts,
2663                home,
2664                stop,
2665                &mut cache_last_checked,
2666                now,
2667            )
2668            .await;
2669        }
2670
2671        let stalled = stalled_tasks(queue, home, now);
2672        let stalled_ids: std::collections::BTreeSet<_> =
2673            stalled.iter().map(|task| task.id.clone()).collect();
2674        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2675        if !reclaimed.is_empty() {
2676            tracing::warn!(
2677                "reclaimed {} task(s) left `running` by a daemon that never \
2678                 recorded the outcome: {}",
2679                reclaimed.len(),
2680                reclaimed.join(", ")
2681            );
2682        }
2683        let abandoned_runs = reclaim_abandoned_runs(home, now);
2684        if !abandoned_runs.is_empty() {
2685            tracing::warn!(
2686                "failed {} run(s) left behind by a killed process, past every \
2687                 active seat's own timeout: {}",
2688                abandoned_runs.len(),
2689                abandoned_runs.join(", ")
2690            );
2691        }
2692
2693        // `home`, not `ask::Questions::open()`'s own process-global default:
2694        // `poll` is handed its home explicitly precisely so a test can point
2695        // it elsewhere, the same reason `Queue::at` and the status file path
2696        // are parameters rather than resolved here - see `drive`'s own doc.
2697        let questions = Questions::at(home.join("questions"));
2698
2699        // Deterministic: no model, run before the conductor sees anything so
2700        // its input reflects the queue's current, already-resolved state.
2701        resolve_blockers(queue, &questions);
2702        apply_choice_actions(queue, &questions, home);
2703        triage::apply_answers(queue, &questions);
2704        reconcile_task_questions(queue, &questions);
2705        // Tell the chat a filed task or watched command has ended. Reconciled
2706        // here regardless of how it ended, and started only when no
2707        // upgrade is parking (the draft then waits for a manual resume).
2708        {
2709            let talks = crate::talk::Talks::at(home.join("talks"));
2710            crate::chat_notify::sweep(queue, &talks, home);
2711            crate::chat_watch::sweep(home, &talks);
2712            crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
2713        }
2714
2715        // The conductor gets one look per cycle, right before the loop takes
2716        // its next task, and only when there is something new to look at -
2717        // see `Conductor::worth_a_look`'s own doc for why "stalled is
2718        // non-empty" is the wrong test. Checked before `prepare` so an
2719        // unchanged cycle never pays for a synchronous config load.
2720        let finished: Vec<Task> = finished_tasks(queue)
2721            .into_iter()
2722            .filter(|task| !stalled_ids.contains(&task.id))
2723            // A parked run is waiting for this loop, not for a decision: the
2724            // conductor must not get to hold it or requeue it (a requeue
2725            // sets `fresh_start` and re-competes) before `attempt` resumes.
2726            .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2727            .collect();
2728        let queued = queued_tasks(queue);
2729        // An empty queue has nothing to arrange. In particular, do not let
2730        // the conductor's initial snapshot cause synchronous config I/O
2731        // between the caller's stop notification and the idle wait below.
2732        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2733            && conductor.worth_a_look(queue, &stalled, &finished)
2734        {
2735            match prepare(&opts.repo, opts) {
2736                Ok(cfg) => {
2737                    conductor
2738                        .maybe_run(
2739                            &cfg,
2740                            &opts.repo,
2741                            queue,
2742                            &questions,
2743                            home,
2744                            &queued,
2745                            &stalled,
2746                            &finished,
2747                            opts.max_attempts,
2748                        )
2749                        .await;
2750                }
2751                Err(e) => {
2752                    tracing::warn!("conductor: no config: {e:#}");
2753                    notices::raise(Notice::warn(
2754                        "loop:no-config",
2755                        "The loop could not read this repository's config, so held tasks are not being triaged.",
2756                    ));
2757                }
2758            }
2759        }
2760
2761        let candidates: Vec<Task> = runnable(queue)
2762            .into_iter()
2763            .filter(|t| !opts.once || !attempted.contains(&t.id))
2764            .collect();
2765
2766        // A task id only stays a key here while its attempt is genuinely in
2767        // flight; `status.current` is the same liveness fact `InFlightGuard`
2768        // maintains for the phone's own status file, so this piggybacks on
2769        // it rather than tracking a second copy of the same thing.
2770        let in_flight: Vec<String> = lock(status)
2771            .current
2772            .iter()
2773            .map(|c| c.task.clone())
2774            .collect();
2775        interrupt_pauses.retain(|id, _| in_flight.contains(id));
2776
2777        interrupt =
2778            advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2779        if let Interrupt::Parking {
2780            parked,
2781            interrupt_task,
2782        } = &interrupt
2783        {
2784            let reason = format!(
2785                "task {} asked to run first",
2786                crate::run::short_of(interrupt_task)
2787            );
2788            for id in parked {
2789                if let Some(pause) = interrupt_pauses.get(id) {
2790                    pause.park_because(reason.clone());
2791                }
2792            }
2793        }
2794        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2795
2796        let cooling_down =
2797            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2798
2799        let mut started_any = false;
2800        for candidate in candidates {
2801            if stop.stopped() {
2802                break;
2803            }
2804
2805            let Some(DispatchClaim {
2806                mut task,
2807                claim,
2808                permit,
2809            }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
2810            else {
2811                continue;
2812            };
2813
2814            let task_id = task.id.clone();
2815            attempted.push(task_id.clone());
2816            lock(status).idle = false;
2817            // A stop asked for from here on is "finishing", not "stopped": the
2818            // run gets to reach a terminal status before the loop returns.
2819            stop.enter();
2820            started_any = true;
2821
2822            // A fresh, unshared handle - never `stop.pause()` - so parking
2823            // this run for an interrupt cannot leak into any other run this
2824            // loop ever drives. See `Pause`'s own doc.
2825            let run_pause = crate::graph::Pause::new();
2826            interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2827
2828            let opts = opts.clone();
2829            let queue = queue.clone();
2830            let status = Arc::clone(status);
2831            let stop = stop.clone();
2832            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
2833            inflight.spawn(async move {
2834                // Held for the whole attempt: dropping either at the end of
2835                // this task is what releases the claim and, for an ordinary
2836                // candidate, frees its concurrency slot back to the loop.
2837                let _claim = claim;
2838                let _permit = permit;
2839                // See `InFlightGuard`: this must survive a panic inside `attempt`.
2840                let _inflight = InFlightGuard {
2841                    status: &status,
2842                    stop: &stop,
2843                    task_id: &task_id,
2844                };
2845                let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2846                lock(&status).completed += 1;
2847                // A quota loss is a fact about the machine, not this task, and
2848                // the next ordinary candidate the loop offers is no less
2849                // likely to hit the same wall: without a cooldown here a
2850                // whole backlog can be run - and failed - in the seconds it
2851                // takes each attempt to notice the CLI is out of quota.
2852                let now = Timestamp::now();
2853                if let Some(until) = cooldown_until(&quota, now) {
2854                    let wait = until.as_second() - now.as_second();
2855                    *lock(&quota_cooldown_until) = Some(until);
2856                    let hint = quota
2857                        .iter()
2858                        .find(|q| q.reset.is_some())
2859                        .and_then(|q| q.reset.as_deref());
2860                    match hint {
2861                        Some(h) => tracing::warn!(
2862                            "quota hit; waiting {wait}s before taking another ordinary task \
2863                             (CLI reported reset: {h})"
2864                        ),
2865                        None => tracing::warn!(
2866                            "quota hit; waiting {wait}s before taking another ordinary task \
2867                             (no reset hint reported)"
2868                        ),
2869                    }
2870                }
2871            });
2872        }
2873
2874        if started_any {
2875            continue;
2876        }
2877
2878        if stop.busy_now() {
2879            // Something started on an earlier tick is still running. Recheck
2880            // soon rather than sleeping out the whole poll interval - a freed
2881            // slot, or a land approval answered mid-run, must not sit idle
2882            // for it.
2883            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2884            continue;
2885        }
2886
2887        // Truly idle: nothing new to start and nothing still running.
2888        lock(status).idle = true;
2889        if opts.once {
2890            // A one-shot drain must perform the same post-work cleanup as a
2891            // daemon that reached a normal idle interval. The startup pass
2892            // cannot see runs or cache files produced by this drain.
2893            janitor(&opts.repo, opts, home, worktrees_root).await;
2894            resweep_superseded_attempts(queue, home);
2895            triage_held(queue, home, opts).await;
2896            break;
2897        }
2898        stop.idle(opts.poll).await;
2899        if stop.stopped() {
2900            continue;
2901        }
2902        // Housekeeping only after a full quiet interval. Running it before
2903        // the first idle wait can block the executor while an operator's
2904        // stop request is waiting to be scheduled, defeating Stop's retained
2905        // wake permit. No run can start while this branch is active, so the
2906        // janitor still never races an in-flight compile.
2907        janitor(&opts.repo, opts, home, worktrees_root).await;
2908        resweep_superseded_attempts(queue, home);
2909        triage_held(queue, home, opts).await;
2910    }
2911
2912    // Never return while a run is still in flight, whichever way the loop
2913    // above exited: a stop only sets a flag - see `serve_until` - and
2914    // returning here while `inflight` still holds spawned work would abandon
2915    // it exactly as a mid-node kill would.
2916    while let Some(result) = inflight.join_next().await {
2917        if let Err(e) = result {
2918            tracing::error!("a spawned attempt did not finish cleanly: {e}");
2919            notices::raise(Notice::error(
2920                "loop:attempt",
2921                "A queued attempt ended abnormally; check the task it was running.",
2922            ));
2923        }
2924    }
2925    Ok(())
2926}
2927
2928/// Run one claimed task to a terminal status and record the outcome.
2929///
2930/// Every transition is flushed to the queue as it happens, so the state on disk
2931/// is what actually occurred rather than what this process still intends to
2932/// write.
2933async fn attempt(
2934    opts: &Opts,
2935    queue: &Queue,
2936    status: &Arc<Mutex<Status>>,
2937    stop: &Stop,
2938    interrupt_pause: crate::graph::Pause,
2939    task: &mut Task,
2940) -> Vec<QuotaLoss> {
2941    let repo = repo_for(task, &opts.repo);
2942    tracing::info!(
2943        "task {} — {} (repo {})",
2944        task.short(),
2945        task.title,
2946        repo.display()
2947    );
2948
2949    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
2950    // failure here is the network's or the operator's, not the task's: hold
2951    // without spending an attempt, never fall back to a possibly stale copy.
2952    let explicit = match &task.overrides {
2953        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
2954        Some(_) => opts.config.as_deref(),
2955        None => opts.config.as_deref(),
2956    };
2957    if let Err(e) = Config::discover_fetched(&repo, explicit).await {
2958        let reason = format!("[config] {e:#}");
2959        record_config_failure(task, &e);
2960        task.last_error = Some(reason.clone());
2961        task.hold_machine(Some(reason.clone()));
2962        record(queue, task);
2963        tracing::warn!("holding {}: {reason}", task.short());
2964        return Vec::new();
2965    }
2966    let mut config = match prepare_for(&repo, opts, task) {
2967        Ok(c) => c,
2968        Err(e) => {
2969            // A setup failure spends an attempt even though no run was minted.
2970            // Without that, a task naming a repository that does not exist
2971            // would be retried at every poll for as long as the daemon lives.
2972            task.attempts += 1;
2973            task.fail_startup(
2974                "startup-config",
2975                format!("config: {e:#}"),
2976                opts.max_attempts,
2977            );
2978            record(queue, task);
2979            return Vec::new();
2980        }
2981    };
2982    apply_task_implementers(&mut config, task);
2983    let p = phrases(&config.graph.language);
2984    let start_failed = p.could_not_start;
2985
2986    // The free-space gate, checked *before* anything is minted: a task that
2987    // waits out a full disk costs nothing yet, and must not spend an attempt
2988    // or start a run the machine cannot finish. Held tasks stay in the list
2989    // for the human to see, and `magi task release` re-queues them when space
2990    // comes back - the same recovery as any other hold. A volume whose free
2991    // space cannot be measured closes the gate too: starting a run blind on a
2992    // disk that may be full is how the machine ends up with 6.7 GB free.
2993    if let Some(reason) = disk_gate(&repo, &config) {
2994        task.notice_cause("disk-space", None, None);
2995        task.last_error = Some(reason.clone());
2996        task.hold_machine(Some(reason.clone()));
2997        record(queue, task);
2998        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2999        // Stable wording - the free-space figures live in the task's hold
3000        // reason, and changing numbers would relight the bell every poll.
3001        notices::raise(
3002            Notice::warn(
3003                &format!("disk:{}", repo.display()),
3004                "A task was held for want of free disk space; free some, then release it from the queue.",
3005            )
3006            .link(Link::Task {
3007                id: task.id.clone(),
3008            }),
3009        );
3010        return Vec::new();
3011    }
3012
3013    // A resumable run of this task is carried on, never re-competed. The
3014    // candidates are built and paid for, and a fresh competition races a
3015    // second implementation against them.
3016    //
3017    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
3018    // started 3cbf on the same task a moment later, duplicating two and a
3019    // half hours of agent work. Then b25f stalled on a judge that timed out
3020    // and one that answered with no JSON - `quota: 0`, so nothing the machine
3021    // was to blame for - and 4043 started **one second** later, buying three
3022    // fresh implementations to reach the same panel. `RunStatus::resumable`
3023    // rather than `!done()` is what catches the second case: a stall is
3024    // terminal, and its cheap recovery re-asks only the absent seats.
3025    //
3026    // A load failure is warned about rather than silently read as "not
3027    // resumable": the alternative is exactly what let a schema mismatch on
3028    // run `eba2` fall through to a full re-competition with nobody told why.
3029    // `crate::conduct` is what actually offers a better answer than
3030    // `Runner::start` here (see `Recovery::Review`), once this task's next
3031    // failure shows it up as `held`/`failed` with the run state unreadable.
3032    let unfinished = (!task.fresh_start)
3033        .then(|| unfinished_run(&task.runs, task.short()))
3034        .flatten()
3035        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3036    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
3037    // branch survived, and this reopens exactly that branch as a
3038    // review-only pass rather than resuming or competing again. Consumed
3039    // (cleared) here whichever way this goes, so it never outlives this one
3040    // attempt - see `queue::Task::review_branch`.
3041    let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3042    let review_branch = take_review_branch(task, previous.as_ref());
3043    let branch_exists = match &review_branch {
3044        Some(branch) => crate::git::branch_exists(&repo, branch)
3045            .await
3046            .unwrap_or(false),
3047        None => false,
3048    };
3049    // An explicit `magi review <branch>` is reviewed whatever happens to the
3050    // branch unless an explicit implementer change requires fresh work. An
3051    // unfinished run of the same task still wins, so a retry resumes.
3052    let proposed = match (&review_branch, &unfinished, &task.review_of) {
3053        (None, None, Some(branch)) => Starter::Review(branch.clone()),
3054        _ => choose_starter(
3055            review_branch.as_deref(),
3056            branch_exists,
3057            unfinished.as_deref(),
3058        ),
3059    };
3060    let starter = if let Some(selected) = &task.pr_recovery {
3061        if selected.check_task(&task.id, &task.instruction).is_ok() {
3062            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3063        } else {
3064            Starter::Review(selected.branch.clone())
3065        }
3066    } else {
3067        starter_with_implementers(task, previous.as_ref(), proposed)
3068    };
3069    // A repair pin must never degrade into a new competition or takeover if
3070    // the owner disappears between the answer and dispatch.
3071    if let Some(pin) = &task.resume_override
3072        && let Some(run) = &pin.pinned_run
3073        && Questions::open().get(&pin.question_id).map_or(true, |q| {
3074            q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR)
3075        })
3076        && starter != Starter::Resume(run.clone())
3077    {
3078        let run = run.clone();
3079        task.notice_cause("repair-owner", Some(&run), None);
3080        task.hold_machine(Some(format!(
3081            "repair owner cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3082            task.id
3083        )));
3084        record(queue, task);
3085        return Vec::new();
3086    }
3087    // Absolute paths of the files the task was filed with, re-read from the
3088    // task now so a file attached while it was held reaches a resumed run
3089    // too. A stored name whose file has gone is an error before any agent is
3090    // paid for, never a silent omission the implementer cannot notice.
3091    let attachments = match task_attachments(queue, task) {
3092        Ok(a) => a,
3093        Err(e) => {
3094            task.attempts += 1;
3095            task.fail_startup_target(
3096                "startup-attachments",
3097                e.name.clone(),
3098                format!("{start_failed}{e:#}"),
3099                opts.max_attempts,
3100            );
3101            record(queue, task);
3102            return Vec::new();
3103        }
3104    };
3105    let started = match &starter {
3106        Starter::Review(_) if task.pr_recovery.is_some() => {
3107            let selected = task.pr_recovery.clone().expect("selected recovery");
3108            match selected.check_task(&task.id, &task.instruction) {
3109                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3110                    .await
3111                    .map(|mut r| {
3112                        r.state.attachments = attachments.clone();
3113                        r
3114                    }),
3115                Err(e) => Err(e),
3116            }
3117        }
3118        Starter::Review(branch) => {
3119            tracing::info!(
3120                "task {} reopens `{branch}` as a review-only pass",
3121                task.short()
3122            );
3123            // Every earlier attempt is superseded by the one being minted
3124            // now, so a branch one of them still holds may be taken over.
3125            let takeover = crate::handover::Takeover {
3126                earlier: task.earlier_attempts().to_vec(),
3127                home: crate::run::home(),
3128                choice: take_divergence_answer(branch, &config.merge.remote, task),
3129                task_instruction: Some(instruction_for(task)),
3130            };
3131            Runner::review_taking_over(
3132                &repo,
3133                branch,
3134                config,
3135                Some(takeover),
3136                crate::run::Origin::queue(&task.id),
3137            )
3138            .await
3139        }
3140        Starter::Resume(id) => {
3141            tracing::info!("resuming run {id} rather than competing again");
3142            Runner::resume(id).and_then(|mut r| {
3143                if r.state.prep_failure.is_some() {
3144                    let approval = task
3145                        .resumption
3146                        .as_ref()
3147                        .context("preparation retry requires an explicit task release")?;
3148                    r.retry_preparation(approval.at)?;
3149                }
3150                if let Some(instruction) =
3151                    prepare_instruction(&starter, Some(&r.state.instruction), task)
3152                {
3153                    r.state.instruction = instruction;
3154                }
3155                r.state.attachments = attachments.clone();
3156                // The merge choice of a hand-started task still holds when the
3157                // run it resumes was started under another one.
3158                if let Some(mode) = task
3159                    .overrides
3160                    .as_ref()
3161                    .and_then(|o| o.merge.as_deref())
3162                    .and_then(|m| merge_mode(m).ok())
3163                {
3164                    r.state.config.merge.mode = mode;
3165                }
3166                Ok(r)
3167            })
3168        }
3169        Starter::Start => {
3170            if let Some(branch) = &review_branch {
3171                tracing::warn!(
3172                    "conductor chose review for task {} but branch `{branch}` no longer \
3173                     exists; requeuing as a fresh competition instead",
3174                    task.short()
3175                );
3176            }
3177            let instruction = prepare_instruction(&starter, None, task)
3178                .unwrap_or_else(|| task.instruction.clone());
3179            Runner::start_naming(
3180                &repo,
3181                instruction,
3182                &task.title,
3183                config,
3184                crate::run::Origin::queue(&task.id),
3185            )
3186            .await
3187            .map(|mut r| {
3188                r.state.attachments = attachments.clone();
3189                r
3190            })
3191        }
3192    };
3193    let mut runner = match started {
3194        Ok(r) => r,
3195        // A branch an earlier attempt still holds and magi will not release
3196        // by itself is the operator's call, not a failed attempt: hold the
3197        // task with the reason, spend nothing, and say so on the bell.
3198        Err(e) if task.pr_recovery.is_some() => {
3199            task.startup_notice_cause("startup-public-head");
3200            task.attempts += 1;
3201            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3202                task.link_run(&partial.run);
3203                task.record_pass(&partial.run, 0, task.attempts, None);
3204            }
3205            task.last_error = Some(format!("{start_failed}{e:#}"));
3206            task.hold_unrequested_retry(Some(format!(
3207                "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."
3208            )));
3209            record(queue, task);
3210            return Vec::new();
3211        }
3212        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
3213            let detail = match e.downcast_ref::<crate::handover::Refused>() {
3214                Some(r) => (p.handover_refused)(r),
3215                None => format!("{e:#}"),
3216            };
3217            task.startup_notice_cause("startup-handover");
3218            let reason = format!("{start_failed}{detail}");
3219            task.last_error = Some(reason.clone());
3220            // Consumed above by `take`; keep it so the released task retries
3221            // as a review of this same branch.
3222            let branch = match &starter {
3223                Starter::Review(branch) => Some(branch.clone()),
3224                _ => None,
3225            };
3226            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
3227            // one page; the guidance rides in the reason, fixed per state so a
3228            // re-put never changes the wording and relights it.
3229            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
3230            record(queue, task);
3231            tracing::warn!(
3232                "holding {} for a branch it cannot take over: {e:#}",
3233                task.short()
3234            );
3235            return Vec::new();
3236        }
3237        // A branch that differs between here and the remote in ways magi
3238        // cannot prove are the same change is a decision for the owner, not a
3239        // failed attempt: ask with both sides laid out, spend no attempt, and
3240        // let the answer requeue the task.
3241        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
3242            let d = e
3243                .downcast_ref::<crate::reconcile::Diverged>()
3244                .expect("checked by the guard");
3245            let mut q = ask::Question::new(
3246                task.id.clone(),
3247                crate::reconcile::NODE.to_owned(),
3248                crate::reconcile::SEAT.to_owned(),
3249                d.summary(),
3250                d.detail(),
3251                d.choices(),
3252            );
3253            match Questions::open().put(&mut q) {
3254                Ok(()) => {
3255                    task.last_error = Some(format!("{e:#}"));
3256                    // Consumed above by `take`; the answer has to reach a review
3257                    // of this same branch, so keep pointing the task at it.
3258                    task.review_branch = Some(d.branch.clone());
3259                    task.review_instruction = Some(task.instruction.clone());
3260                    task.block(vec![q.id.clone()], Some(d.summary()));
3261                }
3262                Err(put) => {
3263                    tracing::warn!("could not file the divergence question: {put:#}");
3264                    task.attempts += 1;
3265                    task.fail_startup(
3266                        "startup-question-store",
3267                        format!("{start_failed}{e:#}"),
3268                        opts.max_attempts,
3269                    );
3270                }
3271            }
3272            record(queue, task);
3273            return Vec::new();
3274        }
3275        Err(e) => {
3276            // The answer was stale and nothing was applied: keep pointing at
3277            // the branch so the next attempt asks again against its new tips.
3278            // Nothing went wrong with the task, so no attempt is spent: a
3279            // budget one short of its limit must not hold it instead of
3280            // letting the question be asked again.
3281            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3282                && let Starter::Review(branch) = &starter
3283            {
3284                task.review_branch = Some(branch.clone());
3285                task.review_instruction = Some(task.instruction.clone());
3286                task.last_error = Some(format!("{start_failed}{e:#}"));
3287                task.status = crate::queue::TaskStatus::Failed;
3288                record(queue, task);
3289                return Vec::new();
3290            }
3291            task.attempts += 1;
3292            task.last_error = Some(format!("{start_failed}{e:#}"));
3293            task.startup_notice_cause("startup-source");
3294            task.hold_unrequested_retry(Some(format!(
3295                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
3296            )));
3297            record(queue, task);
3298            return Vec::new();
3299        }
3300    };
3301    runner.state.task_instruction = Some(task.instruction.clone());
3302    // The follow-up depth is fixed now, while the task certainly exists:
3303    // deleting it later must not reset the cap (`crate::followup`).
3304    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
3305    if runner.state.origin_chat.is_none() {
3306        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
3307    }
3308    // A stop that means "park" reaches the graph through this handle.
3309    runner.on_pause(stop.pause());
3310    // `poll`'s interrupt scheduler reaches this one run - and no other -
3311    // through this handle. See `Pause`'s own doc for why these are never
3312    // the same one.
3313    runner.watch_interrupt(interrupt_pause);
3314
3315    // `start` has minted the run, so the task can now point at it. Persisting
3316    // `Running` before `execute` is what makes a crash mid-run legible.
3317    let run = runner.state.id.clone();
3318    task.start(run.clone());
3319    record(queue, task);
3320    lock(status).current.push(Current {
3321        task: task.id.clone(),
3322        run,
3323    });
3324
3325    // `RunState::quota` is the run's whole history across every resume, so
3326    // only what this execution added may arm the cooldown or earn a refund.
3327    let quota_before = runner.state.quota.clone();
3328    runner.state.next_pass_task_entry = true;
3329    let result = runner.execute().await;
3330    finish_attempt(
3331        opts.max_attempts,
3332        queue,
3333        task,
3334        &runner.state,
3335        &quota_before,
3336        result,
3337    )
3338}
3339
3340/// Settle `task` after its run executed: the verdict, the diagnosis, the
3341/// supersession of earlier attempts and the save. Shared by the loop and by
3342/// `magi run --resume`, so an attempt is counted one way wherever it ran.
3343/// Returns the quota losses this execution added to the run.
3344pub fn finish_attempt(
3345    max_attempts: usize,
3346    queue: &Queue,
3347    task: &mut Task,
3348    state: &RunState,
3349    quota_before: &[QuotaLoss],
3350    result: Result<()>,
3351) -> Vec<QuotaLoss> {
3352    let detail = match result {
3353        Ok(()) => describe(state),
3354        Err(e) => format!("{e:#}"),
3355    };
3356    let fresh = losses_this_attempt(quota_before, &state.quota);
3357    let verdict = Verdict {
3358        status: state.status,
3359        // A run that opened a pull request handed its work over, whatever the
3360        // gate then decided about merging it.
3361        left_pr: state.pr.is_some(),
3362        // Only a rate limit earns the task its attempt back - and only one
3363        // suffered now: a refund justified by a previous session's loss is
3364        // the same mistake as re-arming the cooldown from it. A stalled run
3365        // resumed without hitting quota again therefore spends its attempt,
3366        // like any other failure of the task's own.
3367        quota_hit: !fresh.is_empty(),
3368        // A run that parked was asked to stop; that is not a failure and must
3369        // not spend an attempt, or replacing the binary a few times would
3370        // exhaust a task's budget without an agent ever misbehaving.
3371        parked: state.parked,
3372        // A quota loss that left nothing viable is the same machine fact as a
3373        // `Stalled` quota loss; see `settle`'s doc table.
3374        no_viable_candidates: state.viable().is_empty(),
3375    };
3376    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
3377    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
3378        task.hold_unrequested_retry(Some(format!(
3379            "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
3380        )));
3381    }
3382    if task.status == TaskStatus::Done {
3383        supersede_prior_runs(task, &crate::run::home());
3384    }
3385    record(queue, task);
3386    tracing::info!(
3387        "task {} is {} after run {} ({})",
3388        task.short(),
3389        task.status.as_str(),
3390        state.short(),
3391        label(state.status)
3392    );
3393    fresh
3394}
3395
3396/// A task a hand-started run leaves runnable (failed with attempts to spare,
3397/// or requeued) is **held**: nobody asked for a retry, and a loop starting
3398/// later must not spend agent calls on it. `magi task release` retries.
3399pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
3400    // A run parked on the owner's word about a withheld PR title/body is not a
3401    // failure nobody asked to retry: it resumes (answer, or the neutral text on
3402    // the deadline) the moment a loop serves the queue, via `land_resume_state`.
3403    // Holding it would keep it from ever being a candidate.
3404    let waits_on_owner = withheld_text_wait(task).is_some();
3405    if task.status.runnable() && !waits_on_owner {
3406        let why = task.last_error.clone().map_or_else(
3407            || "the run did not finish".to_owned(),
3408            |e| format!("the run did not finish: {e}"),
3409        );
3410        task.hold_unrequested_retry(Some(format!(
3411            "{why}. It was started by hand, so it is not retried \
3412             automatically; `magi task release` retries it."
3413        )));
3414        record(queue, task);
3415    }
3416}
3417
3418/// Whether an attempt at a task whose newest run is `run` would resume that
3419/// run rather than start a fresh competition. `magi run --resume` hands a run
3420/// to a live loop only when this holds.
3421#[must_use]
3422pub fn loop_would_resume(run: &str) -> bool {
3423    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
3424}
3425
3426/// A loop in another process that is alive right now: a fresh heartbeat in
3427/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
3428/// carries the pid it published (`None` inside when it published none - a
3429/// fresh heartbeat is still evidence of a live loop).
3430///
3431/// The one judgement of "is somebody else serving this queue", shared by the
3432/// web UI's refusal to start a second loop and by `magi run` / `magi review`
3433/// deciding whether to hand a task to the loop. A claim file proves nothing
3434/// here: whether a claim succeeds says nothing about whether its owner lives.
3435#[must_use]
3436pub fn foreign_loop(
3437    reading: Option<&Reading>,
3438    now: Timestamp,
3439    own_pid: u32,
3440) -> Option<Option<u32>> {
3441    let reading = reading.filter(|r| r.running(now))?;
3442    match reading.pid {
3443        Some(pid) if pid == own_pid => None,
3444        pid => Some(pid),
3445    }
3446}
3447
3448/// Run one task this process has claimed, in this process, through exactly the
3449/// attempt a daemon would make: the same starter choice (start, resume,
3450/// review), the same `Task::start` / `settle` transitions, attempt counting,
3451/// quota refund and parking. No second dispatcher - `magi run` and `magi
3452/// review` call this when no daemon is alive.
3453///
3454/// The caller holds the [`Queue::claim`] for the whole call, which is what
3455/// keeps a daemon that starts meanwhile from taking the task.
3456///
3457/// The one deliberate difference from the loop: a task the attempt leaves
3458/// runnable (failed with attempts to spare, or requeued) is **held** instead.
3459/// Nobody asked for a retry, and a daemon starting later must not spend agent
3460/// calls re-running a hand-started task behind the operator's back;
3461/// `magi task release` is the explicit retry.
3462pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
3463    let status = Arc::new(Mutex::new(Status::new()));
3464    let stop = Stop::new();
3465    attempt(
3466        opts,
3467        queue,
3468        &status,
3469        &stop,
3470        crate::graph::Pause::new(),
3471        task,
3472    )
3473    .await;
3474    // A run parked on the owner's word about a withheld PR title/body has no
3475    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
3476    // here with the claim still held, and resume once the question is settled
3477    // (answered, or abandoned at its deadline -> the neutral text).
3478    // A rejected reply files one more question (the gate asks at most twice),
3479    // so after a resume the run may be waiting again: keep going, with a fresh
3480    // limit for the new question. `resumes` bounds it even if a resume parks
3481    // without asking anything new.
3482    let mut resumes = 0;
3483    while resumes < MAX_WITHHELD_RESUMES {
3484        let Some(timeout) = withheld_text_wait(task) else {
3485            break;
3486        };
3487        eprintln!(
3488            "waiting for the owner's answer on a withheld pull request text \
3489             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
3490        );
3491        // The deadline abandons the question itself; the extra margin only
3492        // covers an abandon that could not be saved.
3493        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
3494        let ready = loop {
3495            match land_resume_state(task) {
3496                LandResume::StillWaiting if std::time::Instant::now() < limit => {
3497                    tokio::time::sleep(WITHHELD_POLL).await;
3498                }
3499                LandResume::Ready => break true,
3500                _ => break false,
3501            }
3502        };
3503        if !ready {
3504            break;
3505        }
3506        resumes += 1;
3507        attempt(
3508            opts,
3509            queue,
3510            &status,
3511            &stop,
3512            crate::graph::Pause::new(),
3513            task,
3514        )
3515        .await;
3516    }
3517    hold_if_runnable(queue, task);
3518}
3519
3520/// Resumes an in-process run makes for withheld-text questions: the gate asks
3521/// at most twice, plus one for a resume that asks nothing new.
3522const MAX_WITHHELD_RESUMES: u32 = 3;
3523
3524/// How often an in-process run rechecks its withheld-text question.
3525const WITHHELD_POLL: Duration = Duration::from_secs(15);
3526
3527/// The `answer_timeout` (seconds) of the task's last run when that run is
3528/// parked on an unresolved withheld-text question; `None` otherwise.
3529fn withheld_text_wait(task: &Task) -> Option<u64> {
3530    let id = task.runs.last()?;
3531    let s = RunState::load(id).ok()?;
3532    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
3533        .then_some(s.config.graph.answer_timeout)
3534}
3535
3536/// The quota losses `after` holds that `before` did not: what one execution
3537/// suffered, as opposed to the run's history.
3538///
3539/// Compared by value rather than by length or position because
3540/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
3541/// the vector can shrink and shift under a resume. A retried seat that hits
3542/// quota again is a `push` with a new `at`, so it shows up as new here.
3543/// `reclaim` deliberately keeps reading the whole history: after a crash there
3544/// is no attempt boundary to diff against.
3545fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
3546    after
3547        .iter()
3548        .filter(|q| !before.contains(q))
3549        .cloned()
3550        .collect()
3551}
3552
3553/// When the loop-wide quota cooldown should end, given this attempt's losses;
3554/// `None` when there were none. Reset-hint parsing and the cap live here.
3555fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
3556    if quota.is_empty() {
3557        return None;
3558    }
3559    let with_hint = quota.iter().find(|q| q.reset.is_some());
3560    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
3561    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
3562    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
3563    Some(
3564        now.checked_add(jiff::SignedDuration::from_secs(secs))
3565            .unwrap_or(Timestamp::MAX),
3566    )
3567}
3568
3569/// An explicit task count must agree with a run before any resume.
3570fn implementers_match(task: &Task, state: &RunState) -> bool {
3571    task.implementers()
3572        .is_none_or(|n| n == state.config.graph.implementers)
3573}
3574
3575/// Never resume or take over candidate work built for a different seat count.
3576fn starter_with_implementers(
3577    task: &Task,
3578    previous: Option<&RunState>,
3579    proposed: Starter,
3580) -> Starter {
3581    if previous.is_some_and(|s| !implementers_match(task, s)) {
3582        task.review_of
3583            .as_ref()
3584            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
3585    } else {
3586        proposed
3587    }
3588}
3589
3590/// Apply this task's explicit count to the new attempt, without changing defaults.
3591fn apply_task_implementers(config: &mut Config, task: &Task) {
3592    if let Some(n) = task.implementers() {
3593        config.graph.implementers = n;
3594    }
3595}
3596
3597/// [`prepare`] for one task: its own `--config` and command-line overrides
3598/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
3599/// over the loop's, so handing a hand-started task to a daemon changes nothing
3600/// about what it does.
3601fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
3602    let Some(o) = &task.overrides else {
3603        return prepare(repo, opts);
3604    };
3605    // A task filed by `magi run` / `magi review` was configured by that
3606    // command line alone: the loop's own `--config` / `--merge` must not leak
3607    // in, or the same command would behave differently with a loop alive.
3608    let own = Opts {
3609        config: o.config.clone(),
3610        merge: None,
3611        ..opts.clone()
3612    };
3613    let mut config = prepare(repo, if o.inherit_daemon_options { opts } else { &own })?;
3614    o.apply(&mut config);
3615    Ok(config)
3616}
3617
3618/// Load the config for a task's repository, with the merge override applied.
3619fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
3620    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
3621    if let Some(mode) = &opts.merge {
3622        config.merge.mode = merge_mode(mode)?;
3623    }
3624    Ok(config)
3625}
3626
3627/// Prune the shared build cache back under its cap at a safe boundary
3628/// between runs, so a queue that never empties - and so never reaches
3629/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
3630/// does not leave the cache to grow unchecked for as long as the backlog
3631/// lasts.
3632///
3633/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
3634/// same liveness fact the idle branch's own janitor call rests on - no run
3635/// this daemon spawned is still mid-compile - so pruning here races nothing.
3636/// The caller must not call this while a run is in flight; there is no
3637/// second `busy_now()` check inside this function, on purpose, because there
3638/// is nothing left to check that `busy_now()` has not already answered.
3639///
3640/// A stop that has already been asked for *is* checked here, for a different
3641/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
3642/// synchronously before it decides anything, so the poll loop cannot get back
3643/// to its own `stopped()` test until that walk is over — and a loop already
3644/// on its way out must not make the operator wait out housekeeping it is
3645/// about to stop needing. This is the same call the idle branch makes when it
3646/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
3647/// it matters more here: `busy_now()` is false throughout, so
3648/// [`Stop::finishing`] would report a stop as already landed while the walk
3649/// still held the loop. Nothing is lost by skipping — the cap is a standing
3650/// policy, and the next daemon's startup pass measures the same cache.
3651///
3652/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
3653/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
3654/// and the next has not yet claimed a task, which can be every few
3655/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
3656/// more than the growth it is guarding against.
3657async fn maybe_prune_cache_between_runs(
3658    repo: &Path,
3659    opts: &Opts,
3660    home: &Path,
3661    stop: &Stop,
3662    last_checked: &mut Option<Timestamp>,
3663    now: Timestamp,
3664) {
3665    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
3666        return;
3667    }
3668    *last_checked = Some(now);
3669    let cfg = match prepare(repo, opts) {
3670        Ok(cfg) => cfg,
3671        Err(e) => {
3672            tracing::warn!("cache check: no config: {e:#}");
3673            return;
3674        }
3675    };
3676    match clean::prune_cache_if_over_limit(&cfg, home) {
3677        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
3678            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
3679            pruned.files,
3680            pruned.freed
3681        ),
3682        Ok(_) => {}
3683        Err(e) => {
3684            tracing::warn!("housekeep: prune cache: {e:#}");
3685            notices::raise_in(
3686                home,
3687                Notice::warn(
3688                    "housekeep:cache",
3689                    "Pruning the shared build cache failed; disk usage may keep growing.",
3690                ),
3691            );
3692        }
3693    }
3694}
3695
3696/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
3697/// now, given when it last did (if ever). Pure, so the cadence is asserted
3698/// directly rather than by waiting out real minutes in a test.
3699fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
3700    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
3701}
3702
3703/// The disk janitor, with its housekeeping logged rather than fatal.
3704///
3705/// Called only at the loop's idle points, for the reason the caller documents:
3706/// a prune racing a live compile would delete files mid-build. The config is
3707/// re-read on every call because the repository that just ran may not be the
3708/// daemon's own default, and the cache directory is a repository fact.
3709///
3710/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
3711/// and [`crate::run::default_worktree_root`] read here, for the same reason
3712/// [`drive`] takes its queue and status file rather than resolving them: a
3713/// test driving the loop must not reach through to the operator's real home
3714/// or worktree bay just because the janitor runs on every idle tick.
3715/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
3716/// to get wrong silently - a test's `home` was already isolated, but nothing
3717/// exercised the parameter next to it, so a real worktree bay stayed wired in
3718/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
3719/// it for real, every test in this file that drives the loop at all started
3720/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
3721async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
3722    let cfg = match prepare(repo, opts) {
3723        Ok(cfg) => cfg,
3724        Err(e) => {
3725            tracing::warn!("housekeep: no config: {e:#}");
3726            return;
3727        }
3728    };
3729    // A run's own worktree lives under `config.graph.worktree_root` when the
3730    // repository sets one - the same precedence `RunState::worktree_root`
3731    // uses - and `worktrees_root` only stands in for the *default* an
3732    // unconfigured repository resolves to (see this function's own
3733    // parameter, or the test fixture wiring one to a fake path). Housekeeping
3734    // that always swept the default regardless of this override would never
3735    // see, and so never reclaim, a single worktree for a repository that
3736    // relocated them elsewhere.
3737    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
3738    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
3739    // Reported whenever there is anything to say, not only when `folded > 0`:
3740    // the incident this exists to prevent was 90 of 93 runs skipped and 0
3741    // folded, on every single pass, for months - a report gated on `folded`
3742    // would have stayed silent through every one of them.
3743    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
3744        let mut extra = Vec::new();
3745        if out.unreadable > 0 {
3746            extra.push(format!("{} unreadable", out.unreadable));
3747        }
3748        if out.orphaned_worktrees > 0 {
3749            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
3750        }
3751        let detail = if extra.is_empty() {
3752            String::new()
3753        } else {
3754            format!(" ({})", extra.join(", "))
3755        };
3756        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
3757    }
3758    if out.external_merges_recorded > 0 {
3759        tracing::info!(
3760            "housekeep: recorded {} run(s) as merged externally",
3761            out.external_merges_recorded
3762        );
3763    }
3764    if out.stale_pr_states_repaired > 0 {
3765        tracing::info!(
3766            "housekeep: rewrote {} run record(s) whose pull request had already settled",
3767            out.stale_pr_states_repaired
3768        );
3769    }
3770    if out.cache_files > 0 {
3771        tracing::info!(
3772            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
3773            out.cache_files,
3774            out.cache_freed
3775        );
3776    }
3777    if out.questions_abandoned > 0 {
3778        tracing::info!(
3779            "housekeep: abandoned {} question(s) left open by a finished run",
3780            out.questions_abandoned
3781        );
3782    }
3783}
3784
3785/// Run [`triage::run_once`] and log whatever it did, the same "only when
3786/// there is something to say" rule [`janitor`] follows for its own report.
3787///
3788/// Called at the same idle points as [`janitor`] - once per full poll
3789/// interval, never mid-attempt - for the same reason: it is not liveness
3790/// critical, and a task's own `hold_reason` string is the one thing this
3791/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
3792/// tick for no benefit.
3793async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
3794    let questions = Questions::at(home.join("questions"));
3795    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
3796    if report.is_empty() {
3797        return;
3798    }
3799    if !report.quarantined.is_empty() {
3800        tracing::info!(
3801            "triage: held {} blocked task(s) whose blocked-on task or \
3802             question no longer exists: {}",
3803            report.quarantined.len(),
3804            report.quarantined.join(", ")
3805        );
3806    }
3807    if !report.resumed.is_empty() {
3808        tracing::info!(
3809            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
3810            report.resumed.len(),
3811            report.resumed.join(", ")
3812        );
3813    }
3814    if !report.asked.is_empty() {
3815        tracing::info!(
3816            "triage: asked about {} held task(s): {}",
3817            report.asked.len(),
3818            report.asked.join(", ")
3819        );
3820    }
3821    if !report.answered.is_empty() {
3822        tracing::info!(
3823            "triage: applied {} operator answer(s): {}",
3824            report.answered.len(),
3825            report.answered.join(", ")
3826        );
3827    }
3828}
3829
3830/// The free-space gate: what stands between this task and a new run, if
3831/// anything. `Some(reason)` holds the task; `None` lets it start.
3832///
3833/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
3834/// the operator opted out. A measurement failure is a gate, not a pass: both
3835/// sides of "cannot tell" are served by not starting.
3836fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
3837    disk_gate_with(repo, config, crate::disk::free_bytes)
3838}
3839
3840/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
3841/// test can assert the exact wiring `attempt` runs - config's threshold in,
3842/// task-holding reason out - without asking the real machine's disk anything.
3843fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
3844    repo: &Path,
3845    config: &Config,
3846    free_bytes: F,
3847) -> Option<String> {
3848    let min = config.disk.min_free_bytes;
3849    if min == 0 {
3850        return None;
3851    }
3852    match free_bytes(repo) {
3853        Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
3854        Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
3855    }
3856}
3857
3858/// How long to wait before offering another task when a run lost a seat to a
3859/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
3860/// could read, or carried nothing at all. Long enough that a quota outage
3861/// cannot burn through a whole backlog in the few seconds each doomed attempt
3862/// takes to fail; short enough that a quota which clears early is not left
3863/// idle for the fallback's sake.
3864const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
3865
3866/// Longest a parsed reset hint may push the wait out to. The hint comes from
3867/// the CLI's own words, not a contract, so a parsing slip that lands a day
3868/// away must not leave the loop asleep for a day.
3869const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
3870
3871/// How long [`poll`] should wait before offering the next task, after a run
3872/// lost at least one seat to a rate limit.
3873///
3874/// Pure and separate from the loop so the policy can be exercised without a
3875/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
3876/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
3877/// nothing to parse, or the parsed time has already passed; `cap` bounds how
3878/// far a parsed hint is trusted to push the wait out.
3879fn quota_wait(
3880    reset_at: Option<Timestamp>,
3881    now: Timestamp,
3882    fallback: Duration,
3883    cap: Duration,
3884) -> Duration {
3885    match reset_at {
3886        Some(at) if at > now => {
3887            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
3888            Duration::from_secs(secs).min(cap)
3889        }
3890        _ => fallback,
3891    }
3892}
3893
3894/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
3895///
3896/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
3897/// explains why parsing it exactly "would be a bug factory" — so this only
3898/// recognises the shapes actually observed in the wild, and returns `None`
3899/// for anything else rather than guess at a format nobody has seen.
3900///
3901/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
3902/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
3903/// said it, not from whenever this loop happens to read it: anchoring on `now`
3904/// would push the reset later on every read and would read an already-elapsed
3905/// reset as still in the future. (A long hint is still clamped by
3906/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
3907fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3908    parse_reset_hint_zoned(text, now)
3909        .or_else(|| parse_reset_hint_dated(text))
3910        .or_else(|| parse_reset_hint_relative(text, recorded))
3911}
3912
3913/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
3914/// optional but at least one required, in that order. A bare number or any
3915/// unknown unit is refused.
3916fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3917    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3918    let mut rest = rest.trim();
3919    if rest.is_empty() {
3920        return None;
3921    }
3922    let mut total: i64 = 0;
3923    let mut matched = false;
3924    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3925        if let Some((digits, tail)) = rest.split_once(unit)
3926            && !digits.is_empty()
3927            && digits.bytes().all(|b| b.is_ascii_digit())
3928        {
3929            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3930            rest = tail;
3931            matched = true;
3932        }
3933    }
3934    if !rest.is_empty() || !matched {
3935        return None;
3936    }
3937    recorded
3938        .checked_add(jiff::SignedDuration::from_secs(total))
3939        .ok()
3940}
3941
3942/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
3943/// case-insensitive) into a 24-hour hour and minute. Shared by every
3944/// reset-hint shape below.
3945fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3946    let clock = clock.trim().to_lowercase();
3947    let (digits, pm) = clock
3948        .strip_suffix("am")
3949        .map(|d| (d, false))
3950        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3951    let (h, m) = digits.trim().split_once(':')?;
3952    let mut hour: i8 = h.trim().parse().ok()?;
3953    let minute: i8 = m.trim().parse().ok()?;
3954    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3955        return None;
3956    }
3957    if pm && hour != 12 {
3958        hour += 12;
3959    } else if !pm && hour == 12 {
3960        hour = 0;
3961    }
3962    Some((hour, minute))
3963}
3964
3965/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
3966/// and a zone, never a date. A clock reading already past today is read as
3967/// tomorrow's: a CLI naming a same-day reset that has already gone by means
3968/// the window rolled over while nothing was watching.
3969fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3970    let open = text.find('(')?;
3971    let close = text.rfind(')')?;
3972    if close <= open {
3973        return None;
3974    }
3975    let zone = text[open + 1..close].trim();
3976    let (hour, minute) = parse_12h_clock(&text[..open])?;
3977    let tz = jiff::tz::TimeZone::get(zone).ok()?;
3978    let candidate = now
3979        .to_zoned(tz)
3980        .with()
3981        .hour(hour)
3982        .minute(minute)
3983        .second(0)
3984        .millisecond(0)
3985        .microsecond(0)
3986        .nanosecond(0)
3987        .build()
3988        .ok()?;
3989    let mut at = candidate.timestamp();
3990    if at <= now {
3991        at += jiff::SignedDuration::from_hours(24);
3992    }
3993    Some(at)
3994}
3995
3996/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
3997/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
3998/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
3999/// "already past today" correction to make: the year already disambiguates
4000/// it. Scanned as a five-word window so it can be pulled out of the middle
4001/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
4002/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
4003/// any other timestamp with no zone attached.
4004fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4005    let words: Vec<&str> = text.split_whitespace().collect();
4006    if words.len() < 5 {
4007        return None;
4008    }
4009    (0..=words.len() - 5)
4010        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4011}
4012
4013/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
4014/// parenthesis right after the window is refused rather than ignored — it
4015/// reads as an explicit zone annotation on a shape that otherwise carries
4016/// none, and guessing UTC anyway would be exactly the silent misread this
4017/// module's parsing otherwise avoids.
4018fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4019    if trailing.is_some_and(|next| next.starts_with('(')) {
4020        return None;
4021    }
4022    let month = month_number(window[0])?;
4023    let day_token = window[1].strip_suffix(',')?.to_lowercase();
4024    let day_digits = ["st", "nd", "rd", "th"]
4025        .iter()
4026        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4027    let day: i8 = day_digits.parse().ok()?;
4028    let year_token = window[2];
4029    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4030        return None;
4031    }
4032    let year: i16 = year_token.parse().ok()?;
4033    // The am/pm word carries the sentence's own trailing punctuation, e.g.
4034    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
4035    // reusing the same 12-hour clock reader the bracketed shape uses.
4036    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4037    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4038    let date = jiff::civil::Date::new(year, month, day).ok()?;
4039    let candidate = date
4040        .at(hour, minute, 0, 0)
4041        .to_zoned(jiff::tz::TimeZone::UTC)
4042        .ok()?;
4043    Some(candidate.timestamp())
4044}
4045
4046/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
4047/// case-insensitively, into a 1-based month number.
4048fn month_number(name: &str) -> Option<i8> {
4049    const NAMES: [&str; 12] = [
4050        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4051    ];
4052    let lower = name.to_lowercase();
4053    NAMES
4054        .iter()
4055        .position(|n| *n == lower.as_str())
4056        .map(|i| i as i8 + 1)
4057}
4058
4059/// Resuming a `Blocked` run that already spent every review round its own
4060/// config allowed cannot make progress: `graph::Runner`'s review loop walks
4061/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
4062/// reached `max_rounds`, so `execute` would settle straight back to
4063/// `Blocked` without asking anyone anything. Read-only against a state this
4064/// build never mutates — `src/graph.rs` stays untouched — but without this
4065/// check, [`unfinished_run`] would keep reporting such a run as still
4066/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
4067/// promise is a fresh competition when a design needs to change) would
4068/// silently resume the exhausted run instead, spending an attempt on a
4069/// cycle that cannot change anything.
4070fn exhausted_review_budget(state: &RunState) -> bool {
4071    // A run whose task-head publication failed has nothing left to review:
4072    // resuming it only retries the publication, so it is never "exhausted".
4073    state.status == RunStatus::Blocked
4074        && !state.pr_publication_pending
4075        && state.reviews.len() >= state.config.graph.review_rounds
4076}
4077
4078/// This task's *most recent* run, if resuming it would actually make
4079/// progress. `short` is only for the warning's own message.
4080///
4081/// Only ever `runs.last()` — never a search back through older history.
4082/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
4083/// mint, oldest first, and every entry before the last one was already
4084/// superseded at the moment it was minted: the daemon only ever starts a new
4085/// run when the previous one was not worth resuming (unresumable, exhausted,
4086/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
4087/// opens a fresh review-only run alongside an older, already-failed
4088/// competition. Searching further back would let an old run that merely
4089/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
4090/// behind, say — get resumed instead of the fresh competition
4091/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
4092/// nothing asked to revisit.
4093///
4094/// Two runs paid for the "prefer resuming over restarting" half of this
4095/// lesson, which is why this still checks `runs.last()` rather than always
4096/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
4097/// task a moment later, duplicating two and a half hours of agent work. Then
4098/// b25f stalled on a judge that timed out and one that answered with no JSON
4099/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
4100/// **one second** later, buying three fresh implementations to reach the
4101/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
4102/// the second case: a stall is terminal, and its cheap recovery re-asks only
4103/// the absent seats. [`exhausted_review_budget`] is the other half: a run
4104/// that is technically `resumable()` but provably cannot progress must not
4105/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
4106/// no-op instead of the fresh competition it promises.
4107///
4108/// A load failure is warned about rather than silently read as "not
4109/// resumable": the alternative is exactly what let a schema mismatch on run
4110/// `eba2` fall through to a full re-competition with nobody told why.
4111/// `crate::conduct` is what actually offers a better answer than
4112/// `Runner::start` here (see `Recovery::Review`), once this task's next
4113/// failure shows it up as `held`/`failed` with the run state unreadable.
4114fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4115    unfinished_run_with(runs, short, RunState::load)
4116}
4117
4118/// [`unfinished_run`] with an injected state reader. Tests provide their
4119/// fixtures directly rather than touching the process-global run home.
4120fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
4121where
4122    F: FnOnce(&str) -> Result<RunState>,
4123{
4124    let id = runs.last()?;
4125    match load(id) {
4126        // A run some process is driving right now is not "unfinished" in the
4127        // sense of waiting to be picked up: a run started by hand is in
4128        // `runs` while it is still executing, and resuming it here
4129        // would put a second driver on the same worktrees.
4130        Ok(s)
4131            if s.status.resumable()
4132                && !s.released()
4133                && !exhausted_review_budget(&s)
4134                && s.liveness(false) != crate::run::Liveness::Live =>
4135        {
4136            Some(id.clone())
4137        }
4138        Ok(_) => None,
4139        Err(e) => {
4140            tracing::warn!("could not read run {id} for task {short}: {e:#}");
4141            None
4142        }
4143    }
4144}
4145
4146/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
4147/// that [`attempt`] will resume it on its own?
4148///
4149/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
4150/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
4151/// injected reader like its sibling. An unreadable run is not awaiting
4152/// anything: it keeps going to the conductor as before.
4153fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
4154where
4155    F: FnOnce(&str) -> Result<RunState>,
4156{
4157    // `Failed` stays: a record an older build wrote for a parked run.
4158    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
4159        || task.fresh_start
4160        || task.review_branch.is_some()
4161    {
4162        return false;
4163    }
4164    let Some(id) = task.runs.last() else {
4165        return false;
4166    };
4167    load(id).is_ok_and(|s| {
4168        s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
4169    })
4170}
4171
4172/// Which of the three ways [`attempt`] can mint or continue a run this task
4173/// should use.
4174#[derive(Debug, Clone, PartialEq, Eq)]
4175enum Starter {
4176    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
4177    /// and that still exists.
4178    Review(String),
4179    /// `crate::graph::Runner::resume` on an unfinished run of this task.
4180    Resume(String),
4181    /// `crate::graph::Runner::start`: a fresh competition.
4182    Start,
4183}
4184
4185/// A selected public implementation overrides every historical candidate and pin.
4186fn selected_starter(
4187    selected: &crate::pr_recovery::Selection,
4188    previous: Option<&RunState>,
4189    unfinished: Option<&str>,
4190) -> Starter {
4191    if let Some(id) = unfinished
4192        && previous.is_some_and(|r| {
4193            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
4194        })
4195    {
4196        Starter::Resume(id.to_owned())
4197    } else {
4198        Starter::Review(selected.branch.clone())
4199    }
4200}
4201
4202/// The owner's answer to this branch's divergence question, consumed from the
4203/// task so a later, different divergence asks again. The runner applies it
4204/// (see `Runner::review_taking_over`), after the earlier worktree is released.
4205fn take_divergence_answer(
4206    branch: &str,
4207    remote: &str,
4208    task: &mut Task,
4209) -> Option<crate::reconcile::Choice> {
4210    let summary = crate::reconcile::summary_for(branch, remote);
4211    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
4212        (a.question == summary)
4213            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
4214            .flatten()
4215            .map(|c| (i, c))
4216    })?;
4217    task.answers.remove(idx);
4218    Some(choice)
4219}
4220
4221/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
4222/// this attempt should use. Pure, and separate from [`attempt`], so the
4223/// routing itself is assertable without spawning a real graph or a git
4224/// process: `attempt`'s own `crate::git::branch_exists` call has already
4225/// happened by the time this is called.
4226///
4227/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
4228/// whose branch is gone falls all the way through to [`Starter::Start`], not
4229/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
4230/// old (likely `Blocked`) run in the first place, and a branch that vanished
4231/// out from under that choice is not evidence resuming it would fare better.
4232fn choose_starter(
4233    review_branch: Option<&str>,
4234    branch_exists: bool,
4235    unfinished: Option<&str>,
4236) -> Starter {
4237    match review_branch {
4238        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
4239        Some(_) => Starter::Start,
4240        None => match unfinished {
4241            Some(id) => Starter::Resume(id.to_owned()),
4242            None => Starter::Start,
4243        },
4244    }
4245}
4246
4247/// Consume a retained review only while its authored criteria still match.
4248fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
4249    let branch = task.review_branch.take();
4250    let instruction = task.review_instruction.take();
4251    branch.filter(|branch| match &instruction {
4252        Some(authored) => *authored == task.instruction,
4253        // Legacy retained branches must agree with their prior run; only an
4254        // explicitly pinned review can proceed without recoverable provenance.
4255        None => previous.map_or_else(
4256            || task.review_of.as_ref() == Some(branch),
4257            |run| compatible_run_instruction(run, task),
4258        ),
4259    })
4260}
4261
4262/// A current explicit pin can select an otherwise incompatible run. Edits
4263/// and subsequent approvals invalidate pins selected for earlier criteria.
4264fn may_resume_run(run: &RunState, task: &Task) -> bool {
4265    task.resume_override
4266        .as_ref()
4267        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
4268        || compatible_run_instruction(run, task)
4269}
4270
4271/// Review scaffolding is execution context, not evidence of an operator edit.
4272pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
4273    if let Some(authored) = &run.task_instruction {
4274        return compatible_instruction(authored, task);
4275    }
4276    if compatible_instruction(&run.instruction, task) {
4277        return true;
4278    }
4279    // Recognize only the existing generated review shapes on legacy runs.
4280    // Ordinary authored text with a similar heading is left intact.
4281    if run.reviewed_commits.is_some() {
4282        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
4283            return strip_answers_block(authored, task).trim() == task.instruction.trim();
4284        }
4285        if let Some(branch) = &task.review_of {
4286            let canonical = format!(
4287                "Review the branch `{branch}` (review-only: no implementation, no judging)."
4288            );
4289            let generated = format!(
4290                "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"
4291            );
4292            return task.instruction == canonical && run.instruction.starts_with(&generated);
4293        }
4294    }
4295    false
4296}
4297
4298/// Compare authored instructions, excluding answer blocks appended by the daemon.
4299pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
4300    strip_answers_block(old, task) == task.instruction
4301}
4302
4303/// Which repository a task runs in. A task that names none — the normal case
4304/// for one filed from a phone — runs in the daemon's own default.
4305fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
4306    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
4307        return fallback.to_path_buf();
4308    }
4309    task.repo.clone()
4310}
4311
4312/// The header [`append_answers`] appends operator answers under. Shared with
4313/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
4314/// rather than grown a new block on every resume.
4315const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
4316
4317/// Render the first `count` answers in the block appended to an instruction.
4318fn answers_block(task: &Task, count: usize) -> String {
4319    let mut s = ANSWERS_HEADER.to_owned();
4320    for a in &task.answers[..count] {
4321        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
4322    }
4323    s
4324}
4325
4326/// Render the approval independently of transient task state, so historical
4327/// suffixes remain recognizable after another explicit release.
4328fn resumption_block(r: &crate::queue::Resumption) -> String {
4329    format!(
4330        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
4331         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
4332        r.generation, r.at, r.instruction, r.answers_through,
4333    )
4334}
4335
4336/// Append audit answers and the latest explicit approval to the instruction.
4337fn append_answers(base: &str, task: &Task) -> String {
4338    let mut s = base.to_owned();
4339    if !task.answers.is_empty() {
4340        s.push_str(&answers_block(task, task.answers.len()));
4341    }
4342    if let Some(r) = &task.resumption {
4343        s.push_str(&resumption_block(r));
4344    }
4345    s
4346}
4347
4348/// Drop the prior answer block only when it is exactly the suffix this task
4349/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
4350/// the task author is ordinary instruction text, not a block to remove.
4351fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
4352    let mut instruction = instruction;
4353    for approval in task
4354        .resumption
4355        .iter()
4356        .chain(task.resumption_history.iter().rev())
4357    {
4358        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
4359            instruction = base;
4360            break;
4361        }
4362    }
4363    for count in (1..=task.answers.len()).rev() {
4364        let block = answers_block(task, count);
4365        if let Some(base) = instruction.strip_suffix(&block) {
4366            return base;
4367        }
4368    }
4369    instruction
4370}
4371
4372/// The instruction handed to `Runner::start`: the task's own text, plus any
4373/// operator answers `crate::conduct` collected for it (see
4374/// [`Task::answers`]), so a decision the operator actually made reaches the
4375/// implementers rather than only clearing the block that was waiting on it.
4376///
4377/// Appended rather than merged into [`Task::instruction`] itself, so the
4378/// task's own record stays exactly what its author wrote.
4379fn instruction_for(task: &Task) -> String {
4380    append_answers(&task.instruction, task)
4381}
4382
4383/// The instruction a resumed run should carry on with: whatever it already
4384/// had, refreshed with the task's *current* operator answers.
4385///
4386/// A resumable run's own `RunState::instruction` predates any answer
4387/// `crate::conduct` collects after the run parks, so resuming it unchanged —
4388/// the behaviour before this function existed — silently drops the very
4389/// decision the operator made to unblock it. Re-stripping any block this
4390/// function appended on an earlier resume before re-appending the current
4391/// list (rather than blindly appending again) is what keeps a task resumed
4392/// three times over three answered questions from carrying the same answer
4393/// three times.
4394fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
4395    append_answers(strip_answers_block(old_instruction, task), task)
4396}
4397
4398/// Preserve the producer's verified boundary and target, independent of prose.
4399fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
4400    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
4401    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
4402    if let Some(cause) = task.hold_notice_cause.as_mut() {
4403        cause.target = failure.map(|f| f.target.clone());
4404    }
4405}
4406
4407#[derive(Debug, thiserror::Error)]
4408#[error("attachment `{name}` is recorded on the task but {path} is missing")]
4409struct MissingAttachment {
4410    name: String,
4411    path: PathBuf,
4412}
4413
4414/// The task's attachments as absolute paths, each checked to still exist.
4415fn task_attachments(
4416    queue: &Queue,
4417    task: &Task,
4418) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
4419    let paths = queue.attachment_paths(task);
4420    for (name, path) in task.attachments.iter().zip(&paths) {
4421        if !path.is_file() {
4422            return Err(MissingAttachment {
4423                name: name.clone(),
4424                path: path.clone(),
4425            });
4426        }
4427    }
4428    Ok(paths)
4429}
4430
4431/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
4432/// answers before handing it to `Runner` — the actual boundary between
4433/// [`choose_starter`]'s routing and the graph, factored out so it is
4434/// assertable without a real repository, git branch, or agent CLI.
4435///
4436/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
4437/// instruction from the reviewed branch's own commit log because there is no
4438/// task statement to speak of for hand-written work, and splicing operator
4439/// answers into that text would contradict the very message it sends
4440/// reviewers ("there is no task statement").
4441fn prepare_instruction(
4442    starter: &Starter,
4443    old_instruction: Option<&str>,
4444    task: &Task,
4445) -> Option<String> {
4446    match starter {
4447        Starter::Start => Some(instruction_for(task)),
4448        Starter::Resume(_) => Some(resumed_instruction(
4449            old_instruction.expect("a resumed run always has a prior instruction"),
4450            task,
4451        )),
4452        Starter::Review(_) => None,
4453    }
4454}
4455
4456/// Persist a transition. A queue write failure is logged rather than fatal: the
4457/// run already happened, and taking the daemon down would only add a lost
4458/// backlog to a full disk.
4459fn record(queue: &Queue, task: &mut Task) {
4460    if let Err(e) = queue.put(task) {
4461        tracing::error!("could not record task {}: {e:#}", task.short());
4462        let notice = Notice::error(
4463            "loop:record",
4464            "The loop could not save a task's state; check the disk.",
4465        )
4466        .link(Link::Task {
4467            id: task.id.clone(),
4468        });
4469        // The queue lives at `<home>/queue`, so its parent is the home.
4470        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
4471            Some(home) => notices::raise_in(home, notice),
4472            None => notices::raise(notice),
4473        }
4474    }
4475}
4476
4477/// Every runnable task, in the order the loop should try them.
4478///
4479/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
4480/// tail exists so that a claim somebody else holds costs the loop the next
4481/// candidate rather than a whole poll interval of idleness.
4482fn runnable(queue: &Queue) -> Vec<Task> {
4483    let mut tasks: Vec<Task> = queue
4484        .list()
4485        .into_iter()
4486        .filter(|t| t.status.runnable())
4487        .collect();
4488    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
4489    tasks
4490}
4491
4492/// Why a run ended where it did, in one line, for [`Task::last_error`].
4493///
4494/// A stalled run names the seats the quota took out: "out of quota" is not
4495/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
4496/// agent to replace or which plan to top up.
4497///
4498/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
4499/// purpose: unlike `label`'s other callers (an internal log line, an
4500/// already-a-bug fallback message), this string becomes `Task::last_error`
4501/// verbatim, which the phone renders in the same alarm-styled box an
4502/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
4503/// `.err` styling. A bare `verified_noop` there would read exactly like the
4504/// failure this whole feature exists to tell apart from one.
4505fn describe(state: &RunState) -> String {
4506    let p = phrases(&state.config.graph.language);
4507    let mut detail = if state.status == RunStatus::Stalled {
4508        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
4509        seats.sort_unstable();
4510        seats.dedup();
4511        if seats.is_empty() {
4512            p.quorum_lost.to_owned()
4513        } else {
4514            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
4515        }
4516    } else {
4517        format!("{}{}", p.run_ended, state.status.display_label())
4518    };
4519    if let Some(last) = state.events.last() {
4520        // The review loop's "never answered" stop is the one event worth
4521        // translating; it is recognised from structured state, not by
4522        // matching the English event text (which stays as recorded).
4523        let unanswered = state
4524            .reviews
4525            .last()
4526            .filter(|r| {
4527                state.status == RunStatus::Blocked
4528                    && last.node == "review"
4529                    && r.incomplete()
4530                    && r.blocking == 0
4531                    && r.round == state.config.graph.review_rounds
4532                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
4533            })
4534            .map(|r| (r.expected - r.answered, r.round));
4535        match unanswered {
4536            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
4537                detail.push_str(&format!(
4538                    " ({}: {})",
4539                    last.node,
4540                    (p.reviewers_never_answered)(missing, rounds)
4541                ));
4542            }
4543            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
4544        }
4545    }
4546    detail.push_str(&format!(" [run {}]", state.id));
4547    detail
4548}
4549
4550/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
4551///
4552/// The task file lives in the backlog indefinitely; a diagnostic is an
4553/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
4554/// stay small regardless of how much a gate command or a candidate printed.
4555const DIAGNOSTIC_MAX: usize = 4_000;
4556
4557/// Tail kept from a single failing command's output inside a diagnostic.
4558/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
4559/// pointer for a human deciding whether to go read the full artifact by hand,
4560/// not a replacement for reading it.
4561const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
4562
4563/// Assemble a bounded diagnostic excerpt from a held task's own run, so
4564/// `magi task show` says more than the one-line reason in [`describe`].
4565///
4566/// The one-liner answers "where did the run stop"; this answers "what would a
4567/// human have found opening `artifacts/` by hand" — the point of the whole
4568/// feature is the case that one-liner actively misleads on: a run held as "no
4569/// candidate produced a change" can mean the implementer actually finished
4570/// the task (opened a PR, merged it, tagged a release) and only left a clean
4571/// local worktree behind, which reads as "nothing happened" unless someone
4572/// goes and reads what the agent actually said. `None` when the run carries
4573/// none of the three shapes this recognises — an ordinary run held for
4574/// something not diagnosable from `RunState` alone still explains itself
4575/// through `Task::last_error`.
4576fn diagnostic(state: &RunState) -> Option<String> {
4577    let mut parts: Vec<String> = Vec::new();
4578
4579    // Gate failure: which check(s), and the tail of what each printed.
4580    for o in state.gate.iter().filter(|o| !o.ok()) {
4581        parts.push(format!(
4582            "gate `{}` failed ({:?}):\n{}",
4583            o.command,
4584            o.code,
4585            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
4586        ));
4587    }
4588
4589    // The land loop gave up because the fixer declined while checks were
4590    // still red: the message already names them (see `land::run`).
4591    if let Some(last) = state
4592        .events
4593        .iter()
4594        .rev()
4595        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
4596    {
4597        parts.push(last.message.clone());
4598    }
4599
4600    // No viable candidate: every implementer's own final word, sanitized the
4601    // same way a judge would have read it, so a run that actually finished
4602    // the job does not read as an unexplained failure. A verified no-op is
4603    // called out ahead of its own summary and apart from an ordinary
4604    // failure's `why` — this is the one candidate shape whose diagnostic a
4605    // human is expected to actually judge, not just skim.
4606    if state.viable().is_empty() {
4607        for c in &state.candidates {
4608            if let Some(evidence) = &c.verified_noop {
4609                parts.push(format!(
4610                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
4611                    c.label
4612                ));
4613            } else if !c.summary.trim().is_empty() {
4614                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
4615            } else if let Some(why) = &c.failed {
4616                parts.push(format!("candidate {}: {why}", c.label));
4617            }
4618        }
4619    }
4620
4621    if parts.is_empty() {
4622        return None;
4623    }
4624    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
4625    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
4626    // back slightly over. Leave it enough room to always land under the
4627    // limit.
4628    Some(crate::run::tail(
4629        &parts.join("\n\n"),
4630        DIAGNOSTIC_MAX.saturating_sub(100),
4631    ))
4632}
4633
4634/// Stable lower-case name for a run status, for an internal log line and the
4635/// "graph stopped without reaching a terminal status" bug message in
4636/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
4637/// doc for why that one reads [`RunStatus::display_label`] instead. One
4638/// definition of a status's name, on the type that owns it: this table used
4639/// to live here as a second copy, and a status renamed in one place would
4640/// have gone on reading correctly in the other.
4641fn label(status: RunStatus) -> &'static str {
4642    status.as_str()
4643}
4644
4645/// Parse a merge mode override.
4646pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
4647    match mode {
4648        "none" => Ok(MergeMode::None),
4649        "local" => Ok(MergeMode::Local),
4650        "pr" => Ok(MergeMode::Pr),
4651        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
4652    }
4653}
4654
4655/// Take the status lock, recovering from a poisoned one.
4656///
4657/// A panic elsewhere must not silently stop the heartbeat: the status is plain
4658/// data, and the worst a poisoned lock can hold is a stale timestamp.
4659fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
4660    mutex
4661        .lock()
4662        .unwrap_or_else(std::sync::PoisonError::into_inner)
4663}
4664
4665#[cfg(test)]
4666mod tests {
4667    use super::*;
4668    use crate::queue::{Source, TaskStatus};
4669    use crate::run::{Candidate, CommandOutcome};
4670    use pretty_assertions::assert_eq;
4671
4672    fn task() -> Task {
4673        Task::new(
4674            "add retries".to_owned(),
4675            "add retries".to_owned(),
4676            PathBuf::from("/repo"),
4677            Source::Human,
4678        )
4679    }
4680
4681    #[test]
4682    fn selected_public_head_overrides_historical_resume_and_pin() {
4683        let mut t = task();
4684        let mut old = run_state(RunStatus::Blocked);
4685        let selection = crate::pr_recovery::Selection {
4686            url: "url".into(),
4687            branch: format!("magi/task-{}", t.id),
4688            head: "a".repeat(40),
4689            instruction: t.instruction.clone(),
4690            approved_at: Timestamp::now(),
4691        };
4692        t.resume_override = Some(crate::queue::OperatorResume {
4693            pinned_run: Some(old.id.clone()),
4694            question_id: "choice".into(),
4695            at: Timestamp::now(),
4696            conductor_rehold: None,
4697            forced: false,
4698        });
4699        assert_eq!(
4700            selected_starter(&selection, Some(&old), Some(&old.id)),
4701            Starter::Review(selection.branch.clone())
4702        );
4703        old.pr_recovery = Some(selection.clone());
4704        assert_eq!(
4705            selected_starter(&selection, Some(&old), Some(&old.id)),
4706            Starter::Review(selection.branch.clone())
4707        );
4708        old.reviewed_commits = Some(vec!["implementation".into()]);
4709        assert_eq!(
4710            selected_starter(&selection, Some(&old), Some(&old.id)),
4711            Starter::Resume(old.id.clone())
4712        );
4713        let mut changed = selection.clone();
4714        changed.head = "b".repeat(40);
4715        assert_eq!(
4716            selected_starter(&changed, Some(&old), Some(&old.id)),
4717            Starter::Review(changed.branch)
4718        );
4719    }
4720
4721    #[test]
4722    fn candidate_transplant_failure_is_one_actionable_hold() {
4723        let dir = tempfile::tempdir().unwrap();
4724        let q = Queue::at(dir.path().join("queue"));
4725        let mut t = task();
4726        let mut state = run_state(RunStatus::Blocked);
4727        state.event("prep", "cannot apply referenced commit: conflict");
4728        state.prep_failure = Some("conflict".into());
4729        t.start(state.id.clone());
4730        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
4731        assert_eq!(t.attempts, 1);
4732        assert_eq!(t.status, TaskStatus::Held);
4733        assert!(t.operator_held());
4734        assert!(!t.status.runnable());
4735        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
4736        let first = t.chat_notice_key().unwrap();
4737        t.chat_notices.push(first.clone());
4738        t.release_operator("test", None);
4739        state.id = "another-unprepared-run".into();
4740        t.start(state.id.clone());
4741        finish_attempt(
4742            3,
4743            &q,
4744            &mut t,
4745            &state,
4746            &[],
4747            Err(anyhow::anyhow!("still conflicts")),
4748        );
4749        assert_eq!(
4750            t.chat_notice_key().as_ref(),
4751            Some(&first),
4752            "no work happened"
4753        );
4754        t.release_operator("test", None);
4755        state.prep_failure = None;
4756        state.status = RunStatus::Failed;
4757        state.begin_pass();
4758        t.start(state.id.clone());
4759        finish_attempt(
4760            1,
4761            &q,
4762            &mut t,
4763            &state,
4764            &[],
4765            Err(anyhow::anyhow!("new gate failure")),
4766        );
4767        let failure = t.chat_notice_key().unwrap();
4768        assert_ne!(failure, first, "approved recovery reached a real failure");
4769        t.release_operator("test", None);
4770        state.begin_pass();
4771        t.start(state.id.clone());
4772        finish_attempt(
4773            1,
4774            &q,
4775            &mut t,
4776            &state,
4777            &[],
4778            Err(anyhow::anyhow!("new failure on resume")),
4779        );
4780        assert_ne!(
4781            t.chat_notice_key().as_ref(),
4782            Some(&failure),
4783            "a new settled pass"
4784        );
4785    }
4786
4787    #[test]
4788    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
4789        for source in ["cli", "web"] {
4790            let mut t = task();
4791            let mut run = run_state(RunStatus::Blocked);
4792            run.instruction = "Run A original criteria".into();
4793            run.task_instruction = Some(run.instruction.clone());
4794            t.start(run.id.clone());
4795            t.release_operator("choice", Some("resume-question"));
4796            t.resume_override = Some(crate::queue::OperatorResume {
4797                question_id: "resume-question".into(),
4798                at: Timestamp::now(),
4799                conductor_rehold: None,
4800                forced: true,
4801                pinned_run: Some(run.id.clone()),
4802            });
4803            t.hold_machine(Some("not enough free space to start a run".into()));
4804            let mut unchanged = t.clone();
4805            unchanged
4806                .edit("title changed".into(), unchanged.instruction.clone())
4807                .unwrap();
4808            unchanged.release_operator(source, None);
4809            assert_eq!(
4810                unchanged
4811                    .resume_override
4812                    .as_ref()
4813                    .unwrap()
4814                    .pinned_run
4815                    .as_deref(),
4816                Some(run.id.as_str())
4817            );
4818            assert!(!compatible_run_instruction(&run, &unchanged));
4819            assert!(may_resume_run(&run, &unchanged));
4820
4821            t.edit(
4822                "approved recovery".into(),
4823                "Reuse measured PR head B; fix Clippy; review".into(),
4824            )
4825            .unwrap();
4826            assert!(t.resume_override.is_none());
4827            t.release_operator(source, None);
4828            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
4829            assert!(reloaded.resume_override.is_none());
4830            assert!(!may_resume_run(&run, &reloaded));
4831            let unfinished =
4832                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
4833                    .filter(|_| may_resume_run(&run, &reloaded));
4834            assert_eq!(
4835                choose_starter(None, false, unfinished.as_deref()),
4836                Starter::Start
4837            );
4838            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
4839            assert_eq!(
4840                reloaded.resumption_history[0].question_id.as_deref(),
4841                Some("resume-question")
4842            );
4843
4844            // A revision already persisted with the old approval/pin is also
4845            // invalidated when the new operator release is recorded.
4846            unchanged.instruction = "Reuse measured PR head B".into();
4847            unchanged.hold_machine(Some("disk hold".into()));
4848            unchanged.release_operator(source, None);
4849            assert!(unchanged.resume_override.is_none());
4850            assert!(!may_resume_run(&run, &unchanged));
4851        }
4852    }
4853
4854    #[test]
4855    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
4856        let mut t = task();
4857        let mut run = run_state(RunStatus::Blocked);
4858        t.review_of = Some("approved-head".into());
4859        t.instruction =
4860            "Review the branch `approved-head` (review-only: no implementation, no judging)."
4861                .into();
4862        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();
4863        run.reviewed_commits = Some(vec!["Commit log".into()]);
4864        t.start(run.id.clone());
4865        t.hold_machine(Some("interrupted review".into()));
4866        t.release_operator("cli", None);
4867        assert!(
4868            compatible_run_instruction(&run, &t),
4869            "legacy explicit review remains resumable"
4870        );
4871        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
4872            .filter(|_| compatible_run_instruction(&run, &t));
4873        assert_eq!(
4874            choose_starter(None, false, unfinished.as_deref()),
4875            Starter::Resume(run.id.clone())
4876        );
4877        run.task_instruction = Some(t.instruction.clone());
4878        assert!(compatible_run_instruction(&run, &t));
4879        let reloaded: RunState =
4880            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
4881        assert!(compatible_run_instruction(&reloaded, &t));
4882        t.edit(
4883            "new approved head".into(),
4884            "Reuse measured PR head B".into(),
4885        )
4886        .unwrap();
4887        assert!(!compatible_run_instruction(&run, &t));
4888
4889        // Legacy recovery reviews retain the task criteria ahead of the log.
4890        t.review_of = None;
4891        t.instruction = "Fix Clippy on approved head".into();
4892        run.task_instruction = None;
4893        run.instruction = format!(
4894            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
4895            t.instruction
4896        );
4897        assert!(compatible_run_instruction(&run, &t));
4898        t.instruction.push('\n');
4899        assert!(
4900            compatible_run_instruction(&run, &t),
4901            "legacy generated review trimmed the original criteria"
4902        );
4903        t.hold_for_handover(Some("approved-head".into()), "refused".into());
4904        let mut unchanged = t.clone();
4905        assert_eq!(
4906            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
4907            Some("approved-head")
4908        );
4909        t.edit("new plan".into(), "Reuse measured PR head B".into())
4910            .unwrap();
4911        assert!(take_review_branch(&mut t, Some(&run)).is_none());
4912        assert!(!compatible_run_instruction(&run, &t));
4913        t.review_branch = Some("approved-head".into());
4914        t.review_instruction = None;
4915        assert!(
4916            take_review_branch(&mut t, Some(&run)).is_none(),
4917            "legacy retained candidate cannot replace a revised approved head"
4918        );
4919    }
4920
4921    #[test]
4922    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
4923        crate::run::pin_test_home();
4924        let dir = tempfile::tempdir().unwrap();
4925        let queue = Queue::at(dir.path().join("queue"));
4926        for resume in [true, false] {
4927            let state = run_state(RunStatus::Blocked);
4928            let mut t = task();
4929            t.start(state.id.clone());
4930            let action = if resume {
4931                ask::ChoiceAction::Resume {
4932                    run: state.id.clone(),
4933                }
4934            } else {
4935                ask::ChoiceAction::Requeue
4936            };
4937            let mut q = action_question(&state.id, action);
4938            q.status = ask::QuestionStatus::Open;
4939            q.answer = None;
4940            q.answered_at = None;
4941            t.fail("run stopped with a question", 3);
4942            hold_if_runnable(&queue, &mut t);
4943            assert!(t.operator_decided_at.is_none());
4944            assert!(t.operator_held());
4945            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
4946            let expected = if resume {
4947                ActionDecision::Resume(state.id.clone())
4948            } else {
4949                ActionDecision::Requeue
4950            };
4951            assert_eq!(
4952                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
4953                expected
4954            );
4955            t.hold_manual(Some("later explicit hold".into()));
4956            assert_eq!(
4957                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
4958                ActionDecision::Stale
4959            );
4960        }
4961    }
4962
4963    #[test]
4964    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
4965        let mut t = task();
4966        t.answers.push(crate::queue::AnsweredQuestion {
4967            question: "Inspect the remote?".into(),
4968            answer: "Inspect then wait".into(),
4969        });
4970        let old = instruction_for(&t);
4971        assert!(compatible_instruction(&old, &t));
4972        t.instruction = "Reuse approved PR head and review".into();
4973        t.release_operator("cli", None);
4974        assert!(!compatible_instruction(&old, &t));
4975        let approved = instruction_for(&t);
4976        assert!(approved.contains("waiting premises are superseded"));
4977        assert!(compatible_instruction(&approved, &t));
4978        assert_eq!(resumed_instruction(&approved, &t), approved);
4979        t.release_operator("web", None);
4980        assert!(compatible_instruction(&approved, &t));
4981        assert_eq!(t.resumption_history.len(), 1);
4982        t.start("run".into());
4983        assert!(instruction_for(&t).contains("Explicit operator resumption"));
4984    }
4985
4986    /// A run that stopped on an infrastructure wait asked no agent anything:
4987    /// the task is held by the machine under a `[resource]` reason (resumable,
4988    /// re-checked by triage), and the attempt it started is given back.
4989    #[test]
4990    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
4991        let mut state = RunState::new(
4992            PathBuf::from("/repo"),
4993            "main".to_owned(),
4994            "abc1234".to_owned(),
4995            "task".to_owned(),
4996            Config::default(),
4997        );
4998        state.status = RunStatus::Blocked;
4999        state.resource_block = Some(crate::run::ResourceBlock {
5000            node: "graft".to_owned(),
5001            kind: "shared build cache".to_owned(),
5002            detail: "timed out".to_owned(),
5003            at: jiff::Timestamp::now(),
5004        });
5005        let mut t = task();
5006        t.start("20260902-000000-aaaa".to_owned());
5007        assert_eq!(t.attempts, 1);
5008        let verdict = Verdict {
5009            status: RunStatus::Blocked,
5010            left_pr: false,
5011            quota_hit: false,
5012            parked: false,
5013            no_viable_candidates: false,
5014        };
5015        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5016        assert_eq!(t.status, TaskStatus::Held);
5017        assert_eq!(t.attempts, 0, "the attempt is refunded");
5018        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5019        assert!(
5020            !t.operator_held(),
5021            "a machine hold, released without a human"
5022        );
5023
5024        // A park request outranks it: still the operator's doing.
5025        let mut p = task();
5026        p.start("20260902-000000-bbbb".to_owned());
5027        settle_and_diagnose(
5028            &mut p,
5029            Verdict {
5030                parked: true,
5031                ..verdict
5032            },
5033            "parked",
5034            2,
5035            &state,
5036        );
5037        assert_eq!(p.status, TaskStatus::Parked);
5038    }
5039
5040    #[test]
5041    fn record_failure_notice_links_the_task() {
5042        let dir = tempfile::tempdir().unwrap();
5043        // A regular file where the queue directory should be makes every
5044        // `put` fail, on every platform and whoever runs the test.
5045        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
5046        let queue = Queue::at(dir.path().join("queue"));
5047        let mut t = interrupt_task("rec-fail-1");
5048        record(&queue, &mut t);
5049
5050        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
5051        assert_eq!(found.len(), 1);
5052        assert_eq!(found[0].key, "loop:record");
5053        assert_eq!(
5054            found[0].link,
5055            Some(Link::Task {
5056                id: "rec-fail-1".to_owned()
5057            })
5058        );
5059    }
5060
5061    /// A runnable task marked to interrupt, with an id fixed for assertions
5062    /// rather than the random one [`Task::new`] mints.
5063    fn interrupt_task(id: &str) -> Task {
5064        let mut t = task();
5065        t.id = id.to_owned();
5066        t.interrupt = true;
5067        t
5068    }
5069
5070    /// An ordinary runnable task with an id fixed for assertions.
5071    fn task_with_id(id: &str) -> Task {
5072        let mut t = task();
5073        t.id = id.to_owned();
5074        t
5075    }
5076
5077    /// A runnable task marked `--urgent`, with an id fixed for assertions.
5078    fn urgent_task(id: &str) -> Task {
5079        let mut t = task();
5080        t.id = id.to_owned();
5081        t.urgent = true;
5082        t
5083    }
5084
5085    #[test]
5086    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
5087        let dir = tempfile::tempdir().unwrap();
5088        let queue = Queue::at(dir.path().join("queue"));
5089        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5090        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5091        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
5092        let mut first = task();
5093        queue.put(&mut first).unwrap();
5094        let stale_plain = queue.get(&first.id).unwrap();
5095        first.set_urgent(true).unwrap();
5096        queue.put(&mut first).unwrap();
5097        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
5098        let mut second = urgent_task("second");
5099        queue.put(&mut second).unwrap();
5100        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
5101        drop(queue.claim(&second.id).unwrap());
5102        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
5103        drop(dispatched);
5104        let stale_urgent = queue.get(&first.id).unwrap();
5105        first.set_urgent(false).unwrap();
5106        queue.put(&mut first).unwrap();
5107        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
5108        assert_eq!(urgent.available_permits(), 1);
5109        drop(queue.claim(&first.id).unwrap());
5110        drop(occupied);
5111    }
5112
5113    #[test]
5114    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
5115        let dir = tempfile::tempdir().unwrap();
5116        let queue = Queue::at(dir.path().join("queue"));
5117        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5118        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5119        let mut t = task();
5120        queue.put(&mut t).unwrap();
5121        for enabled in [true, false] {
5122            let stale = queue.get(&t.id).unwrap();
5123            t.set_urgent(enabled).unwrap();
5124            queue.put(&mut t).unwrap();
5125            assert_ne!(stale.urgent, enabled);
5126            let DispatchClaim {
5127                task: fresh,
5128                claim,
5129                permit,
5130            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
5131            assert_eq!(fresh.urgent, enabled);
5132            assert_eq!(ordinary.available_permits(), usize::from(enabled));
5133            assert_eq!(urgent.available_permits(), usize::from(!enabled));
5134            assert!(queue.claim(&t.id).is_err());
5135            assert_eq!(fresh.attempts, stale.attempts);
5136            drop((claim, permit));
5137            assert_eq!(ordinary.available_permits(), 1);
5138            assert_eq!(urgent.available_permits(), 1);
5139        }
5140        t.set_urgent(true).unwrap();
5141        queue.put(&mut t).unwrap();
5142        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
5143        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5144        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
5145        drop(queue.claim(&t.id).unwrap());
5146        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
5147        drop(occupied);
5148        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
5149        drop(queue.claim(&t.id).unwrap());
5150        let held = queue.claim(&t.id).unwrap();
5151        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5152        drop(held);
5153        t.status = TaskStatus::Held;
5154        queue.put(&mut t).unwrap();
5155        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5156        drop(queue.claim(&t.id).unwrap());
5157        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
5158        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5159        drop(queue.claim(&t.id).unwrap());
5160        assert_eq!(urgent.available_permits(), 1);
5161    }
5162
5163    /// The land-resume exemption wins outright, whether or not the candidate
5164    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
5165    /// queue behind anything" guarantee cannot be weaker just because the
5166    /// same task was also filed with `--urgent`.
5167    #[test]
5168    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
5169        assert_eq!(permit_kind(true, false), PermitKind::None);
5170        assert_eq!(permit_kind(true, true), PermitKind::None);
5171    }
5172
5173    /// The one property this whole feature exists for: `--urgent` draws from
5174    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
5175    /// ordinary candidate draws from the ordinary pool exactly as before,
5176    /// untouched by the urgent slot's existence.
5177    #[test]
5178    fn permit_kind_separates_urgent_from_ordinary() {
5179        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
5180        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
5181    }
5182
5183    /// The exact wiring `attempt` runs before minting anything: a config's
5184    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
5185    /// Free space is injected rather than asked of the real disk - the point
5186    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
5187    /// is deterministic on every machine this test runs on, never dependent
5188    /// on how full the CI runner's own disk happens to be.
5189    #[test]
5190    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
5191        let cfg = Config::default();
5192        let repo = Path::new("/any/repo/path");
5193
5194        let reason =
5195            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
5196        assert!(reason.contains("1024"), "{reason}");
5197        assert!(
5198            reason.contains(&cfg.disk.min_free_bytes.to_string()),
5199            "{reason}"
5200        );
5201
5202        assert_eq!(
5203            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
5204            None,
5205            "exactly at the floor is open"
5206        );
5207        assert_eq!(
5208            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
5209            None,
5210            "comfortably above the floor is open"
5211        );
5212    }
5213
5214    #[test]
5215    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
5216        let mut cfg = Config::default();
5217        cfg.disk.min_free_bytes = 0;
5218        let repo = Path::new("/any/repo/path");
5219        assert_eq!(
5220            disk_gate_with(repo, &cfg, |_| Ok(0)),
5221            None,
5222            "a zero floor never measures at all"
5223        );
5224    }
5225
5226    #[test]
5227    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
5228        let cfg = Config::default();
5229        let repo = Path::new("/any/repo/path");
5230        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
5231            .expect("a measurement failure must close the gate, not open it");
5232        assert!(reason.contains("could not measure"), "{reason}");
5233    }
5234
5235    #[test]
5236    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
5237        let ordinary = task();
5238        let next = advance_interrupt(
5239            Interrupt::Idle,
5240            std::slice::from_ref(&ordinary.id),
5241            std::slice::from_ref(&ordinary),
5242        );
5243        assert_eq!(next, Interrupt::Idle);
5244    }
5245
5246    #[test]
5247    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
5248        // Nothing to interrupt - this is just an ordinary candidate, and the
5249        // loop's normal dispatch will pick it up like any other.
5250        let marked = interrupt_task("marked");
5251        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5252        assert_eq!(next, Interrupt::Idle);
5253    }
5254
5255    #[test]
5256    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
5257        let marked = interrupt_task("marked");
5258        let next = advance_interrupt(
5259            Interrupt::Idle,
5260            &["running".to_owned()],
5261            std::slice::from_ref(&marked),
5262        );
5263        assert_eq!(
5264            next,
5265            Interrupt::Parking {
5266                parked: vec!["running".to_owned()],
5267                interrupt_task: "marked".to_owned(),
5268            }
5269        );
5270    }
5271
5272    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
5273    /// one run can be in flight when a task becomes runnable and marked.
5274    /// Parking all of them would mean `Resuming` later has more than one id
5275    /// to release back to ordinary dispatch, which cannot be made safe
5276    /// against that same setting's own extra concurrency slots letting two
5277    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
5278    /// The simplification the task's own constraints ask for: do not begin
5279    /// a sequence at all until the herd settles back to exactly one.
5280    #[test]
5281    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
5282        let marked = interrupt_task("marked");
5283
5284        let two = advance_interrupt(
5285            Interrupt::Idle,
5286            &["a".to_owned(), "b".to_owned()],
5287            std::slice::from_ref(&marked),
5288        );
5289        assert_eq!(two, Interrupt::Idle);
5290
5291        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
5292        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
5293    }
5294
5295    #[test]
5296    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
5297        let state = Interrupt::Parking {
5298            parked: vec!["running".to_owned()],
5299            interrupt_task: "marked".to_owned(),
5300        };
5301        // Still in flight: no change.
5302        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
5303        assert_eq!(still_going, state);
5304
5305        // Left flight, but the interrupt task has not been dispatched yet on
5306        // this tick - stays `Parking` so `interrupt_gate` can let it through,
5307        // as long as it is still runnable.
5308        let stopped_but_not_yet_dispatched =
5309            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
5310        assert_eq!(stopped_but_not_yet_dispatched, state);
5311
5312        // Left flight, and the interrupt task is now in flight itself.
5313        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
5314        assert_eq!(
5315            dispatched,
5316            Interrupt::Running {
5317                parked: vec!["running".to_owned()],
5318                interrupt_task: "marked".to_owned(),
5319            }
5320        );
5321    }
5322
5323    #[test]
5324    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
5325        let state = Interrupt::Running {
5326            parked: vec!["running".to_owned()],
5327            interrupt_task: "marked".to_owned(),
5328        };
5329        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
5330        assert_eq!(still_running, state);
5331
5332        // Whatever it ended as - merged, failed, held - is not this
5333        // function's concern: leaving flight is the only trigger, driven
5334        // straight off the same in-flight list `poll` already reaps. It does
5335        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
5336        // why that would let an unrelated task start ahead of, or alongside,
5337        // the guaranteed resume.
5338        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
5339        assert_eq!(
5340            ended,
5341            Interrupt::Resuming {
5342                parked: vec!["running".to_owned()]
5343            }
5344        );
5345    }
5346
5347    #[test]
5348    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
5349        let state = Interrupt::Resuming {
5350            parked: vec!["running".to_owned()],
5351        };
5352        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
5353        assert_eq!(still_waiting, state);
5354
5355        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
5356        assert_eq!(dispatched, Interrupt::Idle);
5357    }
5358
5359    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
5360    /// or otherwise moved on by an operator with no claim standing in the
5361    /// way - must not wedge the sequence (and so the whole loop's dispatch,
5362    /// via `interrupt_gate`) waiting forever for a dispatch that can never
5363    /// come. The parked run still gets its resume.
5364    #[test]
5365    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
5366    {
5367        let state = Interrupt::Parking {
5368            parked: vec!["running".to_owned()],
5369            interrupt_task: "marked".to_owned(),
5370        };
5371        // `marked` has been held/blocked/deleted since the sequence began:
5372        // it no longer appears in `runnable` at all.
5373        let next = advance_interrupt(state, &[], &[]);
5374        assert_eq!(
5375            next,
5376            Interrupt::Resuming {
5377                parked: vec!["running".to_owned()]
5378            },
5379            "abandoning the interrupt must not abandon the resume it owes"
5380        );
5381    }
5382
5383    /// The same abandonment, one step later: `Resuming` itself must not wait
5384    /// forever for a parked task that has since become unrunnable.
5385    #[test]
5386    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
5387        let state = Interrupt::Resuming {
5388            parked: vec!["running".to_owned()],
5389        };
5390        let next = advance_interrupt(state, &[], &[]);
5391        assert_eq!(
5392            next,
5393            Interrupt::Idle,
5394            "nothing is left to wait for; the loop must not stay wedged"
5395        );
5396    }
5397
5398    #[test]
5399    fn disabled_by_config_the_sequence_can_never_leave_idle() {
5400        let marked = interrupt_task("marked");
5401        let next = advance_interrupt_tick(
5402            false,
5403            Interrupt::Idle,
5404            &["running".to_owned()],
5405            std::slice::from_ref(&marked),
5406        );
5407        assert_eq!(
5408            next,
5409            Interrupt::Idle,
5410            "an unmarked, unconfigured daemon must behave exactly as before"
5411        );
5412    }
5413
5414    #[test]
5415    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
5416        let state = Interrupt::Parking {
5417            parked: vec!["running".to_owned()],
5418            interrupt_task: "marked".to_owned(),
5419        };
5420        let candidates = vec![interrupt_task("marked"), task()];
5421        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5422        assert!(
5423            allowed.is_empty(),
5424            "nothing may dispatch - not even the interrupt task itself - \
5425             until the parked run has actually stopped"
5426        );
5427    }
5428
5429    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
5430    /// grow a special case for it: an urgent candidate that is not the
5431    /// interrupt task withholds exactly like an ordinary one for as long as
5432    /// the parked run it is racing has not actually left flight. A version
5433    /// of this feature once bypassed the gate for urgent candidates, on the
5434    /// theory that a genuinely separate concurrency lane could not collide
5435    /// with 75dd's own; it could, and did - the bypassed task dispatched
5436    /// alongside a run 75dd's own state machine had only *asked* to park,
5437    /// not yet confirmed gone, which is exactly the second run
5438    /// `Interrupt::Parking`'s own doc says must never happen. There is no
5439    /// tick during Parking/Running/Resuming where letting an extra
5440    /// candidate through is safe, urgent or not - the parked run may still
5441    /// be genuinely mid-call.
5442    #[test]
5443    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
5444        for state in [
5445            Interrupt::Parking {
5446                parked: vec!["running".to_owned()],
5447                interrupt_task: "marked".to_owned(),
5448            },
5449            Interrupt::Running {
5450                parked: vec!["running".to_owned()],
5451                interrupt_task: "marked".to_owned(),
5452            },
5453            Interrupt::Resuming {
5454                parked: vec!["running".to_owned()],
5455            },
5456        ] {
5457            let candidates = vec![
5458                interrupt_task("marked"),
5459                urgent_task("hot"),
5460                task_with_id("ordinary"),
5461            ];
5462            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
5463            assert!(
5464                !allowed.iter().any(|t| t.id == "hot"),
5465                "an urgent candidate must wait out the same gate as anything \
5466                 else while the run it would run alongside has not actually \
5467                 left flight, for state {state:?}: {allowed:?}"
5468            );
5469        }
5470    }
5471
5472    /// The one case where marking a task `--urgent` and `interrupt` at once
5473    /// is not redundant: once the interrupt sequence's own guaranteed
5474    /// resume/dispatch actually admits the task, it is unaffected by also
5475    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
5476    /// never on the urgent flag.
5477    #[test]
5478    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
5479        let state = Interrupt::Resuming {
5480            parked: vec!["hot".to_owned()],
5481        };
5482        let candidates = vec![urgent_task("hot"), task()];
5483        let allowed = interrupt_gate(&state, &[], candidates);
5484        assert_eq!(
5485            allowed.iter().filter(|t| t.id == "hot").count(),
5486            1,
5487            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
5488        );
5489    }
5490
5491    #[test]
5492    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
5493        let state = Interrupt::Parking {
5494            parked: vec!["running".to_owned()],
5495            interrupt_task: "marked".to_owned(),
5496        };
5497        let other = task();
5498        let candidates = vec![interrupt_task("marked"), other.clone()];
5499        let allowed = interrupt_gate(&state, &[], candidates);
5500        assert_eq!(allowed.len(), 1);
5501        assert_eq!(allowed[0].id, "marked");
5502    }
5503
5504    #[test]
5505    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
5506        let state = Interrupt::Running {
5507            parked: vec!["running".to_owned()],
5508            interrupt_task: "marked".to_owned(),
5509        };
5510        let candidates = vec![task(), task()];
5511        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
5512        assert!(allowed.is_empty());
5513    }
5514
5515    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
5516    /// sequence began (only reachable above the default
5517    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
5518    /// never both in the same tick, which is what "exactly one resume, no
5519    /// simultaneous run" actually requires structurally rather than by
5520    /// coincidence of how many ordinary slots happen to be free.
5521    #[test]
5522    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
5523        let state = Interrupt::Resuming {
5524            parked: vec!["a".to_owned(), "c".to_owned()],
5525        };
5526        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
5527        let allowed = interrupt_gate(&state, &[], candidates);
5528        assert_eq!(
5529            allowed.len(),
5530            1,
5531            "at most one candidate may be offered while resuming: {allowed:?}"
5532        );
5533        assert_eq!(allowed[0].id, "a");
5534    }
5535
5536    #[test]
5537    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
5538        let state = Interrupt::Resuming {
5539            parked: vec!["a".to_owned()],
5540        };
5541        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
5542        assert!(allowed.is_empty());
5543    }
5544
5545    /// The invariant the completion criteria ask for by name: across a whole
5546    /// simulated sequence, there is never a tick where the gate would let
5547    /// through both the parked run's resume and the interrupt task, and
5548    /// exactly one candidate resumes the instant the interrupt task's run
5549    /// ends - never zero, never more than one.
5550    #[test]
5551    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
5552        let running = task(); // id: whatever `Task::new` minted
5553        let marked = interrupt_task("marked");
5554
5555        let mut state = Interrupt::Idle;
5556        // Tick 1: `running` is in flight, `marked` becomes runnable.
5557        let in_flight = vec![running.id.clone()];
5558        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
5559        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
5560        assert!(gated.is_empty(), "still waiting on `running` to park");
5561
5562        // Tick 2: `running` parked and left flight; nothing dispatched yet.
5563        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
5564        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
5565        assert_eq!(
5566            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5567            vec!["marked"],
5568            "only the interrupt task may be offered to the dispatcher now"
5569        );
5570
5571        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
5572        state = advance_interrupt_tick(
5573            true,
5574            state,
5575            &["marked".to_owned()],
5576            std::slice::from_ref(&running),
5577        );
5578        let gated = interrupt_gate(
5579            &state,
5580            &["marked".to_owned()],
5581            vec![marked.clone(), running.clone()],
5582        );
5583        assert!(
5584            gated.is_empty(),
5585            "the parked run must not be offered back while the interrupt \
5586             task is still running"
5587        );
5588
5589        // Tick 4: `marked`'s run reached a terminal status and left flight.
5590        // A higher-priority ordinary task `other` is also runnable now - it
5591        // must not be let through instead of, or alongside, `running`.
5592        let other = task_with_id("other");
5593        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
5594        assert_eq!(
5595            state,
5596            Interrupt::Resuming {
5597                parked: vec![running.id.clone()]
5598            }
5599        );
5600        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
5601        assert_eq!(
5602            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5603            vec![running.id.as_str()],
5604            "exactly the parked run resumes - not the unrelated task, even \
5605             though it was offered first"
5606        );
5607
5608        // Tick 5: `running` is now in flight (dispatched from tick 4's
5609        // gate). Only now does the sequence end and ordinary dispatch fully
5610        // resume.
5611        state = advance_interrupt_tick(
5612            true,
5613            state,
5614            std::slice::from_ref(&running.id),
5615            std::slice::from_ref(&other),
5616        );
5617        assert_eq!(state, Interrupt::Idle);
5618        let gated = interrupt_gate(
5619            &state,
5620            std::slice::from_ref(&running.id),
5621            vec![other.clone()],
5622        );
5623        assert_eq!(
5624            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
5625            vec![other.id.as_str()],
5626            "ordinary dispatch is unrestricted again"
5627        );
5628    }
5629
5630    #[test]
5631    fn every_run_status_settles_the_task_it_came_from() {
5632        // run status, resulting task status, attempts still standing after one
5633        let table = [
5634            (RunStatus::Merged, TaskStatus::Done, 1),
5635            (RunStatus::Ready, TaskStatus::Done, 1),
5636            (RunStatus::Stalled, TaskStatus::Failed, 0),
5637            (RunStatus::Blocked, TaskStatus::Failed, 1),
5638            (RunStatus::Failed, TaskStatus::Failed, 1),
5639            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
5640            (RunStatus::Prep, TaskStatus::Failed, 1),
5641            (RunStatus::Implementing, TaskStatus::Failed, 1),
5642            (RunStatus::Judging, TaskStatus::Failed, 1),
5643            (RunStatus::Deliberating, TaskStatus::Failed, 1),
5644            (RunStatus::Voting, TaskStatus::Failed, 1),
5645            (RunStatus::Reviewing, TaskStatus::Failed, 1),
5646            (RunStatus::Gating, TaskStatus::Failed, 1),
5647        ];
5648        for (run, want, attempts) in table {
5649            let mut t = task();
5650            t.start("20260902-000000-aaaa".to_owned());
5651            settle(
5652                &mut t,
5653                Verdict {
5654                    status: run,
5655                    left_pr: false,
5656                    parked: false,
5657                    quota_hit: matches!(run, RunStatus::Stalled),
5658                    no_viable_candidates: false,
5659                },
5660                "why",
5661                2,
5662            );
5663            assert_eq!(t.status, want, "task status after {}", label(run));
5664            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
5665        }
5666    }
5667
5668    #[test]
5669    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
5670        let mut stalled = task();
5671        stalled.start("20260902-000000-aaaa".to_owned());
5672        settle(
5673            &mut stalled,
5674            Verdict {
5675                status: RunStatus::Stalled,
5676                left_pr: false,
5677                parked: false,
5678                quota_hit: true,
5679                no_viable_candidates: false,
5680            },
5681            "quota",
5682            1,
5683        );
5684        assert_eq!(stalled.attempts, 0);
5685        assert!(
5686            stalled.status.runnable(),
5687            "a machine problem must leave the task in line"
5688        );
5689
5690        let mut blocked = task();
5691        blocked.start("20260902-000000-aaaa".to_owned());
5692        settle(
5693            &mut blocked,
5694            Verdict {
5695                status: RunStatus::Blocked,
5696                left_pr: false,
5697                parked: false,
5698                quota_hit: false,
5699                no_viable_candidates: false,
5700            },
5701            "findings open",
5702            1,
5703        );
5704        assert_eq!(blocked.attempts, 1);
5705        assert_eq!(
5706            blocked.status,
5707            TaskStatus::Held,
5708            "the last attempt hands the task to a human"
5709        );
5710    }
5711
5712    #[test]
5713    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
5714        // Attempts to spare: without the pull request this task would go
5715        // straight back in line and run the whole competition again.
5716        let mut delivered = task();
5717        delivered.start("20260903-080619-01c2".to_owned());
5718        settle(
5719            &mut delivered,
5720            Verdict {
5721                status: RunStatus::Blocked,
5722                left_pr: true,
5723                parked: false,
5724                quota_hit: false,
5725                no_viable_candidates: false,
5726            },
5727            "no check status",
5728            4,
5729        );
5730        assert_eq!(
5731            delivered.status,
5732            TaskStatus::Held,
5733            "a pull request waiting on CI or a person is not a retryable failure"
5734        );
5735        assert!(
5736            !delivered.status.runnable(),
5737            "the loop must not pick this task up again"
5738        );
5739        assert_eq!(
5740            delivered.last_error.as_deref(),
5741            Some("no check status"),
5742            "the operator needs to be told what the gate was waiting for"
5743        );
5744
5745        // The same status without a pull request is a plain failure, and with
5746        // attempts left it is retried.
5747        let mut empty_handed = task();
5748        empty_handed.start("20260903-080619-01c2".to_owned());
5749        settle(
5750            &mut empty_handed,
5751            Verdict {
5752                status: RunStatus::Blocked,
5753                left_pr: false,
5754                parked: false,
5755                quota_hit: false,
5756                no_viable_candidates: false,
5757            },
5758            "findings open",
5759            4,
5760        );
5761        assert_eq!(empty_handed.status, TaskStatus::Failed);
5762        assert!(empty_handed.status.runnable());
5763    }
5764
5765    #[test]
5766    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
5767        // Every candidate agreed, with evidence, that nothing belonged in the
5768        // worktree. That is not a confirmed success to close automatically -
5769        // a human still has to check the claim - and it is not an ordinary
5770        // failure either, so this settles exactly like a pull request nobody
5771        // merged yet: `Held`, same as `Blocked` with a PR.
5772        let mut noop = task();
5773        noop.start("20260912-131304-391f".to_owned());
5774        settle(
5775            &mut noop,
5776            Verdict {
5777                status: RunStatus::VerifiedNoop,
5778                left_pr: false,
5779                parked: false,
5780                quota_hit: false,
5781                no_viable_candidates: true,
5782            },
5783            "candidate A: already fixed by b32cfc4, on main",
5784            4,
5785        );
5786        assert_eq!(
5787            noop.status,
5788            TaskStatus::Held,
5789            "an unverified claim is a request for a human, not a failure"
5790        );
5791        assert!(
5792            !noop.status.runnable(),
5793            "the loop must not requeue this on the same unverified claim"
5794        );
5795        // `Task::release` resets attempts to zero the moment a human looks at
5796        // the evidence and lets it run again, so it does not matter here
5797        // whether the one attempt already spent stays spent - what matters is
5798        // that nothing retries this task unattended in the meantime.
5799        assert_eq!(noop.attempts, 1);
5800    }
5801
5802    #[test]
5803    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
5804        // Parking is the operator asking for the process back - to replace the
5805        // binary, most of all. The run's work is intact on disk, so this is
5806        // not a failed attempt, and charging for it would mean a few upgrades
5807        // could exhaust a budget meant for agents that misbehaved.
5808        let mut parked = task();
5809        parked.start("20260903-183634-2d98".to_owned());
5810        settle(
5811            &mut parked,
5812            Verdict {
5813                status: RunStatus::Implementing,
5814                left_pr: false,
5815                quota_hit: false,
5816                parked: true,
5817                no_viable_candidates: false,
5818            },
5819            "parked after `implementing`",
5820            2,
5821        );
5822        assert_eq!(parked.attempts, 0, "a park is refunded");
5823        assert!(
5824            parked.status.runnable(),
5825            "and the task stays in line so the next loop resumes its run"
5826        );
5827        assert_eq!(parked.status, TaskStatus::Parked);
5828        assert_eq!(
5829            parked.park_reason.as_deref(),
5830            Some("parked after `implementing`"),
5831            "the card says where it stopped"
5832        );
5833        assert_eq!(parked.last_error, None, "nothing failed");
5834
5835        // Without the park flag the same non-terminal status is what it always
5836        // was: `execute` returning mid-flight, which is a bug and spends an
5837        // attempt so a task cannot loop on it forever.
5838        let mut broken = task();
5839        broken.start("20260903-183634-2d98".to_owned());
5840        settle(
5841            &mut broken,
5842            Verdict {
5843                status: RunStatus::Implementing,
5844                left_pr: false,
5845                quota_hit: false,
5846                parked: false,
5847                no_viable_candidates: false,
5848            },
5849            "returned mid-flight",
5850            2,
5851        );
5852        assert_eq!(broken.attempts, 1);
5853    }
5854
5855    #[test]
5856    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
5857        // Run e633: quorum lost because two judges answered with the wrong
5858        // JSON shape, `quota: []`. Refunding that takes the bound off the
5859        // retry loop, and each retry pays for a fresh hour-long implement
5860        // wave before it can fail the same way.
5861        let mut flaky = task();
5862        flaky.start("20260903-123023-e633".to_owned());
5863        settle(
5864            &mut flaky,
5865            Verdict {
5866                status: RunStatus::Stalled,
5867                left_pr: false,
5868                parked: false,
5869                quota_hit: false,
5870                no_viable_candidates: false,
5871            },
5872            "verdict rests on 1 of 3 judges",
5873            2,
5874        );
5875        assert_eq!(
5876            flaky.attempts, 1,
5877            "flakiness spends an attempt, so `max_attempts` still bounds it"
5878        );
5879        assert!(flaky.status.runnable(), "and it is still worth retrying");
5880
5881        // The same status, lost to a rate limit, is the machine's fault.
5882        let mut limited = task();
5883        limited.start("20260903-123023-e633".to_owned());
5884        settle(
5885            &mut limited,
5886            Verdict {
5887                status: RunStatus::Stalled,
5888                left_pr: false,
5889                parked: false,
5890                quota_hit: true,
5891                no_viable_candidates: false,
5892            },
5893            "judge-2, judge-3 out of quota",
5894            2,
5895        );
5896        assert_eq!(limited.attempts, 0, "a quota window is refunded");
5897        assert!(limited.status.runnable());
5898
5899        // And the bound really binds: a task that keeps stalling on flakiness
5900        // reaches a human instead of running the roster forever.
5901        let mut worn = task();
5902        for _ in 0..2 {
5903            worn.release();
5904        }
5905        worn.start("20260903-123023-e633".to_owned());
5906        worn.attempts = 2;
5907        settle(
5908            &mut worn,
5909            Verdict {
5910                status: RunStatus::Stalled,
5911                left_pr: false,
5912                parked: false,
5913                quota_hit: false,
5914                no_viable_candidates: false,
5915            },
5916            "no quorum again",
5917            2,
5918        );
5919        assert_eq!(worn.status, TaskStatus::Held);
5920        assert!(!worn.status.runnable());
5921    }
5922
5923    #[test]
5924    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
5925        // The implement wave loses every seat to the same rate limit and
5926        // `after_implement` bails with nothing viable, which surfaces as
5927        // `Failed` rather than `Stalled`. That is the same machine fact the
5928        // `Stalled`-quota row already refunds, and must be refunded the same
5929        // way, or a quota outage quietly holds every task it touches instead
5930        // of leaving them in line for the reset.
5931        let mut wiped_out = task();
5932        wiped_out.start("20260907-025000-a1b2".to_owned());
5933        settle(
5934            &mut wiped_out,
5935            Verdict {
5936                status: RunStatus::Failed,
5937                left_pr: false,
5938                parked: false,
5939                quota_hit: true,
5940                no_viable_candidates: true,
5941            },
5942            "no candidate produced a change; nothing to judge",
5943            2,
5944        );
5945        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
5946        assert!(
5947            wiped_out.status.runnable(),
5948            "a machine problem must leave the task in line"
5949        );
5950
5951        // This is the exemption that must stay narrow: a candidate that did
5952        // produce a change, and then failed for some other reason, still
5953        // spends the attempt even though a seat elsewhere hit its quota.
5954        // Otherwise every ordinary failure that happens to share a run with
5955        // an unrelated rate limit would be refunded for free.
5956        let mut partial_progress = task();
5957        partial_progress.start("20260907-025500-c3d4".to_owned());
5958        settle(
5959            &mut partial_progress,
5960            Verdict {
5961                status: RunStatus::Failed,
5962                left_pr: false,
5963                parked: false,
5964                quota_hit: true,
5965                no_viable_candidates: false,
5966            },
5967            "gate failed on the winning candidate",
5968            2,
5969        );
5970        assert_eq!(
5971            partial_progress.attempts, 1,
5972            "a candidate that actually produced a change spends the attempt \
5973             even though some other seat hit its quota"
5974        );
5975        assert!(partial_progress.status.runnable());
5976    }
5977
5978    #[test]
5979    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
5980        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
5981        // disk, and that construction must reach the same conclusion as the
5982        // one `attempt` builds from a live run, or a crash at exactly the
5983        // wrong moment gives a recovered task a different policy than one a
5984        // daemon finished settling itself.
5985        let mut t = task();
5986        t.start("20260907-025000-a1b2".to_owned());
5987        let mut state = run_state(RunStatus::Failed);
5988        state.quota.push(QuotaLoss {
5989            seat: "cand-a".to_owned(),
5990            node: "implement".to_owned(),
5991            at: Timestamp::now(),
5992            reset: None,
5993        });
5994        assert!(
5995            state.viable().is_empty(),
5996            "no candidate was added, so nothing is viable"
5997        );
5998        reclaim(&mut t, Some(state), 2, "en");
5999        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6000        assert!(t.status.runnable());
6001    }
6002
6003    #[test]
6004    fn a_held_task_is_never_offered_to_the_loop() {
6005        let dir = tempfile::tempdir().unwrap();
6006        let queue = Queue::at(dir.path().to_path_buf());
6007        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6008            let mut t = task();
6009            t.id = format!("2026090{n}-000000-000{n}");
6010            t.priority = priority;
6011            queue.put(&mut t).unwrap();
6012        }
6013        let mut held = task();
6014        held.id = "20260909-000000-9999".to_owned();
6015        held.priority = 99;
6016        held.hold_machine(None);
6017        queue.put(&mut held).unwrap();
6018
6019        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6020        assert_eq!(order.len(), 3);
6021        assert!(!order.contains(&held.id));
6022        assert_eq!(
6023            order.first().cloned(),
6024            queue.next_runnable().map(|t| t.id),
6025            "the loop's first candidate is exactly what the queue offers"
6026        );
6027        assert_eq!(
6028            order,
6029            vec![
6030                "20260902-000000-0002".to_owned(),
6031                "20260903-000000-0003".to_owned(),
6032                "20260901-000000-0001".to_owned(),
6033            ],
6034            "priority first, then oldest, so nothing starves"
6035        );
6036    }
6037
6038    #[test]
6039    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6040        let dir = tempfile::tempdir().unwrap();
6041        let queue = Queue::at(dir.path().to_path_buf());
6042        let mut old = task();
6043        old.id = "20260101-000000-old0".to_owned();
6044        queue.put(&mut old).unwrap();
6045        let mut fresh = task();
6046        fresh.id = "20260101-000000-new0".to_owned();
6047        queue.put(&mut fresh).unwrap();
6048
6049        // No parseable pid at all, so age is the only signal there is to
6050        // check - unlike a real `Queue::claim`, which always names a real,
6051        // and therefore alive, pid this test cannot fake as dead.
6052        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
6053        std::thread::sleep(Duration::from_millis(60));
6054        let live = queue.claim(&fresh.id).unwrap();
6055
6056        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6057        assert_eq!(swept, vec![old.id.clone()]);
6058        assert!(
6059            queue.claim(&old.id).is_ok(),
6060            "an unparseable lock older than the threshold is swept"
6061        );
6062        assert!(
6063            queue.claim(&fresh.id).is_err(),
6064            "a live pid protects its lock regardless of age"
6065        );
6066        drop(live);
6067    }
6068
6069    #[test]
6070    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
6071        // The regression this guards: `sweep` now runs concurrently with
6072        // every attempt this daemon itself has spawned (see
6073        // `InFlightGuard`), not only between them the way a single
6074        // sequential loop once did. A run that legitimately outlives
6075        // `older_than` still has this very process's own live pid sitting in
6076        // its own lock file on every later sweep, and deciding by age alone
6077        // would delete that still-valid claim out from under the attempt
6078        // that holds it - which `reclaim_orphaned_running` would then read
6079        // as abandoned and hand to a second, competing attempt.
6080        let dir = tempfile::tempdir().unwrap();
6081        let queue = Queue::at(dir.path().to_path_buf());
6082        let mut t = task();
6083        t.id = "20260101-000000-live".to_owned();
6084        queue.put(&mut t).unwrap();
6085
6086        let claim = queue.claim(&t.id).unwrap();
6087        std::thread::sleep(Duration::from_millis(60));
6088
6089        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6090        assert!(
6091            swept.is_empty(),
6092            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
6093        );
6094        assert!(
6095            queue.claim(&t.id).is_err(),
6096            "the lock still protects its task"
6097        );
6098        drop(claim);
6099    }
6100
6101    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
6102    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
6103    fn injected_dead_pid() -> u32 {
6104        std::process::id().checked_add(1).unwrap_or(1)
6105    }
6106
6107    #[test]
6108    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
6109        let dir = tempfile::tempdir().unwrap();
6110        let queue = Queue::at(dir.path().to_path_buf());
6111        let mut t = task();
6112        t.id = "20260101-000000-dead".to_owned();
6113        queue.put(&mut t).unwrap();
6114        let dead_pid = injected_dead_pid();
6115
6116        // Written directly rather than through `Queue::claim`, which would
6117        // stamp this test process's own very much alive pid and defeat the
6118        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
6119        // like moments after it died, not six hours later.
6120        std::fs::write(
6121            dir.path().join(format!("{}.lock", t.id)),
6122            dead_pid.to_string(),
6123        )
6124        .unwrap();
6125
6126        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6127            pid != dead_pid
6128        });
6129        assert_eq!(
6130            swept,
6131            vec![t.id.clone()],
6132            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
6133        );
6134        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
6135    }
6136
6137    #[test]
6138    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
6139        let dir = tempfile::tempdir().unwrap();
6140        let queue = Queue::at(dir.path().to_path_buf());
6141        let mut t = task();
6142        t.id = "20260101-000000-late".to_owned();
6143        queue.put(&mut t).unwrap();
6144        let dead_pid = injected_dead_pid();
6145
6146        // Tick one, standing in for the sweep `poll` already runs at
6147        // startup: nothing to find yet.
6148        assert!(
6149            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
6150            "nothing has claimed the task yet"
6151        );
6152
6153        // A second daemon claims the task and dies before it ever writes
6154        // `running`, well after this loop's own startup sweep already ran.
6155        std::fs::write(
6156            dir.path().join(format!("{}.lock", t.id)),
6157            dead_pid.to_string(),
6158        )
6159        .unwrap();
6160
6161        // Tick two, standing in for a poll long into this daemon's uptime:
6162        // the same function, called again, notices what only just appeared -
6163        // proving the sweep is not a one-shot startup check.
6164        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6165            pid != dead_pid
6166        });
6167        assert_eq!(swept, vec![t.id.clone()]);
6168    }
6169
6170    #[test]
6171    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
6172        // `reclaim_orphaned_running` looks up the task's last run, which
6173        // touches `run::home()`; the first call anywhere in this binary wins,
6174        // so this is a no-op if another test already pinned one, and either
6175        // way the run id below is never written under it.
6176        crate::run::pin_test_home();
6177        let dir = tempfile::tempdir().unwrap();
6178        let queue = Queue::at(dir.path().to_path_buf());
6179        let mut t = task();
6180        t.id = "20260101-000000-crsh".to_owned();
6181        t.status = TaskStatus::Running;
6182        t.attempts = 1;
6183        // No `run.json` behind this id: standing in for a run this test does
6184        // not need to make readable, since the point is the lock, not the
6185        // recovery table `reclaim` already has its own tests for.
6186        t.runs.push("20260904-000000-4043".to_owned());
6187        queue.put(&mut t).unwrap();
6188        let dead_pid = injected_dead_pid();
6189
6190        // The crashed daemon's own claim, naming a pid nothing on the
6191        // machine holds anymore.
6192        std::fs::write(
6193            dir.path().join(format!("{}.lock", t.id)),
6194            dead_pid.to_string(),
6195        )
6196        .unwrap();
6197
6198        // Before the lock is swept the task looks claimed, and
6199        // `reclaim_orphaned_running` must leave it alone - this is exactly
6200        // the bug: a `running` task stranded behind a dead daemon's lock,
6201        // invisible to the claim-as-proof check because the lock outlived
6202        // the process that wrote it.
6203        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
6204        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6205
6206        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6207            pid != dead_pid
6208        });
6209        assert_eq!(swept, vec![t.id.clone()]);
6210
6211        let reclaimed = reclaim_orphaned_running(&queue, 2);
6212        assert_eq!(reclaimed, vec![t.id.clone()]);
6213        let after = queue.get(&t.id).unwrap();
6214        assert_eq!(
6215            after.status,
6216            TaskStatus::Held,
6217            "no run.json to recover from, so a human is asked"
6218        );
6219        assert_eq!(
6220            after.runs,
6221            vec!["20260904-000000-4043".to_owned()],
6222            "the crashed run's id is kept as evidence, not discarded"
6223        );
6224    }
6225
6226    #[test]
6227    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
6228        let dir = tempfile::tempdir().unwrap();
6229        let queue = Queue::at(dir.path().to_path_buf());
6230        let mut t = task();
6231        t.id = "20260101-000000-unknown".to_owned();
6232        queue.put(&mut t).unwrap();
6233        let dead_pid = injected_dead_pid();
6234        std::fs::write(
6235            dir.path().join(format!("{}.lock", t.id)),
6236            dead_pid.to_string(),
6237        )
6238        .unwrap();
6239
6240        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
6241        assert!(swept.is_empty(), "an unknown pid must keep its lock");
6242        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
6243    }
6244
6245    fn run_state_in(status: RunStatus, language: &str) -> RunState {
6246        let mut s = run_state(status);
6247        s.config.graph.language = language.to_owned();
6248        s
6249    }
6250
6251    fn unstarted_verdict(status: RunStatus) -> Verdict {
6252        Verdict {
6253            status,
6254            left_pr: false,
6255            quota_hit: false,
6256            parked: false,
6257            no_viable_candidates: false,
6258        }
6259    }
6260
6261    #[test]
6262    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
6263        let mut t = task();
6264        t.attempts = 1;
6265        settle_in(
6266            &mut t,
6267            unstarted_verdict(RunStatus::AlreadyInBase),
6268            "already in main",
6269            1,
6270            phrases("en"),
6271        );
6272        assert_eq!(t.status, TaskStatus::Done);
6273        assert_eq!(t.attempts, 0);
6274    }
6275
6276    #[test]
6277    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
6278        let reason = |language: &str| {
6279            let mut t = task();
6280            settle_in(
6281                &mut t,
6282                unstarted_verdict(RunStatus::Judging),
6283                "boom",
6284                1,
6285                phrases(language),
6286            );
6287            t.last_error.or(t.hold_reason).unwrap_or_default()
6288        };
6289        assert!(
6290            reason("en").starts_with("the graph stopped at `"),
6291            "{}",
6292            reason("en")
6293        );
6294        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
6295        assert!(reason("日本語").contains("boom"));
6296        assert_eq!(reason("fr"), reason("en"));
6297    }
6298
6299    #[test]
6300    fn describe_follows_the_run_language_and_keeps_the_run_id() {
6301        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
6302        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
6303        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
6304        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
6305        assert!(ja.contains("[run "), "{ja}");
6306        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
6307        assert!(ended.starts_with("run 終了: "), "{ended}");
6308        let mut de = run_state_in(RunStatus::Failed, "de");
6309        let mut en = run_state_in(RunStatus::Failed, "en");
6310        de.id = "same".to_owned();
6311        en.id = "same".to_owned();
6312        assert_eq!(describe(&de), describe(&en));
6313    }
6314
6315    #[test]
6316    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
6317        use crate::handover::Refused;
6318        let cases = [
6319            Refused::Foreign {
6320                branch: "b".into(),
6321                path: "/w/x".into(),
6322                why: "made by hand".into(),
6323            },
6324            Refused::Unsafe {
6325                branch: "b".into(),
6326                path: "/w/x".into(),
6327                why: "its worktree has uncommitted changes (a.rs)".into(),
6328            },
6329            Refused::ReleaseFailed {
6330                branch: "b".into(),
6331                path: "/w/x".into(),
6332                run: "ab12".into(),
6333            },
6334        ];
6335        for r in &cases {
6336            let en = (phrases("en").handover_refused)(r);
6337            assert_eq!(en, r.to_string());
6338            let ja = (phrases("ja").handover_refused)(r);
6339            assert!(
6340                !ja.contains("is checked out") && !ja.contains("try again"),
6341                "{ja}"
6342            );
6343            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
6344            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
6345                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
6346            }
6347        }
6348        assert!(phrases("en").handover_hint.contains("release the task"));
6349        assert!(phrases("ja").handover_hint.contains("解放"));
6350    }
6351
6352    #[test]
6353    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
6354        let build = |lang: &str| {
6355            let mut s = run_state_in(RunStatus::Blocked, lang);
6356            s.id = "same".to_owned();
6357            s.config.graph.review_rounds = 3;
6358            let mut r = review_round(3);
6359            r.expected = 3;
6360            r.answered = 1;
6361            s.reviews.push(r);
6362            s.event(
6363                "review",
6364                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
6365            );
6366            s
6367        };
6368        let en = describe(&build("en"));
6369        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
6370        let ja = describe(&build("ja"));
6371        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
6372        assert!(!ja.contains("never answered"), "{ja}");
6373        assert!(ja.contains("[run "), "{ja}");
6374
6375        // An incomplete panel whose verification failed is a different stop:
6376        // the real event must survive in ja too.
6377        let mut failed = build("ja");
6378        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
6379            command: "cargo test".to_owned(),
6380            code: Some(1),
6381            output_tail: String::new(),
6382            duration_ms: 0,
6383            resource_blocked: false,
6384        });
6385        failed.event("review", "stopped; e2e failed: cargo test");
6386        let ja = describe(&failed);
6387        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
6388        assert!(!ja.contains("席のレビュアー"), "{ja}");
6389    }
6390
6391    #[test]
6392    fn refusals_and_recovery_prose_follow_the_language() {
6393        let t = held_task_with("r1");
6394        let q = action_question(
6395            "r1",
6396            ask::ChoiceAction::Resume {
6397                run: "r1".to_owned(),
6398            },
6399        );
6400        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
6401            ActionDecision::Refuse(s) => s,
6402            other => panic!("{other:?}"),
6403        };
6404        assert!(refuse(phrases("en")).contains("could not be read: gone"));
6405        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
6406        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
6407
6408        let mut held = task();
6409        reclaim(&mut held, None, 2, "ja");
6410        assert!(held.hold_reason.unwrap().contains("保留にしました"));
6411        let mut held = task();
6412        reclaim(&mut held, None, 2, "xx");
6413        assert!(held.hold_reason.unwrap().contains("held for a human"));
6414    }
6415
6416    fn run_state(status: RunStatus) -> RunState {
6417        let mut state = RunState::new(
6418            PathBuf::from("/repo"),
6419            "main".to_owned(),
6420            "abc1234def".to_owned(),
6421            "add retries".to_owned(),
6422            Config::default(),
6423        );
6424        state.status = status;
6425        state
6426    }
6427
6428    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
6429        Candidate {
6430            index: 0,
6431            label,
6432            agent: "claude".to_owned(),
6433            branch: format!("magi/x/{label}"),
6434            worktree: PathBuf::from("/repo"),
6435            summary: summary.to_owned(),
6436            stat: String::new(),
6437            files: 0,
6438            commits: usize::from(!empty),
6439            empty,
6440            failed: failed.map(str::to_owned),
6441            verified_noop: None,
6442            duration_ms: 0,
6443            folded: false,
6444        }
6445    }
6446
6447    #[test]
6448    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
6449        let mut state = run_state(RunStatus::Blocked);
6450        state.gate = vec![
6451            CommandOutcome {
6452                command: "cargo make check".to_owned(),
6453                code: Some(0),
6454                output_tail: "ok".to_owned(),
6455                duration_ms: 0,
6456                resource_blocked: false,
6457            },
6458            CommandOutcome {
6459                command: "cargo test".to_owned(),
6460                code: Some(101),
6461                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
6462                duration_ms: 0,
6463                resource_blocked: false,
6464            },
6465        ];
6466        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
6467        assert!(d.contains("cargo test"), "{d}");
6468        assert!(
6469            !d.contains("cargo make check"),
6470            "a passing check is not a diagnostic: {d}"
6471        );
6472        assert!(d.contains("assertion failed"), "{d}");
6473    }
6474
6475    #[test]
6476    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
6477        let mut state = run_state(RunStatus::Blocked);
6478        state.event(
6479            "land",
6480            "stopped: the fixer produced no commit while 2 check(s) were failing \
6481             (build, lint); stopping instead of looping on an unchanged tree",
6482        );
6483        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
6484        assert!(d.contains("build"), "{d}");
6485        assert!(d.contains("lint"), "{d}");
6486        assert!(d.contains("fixer produced no commit"), "{d}");
6487    }
6488
6489    #[test]
6490    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
6491        // `describe`'s output becomes `Task::last_error` verbatim, and the
6492        // phone renders that in the same alarm-styled box an ordinary
6493        // failure gets. A bare `verified_noop` there would read exactly like
6494        // the failure this status exists to be told apart from.
6495        let state = run_state(RunStatus::VerifiedNoop);
6496        let d = describe(&state);
6497        assert!(
6498            d.contains("agent-verified no-op"),
6499            "expected the display label, not the wire spelling: {d}"
6500        );
6501        assert!(!d.contains("verified_noop"), "{d}");
6502    }
6503
6504    #[test]
6505    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
6506        // The whole point of the feature: a run held as "no candidate produced
6507        // a change" can mean the implementer actually finished the task and
6508        // only left a clean local tree behind - see AGENTS.md on this exact
6509        // failure mode. The diagnostic has to carry what the agent actually
6510        // said, not just the fact that nothing was there to judge.
6511        let mut state = run_state(RunStatus::Failed);
6512        state.candidates = vec![candidate(
6513            'A',
6514            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
6515            true,
6516            None,
6517        )];
6518        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
6519        assert!(d.contains("candidate A"), "{d}");
6520        assert!(d.contains("tagged v1.2.3"), "{d}");
6521    }
6522
6523    #[test]
6524    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
6525        let mut state = run_state(RunStatus::Failed);
6526        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
6527        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
6528        assert!(d.contains("candidate A"), "{d}");
6529        assert!(d.contains("agent timed out"), "{d}");
6530    }
6531
6532    #[test]
6533    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
6534        // A viable candidate existed, the gate never ran, and nothing land
6535        // said matches - `Task::last_error` is left to explain this one alone.
6536        let mut state = run_state(RunStatus::Failed);
6537        state.candidates = vec![candidate('A', "did the work", false, None)];
6538        assert!(diagnostic(&state).is_none());
6539    }
6540
6541    #[test]
6542    fn diagnostic_is_bounded_however_much_a_run_printed() {
6543        let mut state = run_state(RunStatus::Blocked);
6544        state.gate = vec![
6545            CommandOutcome {
6546                command: "cargo test".to_owned(),
6547                code: Some(101),
6548                output_tail: "x".repeat(50_000),
6549                duration_ms: 0,
6550                resource_blocked: false,
6551            },
6552            CommandOutcome {
6553                command: "cargo clippy".to_owned(),
6554                code: Some(1),
6555                output_tail: "y".repeat(50_000),
6556                duration_ms: 0,
6557                resource_blocked: false,
6558            },
6559        ];
6560        state.candidates = vec![
6561            candidate('A', &"z".repeat(50_000), true, None),
6562            candidate('B', &"w".repeat(50_000), true, None),
6563        ];
6564        let d = diagnostic(&state).expect("plenty here to diagnose");
6565        assert!(
6566            d.len() <= DIAGNOSTIC_MAX,
6567            "diagnostic grew to {} bytes, unbounded",
6568            d.len()
6569        );
6570    }
6571
6572    #[test]
6573    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
6574        let mut state = run_state(RunStatus::Blocked);
6575        state.gate = vec![CommandOutcome {
6576            command: "cargo test".to_owned(),
6577            code: Some(101),
6578            output_tail: "assertion failed".to_owned(),
6579            duration_ms: 0,
6580            resource_blocked: false,
6581        }];
6582        let verdict = Verdict {
6583            status: RunStatus::Blocked,
6584            left_pr: false,
6585            quota_hit: false,
6586            parked: false,
6587            no_viable_candidates: false,
6588        };
6589
6590        // Attempt one of two still has a retry coming: no diagnostic yet, the
6591        // task is going to run again and this run's evidence would go stale.
6592        let mut t = task();
6593        t.start("run-1".to_owned());
6594        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6595        assert_eq!(t.status, TaskStatus::Failed);
6596        assert!(t.diagnostic.is_none());
6597
6598        // Attempt two exhausts the budget: now it is held, and the
6599        // diagnostic is what `magi task show` has to say more than one line.
6600        t.start("run-2".to_owned());
6601        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
6602        assert_eq!(t.status, TaskStatus::Held);
6603        let d = t.diagnostic.expect("a held task must carry its diagnostic");
6604        assert!(d.contains("cargo test"), "{d}");
6605    }
6606
6607    #[test]
6608    fn a_held_task_names_the_open_question_it_is_waiting_on() {
6609        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
6610        // `magi ask` question settled Held with `hold_reason: null`, so the
6611        // notification said nothing actionable. `note_open_question` should
6612        // append the question id to whatever `handed_off` already wrote.
6613        crate::run::pin_test_home();
6614        let home = crate::run::home();
6615        let state = run_state(RunStatus::VerifiedNoop);
6616        let mut q = ask::Question::new(
6617            state.id.clone(),
6618            "implement".to_owned(),
6619            "impl-A".to_owned(),
6620            "is this really a no-op?".to_owned(),
6621            String::new(),
6622            Vec::new(),
6623        );
6624        Questions::at(home.join("questions")).put(&mut q).unwrap();
6625
6626        let verdict = Verdict {
6627            status: RunStatus::VerifiedNoop,
6628            left_pr: false,
6629            quota_hit: false,
6630            parked: false,
6631            no_viable_candidates: false,
6632        };
6633        let mut t = task();
6634        t.start(state.id.clone());
6635        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
6636
6637        assert_eq!(t.status, TaskStatus::Held);
6638        let reason = t.hold_reason.expect("a held task must record why");
6639        assert!(
6640            reason.starts_with("run ended agent-verified no-op"),
6641            "the original settle reason must survive unchanged: {reason}"
6642        );
6643        assert!(
6644            reason.contains(q.short()),
6645            "the open question's id must be named so the notice is actionable: {reason}"
6646        );
6647    }
6648
6649    #[test]
6650    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
6651        crate::run::pin_test_home();
6652        let state = run_state(RunStatus::VerifiedNoop);
6653
6654        let verdict = Verdict {
6655            status: RunStatus::VerifiedNoop,
6656            left_pr: false,
6657            quota_hit: false,
6658            parked: false,
6659            no_viable_candidates: false,
6660        };
6661        let mut t = task();
6662        t.start(state.id.clone());
6663        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
6664
6665        assert_eq!(t.status, TaskStatus::Held);
6666        assert_eq!(
6667            t.hold_reason.as_deref(),
6668            Some("run ended agent-verified no-op"),
6669            "nothing to append when the question was already answered or never asked"
6670        );
6671    }
6672
6673    #[test]
6674    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
6675        crate::run::pin_test_home();
6676        let mut first = run_state(RunStatus::Blocked);
6677        first.id = "20260101-000000-sup1".to_owned();
6678        first.save().unwrap();
6679        let mut second = run_state(RunStatus::Merged);
6680        second.id = "20260101-000000-sup2".to_owned();
6681        second.save().unwrap();
6682
6683        let mut t = task();
6684        t.runs = vec![first.id.clone(), second.id.clone()];
6685        t.status = TaskStatus::Done;
6686
6687        supersede_prior_runs(&t, &crate::run::home());
6688
6689        assert_eq!(
6690            RunState::load(&first.id).unwrap().status,
6691            RunStatus::Superseded,
6692            "the first attempt's Blocked no longer needs anyone's attention"
6693        );
6694        assert_eq!(
6695            RunState::load(&second.id).unwrap().status,
6696            RunStatus::Merged,
6697            "the run that actually succeeded is left exactly as it was"
6698        );
6699    }
6700
6701    #[test]
6702    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
6703        // `is_working_on` alone only proves a *daemon* claim; a `magi run
6704        // --resume` invoked by hand outside the daemon never touches
6705        // `daemon.json` at all, so it would look identical to a genuinely
6706        // idle run without also consulting `RunState::liveness`, which reads
6707        // this run's own recorded `driver_pid` instead.
6708        crate::run::pin_test_home();
6709        let mut first = run_state(RunStatus::Blocked);
6710        first.id = "20260101-000000-sup9".to_owned();
6711        // This test process's own pid: guaranteed alive without needing a
6712        // real second process or daemon.
6713        first.driver_pid = Some(std::process::id());
6714        first.driver_started_at = Some(
6715            crate::proc::process_started_at(std::process::id())
6716                .expect("this test process's own start time must be queryable"),
6717        );
6718        first.save().unwrap();
6719        let mut second = run_state(RunStatus::Merged);
6720        second.id = "20260101-000000-supa".to_owned();
6721        second.save().unwrap();
6722
6723        let mut t = task();
6724        t.runs = vec![first.id.clone(), second.id.clone()];
6725        t.status = TaskStatus::Done;
6726
6727        supersede_prior_runs(&t, &crate::run::home());
6728
6729        assert_eq!(
6730            RunState::load(&first.id).unwrap().status,
6731            RunStatus::Blocked,
6732            "a live driver_pid means something is still actually working this run, \
6733             even though no daemon claims it - rewriting under it would just be \
6734             undone the next time that process saves"
6735        );
6736    }
6737
6738    #[test]
6739    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
6740        // The first resweep must skip a still-live attempt exactly like
6741        // `supersede_prior_runs` itself does; a later resweep, once that
6742        // process is no longer actually driving it, is what closes the gap
6743        // `supersede_prior_runs` alone leaves - a task only ever reaches
6744        // `Done` once, so nothing else would ever look at this run again.
6745        let dir = tempfile::tempdir().unwrap();
6746        let home = dir.path().to_path_buf();
6747        let queue = Queue::at(dir.path().join("queue"));
6748
6749        let mut first = run_state(RunStatus::Blocked);
6750        first.id = "20260101-000000-supd".to_owned();
6751        first.driver_pid = Some(std::process::id());
6752        first.driver_started_at = Some(
6753            crate::proc::process_started_at(std::process::id())
6754                .expect("this test process's own start time must be queryable"),
6755        );
6756        first.save_under(&home).unwrap();
6757        let mut second = run_state(RunStatus::Merged);
6758        second.id = "20260101-000000-supe".to_owned();
6759        second.save_under(&home).unwrap();
6760
6761        let mut t = task();
6762        t.runs = vec![first.id.clone(), second.id.clone()];
6763        t.status = TaskStatus::Done;
6764        queue.put(&mut t).unwrap();
6765
6766        resweep_superseded_attempts(&queue, &home);
6767        assert_eq!(
6768            RunState::load_under(&first.id, &home).unwrap().status,
6769            RunStatus::Blocked,
6770            "still live on the first pass, so still untouched"
6771        );
6772
6773        // Stand in for the manual process no longer being the one driving
6774        // this run: same pid (this test process really is still alive), but
6775        // an identity marker that no longer matches it - see
6776        // `RunState::liveness`'s own doc for why a mismatched
6777        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
6778        let mut stale = RunState::load_under(&first.id, &home).unwrap();
6779        stale.driver_started_at = Some("1".to_owned());
6780        stale.save_under(&home).unwrap();
6781
6782        resweep_superseded_attempts(&queue, &home);
6783        assert_eq!(
6784            RunState::load_under(&first.id, &home).unwrap().status,
6785            RunStatus::Superseded,
6786            "the second pass catches up what the first one correctly skipped"
6787        );
6788    }
6789
6790    #[test]
6791    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
6792        crate::run::pin_test_home();
6793        let mut first = run_state(RunStatus::Blocked);
6794        first.id = "20260101-000000-sup3".to_owned();
6795        first.save().unwrap();
6796        let mut second = run_state(RunStatus::Blocked);
6797        second.id = "20260101-000000-sup4".to_owned();
6798        second.save().unwrap();
6799
6800        let mut t = task();
6801        t.runs = vec![first.id.clone(), second.id.clone()];
6802        // Still retrying: nothing about this task's story is settled yet, so
6803        // neither Blocked run may be relabelled, even though a later attempt
6804        // already exists.
6805        t.status = TaskStatus::Failed;
6806
6807        supersede_prior_runs(&t, &crate::run::home());
6808
6809        assert_eq!(
6810            RunState::load(&first.id).unwrap().status,
6811            RunStatus::Blocked
6812        );
6813        assert_eq!(
6814            RunState::load(&second.id).unwrap().status,
6815            RunStatus::Blocked
6816        );
6817    }
6818
6819    #[test]
6820    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
6821        // `magi task done` (or the API's equivalent) can close a task with no
6822        // run of its own ever having succeeded - there is nothing here that
6823        // counts as "the attempt that finished it", so nothing is rewritten.
6824        crate::run::pin_test_home();
6825        let mut first = run_state(RunStatus::Blocked);
6826        first.id = "20260101-000000-sup5".to_owned();
6827        first.save().unwrap();
6828
6829        let mut t = task();
6830        t.runs = vec![first.id.clone()];
6831        t.status = TaskStatus::Done;
6832
6833        supersede_prior_runs(&t, &crate::run::home());
6834
6835        assert_eq!(
6836            RunState::load(&first.id).unwrap().status,
6837            RunStatus::Blocked,
6838            "a single-attempt task has no earlier run to supersede"
6839        );
6840    }
6841
6842    #[test]
6843    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
6844        // `magi task done` (or the web/conductor equivalents) can close a
6845        // task in any status, including one whose *last* recorded attempt is
6846        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
6847        // never watched, say. `runs.last()` being `Done`-adjacent is not
6848        // proof it actually succeeded, so nothing earlier may be relabelled
6849        // on its say-so alone.
6850        crate::run::pin_test_home();
6851        let mut first = run_state(RunStatus::Blocked);
6852        first.id = "20260101-000000-supb".to_owned();
6853        first.save().unwrap();
6854        let mut second = run_state(RunStatus::Failed);
6855        second.id = "20260101-000000-supc".to_owned();
6856        second.save().unwrap();
6857
6858        let mut t = task();
6859        t.runs = vec![first.id.clone(), second.id.clone()];
6860        t.status = TaskStatus::Done;
6861
6862        supersede_prior_runs(&t, &crate::run::home());
6863
6864        assert_eq!(
6865            RunState::load(&first.id).unwrap().status,
6866            RunStatus::Blocked,
6867            "the task's last attempt never landed, so there is nothing here \
6868             actually superseding it"
6869        );
6870    }
6871
6872    #[test]
6873    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
6874        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
6875        // to look" - `Failed` and `VerifiedNoop` are already their own
6876        // terminal answers and must not be relabelled into a third one.
6877        crate::run::pin_test_home();
6878        let mut failed = run_state(RunStatus::Failed);
6879        failed.id = "20260101-000000-sup6".to_owned();
6880        failed.save().unwrap();
6881        let mut noop = run_state(RunStatus::VerifiedNoop);
6882        noop.id = "20260101-000000-sup7".to_owned();
6883        noop.save().unwrap();
6884        let mut winner = run_state(RunStatus::Ready);
6885        winner.id = "20260101-000000-sup8".to_owned();
6886        winner.save().unwrap();
6887
6888        let mut t = task();
6889        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
6890        t.status = TaskStatus::Done;
6891
6892        supersede_prior_runs(&t, &crate::run::home());
6893
6894        assert_eq!(
6895            RunState::load(&failed.id).unwrap().status,
6896            RunStatus::Failed
6897        );
6898        assert_eq!(
6899            RunState::load(&noop.id).unwrap().status,
6900            RunStatus::VerifiedNoop
6901        );
6902    }
6903
6904    fn approval_question(run: &str) -> ask::Question {
6905        ask::Question::new(
6906            run.to_owned(),
6907            land::APPROVAL_NODE.to_owned(),
6908            "land".to_owned(),
6909            "merge?".to_owned(),
6910            String::new(),
6911            vec!["merge".to_owned(), "hold".to_owned()],
6912        )
6913    }
6914
6915    #[test]
6916    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
6917        crate::run::pin_test_home();
6918        let mut state = run_state(RunStatus::Landing);
6919        state.id = "20260101-000000-fre1".to_owned();
6920        state.parked = true;
6921        state.save().unwrap();
6922        ask::Questions::open()
6923            .put(&mut approval_question(&state.id))
6924            .unwrap();
6925
6926        let mut t = task();
6927        t.runs.push(state.id.clone());
6928        assert_eq!(
6929            land_resume_state(&t),
6930            LandResume::StillWaiting,
6931            "nobody has answered and the timeout has not passed"
6932        );
6933    }
6934
6935    #[test]
6936    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
6937        crate::run::pin_test_home();
6938        let mut state = run_state(RunStatus::Gating);
6939        state.id = "20260101-000000-gt01".to_owned();
6940        state.parked = true;
6941        state.config.graph.answer_timeout = 60;
6942        state.github_text = Some(crate::run::GithubTextAsk {
6943            rewrite: None,
6944            fingerprint: "f".into(),
6945            title: true,
6946            body: false,
6947            categories: vec!["title-language".into()],
6948            question: None,
6949            asks: 1,
6950            resolved: false,
6951            chosen_title: None,
6952            choice: None,
6953        });
6954        state.save().unwrap();
6955        let store = ask::Questions::open();
6956        let mut q = ask::Question::new(
6957            state.id.clone(),
6958            crate::github_text::ASK_NODE.to_owned(),
6959            crate::github_text::ASK_SEAT.to_owned(),
6960            "s".into(),
6961            String::new(),
6962            vec!["use fallback".into()],
6963        );
6964        store.put(&mut q).unwrap();
6965        let mut t = task();
6966        t.runs.push(state.id.clone());
6967        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
6968        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6969        store.put(&mut q).unwrap();
6970        assert_eq!(land_resume_state(&t), LandResume::Ready);
6971        assert!(!store.get(&q.id).unwrap().status.open());
6972        // Once decided, a parked run is an ordinary candidate again.
6973        state.github_text.as_mut().unwrap().resolved = true;
6974        state.save().unwrap();
6975        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
6976    }
6977
6978    #[test]
6979    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
6980        // `ask::ask_and_wait`'s own deadline used to retire a question
6981        // nobody answered; land's approval bypasses that wait (see
6982        // `land::approval_gate`), so this is now the only place
6983        // `graph.answer_timeout` is enforced for a land approval at all.
6984        crate::run::pin_test_home();
6985        let mut state = run_state(RunStatus::Landing);
6986        state.id = "20260101-000000-exp1".to_owned();
6987        state.parked = true;
6988        state.config.graph.answer_timeout = 60;
6989        state.save().unwrap();
6990
6991        let store = ask::Questions::open();
6992        let mut q = approval_question(&state.id);
6993        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
6994        store.put(&mut q).unwrap();
6995
6996        let mut t = task();
6997        t.runs.push(state.id.clone());
6998        assert_eq!(
6999            land_resume_state(&t),
7000            LandResume::Ready,
7001            "an expired question must not be waited on forever"
7002        );
7003
7004        let after = store.get(&q.id).unwrap();
7005        assert!(
7006            !after.status.open(),
7007            "the question is abandoned, not silently ignored"
7008        );
7009        assert!(
7010            after.resolution().is_none(),
7011            "an abandoned question is not read as a decision"
7012        );
7013    }
7014
7015    #[test]
7016    fn reclaim_settles_a_running_task_against_its_last_run() {
7017        let mut t = task();
7018        t.start("20260904-000000-4043".to_owned());
7019        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
7020        assert_eq!(
7021            t.status,
7022            TaskStatus::Done,
7023            "a run that actually finished must not stay `running` forever"
7024        );
7025    }
7026
7027    #[test]
7028    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
7029        let mut t = task();
7030        t.start("20260904-000000-4043".to_owned());
7031        t.last_error = Some("earlier trouble".to_owned());
7032        let mut state = run_state(RunStatus::Judging);
7033        state.parked = true;
7034        reclaim(&mut t, Some(state), 1, "en");
7035        assert_eq!(t.status, TaskStatus::Parked);
7036        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
7037        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7038        assert!(t.park_reason.is_some());
7039        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
7040        assert!(!t.fresh_start);
7041        assert!(t.status.runnable());
7042    }
7043
7044    #[test]
7045    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
7046        let mut t = task();
7047        t.start("20260904-000000-4043".to_owned());
7048        t.last_error = Some("earlier trouble".to_owned());
7049        settle(
7050            &mut t,
7051            Verdict {
7052                status: RunStatus::Judging,
7053                left_pr: false,
7054                quota_hit: false,
7055                parked: true,
7056                no_viable_candidates: false,
7057            },
7058            "parked after `judging`",
7059            1,
7060        );
7061        assert_eq!(t.status, TaskStatus::Parked);
7062        assert_eq!(t.attempts, 0);
7063        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7064        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
7065        assert_eq!(t.schema, crate::queue::SCHEMA);
7066        assert!(
7067            crate::notices::task_held(&t).is_none(),
7068            "a park is not news"
7069        );
7070        t.start("20260904-000000-4043".to_owned());
7071        assert_eq!(t.park_reason, None);
7072    }
7073
7074    #[test]
7075    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
7076        // A blocked run with attempts left goes back to `Failed`, exactly as
7077        // it would from `attempt` itself - `reclaim` must not invent a second
7078        // policy for a task a daemon merely stopped without reporting.
7079        let mut t = task();
7080        t.start("20260904-000000-4043".to_owned());
7081        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
7082        assert_eq!(t.status, TaskStatus::Failed);
7083        assert!(t.status.runnable());
7084    }
7085
7086    #[test]
7087    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
7088        let mut t = task();
7089        t.start("20260904-000000-4043".to_owned());
7090        assert_eq!(t.attempts, 1);
7091        let mut run = run_state(RunStatus::Implementing);
7092        run.id = "20260904-000000-4043".to_owned();
7093        run.begin_pass();
7094        let cause = crate::run::ParkCause::Upgrade {
7095            from: "0.121.0".to_owned(),
7096            to: Some("0.121.1".to_owned()),
7097        };
7098        run.end_pass_parked(cause.clone());
7099        run.parked = true;
7100        let verdict = Verdict {
7101            status: run.status,
7102            left_pr: false,
7103            quota_hit: false,
7104            parked: true,
7105            no_viable_candidates: false,
7106        };
7107        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
7108        assert_eq!(t.attempts, 0);
7109        assert_eq!(t.passes.len(), 1);
7110        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7111        assert_eq!(t.passes[0].parked, Some(cause));
7112        assert_eq!(t.passes[0].pass_index, 0);
7113
7114        // A resumed pass that then fails spends its attempt, and the earlier
7115        // pass's entry is untouched.
7116        t.start("20260904-000000-4043".to_owned());
7117        run.begin_pass();
7118        run.status = RunStatus::Failed;
7119        let verdict = Verdict {
7120            status: RunStatus::Failed,
7121            left_pr: false,
7122            quota_hit: false,
7123            parked: false,
7124            no_viable_candidates: false,
7125        };
7126        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
7127        assert_eq!(t.passes.len(), 2);
7128        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7129        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
7130        assert_eq!(t.passes[1].pass_index, 1);
7131        assert_eq!(t.attempts, 1);
7132    }
7133
7134    #[test]
7135    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
7136        let mut t = task();
7137        t.start("20260904-000000-4043".to_owned());
7138        reclaim(&mut t, None, 2, "en");
7139        assert_eq!(t.status, TaskStatus::Held);
7140        assert!(
7141            t.last_error
7142                .as_deref()
7143                .is_some_and(|e| e.contains("running")),
7144            "the operator needs to know why this task was held"
7145        );
7146    }
7147
7148    #[test]
7149    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
7150        let dir = tempfile::tempdir().unwrap();
7151        let queue = Queue::at(dir.path().to_path_buf());
7152
7153        // No run recorded, so this never has to touch `RunState::load`.
7154        let mut orphaned = task();
7155        orphaned.id = "20260904-000000-orph".to_owned();
7156        orphaned.status = TaskStatus::Running;
7157        orphaned.attempts = 1;
7158        queue.put(&mut orphaned).unwrap();
7159
7160        let mut alive = task();
7161        alive.id = "20260904-000000-live".to_owned();
7162        alive.status = TaskStatus::Running;
7163        alive.attempts = 1;
7164        queue.put(&mut alive).unwrap();
7165        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
7166
7167        let mut queued = task();
7168        queued.id = "20260904-000000-wait".to_owned();
7169        queue.put(&mut queued).unwrap();
7170
7171        let reclaimed = reclaim_orphaned_running(&queue, 2);
7172        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
7173
7174        assert_eq!(
7175            queue.get(&orphaned.id).unwrap().status,
7176            TaskStatus::Held,
7177            "nothing was driving it and there was no run to recover"
7178        );
7179        assert_eq!(
7180            queue.get(&alive.id).unwrap().status,
7181            TaskStatus::Running,
7182            "a live claim must protect the task it belongs to"
7183        );
7184        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
7185    }
7186
7187    /// Read a run.json back from an explicit `home`, the same way
7188    /// `reclaim_abandoned_runs` itself does - never through the
7189    /// process-global `RunState::load`, which this test's own `home` (an
7190    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
7191    /// use at all.
7192    fn read_run_under(home: &Path, id: &str) -> RunState {
7193        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
7194        serde_json::from_str(&body).unwrap()
7195    }
7196
7197    #[test]
7198    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
7199        let dir = tempfile::tempdir().unwrap();
7200        let home = dir.path().to_path_buf();
7201        let now = Timestamp::now();
7202        let overrun_seat = || crate::run::ActiveSeat {
7203            node: "implement".to_owned(),
7204            started_at: now - jiff::SignedDuration::new(21_000, 0),
7205            timeout_secs: 3_600,
7206            attempt: 0,
7207            task: None,
7208            command: None,
7209            index: None,
7210            total: None,
7211        };
7212
7213        let mut dead = run_state(RunStatus::Implementing);
7214        dead.id = "20260101-000000-dead".to_owned();
7215        dead.active.insert("impl-A".to_owned(), overrun_seat());
7216        // A `driver_pid` the injected query below confirms gone outright —
7217        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
7218        dead.driver_pid = Some(4242);
7219        dead.save_under(&home).unwrap();
7220
7221        // Same shape, but a live daemon's heartbeat names it: must be left
7222        // exactly alone, however far past its own timeout the seat sits.
7223        let mut alive = run_state(RunStatus::Implementing);
7224        alive.id = "20260101-000000-aliv".to_owned();
7225        alive.active.insert("impl-A".to_owned(), overrun_seat());
7226        alive.save_under(&home).unwrap();
7227        let mut status = Status::new();
7228        status.current = vec![Current {
7229            task: "20260101-000000-task".to_owned(),
7230            run: alive.id.clone(),
7231        }];
7232        write_status_to(&home.join("daemon.json"), &status).unwrap();
7233
7234        // The abandoned seat left an open question behind: nobody is left to
7235        // read an answer once the run is failed, and this must not wait for
7236        // some later daemon startup's own sweep to notice that.
7237        let questions = Questions::at(home.join("questions"));
7238        let mut q = ask::Question::new(
7239            dead.id.clone(),
7240            "implement".to_owned(),
7241            "impl-A".to_owned(),
7242            "Which storage backend?".to_owned(),
7243            String::new(),
7244            vec!["SQLite".to_owned(), "Redis".to_owned()],
7245        );
7246        questions.put(&mut q).unwrap();
7247
7248        let abandoned = reclaim_abandoned_runs_with(
7249            &home,
7250            now,
7251            |pid| if pid == 4242 { Some(false) } else { None },
7252            |_| panic!("a query answering Dead outright needs no identity corroboration"),
7253        );
7254        assert_eq!(abandoned, vec![dead.id.clone()]);
7255
7256        let reloaded = read_run_under(&home, &dead.id);
7257        assert_eq!(reloaded.status, RunStatus::Failed);
7258        assert!(reloaded.active.is_empty());
7259        assert!(
7260            !questions.get(&q.id).unwrap().status.open(),
7261            "the failed run's own open question must be settled in the same pass"
7262        );
7263
7264        let still_alive = read_run_under(&home, &alive.id);
7265        assert_eq!(
7266            still_alive.status,
7267            RunStatus::Implementing,
7268            "a live daemon's claim protects it"
7269        );
7270        assert!(!still_alive.active.is_empty());
7271    }
7272
7273    /// The exact shape a review round flagged as broken: `magi serve` running
7274    /// in this same `home` scans *every* run on disk, including a manual
7275    /// `magi review` / `magi run` this daemon never started and that
7276    /// therefore claims no heartbeat of its own. Before this scan asked
7277    /// `liveness` rather than just `is_working_on`, a manual run whose active
7278    /// seat merely ran a little past its own timeout — the CLI finishing up,
7279    /// its result still being collected — got wiped and failed by a daemon
7280    /// that had nothing to do with it, out from under a process that was
7281    /// still very much running.
7282    #[test]
7283    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
7284        let dir = tempfile::tempdir().unwrap();
7285        let home = dir.path().to_path_buf();
7286        let now = Timestamp::now();
7287
7288        let mut manual = run_state(RunStatus::Reviewing);
7289        manual.id = "20260101-000000-manl".to_owned();
7290        manual.active.insert(
7291            "review-1".to_owned(),
7292            crate::run::ActiveSeat {
7293                node: "review".to_owned(),
7294                started_at: now - jiff::SignedDuration::new(21_000, 0),
7295                timeout_secs: 3_600,
7296                attempt: 0,
7297                task: None,
7298                command: None,
7299                index: None,
7300                total: None,
7301            },
7302        );
7303        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
7304        // but a real, still-running process: `liveness` must corroborate this
7305        // as `Live`, not read the missing daemon claim as death.
7306        manual.driver_pid = Some(4242);
7307        manual.driver_started_at = Some("1790000000".to_owned());
7308        manual.save_under(&home).unwrap();
7309
7310        let abandoned = reclaim_abandoned_runs_with(
7311            &home,
7312            now,
7313            |pid| if pid == 4242 { Some(true) } else { None },
7314            |pid| {
7315                if pid == 4242 {
7316                    Some("1790000000".to_owned())
7317                } else {
7318                    None
7319                }
7320            },
7321        );
7322        assert!(
7323            abandoned.is_empty(),
7324            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
7325        );
7326
7327        let reloaded = read_run_under(&home, &manual.id);
7328        assert_eq!(reloaded.status, RunStatus::Reviewing);
7329        assert!(!reloaded.active.is_empty());
7330    }
7331
7332    #[test]
7333    fn an_already_claimed_task_is_skipped_rather_than_failed() {
7334        let dir = tempfile::tempdir().unwrap();
7335        let queue = Queue::at(dir.path().to_path_buf());
7336        let mut only = task();
7337        queue.put(&mut only).unwrap();
7338
7339        let _elsewhere = queue.claim(&only.id).unwrap();
7340        let candidates = runnable(&queue);
7341        assert_eq!(candidates.len(), 1, "the task is still runnable");
7342        assert!(
7343            queue.claim(&candidates[0].id).is_err(),
7344            "the loop cannot take a claim somebody else holds"
7345        );
7346
7347        let after = queue.get(&only.id).unwrap();
7348        assert_eq!(after.status, TaskStatus::Queued);
7349        assert_eq!(
7350            after.attempts, 0,
7351            "losing the race is not an attempt at the task"
7352        );
7353        assert_eq!(after.last_error, None);
7354    }
7355
7356    #[test]
7357    fn the_status_file_round_trips_and_its_heartbeat_advances() {
7358        let dir = tempfile::tempdir().unwrap();
7359        let path = dir.path().join("daemon.json");
7360
7361        let mut status = Status::new();
7362        status.idle = false;
7363        status.completed = 7;
7364        status.current = vec![Current {
7365            task: "20260902-000000-t111".to_owned(),
7366            run: "20260902-000001-r111".to_owned(),
7367        }];
7368        write_status_to(&path, &status).unwrap();
7369        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7370        assert_eq!(first.schema, SCHEMA);
7371        assert_eq!(first.pid, std::process::id());
7372        assert!(!first.idle);
7373        assert_eq!(first.completed, 7);
7374        assert_eq!(first.current, status.current);
7375        assert!(
7376            !path.with_extension("json.tmp").exists(),
7377            "the temp file is renamed, not left behind"
7378        );
7379
7380        std::thread::sleep(Duration::from_millis(5));
7381        status.updated_at = Timestamp::now();
7382        status.polls = 3;
7383        write_status_to(&path, &status).unwrap();
7384        let second: Status =
7385            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7386        assert!(
7387            second.updated_at > first.updated_at,
7388            "a reader can only detect staleness if the heartbeat moves"
7389        );
7390        assert_eq!(
7391            second.started_at, first.started_at,
7392            "the start time is not a heartbeat"
7393        );
7394        assert_eq!(second.polls, 3);
7395    }
7396
7397    #[test]
7398    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
7399        let dir = tempfile::tempdir().unwrap();
7400
7401        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
7402
7403        let mut status = Status::new();
7404        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
7405        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7406        let stale = read_status(dir.path()).unwrap();
7407        assert!(
7408            !stale.running(Timestamp::now()),
7409            "a minute without a heartbeat is a dead daemon, not a busy one"
7410        );
7411        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
7412
7413        status.updated_at = Timestamp::now();
7414        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7415        let fresh = read_status(dir.path()).unwrap();
7416        assert!(fresh.running(Timestamp::now()));
7417    }
7418
7419    #[test]
7420    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
7421        let dir = tempfile::tempdir().unwrap();
7422        let now = Timestamp::now();
7423        let mine = "20260903-080619-01c2";
7424
7425        assert!(
7426            !is_working_on(dir.path(), mine, now),
7427            "no status file means nobody is working on anything"
7428        );
7429
7430        let mut status = Status::new();
7431        status.current = vec![Current {
7432            task: "20260903-080340-0167".to_owned(),
7433            run: mine.to_owned(),
7434        }];
7435        status.updated_at = now;
7436        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7437        assert!(is_working_on(dir.path(), mine, now));
7438        assert!(
7439            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
7440            "a daemon busy with one run is not working on another"
7441        );
7442
7443        // A killed daemon stops writing heartbeats but leaves the file behind
7444        // naming the run it died in. That run must not be undeletable forever.
7445        status.updated_at = now - jiff::SignedDuration::from_secs(600);
7446        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7447        assert!(
7448            !is_working_on(dir.path(), mine, now),
7449            "a stale heartbeat is a dead daemon, so its run is a leftover"
7450        );
7451    }
7452
7453    #[test]
7454    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
7455        let dir = tempfile::tempdir().unwrap();
7456        let now = Timestamp::now();
7457
7458        assert!(
7459            !is_working_on_short(dir.path(), "01c2", now),
7460            "no status file means nobody is working on anything"
7461        );
7462
7463        let mut status = Status::new();
7464        status.current = vec![Current {
7465            task: "20260903-080340-0167".to_owned(),
7466            run: "20260903-080619-01c2".to_owned(),
7467        }];
7468        status.updated_at = now;
7469        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
7470        assert!(
7471            is_working_on_short(dir.path(), "01c2", now),
7472            "the run's short id is the last block of its full id"
7473        );
7474        assert!(
7475            !is_working_on_short(dir.path(), "3cbf", now),
7476            "a daemon busy with one worktree bay is not working on another"
7477        );
7478    }
7479
7480    #[test]
7481    fn a_newer_status_file_still_yields_a_reading() {
7482        let dir = tempfile::tempdir().unwrap();
7483        // A field this build has never heard of must not turn the reading into
7484        // nothing at all; that is the whole reason the reader is permissive.
7485        std::fs::write(
7486            dir.path().join("daemon.json"),
7487            serde_json::json!({
7488                "schema": 2,
7489                "updated_at": Timestamp::now().to_string(),
7490                "idle": true,
7491                "surprise": { "nested": [1, 2, 3] },
7492            })
7493            .to_string(),
7494        )
7495        .unwrap();
7496
7497        let reading = read_status(dir.path()).expect("a forward-compatible read");
7498        assert!(reading.running(Timestamp::now()));
7499        assert!(reading.idle);
7500        assert!(reading.current.is_empty());
7501    }
7502
7503    #[test]
7504    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
7505        // A daemon started before `current` became a list keeps writing this
7506        // shape on every heartbeat until it is restarted. A rolling upgrade
7507        // - a newer `magi web` or `magi doctor` reading an older `magi
7508        // serve`'s heartbeat - must still see the run it is on, not "no
7509        // daemon" from a type mismatch failing the whole struct.
7510        let dir = tempfile::tempdir().unwrap();
7511        std::fs::write(
7512            dir.path().join("daemon.json"),
7513            serde_json::json!({
7514                "schema": 1,
7515                "pid": 4242,
7516                "updated_at": Timestamp::now().to_string(),
7517                "idle": false,
7518                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
7519                "completed": 3,
7520                "polls": 9,
7521            })
7522            .to_string(),
7523        )
7524        .unwrap();
7525
7526        let reading = read_status(dir.path()).expect("an older shape must still parse");
7527        assert!(reading.running(Timestamp::now()));
7528        assert_eq!(
7529            reading.current,
7530            vec![Current {
7531                task: "20260902-140501-aaaa".to_owned(),
7532                run: "20260902-140502-bbbb".to_owned(),
7533            }]
7534        );
7535    }
7536
7537    #[test]
7538    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
7539        let dir = tempfile::tempdir().unwrap();
7540        std::fs::write(
7541            dir.path().join("daemon.json"),
7542            serde_json::json!({
7543                "schema": 1,
7544                "updated_at": Timestamp::now().to_string(),
7545                "idle": true,
7546                "current": null,
7547            })
7548            .to_string(),
7549        )
7550        .unwrap();
7551        let with_null = read_status(dir.path()).expect("null must still parse");
7552        assert!(with_null.current.is_empty());
7553
7554        std::fs::write(
7555            dir.path().join("daemon.json"),
7556            serde_json::json!({
7557                "schema": 1,
7558                "updated_at": Timestamp::now().to_string(),
7559                "idle": true,
7560            })
7561            .to_string(),
7562        )
7563        .unwrap();
7564        let absent = read_status(dir.path()).expect("a missing field must still parse");
7565        assert!(absent.current.is_empty());
7566    }
7567
7568    #[test]
7569    fn a_task_without_a_repository_runs_in_the_daemons_default() {
7570        let fallback = Path::new("/default");
7571        let mut blank = task();
7572        blank.repo = PathBuf::new();
7573        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
7574        let mut dot = task();
7575        dot.repo = PathBuf::from(".");
7576        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
7577        assert_eq!(
7578            repo_for(&task(), fallback),
7579            PathBuf::from("/repo"),
7580            "a task that names a repository keeps it"
7581        );
7582    }
7583
7584    #[test]
7585    fn task_implementers_edit_inherits_daemon_config_and_merge() {
7586        let dir = tempfile::tempdir().unwrap();
7587        let path = dir.path().join("explicit.toml");
7588        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
7589        let opts = Opts {
7590            config: Some(path),
7591            merge: Some("none".into()),
7592            ..Default::default()
7593        };
7594        let mut t = task();
7595        t.set_implementers(
7596            2,
7597            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7598                .unwrap(),
7599        )
7600        .unwrap();
7601        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
7602        assert_eq!(cfg.graph.implementers, 2);
7603        assert_eq!(cfg.graph.judges, 1);
7604        assert_eq!(cfg.merge.mode, MergeMode::None);
7605        t.set_implementers(1, &cfg).unwrap();
7606        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
7607        apply_task_implementers(&mut cfg, &t);
7608        assert_eq!(cfg.graph.implementers, 1);
7609        assert_eq!(cfg.graph.judges, 1);
7610        assert_eq!(cfg.merge.mode, MergeMode::None);
7611    }
7612
7613    #[test]
7614    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
7615        let dir = tempfile::tempdir().unwrap();
7616        let repo = dir.path().join("repo");
7617        std::fs::create_dir(&repo).unwrap();
7618        std::fs::write(
7619            repo.join("magi.toml"),
7620            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
7621        )
7622        .unwrap();
7623        let daemon_config = dir.path().join("daemon.toml");
7624        std::fs::write(
7625            &daemon_config,
7626            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
7627        )
7628        .unwrap();
7629        let opts = Opts {
7630            config: Some(daemon_config),
7631            merge: Some("pr".into()),
7632            ..Default::default()
7633        };
7634        let q = Queue::at(dir.path().join("queue"));
7635        let validation: Config =
7636            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7637                .unwrap();
7638        // No provenance field on legacy direct tasks: both shapes stay isolated.
7639        for record in ["{}", r#"{"candidates":2}"#] {
7640            let overrides = serde_json::from_str(record).unwrap();
7641            let filing = crate::direct::Filing {
7642                instruction: "work".into(),
7643                title: "direct".into(),
7644                repo: repo.clone(),
7645                source: crate::queue::Source::Human,
7646                solo: false,
7647                overrides,
7648                review_of: None,
7649            };
7650            let filed =
7651                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
7652            let crate::direct::Filed::Standalone {
7653                mut task,
7654                claim: _claim,
7655            } = filed
7656            else {
7657                panic!("local filing")
7658            };
7659            let before = prepare_for(&repo, &opts, &task).unwrap();
7660            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
7661            assert_eq!(
7662                before.merge.mode,
7663                MergeMode::None,
7664                "daemon --merge must not leak"
7665            );
7666            for n in [2, 1, 2] {
7667                task.set_implementers(n, &validation).unwrap();
7668                q.put(&mut task).unwrap();
7669                task = q.get(&task.id).unwrap();
7670                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
7671                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
7672                apply_task_implementers(&mut cfg, &task);
7673                assert_eq!(cfg.graph.implementers, usize::from(n));
7674                assert_eq!(cfg.graph.judges, 2);
7675                assert_eq!(cfg.merge.mode, MergeMode::None);
7676            }
7677        }
7678    }
7679
7680    #[test]
7681    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
7682        let cfg: Config =
7683            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7684                .unwrap();
7685        let mut t = task();
7686        t.review_of = Some("review-target".into());
7687        t.hold_manual(Some("retry".into()));
7688        let mut previous = RunState::new(
7689            PathBuf::from("/repo"),
7690            "main".into(),
7691            "abc1234".into(),
7692            "review".into(),
7693            cfg.clone(),
7694        );
7695        previous.config.graph.implementers = 2;
7696        for count in [1, 3] {
7697            t.set_implementers(count, &cfg).unwrap();
7698            t.release();
7699            assert_eq!(t.review_of.as_deref(), Some("review-target"));
7700            for proposed in [
7701                Starter::Resume(previous.id.clone()),
7702                Starter::Review("recovery-target".into()),
7703            ] {
7704                assert_eq!(
7705                    starter_with_implementers(&t, Some(&previous), proposed),
7706                    Starter::Review("review-target".into())
7707                );
7708            }
7709            let mut configured = cfg.clone();
7710            apply_task_implementers(&mut configured, &t);
7711            assert_eq!(configured.graph.implementers, usize::from(count));
7712            assert_eq!(previous.config.graph.implementers, 2);
7713        }
7714    }
7715
7716    #[test]
7717    fn task_implementers_dispatch_and_resume_agree() {
7718        let mut t = task();
7719        let cfg: crate::config::Config =
7720            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
7721                .unwrap();
7722        let mut run = RunState::new(
7723            PathBuf::from("/repo"),
7724            "main".into(),
7725            "abc1234".into(),
7726            "work".into(),
7727            cfg.clone(),
7728        );
7729        run.config.graph.implementers = 2;
7730        for n in [2, 1, 3, 2] {
7731            t.set_implementers(n, &cfg).unwrap();
7732            let mut dispatched = cfg.clone();
7733            apply_task_implementers(&mut dispatched, &t);
7734            assert_eq!(dispatched.graph.implementers, usize::from(n));
7735            assert_eq!(implementers_match(&t, &run), n == 2);
7736            for proposed in [
7737                Starter::Resume(run.id.clone()),
7738                Starter::Review("old-branch".into()),
7739            ] {
7740                let expected = if n == 2 {
7741                    proposed.clone()
7742                } else {
7743                    Starter::Start
7744                };
7745                assert_eq!(
7746                    starter_with_implementers(&t, Some(&run), proposed),
7747                    expected
7748                );
7749            }
7750            assert_eq!(
7751                run.config.graph.implementers, 2,
7752                "history must not be rewritten"
7753            );
7754        }
7755        t.solo = false;
7756        t.overrides = None;
7757        assert!(implementers_match(&t, &run));
7758    }
7759
7760    #[test]
7761    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
7762        // Three seats said out loud. What `solo` promises is one candidate
7763        // *whatever the config asks for*, so the contrast has to be a number
7764        // this test owns - it used to be `Config::default()`'s, which became
7765        // 1 when one implementation became the default and left the two
7766        // halves of this test asserting the same thing.
7767        let mut solo_cfg = Config::default();
7768        solo_cfg.graph.implementers = 3;
7769        let mut solo_task = task();
7770        solo_task.solo = true;
7771        apply_task_implementers(&mut solo_cfg, &solo_task);
7772        assert_eq!(solo_cfg.graph.implementers, 1);
7773
7774        let mut plain_cfg = Config::default();
7775        plain_cfg.graph.implementers = 3;
7776        let plain_task = task();
7777        assert!(!plain_task.solo);
7778        apply_task_implementers(&mut plain_cfg, &plain_task);
7779        assert_eq!(
7780            plain_cfg.graph.implementers, 3,
7781            "a task that did not ask to run alone keeps the config's candidates"
7782        );
7783    }
7784
7785    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
7786        QuotaLoss {
7787            seat: seat.into(),
7788            node: "judge".into(),
7789            at: at.parse().unwrap(),
7790            reset: reset.map(str::to_string),
7791        }
7792    }
7793
7794    #[test]
7795    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
7796        let old: Vec<QuotaLoss> = (1..=4)
7797            .map(|i| {
7798                loss(
7799                    &format!("judge-{i}"),
7800                    "2026-09-23T05:23:00Z",
7801                    Some("2:40pm (Asia/Tokyo)"),
7802                )
7803            })
7804            .collect();
7805        let fresh = losses_this_attempt(&old, &old);
7806        assert!(fresh.is_empty());
7807        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
7808        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
7809    }
7810
7811    #[test]
7812    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
7813        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
7814        let now = Timestamp::now();
7815        let mut after = old.clone();
7816        after.push(loss("judge-2", &now.to_string(), None));
7817        let fresh = losses_this_attempt(&old, &after);
7818        assert_eq!(fresh, vec![after[1].clone()]);
7819        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
7820        assert_eq!(
7821            until,
7822            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
7823        );
7824    }
7825
7826    #[test]
7827    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
7828        // `recover_stall` removes judge-1's loss and the retry then hits quota
7829        // again: the vector is the same length, so an index diff sees nothing.
7830        let before = vec![
7831            loss("judge-1", "2026-09-23T05:23:00Z", None),
7832            loss("judge-2", "2026-09-23T05:24:00Z", None),
7833        ];
7834        let after = vec![
7835            loss("judge-2", "2026-09-23T05:24:00Z", None),
7836            loss("judge-1", "2026-09-24T01:00:00Z", None),
7837        ];
7838        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
7839    }
7840
7841    #[test]
7842    fn merge_overrides_are_parsed_or_refused() {
7843        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
7844        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
7845        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
7846        assert!(merge_mode("squash").is_err());
7847    }
7848
7849    #[test]
7850    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
7851        let now = Timestamp::now();
7852        let fallback = Duration::from_secs(300);
7853        let cap = Duration::from_secs(1800);
7854
7855        // No reset hint at all: the fallback.
7856        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
7857
7858        // A reset ten minutes out, well inside the cap: waited for exactly.
7859        let soon = now + jiff::SignedDuration::from_secs(600);
7860        assert_eq!(
7861            quota_wait(Some(soon), now, fallback, cap),
7862            Duration::from_secs(600)
7863        );
7864
7865        // A reset already in the past is not trusted: the fallback, not a
7866        // zero or negative wait that would spin the loop right back around.
7867        let past = now - jiff::SignedDuration::from_secs(60);
7868        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
7869
7870        // A reset further out than the cap is trusted for direction but not
7871        // for magnitude: a parsing slip must not sleep the loop for a day.
7872        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
7873        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
7874    }
7875
7876    #[test]
7877    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
7878        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7879
7880        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
7881        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
7882
7883        // Same clock reading, but it has already gone by today: read as
7884        // tomorrow's, since the CLI would not still be reporting a limit past
7885        // its own stated reset.
7886        let already_past =
7887            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
7888        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
7889
7890        assert!(
7891            parse_reset_hint("session limit reached", now, now).is_none(),
7892            "free text with no recognised shape is not guessed at"
7893        );
7894        assert!(
7895            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
7896            "an unresolvable zone name is not guessed at either"
7897        );
7898    }
7899
7900    #[test]
7901    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
7902        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
7903
7904        let at = parse_reset_hint(
7905            "You've hit your usage limit. Visit \
7906             https://chatgpt.com/codex/settings/usage to purchase more \
7907             credits or try again at Sep 19th, 2026 5:10 PM.",
7908            now,
7909            now,
7910        )
7911        .expect("the codex reset wording is a recognised shape");
7912        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
7913
7914        // The month is explicit, so a date already earlier in the same
7915        // sentence-implied year than `now` is trusted as written rather than
7916        // rolled forward a year the way the bracketed shape rolls a
7917        // same-day clock reading to tomorrow.
7918        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
7919            .expect("an explicit year needs no rollover");
7920        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
7921
7922        assert!(
7923            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
7924            "a two-digit year is not the documented shape and is not guessed at"
7925        );
7926        assert!(
7927            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
7928            "a four-letter month name is not the documented three-letter abbreviation"
7929        );
7930        assert!(
7931            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
7932            "an explicit zone on the dated shape is a format nobody has \
7933             documented, and is refused rather than guessed at as UTC"
7934        );
7935    }
7936
7937    #[test]
7938    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
7939        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
7940        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
7941
7942        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
7943        assert_eq!(at.as_second() - recorded.as_second(), 3769);
7944
7945        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
7946        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
7947
7948        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
7949            assert!(
7950                parse_reset_hint(bad, now, recorded).is_none(),
7951                "{bad:?} must not be guessed at"
7952            );
7953        }
7954    }
7955
7956    /// A loop whose queue lives in a temp tree and whose poll interval is far
7957    /// longer than the test's patience, so anything that waits out a poll
7958    /// instead of noticing the stop fails rather than merely being slow.
7959    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
7960        let config = dir.join("magi.toml");
7961        std::fs::write(
7962            &config,
7963            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
7964        )
7965        .unwrap();
7966        let opts = Opts {
7967            poll: Duration::from_secs(30),
7968            config: Some(config),
7969            // The explicit fixture config keeps startup cleanup from reading
7970            // machine configuration. This fictional repository likewise
7971            // keeps any best-effort git cleanup away from this checkout.
7972            repo: dir.join("repo"),
7973            ..Opts::default()
7974        };
7975        // The status file goes in a directory that does not exist yet, so its
7976        // creation is itself evidence the loop published one. `worktrees`
7977        // must be just as fictional: the janitor reclaims worktrees under it
7978        // for real, and a test that let it fall through to
7979        // `crate::run::default_worktree_root()` would have it reclaim
7980        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
7981        // which is exactly what happened before this function took the
7982        // parameter at all.
7983        let home = dir.join("home");
7984        let worktrees = dir.join("wt");
7985        (
7986            opts,
7987            Queue::at(dir.join("queue")),
7988            home.join("daemon.json"),
7989            home,
7990            worktrees,
7991        )
7992    }
7993
7994    #[test]
7995    fn a_stop_is_idempotent_and_once_set_stays_set() {
7996        let stop = Stop::new();
7997        assert!(!stop.stopped());
7998
7999        stop.stop();
8000        assert!(stop.stopped());
8001        stop.stop();
8002        assert!(stop.stopped(), "a second stop is not a toggle");
8003
8004        let shared = stop.clone();
8005        assert!(
8006            shared.stopped(),
8007            "a clone is the same stop; that is how the loop and its caller share one"
8008        );
8009    }
8010
8011    #[test]
8012    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
8013        let stop = Stop::new();
8014        stop.enter();
8015        assert!(
8016            !stop.finishing(),
8017            "a busy loop nobody has asked to stop is just running"
8018        );
8019
8020        stop.stop();
8021        assert!(
8022            stop.finishing(),
8023            "a stop asked for mid-run has not landed until the run is settled"
8024        );
8025
8026        stop.exit();
8027        assert!(
8028            !stop.finishing(),
8029            "once the run is settled the stop has landed and there is nothing to finish"
8030        );
8031    }
8032
8033    #[test]
8034    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
8035        let stop = Stop::new();
8036        stop.enter();
8037        stop.enter();
8038        stop.stop();
8039        assert!(stop.finishing(), "two runs still in flight");
8040
8041        stop.exit();
8042        assert!(
8043            stop.finishing(),
8044            "one run finished, but a sibling is still working"
8045        );
8046
8047        stop.exit();
8048        assert!(
8049            !stop.finishing(),
8050            "the last run out is what actually lands the stop"
8051        );
8052    }
8053
8054    #[tokio::test]
8055    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
8056        let dir = tempfile::tempdir().unwrap();
8057        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8058        let stop = Stop::new();
8059        stop.stop();
8060
8061        let began = std::time::Instant::now();
8062        tokio::time::timeout(
8063            Duration::from_secs(2),
8064            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8065        )
8066        .await
8067        .expect("a stopped loop must return, not sit out its poll interval")
8068        .expect("the loop's own setup and teardown must not fail");
8069        assert!(
8070            began.elapsed() < opts.poll,
8071            "returned only after {:?}, which is a poll interval, not a stop",
8072            began.elapsed()
8073        );
8074    }
8075
8076    #[tokio::test]
8077    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
8078        let dir = tempfile::tempdir().unwrap();
8079        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8080        let stop = Stop::new();
8081
8082        // Asked for after the loop is already parked on its empty queue, which
8083        // is the case an operator tapping stop on a phone actually hits.
8084        let asker = {
8085            let stop = stop.clone();
8086            tokio::spawn(async move {
8087                tokio::time::sleep(Duration::from_millis(20)).await;
8088                stop.stop();
8089            })
8090        };
8091
8092        let began = std::time::Instant::now();
8093        tokio::time::timeout(
8094            Duration::from_secs(2),
8095            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8096        )
8097        .await
8098        .expect("a stop asked for while idle must wake the wait")
8099        .expect("the loop's own setup and teardown must not fail");
8100        asker.await.unwrap();
8101        assert!(
8102            began.elapsed() < opts.poll,
8103            "returned only after {:?}, so the stop waited on the sleep",
8104            began.elapsed()
8105        );
8106    }
8107
8108    #[tokio::test]
8109    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
8110        let dir = tempfile::tempdir().unwrap();
8111        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8112        let stop = Stop::new();
8113        stop.stop();
8114
8115        tokio::time::timeout(
8116            Duration::from_secs(2),
8117            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8118        )
8119        .await
8120        .expect("a stopped loop must return")
8121        .expect("the loop's own setup and teardown must not fail");
8122
8123        assert!(
8124            home.is_dir(),
8125            "the loop did publish a status file, so its removal is the teardown and not an absence"
8126        );
8127        assert!(
8128            !status_file.exists(),
8129            "a stopped loop clears its status file"
8130        );
8131        assert!(
8132            read_status(&home).is_none(),
8133            "a reader must see no daemon at all, not a heartbeat that merely stopped"
8134        );
8135    }
8136
8137    #[tokio::test]
8138    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
8139        let dir = tempfile::tempdir().unwrap();
8140        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8141        opts.once = true;
8142
8143        let mut settled = RunState::new(
8144            dir.path().join("repo"),
8145            "main".to_owned(),
8146            "abc1234".to_owned(),
8147            "fixture".to_owned(),
8148            Config::default(),
8149        );
8150        settled.status = RunStatus::Ready;
8151        let run_dir = home.join("runs").join(&settled.id);
8152        std::fs::create_dir_all(&run_dir).unwrap();
8153        std::fs::write(
8154            run_dir.join("run.json"),
8155            serde_json::to_string_pretty(&settled).unwrap(),
8156        )
8157        .unwrap();
8158        let questions = Questions::at(home.join("questions"));
8159        let mut question = ask::Question::new(
8160            settled.id.clone(),
8161            "review".to_owned(),
8162            "reviewer-1".to_owned(),
8163            "Continue?".to_owned(),
8164            String::new(),
8165            Vec::new(),
8166        );
8167        questions.put(&mut question).unwrap();
8168
8169        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
8170            .await
8171            .unwrap();
8172
8173        assert_eq!(
8174            questions.get(&question.id).unwrap().status,
8175            ask::QuestionStatus::Abandoned,
8176            "an empty --once drain still performs startup question cleanup"
8177        );
8178    }
8179
8180    #[test]
8181    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
8182        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8183
8184        assert!(
8185            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
8186            "never checked before: due at once"
8187        );
8188
8189        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
8190        assert!(
8191            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
8192            "well inside the interval: not due yet"
8193        );
8194
8195        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
8196        assert!(
8197            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
8198            "exactly at the edge: not yet due, same convention as `clean::due`"
8199        );
8200
8201        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8202        assert!(
8203            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
8204            "past the interval: due again"
8205        );
8206    }
8207
8208    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
8209    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
8210    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
8211    /// and the congestion test below both need, and must not drift apart.
8212    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
8213        let config = dir.join("magi.toml");
8214        // A literal (single-quoted) TOML string, not a basic one: the cache
8215        // path is a Windows path full of backslashes, and a basic string
8216        // would have TOML try to interpret `\U` (from `\Users\...`) as a
8217        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
8218        // `{{ vars.cache }}` rendering documents.
8219        std::fs::write(
8220            &config,
8221            format!(
8222                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
8223                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
8224                cache_dir.display()
8225            ),
8226        )
8227        .unwrap();
8228        Opts {
8229            config: Some(config),
8230            repo: dir.join("repo"),
8231            ..Opts::default()
8232        }
8233    }
8234
8235    #[tokio::test]
8236    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
8237        let dir = tempfile::tempdir().unwrap();
8238        let home = dir.path().join("home");
8239        let cache_dir = dir.path().join("cache");
8240        std::fs::create_dir_all(&cache_dir).unwrap();
8241        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8242        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8243
8244        // Nobody has asked this daemon to stop, which is the ordinary case;
8245        // the skip that a stop buys is asserted by its own test below.
8246        let running = Stop::new();
8247        let mut last_checked = None;
8248        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8249        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
8250            .await;
8251        assert_eq!(
8252            crate::disk::dir_size(&cache_dir),
8253            0,
8254            "over the cap on the first check ever: pruned at once, no idle queue required"
8255        );
8256        assert_eq!(last_checked, Some(t0));
8257
8258        // A fresh oversized file lands, but the next check is not due yet.
8259        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
8260        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
8261        maybe_prune_cache_between_runs(
8262            &opts.repo,
8263            &opts,
8264            &home,
8265            &running,
8266            &mut last_checked,
8267            too_soon,
8268        )
8269        .await;
8270        assert_eq!(
8271            crate::disk::dir_size(&cache_dir),
8272            10,
8273            "too soon since the last check: left alone rather than rescanned every call"
8274        );
8275        assert_eq!(
8276            last_checked,
8277            Some(t0),
8278            "an idle check does not reset the clock"
8279        );
8280
8281        // Once the interval elapses, the same oversized cache is caught again.
8282        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8283        maybe_prune_cache_between_runs(
8284            &opts.repo,
8285            &opts,
8286            &home,
8287            &running,
8288            &mut last_checked,
8289            due_again,
8290        )
8291        .await;
8292        assert_eq!(
8293            crate::disk::dir_size(&cache_dir),
8294            0,
8295            "due again: pruned back under the cap"
8296        );
8297    }
8298
8299    /// A stop must not queue behind housekeeping. The prune below is a
8300    /// synchronous walk of the whole cache with no await point in it, so a
8301    /// loop that entered it could not get back to its own `stopped()` test
8302    /// until the walk finished - and because no run is in flight at this
8303    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
8304    /// the stop had already landed. The idle branch has always made this same
8305    /// check before reaching `janitor`; the between-runs path makes it too.
8306    #[tokio::test]
8307    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
8308        let dir = tempfile::tempdir().unwrap();
8309        let home = dir.path().join("home");
8310        let cache_dir = dir.path().join("cache");
8311        std::fs::create_dir_all(&cache_dir).unwrap();
8312        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
8313        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
8314
8315        let stop = Stop::new();
8316        stop.stop();
8317        assert!(
8318            !stop.finishing(),
8319            "no run is in flight at a between-runs boundary, so nothing else \
8320             would tell the operator this stop had not taken effect yet"
8321        );
8322
8323        let mut last_checked = None;
8324        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8325        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
8326            .await;
8327        assert_eq!(
8328            crate::disk::dir_size(&cache_dir),
8329            10,
8330            "over its cap, and due for the first check ever, but a stop outranks \
8331             it: the cap is a standing policy the next start measures again"
8332        );
8333        assert_eq!(
8334            last_checked, None,
8335            "a check that never happened must not claim the interval"
8336        );
8337    }
8338
8339    /// The regression this whole change exists for: gate timeouts on runs
8340    /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
8341    /// GiB against a 10 GiB cap, because the operator's queue never had a
8342    /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
8343    /// `janitor` pass.
8344    ///
8345    /// Reproduced with a backlog whose repository is never created:
8346    /// `Runner::start` fails at `git::toplevel`, spawning no agent CLI.
8347    /// Each task is held after one startup failure, but the remaining tasks
8348    /// keep the queue busy until an external stop ends the loop.
8349    #[tokio::test]
8350    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
8351        let dir = tempfile::tempdir().unwrap();
8352        let cache_dir = dir.path().join("cache");
8353        std::fs::create_dir_all(&cache_dir).unwrap();
8354        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
8355
8356        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
8357        opts.poll = Duration::from_millis(20);
8358        opts.max_attempts = 1_000;
8359
8360        let queue = Queue::at(dir.path().join("queue"));
8361        for i in 0..128 {
8362            let mut task = Task::new(
8363                format!("queued work {i}"),
8364                format!("queued work {i}"),
8365                opts.repo.clone(),
8366                Source::Human,
8367            );
8368            queue.put(&mut task).unwrap();
8369        }
8370
8371        let home = dir.path().join("home");
8372        let worktrees = dir.path().join("wt");
8373        let status_file = home.join("daemon.json");
8374        let stop = Stop::new();
8375        let stopper = {
8376            let stop = stop.clone();
8377            let queue = Queue::at(dir.path().join("queue"));
8378            tokio::spawn(async move {
8379                // Observe completed work rather than rely on a wall-clock
8380                // delay. Every startup failure holds only its own task; the
8381                // backlog keeps offering work at the next boundary.
8382                for _ in 0..2_000 {
8383                    if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
8384                        break;
8385                    }
8386                    tokio::time::sleep(Duration::from_millis(5)).await;
8387                }
8388                stop.stop();
8389            })
8390        };
8391
8392        tokio::time::timeout(
8393            Duration::from_secs(20),
8394            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8395        )
8396        .await
8397        .expect("the loop must not hang on a queue that keeps producing failing work")
8398        .expect("the loop's own setup and teardown must not fail");
8399        stopper.await.unwrap();
8400
8401        let after = queue.list();
8402        let completed = after.iter().filter(|t| t.attempts == 1).count();
8403        assert!(
8404            completed >= 2,
8405            "the harness must have processed multiple tasks to exercise a busy queue \
8406             (got {completed} completed task(s))"
8407        );
8408        assert!(
8409            after.iter().any(|t| t.status.runnable()),
8410            "unprocessed tasks must remain: the external stop, rather than an \
8411             exhausted backlog, must end the test"
8412        );
8413        assert!(
8414            after
8415                .iter()
8416                .filter(|t| t.attempts > 0)
8417                .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
8418            "a busy backlog must not retry a task's unchanged startup failure"
8419        );
8420
8421        assert_eq!(
8422            crate::disk::dir_size(&cache_dir),
8423            0,
8424            "an oversized cache must not be left to grow unboundedly just because the \
8425             queue kept the loop busy the whole time"
8426        );
8427    }
8428
8429    #[test]
8430    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
8431        let dir = tempfile::tempdir().unwrap();
8432        let queue = Queue::at(dir.path().join("queue"));
8433        let questions = Questions::at(dir.path().join("questions"));
8434        let mut task = task();
8435        queue.put(&mut task).unwrap();
8436
8437        let mut task_question = ask::Question::new(
8438            task.id.clone(),
8439            crate::conduct::NODE.to_owned(),
8440            "conduct".to_owned(),
8441            "Which backend?".to_owned(),
8442            String::new(),
8443            Vec::new(),
8444        );
8445        questions.put(&mut task_question).unwrap();
8446        task.block(vec![task_question.id.clone()], None);
8447        queue.put(&mut task).unwrap();
8448
8449        let mut run_question = ask::Question::new(
8450            "20260101-000000-run1".to_owned(),
8451            "review".to_owned(),
8452            "reviewer-1".to_owned(),
8453            "Run question".to_owned(),
8454            String::new(),
8455            Vec::new(),
8456        );
8457        questions.put(&mut run_question).unwrap();
8458
8459        // A question from another node whose `run` happens to equal this
8460        // task's id — the same field, filled in for an unrelated reason. Only
8461        // `crate::conduct::NODE` questions use `run` as a task id; this one
8462        // must never be touched by this reconciliation, even after release.
8463        let mut coincidental = ask::Question::new(
8464            task.id.clone(),
8465            "review".to_owned(),
8466            "reviewer-1".to_owned(),
8467            "Unrelated review question".to_owned(),
8468            String::new(),
8469            Vec::new(),
8470        );
8471        questions.put(&mut coincidental).unwrap();
8472
8473        reconcile_task_questions(&queue, &questions);
8474        assert!(questions.get(&task_question.id).unwrap().status.open());
8475        assert!(questions.get(&run_question.id).unwrap().status.open());
8476        assert!(questions.get(&coincidental.id).unwrap().status.open());
8477
8478        task.release();
8479        queue.put(&mut task).unwrap();
8480        reconcile_task_questions(&queue, &questions);
8481        assert_eq!(
8482            questions.get(&task_question.id).unwrap().status,
8483            ask::QuestionStatus::Abandoned
8484        );
8485        assert!(
8486            questions.get(&run_question.id).unwrap().status.open(),
8487            "run questions remain the run janitor's responsibility"
8488        );
8489        assert!(
8490            questions.get(&coincidental.id).unwrap().status.open(),
8491            "a non-conductor question must not be abandoned just because its \
8492             run id coincides with a task id"
8493        );
8494    }
8495
8496    #[test]
8497    fn a_freshly_started_running_task_is_never_stalled() {
8498        let dir = tempfile::tempdir().unwrap();
8499        let mut t = task();
8500        t.start("run-1".to_owned());
8501        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
8502        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
8503        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
8504    }
8505
8506    #[test]
8507    fn a_long_running_task_with_no_live_daemon_is_stalled() {
8508        let dir = tempfile::tempdir().unwrap();
8509        let mut t = task();
8510        t.start("run-1".to_owned());
8511        t.updated_at = Timestamp::now()
8512            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8513        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
8514        assert_eq!(
8515            stalled_tasks(
8516                &Queue::at(dir.path().join("q")),
8517                dir.path(),
8518                Timestamp::now()
8519            )
8520            .len(),
8521            0,
8522            "the task was never written to this queue"
8523        );
8524    }
8525
8526    #[test]
8527    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
8528        let dir = tempfile::tempdir().unwrap();
8529        let mut t = task();
8530        t.id = "20260903-080340-0167".to_owned();
8531        t.start("20260903-080619-01c2".to_owned());
8532        t.updated_at = Timestamp::now()
8533            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
8534
8535        let mut status = Status::new();
8536        status.current = vec![Current {
8537            task: t.id.clone(),
8538            run: "20260903-080619-01c2".to_owned(),
8539        }];
8540        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8541
8542        assert!(
8543            !is_stalled(&t, dir.path(), Timestamp::now()),
8544            "a live daemon's own heartbeat rules out stalled, however long the task has run"
8545        );
8546    }
8547
8548    /// Rewrite a task's `updated_at` on disk directly, bypassing
8549    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
8550    /// a fixture look like it has genuinely been `running` for a while.
8551    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
8552        let path = queue.path_of(id);
8553        let body = std::fs::read_to_string(&path).unwrap();
8554        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
8555        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
8556        v["updated_at"] = serde_json::Value::String(old.to_string());
8557        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
8558    }
8559
8560    #[test]
8561    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
8562        // The realistic `poll()` ordering, not `is_stalled` in isolation:
8563        // `reclaim_orphaned_running` runs first, on every poll, and settles
8564        // any `running` task whose claim it can actually take. For most
8565        // crashes that is immediate - a dead pid is proof enough for
8566        // `sweep_stale_claims` to drop the lock the same tick, and the very
8567        // next claim attempt succeeds. But a lock whose pid cannot be parsed
8568        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
8569        // `sweep_stale_claims`'s own doc), so the lock - and the claim
8570        // failure behind it - can legitimately outlive many polls. This is
8571        // exactly the gap `stalled_tasks` exists to surface well before that
8572        // six-hour sweep would: reclaim leaves the task `running`, and it
8573        // must still reach the conductor as stalled.
8574        let dir = tempfile::tempdir().unwrap();
8575        let queue = Queue::at(dir.path().join("queue"));
8576        let home = dir.path().join("home");
8577
8578        let mut t = task();
8579        t.id = "20260101-000001-lock".to_owned();
8580        t.start("run-1".to_owned());
8581        queue.put(&mut t).unwrap();
8582        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8583        std::fs::write(
8584            dir.path().join("queue").join(format!("{}.lock", t.id)),
8585            "not a pid",
8586        )
8587        .unwrap();
8588
8589        let now = Timestamp::now();
8590        assert!(
8591            reclaim_orphaned_running(&queue, 2).is_empty(),
8592            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
8593             and reclaim must leave the task alone"
8594        );
8595        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8596
8597        let stalled = stalled_tasks(&queue, &home, now);
8598        assert_eq!(
8599            stalled.len(),
8600            1,
8601            "reclaim's inability to claim it yet must not hide it from the conductor"
8602        );
8603        assert_eq!(stalled[0].id, t.id);
8604    }
8605
8606    #[test]
8607    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
8608        let dir = tempfile::tempdir().unwrap();
8609        crate::run::set_home(dir.path().join("run-home"));
8610        let queue = Queue::at(dir.path().join("queue"));
8611        let home = dir.path().join("home");
8612        let questions = Questions::at(dir.path().join("questions"));
8613
8614        let mut t = task();
8615        t.id = "20260101-000003-dead".to_owned();
8616        t.start("missing-run".to_owned());
8617        queue.put(&mut t).unwrap();
8618        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
8619
8620        // This is the real poll ordering: retain the deterministic stalled
8621        // input before a claim proves the owner is gone and reclaims it.
8622        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
8623        assert_eq!(
8624            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
8625            [&t.id]
8626        );
8627        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
8628        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
8629
8630        // Reclaim drops its guard before conductor decisions are applied, so
8631        // the decision for the captured stalled input has a real write path.
8632        crate::conduct::apply(
8633            &queue,
8634            &questions,
8635            &crate::conduct::Verdict {
8636                decisions: vec![crate::conduct::Decision {
8637                    id: t.id.clone(),
8638                    recovery: Some(crate::conduct::Recovery::Requeue),
8639                    ..crate::conduct::Decision::default()
8640                }],
8641            },
8642        )
8643        .unwrap();
8644        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
8645    }
8646
8647    #[test]
8648    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
8649        let dir = tempfile::tempdir().unwrap();
8650        let queue = Queue::at(dir.path().join("queue"));
8651        let home = dir.path().join("home");
8652
8653        let mut fresh = task();
8654        fresh.id = "20260101-000001-aaaa".to_owned();
8655        fresh.start("run-1".to_owned());
8656        queue.put(&mut fresh).unwrap();
8657
8658        let mut old = task();
8659        old.id = "20260101-000002-bbbb".to_owned();
8660        old.start("run-2".to_owned());
8661        queue.put(&mut old).unwrap();
8662        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
8663
8664        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
8665        assert_eq!(stalled.len(), 1);
8666        assert_eq!(stalled[0].id, old.id);
8667    }
8668
8669    #[test]
8670    fn queued_and_finished_task_views_partition_by_status() {
8671        let dir = tempfile::tempdir().unwrap();
8672        let queue = Queue::at(dir.path().join("queue"));
8673
8674        let mut queued = task();
8675        queued.id = "20260101-000001-aaaa".to_owned();
8676        queue.put(&mut queued).unwrap();
8677
8678        let mut failed = task();
8679        failed.id = "20260101-000002-bbbb".to_owned();
8680        failed.start("run-1".to_owned());
8681        failed.fail("gate red", 5);
8682        queue.put(&mut failed).unwrap();
8683
8684        let mut held = task();
8685        held.id = "20260101-000003-cccc".to_owned();
8686        held.hold_machine(None);
8687        queue.put(&mut held).unwrap();
8688
8689        let mut running = task();
8690        running.id = "20260101-000004-dddd".to_owned();
8691        running.start("run-2".to_owned());
8692        queue.put(&mut running).unwrap();
8693
8694        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
8695        assert_eq!(queued_ids, [queued.id.clone()]);
8696
8697        let mut finished_ids: Vec<String> =
8698            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
8699        finished_ids.sort_unstable();
8700        let mut want = vec![failed.id.clone(), held.id.clone()];
8701        want.sort_unstable();
8702        assert_eq!(finished_ids, want);
8703    }
8704
8705    #[test]
8706    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
8707        for short in [false, true] {
8708            let dir = tempfile::tempdir().unwrap();
8709            let queue = Queue::at(dir.path().join("queue"));
8710            let questions = ask::Questions::at(dir.path().join("questions"));
8711            let mut running = task();
8712            running.id = "20261013-192213-feb2".into();
8713            running.start("existing-run".into());
8714            queue.put(&mut running).unwrap();
8715            let mut middle = task();
8716            middle.id = "20261013-193611-ca5b".into();
8717            middle.block(
8718                vec![if short {
8719                    "feb2".into()
8720                } else {
8721                    running.id.clone()
8722                }],
8723                None,
8724            );
8725            queue.put(&mut middle).unwrap();
8726            let mut waiting = task();
8727            waiting.id = "20261013-202849-ee37".into();
8728            waiting.block(
8729                vec![if short {
8730                    "ca5b".into()
8731                } else {
8732                    middle.id.clone()
8733                }],
8734                Some("wait for implementation".into()),
8735            );
8736            queue.put(&mut waiting).unwrap();
8737            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
8738            let inv = crate::blockers::Inventory::load(&queue, &questions);
8739            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
8740            assert!(inv.stuck().is_empty());
8741            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
8742            assert!(report.quarantined.is_empty());
8743            assert!(report.asked.is_empty());
8744            resolve_blockers(&queue, &questions);
8745            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
8746            assert!(questions.list().is_empty());
8747            // Finishing the transitive prerequisite alone does not satisfy
8748            // the task's direct dependency.
8749            running.succeed();
8750            queue.put(&mut running).unwrap();
8751            resolve_blockers(&queue, &questions);
8752            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
8753            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
8754            middle = queue.get(&middle.id).unwrap();
8755            middle.succeed();
8756            queue.put(&mut middle).unwrap();
8757            resolve_blockers(&queue, &questions);
8758            let after = queue.get(&waiting.id).unwrap();
8759            assert_eq!(after.status, TaskStatus::Queued);
8760            assert!(after.blocked_by.is_empty());
8761            assert_eq!(after.instruction, waiting.instruction);
8762        }
8763    }
8764
8765    #[test]
8766    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
8767        for future_schema in [false, true] {
8768            let name = "20261013-193611-ca5b";
8769            let mut future = task();
8770            future.id = name.into();
8771            future.schema = crate::queue::SCHEMA + 1;
8772            let contents = if future_schema {
8773                serde_json::to_string(&future).unwrap()
8774            } else {
8775                "corrupt".into()
8776            };
8777            let dir = tempfile::tempdir().unwrap();
8778            let queue = Queue::at(dir.path().join("queue"));
8779            let questions = ask::Questions::at(dir.path().join("questions"));
8780            let mut waiting = task();
8781            waiting.id = "20261013-202849-ee37".into();
8782            waiting.block(vec!["ca5b".into()], None);
8783            queue.put(&mut waiting).unwrap();
8784            std::fs::write(queue.path_of(name), contents).unwrap();
8785            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
8786            assert!(
8787                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
8788            );
8789            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
8790            assert!(report.asked.is_empty());
8791            resolve_blockers(&queue, &questions);
8792            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
8793            assert!(questions.list().is_empty());
8794        }
8795        let dir = tempfile::tempdir().unwrap();
8796        let queue = Queue::at(dir.path().join("queue"));
8797        let questions = ask::Questions::at(dir.path().join("questions"));
8798        let mut waiting = task();
8799        waiting.id = "20261013-202849-ee37".into();
8800        waiting.block(vec!["ca5b".into()], None);
8801        queue.put(&mut waiting).unwrap();
8802        let mut done = task();
8803        done.id = "20261013-193611-ca5b".into();
8804        done.succeed();
8805        queue.put(&mut done).unwrap();
8806        // An unreadable second match must not disappear from uniqueness
8807        // checks just because Queue::list skips it.
8808        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
8809        assert!(queue.get("ca5b").is_err());
8810        assert_eq!(
8811            crate::queue::dependency(&queue, &questions, "ca5b"),
8812            crate::queue::Dependency::Ambiguous
8813        );
8814        resolve_blockers(&queue, &questions);
8815        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
8816        assert!(report.asked.is_empty());
8817        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
8818        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
8819    }
8820
8821    #[test]
8822    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
8823        for held in [false, true] {
8824            for question in [false, true] {
8825                for reference in ["ca5b", "20261013-193611-ca5b"] {
8826                    let dir = tempfile::tempdir().unwrap();
8827                    let queue = Queue::at(dir.path().join("queue"));
8828                    let questions = ask::Questions::at(dir.path().join("questions"));
8829                    let mut prerequisite = task();
8830                    prerequisite.id = "20261013-193611-ca5b".into();
8831                    prerequisite.start("existing-run".into());
8832                    queue.put(&mut prerequisite).unwrap();
8833                    let mut waiting = task();
8834                    waiting.id = "20261013-202849-ee37".into();
8835                    if held {
8836                        waiting.hold_machine(Some("waiting for separate consent".into()));
8837                    }
8838                    queue.put(&mut waiting).unwrap();
8839                    let reason = "Deleting saved data requires separate owner consent";
8840                    crate::conduct::apply(
8841                        &queue,
8842                        &questions,
8843                        &crate::conduct::Verdict {
8844                            decisions: vec![crate::conduct::Decision {
8845                                id: waiting.id.clone(),
8846                                blocked_by: vec![reference.into()],
8847                                question: question.then(|| "May the saved data be deleted?".into()),
8848                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
8849                                reason: Some(reason.into()),
8850                                ..crate::conduct::Decision::default()
8851                            }],
8852                        },
8853                    )
8854                    .unwrap();
8855                    let before = queue.get(&waiting.id).unwrap();
8856                    if question {
8857                        assert_eq!(before.status, TaskStatus::Blocked);
8858                        let q = questions.get(&before.blocked_by[0]).unwrap();
8859                        assert_eq!(q.summary, "May the saved data be deleted?");
8860                        assert!(q.status.open());
8861                    } else {
8862                        assert_eq!(before.status, TaskStatus::Held);
8863                        let recorded_reason = before.hold_reason.as_deref().unwrap();
8864                        assert!(recorded_reason.starts_with(reason));
8865                        if held {
8866                            assert!(recorded_reason.contains("waiting for separate consent"));
8867                        }
8868                    }
8869                    prerequisite.succeed();
8870                    queue.put(&mut prerequisite).unwrap();
8871                    resolve_blockers(&queue, &questions);
8872                    let after = queue.get(&waiting.id).unwrap();
8873                    assert_eq!(after.status, before.status);
8874                    assert_eq!(after.blocked_by, before.blocked_by);
8875                    assert_eq!(after.hold_reason, before.hold_reason);
8876                    assert_eq!(after.instruction, waiting.instruction);
8877                    if question {
8878                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
8879                    }
8880                    assert!(
8881                        queue.next_runnable().is_none(),
8882                        "dependency completion is not consent"
8883                    );
8884                }
8885            }
8886        }
8887    }
8888
8889    #[test]
8890    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
8891        let dir = tempfile::tempdir().unwrap();
8892        let queue = Queue::at(dir.path().join("queue"));
8893        let questions = ask::Questions::at(dir.path().join("questions"));
8894
8895        let mut dep = task();
8896        dep.id = "20260101-000001-dep0".to_owned();
8897        dep.succeed();
8898        queue.put(&mut dep).unwrap();
8899
8900        let mut still_going = task();
8901        still_going.id = "20260101-000002-dep1".to_owned();
8902        queue.put(&mut still_going).unwrap();
8903
8904        let mut blocked = task();
8905        blocked.id = "20260101-000003-main".to_owned();
8906        blocked.block(
8907            vec![dep.id.clone(), still_going.id.clone()],
8908            Some("waits on both".to_owned()),
8909        );
8910        queue.put(&mut blocked).unwrap();
8911
8912        resolve_blockers(&queue, &questions);
8913
8914        let after = queue.get(&blocked.id).unwrap();
8915        assert_eq!(
8916            after.status,
8917            TaskStatus::Blocked,
8918            "one dependency is still outstanding"
8919        );
8920        assert_eq!(after.blocked_by, [still_going.id.clone()]);
8921    }
8922
8923    #[test]
8924    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
8925        let dir = tempfile::tempdir().unwrap();
8926        let queue = Queue::at(dir.path().join("queue"));
8927        let questions = ask::Questions::at(dir.path().join("questions"));
8928
8929        let mut q = crate::ask::Question::new(
8930            "20260101-000001-main".to_owned(),
8931            crate::conduct::NODE.to_owned(),
8932            "conduct".to_owned(),
8933            "Which backend?".to_owned(),
8934            String::new(),
8935            Vec::new(),
8936        );
8937        questions.put(&mut q).unwrap();
8938        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
8939            .unwrap();
8940        questions.put(&mut q).unwrap();
8941
8942        let mut blocked = task();
8943        blocked.id = "20260101-000001-main".to_owned();
8944        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
8945        queue.put(&mut blocked).unwrap();
8946
8947        resolve_blockers(&queue, &questions);
8948
8949        let after = queue.get(&blocked.id).unwrap();
8950        assert_eq!(
8951            after.status,
8952            TaskStatus::Queued,
8953            "the only blocker resolved"
8954        );
8955        assert_eq!(after.answers.len(), 1);
8956        assert_eq!(after.answers[0].question, "Which backend?");
8957        assert_eq!(after.answers[0].answer, "SQLite");
8958
8959        // And the run this task starts next is told about it.
8960        let instruction = instruction_for(&after);
8961        assert!(instruction.contains("Which backend?"));
8962        assert!(instruction.contains("SQLite"));
8963    }
8964
8965    #[test]
8966    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
8967        let dir = tempfile::tempdir().unwrap();
8968        let queue = Queue::at(dir.path().join("queue"));
8969        let questions = ask::Questions::at(dir.path().join("questions"));
8970
8971        let mut q = crate::ask::Question::new(
8972            "20260101-000001-main".to_owned(),
8973            crate::conduct::NODE.to_owned(),
8974            "conduct".to_owned(),
8975            "Is the setup done?".to_owned(),
8976            String::new(),
8977            Vec::new(),
8978        );
8979        q.abandon("no answer within 60s of asking");
8980        questions.put(&mut q).unwrap();
8981
8982        let mut blocked = task();
8983        blocked.id = "20260101-000001-main".to_owned();
8984        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
8985        queue.put(&mut blocked).unwrap();
8986
8987        resolve_blockers(&queue, &questions);
8988
8989        let after = queue.get(&blocked.id).unwrap();
8990        assert_eq!(
8991            after.status,
8992            TaskStatus::Held,
8993            "never left blocked on nothing"
8994        );
8995        assert!(!after.operator_held(), "a machine hold, for triage");
8996        assert!(
8997            after
8998                .hold_reason
8999                .as_deref()
9000                .unwrap_or_default()
9001                .contains("went unanswered")
9002        );
9003    }
9004
9005    #[test]
9006    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
9007        // Reproduces the reported bug (task 3958): a task held out of
9008        // attempts, blocked on a `crate::conduct` follow-up question, must
9009        // come back `held` once that question is answered - never `queued`,
9010        // whatever the answer said - or it silently re-enters the
9011        // competition queue with its attempts already exhausted.
9012        let dir = tempfile::tempdir().unwrap();
9013        let queue = Queue::at(dir.path().join("queue"));
9014        let questions = ask::Questions::at(dir.path().join("questions"));
9015
9016        let mut q = crate::ask::Question::new(
9017            "20260101-000001-main".to_owned(),
9018            crate::conduct::NODE.to_owned(),
9019            "conduct".to_owned(),
9020            "How should this be handled?".to_owned(),
9021            String::new(),
9022            Vec::new(),
9023        );
9024        questions.put(&mut q).unwrap();
9025        q.answer(crate::ask::Answer::Text(
9026            "leave it held, a human will look at it later".to_owned(),
9027        ))
9028        .unwrap();
9029        questions.put(&mut q).unwrap();
9030
9031        let mut held = task();
9032        held.id = "20260101-000001-main".to_owned();
9033        held.hold_machine(Some("out of attempts".to_owned()));
9034        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
9035        queue.put(&mut held).unwrap();
9036
9037        resolve_blockers(&queue, &questions);
9038
9039        let after = queue.get(&held.id).unwrap();
9040        assert_eq!(after.status, TaskStatus::Held);
9041        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
9042        assert_eq!(
9043            after.answers[0].answer,
9044            "leave it held, a human will look at it later"
9045        );
9046    }
9047
9048    #[test]
9049    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
9050        let dir = tempfile::tempdir().unwrap();
9051        let queue = Queue::at(dir.path().join("queue"));
9052        let questions = ask::Questions::at(dir.path().join("questions"));
9053        let mut dep = task();
9054        dep.id = "20260101-000001-gone".to_owned();
9055        queue.put(&mut dep).unwrap();
9056        let mut blocked = task();
9057        blocked.id = "20260101-000003-main".to_owned();
9058        blocked.block(vec![dep.id.clone()], None);
9059        queue.put(&mut blocked).unwrap();
9060
9061        // Claimed, so `remove` cannot rewrite it and the resolver must.
9062        let claim = queue.claim(&blocked.id).unwrap();
9063        queue.remove(&dep.id, false, &questions).unwrap();
9064        drop(claim);
9065        resolve_blockers(&queue, &questions);
9066
9067        let after = queue.get(&blocked.id).unwrap();
9068        assert_eq!(after.status, TaskStatus::Queued);
9069        assert!(after.blocked_by.is_empty());
9070    }
9071
9072    #[test]
9073    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
9074        // Reproduces the reported bug: a task blocked on a task id that was
9075        // removed (`magi task rm`, or deleted by hand) can never see that id
9076        // reach `Done`, so the ordinary per-id loop has nothing to notice and
9077        // would otherwise leave the task `blocked` forever with no way for an
9078        // operator to find out why.
9079        let dir = tempfile::tempdir().unwrap();
9080        let queue = Queue::at(dir.path().join("queue"));
9081        let questions = ask::Questions::at(dir.path().join("questions"));
9082
9083        let mut still_going = task();
9084        still_going.id = "20260101-000002-dep1".to_owned();
9085        queue.put(&mut still_going).unwrap();
9086
9087        let mut blocked = task();
9088        blocked.id = "20260101-000003-main".to_owned();
9089        blocked.block(
9090            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
9091            Some("waits on both".to_owned()),
9092        );
9093        queue.put(&mut blocked).unwrap();
9094
9095        resolve_blockers(&queue, &questions);
9096
9097        let after = queue.get(&blocked.id).unwrap();
9098        assert_eq!(
9099            after.status,
9100            TaskStatus::Held,
9101            "a missing dependency must not leave the task blocked forever"
9102        );
9103        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
9104        assert!(after.blocked_by.is_empty());
9105        let reason = after.hold_reason.as_deref().unwrap_or_default();
9106        assert!(
9107            reason.contains("20260101-000001-gone"),
9108            "the missing id must be named so an operator can tell what happened: {reason}"
9109        );
9110        assert!(
9111            reason.contains(&still_going.id),
9112            "the still-valid dependency must not silently vanish from the record: {reason}"
9113        );
9114    }
9115
9116    #[test]
9117    fn instruction_for_is_unchanged_without_any_answers() {
9118        let t = task();
9119        assert_eq!(instruction_for(&t), t.instruction);
9120    }
9121
9122    #[test]
9123    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
9124        let dir = tempfile::tempdir().unwrap();
9125        let q = Queue::at(dir.path().join("queue"));
9126        let src = dir.path().join("shot.png");
9127        std::fs::write(&src, "x").unwrap();
9128        let mut t = task();
9129        q.attach(&mut t, &[src]).unwrap();
9130        let paths = task_attachments(&q, &t).unwrap();
9131        assert_eq!(paths.len(), 1);
9132        assert!(paths[0].is_absolute() && paths[0].is_file());
9133        std::fs::remove_file(&paths[0]).unwrap();
9134        let err = task_attachments(&q, &t).unwrap_err().to_string();
9135        assert!(err.contains("shot.png"), "{err}");
9136    }
9137
9138    #[tokio::test]
9139    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
9140        let dir = tempfile::tempdir().unwrap();
9141        let queue_path = dir.path().join("queue");
9142        let queue = Queue::at(queue_path.clone());
9143        let mut t = task();
9144        t.source = Source::Agent {
9145            run: "originating-chat".into(),
9146            node: crate::queue::CHAT_NODE.into(),
9147        };
9148        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
9149            stage: "config-fetch",
9150            target: "origin/main".into(),
9151        });
9152        record_config_failure(&mut t, &fetch);
9153        t.hold_machine(Some(format!("{fetch:#}")));
9154        let fetch_key = t.chat_notice_due().unwrap();
9155        t.chat_notices.push(fetch_key.clone());
9156        queue.put(&mut t).unwrap();
9157
9158        let queue = Queue::at(queue_path);
9159        let mut t = queue.get(&t.id).unwrap();
9160        let a = dir.path().join("a.toml");
9161        let b = dir.path().join("b.toml");
9162        for (path, text, new_cause) in [
9163            (&a, "[graph", true),
9164            (&a, "[verify", false),
9165            (&a, "[graph]\nimplementers = 'invalid-type'", true),
9166            (&b, "[graph]\nimplementers = 'invalid-type'", true),
9167        ] {
9168            t.release_operator("test", None);
9169            std::fs::write(path, text).unwrap();
9170            let error = Config::discover_fetched(dir.path(), Some(path))
9171                .await
9172                .unwrap_err();
9173            record_config_failure(&mut t, &error);
9174            t.hold_machine(Some(format!("{error:#}")));
9175            let due = t.chat_notice_due();
9176            assert_eq!(due.is_some(), new_cause, "{error:#}");
9177            if let Some(key) = due {
9178                assert_ne!(key, fetch_key);
9179                t.chat_notices.push(key);
9180            }
9181        }
9182        t.succeed();
9183        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
9184    }
9185
9186    #[test]
9187    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
9188        let dir = tempfile::tempdir().unwrap();
9189        let queue_path = dir.path().join("queue");
9190        let queue = Queue::at(queue_path.clone());
9191        let mut t = task();
9192        t.source = crate::queue::Source::Agent {
9193            run: "originating-chat".into(),
9194            node: crate::queue::CHAT_NODE.into(),
9195        };
9196        let a = dir.path().join("a.png");
9197        let b = dir.path().join("b.png");
9198        std::fs::write(&a, "a").unwrap();
9199        std::fs::write(&b, "b").unwrap();
9200        queue.attach(&mut t, &[a, b]).unwrap();
9201        let paths = task_attachments(&queue, &t).unwrap();
9202        for path in &paths {
9203            std::fs::remove_file(path).unwrap();
9204        }
9205        let missing = task_attachments(&queue, &t).unwrap_err();
9206        t.attempts += 1;
9207        let reason = missing.to_string();
9208        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9209        let first = t.chat_notice_due().expect("first attachment notice");
9210        t.chat_notices.push(first.clone());
9211        queue.put(&mut t).unwrap();
9212
9213        let queue = Queue::at(queue_path.clone());
9214        let mut t = queue.get(&t.id).unwrap();
9215        assert!(t.chat_notice_due().is_none(), "restart does not replay");
9216        t.release_operator("test", None);
9217        t.attempts += 1;
9218        let missing = task_attachments(&queue, &t).unwrap_err();
9219        t.fail_startup_target(
9220            "startup-attachments",
9221            missing.name,
9222            "same missing attachment with regenerated wording",
9223            1,
9224        );
9225        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
9226
9227        std::fs::write(&paths[0], "restored").unwrap();
9228        t.release_operator("test", None);
9229        t.attempts += 1;
9230        let missing = task_attachments(&queue, &t).unwrap_err();
9231        let reason = missing.to_string();
9232        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9233        let second = t
9234            .chat_notice_due()
9235            .expect("different attachment must notify");
9236        assert_ne!(first, second);
9237        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
9238    }
9239
9240    #[test]
9241    fn resumed_instruction_is_unchanged_without_any_answers() {
9242        let t = task();
9243        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
9244    }
9245
9246    #[test]
9247    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
9248        let mut t = task();
9249        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9250        // The run's own instruction on disk predates the answer: it is the
9251        // plain original text `Runner::start` saved before the operator was
9252        // ever asked anything.
9253        let old = t.instruction.clone();
9254
9255        let refreshed = resumed_instruction(&old, &t);
9256        assert!(refreshed.starts_with(&old), "the original text is kept");
9257        assert!(refreshed.contains("Which backend?"));
9258        assert!(refreshed.contains("SQLite"));
9259    }
9260
9261    #[test]
9262    fn resumed_instruction_keeps_an_original_answers_heading() {
9263        let mut t = task();
9264        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
9265        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9266
9267        let refreshed = resumed_instruction(&t.instruction, &t);
9268
9269        assert!(
9270            refreshed.starts_with(&t.instruction),
9271            "an answers heading in the original instruction is not the appended block"
9272        );
9273        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
9274        assert!(refreshed.contains("Which backend?"));
9275        assert!(refreshed.contains("SQLite"));
9276
9277        let repeated = resumed_instruction(&refreshed, &t);
9278        assert_eq!(
9279            repeated, refreshed,
9280            "only the final appended block is refreshed"
9281        );
9282    }
9283
9284    #[test]
9285    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
9286        let mut t = task();
9287        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9288
9289        // A first resume appends the block; a second resume of the same run,
9290        // with no new answer in between, must reproduce exactly the same
9291        // text rather than appending the block a second time.
9292        let once = resumed_instruction(&t.instruction, &t);
9293        let twice = resumed_instruction(&once, &t);
9294        assert_eq!(once, twice);
9295        assert_eq!(once.matches("Which backend?").count(), 1);
9296
9297        // A later answer replaces the block wholesale rather than growing it.
9298        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
9299        let refreshed = resumed_instruction(&once, &t);
9300        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
9301        assert!(refreshed.contains("Which backend?"));
9302        assert!(refreshed.contains("Which cache?"));
9303    }
9304
9305    #[test]
9306    fn prepare_instruction_covers_all_three_starters() {
9307        let mut t = task();
9308        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
9309
9310        // Start: a fresh run gets the task text plus every answer so far —
9311        // exactly `instruction_for`.
9312        assert_eq!(
9313            prepare_instruction(&Starter::Start, None, &t),
9314            Some(instruction_for(&t))
9315        );
9316
9317        // Resume: the run's prior instruction is refreshed with the answer,
9318        // not discarded and not left stale.
9319        let old = t.instruction.clone();
9320        assert_eq!(
9321            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
9322            Some(resumed_instruction(&old, &t))
9323        );
9324
9325        // Review: a review-only pass builds its own instruction from the
9326        // branch's history in `crate::graph`, with no task statement at all -
9327        // this boundary must leave it alone.
9328        assert_eq!(
9329            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
9330            None
9331        );
9332    }
9333
9334    #[test]
9335    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
9336        assert_eq!(
9337            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
9338            Starter::Review("magi/eba2/A".to_owned())
9339        );
9340    }
9341
9342    #[test]
9343    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
9344        assert_eq!(
9345            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
9346            Starter::Start,
9347            "a vanished review branch must not fall back to resuming the old run either"
9348        );
9349    }
9350
9351    #[test]
9352    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
9353        let mut t = task();
9354        t.start("old-run".to_owned());
9355        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
9356        t.release();
9357        let branch = t.review_branch.take();
9358        assert_eq!(
9359            choose_starter(branch.as_deref(), true, Some("old-run")),
9360            Starter::Review("magi/eba2/A".to_owned()),
9361            "a review wins over resuming the old run"
9362        );
9363    }
9364
9365    #[test]
9366    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
9367        assert_eq!(
9368            choose_starter(None, false, Some("some-run")),
9369            Starter::Resume("some-run".to_owned())
9370        );
9371        assert_eq!(choose_starter(None, false, None), Starter::Start);
9372    }
9373
9374    #[test]
9375    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
9376        let mut released = task();
9377        released.start("stalled-run".to_owned());
9378        released.requeue();
9379        let unfinished = (!released.fresh_start)
9380            .then(|| Some("stalled-run".to_owned()))
9381            .flatten();
9382        assert_eq!(
9383            choose_starter(None, false, unfinished.as_deref()),
9384            Starter::Start,
9385            "release keeps run history but must not resume it"
9386        );
9387        assert_eq!(released.runs, ["stalled-run"]);
9388    }
9389
9390    #[test]
9391    fn an_ordinary_release_keeps_a_resumable_run_available() {
9392        let mut released = task();
9393        released.start("stalled-run".to_owned());
9394        released.release();
9395        let unfinished = (!released.fresh_start)
9396            .then(|| Some("stalled-run".to_owned()))
9397            .flatten();
9398        assert_eq!(
9399            choose_starter(None, false, unfinished.as_deref()),
9400            Starter::Resume("stalled-run".to_owned()),
9401            "manual release must preserve the normal resume path"
9402        );
9403    }
9404
9405    #[test]
9406    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
9407        let mut state = run_state(RunStatus::Blocked);
9408        state.config.graph.review_rounds = 3;
9409        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
9410        assert!(exhausted_review_budget(&state));
9411
9412        // One round still unused: resuming can still ask a reviewer something.
9413        state.reviews.pop();
9414        assert!(!exhausted_review_budget(&state));
9415
9416        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
9417        // count: only a `Blocked` run re-enters the review loop on resume.
9418        let mut stalled = run_state(RunStatus::Stalled);
9419        stalled.config.graph.review_rounds = 1;
9420        stalled.reviews = vec![review_round(1)];
9421        assert!(!exhausted_review_budget(&stalled));
9422    }
9423
9424    fn review_round(round: usize) -> crate::run::ReviewRound {
9425        crate::run::ReviewRound {
9426            round,
9427            head: "deadbeef".to_owned(),
9428            verified_head: None,
9429            verified_at: None,
9430            reviews: Vec::new(),
9431            e2e: Vec::new(),
9432            verify_retried: false,
9433            e2e_deferred: false,
9434            e2e_defer_reason: None,
9435            fix: None,
9436            blocking: 0,
9437            answered: 1,
9438            expected: 1,
9439            clean: false,
9440            progressed: true,
9441            vote_split: false,
9442            reconsideration: Vec::new(),
9443            verdict: None,
9444        }
9445    }
9446
9447    #[test]
9448    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
9449        let mut run = RunState::new(
9450            PathBuf::from("/repo"),
9451            "main".to_owned(),
9452            "abc1234def".to_owned(),
9453            "add retries".to_owned(),
9454            Config::default(),
9455        );
9456        run.status = RunStatus::Judging;
9457        run.parked = true;
9458        let mut task = Task::new(
9459            "add retries".to_owned(),
9460            "add retries".to_owned(),
9461            PathBuf::from("/repo"),
9462            crate::queue::Source::Human,
9463        );
9464        task.status = TaskStatus::Failed;
9465        task.runs = vec![run.id.clone()];
9466        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
9467        assert!(with(&task, &run), "parked after judging is the case");
9468        let mut parked_task = task.clone();
9469        parked_task.status = TaskStatus::Parked;
9470        assert!(with(&parked_task, &run), "the Parked status is the case");
9471
9472        let mut not_parked = run.clone();
9473        not_parked.parked = false;
9474        not_parked.status = RunStatus::Stalled;
9475        assert!(!with(&task, &not_parked), "a stall is the conductor's");
9476
9477        let mut fresh = task.clone();
9478        fresh.fresh_start = true;
9479        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
9480
9481        let mut review = task.clone();
9482        review.review_branch = Some("magi/x/A".to_owned());
9483        assert!(!with(&review, &run), "review is ranked before resume");
9484
9485        let mut held = task.clone();
9486        held.status = TaskStatus::Held;
9487        assert!(!with(&held, &run), "a hold stays visible to the conductor");
9488
9489        let mut released = run.clone();
9490        released.released_to = Some("20260901-000000-new1".to_owned());
9491        assert!(!with(&task, &released), "nothing left to resume into");
9492
9493        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
9494            "unreadable"
9495        )));
9496    }
9497
9498    #[test]
9499    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
9500        let mut released = RunState::new(
9501            PathBuf::from("/repo"),
9502            "main".to_owned(),
9503            "abc1234def".to_owned(),
9504            "add retries".to_owned(),
9505            Config::default(),
9506        );
9507        released.status = RunStatus::Blocked;
9508        assert_eq!(
9509            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9510            Some(released.id.clone())
9511        );
9512        released.released_to = Some("20260901-000000-new1".to_owned());
9513        assert_eq!(
9514            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
9515            None,
9516            "there is nothing left to resume it into"
9517        );
9518    }
9519
9520    #[test]
9521    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
9522        // Mirrors the failure this exists to close: a task's last run ended
9523        // `Blocked` with the review budget spent, `crate::conduct` chose
9524        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
9525        // evidence), and without this check `attempt` would go on treating
9526        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
9527        // review loop iterates zero times over an already-spent budget, so
9528        // the resumed run settles right back to `Blocked` having asked nobody
9529        // anything, and `Requeue`'s promised fresh competition never happens.
9530        let mut exhausted = RunState::new(
9531            PathBuf::from("/repo"),
9532            "main".to_owned(),
9533            "abc1234def".to_owned(),
9534            "add retries".to_owned(),
9535            Config::default(),
9536        );
9537        exhausted.status = RunStatus::Blocked;
9538        exhausted.config.graph.review_rounds = 1;
9539        exhausted.reviews = vec![review_round(1)];
9540
9541        assert_eq!(
9542            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
9543            None,
9544            "an exhausted `Blocked` run must not be offered as resumable"
9545        );
9546
9547        // A `Blocked` run with rounds still unused is genuinely worth
9548        // resuming, and must still be found.
9549        let mut has_budget_left = RunState::new(
9550            PathBuf::from("/repo"),
9551            "main".to_owned(),
9552            "abc1234def".to_owned(),
9553            "add retries".to_owned(),
9554            Config::default(),
9555        );
9556        has_budget_left.status = RunStatus::Blocked;
9557        has_budget_left.config.graph.review_rounds = 3;
9558        has_budget_left.reviews = vec![review_round(1)];
9559
9560        assert_eq!(
9561            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
9562                Ok(has_budget_left.clone())
9563            }),
9564            Some(has_budget_left.id.clone())
9565        );
9566    }
9567
9568    #[test]
9569    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
9570        let mut run = RunState::new(
9571            PathBuf::from("/repo"),
9572            "main".to_owned(),
9573            "abc1234def".to_owned(),
9574            "add retries".to_owned(),
9575            Config::default(),
9576        );
9577        run.status = RunStatus::Blocked;
9578        run.config.graph.review_rounds = 1;
9579        run.reviews = vec![review_round(1)];
9580        run.pr_publication_pending = true;
9581        assert_eq!(
9582            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
9583            Some(run.id.clone()),
9584            "a spent review budget must not turn a failed publication into a re-competition"
9585        );
9586    }
9587
9588    #[test]
9589    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
9590        // A task whose history holds an *older* run that still looks
9591        // resumable (say, a competition `Runner::review` was started
9592        // alongside after that older run went `Stalled`) and a *newest* run
9593        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
9594        // on this task must mean a fresh competition — falling back to the
9595        // stale, superseded `Stalled` run instead would resurrect history
9596        // nothing asked to revisit and silently defeat the requeue.
9597        let mut older_stalled = RunState::new(
9598            PathBuf::from("/repo"),
9599            "main".to_owned(),
9600            "abc1234def".to_owned(),
9601            "add retries".to_owned(),
9602            Config::default(),
9603        );
9604        older_stalled.status = RunStatus::Stalled;
9605
9606        let mut newest_exhausted = RunState::new(
9607            PathBuf::from("/repo"),
9608            "main".to_owned(),
9609            "abc1234def".to_owned(),
9610            "add retries".to_owned(),
9611            Config::default(),
9612        );
9613        newest_exhausted.status = RunStatus::Blocked;
9614        newest_exhausted.config.graph.review_rounds = 1;
9615        newest_exhausted.reviews = vec![review_round(1)];
9616
9617        assert_eq!(
9618            unfinished_run_with(
9619                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
9620                "t",
9621                |_| Ok(newest_exhausted.clone())
9622            ),
9623            None,
9624            "the newest run is exhausted, so nothing here is worth resuming - \
9625             least of all the older, already-superseded run"
9626        );
9627    }
9628
9629    #[test]
9630    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
9631        assert_eq!(
9632            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
9633                Err(anyhow::anyhow!("fixture is absent"))
9634            }),
9635            None
9636        );
9637    }
9638
9639    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
9640        let mut q = ask::Question::new(
9641            run.to_owned(),
9642            "implement".to_owned(),
9643            "impl-A".to_owned(),
9644            "continue?".to_owned(),
9645            String::new(),
9646            vec!["resume で続行する".to_owned(), "other".to_owned()],
9647        );
9648        q.actions.insert("resume で続行する".to_owned(), action);
9649        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
9650            .unwrap();
9651        q
9652    }
9653
9654    fn held_task_with(run: &str) -> Task {
9655        let mut t = task();
9656        t.runs = vec![run.to_owned()];
9657        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
9658        t
9659    }
9660
9661    fn resume_action(run: &str) -> ask::ChoiceAction {
9662        ask::ChoiceAction::Resume { run: run.into() }
9663    }
9664
9665    #[test]
9666    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
9667        for parked in [false, true] {
9668            let mut t = task();
9669            t.start("A".into());
9670            t.start("B".into());
9671            assert_eq!(t.runs, vec!["A", "B"]);
9672            t.start("A".into());
9673            let mut resumed = run_state(RunStatus::Blocked);
9674            resumed.id = "A".into();
9675            resumed.parked = parked;
9676            resumed.driver_exited = true;
9677            t.hold_machine(Some("resumed run stopped".into()));
9678            let q = action_question("A", resume_action("A"));
9679            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
9680            assert_eq!(
9681                decide_action(&t, &q, &PHRASES_EN, |id| {
9682                    assert_eq!(id, "A");
9683                    Ok(resumed.clone())
9684                }),
9685                ActionDecision::Resume("A".into())
9686            );
9687            assert_eq!(
9688                action_standing(&t, &action_question("B", resume_action("B"))),
9689                ActionStanding::Stale
9690            );
9691            t.release_operator("cli", None);
9692            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
9693                assert_eq!(id, "A");
9694                Ok(resumed.clone())
9695            });
9696            assert_eq!(
9697                choose_starter(None, false, unfinished.as_deref()),
9698                Starter::Resume("A".into())
9699            );
9700            assert_eq!(t.runs, vec!["B", "A"]);
9701        }
9702    }
9703
9704    #[test]
9705    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
9706        let mut state = crate::land::tests::repair_state(true, true);
9707        state.status = RunStatus::Landing;
9708        state.parked = true;
9709        state.driver_exited = true;
9710        let mut q = ask::Question::new(
9711            state.id.clone(),
9712            land::APPROVAL_NODE.into(),
9713            "land".into(),
9714            "Merge?".into(),
9715            String::new(),
9716            vec![land::APPROVE.into(), land::HOLD.into()],
9717        );
9718        q.id = state.id.clone();
9719        state.land_approval = Some(crate::run::LandApproval {
9720            question: q.id.clone(),
9721            head: "current-head".into(),
9722        });
9723        assert!(land::upgrade_repair_choice(&mut q, &state));
9724        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
9725        let mut task = held_task_with(&state.id);
9726        task.status = TaskStatus::Parked;
9727        assert_eq!(
9728            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
9729            ActionDecision::Resume(state.id.clone())
9730        );
9731        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
9732        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
9733        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
9734        assert_eq!(
9735            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
9736            ActionDecision::Resume(state.id.clone()),
9737            "a repair answer newer than the manual hold resumes the existing owner"
9738        );
9739        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
9740        for answered_at in [q.answered_at, None] {
9741            let mut older = q.clone();
9742            older.answered_at = answered_at;
9743            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
9744                panic!("a later manual hold must prevent dispatch")
9745            });
9746            let ActionDecision::Refuse(reason) = refused else {
9747                panic!("expected an actionable refusal, got {refused:?}");
9748            };
9749            assert!(reason.contains("later operator decision"));
9750            assert!(reason.contains(&format!("magi task release {}", task.id)));
9751        }
9752        task.operator_decided_at = None;
9753        let mut superseded = state.clone();
9754        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
9755        assert_eq!(
9756            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
9757            ActionDecision::Stale
9758        );
9759        for case in 1..4 {
9760            let mut changed = state.clone();
9761            match case {
9762                1 => changed.status = RunStatus::Blocked,
9763                2 => changed.released_to = Some("new-owner".into()),
9764                _ => changed.land_approval.as_mut().unwrap().head.clear(),
9765            }
9766            assert!(matches!(
9767                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
9768                ActionDecision::Refuse(_)
9769            ));
9770        }
9771        assert!(matches!(
9772            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
9773            ActionDecision::Refuse(_)
9774        ));
9775        task.runs.push("replacement".into());
9776        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
9777        assert_eq!(
9778            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
9779                "old owner must not load"
9780            )),
9781            ActionDecision::Stale
9782        );
9783    }
9784
9785    #[test]
9786    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
9787        let mut state = crate::land::tests::repair_state(true, true);
9788        state.status = RunStatus::Landing;
9789        state.parked = true;
9790        state.driver_exited = true;
9791        let mut q = ask::Question::new(
9792            state.id.clone(),
9793            land::APPROVAL_NODE.into(),
9794            "land".into(),
9795            "Merge?".into(),
9796            String::new(),
9797            vec![land::APPROVE.into(), land::HOLD.into()],
9798        );
9799        q.id = state.id.clone();
9800        state.land_approval = Some(crate::run::LandApproval {
9801            question: q.id.clone(),
9802            head: "current-head".into(),
9803        });
9804        state.save().unwrap();
9805        land::upgrade_repair_choice(&mut q, &state);
9806        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
9807        Questions::open().put(&mut q).unwrap();
9808        let tmp = tempfile::tempdir().unwrap();
9809        let queue = Queue::at(tmp.path().join("queue"));
9810        let mut task = held_task_with(&state.id);
9811        task.status = TaskStatus::Parked;
9812        queue.put(&mut task).unwrap();
9813        let empty = Arc::new(tokio::sync::Semaphore::new(0));
9814        let free = Arc::new(tokio::sync::Semaphore::new(1));
9815        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
9816        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
9817        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
9818        assert!(claim.permit.is_some());
9819        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
9820        drop(claim);
9821        Questions::open()
9822            .update(&q.id, |q| {
9823                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
9824                Ok(())
9825            })
9826            .unwrap();
9827        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
9828        assert!(claim.permit.is_none());
9829        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
9830    }
9831
9832    #[test]
9833    fn decide_action_resumes_only_the_latest_resumable_run() {
9834        let t = held_task_with("r1");
9835        let q = action_question("r1", resume_action("r1"));
9836        let load = |s: RunState| move |_: &str| Ok(s);
9837        assert_eq!(
9838            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
9839            ActionDecision::Resume("r1".into())
9840        );
9841        // Not the latest run of the task.
9842        let q_other = action_question("r1", resume_action("r0"));
9843        assert!(matches!(
9844            decide_action(
9845                &t,
9846                &q_other,
9847                &PHRASES_EN,
9848                load(run_state(RunStatus::Blocked))
9849            ),
9850            ActionDecision::Refuse(_)
9851        ));
9852        // A finished run cannot make progress.
9853        assert!(matches!(
9854            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
9855            ActionDecision::Refuse(_)
9856        ));
9857        // A released one either.
9858        let mut released = run_state(RunStatus::Blocked);
9859        released.released_to = Some("elsewhere".into());
9860        assert!(matches!(
9861            decide_action(&t, &q, &PHRASES_EN, load(released)),
9862            ActionDecision::Refuse(_)
9863        ));
9864        // Unreadable state is a refusal, never a fresh competition.
9865        assert!(matches!(
9866            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
9867            ActionDecision::Refuse(_)
9868        ));
9869    }
9870
9871    #[test]
9872    fn decide_action_ignores_a_question_about_an_earlier_run() {
9873        let mut t = held_task_with("r1");
9874        t.runs.push("r2".to_owned());
9875        let never = |_: &str| -> Result<RunState> { bail!("not read") };
9876        assert_eq!(
9877            decide_action(
9878                &t,
9879                &action_question("r1", ask::ChoiceAction::Done),
9880                &PHRASES_EN,
9881                never
9882            ),
9883            ActionDecision::Stale
9884        );
9885    }
9886
9887    #[test]
9888    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
9889        let mut t = held_task_with("r1");
9890        let never = |_: &str| -> Result<RunState> { bail!("not read") };
9891        assert_eq!(
9892            decide_action(
9893                &t,
9894                &action_question("r1", ask::ChoiceAction::Requeue),
9895                &PHRASES_EN,
9896                never
9897            ),
9898            ActionDecision::Requeue
9899        );
9900        let done_q = action_question("r1", ask::ChoiceAction::Done);
9901        assert_eq!(
9902            decide_action(&t, &done_q, &PHRASES_EN, never),
9903            ActionDecision::Done
9904        );
9905        t.mark_action_applied(&done_q.id);
9906        assert_eq!(
9907            decide_action(&t, &done_q, &PHRASES_EN, never),
9908            ActionDecision::Skip
9909        );
9910
9911        // A plain answer (no action for that label) does nothing.
9912        let mut plain = action_question("r1", ask::ChoiceAction::Done);
9913        plain.actions.clear();
9914        assert_eq!(
9915            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
9916            ActionDecision::Skip
9917        );
9918        // A running task is left alone.
9919        let mut running = held_task_with("r1");
9920        running.status = TaskStatus::Running;
9921        assert_eq!(
9922            decide_action(
9923                &running,
9924                &action_question("r1", ask::ChoiceAction::Done),
9925                &PHRASES_EN,
9926                never
9927            ),
9928            ActionDecision::Skip
9929        );
9930    }
9931
9932    #[test]
9933    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
9934        crate::run::pin_test_home();
9935        for legacy in [false, true] {
9936            let dir = tempfile::tempdir().unwrap();
9937            let queue = Queue::at(dir.path().join("queue"));
9938            let questions = Questions::at(dir.path().join("questions"));
9939            let run = "20260101-000000-hold";
9940            let mut task = held_task_with(run);
9941            task.status = TaskStatus::Parked;
9942            let mut q = ask::Question::new(
9943                run.into(),
9944                land::APPROVAL_NODE.into(),
9945                "land".into(),
9946                "Repair?".into(),
9947                String::new(),
9948                vec![land::REPAIR.into()],
9949            );
9950            q.actions.insert(land::REPAIR.into(), resume_action(run));
9951            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
9952            // Deterministically order the answer before the actual manual hold.
9953            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
9954            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
9955            questions.put(&mut q).unwrap();
9956            task.hold_manual(Some("Keep this PR paused".into()));
9957            if legacy {
9958                task.hold_source = None;
9959            }
9960            queue.put(&mut task).unwrap();
9961
9962            apply_choice_actions(&queue, &questions, dir.path());
9963            let after = queue.get(&task.id).unwrap();
9964            assert!(after.operator_held());
9965            assert_eq!(after.hold_source, task.hold_source);
9966            assert_eq!(after.operator_decided_at, task.operator_decided_at);
9967            assert_eq!(after.runs, task.runs);
9968            assert_eq!(after.instruction, task.instruction);
9969            assert!(after.resume_override.is_none());
9970            assert!(after.action_applied(&q.id));
9971            let reason = after.hold_reason.as_deref().unwrap();
9972            assert!(reason.starts_with("Keep this PR paused"));
9973            assert!(reason.contains("later operator decision"));
9974            assert!(reason.contains(&format!("magi task release {}", task.id)));
9975
9976            for recovery in [
9977                crate::conduct::Recovery::Review,
9978                crate::conduct::Recovery::Requeue,
9979            ] {
9980                crate::conduct::apply(
9981                    &queue,
9982                    &questions,
9983                    &crate::conduct::Verdict {
9984                        decisions: vec![crate::conduct::Decision {
9985                            id: task.id.clone(),
9986                            recovery: Some(recovery),
9987                            ..Default::default()
9988                        }],
9989                    },
9990                )
9991                .unwrap();
9992            }
9993            // Reconciliation is idempotent, and automatic recovery cannot
9994            // reopen this owner after it observes the rejected repair answer.
9995            apply_choice_actions(&queue, &questions, dir.path());
9996            let still_held = queue.get(&task.id).unwrap();
9997            assert!(still_held.operator_held());
9998            assert_eq!(still_held.hold_reason, after.hold_reason);
9999            assert_eq!(still_held.runs, task.runs);
10000            assert!(still_held.review_branch.is_none());
10001            assert!(!still_held.fresh_start);
10002            assert!(queue.next_runnable().is_none());
10003        }
10004    }
10005
10006    #[test]
10007    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
10008        let dir = tempfile::tempdir().unwrap();
10009        let queue = Queue::at(dir.path().join("queue"));
10010        let questions = Questions::at(dir.path().join("questions"));
10011        let home = dir.path().join("home");
10012        let mut state = run_state(RunStatus::Blocked);
10013        state.id = "20260101-000000-act1".to_owned();
10014        state.save_under(&home).unwrap();
10015
10016        let mut t = held_task_with(&state.id);
10017        queue.put(&mut t).unwrap();
10018        let mut q = action_question(&state.id, resume_action(&state.id));
10019        questions.put(&mut q).unwrap();
10020
10021        apply_choice_actions(&queue, &questions, &home);
10022        let after = queue.get(&t.id).unwrap();
10023        assert_eq!(after.status, TaskStatus::Queued);
10024        assert!(!after.fresh_start);
10025        assert!(after.action_applied(&q.id));
10026        let pin = after.resume_override.clone().unwrap();
10027        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
10028        assert!(pin.forced);
10029
10030        // Held again later: the same answer does not release it a second time.
10031        let mut again = queue.get(&t.id).unwrap();
10032        again.hold_machine(Some("later".into()));
10033        queue.put(&mut again).unwrap();
10034        apply_choice_actions(&queue, &questions, &home);
10035        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10036    }
10037
10038    #[test]
10039    fn a_delivered_answer_is_still_acted_on_exactly_once() {
10040        let dir = tempfile::tempdir().unwrap();
10041        let queue = Queue::at(dir.path().join("queue"));
10042        let questions = Questions::at(dir.path().join("questions"));
10043        let home = dir.path().join("home");
10044        let mut state = run_state(RunStatus::Blocked);
10045        state.id = "20260101-000000-act2".to_owned();
10046        state.save_under(&home).unwrap();
10047
10048        let mut t = held_task_with(&state.id);
10049        queue.put(&mut t).unwrap();
10050        let mut q = action_question(&state.id, resume_action(&state.id));
10051        q.answer_delivered = true;
10052        questions.put(&mut q).unwrap();
10053
10054        // Delivered, and the agent then died: the task is still held, so the
10055        // chosen action applies.
10056        apply_choice_actions(&queue, &questions, &home);
10057        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10058        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
10059
10060        // Held again: the same answer does nothing a second time.
10061        let mut again = queue.get(&t.id).unwrap();
10062        again.hold_machine(Some("later".into()));
10063        queue.put(&mut again).unwrap();
10064        apply_choice_actions(&queue, &questions, &home);
10065        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10066    }
10067
10068    #[test]
10069    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
10070        let dir = tempfile::tempdir().unwrap();
10071        let queue = Queue::at(dir.path().join("queue"));
10072        let questions = Questions::at(dir.path().join("questions"));
10073        let home = dir.path().join("home");
10074        let mut state = run_state(RunStatus::Blocked);
10075        state.id = "20260101-000000-act3".to_owned();
10076        state.save_under(&home).unwrap();
10077        let mut t = held_task_with(&state.id);
10078        queue.put(&mut t).unwrap();
10079        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
10080        questions.put(&mut q).unwrap();
10081
10082        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
10083        apply_choice_actions(&queue, &questions, &home);
10084        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10085
10086        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10087        apply_choice_actions(&queue, &questions, &home);
10088        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10089    }
10090
10091    #[test]
10092    fn action_standing_tells_the_reasons_apart() {
10093        let mut t = held_task_with("r1");
10094        let q = action_question("r1", ask::ChoiceAction::Requeue);
10095        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10096        let mut plain = q.clone();
10097        plain.actions.clear();
10098        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
10099
10100        // Applied wins over everything, even a running task.
10101        t.mark_action_applied(&q.id);
10102        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
10103
10104        // A newer attempt running: the old question is Stale, not Busy.
10105        let mut t = held_task_with("r1");
10106        t.start("r2".to_owned());
10107        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
10108        // The same question about the latest run just waits.
10109        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
10110        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10111        t.status = TaskStatus::Blocked;
10112        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10113
10114        // A conductor question is keyed by the task, never stale.
10115        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
10116        c.node = crate::conduct::NODE.to_owned();
10117        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
10118        assert!(!ActionStanding::Busy.daemon_owns());
10119    }
10120
10121    #[test]
10122    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
10123        let dir = tempfile::tempdir().unwrap();
10124        let queue = Queue::at(dir.path().join("queue"));
10125        let questions = Questions::at(dir.path().join("questions"));
10126        let home = dir.path().join("home");
10127        let mut state = run_state(RunStatus::Blocked);
10128        state.id = "20260101-000000-act4".to_owned();
10129        state.save_under(&home).unwrap();
10130        let mut t = held_task_with(&state.id);
10131        t.status = TaskStatus::Running;
10132        queue.put(&mut t).unwrap();
10133        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
10134        q.cwd = Some(dir.path().display().to_string());
10135        questions.put(&mut q).unwrap();
10136
10137        // While the task runs the daemon will not act, so the waiter still
10138        // delivers the word to the dead asker's seat ...
10139        let running = queue.get(&t.id).unwrap();
10140        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
10141        assert!(matches!(
10142            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
10143            crate::waiter::Action::Deliver(_)
10144        ));
10145        // ... and the daemon waits while the task runs, then applies once.
10146        apply_choice_actions(&queue, &questions, &home);
10147        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10148        let mut back = queue.get(&t.id).unwrap();
10149        back.hold_machine(Some("later".into()));
10150        queue.put(&mut back).unwrap();
10151        apply_choice_actions(&queue, &questions, &home);
10152        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
10153        let mut again = queue.get(&t.id).unwrap();
10154        again.hold_machine(Some("again".into()));
10155        queue.put(&mut again).unwrap();
10156        apply_choice_actions(&queue, &questions, &home);
10157        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10158    }
10159}