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    /// Effective startup capabilities of the question recovery loops.
156    #[serde(default)]
157    pub question_recovery: Option<crate::question_delivery::Recovery>,
158}
159
160impl Status {
161    /// A fresh, idle status for this process.
162    #[must_use]
163    pub fn new() -> Self {
164        let now = Timestamp::now();
165        Self {
166            schema: SCHEMA,
167            pid: std::process::id(),
168            started_at: now,
169            updated_at: now,
170            idle: true,
171            current: Vec::new(),
172            completed: 0,
173            polls: 0,
174            question_recovery: None,
175        }
176    }
177}
178
179impl Default for Status {
180    fn default() -> Self {
181        Self::new()
182    }
183}
184
185/// How the loop should behave.
186#[derive(Debug, Clone)]
187pub struct Opts {
188    /// Repository used by tasks that name none.
189    pub repo: PathBuf,
190    /// Explicit `magi.toml`, instead of the discovered layer stack.
191    pub config: Option<PathBuf>,
192    /// Queue poll interval.
193    pub poll: Duration,
194    /// Attempts a task gets before it is held for a human.
195    pub max_attempts: usize,
196    /// Drain what is runnable now, then return, instead of waiting for more.
197    pub once: bool,
198    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
199    pub merge: Option<String>,
200    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
201    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
202    /// `None` resolves to [`crate::run::default_worktree_root`] - the
203    /// operator's real `~/wt/<repo>` - the same way a run with no
204    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
205    /// that does not own that directory (a test, an embedding that manages
206    /// worktrees itself) must set this, or every idle tick reclaims worktrees
207    /// out from under whoever actually does.
208    pub worktrees_root: Option<PathBuf>,
209}
210
211impl Default for Opts {
212    fn default() -> Self {
213        Self {
214            repo: PathBuf::from("."),
215            config: None,
216            poll: POLL,
217            max_attempts: 2,
218            once: false,
219            merge: None,
220            worktrees_root: None,
221        }
222    }
223}
224
225/// How many runs a plain `usize` from config may drive concurrently, floored
226/// at one. A `0` in a config file would otherwise stall the loop entirely -
227/// no runnable task could ever start - which is never what an operator who
228/// wrote `0` meant.
229fn max_concurrent(n: usize) -> usize {
230    n.max(1)
231}
232
233/// Where the status file lives.
234#[must_use]
235pub fn status_path() -> PathBuf {
236    crate::run::home().join("daemon.json")
237}
238
239/// Publish the status file for this process.
240pub fn write_status(status: &Status) -> Result<()> {
241    write_status_to(&status_path(), status)
242}
243
244/// Publish a status to an explicit path.
245///
246/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
247/// on every health poll and must never see a half-written one.
248pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
249    if let Some(parent) = path.parent() {
250        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
251    }
252    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
253    let tmp = path.with_extension("json.tmp");
254    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
255    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
256    Ok(())
257}
258
259/// Delete the status file. Called on the way out so a clean exit reads as
260/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
261pub fn clear_status() {
262    clear_status_at(&status_path());
263}
264
265/// Delete a status file at an explicit path, so the loop's teardown and
266/// [`clear_status`] cannot drift apart: the loop is handed the path it
267/// published to, and a test can watch a temp file disappear.
268fn clear_status_at(path: &Path) {
269    let _ = std::fs::remove_file(path);
270}
271
272/// A cooperative stop, shared with whoever asked the loop to run.
273///
274/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
275/// Ctrl-C listener and the web UI keep others, and every clone points at the
276/// same flag. There is no channel because there is nothing to send — the only
277/// message is "stop", it is idempotent, and a flag cannot be missed by a
278/// receiver that was not listening yet.
279///
280/// The handle also answers the question the operator's screen asks next: a
281/// stop does not take effect until the run in flight has finished, so
282/// [`Stop::finishing`] reports "asked to stop, still working" rather than
283/// leaving a caller to infer it from a heartbeat and hope.
284#[derive(Debug, Clone, Default)]
285pub struct Stop {
286    /// Set once, never cleared: a stop is not something an operator takes back
287    /// half way through, and a clearable flag would let a start racing a stop
288    /// resurrect a loop that is already unwinding.
289    stopped: Arc<AtomicBool>,
290    /// How many runs are in flight, so `finishing` can distinguish a stop
291    /// that has landed from one that is waiting on `execute`. A count, not a
292    /// flag, because more than one run can be in flight at once - see
293    /// [`crate::config::Daemon::max_concurrent_runs`] - and the last one to
294    /// finish is the one that should turn "finishing" off.
295    busy: Arc<std::sync::atomic::AtomicUsize>,
296    /// Wakes the idle wait. Without this a stop would not be seen until the
297    /// poll interval elapsed, and an operator tapping stop on a phone would
298    /// watch a button do nothing for five seconds.
299    wake: Arc<Notify>,
300    /// Handed to the run in flight, so a stop can also mean "park at the next
301    /// node boundary" instead of "finish the whole competition first".
302    pause: crate::graph::Pause,
303}
304
305impl Stop {
306    /// A stop nobody has asked for yet.
307    #[must_use]
308    pub fn new() -> Self {
309        Self::default()
310    }
311
312    /// Ask the loop to stop. Idempotent, and safe to call before the loop
313    /// starts: the flag is checked before the first poll.
314    pub fn stop(&self) {
315        self.stopped.store(true, Ordering::SeqCst);
316        // `notify_one` rather than `notify_waiters` because the loop may not be
317        // parked yet: this stores a permit, so a wait that registers a moment
318        // later returns at once instead of sleeping out the whole interval.
319        self.wake.notify_one();
320    }
321
322    /// Has a stop been asked for?
323    #[must_use]
324    pub fn stopped(&self) -> bool {
325        self.stopped.load(Ordering::SeqCst)
326    }
327
328    /// Has a stop been asked for that has not taken effect yet, because a run
329    /// is still in flight?
330    ///
331    /// This is the state a screen has to be able to show. A stop never abandons
332    /// a run — see [`serve_until`] — so between the tap and the loop's return
333    /// there is a window of tens of minutes in which "running" and "stopped"
334    /// are both misleading answers.
335    #[must_use]
336    pub fn finishing(&self) -> bool {
337        self.stopped() && self.busy_now()
338    }
339
340    /// Ask the loop to stop *and* the run in flight to park at its next node
341    /// boundary.
342    ///
343    /// The plain [`Stop::stop`] never abandons a run, which is right when the
344    /// operator only wants the queue to drain: a competition is tens of
345    /// minutes and its worktrees are paid for. But an operator who wants to
346    /// replace the binary cannot wait out a run that has an hour left, and
347    /// killing the process loses whatever the seats in flight had not written.
348    /// Parking costs at most the node in progress and leaves the run
349    /// resumable.
350    pub fn park(&self, cause: crate::run::ParkCause) {
351        self.pause.park_for(cause);
352        self.stop();
353    }
354
355    /// Has a park been asked for?
356    #[must_use]
357    pub fn parking(&self) -> bool {
358        self.pause.parked()
359    }
360
361    /// The pause handle to give a runner.
362    #[must_use]
363    pub fn pause(&self) -> crate::graph::Pause {
364        self.pause.clone()
365    }
366
367    /// Is any run in flight right now?
368    ///
369    /// `finishing` answers "a stop is waiting on a run", which is false until
370    /// someone asks to stop. An upgrade needs the plain question, because it
371    /// is about to be the one asking.
372    #[must_use]
373    pub fn busy_now(&self) -> bool {
374        self.busy.load(Ordering::SeqCst) > 0
375    }
376
377    /// Mark one more run as in flight, for [`Stop::finishing`].
378    fn enter(&self) {
379        self.busy.fetch_add(1, Ordering::SeqCst);
380    }
381
382    /// Mark one run as finished. The last one out is what makes
383    /// [`Stop::busy_now`] false again.
384    fn exit(&self) {
385        self.busy.fetch_sub(1, Ordering::SeqCst);
386    }
387
388    /// Wait out one poll interval, returning early once a stop is asked for.
389    async fn idle(&self, poll: Duration) {
390        tokio::select! {
391            () = tokio::time::sleep(poll) => {}
392            () = self.wake.notified() => {}
393        }
394    }
395}
396
397/// The daemon's published state, read permissively.
398///
399/// This mirrors [`Status`], but is a separate declaration on purpose: every
400/// field defaults, so a status file from an older or newer magi still yields
401/// a usable reading — one this build has never heard of — instead of a parse
402/// error that hides the daemon entirely.
403#[derive(Debug, Clone, Default, Deserialize)]
404#[serde(default)]
405pub struct Reading {
406    /// Format version the daemon claims.
407    pub schema: u32,
408    /// Daemon process id, for an operator who wants to stop it.
409    pub pid: Option<u32>,
410    /// When that process started.
411    pub started_at: Option<Timestamp>,
412    /// Last heartbeat. Absent means the file is unusable, hence not running.
413    pub updated_at: Option<Timestamp>,
414    /// True when the queue had nothing runnable at the last poll.
415    pub idle: bool,
416    /// What the daemon is working on. Empty means idle; more than one entry
417    /// means more than one run is in flight at once.
418    ///
419    /// `deserialize_with` rather than the plain derive: a daemon started
420    /// before this field became a list is still out there writing the old
421    /// shape — a single `{"task":...,"run":...}` object, or its absence —
422    /// on every heartbeat until it is restarted, and a live process reading
423    /// that file during the rollout must still see it as running rather than
424    /// as absent. A bare type change here would fail the whole struct's
425    /// deserialization on a type mismatch, defeating the permissiveness this
426    /// type exists for.
427    #[serde(deserialize_with = "de_current")]
428    pub current: Vec<Current>,
429    /// Tasks this daemon process has finished.
430    pub completed: u64,
431    /// Queue polls this daemon process has made.
432    pub polls: u64,
433    /// Effective startup capabilities of the question recovery loops.
434    #[serde(default)]
435    pub question_recovery: Option<crate::question_delivery::Recovery>,
436}
437
438/// Accept the old single-`Current`-or-absent shape as well as the current
439/// list, so a reader never has to know which build wrote the file.
440fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
441where
442    D: serde::Deserializer<'de>,
443{
444    #[derive(Deserialize)]
445    #[serde(untagged)]
446    enum Shape {
447        Many(Vec<Current>),
448        One(Current),
449    }
450    Ok(
451        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
452            Shape::Many(v) => v,
453            Shape::One(c) => vec![c],
454        }),
455    )
456}
457
458impl Reading {
459    /// Seconds since the last heartbeat, or `None` when there has never been
460    /// one.
461    #[must_use]
462    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
463        self.updated_at
464            .map(|at| (now.as_second() - at.as_second()).max(0))
465    }
466
467    /// Whether the loop counts as running: a heartbeat no older than
468    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
469    /// progress hours after the daemon that owned it was killed.
470    #[must_use]
471    pub fn running(&self, now: Timestamp) -> bool {
472        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
473    }
474}
475
476/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
477/// usable there.
478///
479/// Missing, half-written and unparseable all collapse to `None`, because the
480/// only question a reader asks is whether a daemon is alive, and a file it
481/// cannot read is not evidence that one is.
482#[must_use]
483pub fn read_status(home: &Path) -> Option<Reading> {
484    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
485    serde_json::from_str(&body).ok()
486}
487
488/// Every run a live daemon is working on right now.
489///
490/// One definition of liveness, because deleting a task and deleting a run are
491/// both gated on it from both the CLI and the web UI - four callers that must
492/// never disagree about whether the same thing is in flight. A stale heartbeat
493/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
494/// left at `running` or a run left at `implementing` by a killed daemon is a
495/// leftover record rather than work in progress. More than one entry once
496/// [`crate::config::Daemon::max_concurrent_runs`] is more than one - a caller
497/// after "the one thing in flight" wants [`is_working_on`] or
498/// [`is_working_on_task`], not this directly.
499#[must_use]
500pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
501    read_status(home)
502        .filter(|reading| reading.running(now))
503        .map(|reading| reading.current)
504        .unwrap_or_default()
505}
506
507/// Whether a live daemon is working on this run at this moment.
508#[must_use]
509pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
510    current_work(home, now).iter().any(|c| c.run == run)
511}
512
513/// Whether a live daemon is working on a run whose short id is this one.
514///
515/// For a worktree that has no run record to compare against at all -
516/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
517/// id is not available to hand to [`is_working_on`]. The short id is: a run's
518/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
519/// and it is exactly the gap between the daemon claiming a task and
520/// `RunState::new` saving the first `run.json` that this exists to protect -
521/// a run genuinely in flight but invisible to a scan of `runs/`.
522#[must_use]
523pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
524    current_work(home, now)
525        .iter()
526        .any(|c| crate::run::short_of(&c.run) == short)
527}
528
529/// Whether a live daemon is working on this task at this moment.
530#[must_use]
531pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
532    current_work(home, now).iter().any(|c| c.task == task)
533}
534
535/// Remove claim files whose owner is provably dead, or that have simply
536/// outlived `older_than`, and return the task ids swept.
537///
538/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
539/// destructor, and the orphaned `.lock` file would make its task permanently
540/// unclaimable — the backlog would stop for good at exactly the task that was
541/// in flight when the machine went down.
542///
543/// The pid recorded in the lock is the authority whenever it can be read at
544/// all; age is only a fallback for when it cannot be.
545///
546/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
547///   full stop — dead sweeps the lock immediately, regardless of age; alive
548///   protects it, regardless of age. This is what lets a lock be reclaimed in
549///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
550///   before this daemon even started, next to a `queued` task, no longer has
551///   to sit for six hours before anything notices its owner is gone.
552/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
553///   falls back to `older_than`, since there is nothing else to check.
554///
555/// Age must never override a *positive* liveness confirmation. `sweep`
556/// [`poll`]s concurrently with every attempt this daemon itself has spawned —
557/// see [`InFlightGuard`] — not only between them the way a single sequential
558/// loop once did, so a run that legitimately runs longer than `older_than`
559/// (a multi-round review, a long land wait carried across several resumed
560/// attempts) still has this very process's own live pid sitting in its own
561/// lock file on every later sweep. Deciding by age alone in that case would
562/// delete this daemon's own still-valid claim on its own in-flight task,
563/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
564/// to a second attempt — two `Runner`s writing the same `run.json` and the
565/// same worktree at once. `pid_alive` answering "alive" for anything it
566/// cannot determine (a live process, a pid this build cannot check, one
567/// under another account) is exactly what keeps that path from ever
568/// firing on a guess.
569///
570/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
571/// output unreadable must not be license to guess, and the risk of an
572/// unparseable lock outliving a genuinely dead owner is bounded by an order
573/// of magnitude above any plausible run rather than by a positive check.
574///
575/// Runs on every poll, not only at startup — a daemon up for days must keep
576/// noticing a lock some other, now-dead, daemon left behind just as readily
577/// as one it trips over on the way up.
578pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
579    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
580}
581
582/// [`sweep_stale_claims`] with its process-query boundary supplied by the
583/// caller. This keeps the lock policy testable where process listing is
584/// unavailable, while production still uses the platform query above.
585fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
586where
587    F: Fn(u32) -> bool,
588{
589    let this_process = std::process::id();
590    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
591        .into_iter()
592        .flatten()
593        .flatten()
594        .map(|e| e.path())
595        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
596        .filter(|p| {
597            match std::fs::read_to_string(p)
598                .ok()
599                .and_then(|body| body.trim().parse::<u32>().ok())
600            {
601                // This process wrote it and is asking the question right
602                // now, so it is definitionally still alive - settled without
603                // spawning a helper process at all.
604                Some(pid) if pid == this_process => false,
605                Some(pid) => !pid_alive(pid),
606                None => p
607                    .metadata()
608                    .and_then(|m| m.modified())
609                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
610                    .is_ok_and(|age| age >= older_than),
611            }
612        })
613        .filter(|p| std::fs::remove_file(p).is_ok())
614        .filter_map(|p| {
615            p.file_stem()
616                .and_then(|s| s.to_str())
617                .map(std::borrow::ToOwned::to_owned)
618        })
619        .collect();
620    swept.sort_unstable();
621    swept
622}
623
624/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
625/// no live daemon's heartbeat naming it? Deterministic — no model call, and
626/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
627/// shown.
628fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
629    task.status == TaskStatus::Running
630        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
631        && !is_working_on_task(home, &task.id, now)
632}
633
634/// Every task [`is_stalled`] right now — "止まったタスク" in
635/// `crate::conduct`'s vocabulary.
636fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
637    queue
638        .list()
639        .into_iter()
640        .filter(|t| is_stalled(t, home, now))
641        .collect()
642}
643
644/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
645/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
646/// `Failed`-and-so-also-runnable: a task that already attempted and lost
647/// belongs in [`finished_tasks`], where the question is a recovery, not a
648/// dependency.
649fn queued_tasks(queue: &Queue) -> Vec<Task> {
650    queue
651        .list()
652        .into_iter()
653        .filter(|t| t.status == TaskStatus::Queued)
654        .collect()
655}
656
657/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
658/// タスク" in `crate::conduct`'s vocabulary.
659fn finished_tasks(queue: &Queue) -> Vec<Task> {
660    queue
661        .list()
662        .into_iter()
663        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
664        .collect()
665}
666
667/// Deterministically resolve `Task::blocked_by`: a dependency task that
668/// reached `Done`, or a question that was answered, is removed — no model
669/// involved, on every poll. An answered question's content is copied onto
670/// the task ([`Task::record_answer`]) before its id is dropped, so it
671/// reaches the next `crate::conduct` prompt and the next run's instruction
672/// (see [`instruction_for`]) rather than only clearing the block.
673///
674/// A `blocked_by` id that names neither an existing task nor an existing
675/// question - `magi task rm` (or an operator by hand) deleted it while this
676/// task was still waiting - is caught before any of that: it can never
677/// become `Done` or `Answered`, so the ordinary loop below would otherwise
678/// leave the task `blocked` forever with nothing to notice. Such a task is
679/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
680/// which puts it in front of `crate::triage::run_once`'s own walk the next
681/// time it runs - see that module's doc for why the choice is "ask a human",
682/// never "assume the missing dependency was satisfied and unblock anyway".
683fn resolve_blockers(queue: &Queue, questions: &Questions) {
684    for listed in queue.list() {
685        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
686            continue;
687        }
688        let Ok(_claim) = queue.claim(&listed.id) else {
689            continue;
690        };
691        let Ok(mut task) = queue.get(&listed.id) else {
692            continue;
693        };
694        if task.status != TaskStatus::Blocked {
695            continue;
696        }
697        // A dependency deleted on purpose is released, not held - and before
698        // the missing check, so a pass that races the delete (or a claim that
699        // made `Queue::remove` skip this task) settles it quietly.
700        let deleted = queue.apply_deleted_blockers(&mut task, questions);
701        if !deleted.is_empty() {
702            record(queue, &mut task);
703            for id in &deleted {
704                queue.note_dependency_deleted(&task, id);
705            }
706            if task.status != TaskStatus::Blocked {
707                continue;
708            }
709        }
710        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
711        if !missing.is_empty() {
712            let language = language_of(&task, Path::new("."));
713            let mut cause = missing.clone();
714            cause.sort();
715            cause.dedup();
716            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
717            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
718                &task.blocked_by,
719                &missing,
720                &language,
721            )));
722            record(queue, &mut task);
723            continue;
724        }
725        // A conductor question nobody answered in time is retired by the
726        // waiter, and nothing else would ever move the task it blocks.
727        if let Some(q) = task.blocked_by.iter().find_map(|id| {
728            let crate::queue::Dependency::Question(full) =
729                crate::queue::dependency(queue, questions, id)
730            else {
731                return None;
732            };
733            questions.get(&full).ok().filter(|q| {
734                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
735            })
736        }) {
737            let language = language_of(&task, Path::new("."));
738            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
739            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
740            record(queue, &mut task);
741            continue;
742        }
743        let mut changed = false;
744        for id in task.blocked_by.clone() {
745            let resolved = crate::queue::dependency(queue, questions, &id);
746            if let crate::queue::Dependency::Task(full) = &resolved {
747                if queue
748                    .get(full)
749                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
750                {
751                    task.unblock(&id);
752                    changed = true;
753                }
754                continue;
755            }
756            if let crate::queue::Dependency::Question(full) = resolved
757                && let Ok(q) = questions.get(&full)
758                && q.status == ask::QuestionStatus::Answered
759            {
760                // The action sweep releases conductor blockers atomically
761                // with their selected operation. A fresh deputy lease must
762                // never leave an answered hold temporarily runnable.
763                if q.node == crate::conduct::NODE
764                    && q.chosen_action().is_some()
765                    && !task.action_applied(&q.id)
766                {
767                    continue;
768                }
769                let answer = match &q.answer {
770                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
771                    None => String::new(),
772                };
773                task.record_answer(q.summary.clone(), answer);
774                task.unblock(&id);
775                changed = true;
776            }
777        }
778        if changed {
779            record(queue, &mut task);
780        }
781    }
782}
783
784/// The `hold_reason` of a task whose conductor question went unanswered.
785fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
786    if crate::lang::is_japanese(language) {
787        format!(
788            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
789            q.short(),
790            q.summary
791        )
792    } else {
793        format!(
794            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
795            q.short(),
796            q.summary
797        )
798    }
799}
800
801/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
802/// for several unrelated reasons, and the waiter must not read them alike.
803#[derive(Debug, Clone, Copy, PartialEq, Eq)]
804pub(crate) enum ActionStanding {
805    /// The answer carries no action: the waiter delivers it as before.
806    NoAction,
807    /// The daemon will apply it (not applied, task idle, current attempt).
808    Pending,
809    /// Already applied (`Task::actions_applied`): the daemon has acted, so
810    /// delivering the word to the old seat would run it beside the new work.
811    Applied,
812    /// The question is about an earlier attempt than the task's latest.
813    Stale,
814    /// The task is running / blocked / done: the daemon defers for now.
815    Busy,
816}
817
818impl ActionStanding {
819    /// The daemon has acted or will act: the waiter must not deliver.
820    pub(crate) fn daemon_owns(self) -> bool {
821        matches!(self, Self::Pending | Self::Applied | Self::Stale)
822    }
823}
824
825/// Classify `q`'s chosen action against `task`. `Stale` is judged before
826/// `Busy`: a question about an earlier attempt must be stopped even while a
827/// newer competition is running.
828pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
829    if q.chosen_action().is_none() {
830        ActionStanding::NoAction
831    } else if task.action_applied(&q.id) {
832        ActionStanding::Applied
833    } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
834        ActionStanding::Stale
835    } else if matches!(
836        task.status,
837        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
838    ) {
839        ActionStanding::Busy
840    } else {
841        ActionStanding::Pending
842    }
843}
844
845/// What [`decide_action`] concluded about one answered question.
846#[derive(Debug, Clone, PartialEq, Eq)]
847enum ActionDecision {
848    /// Nothing to do now (no action, already applied, or the task is busy).
849    Skip,
850    /// Continue the named run instead of competing again.
851    Resume(String),
852    /// Requeue as a fresh competition.
853    Requeue,
854    /// Hold the task by explicit operator choice.
855    Hold,
856    /// Close the task as done.
857    Done,
858    /// The question is about an earlier attempt than the task's latest; it
859    /// is recorded as handled and changes nothing.
860    Stale,
861    /// The action cannot be carried out; hold the task and say why. Never
862    /// falls back to something else, because the operator chose this one.
863    Refuse(String),
864}
865
866/// Decide what the choice answered on `q` means for `task`. Pure: `load`
867/// reads a run's state, as with [`unfinished_run_with`].
868///
869/// `Resume` only fires on the task's *latest* run, and only while that run
870/// could actually make progress ([`RunStatus::resumable`], not released, review
871/// budget left); an answer naming anything else is refused rather than
872/// reinterpreted as a fresh competition.
873fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
874where
875    F: FnOnce(&str) -> Result<RunState>,
876{
877    let Some(action) = q.chosen_action() else {
878        return ActionDecision::Skip;
879    };
880    if task.action_applied(&q.id)
881        || matches!(
882            task.status,
883            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
884        )
885    {
886        return ActionDecision::Skip;
887    }
888    // A question about an earlier attempt must not act on a newer one. A
889    // conductor question is keyed by the task id, not a run, so it is exempt.
890    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891        return ActionDecision::Stale;
892    }
893    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
894    let stopping = q.node == land::APPROVAL_NODE
895        && q.resolution()
896            .as_deref()
897            .is_some_and(crate::merge_decision::stops);
898    // Repair and stop actions are new decisions on an existing approval card. A
899    // manual hold before that answer must not discard it just because the
900    // card predates the hold. Keep the older policy for other choice actions.
901    let decision_at = if repair || stopping {
902        q.answered_at.unwrap_or(q.asked_at)
903    } else {
904        q.asked_at
905    };
906    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
907        return if repair || stopping {
908            ActionDecision::Refuse(format!(
909                "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
910                if repair { "repair" } else { "stop" },
911                q.id,
912                q.run,
913                task.id
914            ))
915        } else {
916            ActionDecision::Stale
917        };
918    }
919    match action {
920        a if a.maintenance() => ActionDecision::Skip,
921        ask::ChoiceAction::ResumeRun { .. }
922        | ask::ChoiceAction::ReleaseTask { .. }
923        | ask::ChoiceAction::RerunChecks { .. }
924        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
925        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
926        ask::ChoiceAction::Hold => ActionDecision::Hold,
927        ask::ChoiceAction::Done => ActionDecision::Done,
928        ask::ChoiceAction::Resume { run } => {
929            if task.runs.last() != Some(run) {
930                return ActionDecision::Refuse((p.resume_not_latest)(
931                    q.short(),
932                    ask::short_id(run),
933                ));
934            }
935            match load(run) {
936                Ok(s) if stopping => {
937                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
938                        || !s
939                            .land_approval
940                            .as_ref()
941                            .is_some_and(|binding| binding.question == q.id)
942                    {
943                        ActionDecision::Stale
944                    } else if s.liveness(false) == Liveness::Live {
945                        ActionDecision::Skip
946                    } else if s.status == RunStatus::Landing
947                        && !s.released()
948                        && s.retired_to.is_none()
949                    {
950                        ActionDecision::Resume(run.clone())
951                    } else {
952                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
953                    }
954                }
955                Ok(s)
956                    if q.node == land::APPROVAL_NODE
957                        && q.resolution().as_deref() == Some(land::REPAIR) =>
958                {
959                    if s.merge_repairs.iter().any(|r| r.question == q.id)
960                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
961                    {
962                        // A live/manual driver already consumed or superseded
963                        // this answer. Do not hold its fresh approval wait.
964                        ActionDecision::Stale
965                    } else if s.liveness(false) == Liveness::Live {
966                        ActionDecision::Skip
967                    } else if s.status != RunStatus::Landing
968                        || s.released()
969                        || s.reviews.is_empty()
970                        || !implementers_match(task, &s)
971                        || !s
972                            .land_approval
973                            .as_ref()
974                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
975                    {
976                        ActionDecision::Refuse(format!(
977                            "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",
978                            q.id, run, run
979                        ))
980                    } else {
981                        ActionDecision::Resume(run.clone())
982                    }
983                }
984                Ok(s) if s.liveness(false) == Liveness::Live => {
985                    ActionDecision::Refuse("run already has a live driver".into())
986                }
987                Ok(s)
988                    if s.status.resumable()
989                        && !s.released()
990                        && s.retired_to.is_none()
991                        && !exhausted_review_budget(&s) =>
992                {
993                    ActionDecision::Resume(run.clone())
994                }
995                Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
996                    q.short(),
997                    ask::short_id(run),
998                )),
999                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1000                    q.short(),
1001                    ask::short_id(run),
1002                    &format!("{e:#}"),
1003                )),
1004            }
1005        }
1006    }
1007}
1008
1009/// The fixed prose the daemon writes into [`Task::last_error`] and
1010/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1011/// `triage::Wording` and `land::Words`: only English and Japanese are
1012/// translated, anything else falls back to English.
1013///
1014/// Rendered when the reason is *generated*, so a reason keeps the language it
1015/// was written in if the setting changes later. The notification frame
1016/// (`Task <id> is held:`) is not here and stays English.
1017///
1018/// Deliberately **not** translated, because other code reads them back by
1019/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1020/// and `gate red`. IDs, node names, paths and external error text are embedded
1021/// as they are.
1022struct Phrases {
1023    /// `{}` = status label, then the detail.
1024    graph_stopped: fn(&str, &str) -> String,
1025    quorum_lost: &'static str,
1026    /// Followed by the seats' names.
1027    quota_took_out: &'static str,
1028    /// Followed by the status label.
1029    run_ended: &'static str,
1030    /// Followed by the question's short id.
1031    waiting_for_answer: &'static str,
1032    recovered_running: &'static str,
1033    no_run_to_recover: &'static str,
1034    could_not_start: &'static str,
1035    resume_not_latest: fn(&str, &str) -> String,
1036    resume_cannot_progress: fn(&str, &str) -> String,
1037    resume_unreadable: fn(&str, &str, &str) -> String,
1038    /// A takeover refusal: the operator-facing text. English is the error's own
1039    /// `Display`; a translation keeps the machine detail apart in parentheses.
1040    handover_refused: fn(&crate::handover::Refused) -> String,
1041    /// Appended to a refused handover's hold reason (leading space included).
1042    handover_hint: &'static str,
1043    /// (seats that never answered, review rounds) for the review loop's
1044    /// "refusing to call it clean" stop.
1045    reviewers_never_answered: fn(usize, usize) -> String,
1046}
1047
1048const PHRASES_EN: Phrases = Phrases {
1049    graph_stopped: |status, detail| {
1050        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1051    },
1052    quorum_lost: "the judging panel lost its quorum",
1053    quota_took_out: "; quota took out ",
1054    run_ended: "run ended ",
1055    waiting_for_answer: " - waiting for operator answer to question ",
1056    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1057    no_run_to_recover: "task was `running` with no live daemon and no readable \
1058                        run to recover; held for a human to check what happened",
1059    could_not_start: "could not start the run: ",
1060    resume_not_latest: |q, run| {
1061        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1062    },
1063    resume_cannot_progress: |q, run| {
1064        format!("question {q} asked to resume run {run}, which cannot make progress")
1065    },
1066    resume_unreadable: |q, run, e| {
1067        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1068    },
1069    handover_refused: |r| r.to_string(),
1070    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1071    reviewers_never_answered: |missing, rounds| {
1072        format!(
1073            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1074             refusing to call it clean"
1075        )
1076    },
1077};
1078
1079const PHRASES_JA: Phrases = Phrases {
1080    graph_stopped: |status, detail| {
1081        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1082    },
1083    quorum_lost: "審査パネルが定足数を失いました",
1084    quota_took_out: "。クォータで脱落: ",
1085    run_ended: "run 終了: ",
1086    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1087    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1088    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1089                        何が起きたか人が確認するため保留にしました",
1090    could_not_start: "run を開始できませんでした: ",
1091    resume_not_latest: |q, run| {
1092        format!(
1093            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1094        )
1095    },
1096    resume_cannot_progress: |q, run| {
1097        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1098    },
1099    resume_unreadable: |q, run, e| {
1100        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1101    },
1102    handover_refused: |r| {
1103        use crate::handover::Refused;
1104        match r {
1105            Refused::Foreign { branch, path, why } => format!(
1106                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1107                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1108                 から、やり直してください(詳細: {why})"
1109            ),
1110            Refused::Unsafe { branch, path, why } => format!(
1111                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1112                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1113                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1114            ),
1115            Refused::ReleaseFailed { branch, path, run } => format!(
1116                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1117                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1118                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1119            ),
1120        }
1121    },
1122    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1123    reviewers_never_answered: |missing, rounds| {
1124        format!(
1125            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1126             クリーンとは認めません"
1127        )
1128    },
1129};
1130
1131fn phrases(language: &str) -> &'static Phrases {
1132    if crate::lang::is_japanese(language) {
1133        &PHRASES_JA
1134    } else {
1135        &PHRASES_EN
1136    }
1137}
1138
1139/// The language of the repository a task belongs to, read best-effort for the
1140/// paths that have no run (and so no config of their own) to ask. An unreadable
1141/// config is English, not an error: a hold reason must still get written.
1142fn language_of(task: &Task, fallback: &Path) -> String {
1143    crate::lang::of_repo(&repo_for(task, fallback))
1144}
1145
1146/// The task an answered question speaks for: the one whose runs include the
1147/// question's run, or - for a conductor question, filed under the task's own
1148/// id - the task with that id.
1149pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1150    if q.node == crate::conduct::NODE {
1151        return tasks.iter().find(|t| t.id == q.run);
1152    }
1153    tasks.iter().find(|t| t.runs.contains(&q.run))
1154}
1155
1156/// Legacy conductor prose never becomes a maintenance command by inference.
1157/// Replace unsupported open labels under the question lock before dispatch.
1158fn repair_choice_offers(questions: &Questions) {
1159    for q in questions.list().into_iter().filter(|q| {
1160        q.status.open()
1161            && q.node == crate::conduct::NODE
1162            && q.choices
1163                .iter()
1164                .any(|c| crate::choice_effect::describe(q, c).is_none())
1165    }) {
1166        let _ = questions.update(&q.id, |current| {
1167            if current.status.open() {
1168                crate::choice_effect::executable_conductor(current);
1169                if let Some(deputy) = &mut current.deputy {
1170                    deputy.brief = crate::deputy::brief(
1171                        &current.run,
1172                        &current.detail,
1173                        &current.choices,
1174                        &current.actions,
1175                    );
1176                }
1177            }
1178            Ok(())
1179        });
1180    }
1181}
1182
1183/// Apply answered typed choices. Only the daemon calls this in production;
1184/// deputies settle the question and never execute its actions.
1185pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1186    apply_maintenance_choices(queue, questions, home).await;
1187    apply_task_choice_actions(queue, questions, home);
1188}
1189
1190/// Apply bounded maintenance effects independently of question ownership: a
1191/// release watcher need not have a queue task, and a predecessor is another run.
1192async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1193    use crate::release_watch::{GhForge, ReleaseForge};
1194    for q in questions.list() {
1195        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1196            continue;
1197        };
1198        // Receipt paths use question IDs, whose format is independent of run
1199        // IDs. Apply the question store's filename safety rule to both eras.
1200        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1201            continue;
1202        }
1203        let dir = home.join("choice-actions");
1204        if std::fs::create_dir_all(&dir).is_err() {
1205            continue;
1206        }
1207        let Ok(lock) = std::fs::OpenOptions::new()
1208            .create(true)
1209            .truncate(false)
1210            .write(true)
1211            .open(dir.join(format!("{}.lock", q.id)))
1212        else {
1213            continue;
1214        };
1215        if crate::pr_head::try_lock_file(&lock).is_err() {
1216            continue;
1217        }
1218        let fresh = !home
1219            .join("choice-actions")
1220            .join(format!("{}.json", q.id))
1221            .exists();
1222        let result = async {
1223            let receipt = dir.join(format!("{}.json", q.id));
1224            if receipt.exists() {
1225                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1226                anyhow::ensure!(
1227                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1228                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1229                );
1230                return Ok::<_, anyhow::Error>(());
1231            }
1232            // Never retry an uncertain external effect. The receipt is written
1233            // before calling gh, exactly like release_watch's rerun record.
1234            let record = |status: &str| -> anyhow::Result<()> {
1235                let tmp = receipt.with_extension("tmp");
1236                std::fs::write(
1237                    &tmp,
1238                    serde_json::to_vec(&serde_json::json!({
1239                        "action": action, "status": status,
1240                    }))?,
1241                )?;
1242                std::fs::rename(tmp, &receipt)?;
1243                Ok(())
1244            };
1245            let applied = async {
1246                match action {
1247                    ask::ChoiceAction::ResumeRun { run } => {
1248                        crate::resume::validate(home, run)?;
1249                        record("started")?;
1250                        if let Some(listed) = queue
1251                            .list()
1252                            .into_iter()
1253                            .find(|t| t.runs.last() == Some(run))
1254                        {
1255                            let _claim = queue.claim(&listed.id)?;
1256                            let mut task = queue.get(&listed.id)?;
1257                            anyhow::ensure!(
1258                                task.runs.last() == Some(run)
1259                                    && !matches!(
1260                                        task.status,
1261                                        TaskStatus::Running | TaskStatus::Done
1262                                    ),
1263                                "run queue owner changed"
1264                            );
1265                            anyhow::ensure!(
1266                                !task.operator_held()
1267                                    && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1268                                "resume was superseded by an operator hold or newer operator decision"
1269                            );
1270                            task.release_operator("choice", Some(&q.id));
1271                            task.resume_override = Some(crate::queue::OperatorResume {
1272                                question_id: q.id.clone(),
1273                                at: Timestamp::now(),
1274                                conductor_rehold: None,
1275                                forced: true,
1276                                pinned_run: Some(run.clone()),
1277                            });
1278                            task.mark_action_applied(&q.id);
1279                            queue.put(&mut task)?;
1280                        } else {
1281                            crate::resume::validate_unqueued(home, run)?;
1282                            crate::resume::start(run.clone());
1283                        }
1284                    }
1285                    ask::ChoiceAction::ReleaseTask {
1286                        task,
1287                        held_at,
1288                        reason,
1289                    } => {
1290                        anyhow::ensure!(
1291                            queue.resolve_id(task)? == *task,
1292                            "task action requires an exact task ID"
1293                        );
1294                        let _claim = queue.claim(task)?;
1295                        let mut task = queue.get(task)?;
1296                        if task.action_applied(&q.id) {
1297                            return Ok(());
1298                        }
1299                        // Filing this conductor question temporarily wraps the
1300                        // original hold in a Blocked state. Restore only that
1301                        // exact blocker on the local copy before checking the
1302                        // hold binding; unrelated waits never authorize release.
1303                        if q.node == crate::conduct::NODE
1304                            && q.run == task.id
1305                            && task.status == TaskStatus::Blocked
1306                            && task.blocked_from == Some(TaskStatus::Held)
1307                            && task.blocked_by.as_slice() == [q.id.as_str()]
1308                        {
1309                            task.unblock(&q.id);
1310                        }
1311                        anyhow::ensure!(
1312                            task.status == TaskStatus::Held
1313                                && task.held_at == Some(*held_at)
1314                                && task.hold_reason.as_deref() == reason.as_deref()
1315                                && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1316                            "task no longer has the hold this question names"
1317                        );
1318                        task.release_operator("choice", Some(&q.id));
1319                        task.mark_action_applied(&q.id);
1320                        queue.put(&mut task)?;
1321                    }
1322                    ask::ChoiceAction::AbandonRun { run } => {
1323                        record("started")?;
1324                        crate::driver::abandon_proven_dead(home, run)?;
1325                    }
1326                    ask::ChoiceAction::RerunChecks {
1327                        repo,
1328                        pr,
1329                        head,
1330                        runs,
1331                    } => {
1332                        anyhow::ensure!(
1333                            !runs.is_empty()
1334                                && runs.len() <= 20
1335                                && runs
1336                                    .iter()
1337                                    .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1338                                && !pr.starts_with('-'),
1339                            "invalid rerun targets"
1340                        );
1341                        let snap = GhForge.snapshot(repo, pr).await?;
1342                        anyhow::ensure!(
1343                            snap.head == *head && snap.state == crate::land::PrLifecycle::Open,
1344                            "pull request head or lifecycle changed"
1345                        );
1346                        anyhow::ensure!(
1347                            runs.iter().all(|r| snap
1348                                .checks
1349                                .iter()
1350                                .any(|c| c.run.as_ref() == Some(r)
1351                                    && crate::release_watch::is_failed(c.verdict))),
1352                            "named workflow is no longer failed on this pull request"
1353                        );
1354                        record("started")?;
1355                        let rerun_lock = std::fs::OpenOptions::new()
1356                            .create(true)
1357                            .truncate(false)
1358                            .write(true)
1359                            .open(dir.join("reruns.lock"))?;
1360                        crate::pr_head::try_lock_file(&rerun_lock)?;
1361                        let ledger = dir.join("reruns.json");
1362                        let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1363                            serde_json::from_slice(&std::fs::read(&ledger)?)?
1364                        } else {
1365                            Default::default()
1366                        };
1367                        for run in runs {
1368                            let key = serde_json::to_string(&(&q.id, repo, pr, head, run))?;
1369                            if !recorded.insert(key) {
1370                                continue;
1371                            }
1372                            let tmp = ledger.with_extension("tmp");
1373                            std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1374                            std::fs::rename(tmp, &ledger)?;
1375                            GhForge.rerun(repo, run).await?;
1376                        }
1377                    }
1378                    _ => unreachable!(),
1379                }
1380                Ok::<_, anyhow::Error>(())
1381            }
1382            .await;
1383            match applied {
1384                Ok(()) => record("applied"),
1385                Err(e) => {
1386                    record(&format!("refused or failed: {e:#}"))?;
1387                    Err(e)
1388                }
1389            }
1390        }
1391        .await;
1392        // Retire the originating blocker as well as the target operation.
1393        // A foreign resume leaves its issuer held instead of competing beside
1394        // the execution just started. Other successful maintenance lets the
1395        // original task retry its normal, guarded path.
1396        if home
1397            .join("choice-actions")
1398            .join(format!("{}.json", q.id))
1399            .exists()
1400            && let Some(listed) = task_of_question(&queue.list(), &q)
1401            && !listed.action_applied(&q.id)
1402            && let Ok(_claim) = queue.claim(&listed.id)
1403            && let Ok(mut origin) = queue.get(&listed.id)
1404        {
1405            if !origin.operator_held()
1406                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1407                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1408            {
1409                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1410                    origin.hold_machine(Some(format!(
1411                        "Maintenance choice {} settled; inspect its target before releasing this task",
1412                        q.id
1413                    )));
1414                } else {
1415                    origin.unblock(&q.id);
1416                }
1417            }
1418            origin.mark_action_applied(&q.id);
1419            let _ = queue.put(&mut origin);
1420        }
1421        if let Err(e) = result
1422            && fresh
1423        {
1424            notices::raise_in(
1425                home,
1426                Notice::warn(
1427                    &format!("action:{}", q.id),
1428                    format!("Choice action {} was not completed: {e:#}", q.id),
1429                ),
1430            );
1431        }
1432    }
1433}
1434
1435/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1436///
1437/// Runs on every poll before the conductor looks at the queue. The task is
1438/// re-read under its claim, so a task somebody completed or held by hand in
1439/// the meantime is judged on what it is now. `Resume` releases the task and
1440/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1441/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1442/// ordinary `unfinished_run` logic resumes that same run.
1443pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1444    let tasks = queue.list();
1445    for q in questions.list() {
1446        // Dismissal is committed by the question writer, never a resume.
1447        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1448            continue;
1449        }
1450        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1451            continue;
1452        }
1453        let Some(listed) = task_of_question(&tasks, &q) else {
1454            if q.node == land::APPROVAL_NODE
1455                && q.resolution().as_deref().is_some_and(|choice| {
1456                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1457                })
1458            {
1459                notices::raise_in(
1460                    home,
1461                    Notice::warn(
1462                        &format!("repair-owner:{}", q.id),
1463                        format!(
1464                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1465                            q.run, q.run
1466                        ),
1467                    ),
1468                );
1469            }
1470            continue;
1471        };
1472        if listed.action_applied(&q.id) {
1473            continue;
1474        }
1475        let Ok(_claim) = queue.claim(&listed.id) else {
1476            continue;
1477        };
1478        let Ok(mut task) = queue.get(&listed.id) else {
1479            continue;
1480        };
1481        // Work only on this local copy until the action can be committed.
1482        // In particular, a fresh lease below leaves the persisted task blocked.
1483        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1484            let blockers: Vec<_> = task
1485                .blocked_by
1486                .iter()
1487                .filter(|id| {
1488                    crate::queue::dependency(queue, questions, id)
1489                        == crate::queue::Dependency::Question(q.id.clone())
1490                })
1491                .cloned()
1492                .collect();
1493            if !blockers.is_empty() {
1494                for id in blockers {
1495                    task.unblock(&id);
1496                }
1497                let answer = match &q.answer {
1498                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1499                    None => String::new(),
1500                };
1501                task.record_answer(q.summary.clone(), answer);
1502            }
1503        }
1504        let language = language_of(&task, Path::new("."));
1505        let decision = decide_action(&task, &q, phrases(&language), |id| {
1506            RunState::load_under(id, home)
1507        });
1508        let ran = matches!(
1509            decision,
1510            ActionDecision::Resume(_)
1511                | ActionDecision::Requeue
1512                | ActionDecision::Hold
1513                | ActionDecision::Done
1514        );
1515        if ran && asker_may_still_read(questions, &q, home) {
1516            // The asking process or its seat can still take the word; act
1517            // once it has gone quiet. Bound on the remaining window: the
1518            // check is not atomic with the write below, so an asker that
1519            // takes the word in between (at most one poll, never more than
1520            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1521            // and `Task::actions_applied` under the claim keeps the action to
1522            // one application. The waiter does not deliver an answer that
1523            // carries an action (`waiter::decide_owned`), so it cannot race.
1524            continue;
1525        }
1526        let done = matches!(decision, ActionDecision::Done);
1527        match decision {
1528            ActionDecision::Skip => continue,
1529            ActionDecision::Resume(run) => {
1530                task.release_operator("choice", Some(&q.id));
1531                task.resume_override = Some(crate::queue::OperatorResume {
1532                    question_id: q.id.clone(),
1533                    at: Timestamp::now(),
1534                    conductor_rehold: None,
1535                    forced: true,
1536                    pinned_run: Some(run),
1537                });
1538            }
1539            ActionDecision::Stale => {}
1540            ActionDecision::Requeue => {
1541                task.release_operator("choice-requeue", Some(&q.id));
1542                task.requeue();
1543            }
1544            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1545            ActionDecision::Done => task.succeed(),
1546            ActionDecision::Refuse(why) => {
1547                if task.operator_held() {
1548                    // A rejected answer does not release the operator's hold
1549                    // or reclassify it as recoverable by the conductor.
1550                    task.hold_reason = Some(match task.hold_reason.take() {
1551                        Some(reason) => format!("{reason}\n\n{why}"),
1552                        None => why,
1553                    });
1554                } else {
1555                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1556                    task.hold_machine(Some(why));
1557                }
1558                notices::raise(
1559                    Notice::warn(
1560                        &format!("action:{}", q.id),
1561                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1562                    )
1563                    .link(Link::Task {
1564                        id: task.id.clone(),
1565                    }),
1566                );
1567            }
1568        }
1569        task.mark_action_applied(&q.id);
1570        // The applied id travels with the transition, so a failed save loses
1571        // neither and the answer is acted on at the next poll.
1572        record(queue, &mut task);
1573        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1574            supersede_prior_runs(&task, home);
1575        }
1576        // Delivery is only a note of who has read the answer; the task's own
1577        // mark above is the authority. Best effort.
1578        let _ = questions.update(&q.id, |r| {
1579            r.answer_delivered = true;
1580            Ok(())
1581        });
1582    }
1583}
1584
1585/// Whether something may still read the answer to `q`: a fresh lease, or the
1586/// asking seat still listed as active in its run (its CLI can outlive the
1587/// `magi ask` that was killed).
1588fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1589    let now = Timestamp::now();
1590    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1591        return true;
1592    }
1593    q.node != crate::conduct::NODE
1594        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1595            s.seats_active()
1596                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1597        })
1598}
1599
1600/// Retire an unanswered conductor question after its task no longer refers to
1601/// it. Conductor questions use the task id in `Question::run`, so run-based
1602/// cleanup cannot observe a manual release or completion.
1603///
1604/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1605/// own question also carries a `run`, and a run id that happens to collide
1606/// with some task's id is not this loop's business — only a conductor
1607/// question actually uses the task id that way. One `Questions::list()` scan
1608/// is taken up front and matched against the in-memory task set, rather than
1609/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1610fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1611    let tasks = queue.list();
1612    let by_id: std::collections::BTreeMap<&str, &Task> =
1613        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1614    let referenced: Vec<&str> = tasks
1615        .iter()
1616        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1617        .collect();
1618
1619    for mut question in questions.list() {
1620        if !question.status.open() || question.node != crate::conduct::NODE {
1621            continue;
1622        }
1623        // Keep questions a task still names, including when the reference
1624        // moved to a dependent task.
1625        // Preserve even ambiguous references: retiring a possibly referenced
1626        // question is unsafe until the operator disambiguates it.
1627        if referenced
1628            .iter()
1629            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1630        {
1631            continue;
1632        }
1633        let Some(task) = by_id.get(question.run.as_str()) else {
1634            continue;
1635        };
1636        question.abandon(format!(
1637            "task {} no longer waits for this answer",
1638            task.short()
1639        ));
1640        if let Err(e) = questions.put(&mut question) {
1641            tracing::warn!(
1642                "could not retire question {} for task {}: {e:#}",
1643                question.short(),
1644                task.short()
1645            );
1646        }
1647    }
1648}
1649
1650/// What a finished run tells the queue about the task it came from.
1651///
1652/// A struct rather than a fourth and fifth boolean argument: the two flags
1653/// answer different questions about the same run, and a call site passing
1654/// `(…, true, false)` is one transposition away from refunding attempts
1655/// forever.
1656#[derive(Debug, Clone, Copy)]
1657pub struct Verdict {
1658    /// Where the graph stopped.
1659    pub status: RunStatus,
1660    /// The run opened a pull request.
1661    pub left_pr: bool,
1662    /// At least one seat was lost to a rate limit.
1663    pub quota_hit: bool,
1664    /// The run parked at a node boundary because it was asked to.
1665    pub parked: bool,
1666    /// The run never produced a single candidate a judge could look at.
1667    ///
1668    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1669    /// still have another candidate worth judging, in which case the loss was
1670    /// not the reason nothing came of the run. This is `true` only when the
1671    /// implement wave ended with nothing viable at all.
1672    pub no_viable_candidates: bool,
1673}
1674
1675/// Record a finished run against the task it came from.
1676///
1677/// Kept pure and separate from the loop because this mapping *is* the retry
1678/// policy, and a policy that can only be exercised by spawning a graph is a
1679/// policy nobody checks. The table:
1680///
1681/// | run status                           | task becomes        | attempt spent |
1682/// |---------------------------------------|---------------------|---------------|
1683/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1684/// | `Merged`, `Ready`                      | `Done`               | yes          |
1685/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1686/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1687/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1688/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1689/// | `Blocked` with a PR                    | `Held`               | yes          |
1690/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1691/// | `VerifiedNoop`                          | `Held`               | yes          |
1692/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1693///
1694/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1695/// deliberately: every candidate agreeing there is nothing to write is not a
1696/// machine fact about a rate limit, it is an unverified claim about the
1697/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1698/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1699/// claim could be wrong (a misread instruction, a stale check), and closing
1700/// the task automatically on an implementer's say-so would be the exact
1701/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1702/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1703/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1704/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1705/// claim regardless of whether the one already-spent attempt is refunded, and
1706/// [`Task::release`] resets the count to zero anyway the moment a human looks
1707/// at the evidence and lets it run again.
1708///
1709/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1710/// twice, together. A quorum lost to rate limits is a property of the machine
1711/// and not of the task, so the attempt is refunded and a reset quota picks
1712/// the work up where it stopped — and that is just as true when every
1713/// implement seat lost the same race and `after_implement` bails with nothing
1714/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1715/// machine fact. The `no_viable_candidates` guard is what keeps that row
1716/// narrow: a `Failed` run that produced a real candidate which then lost for
1717/// some other reason still spends the attempt, exactly like the quorum lost
1718/// to judges that answered with the wrong shape is ordinary flakiness, and
1719/// refunding *that* takes the bound off the retry loop entirely: run e633
1720/// stalled with `quota: []` after two judges wrote unusable JSON, was
1721/// refunded, and the next attempt paid for a fresh hour-long implement wave
1722/// before it could fail the same way. `max_attempts` exists precisely so
1723/// that cannot repeat forever.
1724///
1725/// A non-terminal status means `execute` returned while the graph was still
1726/// mid-flight, which is a bug rather than a verdict; it is treated as a
1727/// failure so that a task cannot loop on it either.
1728///
1729/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1730/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1731pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1732    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1733}
1734
1735/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1736fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1737    // A parked run is the operator's own doing, and its work is intact on
1738    // disk. The task goes back in line with its attempt refunded so the next
1739    // loop resumes the same run - which `one_task` prefers over competing
1740    // again - and so that swapping the binary a few times cannot exhaust a
1741    // budget meant for agents that actually misbehaved.
1742    if verdict.parked {
1743        task.park(detail);
1744        return;
1745    }
1746    match verdict.status {
1747        RunStatus::Merged | RunStatus::Ready
1748            if task.pr_recovery.as_ref().is_some_and(|s| {
1749                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1750            }) =>
1751        {
1752            task.hold_manual(Some("Public delivery is not confirmed. Inspect the selected PR and run, then use recover-pr --disposition land with the intended source and validation configuration.".into()));
1753        }
1754        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1755        RunStatus::AlreadyInBase => task.already_landed(detail),
1756        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1757        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1758            task.stall(detail)
1759        }
1760        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1761        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1762        RunStatus::Blocked => task.fail(detail, max_attempts),
1763        RunStatus::VerifiedNoop => task.handed_off(detail),
1764        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1765    }
1766}
1767
1768/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1769/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1770/// itself has actually finished *and* its own last attempt is provably why:
1771/// this loads that run and requires `Merged`/`Ready` before touching
1772/// anything earlier in `runs`, since `Task::succeed` can also be called
1773/// directly on a task whose last attempt never landed at all.
1774///
1775/// Called right after whatever call set `task.status` to
1776/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1777/// `reclaim`'s, but also every other place a task can be closed by hand
1778/// without the loop ever settling it itself: `magi task done`
1779/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1780/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1781/// GitHub merge, say, exactly the workflow this repository's own
1782/// "Landing a run's winner by hand" documents — is just as much "this task's
1783/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1784/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1785/// forever, which is the exact backlog this status exists to clear. `pub`
1786/// for those two out-of-module callers; everything else about this stays
1787/// internal bookkeeping.
1788///
1789/// A run something is still actually driving is left alone: a
1790/// task cannot be `Done` while one of its *own* attempts is still in flight,
1791/// so a live one at this point can only be an unrelated process — a manual
1792/// `--resume` of this old, now-moot run — and rewriting under it would just
1793/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1794/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1795/// pair `run_report`/`run_detail` use for the same question elsewhere:
1796/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1797/// --resume` invoked by hand outside it, which `liveness` also checks via
1798/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1799/// (already terminal in some other way, or itself mid-run) is left untouched
1800/// too.
1801///
1802/// Best-effort, like the rest of this module's bookkeeping: a load or save
1803/// failure here is a `tracing::warn`, not a failed settle, and the next time
1804/// this same task's completion is recorded — or a daemon restart replays
1805/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1806/// separate reconciliation pass; if that gap ever matters in practice, one
1807/// can be added then.
1808///
1809/// `home` is a parameter, not the process-global [`crate::run::home`], for
1810/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1811/// calls this with `ui.home`, which is `crate::run::home()` in a real
1812/// process but a fixture's own directory under test — falling through to
1813/// the global there would read and write through whichever home some other
1814/// test in the same binary happened to pin into that `OnceLock` first, not
1815/// the run this call actually means.
1816pub fn supersede_prior_runs(task: &Task, home: &Path) {
1817    let now = Timestamp::now();
1818    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1819    // right behind a `Merged`/`Ready` verdict) from one set directly by
1820    // `magi task done`/its web equivalent/the conductor on a task whose last
1821    // recorded attempt never actually landed - that requires reading the
1822    // run itself, which is exactly what this does before trusting anything
1823    // in `runs` is safe to relabel.
1824    let last_run_succeeded = task
1825        .runs
1826        .last()
1827        .and_then(|id| RunState::load_under(id, home).ok())
1828        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1829    for id in task.superseded_attempts(last_run_succeeded) {
1830        let mut state = match RunState::load_under(id, home) {
1831            Ok(s) => s,
1832            Err(e) => {
1833                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1834                continue;
1835            }
1836        };
1837        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1838            continue;
1839        }
1840        let daemon_claims = is_working_on(home, id, now);
1841        if state.liveness(daemon_claims) == Liveness::Live {
1842            continue;
1843        }
1844        state.status = RunStatus::Superseded;
1845        if let Err(e) = state.save_under(home) {
1846            tracing::warn!("could not mark run {id} superseded: {e:#}");
1847        }
1848    }
1849}
1850
1851/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1852/// finish the moment it was called, because one of its earlier attempts was
1853/// still live then - a `magi run --resume` invoked by hand on an old run,
1854/// most likely.
1855///
1856/// That skip is correct at the time (rewriting under a run something is
1857/// still actively saving would just be undone), but a task only ever
1858/// reaches `Done` once, so without this nothing would ever look at it
1859/// again: if that manual process later ends anywhere other than
1860/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1861/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1862/// backlog this status exists to clear. Called on the same idle-only
1863/// cadence as [`janitor`], next to it rather than folded into it: this
1864/// walks `queue` and `janitor` never otherwise needs one.
1865///
1866/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1867/// more than one attempt, every pass: each call is a handful of local file
1868/// reads bounded by that task's own attempt count, the same order of cost
1869/// [`clean::fold_due`] already pays scanning every run on disk on the same
1870/// cadence, and a task already fully resolved costs one failed liveness
1871/// check turned no-op the moment its lingering attempt is no longer live.
1872fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1873    for task in queue.list() {
1874        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1875            continue;
1876        }
1877        supersede_prior_runs(&task, home);
1878    }
1879}
1880
1881/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1882/// task ends up held.
1883///
1884/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1885/// dead daemon never got back to) share this, so the two cannot drift into
1886/// disagreeing about which held tasks get a diagnostic.
1887fn settle_and_diagnose(
1888    task: &mut Task,
1889    verdict: Verdict,
1890    detail: &str,
1891    max_attempts: usize,
1892    state: &RunState,
1893) {
1894    let p = phrases(&state.config.graph.language);
1895    // Shared by normal completion and crash recovery, under the task claim.
1896    // No new attempt can own the task until the old driver has exited.
1897    if let Some(d) = &state.merge_decision {
1898        use crate::merge_decision as md;
1899        if task.runs.last().is_some_and(|id| id != &state.id) {
1900            return;
1901        }
1902        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1903            task.succeed();
1904        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1905            if state.liveness(false) != Liveness::Dead {
1906                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1907                return;
1908            }
1909            let replacement = md::Replacement {
1910                question: d.question.clone(),
1911                run: state.id.clone(),
1912                pr: d.target.pr.clone(),
1913                agent: agent.to_owned(),
1914                context: format!(
1915                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1916                    d.target.pr,
1917                    state.id,
1918                    serde_json::to_string(&state.reviews).unwrap_or_default()
1919                ),
1920            };
1921            task.requeue();
1922            task.pr_recovery = None;
1923            task.review_of = None;
1924            task.replacement = Some(replacement);
1925        } else {
1926            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1927                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1928            } else { format!("PR closure was not confirmed. Task held; inspect the existing run before starting replacement work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str())) }));
1929        }
1930        task.mark_action_applied(&d.question);
1931        if let Some(pass) = state.passes.last() {
1932            task.record_pass(&state.id, pass.index, task.attempts, None);
1933        }
1934        return;
1935    }
1936    if let Some(replacement) = &task.replacement
1937        && !state.parked
1938        && state.resource_block.is_none()
1939        && (state.viable().is_empty()
1940            || (state.status == RunStatus::Blocked && state.tally.is_none()))
1941    {
1942        task.hold_manual(Some(format!("Selected implementer `{}` was unavailable, failed or hit quota before producing a viable implementation. No other implementer was dispatched. Inspect the run, restore availability, then explicitly release this task.", replacement.agent)));
1943        return;
1944    }
1945    let attempts_before = task.attempts;
1946    // A run that stopped because a shared resource stayed busy was never a
1947    // failure of the task or of any agent: nothing was asked. The attempt is
1948    // refunded and the task is held by the machine, under a reason `triage`
1949    // can re-check, so the same run resumes with the same agents once the
1950    // resource is free. A park request still wins (it is the operator's).
1951    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1952        task.notice_cause(
1953            &format!("resource:{}:{}", block.kind, block.node),
1954            None,
1955            None,
1956        );
1957        task.last_error = Some(detail.to_owned());
1958        task.diagnostic = None;
1959        task.attempts = task.attempts.saturating_sub(1);
1960        if block.kind == "disk pressure" {
1961            task.hold_machine(Some(format!(
1962                "{}{}",
1963                crate::disk::RUNNING_PRESSURE,
1964                block.detail
1965            )));
1966        } else {
1967            task.hold_machine(Some(format!(
1968                "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1969             no agent was asked and no attempt was spent",
1970                crate::cache::RESOURCE_HOLD,
1971                block.kind,
1972                block.node
1973            )));
1974        }
1975        if let Some(pass) = state.passes.last() {
1976            task.record_pass(&state.id, pass.index, attempts_before, None);
1977        }
1978        return;
1979    }
1980    let unresolved = task.hold_notice_cause.clone();
1981    if !verdict.parked
1982        && task
1983            .pr_recovery
1984            .as_ref()
1985            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
1986        && matches!(
1987            verdict.status,
1988            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
1989        )
1990    {
1991        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
1992            task.succeed();
1993        } else {
1994            task.hold_manual(Some("Selected PR delivery is incomplete: local review or publication is not a confirmed public merge. Inspect the run and PR; use recover-pr --disposition land with --source-head <reviewed-full-SHA> and the required verification configuration. No automatic new attempt will start.".into()));
1995        }
1996    } else if !verdict.parked
1997        && task.pr_recovery.is_some()
1998        && matches!(
1999            verdict.status,
2000            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2001        )
2002        && !verdict.quota_hit
2003    {
2004        task.hold_unrequested_retry(Some(format!("Selected recovery stopped: {detail}. Inspect the retained source and run; correct the cause before explicitly releasing or selecting again. No automatic replacement will start.")));
2005    } else {
2006        settle_in(task, verdict, detail, max_attempts, p);
2007    }
2008    if !verdict.parked
2009        && !verdict.quota_hit
2010        && matches!(
2011            verdict.status,
2012            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2013        )
2014    {
2015        task.recovery_failed(state);
2016    }
2017    if state.prep_failure.is_some() {
2018        // Minting a run whose candidates could not be prepared is not work
2019        // on a newly approved attempt. Keep the unresolved outcome anchor.
2020        task.hold_notice_cause = unresolved;
2021        task.startup_notice_cause("startup-candidates");
2022    }
2023    // Written here, where the refund (or not) is decided, so the history is a
2024    // fact and not a later guess from the run's status.
2025    if let Some(pass) = state.passes.last() {
2026        let parked = match &pass.end {
2027            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2028            _ => None,
2029        };
2030        task.record_pass(&state.id, pass.index, attempts_before, parked);
2031    }
2032    if task.status == TaskStatus::Held {
2033        if state.prep_failure.is_none() {
2034            task.notice_cause(
2035                label(verdict.status),
2036                Some(&state.id),
2037                state.passes.last().map(|p| p.index),
2038            );
2039        }
2040        task.diagnostic = diagnostic(state);
2041        note_open_question(task, &state.id, p);
2042    }
2043}
2044
2045/// If `task` is held with a `magi ask` question still open on `run`, name the
2046/// question in [`Task::hold_reason`] rather than leaving the hold reading
2047/// only [`describe`]'s run summary.
2048///
2049/// This is the shape task 20260928-191407-05fd left underspecified: an
2050/// implementer settled a verified no-op and filed a question for the
2051/// operator, and the hold that followed said nothing about the question
2052/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2053/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2054/// marker) and must keep seeing it unchanged.
2055///
2056/// Best-effort: an unreadable question store must not stop a run from
2057/// settling, so this is a no-op rather than a propagated error when
2058/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2059fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2060    let Some(home) = crate::run::try_home() else {
2061        return;
2062    };
2063    let open = Questions::at(home.join("questions")).open_for(run);
2064    let Some(q) = open.first() else {
2065        return;
2066    };
2067    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2068    decisions.sort_unstable();
2069    task.notice_cause(
2070        &format!("questions:{}", decisions.join(",")),
2071        Some(run),
2072        None,
2073    );
2074    let base = task.hold_reason.clone().unwrap_or_default();
2075    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2076}
2077
2078/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2079/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2080/// by some other means entirely, like a manual `magi run` resume that
2081/// finishes the graph outside the queue's bookkeeping.
2082///
2083/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2084/// `settle` is separate from `attempt`: a task recovered this way must land
2085/// exactly where a live daemon would have put it — the same policy table,
2086/// not a second one that quietly drifts from it — and that is only checkable
2087/// without spawning a real run.
2088fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2089    match last_run {
2090        Some(state) => {
2091            let verdict = Verdict {
2092                status: state.status,
2093                left_pr: state.pr.is_some(),
2094                quota_hit: !state.quota.is_empty(),
2095                parked: state.parked,
2096                no_viable_candidates: state.viable().is_empty(),
2097            };
2098            let detail = format!(
2099                "{}{}",
2100                phrases(&state.config.graph.language).recovered_running,
2101                describe(&state)
2102            );
2103            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2104        }
2105        None => {
2106            // No run, so no config of its own: `language` is the task's
2107            // repository's setting, read by the caller.
2108            let why = phrases(language).no_run_to_recover;
2109            task.last_error = Some(why.to_owned());
2110            // The phone shows `hold_reason`, so a task held by the machine
2111            // says why there too and not only in `last_error`.
2112            task.notice_cause("missing-run", None, None);
2113            task.hold_machine(Some(why.to_owned()));
2114        }
2115    }
2116}
2117
2118/// Find every task left at `running` that no live process is actually
2119/// driving, and settle each one against whatever its last run became.
2120///
2121/// # Why a claim is proof, not a guess
2122///
2123/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2124/// `running`, and the guard is held for the task's whole time in that status:
2125/// `attempt` does not return, and the loop does not move past the scope
2126/// holding the claim, until the run has settled. So a `running` task whose
2127/// lock is gone cannot have a live owner — this process or any other —
2128/// without needing a staleness threshold or a pid check the way
2129/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2130/// task that never got as far as `running` at all. Taking the claim here is
2131/// the whole test: it either fails, because something really does hold it
2132/// and the task is left alone, or it succeeds, which is the proof — and it is
2133/// kept for the rest of the decision so nothing else can start a competing
2134/// run while this one is being written.
2135///
2136/// Called on every poll, not only at startup, for the reason
2137/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2138/// keep noticing this, not only on the one morning it happened to restart.
2139fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
2140    let mut reclaimed = Vec::new();
2141    for listed in queue.list() {
2142        if listed.status != TaskStatus::Running {
2143            continue;
2144        }
2145        let Ok(_claim) = queue.claim(&listed.id) else {
2146            continue;
2147        };
2148        // Re-read under the claim: a release or an edit landed by a human
2149        // between the listing above and the claim just taken must not be
2150        // clobbered by a decision based on the stale copy.
2151        let Ok(mut task) = queue.get(&listed.id) else {
2152            continue;
2153        };
2154        if task.status != TaskStatus::Running {
2155            continue;
2156        }
2157        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2158        // `execute` normally abandons a run's own open questions the moment
2159        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2160        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2161        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2162        // with the question still `open`, because the process died before
2163        // reaching that call. `reclaim` itself stays pure on purpose (see its
2164        // own doc), so the same cleanup runs here instead, against the run
2165        // this reclaim is already reading. `settle_run` costs nothing when
2166        // `execute` already got there first.
2167        if let Some(state) = &last_run
2168            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2169        {
2170            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2171        }
2172        let language = if last_run.is_none() {
2173            language_of(&task, Path::new("."))
2174        } else {
2175            String::new()
2176        };
2177        reclaim(&mut task, last_run, max_attempts, &language);
2178        if task.status == TaskStatus::Done {
2179            supersede_prior_runs(&task, &crate::run::home());
2180        }
2181        record(queue, &mut task);
2182        reclaimed.push(task.id.clone());
2183    }
2184    reclaimed
2185}
2186
2187/// Find every run whose `run.json` is provably dead — every seat it still
2188/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2189/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2190/// not merely "no daemon claims it" — and fail it, clearing the leftover
2191/// active seats so the run stops reading as `implementing` (or whichever
2192/// node) forever.
2193///
2194/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2195/// `running`, using whatever `run.json` already says — but nothing in that
2196/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2197/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2198/// never got back to sits exactly where it was left: `active` full of seats
2199/// nobody will ever answer for, `status` stuck on whatever node was in
2200/// flight. `magi show` already tells an operator this in prose (`no live
2201/// daemon claims this run right now`); this is what makes that fact durable
2202/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2203/// stay stuck once nothing is driving it.
2204///
2205/// Runs on every poll, not only at startup, for the reason
2206/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2207/// daemon up for days must keep noticing a run some other, now-dead, daemon
2208/// left behind just as readily as one it trips over on the way up.
2209///
2210/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2211/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2212/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2213/// `runs` directory instead: `home` here is a parameter precisely so a test
2214/// can point it away from the operator's real history (see [`drive`]'s own
2215/// doc), and a scan that fell through to the global home anyway would walk
2216/// whichever directory some *other* process or test pinned into that
2217/// `OnceLock` first — mutating runs this call was never handed.
2218fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2219    reclaim_abandoned_runs_with(
2220        home,
2221        now,
2222        crate::proc::pid_status,
2223        crate::proc::process_started_at,
2224    )
2225}
2226
2227/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2228/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2229/// for the identical reason: this sweep's real damage (wiping a run's active
2230/// seats and failing it) has to be provable against an injected answer in a
2231/// test, not just the real process table.
2232fn reclaim_abandoned_runs_with<F, G>(
2233    home: &Path,
2234    now: Timestamp,
2235    query: F,
2236    identity: G,
2237) -> Vec<String>
2238where
2239    F: Fn(u32) -> Option<bool>,
2240    G: Fn(u32) -> Option<String>,
2241{
2242    let mut abandoned = Vec::new();
2243    for entry in std::fs::read_dir(home.join("runs"))
2244        .into_iter()
2245        .flatten()
2246        .flatten()
2247    {
2248        let id = entry.file_name().to_string_lossy().into_owned();
2249        if !crate::run::is_run_id(&id) {
2250            continue;
2251        }
2252        // Serialize the proof and save with claims and takeover: a new
2253        // execution must not be overwritten after the liveness observation.
2254        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2255            continue;
2256        };
2257        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2258        // that module's docs for why a run this cannot parse is left alone
2259        // rather than guessed at. A different schema number is not that: this
2260        // touches only `status` and `active`, never a field whose meaning a
2261        // schema bump changed, so an old record's values serve this exactly
2262        // as well as a current one's (see `clean::read_state`'s own doc for
2263        // the same reasoning applied to folding).
2264        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2265            continue;
2266        };
2267        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2268            continue;
2269        };
2270        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2271            continue;
2272        }
2273        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2274        // it", which is also the normal, healthy shape of a manual `magi
2275        // run` / `magi review` sharing this same home — this scan walks
2276        // every run on disk, not only ones this daemon itself started. Such
2277        // a run's active seats can legitimately sit past their own timeout
2278        // for a little while (the CLI finishing up, its result still being
2279        // collected) without the process driving it having died. `liveness`
2280        // is what actually tells the two apart, by corroborating
2281        // `driver_pid` against the process it names — see its own doc. Only
2282        // its strongest, provable answer licenses wiping this run's active
2283        // seats and failing it out from under whatever is still running it.
2284        let daemon_claims = is_working_on(home, &id, now);
2285        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2286            != crate::run::Liveness::Dead
2287        {
2288            continue;
2289        }
2290        state.abandon("daemon");
2291        if let Err(e) = state.save_under(home) {
2292            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2293            continue;
2294        }
2295        // This run never passes through `Runner::execute` again, so its end
2296        // is announced here.
2297        if let Some(notice) = notices::run_ended(&state) {
2298            notices::raise_in(home, notice);
2299        }
2300        // The seat that asked is gone for good now, exactly like any other
2301        // door `graph::Runner::settle_questions` closes the moment `status`
2302        // lands somewhere non-resumable - see that method's own doc. Nothing
2303        // else reaches this one before the next `janitor()` startup pass
2304        // (`clean::abandon_settled_questions`), and a daemon that stays up
2305        // for days must not leave an open question badging the operator
2306        // until it happens to restart.
2307        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2308            tracing::warn!("abandon questions for {id}: {e:#}");
2309        }
2310        abandoned.push(id);
2311    }
2312    abandoned
2313}
2314
2315/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2316///
2317/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2318/// sets, so there is one loop body rather than two that drift apart the first
2319/// time the retry policy changes on only one of them.
2320pub async fn serve(opts: Opts) -> Result<()> {
2321    serve_until(opts, Stop::new()).await
2322}
2323
2324/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2325///
2326/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
2327/// mid-node leaves worktrees, branches and agent sessions behind, and every
2328/// agent call already paid for is lost; finishing the run costs the operator a
2329/// wait and saves them a cleanup. A stop therefore only sets a flag: the
2330/// current `execute` runs to its terminal status, the task's outcome is
2331/// recorded, and only then does the loop return. That window is what
2332/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
2333/// still has a second Ctrl-C, which the runtime turns into a process kill —
2334/// and the task left `Running` then tells the next daemon, and the next human,
2335/// where to look.
2336///
2337/// While the queue is empty the stop is honoured within one wakeup rather than
2338/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2339/// caller that taps stop does not sit through the remainder of a sleep.
2340pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2341    let signal = {
2342        let stop = stop.clone();
2343        tokio::spawn(async move {
2344            if tokio::signal::ctrl_c().await.is_ok() {
2345                stop.stop();
2346                tracing::info!("shutdown requested; a run in flight will be finished first");
2347            }
2348        })
2349    };
2350
2351    let worktrees_root = opts
2352        .worktrees_root
2353        .clone()
2354        .unwrap_or_else(crate::run::default_worktree_root);
2355    let outcome = drive(
2356        &opts,
2357        &Queue::open(),
2358        &status_path(),
2359        &crate::run::home(),
2360        &worktrees_root,
2361        &stop,
2362    )
2363    .await;
2364
2365    signal.abort();
2366    outcome
2367}
2368
2369/// The loop proper: setup, poll, teardown, with the queue and the status file
2370/// supplied rather than discovered.
2371///
2372/// All three of `home`, `worktrees_root` and the queue/status paths are
2373/// parameters rather than resolved here, for the same reason:
2374/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2375/// so a unit test that pinned it would fight every other test in the binary,
2376/// and a loop that resolved its own worktree bay could only be exercised
2377/// against the operator's real `~/wt/<repo>` - publishing over a live
2378/// daemon's status file, claiming tasks out of a live backlog, and, since
2379/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2380/// whatever the operator actually has on disk.
2381async fn drive(
2382    opts: &Opts,
2383    queue: &Queue,
2384    status_file: &Path,
2385    home: &Path,
2386    worktrees_root: &Path,
2387    stop: &Stop,
2388) -> Result<()> {
2389    // The status file is a *snapshot*, not a stream of events: a reader only
2390    // ever wants the latest values, and every tick rewrites the whole file
2391    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2392    // while an mpsc channel would force the loop to re-send unchanged fields on
2393    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2394    // for no gain. The lock is only ever held across a field assignment, never
2395    // across an await.
2396    let recovery_cfg = prepare(&opts.repo, opts).ok();
2397    let daemon_cfg = recovery_cfg
2398        .as_ref()
2399        .map(|c| c.daemon.clone())
2400        .unwrap_or_default();
2401    let reconciled = crate::driver::reconcile(home);
2402    if !reconciled.is_empty() {
2403        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2404    }
2405    let mut initial_status = Status::new();
2406    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2407        recovery_cfg.as_ref(),
2408        daemon_cfg.max_deputies,
2409    ));
2410    let status = Arc::new(Mutex::new(initial_status));
2411    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2412    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2413
2414    // Read once at startup, not per task: how many runs this loop drives at
2415    // once is a property of the machine running it, not of whichever
2416    // repository a given task happens to name - see
2417    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2418    // fact in the same sense the agent roster is.
2419    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2420
2421    // Something has to be waiting on every question for as long as it is open,
2422    // whether or not the agent's own `magi ask` survived. Its own task rather
2423    // than a step of the poll loop: the poll loop is busy for the whole of a
2424    // run, and an owner's reply must not queue behind one.
2425    let waiter = tokio::spawn(crate::waiter::run(
2426        crate::waiter::Waiter::new(
2427            crate::ask::Questions::at(home.join("questions")),
2428            home.to_path_buf(),
2429            recovery_cfg.clone(),
2430        ),
2431        stop.clone(),
2432    ));
2433
2434    // The follow-up seats for the conductor's questions: the conductor files a
2435    // question and moves on, and each open one gets a deputy that reads the
2436    // owner's reply. Its own task for the same reason the waiter's is.
2437    let deputies = tokio::spawn(crate::deputy::run(
2438        crate::deputy::Deputies::new(
2439            crate::ask::Questions::at(home.join("questions")),
2440            home.to_path_buf(),
2441            recovery_cfg.clone(),
2442            opts.repo.clone(),
2443            daemon_cfg.max_deputies,
2444            {
2445                let stop = stop.clone();
2446                Arc::new(move || stop.parking())
2447            },
2448        ),
2449        stop.clone(),
2450    ));
2451
2452    // Keeps every checkout's origin/main fresh; its own task so a slow remote
2453    // never holds up the poll loop.
2454    let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
2455
2456    // Watches the release-bump pull requests until they land; its own task, not
2457    // tied to any run, because a pending bump outlives the run that opened it.
2458    let release_watch = tokio::spawn(crate::release_watch::run(
2459        crate::release_watch::Watcher::new(
2460            Box::new(crate::release_watch::GhForge),
2461            home.to_path_buf(),
2462        ),
2463        {
2464            let (repo, opts) = (opts.repo.clone(), opts.clone());
2465            move || release_watch_settings(&repo, &opts)
2466        },
2467        stop.clone(),
2468    ));
2469
2470    tracing::info!(
2471        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2472        queue.root().display(),
2473        opts.poll.as_secs(),
2474        opts.max_attempts,
2475        concurrency,
2476        if daemon_cfg.pause_for_interrupts {
2477            ", interrupts enabled"
2478        } else {
2479            ""
2480        }
2481    );
2482
2483    // `--once` drains an already-idle queue without reaching the idle wait,
2484    // but must still perform the startup cleanup.
2485    janitor(&opts.repo, opts, home, worktrees_root).await;
2486    resweep_superseded_attempts(queue, home);
2487
2488    let outcome = poll(
2489        opts,
2490        queue,
2491        &status,
2492        home,
2493        worktrees_root,
2494        stop,
2495        DispatchLimits {
2496            max_concurrent: concurrency,
2497            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2498        },
2499    )
2500    .await;
2501
2502    beat.abort();
2503    waiter.abort();
2504    deputies.abort();
2505    fetcher.abort();
2506    release_watch.abort();
2507    clear_status_at(status_file);
2508    outcome
2509}
2510
2511/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2512/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2513fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2514    let Ok(cfg) = prepare(repo, opts) else {
2515        return (Vec::new(), 0);
2516    };
2517    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2518        .into_iter()
2519        .map(|r| r.path)
2520        .collect();
2521    // Repositories the daemon has worked in, wherever they live: a task may
2522    // name one outside `[repos] roots`, and its release PR must be watched too.
2523    let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2524    let runs = crate::run::home().join("runs");
2525    for id in crate::run::list_ids_in(&runs) {
2526        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2527            .ok()
2528            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2529            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2530        known.extend(repo);
2531    }
2532    for k in known {
2533        let k = k.canonicalize().unwrap_or(k);
2534        if k.join(".git").exists() && !paths.contains(&k) {
2535            paths.push(k);
2536        }
2537    }
2538    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2539    if !paths.contains(&own) {
2540        paths.push(own);
2541    }
2542    (paths, cfg.daemon.release_stall_minutes)
2543}
2544
2545/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2546const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2547
2548/// Run [`crate::clean::fetch_origins`] every `[repos] fetch_interval` seconds
2549/// until `stop`. The config is re-read each lap; `0` (or an unreadable config)
2550/// disables the fetch for that lap. Never fails.
2551async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2552    while !stop.stopped() {
2553        let (interval, roots) = match prepare(&repo, &opts) {
2554            Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2555            Err(_) => (0, Vec::new()),
2556        };
2557        if interval > 0 && !roots.is_empty() {
2558            let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2559            tracing::debug!("fetch origins: {r:?}");
2560        }
2561        // Sleep in slices so a stop or a config change is noticed promptly.
2562        let wait = if interval > 0 { interval } else { 60 };
2563        let mut slept = 0;
2564        while slept < wait && !stop.stopped() {
2565            tokio::time::sleep(Duration::from_secs(1)).await;
2566            slept += 1;
2567        }
2568    }
2569}
2570
2571/// Refresh the status file on a fixed tick.
2572///
2573/// Separate from the loop because a run takes tens of minutes: a status file
2574/// written only between tasks would look stale for the whole of every run, and
2575/// a reader would report the daemon dead exactly while it was busiest.
2576async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2577    loop {
2578        tokio::time::sleep(HEARTBEAT).await;
2579        let snapshot = {
2580            let mut guard = lock(&status);
2581            guard.updated_at = Timestamp::now();
2582            guard.clone()
2583        };
2584        if let Err(e) = write_status_to(&path, &snapshot) {
2585            // A failed heartbeat must not take the daemon down: the loop is the
2586            // product, the status file is only the window onto it.
2587            tracing::warn!("could not refresh the daemon status file: {e:#}");
2588        }
2589    }
2590}
2591
2592/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2593/// if so, whether that wait is over.
2594#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2595enum LandResume {
2596    /// The task's last run is not parked on a land approval; schedule it
2597    /// like any other candidate.
2598    NotLanding,
2599    /// Parked in `land`, waiting on a question nobody has answered yet.
2600    /// Left alone: attempting it now would only re-observe the same pull
2601    /// request and park again, spending a `gh` call on a decision that has
2602    /// not changed since the last time this was checked.
2603    StillWaiting,
2604    /// Parked in `land`, and the question is settled - answered or
2605    /// abandoned. Resuming this is the one kind of candidate that must not
2606    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2607    Ready,
2608}
2609
2610/// Classify a runnable candidate by whether it is parked on a land-merge
2611/// approval. Read-only - no claim taken, nothing written - so it is cheap
2612/// enough to call on every candidate, every poll.
2613fn land_resume_state(task: &Task) -> LandResume {
2614    let Some(run_id) = task.runs.last() else {
2615        return LandResume::NotLanding;
2616    };
2617    let Ok(state) = RunState::load(run_id) else {
2618        return LandResume::NotLanding;
2619    };
2620    if !state.parked {
2621        return LandResume::NotLanding;
2622    }
2623    if state.status == RunStatus::Landing
2624        && state.land_approval.as_ref().is_some_and(|binding| {
2625            ask::Questions::open()
2626                .get(&binding.question)
2627                .is_ok_and(|q| {
2628                    q.run == state.id
2629                        && q.resolution()
2630                            .as_deref()
2631                            .is_some_and(crate::merge_decision::stops)
2632                })
2633        })
2634    {
2635        return LandResume::Ready;
2636    }
2637    if !implementers_match(task, &state) {
2638        return LandResume::NotLanding;
2639    }
2640    // Parked in `land` on the merge approval, or at `merge` on the owner's
2641    // word about a title/body the posting gate withheld. Told apart by the
2642    // run's own record, not by a status both can share.
2643    let node = if state.status == RunStatus::Landing {
2644        land::APPROVAL_NODE
2645    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2646        crate::github_text::ASK_NODE
2647    } else {
2648        return LandResume::NotLanding;
2649    };
2650    let store = ask::Questions::open();
2651    let waiting = store
2652        .list()
2653        .into_iter()
2654        .filter(|q| &q.run == run_id && q.node == node)
2655        .max_by(|a, b| a.id.cmp(&b.id));
2656    let Some(mut q) = waiting else {
2657        return LandResume::Ready;
2658    };
2659    if !q.status.open() {
2660        // Repair spends agent resources and must obey concurrency and quota
2661        // waits; only a merge/hold decision may use the decision-only lane.
2662        if q.resolution().as_deref() == Some(land::REPAIR) {
2663            return if state.liveness(false) == Liveness::Live {
2664                LandResume::StillWaiting
2665            } else {
2666                LandResume::NotLanding
2667            };
2668        }
2669        return LandResume::Ready;
2670    }
2671    // `ask::ask_and_wait`'s own deadline is what used to retire a question
2672    // nobody ever answered; land's approval bypasses that wait entirely (see
2673    // `land::approval_gate`), so the same deadline has to be enforced here
2674    // instead, or `graph.answer_timeout` silently stops meaning anything for
2675    // a land approval and a run can sit `StillWaiting` forever with nobody
2676    // told to look at it.
2677    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2678    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2679    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2680        q.abandon(format!(
2681            "no answer within {}s of asking",
2682            timeout.as_secs().max(1)
2683        ));
2684        // If this can't be persisted, do not treat the wait as settled on a
2685        // guess: fall through and try again next poll.
2686        if store.put(&mut q).is_ok() {
2687            return LandResume::Ready;
2688        }
2689    }
2690    LandResume::StillWaiting
2691}
2692
2693/// How often the loop rechecks for new work while something it already
2694/// started is still running, rather than sleeping out the whole
2695/// [`Opts::poll`] interval.
2696///
2697/// Short on purpose: this is what lets a land-merge approval that comes back
2698/// while another task is mid-competition be noticed and resumed within a
2699/// fraction of a second, not within the next multi-second poll.
2700const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2701
2702/// How often [`poll`] rechecks the shared build cache against its cap at a
2703/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
2704/// waiting for the queue to run dry.
2705///
2706/// A queue that never empties means the `janitor` call at the bottom of this
2707/// loop's fully-idle branch can go unreached for as long as the backlog
2708/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
2709/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
2710/// 81.8 GiB an idle-only check let it reach before this existed, and it is
2711/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
2712/// backlog of short tasks does not pay for that walk on every poll.
2713const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2714
2715/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
2716/// in `Status::current` - on drop, so both are released even if the attempt
2717/// panics rather than returning.
2718///
2719/// A `Drop` impl rather than statements written after the `.await` it
2720/// guards: a panic unwinds straight past code placed "after" a call, and
2721/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
2722/// that ruling a panic out there is not a bet this loop can make. Without
2723/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
2724/// forever - the idle branch in [`poll`], and with it the janitor, would
2725/// never run again - and a ghost entry in `Status::current` naming a task
2726/// nothing is still working on.
2727struct InFlightGuard<'a> {
2728    status: &'a Arc<Mutex<Status>>,
2729    stop: &'a Stop,
2730    task_id: &'a str,
2731}
2732
2733impl Drop for InFlightGuard<'_> {
2734    fn drop(&mut self) {
2735        lock(self.status).current.retain(|c| c.task != self.task_id);
2736        self.stop.exit();
2737    }
2738}
2739
2740/// State of [`poll`]'s own interrupt-scheduling sequence - see
2741/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
2742/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
2743/// both kept free of `Task`'s non-identity fields on purpose: every decision
2744/// here turns only on task ids and which ones are in flight, so the "never
2745/// more than one run at once" and "exactly one resume" invariants can be
2746/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
2747/// queue - which is exactly the coverage this feature's first two attempts
2748/// were missing.
2749///
2750/// Deliberately in-memory only, not written to disk anywhere: a daemon
2751/// restart mid-sequence loses track of which run it had asked to park and
2752/// which task was meant to run first, and simply falls back to `Idle` -
2753/// see [`drive`]'s own setup. The parked run itself is not lost - it is
2754/// sitting in the queue exactly like any other resumable, interrupted task,
2755/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
2756/// just resumes on the ordinary priority order rather than guaranteed to go
2757/// first. Giving that guarantee a crash-proof memory would mean a new queue
2758/// field and a recovery ordering to go with it, which is exactly the
2759/// complexity this feature's constraints rule out for the one property that
2760/// actually matters: at most one run, ever, at once.
2761#[derive(Debug, Clone, PartialEq, Eq)]
2762enum Interrupt {
2763    /// No interrupt sequence in progress. Ordinary dispatch applies.
2764    Idle,
2765    /// `interrupt_task` is runnable and exactly one other run is in flight;
2766    /// `parked` names that one task's id. Dispatch is withheld from
2767    /// everyone, including `interrupt_task` itself, until it has left
2768    /// flight - only then is `interrupt_task` let through.
2769    ///
2770    /// `parked` is a `Vec` rather than a bare id for symmetry with
2771    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
2772    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
2773    /// when exactly one run is in flight, so it is guaranteed to hold
2774    /// exactly one entry in practice - see that branch's own doc for why
2775    /// more than one is deliberately never attempted.
2776    Parking {
2777        parked: Vec<String>,
2778        interrupt_task: String,
2779    },
2780    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
2781    /// withheld from everyone until it leaves flight - merged, failed, held,
2782    /// it makes no difference - at which point the sequence moves to
2783    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
2784    /// going straight to `Idle` would hand `parked` back to ordinary
2785    /// priority-order dispatch, where a higher-priority task filed in the
2786    /// meantime could start ahead of it.
2787    Running {
2788        parked: Vec<String>,
2789        interrupt_task: String,
2790    },
2791    /// `interrupt_task` left flight; `parked` still names the one run this
2792    /// sequence owes a resume. Dispatch is withheld from everyone except
2793    /// that task - see [`interrupt_gate`] - so the resume this feature
2794    /// promises is never raced by, or run alongside, an unrelated candidate.
2795    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
2796    /// own doc on abandonment - the moment it is no longer runnable at all.
2797    Resuming { parked: Vec<String> },
2798}
2799
2800/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
2801/// and `runnable` are read-only snapshots of this tick's reality, and the
2802/// only side effect the caller still owes the world is asking whichever
2803/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
2804/// site.
2805///
2806/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
2807/// accepted rather than a narrower type because that is what [`poll`] already
2808/// has on hand from [`runnable`], and building a second, smaller list on
2809/// every tick just to satisfy this signature would cost more than it proves.
2810///
2811/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
2812/// back to a task they are waiting on no longer being [`runnable`] - held,
2813/// blocked, deleted, or finished by some other means entirely, all of which
2814/// an operator can do to a task sitting in the queue with no claim on it at
2815/// all, at any moment, interrupt sequence or not. Without this check the
2816/// sequence would wait forever for a dispatch that can never come, and
2817/// `interrupt_gate` would withhold every other task in the queue right along
2818/// with it - a single `magi task hold` on the wrong id turning into a
2819/// daemon that never dispatches anything again.
2820fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2821    match state {
2822        Interrupt::Idle => {
2823            // Not just "something to interrupt": exactly one thing. More
2824            // than one run in flight only happens above the default
2825            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
2826            // one resume, never run alongside anything else" only because
2827            // it is only ever seeded with exactly one id - see
2828            // `Interrupt::Resuming`'s own doc on why releasing more than one
2829            // parked id back to ordinary dispatch cannot be made safe
2830            // against that same setting's own extra concurrency slots.
2831            // Waiting here for the herd to settle to one is the
2832            // simplification this feature's own constraints ask for rather
2833            // than a second concurrency model to reconcile with the first.
2834            if in_flight.len() != 1 {
2835                return Interrupt::Idle;
2836            }
2837            match runnable.iter().find(|t| t.interrupt) {
2838                Some(t) => Interrupt::Parking {
2839                    parked: in_flight.to_vec(),
2840                    interrupt_task: t.id.clone(),
2841                },
2842                None => Interrupt::Idle,
2843            }
2844        }
2845        Interrupt::Parking {
2846            parked,
2847            interrupt_task,
2848        } => {
2849            if in_flight.iter().any(|id| parked.contains(id)) {
2850                // Still waiting for what was in flight to actually stop.
2851                Interrupt::Parking {
2852                    parked,
2853                    interrupt_task,
2854                }
2855            } else if in_flight.contains(&interrupt_task) {
2856                Interrupt::Running {
2857                    parked,
2858                    interrupt_task,
2859                }
2860            } else if runnable.iter().any(|t| t.id == interrupt_task) {
2861                // The parked run(s) are gone, but the interrupt task has not
2862                // been dispatched yet on this tick - `interrupt_gate` is
2863                // what lets it through next.
2864                Interrupt::Parking {
2865                    parked,
2866                    interrupt_task,
2867                }
2868            } else {
2869                // The interrupt task itself is no longer runnable - see this
2870                // function's own doc on abandonment. The parked run(s) still
2871                // get their guaranteed resume; there is simply no interrupt
2872                // to run ahead of them any longer.
2873                Interrupt::Resuming { parked }
2874            }
2875        }
2876        Interrupt::Running {
2877            parked,
2878            interrupt_task,
2879        } => {
2880            if in_flight.contains(&interrupt_task) {
2881                Interrupt::Running {
2882                    parked,
2883                    interrupt_task,
2884                }
2885            } else {
2886                // The interrupt task's own run reached a terminal status,
2887                // whichever one - this is the *only* trigger that moves the
2888                // sequence on, driven straight off the same in-flight
2889                // bookkeeping `poll` already reaps every tick, not a second,
2890                // independent poll of anything.
2891                Interrupt::Resuming { parked }
2892            }
2893        }
2894        Interrupt::Resuming { parked } => {
2895            if in_flight.iter().any(|id| parked.contains(id)) {
2896                // One of the parked runs has been dispatched - the resume
2897                // this sequence owed is fulfilled. Whatever else is left in
2898                // `parked` (ordinarily nothing, at the default concurrency
2899                // of one) rejoins ordinary priority-order dispatch, same as
2900                // any other runnable task.
2901                Interrupt::Idle
2902            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2903                Interrupt::Resuming { parked }
2904            } else {
2905                // Abandonment (see this function's own doc): nothing left in
2906                // `parked` is even runnable any longer.
2907                Interrupt::Idle
2908            }
2909        }
2910    }
2911}
2912
2913/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
2914/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
2915/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
2916/// indistinguishable from any other runnable task - exactly the "off does
2917/// nothing" this feature promises.
2918fn advance_interrupt_tick(
2919    enabled: bool,
2920    state: Interrupt,
2921    in_flight: &[String],
2922    runnable: &[Task],
2923) -> Interrupt {
2924    if !enabled {
2925        return Interrupt::Idle;
2926    }
2927    advance_interrupt(state, in_flight, runnable)
2928}
2929
2930/// Which of this tick's runnable candidates the interrupt sequence actually
2931/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
2932/// each half is assertable on its own: this is the half that keeps a
2933/// competition and an interrupt from ever running at the same moment.
2934fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2935    match state {
2936        Interrupt::Idle => candidates,
2937        Interrupt::Parking {
2938            parked,
2939            interrupt_task,
2940        } => {
2941            if in_flight.iter().any(|id| parked.contains(id)) {
2942                Vec::new()
2943            } else {
2944                candidates
2945                    .into_iter()
2946                    .filter(|t| &t.id == interrupt_task)
2947                    .collect()
2948            }
2949        }
2950        Interrupt::Running { .. } => Vec::new(),
2951        // At most one: even if `parked` names more than one id (more than
2952        // one run was in flight when the sequence began, only possible
2953        // above the default `max_concurrent_runs = 1`), only the first match
2954        // is offered. Capping this to a single candidate - not merely to
2955        // `parked`'s own ids - is what makes "exactly one resume, never two
2956        // dispatched together" true regardless of how many ordinary slots
2957        // happen to be free this tick.
2958        Interrupt::Resuming { parked } => candidates
2959            .into_iter()
2960            .find(|t| parked.contains(&t.id))
2961            .into_iter()
2962            .collect(),
2963    }
2964}
2965
2966/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
2967/// bundled into one parameter so `poll`'s own signature stays readable -
2968/// see [`drive`]'s call site for where these are actually read.
2969struct DispatchLimits {
2970    /// How many *ordinary* candidates run at once. See
2971    /// [`crate::config::Daemon::max_concurrent_runs`].
2972    max_concurrent: usize,
2973    /// See [`crate::config::Daemon::pause_for_interrupts`].
2974    pause_for_interrupts: bool,
2975}
2976
2977/// Which semaphore, if any, dispatching a candidate should draw its permit
2978/// from.
2979///
2980/// Pure and separate from [`poll`]'s loop body for the same reason
2981/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
2982/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
2983/// exactly the policy this feature adds, and a policy only exercisable by
2984/// running the whole loop is a policy nobody checks.
2985#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2986enum PermitKind {
2987    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
2988    /// Checked first - a task can be both a land resume and marked
2989    /// [`Task::urgent`], and the resume's own "must not queue behind
2990    /// anything" guarantee takes precedence.
2991    None,
2992    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
2993    /// (never in addition to trying) the ordinary pool. This is what lets
2994    /// an urgent task dispatch while every ordinary slot is already checked
2995    /// out, and what stops a second urgent task from opening a third run: it
2996    /// waits on this same one-slot semaphore rather than falling through to
2997    /// the ordinary one.
2998    Urgent,
2999    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3000    /// above.
3001    Ordinary,
3002}
3003
3004/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3005/// own boolean, already computed by the caller from [`land_resume_state`].
3006fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3007    if priority {
3008        PermitKind::None
3009    } else if urgent {
3010        PermitKind::Urgent
3011    } else {
3012        PermitKind::Ordinary
3013    }
3014}
3015
3016struct DispatchClaim {
3017    task: Task,
3018    claim: crate::queue::Claim,
3019    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3020}
3021
3022/// Claim and re-read before choosing a lane: a queue listing may predate an
3023/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3024fn claim_dispatch(
3025    queue: &Queue,
3026    candidate: &Task,
3027    cooling_down: bool,
3028    ordinary: &Arc<tokio::sync::Semaphore>,
3029    urgent: &Arc<tokio::sync::Semaphore>,
3030) -> Option<DispatchClaim> {
3031    let Ok(claim) = queue.claim(&candidate.id) else {
3032        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3033        return None;
3034    };
3035    let task = match queue.get(&candidate.id) {
3036        Ok(t) if t.status.runnable() => t,
3037        Ok(_) => return None,
3038        Err(e) => {
3039            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3040            return None;
3041        }
3042    };
3043    let resume = land_resume_state(&task);
3044    if resume == LandResume::StillWaiting {
3045        return None;
3046    }
3047    let priority = resume == LandResume::Ready;
3048    if !priority && cooling_down {
3049        return None;
3050    }
3051    // Never borrow an ordinary slot when the single urgent slot is busy.
3052    // Keep scanning other candidates when either pool has no free slot.
3053    let permit = match permit_kind(priority, task.urgent) {
3054        PermitKind::None => None,
3055        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3056        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3057    };
3058    Some(DispatchClaim {
3059        task,
3060        claim,
3061        permit,
3062    })
3063}
3064
3065/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3066/// teardown and cannot skip the teardown on an early return.
3067///
3068/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3069/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3070/// land approval that has since been answered is dispatched outside that
3071/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3072/// the whole point of parking there is that it must not queue behind
3073/// whatever else the loop happens to be running, even at the default of one.
3074/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3075/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3076/// these exemptions is still subject to the interrupt gate below, urgent
3077/// included: a land-resume or urgent candidate is exactly as much "something
3078/// else running" as an ordinary one from the interrupt sequence's point of
3079/// view, and letting either slip through while a run is being parked, or
3080/// while the interrupt task itself has the floor, is precisely the second
3081/// run 75dd's own "at most one run, ever, at once" guarantee must never
3082/// allow - see [`Interrupt`]'s own doc.
3083async fn poll(
3084    opts: &Opts,
3085    queue: &Queue,
3086    status: &Arc<Mutex<Status>>,
3087    home: &Path,
3088    worktrees_root: &Path,
3089    stop: &Stop,
3090    limits: DispatchLimits,
3091) -> Result<()> {
3092    let DispatchLimits {
3093        max_concurrent,
3094        pause_for_interrupts,
3095    } = limits;
3096    // Only consulted by `once`, where a task that just failed is still
3097    // `runnable` and would otherwise be picked up again inside the same drain.
3098    // In the long-running mode a later poll retrying a failed task is the point,
3099    // and the attempt counter is what bounds it.
3100    let mut attempted: Vec<String> = Vec::new();
3101    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
3102    // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
3103    // entirely separate from `sem`: an urgent candidate must dispatch
3104    // alongside whatever `sem` already has checked out, never by waiting for
3105    // one of those ordinary slots to free up and never by growing
3106    // `max_concurrent_runs` itself. Sized at one, not unbounded - see
3107    // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
3108    // first on this same slot rather than opening a third run.
3109    let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
3110    // A quota hit is a fact about the machine, not the task that happened to
3111    // surface it, and every other *ordinary* candidate is no less likely to
3112    // hit the same wall - see the warning below. A land-merge resume is
3113    // exempt: it is a human decision finishing, not a fresh competition, and
3114    // must not sit out a quota cooldown it did not cause.
3115    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
3116    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
3117    let mut conductor = Conductor::new();
3118    // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
3119    // a congested queue would otherwise starve of the fully-idle branch below.
3120    let mut cache_last_checked: Option<Timestamp> = None;
3121    let mut disk_last_checked: Option<Timestamp> = None;
3122    // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
3123    let mut interrupt = Interrupt::Idle;
3124    // The `Pause` handed to each dispatched candidate's own `Runner` - see
3125    // `attempt`'s new parameter - kept here so the tick that decides to park
3126    // a run for an interrupt can reach that specific run's handle and no
3127    // other's. Pruned to whatever is still in flight at the top of every
3128    // tick, so a finished attempt's handle does not linger.
3129    let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
3130        std::collections::HashMap::new();
3131
3132    while !stop.stopped() {
3133        lock(status).polls += 1;
3134
3135        // Reap whatever finished since the last tick without blocking on
3136        // anything still running. `InFlightGuard` already released the slot
3137        // even if the spawned attempt panicked; this only surfaces that it
3138        // happened, since a panic swallowed here otherwise leaves no trace.
3139        while let Some(result) = inflight.try_join_next() {
3140            if let Err(e) = result {
3141                tracing::error!("a spawned attempt did not finish cleanly: {e}");
3142                notices::raise(Notice::error(
3143                    "loop:attempt",
3144                    "A queued attempt ended abnormally; check the task it was running.",
3145                ));
3146            }
3147        }
3148
3149        let swept = sweep_stale_claims(queue, STALE_CLAIM);
3150        if !swept.is_empty() {
3151            tracing::warn!(
3152                "swept {} stale claim(s) left behind by an earlier daemon: {}",
3153                swept.len(),
3154                swept.join(", ")
3155            );
3156        }
3157        // Capture stalled work before reclaiming it. A dead daemon's ordinary
3158        // lock is swept and reclaimed in this same poll, but the conductor
3159        // must still see that it was stranded rather than only its mechanical
3160        // terminal state.
3161        let now = Timestamp::now();
3162
3163        // No run this daemon spawned is mid-compile right now, whether or
3164        // not another candidate is about to start - see
3165        // `maybe_prune_cache_between_runs`'s own doc for why this cannot
3166        // wait for the queue to run dry.
3167        if !stop.busy_now() {
3168            maybe_prune_cache_between_runs(
3169                &opts.repo,
3170                opts,
3171                home,
3172                stop,
3173                &mut cache_last_checked,
3174                now,
3175            )
3176            .await;
3177        }
3178
3179        if cache_check_due(disk_last_checked, now, 30) {
3180            disk_last_checked = Some(now);
3181            if let Ok(cfg) = prepare(&opts.repo, opts) {
3182                crate::retention::sweep(home, &cfg.disk, now).await;
3183                // Shared-cache ownership makes this safe even with other runs
3184                // active. Reclaim idle outputs before asking writers to park.
3185                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3186                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3187                }
3188                for current in lock(status).current.clone() {
3189                    if let Ok(state) = RunState::load_under(&current.run, home)
3190                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3191                    {
3192                        if let Some(pause) = interrupt_pauses.get(&current.task) {
3193                            pause.park_because(reason);
3194                        }
3195                        notices::raise_in(
3196                            home,
3197                            Notice::warn(
3198                                "disk:pressure",
3199                                "Disk pressure persists after cleanup; active runs were asked to checkpoint and park. New starts and resumes wait for free space.",
3200                            ),
3201                        );
3202                    }
3203                }
3204            }
3205        }
3206
3207        let stalled = stalled_tasks(queue, home, now);
3208        let stalled_ids: std::collections::BTreeSet<_> =
3209            stalled.iter().map(|task| task.id.clone()).collect();
3210        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
3211        if !reclaimed.is_empty() {
3212            tracing::warn!(
3213                "reclaimed {} task(s) left `running` by a daemon that never \
3214                 recorded the outcome: {}",
3215                reclaimed.len(),
3216                reclaimed.join(", ")
3217            );
3218        }
3219        let abandoned_runs = reclaim_abandoned_runs(home, now);
3220        if !abandoned_runs.is_empty() {
3221            tracing::warn!(
3222                "failed {} run(s) left behind by a killed process, past every \
3223                 active seat's own timeout: {}",
3224                abandoned_runs.len(),
3225                abandoned_runs.join(", ")
3226            );
3227        }
3228
3229        // `home`, not `ask::Questions::open()`'s own process-global default:
3230        // `poll` is handed its home explicitly precisely so a test can point
3231        // it elsewhere, the same reason `Queue::at` and the status file path
3232        // are parameters rather than resolved here - see `drive`'s own doc.
3233        let questions = Questions::at(home.join("questions"));
3234
3235        // Deterministic: no model, run before the conductor sees anything so
3236        // its input reflects the queue's current, already-resolved state.
3237        repair_choice_offers(&questions);
3238        resolve_blockers(queue, &questions);
3239        apply_choice_actions(queue, &questions, home).await;
3240        triage::apply_answers(queue, &questions);
3241        reconcile_task_questions(queue, &questions);
3242        // Tell the chat a filed task or watched command has ended. Reconciled
3243        // here regardless of how it ended, and started only when no
3244        // upgrade is parking (the draft then waits for a manual resume).
3245        {
3246            let talks = crate::talk::Talks::at(home.join("talks"));
3247            crate::chat_notify::sweep(queue, &talks, home);
3248            crate::chat_watch::sweep(home, &talks);
3249            crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
3250        }
3251
3252        // The conductor gets one look per cycle, right before the loop takes
3253        // its next task, and only when there is something new to look at -
3254        // see `Conductor::worth_a_look`'s own doc for why "stalled is
3255        // non-empty" is the wrong test. Checked before `prepare` so an
3256        // unchanged cycle never pays for a synchronous config load.
3257        let finished: Vec<Task> = finished_tasks(queue)
3258            .into_iter()
3259            .filter(|task| !stalled_ids.contains(&task.id))
3260            // A parked run is waiting for this loop, not for a decision: the
3261            // conductor must not get to hold it or requeue it (a requeue
3262            // sets `fresh_start` and re-competes) before `attempt` resumes.
3263            .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
3264            .collect();
3265        let queued = queued_tasks(queue);
3266        // An empty queue has nothing to arrange. In particular, do not let
3267        // the conductor's initial snapshot cause synchronous config I/O
3268        // between the caller's stop notification and the idle wait below.
3269        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3270            && conductor.worth_a_look(queue, &stalled, &finished)
3271        {
3272            match prepare(&opts.repo, opts) {
3273                Ok(cfg) => {
3274                    conductor
3275                        .maybe_run(
3276                            &cfg,
3277                            &opts.repo,
3278                            queue,
3279                            &questions,
3280                            home,
3281                            &queued,
3282                            &stalled,
3283                            &finished,
3284                            opts.max_attempts,
3285                        )
3286                        .await;
3287                }
3288                Err(e) => {
3289                    tracing::warn!("conductor: no config: {e:#}");
3290                    notices::raise(Notice::warn(
3291                        "loop:no-config",
3292                        "The loop could not read this repository's config, so held tasks are not being triaged.",
3293                    ));
3294                }
3295            }
3296        }
3297
3298        let candidates: Vec<Task> = runnable(queue)
3299            .into_iter()
3300            .filter(|t| !opts.once || !attempted.contains(&t.id))
3301            .collect();
3302
3303        // A task id only stays a key here while its attempt is genuinely in
3304        // flight; `status.current` is the same liveness fact `InFlightGuard`
3305        // maintains for the phone's own status file, so this piggybacks on
3306        // it rather than tracking a second copy of the same thing.
3307        let in_flight: Vec<String> = lock(status)
3308            .current
3309            .iter()
3310            .map(|c| c.task.clone())
3311            .collect();
3312        interrupt_pauses.retain(|id, _| in_flight.contains(id));
3313
3314        interrupt =
3315            advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
3316        if let Interrupt::Parking {
3317            parked,
3318            interrupt_task,
3319        } = &interrupt
3320        {
3321            let reason = format!(
3322                "task {} asked to run first",
3323                crate::run::short_of(interrupt_task)
3324            );
3325            for id in parked {
3326                if let Some(pause) = interrupt_pauses.get(id) {
3327                    pause.park_because(reason.clone());
3328                }
3329            }
3330        }
3331        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3332
3333        let cooling_down =
3334            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
3335
3336        let mut started_any = false;
3337        for candidate in candidates {
3338            if stop.stopped() {
3339                break;
3340            }
3341
3342            let Some(DispatchClaim {
3343                mut task,
3344                claim,
3345                permit,
3346            }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
3347            else {
3348                continue;
3349            };
3350
3351            let task_id = task.id.clone();
3352            attempted.push(task_id.clone());
3353            lock(status).idle = false;
3354            // A stop asked for from here on is "finishing", not "stopped": the
3355            // run gets to reach a terminal status before the loop returns.
3356            stop.enter();
3357            started_any = true;
3358
3359            // A fresh, unshared handle - never `stop.pause()` - so parking
3360            // this run for an interrupt cannot leak into any other run this
3361            // loop ever drives. See `Pause`'s own doc.
3362            let run_pause = crate::graph::Pause::new();
3363            interrupt_pauses.insert(task_id.clone(), run_pause.clone());
3364
3365            let opts = opts.clone();
3366            let queue = queue.clone();
3367            let status = Arc::clone(status);
3368            let stop = stop.clone();
3369            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
3370            inflight.spawn(async move {
3371                // Held for the whole attempt: dropping either at the end of
3372                // this task is what releases the claim and, for an ordinary
3373                // candidate, frees its concurrency slot back to the loop.
3374                let _claim = claim;
3375                let _permit = permit;
3376                // See `InFlightGuard`: this must survive a panic inside `attempt`.
3377                let _inflight = InFlightGuard {
3378                    status: &status,
3379                    stop: &stop,
3380                    task_id: &task_id,
3381                };
3382                let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
3383                lock(&status).completed += 1;
3384                // A quota loss is a fact about the machine, not this task, and
3385                // the next ordinary candidate the loop offers is no less
3386                // likely to hit the same wall: without a cooldown here a
3387                // whole backlog can be run - and failed - in the seconds it
3388                // takes each attempt to notice the CLI is out of quota.
3389                let now = Timestamp::now();
3390                if let Some(until) = cooldown_until(&quota, now) {
3391                    let wait = until.as_second() - now.as_second();
3392                    *lock(&quota_cooldown_until) = Some(until);
3393                    let hint = quota
3394                        .iter()
3395                        .find(|q| q.reset.is_some())
3396                        .and_then(|q| q.reset.as_deref());
3397                    match hint {
3398                        Some(h) => tracing::warn!(
3399                            "quota hit; waiting {wait}s before taking another ordinary task \
3400                             (CLI reported reset: {h})"
3401                        ),
3402                        None => tracing::warn!(
3403                            "quota hit; waiting {wait}s before taking another ordinary task \
3404                             (no reset hint reported)"
3405                        ),
3406                    }
3407                }
3408            });
3409        }
3410
3411        if started_any {
3412            continue;
3413        }
3414
3415        if stop.busy_now() {
3416            // Something started on an earlier tick is still running. Recheck
3417            // soon rather than sleeping out the whole poll interval - a freed
3418            // slot, or a land approval answered mid-run, must not sit idle
3419            // for it.
3420            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3421            continue;
3422        }
3423
3424        // Truly idle: nothing new to start and nothing still running.
3425        lock(status).idle = true;
3426        if opts.once {
3427            // A one-shot drain must perform the same post-work cleanup as a
3428            // daemon that reached a normal idle interval. The startup pass
3429            // cannot see runs or cache files produced by this drain.
3430            janitor(&opts.repo, opts, home, worktrees_root).await;
3431            resweep_superseded_attempts(queue, home);
3432            triage_held(queue, home, opts).await;
3433            break;
3434        }
3435        stop.idle(opts.poll).await;
3436        if stop.stopped() {
3437            continue;
3438        }
3439        // Housekeeping only after a full quiet interval. Running it before
3440        // the first idle wait can block the executor while an operator's
3441        // stop request is waiting to be scheduled, defeating Stop's retained
3442        // wake permit. No run can start while this branch is active, so the
3443        // janitor still never races an in-flight compile.
3444        janitor(&opts.repo, opts, home, worktrees_root).await;
3445        resweep_superseded_attempts(queue, home);
3446        triage_held(queue, home, opts).await;
3447    }
3448
3449    // Never return while a run is still in flight, whichever way the loop
3450    // above exited: a stop only sets a flag - see `serve_until` - and
3451    // returning here while `inflight` still holds spawned work would abandon
3452    // it exactly as a mid-node kill would.
3453    while let Some(result) = inflight.join_next().await {
3454        if let Err(e) = result {
3455            tracing::error!("a spawned attempt did not finish cleanly: {e}");
3456            notices::raise(Notice::error(
3457                "loop:attempt",
3458                "A queued attempt ended abnormally; check the task it was running.",
3459            ));
3460        }
3461    }
3462    Ok(())
3463}
3464
3465/// Run one claimed task to a terminal status and record the outcome.
3466///
3467/// Every transition is flushed to the queue as it happens, so the state on disk
3468/// is what actually occurred rather than what this process still intends to
3469/// write.
3470async fn attempt(
3471    opts: &Opts,
3472    queue: &Queue,
3473    status: &Arc<Mutex<Status>>,
3474    stop: &Stop,
3475    interrupt_pause: crate::graph::Pause,
3476    task: &mut Task,
3477) -> Vec<QuotaLoss> {
3478    let repo = repo_for(task, &opts.repo);
3479    tracing::info!(
3480        "task {} — {} (repo {})",
3481        task.short(),
3482        task.title,
3483        repo.display()
3484    );
3485
3486    // A stop spends no agent resources and uses the saved landing owner.
3487    // Current roster edits, missing attachments or a failed config fetch must
3488    // never turn it into a new implementation, or prevent a PR from closing.
3489    if let Some(previous) = task.runs.last().and_then(|id| RunState::load(id).ok())
3490        && previous
3491            .merge_decision
3492            .as_ref()
3493            .is_some_and(|decision| !decision.closed)
3494        && previous.status != RunStatus::Landing
3495        && !crate::merge_decision::resumable_hold(&previous)
3496    {
3497        task.hold_unrequested_retry(Some(format!("The existing owner stop decision remains held. Inspect run {} and its PR; request an explicit fresh review/decision before further work. No replacement or merge was started.", previous.id)));
3498        record(queue, task);
3499        return Vec::new();
3500    }
3501    let stop_owner = task
3502        .runs
3503        .last()
3504        .and_then(|id| RunState::load(id).ok())
3505        .filter(|state| {
3506            crate::merge_decision::resumable_hold(state)
3507                || state.status == RunStatus::Landing
3508                    && state.land_approval.as_ref().is_some_and(|binding| {
3509                        Questions::open().get(&binding.question).is_ok_and(|q| {
3510                            q.run == state.id
3511                                && q.resolution()
3512                                    .as_deref()
3513                                    .is_some_and(crate::merge_decision::stops)
3514                        })
3515                    })
3516        });
3517    if let Some(owner) = stop_owner {
3518        let mut runner = match Runner::resume(&owner.id) {
3519            Ok(runner) => runner,
3520            Err(e) => {
3521                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
3522                record(queue, task);
3523                return Vec::new();
3524            }
3525        };
3526        runner.on_pause(stop.pause());
3527        runner.watch_interrupt(interrupt_pause);
3528        let quota_before = runner.state.quota.clone();
3529        task.start(owner.id.clone());
3530        record(queue, task);
3531        lock(status).current.push(Current {
3532            task: task.id.clone(),
3533            run: owner.id,
3534        });
3535        runner.state.next_pass_task_entry = true;
3536        let result = runner.execute().await;
3537        return finish_attempt(
3538            opts.max_attempts,
3539            queue,
3540            task,
3541            &runner.state,
3542            &quota_before,
3543            result,
3544        );
3545    }
3546
3547    let unfinished = (!task.fresh_start)
3548        .then(|| unfinished_run(&task.runs, task.short()))
3549        .flatten()
3550        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3551    let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3552    if !task.fresh_start
3553        && task.pr_recovery.is_none()
3554        && task.review_branch.is_none()
3555        && task.resume_override.is_none()
3556        && previous
3557            .as_ref()
3558            .is_some_and(|run| run.retired_to.is_some())
3559        && unfinished.is_none()
3560    {
3561        task.hold_unrequested_retry(Some("Recorded recovery authority is unavailable, no longer resumable or no longer authorized for these instructions. Inspect the retained lineage and select a recovery source explicitly; no replacement competition was started.".into()));
3562        record(queue, task);
3563        return Vec::new();
3564    }
3565
3566    let saved_recovery = previous.as_ref().filter(|run| {
3567        task.replacement.is_none()
3568            && task.pr_recovery.as_ref().is_some_and(|selected| {
3569                selected.check_task(&task.id, &task.instruction).is_ok()
3570                    && selected_starter(selected, Some(run), unfinished.as_deref())
3571                        == Starter::Resume(run.id.clone())
3572            })
3573    });
3574
3575    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
3576    // failure here is the network's or the operator's, not the task's: hold
3577    // without spending an attempt, never fall back to a possibly stale copy.
3578    let explicit = match &task.overrides {
3579        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
3580        Some(_) => opts.config.as_deref(),
3581        None => opts.config.as_deref(),
3582    };
3583    let (mut config, layers) = if let Some(run) = saved_recovery {
3584        // A matching resume owns its resolved configuration and evidence;
3585        // current layers and inherited overrides only configure new work.
3586        let mut saved = run.clone();
3587        if let Err(e) = saved.configure_recovery_resume() {
3588            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
3589            record(queue, task);
3590            return Vec::new();
3591        }
3592        (saved.config, Vec::new())
3593    } else {
3594        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
3595            Ok(loaded) => loaded,
3596            Err(e) => {
3597                let reason = format!("[config] {e:#}");
3598                record_config_failure(task, &e);
3599                task.last_error = Some(reason.clone());
3600                task.hold_machine(Some(reason));
3601                record(queue, task);
3602                return Vec::new();
3603            }
3604        };
3605        if let Err(e) = apply_options(&mut config, opts, task) {
3606            task.hold_manual(Some(format!(
3607                "[config] {e:#}; correct the merge override before releasing the task"
3608            )));
3609            record(queue, task);
3610            return Vec::new();
3611        }
3612        if let Some(selected) = &task.pr_recovery
3613            && let Err(e) = selected.configure(&mut config)
3614        {
3615            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
3616            record(queue, task);
3617            return Vec::new();
3618        }
3619        (config, layers)
3620    };
3621    let config_evidence = crate::pr_recovery::ConfigEvidence {
3622        layers,
3623        overrides: task.overrides.clone(),
3624        daemon_merge: task
3625            .overrides
3626            .as_ref()
3627            .is_none_or(|o| o.inherit_daemon_options)
3628            .then(|| opts.merge.clone())
3629            .flatten(),
3630    };
3631    apply_task_implementers(&mut config, task);
3632    if let Some(replacement) = &task.replacement {
3633        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
3634            old.liveness(false) == Liveness::Dead
3635                && old.merge_decision.as_ref().is_some_and(|d| {
3636                    d.closed
3637                        && d.question == replacement.question
3638                        && d.replacement_run.as_ref().is_none_or(|run| {
3639                            task.runs.last() == Some(run)
3640                                && RunState::load(run).is_ok_and(|current| {
3641                                    current.replaces.as_ref().is_some_and(|pin| {
3642                                        pin.question == replacement.question
3643                                            && pin.agent == replacement.agent
3644                                    })
3645                                })
3646                        })
3647                })
3648        });
3649        if !safe {
3650            task.hold_manual(Some("Replacement ownership cannot be confirmed, or a replacement run was already minted before a crash. Inspect the task and its linked runs; no second replacement was started.".into()));
3651            record(queue, task);
3652            return Vec::new();
3653        }
3654        match config.agent(&replacement.agent) {
3655            Ok(agent) if crate::agent::installed(agent) => {}
3656            _ => {
3657                task.hold_manual(Some(format!("Selected implementer `{}` is unavailable or no longer configured. No substitute was dispatched. Restore it and explicitly release the task.", replacement.agent)));
3658                record(queue, task);
3659                return Vec::new();
3660            }
3661        }
3662        config.graph.implementers = 1;
3663        config.graph.land_approval = true;
3664        config.merge.mode = MergeMode::Pr;
3665        config.graph.selected_implementer = Some(replacement.agent.clone());
3666    }
3667    let p = phrases(&config.graph.language);
3668    let start_failed = p.could_not_start;
3669    // Resolve once for both admission and settlement. Review-only runs do not
3670    // have seed records, and may rebase later; neither fact can refund a failed
3671    // automatic generation. Include an explicit review source's current head.
3672    if let Ok(base) =
3673        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
3674            .await
3675        && let Ok(head) =
3676            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
3677    {
3678        let seeds = crate::refs::resolve(
3679            &repo,
3680            &head,
3681            &config.merge.remote,
3682            &format!("{}\n{}", task.title, instruction_for(task)),
3683        )
3684        .await;
3685        let mut inputs = crate::queue::recovery_inputs(&seeds);
3686        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
3687            let source = crate::git::rev_parse(&repo, branch)
3688                .await
3689                .unwrap_or_default();
3690            inputs.push_str(&format!(";review:{branch}:{source}"));
3691        }
3692        if let Some(reason) = task.recovery_exhausted(
3693            &head,
3694            &inputs,
3695            task.attempt_limit
3696                .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
3697        ) {
3698            task.hold_unrequested_retry(Some(reason));
3699            record(queue, task);
3700            return Vec::new();
3701        }
3702        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
3703    }
3704
3705    // The free-space gate, checked *before* anything is minted: a task that
3706    // waits out a full disk costs nothing yet, and must not spend an attempt
3707    // or start a run the machine cannot finish. Held tasks stay in the list
3708    // for the human to see, and `magi task release` re-queues them when space
3709    // comes back - the same recovery as any other hold. A volume whose free
3710    // space cannot be measured closes the gate too: starting a run blind on a
3711    // disk that may be full is how the machine ends up with 6.7 GB free.
3712    if let Some(reason) = disk_gate(&repo, &config) {
3713        task.notice_cause("disk-space", None, None);
3714        task.last_error = Some(reason.clone());
3715        task.hold_machine(Some(reason.clone()));
3716        record(queue, task);
3717        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
3718        // Stable wording - the free-space figures live in the task's hold
3719        // reason, and changing numbers would relight the bell every poll.
3720        notices::raise(
3721            Notice::warn(
3722                &format!("disk:{}", repo.display()),
3723                "A task was held for want of free disk space; free some, then release it from the queue.",
3724            )
3725            .link(Link::Task {
3726                id: task.id.clone(),
3727            }),
3728        );
3729        return Vec::new();
3730    }
3731
3732    // A resumable run of this task is carried on, never re-competed. The
3733    // candidates are built and paid for, and a fresh competition races a
3734    // second implementation against them.
3735    //
3736    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
3737    // started 3cbf on the same task a moment later, duplicating two and a
3738    // half hours of agent work. Then b25f stalled on a judge that timed out
3739    // and one that answered with no JSON - `quota: 0`, so nothing the machine
3740    // was to blame for - and 4043 started **one second** later, buying three
3741    // fresh implementations to reach the same panel. `RunStatus::resumable`
3742    // rather than `!done()` is what catches the second case: a stall is
3743    // terminal, and its cheap recovery re-asks only the absent seats.
3744    //
3745    // A load failure is warned about rather than silently read as "not
3746    // resumable": the alternative is exactly what let a schema mismatch on
3747    // run `eba2` fall through to a full re-competition with nobody told why.
3748    // `crate::conduct` is what actually offers a better answer than
3749    // `Runner::start` here (see `Recovery::Review`), once this task's next
3750    // failure shows it up as `held`/`failed` with the run state unreadable.
3751    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
3752    // branch survived, and this reopens exactly that branch as a
3753    // review-only pass rather than resuming or competing again. Consumed
3754    // (cleared) here whichever way this goes, so it never outlives this one
3755    // attempt - see `queue::Task::review_branch`.
3756    let review_branch = take_review_branch(task, previous.as_ref());
3757    let branch_exists = match &review_branch {
3758        Some(branch) => crate::git::branch_exists(&repo, branch)
3759            .await
3760            .unwrap_or(false),
3761        None => false,
3762    };
3763    // An explicit `magi review <branch>` is reviewed whatever happens to the
3764    // branch unless an explicit implementer change requires fresh work. An
3765    // unfinished run of the same task still wins, so a retry resumes.
3766    let proposed = match (&review_branch, &unfinished, &task.review_of) {
3767        (None, None, Some(branch)) => Starter::Review(branch.clone()),
3768        _ => choose_starter(
3769            review_branch.as_deref(),
3770            branch_exists,
3771            unfinished.as_deref(),
3772        ),
3773    };
3774    let retry_selected = task.replacement.is_some()
3775        && task.resumption.is_some()
3776        && !task.fresh_start
3777        && previous.as_ref().is_some_and(|run| {
3778            run.replaces.is_some()
3779                && ((run.status == RunStatus::Failed && run.viable().is_empty())
3780                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
3781        });
3782    let stop_pin = task
3783        .resume_override
3784        .as_ref()
3785        .filter(|pin| {
3786            Questions::open().get(&pin.question_id).is_ok_and(|q| {
3787                q.node == land::APPROVAL_NODE
3788                    && q.resolution()
3789                        .as_deref()
3790                        .is_some_and(crate::merge_decision::stops)
3791            })
3792        })
3793        .and_then(|pin| pin.pinned_run.clone());
3794    let starter = if let Some(run) = stop_pin {
3795        // Stop actions resume their exact owner even after seat-count edits;
3796        // they must never fall through to implementation or a takeover.
3797        Starter::Resume(run)
3798    } else if retry_selected {
3799        Starter::Resume(previous.as_ref().unwrap().id.clone())
3800    } else if let Some(selected) = &task.pr_recovery {
3801        if selected.check_task(&task.id, &task.instruction).is_ok() {
3802            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3803        } else {
3804            Starter::Review(selected.branch.clone())
3805        }
3806    } else {
3807        starter_with_implementers(task, previous.as_ref(), proposed)
3808    };
3809    // An explicit resume pin must never degrade into a new competition or
3810    // takeover, including when its run stops being eligible after the answer.
3811    if let Some(pin) = &task.resume_override
3812        && let Some(run) = &pin.pinned_run
3813        && starter != Starter::Resume(run.clone())
3814    {
3815        let run = run.clone();
3816        task.notice_cause("resume-owner", Some(&run), None);
3817        task.hold_machine(Some(format!(
3818            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3819            task.id
3820        )));
3821        record(queue, task);
3822        return Vec::new();
3823    }
3824    if task.replacement.is_some()
3825        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
3826        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
3827    {
3828        task.hold_manual(Some("The selected replacement already has an attempt. It cannot be resumed safely; inspect its saved pin and restore the existing run. No additional replacement was started.".into()));
3829        record(queue, task);
3830        return Vec::new();
3831    }
3832    if let Some(reason) = retained_attempt_hold(
3833        task,
3834        &starter,
3835        config.disk.retained_attempt_limit,
3836        RunState::load,
3837    ) {
3838        // The review choice was consumed above. Preserve it across this hold
3839        // so a later release cannot silently become a fresh implementation.
3840        if let Starter::Review(branch) = &starter {
3841            task.review_branch = Some(branch.clone());
3842        }
3843        task.hold_unrequested_retry(Some(reason));
3844        record(queue, task);
3845        return Vec::new();
3846    }
3847    // Absolute paths of the files the task was filed with, re-read from the
3848    // task now so a file attached while it was held reaches a resumed run
3849    // too. A stored name whose file has gone is an error before any agent is
3850    // paid for, never a silent omission the implementer cannot notice.
3851    let attachments = match task_attachments(queue, task) {
3852        Ok(a) => a,
3853        Err(e) => {
3854            task.attempts += 1;
3855            task.fail_startup_target(
3856                "startup-attachments",
3857                e.name.clone(),
3858                format!("{start_failed}{e:#}"),
3859                opts.max_attempts,
3860            );
3861            record(queue, task);
3862            return Vec::new();
3863        }
3864    };
3865    let startup_pause = stop.pause();
3866    let startup_interrupt = interrupt_pause.clone();
3867    let wait = crate::repo_lock::WaitPolicy::new(
3868        Duration::from_secs(config.graph.timeout_resource_wait),
3869        move || startup_pause.parked() || startup_interrupt.parked(),
3870    );
3871    // Startup includes review takeover and recovery. Do not embed its large
3872    // future in both the wait scope and the surrounding attempt stack frame.
3873    let started = wait.scope(Box::pin(async { match &starter {
3874        Starter::Review(_) if task.pr_recovery.is_some() => {
3875            let selected = task.pr_recovery.clone().expect("selected recovery");
3876            match selected.check_task(&task.id, &task.instruction) {
3877                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3878                    .await
3879                    .map(|mut r| {
3880                        r.state.attachments = attachments.clone();
3881                        r
3882                    }),
3883                Err(e) => Err(e),
3884            }
3885        }
3886        Starter::Review(branch) => {
3887            tracing::info!(
3888                "task {} reopens `{branch}` as a review-only pass",
3889                task.short()
3890            );
3891            // Every earlier attempt is superseded by the one being minted
3892            // now, so a branch one of them still holds may be taken over.
3893            let takeover = crate::handover::Takeover {
3894                earlier: task.earlier_attempts().to_vec(),
3895                home: crate::run::home(),
3896                choice: take_divergence_answer(branch, &config.merge.remote, task),
3897                task_instruction: Some(instruction_for(task)),
3898            };
3899            Runner::review_taking_over(
3900                &repo,
3901                branch,
3902                config,
3903                Some(takeover),
3904                crate::run::Origin::queue(&task.id),
3905            )
3906            .await
3907        }
3908        Starter::Resume(id) => {
3909            tracing::info!("resuming run {id} rather than competing again");
3910            Runner::resume(id).and_then(|mut r| {
3911                if retry_selected {
3912                    // The explicit queue release retries this same pinned
3913                    // implementation, preserving the attempt and worktrees.
3914                    for candidate in &mut r.state.candidates {
3915                        candidate.failed = None;
3916                        candidate.empty = false;
3917                        candidate.commits = 0;
3918                    }
3919                    r.state.status = RunStatus::Implementing;
3920                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
3921                }
3922                if r.state.prep_failure.is_some() {
3923                    let approval = task
3924                        .resumption
3925                        .as_ref()
3926                        .context("preparation retry requires an explicit task release")?;
3927                    r.retry_preparation(approval.at)?;
3928                }
3929                if let Some(instruction) =
3930                    prepare_instruction(&starter, Some(&r.state.instruction), task)
3931                {
3932                    r.state.instruction = instruction;
3933                }
3934                r.state.attachments = attachments.clone();
3935                if task.replacement.is_some() {
3936                    r.state.config.merge.mode = MergeMode::Pr;
3937                    r.state.config.graph.land_approval = true;
3938                }
3939                // Replacements publish a new PR and ask again. Selected PR
3940                // recoveries keep their saved disposition; ordinary runs can
3941                // retain the task's merge override.
3942                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
3943                    .overrides
3944                    .as_ref()
3945                    .and_then(|o| o.merge.as_deref())
3946                    .and_then(|m| merge_mode(m).ok())
3947                {
3948                    r.state.config.merge.mode = mode;
3949                }
3950                Ok(r)
3951            })
3952        }
3953        Starter::Start => {
3954            if let Some(branch) = &review_branch {
3955                tracing::warn!(
3956                    "conductor chose review for task {} but branch `{branch}` no longer \
3957                     exists; requeuing as a fresh competition instead",
3958                    task.short()
3959                );
3960            }
3961            let instruction = prepare_instruction(&starter, None, task)
3962                .unwrap_or_else(|| task.instruction.clone());
3963            Runner::start_naming(
3964                &repo,
3965                instruction,
3966                &task.title,
3967                config,
3968                crate::run::Origin::queue(&task.id),
3969            )
3970            .await
3971            .map(|mut r| {
3972                r.state.attachments = attachments.clone();
3973                r
3974            })
3975        }
3976    }})).await;
3977    let mut runner = match started {
3978        Ok(r) => r,
3979        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
3980            task.last_error = Some(e.to_string());
3981            if stop.parking() || interrupt_pause.parked() {
3982                let attempts = task.attempts;
3983                task.park(e.to_string());
3984                // Startup has not spent an attempt to refund.
3985                task.attempts = attempts;
3986            } else {
3987                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
3988            }
3989            record(queue, task);
3990            return Vec::new();
3991        }
3992        // A branch an earlier attempt still holds and magi will not release
3993        // by itself is the operator's call, not a failed attempt: hold the
3994        // task with the reason, spend nothing, and say so on the bell.
3995        Err(e) if task.pr_recovery.is_some() => {
3996            task.startup_notice_cause("startup-public-head");
3997            task.attempts += 1;
3998            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3999                task.link_run(&partial.run);
4000                task.record_pass(&partial.run, 0, task.attempts, None);
4001            }
4002            task.last_error = Some(format!("{start_failed}{e:#}"));
4003            task.hold_unrequested_retry(Some(format!(
4004                "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."
4005            )));
4006            record(queue, task);
4007            return Vec::new();
4008        }
4009        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4010            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4011                Some(r) => (p.handover_refused)(r),
4012                None => format!("{e:#}"),
4013            };
4014            task.startup_notice_cause("startup-handover");
4015            let reason = format!("{start_failed}{detail}");
4016            task.last_error = Some(reason.clone());
4017            // Consumed above by `take`; keep it so the released task retries
4018            // as a review of this same branch.
4019            let branch = match &starter {
4020                Starter::Review(branch) => Some(branch.clone()),
4021                _ => None,
4022            };
4023            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4024            // one page; the guidance rides in the reason, fixed per state so a
4025            // re-put never changes the wording and relights it.
4026            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4027            record(queue, task);
4028            tracing::warn!(
4029                "holding {} for a branch it cannot take over: {e:#}",
4030                task.short()
4031            );
4032            return Vec::new();
4033        }
4034        // A branch that differs between here and the remote in ways magi
4035        // cannot prove are the same change is a decision for the owner, not a
4036        // failed attempt: ask with both sides laid out, spend no attempt, and
4037        // let the answer requeue the task.
4038        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4039            let d = e
4040                .downcast_ref::<crate::reconcile::Diverged>()
4041                .expect("checked by the guard");
4042            let mut q = ask::Question::new(
4043                task.id.clone(),
4044                crate::reconcile::NODE.to_owned(),
4045                crate::reconcile::SEAT.to_owned(),
4046                d.summary(),
4047                d.detail(),
4048                d.choices(),
4049            );
4050            match Questions::open().put(&mut q) {
4051                Ok(()) => {
4052                    task.last_error = Some(format!("{e:#}"));
4053                    // Consumed above by `take`; the answer has to reach a review
4054                    // of this same branch, so keep pointing the task at it.
4055                    task.review_branch = Some(d.branch.clone());
4056                    task.review_instruction = Some(task.instruction.clone());
4057                    task.block(vec![q.id.clone()], Some(d.summary()));
4058                }
4059                Err(put) => {
4060                    tracing::warn!("could not file the divergence question: {put:#}");
4061                    task.attempts += 1;
4062                    task.fail_startup(
4063                        "startup-question-store",
4064                        format!("{start_failed}{e:#}"),
4065                        opts.max_attempts,
4066                    );
4067                }
4068            }
4069            record(queue, task);
4070            return Vec::new();
4071        }
4072        Err(e) => {
4073            // The answer was stale and nothing was applied: keep pointing at
4074            // the branch so the next attempt asks again against its new tips.
4075            // Nothing went wrong with the task, so no attempt is spent: a
4076            // budget one short of its limit must not hold it instead of
4077            // letting the question be asked again.
4078            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4079                && let Starter::Review(branch) = &starter
4080            {
4081                task.review_branch = Some(branch.clone());
4082                task.review_instruction = Some(task.instruction.clone());
4083                task.last_error = Some(format!("{start_failed}{e:#}"));
4084                task.status = crate::queue::TaskStatus::Failed;
4085                record(queue, task);
4086                return Vec::new();
4087            }
4088            task.attempts += 1;
4089            task.last_error = Some(format!("{start_failed}{e:#}"));
4090            task.startup_notice_cause("startup-source");
4091            task.hold_unrequested_retry(Some(format!(
4092                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4093            )));
4094            record(queue, task);
4095            return Vec::new();
4096        }
4097    };
4098    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4099        runner.state.recovery_config = Some(config_evidence);
4100    }
4101    if let Some(replacement) = &task.replacement {
4102        if matches!(starter, Starter::Start) {
4103            runner.state.instruction.push_str(&format!(
4104                "\n\n# Replacement review context\n{}",
4105                replacement.context
4106            ));
4107        }
4108        runner.state.replaces = Some(replacement.clone());
4109        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4110        if let Ok(mut old) = RunState::load(&replacement.run)
4111            && let Some(d) = &mut old.merge_decision
4112        {
4113            d.replacement_run = Some(runner.state.id.clone());
4114            old.event(
4115                "replacement",
4116                format!(
4117                    "replacement run {} owns the next attempt; old PR remains closed",
4118                    runner.state.id
4119                ),
4120            );
4121            if let Err(e) = old.save() {
4122                task.hold_manual(Some(format!(
4123                    "Could not link replacement history: {e}; no agents dispatched"
4124                )));
4125                record(queue, task);
4126                return Vec::new();
4127            }
4128        }
4129    }
4130    runner.state.task_instruction = Some(task.instruction.clone());
4131    // The follow-up depth is fixed now, while the task certainly exists:
4132    // deleting it later must not reset the cap (`crate::followup`).
4133    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4134    if runner.state.origin_chat.is_none() {
4135        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4136    }
4137    // A stop that means "park" reaches the graph through this handle.
4138    runner.on_pause(stop.pause());
4139    // `poll`'s interrupt scheduler reaches this one run - and no other -
4140    // through this handle. See `Pause`'s own doc for why these are never
4141    // the same one.
4142    runner.watch_interrupt(interrupt_pause);
4143
4144    // `start` has minted the run, so the task can now point at it. Persisting
4145    // `Running` before `execute` is what makes a crash mid-run legible.
4146    let run = runner.state.id.clone();
4147    task.start(run.clone());
4148    record(queue, task);
4149    lock(status).current.push(Current {
4150        task: task.id.clone(),
4151        run,
4152    });
4153
4154    // `RunState::quota` is the run's whole history across every resume, so
4155    // only what this execution added may arm the cooldown or earn a refund.
4156    let quota_before = runner.state.quota.clone();
4157    runner.state.next_pass_task_entry = true;
4158    let result = runner.execute().await;
4159    finish_attempt(
4160        opts.max_attempts,
4161        queue,
4162        task,
4163        &runner.state,
4164        &quota_before,
4165        result,
4166    )
4167}
4168
4169/// Settle `task` after its run executed: the verdict, the diagnosis, the
4170/// supersession of earlier attempts and the save. Shared by the loop and by
4171/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4172/// Returns the quota losses this execution added to the run.
4173pub fn finish_attempt(
4174    max_attempts: usize,
4175    queue: &Queue,
4176    task: &mut Task,
4177    state: &RunState,
4178    quota_before: &[QuotaLoss],
4179    result: Result<()>,
4180) -> Vec<QuotaLoss> {
4181    let detail = match result {
4182        Ok(()) => describe(state),
4183        Err(e) => format!("{e:#}"),
4184    };
4185    let fresh = losses_this_attempt(quota_before, &state.quota);
4186    let verdict = Verdict {
4187        status: state.status,
4188        // A run that opened a pull request handed its work over, whatever the
4189        // gate then decided about merging it.
4190        left_pr: state.pr.is_some(),
4191        // Only a rate limit earns the task its attempt back - and only one
4192        // suffered now: a refund justified by a previous session's loss is
4193        // the same mistake as re-arming the cooldown from it. A stalled run
4194        // resumed without hitting quota again therefore spends its attempt,
4195        // like any other failure of the task's own.
4196        quota_hit: !fresh.is_empty(),
4197        // A run that parked was asked to stop; that is not a failure and must
4198        // not spend an attempt, or replacing the binary a few times would
4199        // exhaust a task's budget without an agent ever misbehaving.
4200        parked: state.parked,
4201        // A quota loss that left nothing viable is the same machine fact as a
4202        // `Stalled` quota loss; see `settle`'s doc table.
4203        no_viable_candidates: state.viable().is_empty(),
4204    };
4205    if let Some(replacement) = &state.replaces
4206        && let Some(pr) = &state.pr
4207        && let Ok(mut old) = RunState::load(&replacement.run)
4208        && let Some(d) = &mut old.merge_decision
4209    {
4210        d.replacement_pr = Some(pr.url.clone());
4211        let _ = old.save();
4212    }
4213    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4214    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4215        task.hold_unrequested_retry(Some(format!(
4216            "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
4217        )));
4218    }
4219    if task.status == TaskStatus::Done {
4220        supersede_prior_runs(task, &crate::run::home());
4221    }
4222    record(queue, task);
4223    tracing::info!(
4224        "task {} is {} after run {} ({})",
4225        task.short(),
4226        task.status.as_str(),
4227        state.short(),
4228        label(state.status)
4229    );
4230    fresh
4231}
4232
4233/// A task a hand-started run leaves runnable (failed with attempts to spare,
4234/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4235/// later must not spend agent calls on it. `magi task release` retries.
4236pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4237    // A run parked on the owner's word about a withheld PR title/body is not a
4238    // failure nobody asked to retry: it resumes (answer, or the neutral text on
4239    // the deadline) the moment a loop serves the queue, via `land_resume_state`.
4240    // Holding it would keep it from ever being a candidate.
4241    let waits_on_owner = withheld_text_wait(task).is_some();
4242    if task.status.runnable()
4243        && !waits_on_owner
4244        && !(task.fresh_start && task.replacement.is_some())
4245    {
4246        let why = task.last_error.clone().map_or_else(
4247            || "the run did not finish".to_owned(),
4248            |e| format!("the run did not finish: {e}"),
4249        );
4250        task.hold_unrequested_retry(Some(format!(
4251            "{why}. It was started by hand, so it is not retried \
4252             automatically; `magi task release` retries it."
4253        )));
4254        record(queue, task);
4255    }
4256}
4257
4258/// Whether an attempt at a task whose newest run is `run` would resume that
4259/// run rather than start a fresh competition. `magi run --resume` hands a run
4260/// to a live loop only when this holds.
4261#[must_use]
4262pub fn loop_would_resume(run: &str) -> bool {
4263    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4264}
4265
4266/// A loop in another process that is alive right now: a fresh heartbeat in
4267/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4268/// carries the pid it published (`None` inside when it published none - a
4269/// fresh heartbeat is still evidence of a live loop).
4270///
4271/// The one judgement of "is somebody else serving this queue", shared by the
4272/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4273/// deciding whether to hand a task to the loop. A claim file proves nothing
4274/// here: whether a claim succeeds says nothing about whether its owner lives.
4275#[must_use]
4276pub fn foreign_loop(
4277    reading: Option<&Reading>,
4278    now: Timestamp,
4279    own_pid: u32,
4280) -> Option<Option<u32>> {
4281    let reading = reading.filter(|r| r.running(now))?;
4282    match reading.pid {
4283        Some(pid) if pid == own_pid => None,
4284        pid => Some(pid),
4285    }
4286}
4287
4288/// Run one task this process has claimed, in this process, through exactly the
4289/// attempt a daemon would make: the same starter choice (start, resume,
4290/// review), the same `Task::start` / `settle` transitions, attempt counting,
4291/// quota refund and parking. No second dispatcher - `magi run` and `magi
4292/// review` call this when no daemon is alive.
4293///
4294/// The caller holds the [`Queue::claim`] for the whole call, which is what
4295/// keeps a daemon that starts meanwhile from taking the task.
4296///
4297/// The one deliberate difference from the loop: a task the attempt leaves
4298/// runnable (failed with attempts to spare, or requeued) is **held** instead.
4299/// Nobody asked for a retry, and a daemon starting later must not spend agent
4300/// calls re-running a hand-started task behind the operator's back;
4301/// `magi task release` is the explicit retry.
4302pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4303    let status = Arc::new(Mutex::new(Status::new()));
4304    let stop = Stop::new();
4305    // An attempt embeds startup and graph futures. Keep it off the standalone
4306    // caller's stack, on both the initial execution and withheld-text resume.
4307    Box::pin(attempt(
4308        opts,
4309        queue,
4310        &status,
4311        &stop,
4312        crate::graph::Pause::new(),
4313        task,
4314    ))
4315    .await;
4316    // A run parked on the owner's word about a withheld PR title/body has no
4317    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
4318    // here with the claim still held, and resume once the question is settled
4319    // (answered, or abandoned at its deadline -> the neutral text).
4320    // A rejected reply files one more question (the gate asks at most twice),
4321    // so after a resume the run may be waiting again: keep going, with a fresh
4322    // limit for the new question. `resumes` bounds it even if a resume parks
4323    // without asking anything new.
4324    let mut resumes = 0;
4325    while resumes < MAX_WITHHELD_RESUMES {
4326        let Some(timeout) = withheld_text_wait(task) else {
4327            break;
4328        };
4329        eprintln!(
4330            "waiting for the owner's answer on a withheld pull request text \
4331             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4332        );
4333        // The deadline abandons the question itself; the extra margin only
4334        // covers an abandon that could not be saved.
4335        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4336        let ready = loop {
4337            match land_resume_state(task) {
4338                LandResume::StillWaiting if std::time::Instant::now() < limit => {
4339                    tokio::time::sleep(WITHHELD_POLL).await;
4340                }
4341                LandResume::Ready => break true,
4342                _ => break false,
4343            }
4344        };
4345        if !ready {
4346            break;
4347        }
4348        resumes += 1;
4349        Box::pin(attempt(
4350            opts,
4351            queue,
4352            &status,
4353            &stop,
4354            crate::graph::Pause::new(),
4355            task,
4356        ))
4357        .await;
4358    }
4359    hold_if_runnable(queue, task);
4360}
4361
4362/// Resumes an in-process run makes for withheld-text questions: the gate asks
4363/// at most twice, plus one for a resume that asks nothing new.
4364const MAX_WITHHELD_RESUMES: u32 = 3;
4365
4366/// How often an in-process run rechecks its withheld-text question.
4367const WITHHELD_POLL: Duration = Duration::from_secs(15);
4368
4369/// The `answer_timeout` (seconds) of the task's last run when that run is
4370/// parked on an unresolved withheld-text question; `None` otherwise.
4371fn withheld_text_wait(task: &Task) -> Option<u64> {
4372    let id = task.runs.last()?;
4373    let s = RunState::load(id).ok()?;
4374    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
4375        .then_some(s.config.graph.answer_timeout)
4376}
4377
4378/// The quota losses `after` holds that `before` did not: what one execution
4379/// suffered, as opposed to the run's history.
4380///
4381/// Compared by value rather than by length or position because
4382/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
4383/// the vector can shrink and shift under a resume. A retried seat that hits
4384/// quota again is a `push` with a new `at`, so it shows up as new here.
4385/// `reclaim` deliberately keeps reading the whole history: after a crash there
4386/// is no attempt boundary to diff against.
4387fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
4388    after
4389        .iter()
4390        .filter(|q| !before.contains(q))
4391        .cloned()
4392        .collect()
4393}
4394
4395/// When the loop-wide quota cooldown should end, given this attempt's losses;
4396/// `None` when there were none. Reset-hint parsing and the cap live here.
4397fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
4398    if quota.is_empty() {
4399        return None;
4400    }
4401    let with_hint = quota.iter().find(|q| q.reset.is_some());
4402    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
4403    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
4404    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
4405    Some(
4406        now.checked_add(jiff::SignedDuration::from_secs(secs))
4407            .unwrap_or(Timestamp::MAX),
4408    )
4409}
4410
4411/// An explicit task count must agree with a run before any resume.
4412fn implementers_match(task: &Task, state: &RunState) -> bool {
4413    task.replacement.as_ref().map_or_else(
4414        || {
4415            task.implementers()
4416                .is_none_or(|n| n == state.config.graph.implementers)
4417        },
4418        |replacement| {
4419            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
4420                && state.config.graph.implementers == 1
4421        },
4422    )
4423}
4424
4425/// Never resume or take over candidate work built for a different seat count.
4426fn starter_with_implementers(
4427    task: &Task,
4428    previous: Option<&RunState>,
4429    proposed: Starter,
4430) -> Starter {
4431    if previous.is_some_and(|s| !implementers_match(task, s)) {
4432        task.review_of
4433            .as_ref()
4434            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
4435    } else {
4436        proposed
4437    }
4438}
4439
4440/// Apply this task's explicit count to the new attempt, without changing defaults.
4441fn apply_task_implementers(config: &mut Config, task: &Task) {
4442    if let Some(n) = task.implementers() {
4443        config.graph.implementers = n;
4444    }
4445}
4446
4447/// [`prepare`] for one task: its own `--config` and command-line overrides
4448/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
4449/// over the loop's, so handing a hand-started task to a daemon changes nothing
4450/// about what it does.
4451#[cfg(test)]
4452fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
4453    let explicit = match &task.overrides {
4454        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4455        _ => opts.config.as_deref(),
4456    };
4457    let (mut config, _) = Config::discover(repo, explicit)?;
4458    apply_options(&mut config, opts, task)?;
4459    Ok(config)
4460}
4461
4462fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
4463    if task
4464        .overrides
4465        .as_ref()
4466        .is_none_or(|o| o.inherit_daemon_options)
4467        && let Some(mode) = opts.merge.as_deref()
4468    {
4469        config.merge.mode = merge_mode(mode)?;
4470    }
4471    if let Some(o) = &task.overrides {
4472        o.apply(config);
4473    }
4474    Ok(())
4475}
4476
4477/// Load the config for a task's repository, with the merge override applied.
4478fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
4479    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
4480    if let Some(mode) = &opts.merge {
4481        config.merge.mode = merge_mode(mode)?;
4482    }
4483    Ok(config)
4484}
4485
4486/// Prune the shared build cache back under its cap at a safe boundary
4487/// between runs, so a queue that never empties - and so never reaches
4488/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
4489/// does not leave the cache to grow unchecked for as long as the backlog
4490/// lasts.
4491///
4492/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
4493/// same liveness fact the idle branch's own janitor call rests on - no run
4494/// this daemon spawned is still mid-compile - so pruning here races nothing.
4495/// The caller must not call this while a run is in flight; there is no
4496/// second `busy_now()` check inside this function, on purpose, because there
4497/// is nothing left to check that `busy_now()` has not already answered.
4498///
4499/// A stop that has already been asked for *is* checked here, for a different
4500/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
4501/// synchronously before it decides anything, so the poll loop cannot get back
4502/// to its own `stopped()` test until that walk is over — and a loop already
4503/// on its way out must not make the operator wait out housekeeping it is
4504/// about to stop needing. This is the same call the idle branch makes when it
4505/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
4506/// it matters more here: `busy_now()` is false throughout, so
4507/// [`Stop::finishing`] would report a stop as already landed while the walk
4508/// still held the loop. Nothing is lost by skipping — the cap is a standing
4509/// policy, and the next daemon's startup pass measures the same cache.
4510///
4511/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
4512/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
4513/// and the next has not yet claimed a task, which can be every few
4514/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
4515/// more than the growth it is guarding against.
4516async fn maybe_prune_cache_between_runs(
4517    repo: &Path,
4518    opts: &Opts,
4519    home: &Path,
4520    stop: &Stop,
4521    last_checked: &mut Option<Timestamp>,
4522    now: Timestamp,
4523) {
4524    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
4525        return;
4526    }
4527    *last_checked = Some(now);
4528    let cfg = match prepare(repo, opts) {
4529        Ok(cfg) => cfg,
4530        Err(e) => {
4531            tracing::warn!("cache check: no config: {e:#}");
4532            return;
4533        }
4534    };
4535    match clean::prune_cache_if_over_limit(&cfg, home) {
4536        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
4537            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
4538            pruned.files,
4539            pruned.freed
4540        ),
4541        Ok(_) => {}
4542        Err(e) => {
4543            tracing::warn!("housekeep: prune cache: {e:#}");
4544            notices::raise_in(
4545                home,
4546                Notice::warn(
4547                    "housekeep:cache",
4548                    "Pruning the shared build cache failed; disk usage may keep growing.",
4549                ),
4550            );
4551        }
4552    }
4553}
4554
4555/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
4556/// now, given when it last did (if ever). Pure, so the cadence is asserted
4557/// directly rather than by waiting out real minutes in a test.
4558fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
4559    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
4560}
4561
4562/// The disk janitor, with its housekeeping logged rather than fatal.
4563///
4564/// Called only at the loop's idle points, for the reason the caller documents:
4565/// a prune racing a live compile would delete files mid-build. The config is
4566/// re-read on every call because the repository that just ran may not be the
4567/// daemon's own default, and the cache directory is a repository fact.
4568///
4569/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
4570/// and [`crate::run::default_worktree_root`] read here, for the same reason
4571/// [`drive`] takes its queue and status file rather than resolving them: a
4572/// test driving the loop must not reach through to the operator's real home
4573/// or worktree bay just because the janitor runs on every idle tick.
4574/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
4575/// to get wrong silently - a test's `home` was already isolated, but nothing
4576/// exercised the parameter next to it, so a real worktree bay stayed wired in
4577/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
4578/// it for real, every test in this file that drives the loop at all started
4579/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
4580async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
4581    let cfg = match prepare(repo, opts) {
4582        Ok(cfg) => cfg,
4583        Err(e) => {
4584            tracing::warn!("housekeep: no config: {e:#}");
4585            return;
4586        }
4587    };
4588    // A run's own worktree lives under `config.graph.worktree_root` when the
4589    // repository sets one - the same precedence `RunState::worktree_root`
4590    // uses - and `worktrees_root` only stands in for the *default* an
4591    // unconfigured repository resolves to (see this function's own
4592    // parameter, or the test fixture wiring one to a fake path). Housekeeping
4593    // that always swept the default regardless of this override would never
4594    // see, and so never reclaim, a single worktree for a repository that
4595    // relocated them elsewhere.
4596    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
4597    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
4598    // Reported whenever there is anything to say, not only when `folded > 0`:
4599    // the incident this exists to prevent was 90 of 93 runs skipped and 0
4600    // folded, on every single pass, for months - a report gated on `folded`
4601    // would have stayed silent through every one of them.
4602    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
4603        let mut extra = Vec::new();
4604        if out.unreadable > 0 {
4605            extra.push(format!("{} unreadable", out.unreadable));
4606        }
4607        if out.orphaned_worktrees > 0 {
4608            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
4609        }
4610        let detail = if extra.is_empty() {
4611            String::new()
4612        } else {
4613            format!(" ({})", extra.join(", "))
4614        };
4615        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
4616    }
4617    if out.external_merges_recorded > 0 {
4618        tracing::info!(
4619            "housekeep: recorded {} run(s) as merged externally",
4620            out.external_merges_recorded
4621        );
4622    }
4623    if out.stale_pr_states_repaired > 0 {
4624        tracing::info!(
4625            "housekeep: rewrote {} run record(s) whose pull request had already settled",
4626            out.stale_pr_states_repaired
4627        );
4628    }
4629    if out.cache_files > 0 {
4630        tracing::info!(
4631            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
4632            out.cache_files,
4633            out.cache_freed
4634        );
4635    }
4636    if out.questions_abandoned > 0 {
4637        tracing::info!(
4638            "housekeep: abandoned {} question(s) left open by a finished run",
4639            out.questions_abandoned
4640        );
4641    }
4642}
4643
4644/// Run [`triage::run_once`] and log whatever it did, the same "only when
4645/// there is something to say" rule [`janitor`] follows for its own report.
4646///
4647/// Called at the same idle points as [`janitor`] - once per full poll
4648/// interval, never mid-attempt - for the same reason: it is not liveness
4649/// critical, and a task's own `hold_reason` string is the one thing this
4650/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
4651/// tick for no benefit.
4652async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
4653    let questions = Questions::at(home.join("questions"));
4654    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
4655    if report.is_empty() {
4656        return;
4657    }
4658    if !report.quarantined.is_empty() {
4659        tracing::info!(
4660            "triage: held {} blocked task(s) whose blocked-on task or \
4661             question no longer exists: {}",
4662            report.quarantined.len(),
4663            report.quarantined.join(", ")
4664        );
4665    }
4666    if !report.resumed.is_empty() {
4667        tracing::info!(
4668            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
4669            report.resumed.len(),
4670            report.resumed.join(", ")
4671        );
4672    }
4673    if !report.asked.is_empty() {
4674        tracing::info!(
4675            "triage: asked about {} held task(s): {}",
4676            report.asked.len(),
4677            report.asked.join(", ")
4678        );
4679    }
4680    if !report.answered.is_empty() {
4681        tracing::info!(
4682            "triage: applied {} operator answer(s): {}",
4683            report.answered.len(),
4684            report.answered.join(", ")
4685        );
4686    }
4687}
4688
4689/// The free-space gate: what stands between this task and a new run, if
4690/// anything. `Some(reason)` holds the task; `None` lets it start.
4691///
4692/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
4693/// the operator opted out. A measurement failure is a gate, not a pass: both
4694/// sides of "cannot tell" are served by not starting.
4695pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
4696    disk_gate_with(repo, config, crate::disk::free_bytes)
4697}
4698
4699/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
4700/// test can assert the exact wiring `attempt` runs - config's threshold in,
4701/// task-holding reason out - without asking the real machine's disk anything.
4702fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
4703    repo: &Path,
4704    config: &Config,
4705    free_bytes: F,
4706) -> Option<String> {
4707    let min = config.disk.min_free_bytes;
4708    if min == 0 {
4709        return None;
4710    }
4711    let mut paths = vec![repo.to_owned()];
4712    if let Some(cache) = config.cache_dir() {
4713        paths.push(cache);
4714    }
4715    if let Some(root) = &config.graph.worktree_root {
4716        paths.push(root.clone());
4717    }
4718    for path in paths {
4719        let probe = if path == repo {
4720            path.as_path()
4721        } else {
4722            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
4723        };
4724        let reason = match free_bytes(probe) {
4725            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
4726            Err(e) => Some(crate::disk::unmeasured_in(
4727                probe,
4728                &e,
4729                &config.graph.language,
4730            )),
4731        };
4732        if reason.is_some() {
4733            return reason;
4734        }
4735    }
4736    None
4737}
4738
4739/// How long to wait before offering another task when a run lost a seat to a
4740/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
4741/// could read, or carried nothing at all. Long enough that a quota outage
4742/// cannot burn through a whole backlog in the few seconds each doomed attempt
4743/// takes to fail; short enough that a quota which clears early is not left
4744/// idle for the fallback's sake.
4745const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
4746
4747/// Longest a parsed reset hint may push the wait out to. The hint comes from
4748/// the CLI's own words, not a contract, so a parsing slip that lands a day
4749/// away must not leave the loop asleep for a day.
4750const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
4751
4752/// How long [`poll`] should wait before offering the next task, after a run
4753/// lost at least one seat to a rate limit.
4754///
4755/// Pure and separate from the loop so the policy can be exercised without a
4756/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
4757/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
4758/// nothing to parse, or the parsed time has already passed; `cap` bounds how
4759/// far a parsed hint is trusted to push the wait out.
4760fn quota_wait(
4761    reset_at: Option<Timestamp>,
4762    now: Timestamp,
4763    fallback: Duration,
4764    cap: Duration,
4765) -> Duration {
4766    match reset_at {
4767        Some(at) if at > now => {
4768            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
4769            Duration::from_secs(secs).min(cap)
4770        }
4771        _ => fallback,
4772    }
4773}
4774
4775/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
4776///
4777/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
4778/// explains why parsing it exactly "would be a bug factory" — so this only
4779/// recognises the shapes actually observed in the wild, and returns `None`
4780/// for anything else rather than guess at a format nobody has seen.
4781///
4782/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
4783/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
4784/// said it, not from whenever this loop happens to read it: anchoring on `now`
4785/// would push the reset later on every read and would read an already-elapsed
4786/// reset as still in the future. (A long hint is still clamped by
4787/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
4788fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
4789    parse_reset_hint_zoned(text, now)
4790        .or_else(|| parse_reset_hint_dated(text))
4791        .or_else(|| parse_reset_hint_relative(text, recorded))
4792}
4793
4794/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
4795/// optional but at least one required, in that order. A bare number or any
4796/// unknown unit is refused.
4797fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
4798    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
4799    let mut rest = rest.trim();
4800    if rest.is_empty() {
4801        return None;
4802    }
4803    let mut total: i64 = 0;
4804    let mut matched = false;
4805    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
4806        if let Some((digits, tail)) = rest.split_once(unit)
4807            && !digits.is_empty()
4808            && digits.bytes().all(|b| b.is_ascii_digit())
4809        {
4810            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
4811            rest = tail;
4812            matched = true;
4813        }
4814    }
4815    if !rest.is_empty() || !matched {
4816        return None;
4817    }
4818    recorded
4819        .checked_add(jiff::SignedDuration::from_secs(total))
4820        .ok()
4821}
4822
4823/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
4824/// case-insensitive) into a 24-hour hour and minute. Shared by every
4825/// reset-hint shape below.
4826fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
4827    let clock = clock.trim().to_lowercase();
4828    let (digits, pm) = clock
4829        .strip_suffix("am")
4830        .map(|d| (d, false))
4831        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
4832    let (h, m) = digits.trim().split_once(':')?;
4833    let mut hour: i8 = h.trim().parse().ok()?;
4834    let minute: i8 = m.trim().parse().ok()?;
4835    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
4836        return None;
4837    }
4838    if pm && hour != 12 {
4839        hour += 12;
4840    } else if !pm && hour == 12 {
4841        hour = 0;
4842    }
4843    Some((hour, minute))
4844}
4845
4846/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
4847/// and a zone, never a date. A clock reading already past today is read as
4848/// tomorrow's: a CLI naming a same-day reset that has already gone by means
4849/// the window rolled over while nothing was watching.
4850fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
4851    let open = text.find('(')?;
4852    let close = text.rfind(')')?;
4853    if close <= open {
4854        return None;
4855    }
4856    let zone = text[open + 1..close].trim();
4857    let (hour, minute) = parse_12h_clock(&text[..open])?;
4858    let tz = jiff::tz::TimeZone::get(zone).ok()?;
4859    let candidate = now
4860        .to_zoned(tz)
4861        .with()
4862        .hour(hour)
4863        .minute(minute)
4864        .second(0)
4865        .millisecond(0)
4866        .microsecond(0)
4867        .nanosecond(0)
4868        .build()
4869        .ok()?;
4870    let mut at = candidate.timestamp();
4871    if at <= now {
4872        at += jiff::SignedDuration::from_hours(24);
4873    }
4874    Some(at)
4875}
4876
4877/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
4878/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
4879/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
4880/// "already past today" correction to make: the year already disambiguates
4881/// it. Scanned as a five-word window so it can be pulled out of the middle
4882/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
4883/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
4884/// any other timestamp with no zone attached.
4885fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4886    let words: Vec<&str> = text.split_whitespace().collect();
4887    if words.len() < 5 {
4888        return None;
4889    }
4890    (0..=words.len() - 5)
4891        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4892}
4893
4894/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
4895/// parenthesis right after the window is refused rather than ignored — it
4896/// reads as an explicit zone annotation on a shape that otherwise carries
4897/// none, and guessing UTC anyway would be exactly the silent misread this
4898/// module's parsing otherwise avoids.
4899fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4900    if trailing.is_some_and(|next| next.starts_with('(')) {
4901        return None;
4902    }
4903    let month = month_number(window[0])?;
4904    let day_token = window[1].strip_suffix(',')?.to_lowercase();
4905    let day_digits = ["st", "nd", "rd", "th"]
4906        .iter()
4907        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4908    let day: i8 = day_digits.parse().ok()?;
4909    let year_token = window[2];
4910    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4911        return None;
4912    }
4913    let year: i16 = year_token.parse().ok()?;
4914    // The am/pm word carries the sentence's own trailing punctuation, e.g.
4915    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
4916    // reusing the same 12-hour clock reader the bracketed shape uses.
4917    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4918    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4919    let date = jiff::civil::Date::new(year, month, day).ok()?;
4920    let candidate = date
4921        .at(hour, minute, 0, 0)
4922        .to_zoned(jiff::tz::TimeZone::UTC)
4923        .ok()?;
4924    Some(candidate.timestamp())
4925}
4926
4927/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
4928/// case-insensitively, into a 1-based month number.
4929fn month_number(name: &str) -> Option<i8> {
4930    const NAMES: [&str; 12] = [
4931        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4932    ];
4933    let lower = name.to_lowercase();
4934    NAMES
4935        .iter()
4936        .position(|n| *n == lower.as_str())
4937        .map(|i| i as i8 + 1)
4938}
4939
4940/// Resuming a `Blocked` run that already spent every review round its own
4941/// config allowed cannot make progress: `graph::Runner`'s review loop walks
4942/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
4943/// reached `max_rounds`, so `execute` would settle straight back to
4944/// `Blocked` without asking anyone anything. Read-only against a state this
4945/// build never mutates — `src/graph.rs` stays untouched — but without this
4946/// check, [`unfinished_run`] would keep reporting such a run as still
4947/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
4948/// promise is a fresh competition when a design needs to change) would
4949/// silently resume the exhausted run instead, spending an attempt on a
4950/// cycle that cannot change anything.
4951fn exhausted_review_budget(state: &RunState) -> bool {
4952    // A run whose task-head publication failed has nothing left to review:
4953    // resuming it only retries the publication, so it is never "exhausted".
4954    state.status == RunStatus::Blocked
4955        && !state.pr_publication_pending
4956        && state.reviews.len() >= state.config.graph.review_rounds
4957}
4958
4959/// This task's *most recent* run, if resuming it would actually make
4960/// progress. `short` is only for the warning's own message.
4961///
4962/// Only ever `runs.last()` — never a search back through older history.
4963/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
4964/// mint, oldest first, and every entry before the last one was already
4965/// superseded at the moment it was minted: the daemon only ever starts a new
4966/// run when the previous one was not worth resuming (unresumable, exhausted,
4967/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
4968/// opens a fresh review-only run alongside an older, already-failed
4969/// competition. Searching further back would let an old run that merely
4970/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
4971/// behind, say — get resumed instead of the fresh competition
4972/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
4973/// nothing asked to revisit.
4974///
4975/// Two runs paid for the "prefer resuming over restarting" half of this
4976/// lesson, which is why this still checks `runs.last()` rather than always
4977/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
4978/// task a moment later, duplicating two and a half hours of agent work. Then
4979/// b25f stalled on a judge that timed out and one that answered with no JSON
4980/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
4981/// **one second** later, buying three fresh implementations to reach the
4982/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
4983/// the second case: a stall is terminal, and its cheap recovery re-asks only
4984/// the absent seats. [`exhausted_review_budget`] is the other half: a run
4985/// that is technically `resumable()` but provably cannot progress must not
4986/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
4987/// no-op instead of the fresh competition it promises.
4988///
4989/// A load failure is warned about rather than silently read as "not
4990/// resumable": the alternative is exactly what let a schema mismatch on run
4991/// `eba2` fall through to a full re-competition with nobody told why.
4992/// `crate::conduct` is what actually offers a better answer than
4993/// `Runner::start` here (see `Recovery::Review`), once this task's next
4994/// failure shows it up as `held`/`failed` with the run state unreadable.
4995fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4996    unfinished_run_with(runs, short, RunState::load)
4997}
4998
4999/// [`unfinished_run`] with an injected state reader. Tests provide their
5000/// fixtures directly rather than touching the process-global run home.
5001pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5002where
5003    F: FnMut(&str) -> Result<RunState>,
5004{
5005    let mut id = runs.last()?.clone();
5006    let mut visited = std::collections::BTreeSet::new();
5007    let mut repo = None;
5008    loop {
5009        if !runs.contains(&id) || !visited.insert(id.clone()) {
5010            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5011            return None;
5012        }
5013        let state = match load(&id) {
5014            Ok(state) if state.id == id => state,
5015            Ok(_) => return None,
5016            Err(e) => {
5017                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5018                return None;
5019            }
5020        };
5021        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5022            return None;
5023        }
5024        repo = Some(state.repo.clone());
5025        if let Some(authority) = state.retired_to {
5026            id = authority;
5027            continue;
5028        }
5029        return (state.status.resumable()
5030            && !state.released()
5031            && !exhausted_review_budget(&state)
5032            && state.liveness(false) != crate::run::Liveness::Live)
5033            .then_some(id);
5034    }
5035}
5036
5037/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5038/// that [`attempt`] will resume it on its own?
5039///
5040/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5041/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5042/// injected reader like its sibling. An unreadable run is not awaiting
5043/// anything: it keeps going to the conductor as before.
5044fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5045where
5046    F: FnOnce(&str) -> Result<RunState>,
5047{
5048    // `Failed` stays: a record an older build wrote for a parked run.
5049    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5050        || task.fresh_start
5051        || task.review_branch.is_some()
5052    {
5053        return false;
5054    }
5055    let Some(id) = task.runs.last() else {
5056        return false;
5057    };
5058    load(id).is_ok_and(|s| {
5059        s.parked
5060            && s.status.resumable()
5061            && !s.released()
5062            && s.retired_to.is_none()
5063            && !exhausted_review_budget(&s)
5064    })
5065}
5066
5067/// Which of the three ways [`attempt`] can mint or continue a run this task
5068/// should use.
5069#[derive(Debug, Clone, PartialEq, Eq)]
5070enum Starter {
5071    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5072    /// and that still exists.
5073    Review(String),
5074    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5075    Resume(String),
5076    /// `crate::graph::Runner::start`: a fresh competition.
5077    Start,
5078}
5079
5080/// A second bound independent of inputs and the resettable failure counter.
5081/// Count recovery records, not history entries: resuming appends the same id.
5082/// Unknown history is not evidence that a new set of worktrees is affordable.
5083fn retained_attempt_hold(
5084    task: &Task,
5085    starter: &Starter,
5086    limit: usize,
5087    mut load: impl FnMut(&str) -> Result<RunState>,
5088) -> Option<String> {
5089    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5090        return None;
5091    }
5092    let mut retained = 0;
5093    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5094        let state = match load(id) {
5095            Ok(state) if state.id == *id => state,
5096            _ => {
5097                return Some(format!(
5098                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5099                ));
5100            }
5101        };
5102        if state.retired_to.is_some() || state.released() {
5103            continue;
5104        }
5105        // Neither a completed status nor an empty candidate array proves that
5106        // all recovery sources (including unrecorded preparation) were retired.
5107        retained += 1;
5108    }
5109    (retained >= limit).then(|| format!(
5110        "[recovery-backlog] {retained} unretired attempts reach the limit of {limit}. Resume an existing recovery owner or inspect the lineage and retire proved-obsolete attempts before creating another run. Releases, refunds and changed upstream inputs do not reset this limit. No source or historical report was removed."
5111    ))
5112}
5113
5114/// A selected public implementation overrides every historical candidate and pin.
5115fn selected_starter(
5116    selected: &crate::pr_recovery::Selection,
5117    previous: Option<&RunState>,
5118    unfinished: Option<&str>,
5119) -> Starter {
5120    if let Some(id) = unfinished
5121        && previous.is_some_and(|r| {
5122            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5123        })
5124    {
5125        Starter::Resume(id.to_owned())
5126    } else {
5127        Starter::Review(selected.branch.clone())
5128    }
5129}
5130
5131/// The owner's answer to this branch's divergence question, consumed from the
5132/// task so a later, different divergence asks again. The runner applies it
5133/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5134fn take_divergence_answer(
5135    branch: &str,
5136    remote: &str,
5137    task: &mut Task,
5138) -> Option<crate::reconcile::Choice> {
5139    let summary = crate::reconcile::summary_for(branch, remote);
5140    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5141        (a.question == summary)
5142            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5143            .flatten()
5144            .map(|c| (i, c))
5145    })?;
5146    task.answers.remove(idx);
5147    Some(choice)
5148}
5149
5150/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5151/// this attempt should use. Pure, and separate from [`attempt`], so the
5152/// routing itself is assertable without spawning a real graph or a git
5153/// process: `attempt`'s own `crate::git::branch_exists` call has already
5154/// happened by the time this is called.
5155///
5156/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5157/// whose branch is gone falls all the way through to [`Starter::Start`], not
5158/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5159/// old (likely `Blocked`) run in the first place, and a branch that vanished
5160/// out from under that choice is not evidence resuming it would fare better.
5161fn choose_starter(
5162    review_branch: Option<&str>,
5163    branch_exists: bool,
5164    unfinished: Option<&str>,
5165) -> Starter {
5166    match review_branch {
5167        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5168        Some(_) => Starter::Start,
5169        None => match unfinished {
5170            Some(id) => Starter::Resume(id.to_owned()),
5171            None => Starter::Start,
5172        },
5173    }
5174}
5175
5176/// Consume a retained review only while its authored criteria still match.
5177fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5178    let branch = task.review_branch.take();
5179    let instruction = task.review_instruction.take();
5180    branch.filter(|branch| match &instruction {
5181        Some(authored) => *authored == task.instruction,
5182        // Legacy retained branches must agree with their prior run; only an
5183        // explicitly pinned review can proceed without recoverable provenance.
5184        None => previous.map_or_else(
5185            || task.review_of.as_ref() == Some(branch),
5186            |run| compatible_run_instruction(run, task),
5187        ),
5188    })
5189}
5190
5191/// A current explicit pin can select an otherwise incompatible run. Edits
5192/// and subsequent approvals invalidate pins selected for earlier criteria.
5193fn may_resume_run(run: &RunState, task: &Task) -> bool {
5194    task.resume_override
5195        .as_ref()
5196        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5197        || compatible_run_instruction(run, task)
5198}
5199
5200/// Review scaffolding is execution context, not evidence of an operator edit.
5201pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5202    if let Some(authored) = &run.task_instruction {
5203        return compatible_instruction(authored, task);
5204    }
5205    if compatible_instruction(&run.instruction, task) {
5206        return true;
5207    }
5208    // Recognize only the existing generated review shapes on legacy runs.
5209    // Ordinary authored text with a similar heading is left intact.
5210    if run.reviewed_commits.is_some() {
5211        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5212            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5213        }
5214        if let Some(branch) = &task.review_of {
5215            let canonical = format!(
5216                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5217            );
5218            let generated = format!(
5219                "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"
5220            );
5221            return task.instruction == canonical && run.instruction.starts_with(&generated);
5222        }
5223    }
5224    false
5225}
5226
5227/// Compare authored instructions, excluding answer blocks appended by the daemon.
5228pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5229    strip_answers_block(old, task) == task.instruction
5230}
5231
5232/// Which repository a task runs in. A task that names none — the normal case
5233/// for one filed from a phone — runs in the daemon's own default.
5234fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5235    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5236        return fallback.to_path_buf();
5237    }
5238    task.repo.clone()
5239}
5240
5241/// The header [`append_answers`] appends operator answers under. Shared with
5242/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5243/// rather than grown a new block on every resume.
5244const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5245
5246/// Render the first `count` answers in the block appended to an instruction.
5247fn answers_block(task: &Task, count: usize) -> String {
5248    let mut s = ANSWERS_HEADER.to_owned();
5249    for a in &task.answers[..count] {
5250        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5251    }
5252    s
5253}
5254
5255/// Render the approval independently of transient task state, so historical
5256/// suffixes remain recognizable after another explicit release.
5257fn resumption_block(r: &crate::queue::Resumption) -> String {
5258    format!(
5259        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5260         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5261        r.generation, r.at, r.instruction, r.answers_through,
5262    )
5263}
5264
5265/// Append audit answers and the latest explicit approval to the instruction.
5266fn append_answers(base: &str, task: &Task) -> String {
5267    let mut s = base.to_owned();
5268    if !task.answers.is_empty() {
5269        s.push_str(&answers_block(task, task.answers.len()));
5270    }
5271    if let Some(r) = &task.resumption {
5272        s.push_str(&resumption_block(r));
5273    }
5274    s
5275}
5276
5277/// Drop the prior answer block only when it is exactly the suffix this task
5278/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5279/// the task author is ordinary instruction text, not a block to remove.
5280fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5281    let mut instruction = instruction;
5282    for approval in task
5283        .resumption
5284        .iter()
5285        .chain(task.resumption_history.iter().rev())
5286    {
5287        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5288            instruction = base;
5289            break;
5290        }
5291    }
5292    for count in (1..=task.answers.len()).rev() {
5293        let block = answers_block(task, count);
5294        if let Some(base) = instruction.strip_suffix(&block) {
5295            return base;
5296        }
5297    }
5298    instruction
5299}
5300
5301/// The instruction handed to `Runner::start`: the task's own text, plus any
5302/// operator answers `crate::conduct` collected for it (see
5303/// [`Task::answers`]), so a decision the operator actually made reaches the
5304/// implementers rather than only clearing the block that was waiting on it.
5305///
5306/// Appended rather than merged into [`Task::instruction`] itself, so the
5307/// task's own record stays exactly what its author wrote.
5308fn instruction_for(task: &Task) -> String {
5309    append_answers(&task.instruction, task)
5310}
5311
5312/// The instruction a resumed run should carry on with: whatever it already
5313/// had, refreshed with the task's *current* operator answers.
5314///
5315/// A resumable run's own `RunState::instruction` predates any answer
5316/// `crate::conduct` collects after the run parks, so resuming it unchanged —
5317/// the behaviour before this function existed — silently drops the very
5318/// decision the operator made to unblock it. Re-stripping any block this
5319/// function appended on an earlier resume before re-appending the current
5320/// list (rather than blindly appending again) is what keeps a task resumed
5321/// three times over three answered questions from carrying the same answer
5322/// three times.
5323fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5324    append_answers(strip_answers_block(old_instruction, task), task)
5325}
5326
5327/// Preserve the producer's verified boundary and target, independent of prose.
5328fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5329    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5330    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5331    if let Some(cause) = task.hold_notice_cause.as_mut() {
5332        cause.target = failure.map(|f| f.target.clone());
5333    }
5334}
5335
5336#[derive(Debug, thiserror::Error)]
5337#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5338struct MissingAttachment {
5339    name: String,
5340    path: PathBuf,
5341}
5342
5343/// The task's attachments as absolute paths, each checked to still exist.
5344fn task_attachments(
5345    queue: &Queue,
5346    task: &Task,
5347) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5348    let paths = queue.attachment_paths(task);
5349    for (name, path) in task.attachments.iter().zip(&paths) {
5350        if !path.is_file() {
5351            return Err(MissingAttachment {
5352                name: name.clone(),
5353                path: path.clone(),
5354            });
5355        }
5356    }
5357    Ok(paths)
5358}
5359
5360/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
5361/// answers before handing it to `Runner` — the actual boundary between
5362/// [`choose_starter`]'s routing and the graph, factored out so it is
5363/// assertable without a real repository, git branch, or agent CLI.
5364///
5365/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
5366/// instruction from the reviewed branch's own commit log because there is no
5367/// task statement to speak of for hand-written work, and splicing operator
5368/// answers into that text would contradict the very message it sends
5369/// reviewers ("there is no task statement").
5370fn prepare_instruction(
5371    starter: &Starter,
5372    old_instruction: Option<&str>,
5373    task: &Task,
5374) -> Option<String> {
5375    match starter {
5376        Starter::Start => Some(instruction_for(task)),
5377        Starter::Resume(_) => Some(resumed_instruction(
5378            old_instruction.expect("a resumed run always has a prior instruction"),
5379            task,
5380        )),
5381        Starter::Review(_) => None,
5382    }
5383}
5384
5385/// Persist a transition. A queue write failure is logged rather than fatal: the
5386/// run already happened, and taking the daemon down would only add a lost
5387/// backlog to a full disk.
5388fn record(queue: &Queue, task: &mut Task) {
5389    if let Err(e) = queue.put(task) {
5390        tracing::error!("could not record task {}: {e:#}", task.short());
5391        let notice = Notice::error(
5392            "loop:record",
5393            "The loop could not save a task's state; check the disk.",
5394        )
5395        .link(Link::Task {
5396            id: task.id.clone(),
5397        });
5398        // The queue lives at `<home>/queue`, so its parent is the home.
5399        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
5400            Some(home) => notices::raise_in(home, notice),
5401            None => notices::raise(notice),
5402        }
5403    }
5404}
5405
5406/// Every runnable task, in the order the loop should try them.
5407///
5408/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
5409/// tail exists so that a claim somebody else holds costs the loop the next
5410/// candidate rather than a whole poll interval of idleness.
5411fn runnable(queue: &Queue) -> Vec<Task> {
5412    let mut tasks: Vec<Task> = queue
5413        .list()
5414        .into_iter()
5415        .filter(|t| t.status.runnable())
5416        .collect();
5417    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
5418    tasks
5419}
5420
5421/// Why a run ended where it did, in one line, for [`Task::last_error`].
5422///
5423/// A stalled run names the seats the quota took out: "out of quota" is not
5424/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
5425/// agent to replace or which plan to top up.
5426///
5427/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
5428/// purpose: unlike `label`'s other callers (an internal log line, an
5429/// already-a-bug fallback message), this string becomes `Task::last_error`
5430/// verbatim, which the phone renders in the same alarm-styled box an
5431/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
5432/// `.err` styling. A bare `verified_noop` there would read exactly like the
5433/// failure this whole feature exists to tell apart from one.
5434fn describe(state: &RunState) -> String {
5435    let p = phrases(&state.config.graph.language);
5436    let mut detail = if state.status == RunStatus::Stalled {
5437        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
5438        seats.sort_unstable();
5439        seats.dedup();
5440        if seats.is_empty() {
5441            p.quorum_lost.to_owned()
5442        } else {
5443            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
5444        }
5445    } else {
5446        format!("{}{}", p.run_ended, state.status.display_label())
5447    };
5448    if let Some(last) = state.events.last() {
5449        // The review loop's "never answered" stop is the one event worth
5450        // translating; it is recognised from structured state, not by
5451        // matching the English event text (which stays as recorded).
5452        let unanswered = state
5453            .reviews
5454            .last()
5455            .filter(|r| {
5456                state.status == RunStatus::Blocked
5457                    && last.node == "review"
5458                    && r.incomplete()
5459                    && r.blocking == 0
5460                    && r.round == state.config.graph.review_rounds
5461                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
5462            })
5463            .map(|r| (r.expected - r.answered, r.round));
5464        match unanswered {
5465            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
5466                detail.push_str(&format!(
5467                    " ({}: {})",
5468                    last.node,
5469                    (p.reviewers_never_answered)(missing, rounds)
5470                ));
5471            }
5472            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
5473        }
5474    }
5475    detail.push_str(&format!(" [run {}]", state.id));
5476    detail
5477}
5478
5479/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
5480///
5481/// The task file lives in the backlog indefinitely; a diagnostic is an
5482/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
5483/// stay small regardless of how much a gate command or a candidate printed.
5484const DIAGNOSTIC_MAX: usize = 4_000;
5485
5486/// Tail kept from a single failing command's output inside a diagnostic.
5487/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
5488/// pointer for a human deciding whether to go read the full artifact by hand,
5489/// not a replacement for reading it.
5490const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
5491
5492/// Assemble a bounded diagnostic excerpt from a held task's own run, so
5493/// `magi task show` says more than the one-line reason in [`describe`].
5494///
5495/// The one-liner answers "where did the run stop"; this answers "what would a
5496/// human have found opening `artifacts/` by hand" — the point of the whole
5497/// feature is the case that one-liner actively misleads on: a run held as "no
5498/// candidate produced a change" can mean the implementer actually finished
5499/// the task (opened a PR, merged it, tagged a release) and only left a clean
5500/// local worktree behind, which reads as "nothing happened" unless someone
5501/// goes and reads what the agent actually said. `None` when the run carries
5502/// none of the three shapes this recognises — an ordinary run held for
5503/// something not diagnosable from `RunState` alone still explains itself
5504/// through `Task::last_error`.
5505fn diagnostic(state: &RunState) -> Option<String> {
5506    let mut parts: Vec<String> = Vec::new();
5507
5508    // Gate failure: which check(s), and the tail of what each printed.
5509    for o in state.gate.iter().filter(|o| !o.ok()) {
5510        parts.push(format!(
5511            "gate `{}` failed ({}):\n{}",
5512            o.command,
5513            notices::exit_status(o.code),
5514            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
5515        ));
5516    }
5517
5518    // The land loop gave up because the fixer declined while checks were
5519    // still red: the message already names them (see `land::run`).
5520    if let Some(last) = state
5521        .events
5522        .iter()
5523        .rev()
5524        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
5525    {
5526        parts.push(last.message.clone());
5527    }
5528
5529    // No viable candidate: every implementer's own final word, sanitized the
5530    // same way a judge would have read it, so a run that actually finished
5531    // the job does not read as an unexplained failure. A verified no-op is
5532    // called out ahead of its own summary and apart from an ordinary
5533    // failure's `why` — this is the one candidate shape whose diagnostic a
5534    // human is expected to actually judge, not just skim.
5535    if state.viable().is_empty() {
5536        for c in &state.candidates {
5537            if let Some(evidence) = &c.verified_noop {
5538                parts.push(format!(
5539                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
5540                    c.label
5541                ));
5542            } else if !c.summary.trim().is_empty() {
5543                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
5544            } else if let Some(why) = &c.failed {
5545                parts.push(format!("candidate {}: {why}", c.label));
5546            }
5547        }
5548    }
5549
5550    if parts.is_empty() {
5551        return None;
5552    }
5553    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
5554    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
5555    // back slightly over. Leave it enough room to always land under the
5556    // limit.
5557    Some(crate::run::tail(
5558        &parts.join("\n\n"),
5559        DIAGNOSTIC_MAX.saturating_sub(100),
5560    ))
5561}
5562
5563/// Stable lower-case name for a run status, for an internal log line and the
5564/// "graph stopped without reaching a terminal status" bug message in
5565/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
5566/// doc for why that one reads [`RunStatus::display_label`] instead. One
5567/// definition of a status's name, on the type that owns it: this table used
5568/// to live here as a second copy, and a status renamed in one place would
5569/// have gone on reading correctly in the other.
5570fn label(status: RunStatus) -> &'static str {
5571    status.as_str()
5572}
5573
5574/// Parse a merge mode override.
5575pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
5576    match mode {
5577        "none" => Ok(MergeMode::None),
5578        "local" => Ok(MergeMode::Local),
5579        "pr" => Ok(MergeMode::Pr),
5580        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
5581    }
5582}
5583
5584/// Take the status lock, recovering from a poisoned one.
5585///
5586/// A panic elsewhere must not silently stop the heartbeat: the status is plain
5587/// data, and the worst a poisoned lock can hold is a stale timestamp.
5588fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
5589    mutex
5590        .lock()
5591        .unwrap_or_else(std::sync::PoisonError::into_inner)
5592}
5593
5594#[cfg(test)]
5595mod tests {
5596    use super::*;
5597    use crate::queue::{Source, TaskStatus};
5598    use crate::run::{Candidate, CommandOutcome};
5599    use pretty_assertions::assert_eq;
5600
5601    fn task() -> Task {
5602        Task::new(
5603            "add retries".to_owned(),
5604            "add retries".to_owned(),
5605            PathBuf::from("/repo"),
5606            Source::Human,
5607        )
5608    }
5609
5610    #[test]
5611    fn selected_public_head_overrides_historical_resume_and_pin() {
5612        let mut t = task();
5613        let mut old = run_state(RunStatus::Blocked);
5614        let selection = crate::pr_recovery::Selection {
5615            url: "url".into(),
5616            branch: format!("magi/task-{}", t.id),
5617            head: "a".repeat(40),
5618            source_head: None,
5619            source_run: None,
5620            source_proof: None,
5621            disposition: Some(crate::pr_recovery::Disposition::Review),
5622            instruction: t.instruction.clone(),
5623            approved_at: Timestamp::now(),
5624        };
5625        t.resume_override = Some(crate::queue::OperatorResume {
5626            pinned_run: Some(old.id.clone()),
5627            question_id: "choice".into(),
5628            at: Timestamp::now(),
5629            conductor_rehold: None,
5630            forced: false,
5631        });
5632        assert_eq!(
5633            selected_starter(&selection, Some(&old), Some(&old.id)),
5634            Starter::Review(selection.branch.clone())
5635        );
5636        old.pr_recovery = Some(selection.clone());
5637        assert_eq!(
5638            selected_starter(&selection, Some(&old), Some(&old.id)),
5639            Starter::Review(selection.branch.clone())
5640        );
5641        old.reviewed_commits = Some(vec!["implementation".into()]);
5642        assert_eq!(
5643            selected_starter(&selection, Some(&old), Some(&old.id)),
5644            Starter::Resume(old.id.clone())
5645        );
5646        let mut changed = selection.clone();
5647        changed.head = "b".repeat(40);
5648        assert_eq!(
5649            selected_starter(&changed, Some(&old), Some(&old.id)),
5650            Starter::Review(changed.branch)
5651        );
5652    }
5653
5654    #[test]
5655    fn candidate_transplant_failure_is_one_actionable_hold() {
5656        let dir = tempfile::tempdir().unwrap();
5657        let q = Queue::at(dir.path().join("queue"));
5658        let mut t = task();
5659        let mut state = run_state(RunStatus::Blocked);
5660        state.event("prep", "cannot apply referenced commit: conflict");
5661        state.prep_failure = Some("conflict".into());
5662        t.start(state.id.clone());
5663        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
5664        assert_eq!(t.attempts, 1);
5665        assert_eq!(t.status, TaskStatus::Held);
5666        assert!(t.operator_held());
5667        assert!(!t.status.runnable());
5668        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
5669        let first = t.chat_notice_key().unwrap();
5670        t.chat_notices.push(first.clone());
5671        t.release_operator("test", None);
5672        state.id = "another-unprepared-run".into();
5673        t.start(state.id.clone());
5674        finish_attempt(
5675            3,
5676            &q,
5677            &mut t,
5678            &state,
5679            &[],
5680            Err(anyhow::anyhow!("still conflicts")),
5681        );
5682        assert_eq!(
5683            t.chat_notice_key().as_ref(),
5684            Some(&first),
5685            "no work happened"
5686        );
5687        t.release_operator("test", None);
5688        state.prep_failure = None;
5689        state.status = RunStatus::Failed;
5690        state.begin_pass();
5691        t.start(state.id.clone());
5692        finish_attempt(
5693            1,
5694            &q,
5695            &mut t,
5696            &state,
5697            &[],
5698            Err(anyhow::anyhow!("new gate failure")),
5699        );
5700        let failure = t.chat_notice_key().unwrap();
5701        assert_ne!(failure, first, "approved recovery reached a real failure");
5702        t.release_operator("test", None);
5703        state.begin_pass();
5704        t.start(state.id.clone());
5705        finish_attempt(
5706            1,
5707            &q,
5708            &mut t,
5709            &state,
5710            &[],
5711            Err(anyhow::anyhow!("new failure on resume")),
5712        );
5713        assert_ne!(
5714            t.chat_notice_key().as_ref(),
5715            Some(&failure),
5716            "a new settled pass"
5717        );
5718    }
5719
5720    #[test]
5721    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
5722        for source in ["cli", "web"] {
5723            let mut t = task();
5724            let mut run = run_state(RunStatus::Blocked);
5725            run.instruction = "Run A original criteria".into();
5726            run.task_instruction = Some(run.instruction.clone());
5727            t.start(run.id.clone());
5728            t.release_operator("choice", Some("resume-question"));
5729            t.resume_override = Some(crate::queue::OperatorResume {
5730                question_id: "resume-question".into(),
5731                at: Timestamp::now(),
5732                conductor_rehold: None,
5733                forced: true,
5734                pinned_run: Some(run.id.clone()),
5735            });
5736            t.hold_machine(Some("not enough free space to start a run".into()));
5737            let mut unchanged = t.clone();
5738            unchanged
5739                .edit("title changed".into(), unchanged.instruction.clone())
5740                .unwrap();
5741            unchanged.release_operator(source, None);
5742            assert_eq!(
5743                unchanged
5744                    .resume_override
5745                    .as_ref()
5746                    .unwrap()
5747                    .pinned_run
5748                    .as_deref(),
5749                Some(run.id.as_str())
5750            );
5751            assert!(!compatible_run_instruction(&run, &unchanged));
5752            assert!(may_resume_run(&run, &unchanged));
5753
5754            t.edit(
5755                "approved recovery".into(),
5756                "Reuse measured PR head B; fix Clippy; review".into(),
5757            )
5758            .unwrap();
5759            assert!(t.resume_override.is_none());
5760            t.release_operator(source, None);
5761            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
5762            assert!(reloaded.resume_override.is_none());
5763            assert!(!may_resume_run(&run, &reloaded));
5764            let unfinished =
5765                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
5766                    .filter(|_| may_resume_run(&run, &reloaded));
5767            assert_eq!(
5768                choose_starter(None, false, unfinished.as_deref()),
5769                Starter::Start
5770            );
5771            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
5772            assert_eq!(
5773                reloaded.resumption_history[0].question_id.as_deref(),
5774                Some("resume-question")
5775            );
5776
5777            // A revision already persisted with the old approval/pin is also
5778            // invalidated when the new operator release is recorded.
5779            unchanged.instruction = "Reuse measured PR head B".into();
5780            unchanged.hold_machine(Some("disk hold".into()));
5781            unchanged.release_operator(source, None);
5782            assert!(unchanged.resume_override.is_none());
5783            assert!(!may_resume_run(&run, &unchanged));
5784        }
5785    }
5786
5787    #[test]
5788    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
5789        let mut t = task();
5790        let mut run = run_state(RunStatus::Blocked);
5791        t.review_of = Some("approved-head".into());
5792        t.instruction =
5793            "Review the branch `approved-head` (review-only: no implementation, no judging)."
5794                .into();
5795        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();
5796        run.reviewed_commits = Some(vec!["Commit log".into()]);
5797        t.start(run.id.clone());
5798        t.hold_machine(Some("interrupted review".into()));
5799        t.release_operator("cli", None);
5800        assert!(
5801            compatible_run_instruction(&run, &t),
5802            "legacy explicit review remains resumable"
5803        );
5804        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
5805            .filter(|_| compatible_run_instruction(&run, &t));
5806        assert_eq!(
5807            choose_starter(None, false, unfinished.as_deref()),
5808            Starter::Resume(run.id.clone())
5809        );
5810        run.task_instruction = Some(t.instruction.clone());
5811        assert!(compatible_run_instruction(&run, &t));
5812        let reloaded: RunState =
5813            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
5814        assert!(compatible_run_instruction(&reloaded, &t));
5815        t.edit(
5816            "new approved head".into(),
5817            "Reuse measured PR head B".into(),
5818        )
5819        .unwrap();
5820        assert!(!compatible_run_instruction(&run, &t));
5821
5822        // Legacy recovery reviews retain the task criteria ahead of the log.
5823        t.review_of = None;
5824        t.instruction = "Fix Clippy on approved head".into();
5825        run.task_instruction = None;
5826        run.instruction = format!(
5827            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
5828            t.instruction
5829        );
5830        assert!(compatible_run_instruction(&run, &t));
5831        t.instruction.push('\n');
5832        assert!(
5833            compatible_run_instruction(&run, &t),
5834            "legacy generated review trimmed the original criteria"
5835        );
5836        t.hold_for_handover(Some("approved-head".into()), "refused".into());
5837        let mut unchanged = t.clone();
5838        assert_eq!(
5839            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
5840            Some("approved-head")
5841        );
5842        t.edit("new plan".into(), "Reuse measured PR head B".into())
5843            .unwrap();
5844        assert!(take_review_branch(&mut t, Some(&run)).is_none());
5845        assert!(!compatible_run_instruction(&run, &t));
5846        t.review_branch = Some("approved-head".into());
5847        t.review_instruction = None;
5848        assert!(
5849            take_review_branch(&mut t, Some(&run)).is_none(),
5850            "legacy retained candidate cannot replace a revised approved head"
5851        );
5852    }
5853
5854    #[test]
5855    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
5856        crate::run::pin_test_home();
5857        let dir = tempfile::tempdir().unwrap();
5858        let queue = Queue::at(dir.path().join("queue"));
5859        for resume in [true, false] {
5860            let state = run_state(RunStatus::Blocked);
5861            let mut t = task();
5862            t.start(state.id.clone());
5863            let action = if resume {
5864                ask::ChoiceAction::Resume {
5865                    run: state.id.clone(),
5866                }
5867            } else {
5868                ask::ChoiceAction::Requeue
5869            };
5870            let mut q = action_question(&state.id, action);
5871            q.status = ask::QuestionStatus::Open;
5872            q.answer = None;
5873            q.answered_at = None;
5874            t.fail("run stopped with a question", 3);
5875            hold_if_runnable(&queue, &mut t);
5876            assert!(t.operator_decided_at.is_none());
5877            assert!(t.operator_held());
5878            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
5879            let expected = if resume {
5880                ActionDecision::Resume(state.id.clone())
5881            } else {
5882                ActionDecision::Requeue
5883            };
5884            assert_eq!(
5885                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5886                expected
5887            );
5888            t.hold_manual(Some("later explicit hold".into()));
5889            assert_eq!(
5890                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5891                ActionDecision::Stale
5892            );
5893        }
5894    }
5895
5896    #[test]
5897    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
5898        let mut t = task();
5899        t.answers.push(crate::queue::AnsweredQuestion {
5900            question: "Inspect the remote?".into(),
5901            answer: "Inspect then wait".into(),
5902        });
5903        let old = instruction_for(&t);
5904        assert!(compatible_instruction(&old, &t));
5905        t.instruction = "Reuse approved PR head and review".into();
5906        t.release_operator("cli", None);
5907        assert!(!compatible_instruction(&old, &t));
5908        let approved = instruction_for(&t);
5909        assert!(approved.contains("waiting premises are superseded"));
5910        assert!(compatible_instruction(&approved, &t));
5911        assert_eq!(resumed_instruction(&approved, &t), approved);
5912        t.release_operator("web", None);
5913        assert!(compatible_instruction(&approved, &t));
5914        assert_eq!(t.resumption_history.len(), 1);
5915        t.start("run".into());
5916        assert!(instruction_for(&t).contains("Explicit operator resumption"));
5917    }
5918
5919    /// A run that stopped on an infrastructure wait asked no agent anything:
5920    /// the task is held by the machine under a `[resource]` reason (resumable,
5921    /// re-checked by triage), and the attempt it started is given back.
5922    #[test]
5923    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
5924        let mut state = RunState::new(
5925            PathBuf::from("/repo"),
5926            "main".to_owned(),
5927            "abc1234".to_owned(),
5928            "task".to_owned(),
5929            Config::default(),
5930        );
5931        state.status = RunStatus::Blocked;
5932        state.resource_block = Some(crate::run::ResourceBlock {
5933            node: "graft".to_owned(),
5934            kind: "shared build cache".to_owned(),
5935            detail: "timed out".to_owned(),
5936            at: jiff::Timestamp::now(),
5937        });
5938        let mut t = task();
5939        t.start("20260902-000000-aaaa".to_owned());
5940        assert_eq!(t.attempts, 1);
5941        let verdict = Verdict {
5942            status: RunStatus::Blocked,
5943            left_pr: false,
5944            quota_hit: false,
5945            parked: false,
5946            no_viable_candidates: false,
5947        };
5948        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5949        assert_eq!(t.status, TaskStatus::Held);
5950        assert_eq!(t.attempts, 0, "the attempt is refunded");
5951        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5952        assert!(
5953            !t.operator_held(),
5954            "a machine hold, released without a human"
5955        );
5956
5957        let mut selected = task();
5958        selected.start("20260902-000000-cccc".into());
5959        selected.replacement = Some(crate::merge_decision::Replacement {
5960            question: "fixture".into(),
5961            run: "earlier".into(),
5962            pr: "https://example.invalid/pr/1".into(),
5963            agent: "selected".into(),
5964            context: "fixture".into(),
5965        });
5966        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
5967        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
5968        assert_eq!(selected.attempts, 0);
5969        assert!(
5970            !selected.operator_held(),
5971            "a selected agent also retains a machine resource hold"
5972        );
5973        assert!(
5974            selected
5975                .hold_reason
5976                .as_deref()
5977                .unwrap()
5978                .starts_with("[resource] ")
5979        );
5980
5981        // A park request outranks it: still the operator's doing.
5982        let mut p = task();
5983        p.start("20260902-000000-bbbb".to_owned());
5984        settle_and_diagnose(
5985            &mut p,
5986            Verdict {
5987                parked: true,
5988                ..verdict
5989            },
5990            "parked",
5991            2,
5992            &state,
5993        );
5994        assert_eq!(p.status, TaskStatus::Parked);
5995    }
5996
5997    #[test]
5998    fn record_failure_notice_links_the_task() {
5999        let dir = tempfile::tempdir().unwrap();
6000        // A regular file where the queue directory should be makes every
6001        // `put` fail, on every platform and whoever runs the test.
6002        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
6003        let queue = Queue::at(dir.path().join("queue"));
6004        let mut t = interrupt_task("rec-fail-1");
6005        record(&queue, &mut t);
6006
6007        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
6008        assert_eq!(found.len(), 1);
6009        assert_eq!(found[0].key, "loop:record");
6010        assert_eq!(
6011            found[0].link,
6012            Some(Link::Task {
6013                id: "rec-fail-1".to_owned()
6014            })
6015        );
6016    }
6017
6018    /// A runnable task marked to interrupt, with an id fixed for assertions
6019    /// rather than the random one [`Task::new`] mints.
6020    fn interrupt_task(id: &str) -> Task {
6021        let mut t = task();
6022        t.id = id.to_owned();
6023        t.interrupt = true;
6024        t
6025    }
6026
6027    /// An ordinary runnable task with an id fixed for assertions.
6028    fn task_with_id(id: &str) -> Task {
6029        let mut t = task();
6030        t.id = id.to_owned();
6031        t
6032    }
6033
6034    /// A runnable task marked `--urgent`, with an id fixed for assertions.
6035    fn urgent_task(id: &str) -> Task {
6036        let mut t = task();
6037        t.id = id.to_owned();
6038        t.urgent = true;
6039        t
6040    }
6041
6042    #[test]
6043    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
6044        let dir = tempfile::tempdir().unwrap();
6045        let queue = Queue::at(dir.path().join("queue"));
6046        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6047        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6048        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
6049        let mut first = task();
6050        queue.put(&mut first).unwrap();
6051        let stale_plain = queue.get(&first.id).unwrap();
6052        first.set_urgent(true).unwrap();
6053        queue.put(&mut first).unwrap();
6054        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
6055        let mut second = urgent_task("second");
6056        queue.put(&mut second).unwrap();
6057        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
6058        drop(queue.claim(&second.id).unwrap());
6059        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
6060        drop(dispatched);
6061        let stale_urgent = queue.get(&first.id).unwrap();
6062        first.set_urgent(false).unwrap();
6063        queue.put(&mut first).unwrap();
6064        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
6065        assert_eq!(urgent.available_permits(), 1);
6066        drop(queue.claim(&first.id).unwrap());
6067        drop(occupied);
6068    }
6069
6070    #[test]
6071    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
6072        let dir = tempfile::tempdir().unwrap();
6073        let queue = Queue::at(dir.path().join("queue"));
6074        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6075        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6076        let mut t = task();
6077        queue.put(&mut t).unwrap();
6078        for enabled in [true, false] {
6079            let stale = queue.get(&t.id).unwrap();
6080            t.set_urgent(enabled).unwrap();
6081            queue.put(&mut t).unwrap();
6082            assert_ne!(stale.urgent, enabled);
6083            let DispatchClaim {
6084                task: fresh,
6085                claim,
6086                permit,
6087            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
6088            assert_eq!(fresh.urgent, enabled);
6089            assert_eq!(ordinary.available_permits(), usize::from(enabled));
6090            assert_eq!(urgent.available_permits(), usize::from(!enabled));
6091            assert!(queue.claim(&t.id).is_err());
6092            assert_eq!(fresh.attempts, stale.attempts);
6093            drop((claim, permit));
6094            assert_eq!(ordinary.available_permits(), 1);
6095            assert_eq!(urgent.available_permits(), 1);
6096        }
6097        t.set_urgent(true).unwrap();
6098        queue.put(&mut t).unwrap();
6099        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
6100        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6101        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
6102        drop(queue.claim(&t.id).unwrap());
6103        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
6104        drop(occupied);
6105        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
6106        drop(queue.claim(&t.id).unwrap());
6107        let held = queue.claim(&t.id).unwrap();
6108        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6109        drop(held);
6110        t.status = TaskStatus::Held;
6111        queue.put(&mut t).unwrap();
6112        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6113        drop(queue.claim(&t.id).unwrap());
6114        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
6115        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6116        drop(queue.claim(&t.id).unwrap());
6117        assert_eq!(urgent.available_permits(), 1);
6118    }
6119
6120    /// The land-resume exemption wins outright, whether or not the candidate
6121    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
6122    /// queue behind anything" guarantee cannot be weaker just because the
6123    /// same task was also filed with `--urgent`.
6124    #[test]
6125    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
6126        assert_eq!(permit_kind(true, false), PermitKind::None);
6127        assert_eq!(permit_kind(true, true), PermitKind::None);
6128    }
6129
6130    /// The one property this whole feature exists for: `--urgent` draws from
6131    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
6132    /// ordinary candidate draws from the ordinary pool exactly as before,
6133    /// untouched by the urgent slot's existence.
6134    #[test]
6135    fn permit_kind_separates_urgent_from_ordinary() {
6136        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
6137        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
6138    }
6139
6140    /// The exact wiring `attempt` runs before minting anything: a config's
6141    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
6142    /// Free space is injected rather than asked of the real disk - the point
6143    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
6144    /// is deterministic on every machine this test runs on, never dependent
6145    /// on how full the CI runner's own disk happens to be.
6146    #[test]
6147    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
6148        let cfg = Config::default();
6149        let repo = Path::new("/any/repo/path");
6150
6151        let reason =
6152            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
6153        assert!(reason.contains("1024"), "{reason}");
6154        assert!(
6155            reason.contains(&cfg.disk.min_free_bytes.to_string()),
6156            "{reason}"
6157        );
6158
6159        assert_eq!(
6160            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
6161            None,
6162            "exactly at the floor is open"
6163        );
6164        assert_eq!(
6165            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
6166            None,
6167            "comfortably above the floor is open"
6168        );
6169    }
6170
6171    #[test]
6172    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
6173        let mut cfg = Config::default();
6174        cfg.disk.min_free_bytes = 0;
6175        let repo = Path::new("/any/repo/path");
6176        assert_eq!(
6177            disk_gate_with(repo, &cfg, |_| Ok(0)),
6178            None,
6179            "a zero floor never measures at all"
6180        );
6181    }
6182
6183    #[test]
6184    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
6185        let cfg = Config::default();
6186        let repo = Path::new("/any/repo/path");
6187        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
6188            .expect("a measurement failure must close the gate, not open it");
6189        assert!(reason.contains("could not measure"), "{reason}");
6190    }
6191
6192    #[test]
6193    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
6194        let ordinary = task();
6195        let next = advance_interrupt(
6196            Interrupt::Idle,
6197            std::slice::from_ref(&ordinary.id),
6198            std::slice::from_ref(&ordinary),
6199        );
6200        assert_eq!(next, Interrupt::Idle);
6201    }
6202
6203    #[test]
6204    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
6205        // Nothing to interrupt - this is just an ordinary candidate, and the
6206        // loop's normal dispatch will pick it up like any other.
6207        let marked = interrupt_task("marked");
6208        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6209        assert_eq!(next, Interrupt::Idle);
6210    }
6211
6212    #[test]
6213    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
6214        let marked = interrupt_task("marked");
6215        let next = advance_interrupt(
6216            Interrupt::Idle,
6217            &["running".to_owned()],
6218            std::slice::from_ref(&marked),
6219        );
6220        assert_eq!(
6221            next,
6222            Interrupt::Parking {
6223                parked: vec!["running".to_owned()],
6224                interrupt_task: "marked".to_owned(),
6225            }
6226        );
6227    }
6228
6229    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
6230    /// one run can be in flight when a task becomes runnable and marked.
6231    /// Parking all of them would mean `Resuming` later has more than one id
6232    /// to release back to ordinary dispatch, which cannot be made safe
6233    /// against that same setting's own extra concurrency slots letting two
6234    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
6235    /// The simplification the task's own constraints ask for: do not begin
6236    /// a sequence at all until the herd settles back to exactly one.
6237    #[test]
6238    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
6239        let marked = interrupt_task("marked");
6240
6241        let two = advance_interrupt(
6242            Interrupt::Idle,
6243            &["a".to_owned(), "b".to_owned()],
6244            std::slice::from_ref(&marked),
6245        );
6246        assert_eq!(two, Interrupt::Idle);
6247
6248        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6249        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
6250    }
6251
6252    #[test]
6253    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
6254        let state = Interrupt::Parking {
6255            parked: vec!["running".to_owned()],
6256            interrupt_task: "marked".to_owned(),
6257        };
6258        // Still in flight: no change.
6259        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
6260        assert_eq!(still_going, state);
6261
6262        // Left flight, but the interrupt task has not been dispatched yet on
6263        // this tick - stays `Parking` so `interrupt_gate` can let it through,
6264        // as long as it is still runnable.
6265        let stopped_but_not_yet_dispatched =
6266            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
6267        assert_eq!(stopped_but_not_yet_dispatched, state);
6268
6269        // Left flight, and the interrupt task is now in flight itself.
6270        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
6271        assert_eq!(
6272            dispatched,
6273            Interrupt::Running {
6274                parked: vec!["running".to_owned()],
6275                interrupt_task: "marked".to_owned(),
6276            }
6277        );
6278    }
6279
6280    #[test]
6281    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
6282        let state = Interrupt::Running {
6283            parked: vec!["running".to_owned()],
6284            interrupt_task: "marked".to_owned(),
6285        };
6286        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
6287        assert_eq!(still_running, state);
6288
6289        // Whatever it ended as - merged, failed, held - is not this
6290        // function's concern: leaving flight is the only trigger, driven
6291        // straight off the same in-flight list `poll` already reaps. It does
6292        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
6293        // why that would let an unrelated task start ahead of, or alongside,
6294        // the guaranteed resume.
6295        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
6296        assert_eq!(
6297            ended,
6298            Interrupt::Resuming {
6299                parked: vec!["running".to_owned()]
6300            }
6301        );
6302    }
6303
6304    #[test]
6305    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
6306        let state = Interrupt::Resuming {
6307            parked: vec!["running".to_owned()],
6308        };
6309        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
6310        assert_eq!(still_waiting, state);
6311
6312        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
6313        assert_eq!(dispatched, Interrupt::Idle);
6314    }
6315
6316    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
6317    /// or otherwise moved on by an operator with no claim standing in the
6318    /// way - must not wedge the sequence (and so the whole loop's dispatch,
6319    /// via `interrupt_gate`) waiting forever for a dispatch that can never
6320    /// come. The parked run still gets its resume.
6321    #[test]
6322    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
6323    {
6324        let state = Interrupt::Parking {
6325            parked: vec!["running".to_owned()],
6326            interrupt_task: "marked".to_owned(),
6327        };
6328        // `marked` has been held/blocked/deleted since the sequence began:
6329        // it no longer appears in `runnable` at all.
6330        let next = advance_interrupt(state, &[], &[]);
6331        assert_eq!(
6332            next,
6333            Interrupt::Resuming {
6334                parked: vec!["running".to_owned()]
6335            },
6336            "abandoning the interrupt must not abandon the resume it owes"
6337        );
6338    }
6339
6340    /// The same abandonment, one step later: `Resuming` itself must not wait
6341    /// forever for a parked task that has since become unrunnable.
6342    #[test]
6343    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
6344        let state = Interrupt::Resuming {
6345            parked: vec!["running".to_owned()],
6346        };
6347        let next = advance_interrupt(state, &[], &[]);
6348        assert_eq!(
6349            next,
6350            Interrupt::Idle,
6351            "nothing is left to wait for; the loop must not stay wedged"
6352        );
6353    }
6354
6355    #[test]
6356    fn disabled_by_config_the_sequence_can_never_leave_idle() {
6357        let marked = interrupt_task("marked");
6358        let next = advance_interrupt_tick(
6359            false,
6360            Interrupt::Idle,
6361            &["running".to_owned()],
6362            std::slice::from_ref(&marked),
6363        );
6364        assert_eq!(
6365            next,
6366            Interrupt::Idle,
6367            "an unmarked, unconfigured daemon must behave exactly as before"
6368        );
6369    }
6370
6371    #[test]
6372    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
6373        let state = Interrupt::Parking {
6374            parked: vec!["running".to_owned()],
6375            interrupt_task: "marked".to_owned(),
6376        };
6377        let candidates = vec![interrupt_task("marked"), task()];
6378        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6379        assert!(
6380            allowed.is_empty(),
6381            "nothing may dispatch - not even the interrupt task itself - \
6382             until the parked run has actually stopped"
6383        );
6384    }
6385
6386    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
6387    /// grow a special case for it: an urgent candidate that is not the
6388    /// interrupt task withholds exactly like an ordinary one for as long as
6389    /// the parked run it is racing has not actually left flight. A version
6390    /// of this feature once bypassed the gate for urgent candidates, on the
6391    /// theory that a genuinely separate concurrency lane could not collide
6392    /// with 75dd's own; it could, and did - the bypassed task dispatched
6393    /// alongside a run 75dd's own state machine had only *asked* to park,
6394    /// not yet confirmed gone, which is exactly the second run
6395    /// `Interrupt::Parking`'s own doc says must never happen. There is no
6396    /// tick during Parking/Running/Resuming where letting an extra
6397    /// candidate through is safe, urgent or not - the parked run may still
6398    /// be genuinely mid-call.
6399    #[test]
6400    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
6401        for state in [
6402            Interrupt::Parking {
6403                parked: vec!["running".to_owned()],
6404                interrupt_task: "marked".to_owned(),
6405            },
6406            Interrupt::Running {
6407                parked: vec!["running".to_owned()],
6408                interrupt_task: "marked".to_owned(),
6409            },
6410            Interrupt::Resuming {
6411                parked: vec!["running".to_owned()],
6412            },
6413        ] {
6414            let candidates = vec![
6415                interrupt_task("marked"),
6416                urgent_task("hot"),
6417                task_with_id("ordinary"),
6418            ];
6419            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6420            assert!(
6421                !allowed.iter().any(|t| t.id == "hot"),
6422                "an urgent candidate must wait out the same gate as anything \
6423                 else while the run it would run alongside has not actually \
6424                 left flight, for state {state:?}: {allowed:?}"
6425            );
6426        }
6427    }
6428
6429    /// The one case where marking a task `--urgent` and `interrupt` at once
6430    /// is not redundant: once the interrupt sequence's own guaranteed
6431    /// resume/dispatch actually admits the task, it is unaffected by also
6432    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
6433    /// never on the urgent flag.
6434    #[test]
6435    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
6436        let state = Interrupt::Resuming {
6437            parked: vec!["hot".to_owned()],
6438        };
6439        let candidates = vec![urgent_task("hot"), task()];
6440        let allowed = interrupt_gate(&state, &[], candidates);
6441        assert_eq!(
6442            allowed.iter().filter(|t| t.id == "hot").count(),
6443            1,
6444            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
6445        );
6446    }
6447
6448    #[test]
6449    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
6450        let state = Interrupt::Parking {
6451            parked: vec!["running".to_owned()],
6452            interrupt_task: "marked".to_owned(),
6453        };
6454        let other = task();
6455        let candidates = vec![interrupt_task("marked"), other.clone()];
6456        let allowed = interrupt_gate(&state, &[], candidates);
6457        assert_eq!(allowed.len(), 1);
6458        assert_eq!(allowed[0].id, "marked");
6459    }
6460
6461    #[test]
6462    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
6463        let state = Interrupt::Running {
6464            parked: vec!["running".to_owned()],
6465            interrupt_task: "marked".to_owned(),
6466        };
6467        let candidates = vec![task(), task()];
6468        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
6469        assert!(allowed.is_empty());
6470    }
6471
6472    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
6473    /// sequence began (only reachable above the default
6474    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
6475    /// never both in the same tick, which is what "exactly one resume, no
6476    /// simultaneous run" actually requires structurally rather than by
6477    /// coincidence of how many ordinary slots happen to be free.
6478    #[test]
6479    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
6480        let state = Interrupt::Resuming {
6481            parked: vec!["a".to_owned(), "c".to_owned()],
6482        };
6483        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
6484        let allowed = interrupt_gate(&state, &[], candidates);
6485        assert_eq!(
6486            allowed.len(),
6487            1,
6488            "at most one candidate may be offered while resuming: {allowed:?}"
6489        );
6490        assert_eq!(allowed[0].id, "a");
6491    }
6492
6493    #[test]
6494    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
6495        let state = Interrupt::Resuming {
6496            parked: vec!["a".to_owned()],
6497        };
6498        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
6499        assert!(allowed.is_empty());
6500    }
6501
6502    /// The invariant the completion criteria ask for by name: across a whole
6503    /// simulated sequence, there is never a tick where the gate would let
6504    /// through both the parked run's resume and the interrupt task, and
6505    /// exactly one candidate resumes the instant the interrupt task's run
6506    /// ends - never zero, never more than one.
6507    #[test]
6508    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
6509        let running = task(); // id: whatever `Task::new` minted
6510        let marked = interrupt_task("marked");
6511
6512        let mut state = Interrupt::Idle;
6513        // Tick 1: `running` is in flight, `marked` becomes runnable.
6514        let in_flight = vec![running.id.clone()];
6515        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
6516        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
6517        assert!(gated.is_empty(), "still waiting on `running` to park");
6518
6519        // Tick 2: `running` parked and left flight; nothing dispatched yet.
6520        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
6521        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
6522        assert_eq!(
6523            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6524            vec!["marked"],
6525            "only the interrupt task may be offered to the dispatcher now"
6526        );
6527
6528        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
6529        state = advance_interrupt_tick(
6530            true,
6531            state,
6532            &["marked".to_owned()],
6533            std::slice::from_ref(&running),
6534        );
6535        let gated = interrupt_gate(
6536            &state,
6537            &["marked".to_owned()],
6538            vec![marked.clone(), running.clone()],
6539        );
6540        assert!(
6541            gated.is_empty(),
6542            "the parked run must not be offered back while the interrupt \
6543             task is still running"
6544        );
6545
6546        // Tick 4: `marked`'s run reached a terminal status and left flight.
6547        // A higher-priority ordinary task `other` is also runnable now - it
6548        // must not be let through instead of, or alongside, `running`.
6549        let other = task_with_id("other");
6550        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
6551        assert_eq!(
6552            state,
6553            Interrupt::Resuming {
6554                parked: vec![running.id.clone()]
6555            }
6556        );
6557        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
6558        assert_eq!(
6559            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6560            vec![running.id.as_str()],
6561            "exactly the parked run resumes - not the unrelated task, even \
6562             though it was offered first"
6563        );
6564
6565        // Tick 5: `running` is now in flight (dispatched from tick 4's
6566        // gate). Only now does the sequence end and ordinary dispatch fully
6567        // resume.
6568        state = advance_interrupt_tick(
6569            true,
6570            state,
6571            std::slice::from_ref(&running.id),
6572            std::slice::from_ref(&other),
6573        );
6574        assert_eq!(state, Interrupt::Idle);
6575        let gated = interrupt_gate(
6576            &state,
6577            std::slice::from_ref(&running.id),
6578            vec![other.clone()],
6579        );
6580        assert_eq!(
6581            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6582            vec![other.id.as_str()],
6583            "ordinary dispatch is unrestricted again"
6584        );
6585    }
6586
6587    #[test]
6588    fn every_run_status_settles_the_task_it_came_from() {
6589        // run status, resulting task status, attempts still standing after one
6590        let table = [
6591            (RunStatus::Merged, TaskStatus::Done, 1),
6592            (RunStatus::Ready, TaskStatus::Done, 1),
6593            (RunStatus::Stalled, TaskStatus::Failed, 0),
6594            (RunStatus::Blocked, TaskStatus::Failed, 1),
6595            (RunStatus::Failed, TaskStatus::Failed, 1),
6596            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
6597            (RunStatus::Prep, TaskStatus::Failed, 1),
6598            (RunStatus::Implementing, TaskStatus::Failed, 1),
6599            (RunStatus::Judging, TaskStatus::Failed, 1),
6600            (RunStatus::Deliberating, TaskStatus::Failed, 1),
6601            (RunStatus::Voting, TaskStatus::Failed, 1),
6602            (RunStatus::Reviewing, TaskStatus::Failed, 1),
6603            (RunStatus::Gating, TaskStatus::Failed, 1),
6604        ];
6605        for (run, want, attempts) in table {
6606            let mut t = task();
6607            t.start("20260902-000000-aaaa".to_owned());
6608            settle(
6609                &mut t,
6610                Verdict {
6611                    status: run,
6612                    left_pr: false,
6613                    parked: false,
6614                    quota_hit: matches!(run, RunStatus::Stalled),
6615                    no_viable_candidates: false,
6616                },
6617                "why",
6618                2,
6619            );
6620            assert_eq!(t.status, want, "task status after {}", label(run));
6621            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
6622        }
6623    }
6624
6625    #[test]
6626    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
6627        let mut stalled = task();
6628        stalled.start("20260902-000000-aaaa".to_owned());
6629        settle(
6630            &mut stalled,
6631            Verdict {
6632                status: RunStatus::Stalled,
6633                left_pr: false,
6634                parked: false,
6635                quota_hit: true,
6636                no_viable_candidates: false,
6637            },
6638            "quota",
6639            1,
6640        );
6641        assert_eq!(stalled.attempts, 0);
6642        assert!(
6643            stalled.status.runnable(),
6644            "a machine problem must leave the task in line"
6645        );
6646
6647        let mut blocked = task();
6648        blocked.start("20260902-000000-aaaa".to_owned());
6649        settle(
6650            &mut blocked,
6651            Verdict {
6652                status: RunStatus::Blocked,
6653                left_pr: false,
6654                parked: false,
6655                quota_hit: false,
6656                no_viable_candidates: false,
6657            },
6658            "findings open",
6659            1,
6660        );
6661        assert_eq!(blocked.attempts, 1);
6662        assert_eq!(
6663            blocked.status,
6664            TaskStatus::Held,
6665            "the last attempt hands the task to a human"
6666        );
6667    }
6668
6669    #[test]
6670    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
6671        // Attempts to spare: without the pull request this task would go
6672        // straight back in line and run the whole competition again.
6673        let mut delivered = task();
6674        delivered.start("20260903-080619-01c2".to_owned());
6675        settle(
6676            &mut delivered,
6677            Verdict {
6678                status: RunStatus::Blocked,
6679                left_pr: true,
6680                parked: false,
6681                quota_hit: false,
6682                no_viable_candidates: false,
6683            },
6684            "no check status",
6685            4,
6686        );
6687        assert_eq!(
6688            delivered.status,
6689            TaskStatus::Held,
6690            "a pull request waiting on CI or a person is not a retryable failure"
6691        );
6692        assert!(
6693            !delivered.status.runnable(),
6694            "the loop must not pick this task up again"
6695        );
6696        assert_eq!(
6697            delivered.last_error.as_deref(),
6698            Some("no check status"),
6699            "the operator needs to be told what the gate was waiting for"
6700        );
6701
6702        // The same status without a pull request is a plain failure, and with
6703        // attempts left it is retried.
6704        let mut empty_handed = task();
6705        empty_handed.start("20260903-080619-01c2".to_owned());
6706        settle(
6707            &mut empty_handed,
6708            Verdict {
6709                status: RunStatus::Blocked,
6710                left_pr: false,
6711                parked: false,
6712                quota_hit: false,
6713                no_viable_candidates: false,
6714            },
6715            "findings open",
6716            4,
6717        );
6718        assert_eq!(empty_handed.status, TaskStatus::Failed);
6719        assert!(empty_handed.status.runnable());
6720    }
6721
6722    #[test]
6723    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
6724        // Every candidate agreed, with evidence, that nothing belonged in the
6725        // worktree. That is not a confirmed success to close automatically -
6726        // a human still has to check the claim - and it is not an ordinary
6727        // failure either, so this settles exactly like a pull request nobody
6728        // merged yet: `Held`, same as `Blocked` with a PR.
6729        let mut noop = task();
6730        noop.start("20260912-131304-391f".to_owned());
6731        settle(
6732            &mut noop,
6733            Verdict {
6734                status: RunStatus::VerifiedNoop,
6735                left_pr: false,
6736                parked: false,
6737                quota_hit: false,
6738                no_viable_candidates: true,
6739            },
6740            "candidate A: already fixed by b32cfc4, on main",
6741            4,
6742        );
6743        assert_eq!(
6744            noop.status,
6745            TaskStatus::Held,
6746            "an unverified claim is a request for a human, not a failure"
6747        );
6748        assert!(
6749            !noop.status.runnable(),
6750            "the loop must not requeue this on the same unverified claim"
6751        );
6752        // `Task::release` resets attempts to zero the moment a human looks at
6753        // the evidence and lets it run again, so it does not matter here
6754        // whether the one attempt already spent stays spent - what matters is
6755        // that nothing retries this task unattended in the meantime.
6756        assert_eq!(noop.attempts, 1);
6757    }
6758
6759    #[test]
6760    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
6761        // Parking is the operator asking for the process back - to replace the
6762        // binary, most of all. The run's work is intact on disk, so this is
6763        // not a failed attempt, and charging for it would mean a few upgrades
6764        // could exhaust a budget meant for agents that misbehaved.
6765        let mut parked = task();
6766        parked.start("20260903-183634-2d98".to_owned());
6767        settle(
6768            &mut parked,
6769            Verdict {
6770                status: RunStatus::Implementing,
6771                left_pr: false,
6772                quota_hit: false,
6773                parked: true,
6774                no_viable_candidates: false,
6775            },
6776            "parked after `implementing`",
6777            2,
6778        );
6779        assert_eq!(parked.attempts, 0, "a park is refunded");
6780        assert!(
6781            parked.status.runnable(),
6782            "and the task stays in line so the next loop resumes its run"
6783        );
6784        assert_eq!(parked.status, TaskStatus::Parked);
6785        assert_eq!(
6786            parked.park_reason.as_deref(),
6787            Some("parked after `implementing`"),
6788            "the card says where it stopped"
6789        );
6790        assert_eq!(parked.last_error, None, "nothing failed");
6791
6792        // Without the park flag the same non-terminal status is what it always
6793        // was: `execute` returning mid-flight, which is a bug and spends an
6794        // attempt so a task cannot loop on it forever.
6795        let mut broken = task();
6796        broken.start("20260903-183634-2d98".to_owned());
6797        settle(
6798            &mut broken,
6799            Verdict {
6800                status: RunStatus::Implementing,
6801                left_pr: false,
6802                quota_hit: false,
6803                parked: false,
6804                no_viable_candidates: false,
6805            },
6806            "returned mid-flight",
6807            2,
6808        );
6809        assert_eq!(broken.attempts, 1);
6810    }
6811
6812    #[test]
6813    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
6814        // Run e633: quorum lost because two judges answered with the wrong
6815        // JSON shape, `quota: []`. Refunding that takes the bound off the
6816        // retry loop, and each retry pays for a fresh hour-long implement
6817        // wave before it can fail the same way.
6818        let mut flaky = task();
6819        flaky.start("20260903-123023-e633".to_owned());
6820        settle(
6821            &mut flaky,
6822            Verdict {
6823                status: RunStatus::Stalled,
6824                left_pr: false,
6825                parked: false,
6826                quota_hit: false,
6827                no_viable_candidates: false,
6828            },
6829            "verdict rests on 1 of 3 judges",
6830            2,
6831        );
6832        assert_eq!(
6833            flaky.attempts, 1,
6834            "flakiness spends an attempt, so `max_attempts` still bounds it"
6835        );
6836        assert!(flaky.status.runnable(), "and it is still worth retrying");
6837
6838        // The same status, lost to a rate limit, is the machine's fault.
6839        let mut limited = task();
6840        limited.start("20260903-123023-e633".to_owned());
6841        settle(
6842            &mut limited,
6843            Verdict {
6844                status: RunStatus::Stalled,
6845                left_pr: false,
6846                parked: false,
6847                quota_hit: true,
6848                no_viable_candidates: false,
6849            },
6850            "judge-2, judge-3 out of quota",
6851            2,
6852        );
6853        assert_eq!(limited.attempts, 0, "a quota window is refunded");
6854        assert!(limited.status.runnable());
6855
6856        // And the bound really binds: a task that keeps stalling on flakiness
6857        // reaches a human instead of running the roster forever.
6858        let mut worn = task();
6859        for _ in 0..2 {
6860            worn.release();
6861        }
6862        worn.start("20260903-123023-e633".to_owned());
6863        worn.attempts = 2;
6864        settle(
6865            &mut worn,
6866            Verdict {
6867                status: RunStatus::Stalled,
6868                left_pr: false,
6869                parked: false,
6870                quota_hit: false,
6871                no_viable_candidates: false,
6872            },
6873            "no quorum again",
6874            2,
6875        );
6876        assert_eq!(worn.status, TaskStatus::Held);
6877        assert!(!worn.status.runnable());
6878    }
6879
6880    #[test]
6881    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
6882        // The implement wave loses every seat to the same rate limit and
6883        // `after_implement` bails with nothing viable, which surfaces as
6884        // `Failed` rather than `Stalled`. That is the same machine fact the
6885        // `Stalled`-quota row already refunds, and must be refunded the same
6886        // way, or a quota outage quietly holds every task it touches instead
6887        // of leaving them in line for the reset.
6888        let mut wiped_out = task();
6889        wiped_out.start("20260907-025000-a1b2".to_owned());
6890        settle(
6891            &mut wiped_out,
6892            Verdict {
6893                status: RunStatus::Failed,
6894                left_pr: false,
6895                parked: false,
6896                quota_hit: true,
6897                no_viable_candidates: true,
6898            },
6899            "no candidate produced a change; nothing to judge",
6900            2,
6901        );
6902        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
6903        assert!(
6904            wiped_out.status.runnable(),
6905            "a machine problem must leave the task in line"
6906        );
6907
6908        // This is the exemption that must stay narrow: a candidate that did
6909        // produce a change, and then failed for some other reason, still
6910        // spends the attempt even though a seat elsewhere hit its quota.
6911        // Otherwise every ordinary failure that happens to share a run with
6912        // an unrelated rate limit would be refunded for free.
6913        let mut partial_progress = task();
6914        partial_progress.start("20260907-025500-c3d4".to_owned());
6915        settle(
6916            &mut partial_progress,
6917            Verdict {
6918                status: RunStatus::Failed,
6919                left_pr: false,
6920                parked: false,
6921                quota_hit: true,
6922                no_viable_candidates: false,
6923            },
6924            "gate failed on the winning candidate",
6925            2,
6926        );
6927        assert_eq!(
6928            partial_progress.attempts, 1,
6929            "a candidate that actually produced a change spends the attempt \
6930             even though some other seat hit its quota"
6931        );
6932        assert!(partial_progress.status.runnable());
6933    }
6934
6935    #[test]
6936    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
6937        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
6938        // disk, and that construction must reach the same conclusion as the
6939        // one `attempt` builds from a live run, or a crash at exactly the
6940        // wrong moment gives a recovered task a different policy than one a
6941        // daemon finished settling itself.
6942        let mut t = task();
6943        t.start("20260907-025000-a1b2".to_owned());
6944        let mut state = run_state(RunStatus::Failed);
6945        state.quota.push(QuotaLoss {
6946            seat: "cand-a".to_owned(),
6947            node: "implement".to_owned(),
6948            at: Timestamp::now(),
6949            reset: None,
6950        });
6951        assert!(
6952            state.viable().is_empty(),
6953            "no candidate was added, so nothing is viable"
6954        );
6955        reclaim(&mut t, Some(state), 2, "en");
6956        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6957        assert!(t.status.runnable());
6958    }
6959
6960    #[test]
6961    fn a_held_task_is_never_offered_to_the_loop() {
6962        let dir = tempfile::tempdir().unwrap();
6963        let queue = Queue::at(dir.path().to_path_buf());
6964        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6965            let mut t = task();
6966            t.id = format!("2026090{n}-000000-000{n}");
6967            t.priority = priority;
6968            queue.put(&mut t).unwrap();
6969        }
6970        let mut held = task();
6971        held.id = "20260909-000000-9999".to_owned();
6972        held.priority = 99;
6973        held.hold_machine(None);
6974        queue.put(&mut held).unwrap();
6975
6976        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6977        assert_eq!(order.len(), 3);
6978        assert!(!order.contains(&held.id));
6979        assert_eq!(
6980            order.first().cloned(),
6981            queue.next_runnable().map(|t| t.id),
6982            "the loop's first candidate is exactly what the queue offers"
6983        );
6984        assert_eq!(
6985            order,
6986            vec![
6987                "20260902-000000-0002".to_owned(),
6988                "20260903-000000-0003".to_owned(),
6989                "20260901-000000-0001".to_owned(),
6990            ],
6991            "priority first, then oldest, so nothing starves"
6992        );
6993    }
6994
6995    #[test]
6996    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6997        let dir = tempfile::tempdir().unwrap();
6998        let queue = Queue::at(dir.path().to_path_buf());
6999        let mut old = task();
7000        old.id = "20260101-000000-old0".to_owned();
7001        queue.put(&mut old).unwrap();
7002        let mut fresh = task();
7003        fresh.id = "20260101-000000-new0".to_owned();
7004        queue.put(&mut fresh).unwrap();
7005
7006        // No parseable pid at all, so age is the only signal there is to
7007        // check - unlike a real `Queue::claim`, which always names a real,
7008        // and therefore alive, pid this test cannot fake as dead.
7009        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
7010        std::thread::sleep(Duration::from_millis(60));
7011        let live = queue.claim(&fresh.id).unwrap();
7012
7013        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7014        assert_eq!(swept, vec![old.id.clone()]);
7015        assert!(
7016            queue.claim(&old.id).is_ok(),
7017            "an unparseable lock older than the threshold is swept"
7018        );
7019        assert!(
7020            queue.claim(&fresh.id).is_err(),
7021            "a live pid protects its lock regardless of age"
7022        );
7023        drop(live);
7024    }
7025
7026    #[test]
7027    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
7028        // The regression this guards: `sweep` now runs concurrently with
7029        // every attempt this daemon itself has spawned (see
7030        // `InFlightGuard`), not only between them the way a single
7031        // sequential loop once did. A run that legitimately outlives
7032        // `older_than` still has this very process's own live pid sitting in
7033        // its own lock file on every later sweep, and deciding by age alone
7034        // would delete that still-valid claim out from under the attempt
7035        // that holds it - which `reclaim_orphaned_running` would then read
7036        // as abandoned and hand to a second, competing attempt.
7037        let dir = tempfile::tempdir().unwrap();
7038        let queue = Queue::at(dir.path().to_path_buf());
7039        let mut t = task();
7040        t.id = "20260101-000000-live".to_owned();
7041        queue.put(&mut t).unwrap();
7042
7043        let claim = queue.claim(&t.id).unwrap();
7044        std::thread::sleep(Duration::from_millis(60));
7045
7046        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7047        assert!(
7048            swept.is_empty(),
7049            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
7050        );
7051        assert!(
7052            queue.claim(&t.id).is_err(),
7053            "the lock still protects its task"
7054        );
7055        drop(claim);
7056    }
7057
7058    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
7059    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
7060    fn injected_dead_pid() -> u32 {
7061        std::process::id().checked_add(1).unwrap_or(1)
7062    }
7063
7064    #[test]
7065    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
7066        let dir = tempfile::tempdir().unwrap();
7067        let queue = Queue::at(dir.path().to_path_buf());
7068        let mut t = task();
7069        t.id = "20260101-000000-dead".to_owned();
7070        queue.put(&mut t).unwrap();
7071        let dead_pid = injected_dead_pid();
7072
7073        // Written directly rather than through `Queue::claim`, which would
7074        // stamp this test process's own very much alive pid and defeat the
7075        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
7076        // like moments after it died, not six hours later.
7077        std::fs::write(
7078            dir.path().join(format!("{}.lock", t.id)),
7079            dead_pid.to_string(),
7080        )
7081        .unwrap();
7082
7083        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7084            pid != dead_pid
7085        });
7086        assert_eq!(
7087            swept,
7088            vec![t.id.clone()],
7089            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
7090        );
7091        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
7092    }
7093
7094    #[test]
7095    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
7096        let dir = tempfile::tempdir().unwrap();
7097        let queue = Queue::at(dir.path().to_path_buf());
7098        let mut t = task();
7099        t.id = "20260101-000000-late".to_owned();
7100        queue.put(&mut t).unwrap();
7101        let dead_pid = injected_dead_pid();
7102
7103        // Tick one, standing in for the sweep `poll` already runs at
7104        // startup: nothing to find yet.
7105        assert!(
7106            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
7107            "nothing has claimed the task yet"
7108        );
7109
7110        // A second daemon claims the task and dies before it ever writes
7111        // `running`, well after this loop's own startup sweep already ran.
7112        std::fs::write(
7113            dir.path().join(format!("{}.lock", t.id)),
7114            dead_pid.to_string(),
7115        )
7116        .unwrap();
7117
7118        // Tick two, standing in for a poll long into this daemon's uptime:
7119        // the same function, called again, notices what only just appeared -
7120        // proving the sweep is not a one-shot startup check.
7121        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7122            pid != dead_pid
7123        });
7124        assert_eq!(swept, vec![t.id.clone()]);
7125    }
7126
7127    #[test]
7128    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
7129        // `reclaim_orphaned_running` looks up the task's last run, which
7130        // touches `run::home()`; the first call anywhere in this binary wins,
7131        // so this is a no-op if another test already pinned one, and either
7132        // way the run id below is never written under it.
7133        crate::run::pin_test_home();
7134        let dir = tempfile::tempdir().unwrap();
7135        let queue = Queue::at(dir.path().to_path_buf());
7136        let mut t = task();
7137        t.id = "20260101-000000-crsh".to_owned();
7138        t.status = TaskStatus::Running;
7139        t.attempts = 1;
7140        // No `run.json` behind this id: standing in for a run this test does
7141        // not need to make readable, since the point is the lock, not the
7142        // recovery table `reclaim` already has its own tests for.
7143        t.runs.push("20260904-000000-4043".to_owned());
7144        queue.put(&mut t).unwrap();
7145        let dead_pid = injected_dead_pid();
7146
7147        // The crashed daemon's own claim, naming a pid nothing on the
7148        // machine holds anymore.
7149        std::fs::write(
7150            dir.path().join(format!("{}.lock", t.id)),
7151            dead_pid.to_string(),
7152        )
7153        .unwrap();
7154
7155        // Before the lock is swept the task looks claimed, and
7156        // `reclaim_orphaned_running` must leave it alone - this is exactly
7157        // the bug: a `running` task stranded behind a dead daemon's lock,
7158        // invisible to the claim-as-proof check because the lock outlived
7159        // the process that wrote it.
7160        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
7161        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7162
7163        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7164            pid != dead_pid
7165        });
7166        assert_eq!(swept, vec![t.id.clone()]);
7167
7168        let reclaimed = reclaim_orphaned_running(&queue, 2);
7169        assert_eq!(reclaimed, vec![t.id.clone()]);
7170        let after = queue.get(&t.id).unwrap();
7171        assert_eq!(
7172            after.status,
7173            TaskStatus::Held,
7174            "no run.json to recover from, so a human is asked"
7175        );
7176        assert_eq!(
7177            after.runs,
7178            vec!["20260904-000000-4043".to_owned()],
7179            "the crashed run's id is kept as evidence, not discarded"
7180        );
7181    }
7182
7183    #[test]
7184    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
7185        let dir = tempfile::tempdir().unwrap();
7186        let queue = Queue::at(dir.path().to_path_buf());
7187        let mut t = task();
7188        t.id = "20260101-000000-unknown".to_owned();
7189        queue.put(&mut t).unwrap();
7190        let dead_pid = injected_dead_pid();
7191        std::fs::write(
7192            dir.path().join(format!("{}.lock", t.id)),
7193            dead_pid.to_string(),
7194        )
7195        .unwrap();
7196
7197        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
7198        assert!(swept.is_empty(), "an unknown pid must keep its lock");
7199        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
7200    }
7201
7202    fn run_state_in(status: RunStatus, language: &str) -> RunState {
7203        let mut s = run_state(status);
7204        s.config.graph.language = language.to_owned();
7205        s
7206    }
7207
7208    fn unstarted_verdict(status: RunStatus) -> Verdict {
7209        Verdict {
7210            status,
7211            left_pr: false,
7212            quota_hit: false,
7213            parked: false,
7214            no_viable_candidates: false,
7215        }
7216    }
7217
7218    #[test]
7219    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
7220        let mut t = task();
7221        t.attempts = 1;
7222        settle_in(
7223            &mut t,
7224            unstarted_verdict(RunStatus::AlreadyInBase),
7225            "already in main",
7226            1,
7227            phrases("en"),
7228        );
7229        assert_eq!(t.status, TaskStatus::Done);
7230        assert_eq!(t.attempts, 0);
7231    }
7232
7233    #[test]
7234    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
7235        let reason = |language: &str| {
7236            let mut t = task();
7237            settle_in(
7238                &mut t,
7239                unstarted_verdict(RunStatus::Judging),
7240                "boom",
7241                1,
7242                phrases(language),
7243            );
7244            t.last_error.or(t.hold_reason).unwrap_or_default()
7245        };
7246        assert!(
7247            reason("en").starts_with("the graph stopped at `"),
7248            "{}",
7249            reason("en")
7250        );
7251        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
7252        assert!(reason("日本語").contains("boom"));
7253        assert_eq!(reason("fr"), reason("en"));
7254    }
7255
7256    #[test]
7257    fn describe_follows_the_run_language_and_keeps_the_run_id() {
7258        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
7259        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
7260        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
7261        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
7262        assert!(ja.contains("[run "), "{ja}");
7263        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
7264        assert!(ended.starts_with("run 終了: "), "{ended}");
7265        let mut de = run_state_in(RunStatus::Failed, "de");
7266        let mut en = run_state_in(RunStatus::Failed, "en");
7267        de.id = "same".to_owned();
7268        en.id = "same".to_owned();
7269        assert_eq!(describe(&de), describe(&en));
7270    }
7271
7272    #[test]
7273    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
7274        use crate::handover::Refused;
7275        let cases = [
7276            Refused::Foreign {
7277                branch: "b".into(),
7278                path: "/w/x".into(),
7279                why: "made by hand".into(),
7280            },
7281            Refused::Unsafe {
7282                branch: "b".into(),
7283                path: "/w/x".into(),
7284                why: "its worktree has uncommitted changes (a.rs)".into(),
7285            },
7286            Refused::ReleaseFailed {
7287                branch: "b".into(),
7288                path: "/w/x".into(),
7289                run: "ab12".into(),
7290            },
7291        ];
7292        for r in &cases {
7293            let en = (phrases("en").handover_refused)(r);
7294            assert_eq!(en, r.to_string());
7295            let ja = (phrases("ja").handover_refused)(r);
7296            assert!(
7297                !ja.contains("is checked out") && !ja.contains("try again"),
7298                "{ja}"
7299            );
7300            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
7301            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
7302                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
7303            }
7304        }
7305        assert!(phrases("en").handover_hint.contains("release the task"));
7306        assert!(phrases("ja").handover_hint.contains("解放"));
7307    }
7308
7309    #[test]
7310    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
7311        let build = |lang: &str| {
7312            let mut s = run_state_in(RunStatus::Blocked, lang);
7313            s.id = "same".to_owned();
7314            s.config.graph.review_rounds = 3;
7315            let mut r = review_round(3);
7316            r.expected = 3;
7317            r.answered = 1;
7318            s.reviews.push(r);
7319            s.event(
7320                "review",
7321                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
7322            );
7323            s
7324        };
7325        let en = describe(&build("en"));
7326        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
7327        let ja = describe(&build("ja"));
7328        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
7329        assert!(!ja.contains("never answered"), "{ja}");
7330        assert!(ja.contains("[run "), "{ja}");
7331
7332        // An incomplete panel whose verification failed is a different stop:
7333        // the real event must survive in ja too.
7334        let mut failed = build("ja");
7335        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
7336            command: "cargo test".to_owned(),
7337            code: Some(1),
7338            output_tail: String::new(),
7339            duration_ms: 0,
7340            resource_blocked: false,
7341        });
7342        failed.event("review", "stopped; e2e failed: cargo test");
7343        let ja = describe(&failed);
7344        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
7345        assert!(!ja.contains("席のレビュアー"), "{ja}");
7346    }
7347
7348    #[test]
7349    fn refusals_and_recovery_prose_follow_the_language() {
7350        let t = held_task_with("r1");
7351        let q = action_question(
7352            "r1",
7353            ask::ChoiceAction::Resume {
7354                run: "r1".to_owned(),
7355            },
7356        );
7357        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
7358            ActionDecision::Refuse(s) => s,
7359            other => panic!("{other:?}"),
7360        };
7361        assert!(refuse(phrases("en")).contains("could not be read: gone"));
7362        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
7363        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
7364
7365        let mut held = task();
7366        reclaim(&mut held, None, 2, "ja");
7367        assert!(held.hold_reason.unwrap().contains("保留にしました"));
7368        let mut held = task();
7369        reclaim(&mut held, None, 2, "xx");
7370        assert!(held.hold_reason.unwrap().contains("held for a human"));
7371    }
7372
7373    fn run_state(status: RunStatus) -> RunState {
7374        let mut state = RunState::new(
7375            PathBuf::from("/repo"),
7376            "main".to_owned(),
7377            "abc1234def".to_owned(),
7378            "add retries".to_owned(),
7379            Config::default(),
7380        );
7381        state.status = status;
7382        state
7383    }
7384
7385    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
7386        Candidate {
7387            index: 0,
7388            label,
7389            agent: "claude".to_owned(),
7390            branch: format!("magi/x/{label}"),
7391            worktree: PathBuf::from("/repo"),
7392            summary: summary.to_owned(),
7393            stat: String::new(),
7394            files: 0,
7395            commits: usize::from(!empty),
7396            empty,
7397            failed: failed.map(str::to_owned),
7398            verified_noop: None,
7399            duration_ms: 0,
7400            folded: false,
7401        }
7402    }
7403
7404    #[test]
7405    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
7406        let mut state = run_state(RunStatus::Blocked);
7407        state.gate = vec![
7408            CommandOutcome {
7409                command: "cargo make check".to_owned(),
7410                code: Some(0),
7411                output_tail: "ok".to_owned(),
7412                duration_ms: 0,
7413                resource_blocked: false,
7414            },
7415            CommandOutcome {
7416                command: "cargo test".to_owned(),
7417                code: Some(101),
7418                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
7419                duration_ms: 0,
7420                resource_blocked: false,
7421            },
7422        ];
7423        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
7424        assert!(d.contains("cargo test"), "{d}");
7425        assert!(
7426            !d.contains("cargo make check"),
7427            "a passing check is not a diagnostic: {d}"
7428        );
7429        assert!(d.contains("assertion failed"), "{d}");
7430    }
7431
7432    #[test]
7433    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
7434        let mut state = run_state(RunStatus::Blocked);
7435        state.event(
7436            "land",
7437            "stopped: the fixer produced no commit while 2 check(s) were failing \
7438             (build, lint); stopping instead of looping on an unchanged tree",
7439        );
7440        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
7441        assert!(d.contains("build"), "{d}");
7442        assert!(d.contains("lint"), "{d}");
7443        assert!(d.contains("fixer produced no commit"), "{d}");
7444    }
7445
7446    #[test]
7447    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
7448        // `describe`'s output becomes `Task::last_error` verbatim, and the
7449        // phone renders that in the same alarm-styled box an ordinary
7450        // failure gets. A bare `verified_noop` there would read exactly like
7451        // the failure this status exists to be told apart from.
7452        let state = run_state(RunStatus::VerifiedNoop);
7453        let d = describe(&state);
7454        assert!(
7455            d.contains("agent-verified no-op"),
7456            "expected the display label, not the wire spelling: {d}"
7457        );
7458        assert!(!d.contains("verified_noop"), "{d}");
7459    }
7460
7461    #[test]
7462    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
7463        // The whole point of the feature: a run held as "no candidate produced
7464        // a change" can mean the implementer actually finished the task and
7465        // only left a clean local tree behind - see AGENTS.md on this exact
7466        // failure mode. The diagnostic has to carry what the agent actually
7467        // said, not just the fact that nothing was there to judge.
7468        let mut state = run_state(RunStatus::Failed);
7469        state.candidates = vec![candidate(
7470            'A',
7471            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
7472            true,
7473            None,
7474        )];
7475        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
7476        assert!(d.contains("candidate A"), "{d}");
7477        assert!(d.contains("tagged v1.2.3"), "{d}");
7478    }
7479
7480    #[test]
7481    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
7482        let mut state = run_state(RunStatus::Failed);
7483        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
7484        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
7485        assert!(d.contains("candidate A"), "{d}");
7486        assert!(d.contains("agent timed out"), "{d}");
7487    }
7488
7489    #[test]
7490    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
7491        // A viable candidate existed, the gate never ran, and nothing land
7492        // said matches - `Task::last_error` is left to explain this one alone.
7493        let mut state = run_state(RunStatus::Failed);
7494        state.candidates = vec![candidate('A', "did the work", false, None)];
7495        assert!(diagnostic(&state).is_none());
7496    }
7497
7498    #[test]
7499    fn diagnostic_is_bounded_however_much_a_run_printed() {
7500        let mut state = run_state(RunStatus::Blocked);
7501        state.gate = vec![
7502            CommandOutcome {
7503                command: "cargo test".to_owned(),
7504                code: Some(101),
7505                output_tail: "x".repeat(50_000),
7506                duration_ms: 0,
7507                resource_blocked: false,
7508            },
7509            CommandOutcome {
7510                command: "cargo clippy".to_owned(),
7511                code: Some(1),
7512                output_tail: "y".repeat(50_000),
7513                duration_ms: 0,
7514                resource_blocked: false,
7515            },
7516        ];
7517        state.candidates = vec![
7518            candidate('A', &"z".repeat(50_000), true, None),
7519            candidate('B', &"w".repeat(50_000), true, None),
7520        ];
7521        let d = diagnostic(&state).expect("plenty here to diagnose");
7522        assert!(
7523            d.len() <= DIAGNOSTIC_MAX,
7524            "diagnostic grew to {} bytes, unbounded",
7525            d.len()
7526        );
7527    }
7528
7529    #[test]
7530    fn selected_delivery_guards_survive_recovery_failure_accounting() {
7531        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
7532            let mut t = task();
7533            let mut state = run_state(status);
7534            t.pr_recovery = Some(crate::pr_recovery::Selection {
7535                url: "url".into(),
7536                branch: format!("magi/task-{}", t.id),
7537                head: "a".repeat(40),
7538                source_head: None,
7539                source_run: None,
7540                source_proof: None,
7541                disposition: Some(crate::pr_recovery::Disposition::Land),
7542                instruction: t.instruction.clone(),
7543                approved_at: Timestamp::now(),
7544            });
7545            state.pr_recovery = t.pr_recovery.clone();
7546            t.start(state.id.clone());
7547            settle_and_diagnose(
7548                &mut t,
7549                Verdict {
7550                    status,
7551                    left_pr: false,
7552                    quota_hit: false,
7553                    parked: false,
7554                    no_viable_candidates: false,
7555                },
7556                "delivery stopped",
7557                5,
7558                &state,
7559            );
7560            assert_eq!(t.status, TaskStatus::Held);
7561            let reason = t.hold_reason.as_deref().unwrap();
7562            if status == RunStatus::Ready {
7563                assert!(reason.contains("Selected PR delivery is incomplete"));
7564                assert!(t.recovery_budget.is_none());
7565            } else {
7566                assert!(reason.contains("Selected recovery stopped"));
7567                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
7568            }
7569            assert!(t.pr_recovery.is_some());
7570        }
7571    }
7572
7573    #[test]
7574    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
7575        let mut state = run_state(RunStatus::Blocked);
7576        state.gate = vec![CommandOutcome {
7577            command: "cargo test".to_owned(),
7578            code: Some(101),
7579            output_tail: "assertion failed".to_owned(),
7580            duration_ms: 0,
7581            resource_blocked: false,
7582        }];
7583        let verdict = Verdict {
7584            status: RunStatus::Blocked,
7585            left_pr: false,
7586            quota_hit: false,
7587            parked: false,
7588            no_viable_candidates: false,
7589        };
7590
7591        // Attempt one of two still has a retry coming: no diagnostic yet, the
7592        // task is going to run again and this run's evidence would go stale.
7593        let mut t = task();
7594        t.start("run-1".to_owned());
7595        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7596        assert_eq!(t.status, TaskStatus::Failed);
7597        assert!(t.diagnostic.is_none());
7598
7599        // Attempt two exhausts the budget: now it is held, and the
7600        // diagnostic is what `magi task show` has to say more than one line.
7601        t.start("run-2".to_owned());
7602        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7603        assert_eq!(t.status, TaskStatus::Held);
7604        let d = t.diagnostic.expect("a held task must carry its diagnostic");
7605        assert!(d.contains("cargo test"), "{d}");
7606    }
7607
7608    #[test]
7609    fn a_held_task_names_the_open_question_it_is_waiting_on() {
7610        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
7611        // `magi ask` question settled Held with `hold_reason: null`, so the
7612        // notification said nothing actionable. `note_open_question` should
7613        // append the question id to whatever `handed_off` already wrote.
7614        crate::run::pin_test_home();
7615        let home = crate::run::home();
7616        let state = run_state(RunStatus::VerifiedNoop);
7617        let mut q = ask::Question::new(
7618            state.id.clone(),
7619            "implement".to_owned(),
7620            "impl-A".to_owned(),
7621            "is this really a no-op?".to_owned(),
7622            String::new(),
7623            Vec::new(),
7624        );
7625        Questions::at(home.join("questions")).put(&mut q).unwrap();
7626
7627        let verdict = Verdict {
7628            status: RunStatus::VerifiedNoop,
7629            left_pr: false,
7630            quota_hit: false,
7631            parked: false,
7632            no_viable_candidates: false,
7633        };
7634        let mut t = task();
7635        t.start(state.id.clone());
7636        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7637
7638        assert_eq!(t.status, TaskStatus::Held);
7639        let reason = t.hold_reason.expect("a held task must record why");
7640        assert!(
7641            reason.starts_with("run ended agent-verified no-op"),
7642            "the original settle reason must survive unchanged: {reason}"
7643        );
7644        assert!(
7645            reason.contains(q.short()),
7646            "the open question's id must be named so the notice is actionable: {reason}"
7647        );
7648    }
7649
7650    #[test]
7651    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
7652        crate::run::pin_test_home();
7653        let state = run_state(RunStatus::VerifiedNoop);
7654
7655        let verdict = Verdict {
7656            status: RunStatus::VerifiedNoop,
7657            left_pr: false,
7658            quota_hit: false,
7659            parked: false,
7660            no_viable_candidates: false,
7661        };
7662        let mut t = task();
7663        t.start(state.id.clone());
7664        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7665
7666        assert_eq!(t.status, TaskStatus::Held);
7667        assert_eq!(
7668            t.hold_reason.as_deref(),
7669            Some("run ended agent-verified no-op"),
7670            "nothing to append when the question was already answered or never asked"
7671        );
7672    }
7673
7674    #[test]
7675    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
7676        crate::run::pin_test_home();
7677        let mut first = run_state(RunStatus::Blocked);
7678        first.id = "20260101-000000-sup1".to_owned();
7679        first.save().unwrap();
7680        let mut second = run_state(RunStatus::Merged);
7681        second.id = "20260101-000000-sup2".to_owned();
7682        second.save().unwrap();
7683
7684        let mut t = task();
7685        t.runs = vec![first.id.clone(), second.id.clone()];
7686        t.status = TaskStatus::Done;
7687
7688        supersede_prior_runs(&t, &crate::run::home());
7689
7690        assert_eq!(
7691            RunState::load(&first.id).unwrap().status,
7692            RunStatus::Superseded,
7693            "the first attempt's Blocked no longer needs anyone's attention"
7694        );
7695        assert_eq!(
7696            RunState::load(&second.id).unwrap().status,
7697            RunStatus::Merged,
7698            "the run that actually succeeded is left exactly as it was"
7699        );
7700    }
7701
7702    #[test]
7703    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
7704        // `is_working_on` alone only proves a *daemon* claim; a `magi run
7705        // --resume` invoked by hand outside the daemon never touches
7706        // `daemon.json` at all, so it would look identical to a genuinely
7707        // idle run without also consulting `RunState::liveness`, which reads
7708        // this run's own recorded `driver_pid` instead.
7709        crate::run::pin_test_home();
7710        let mut first = run_state(RunStatus::Blocked);
7711        first.id = "20260101-000000-sup9".to_owned();
7712        // This test process's own pid: guaranteed alive without needing a
7713        // real second process or daemon.
7714        first.driver_pid = Some(std::process::id());
7715        first.driver_started_at = Some(
7716            crate::proc::process_started_at(std::process::id())
7717                .expect("this test process's own start time must be queryable"),
7718        );
7719        first.save().unwrap();
7720        let mut second = run_state(RunStatus::Merged);
7721        second.id = "20260101-000000-supa".to_owned();
7722        second.save().unwrap();
7723
7724        let mut t = task();
7725        t.runs = vec![first.id.clone(), second.id.clone()];
7726        t.status = TaskStatus::Done;
7727
7728        supersede_prior_runs(&t, &crate::run::home());
7729
7730        assert_eq!(
7731            RunState::load(&first.id).unwrap().status,
7732            RunStatus::Blocked,
7733            "a live driver_pid means something is still actually working this run, \
7734             even though no daemon claims it - rewriting under it would just be \
7735             undone the next time that process saves"
7736        );
7737    }
7738
7739    #[test]
7740    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
7741        // The first resweep must skip a still-live attempt exactly like
7742        // `supersede_prior_runs` itself does; a later resweep, once that
7743        // process is no longer actually driving it, is what closes the gap
7744        // `supersede_prior_runs` alone leaves - a task only ever reaches
7745        // `Done` once, so nothing else would ever look at this run again.
7746        let dir = tempfile::tempdir().unwrap();
7747        let home = dir.path().to_path_buf();
7748        let queue = Queue::at(dir.path().join("queue"));
7749
7750        let mut first = run_state(RunStatus::Blocked);
7751        first.id = "20260101-000000-supd".to_owned();
7752        first.driver_pid = Some(std::process::id());
7753        first.driver_started_at = Some(
7754            crate::proc::process_started_at(std::process::id())
7755                .expect("this test process's own start time must be queryable"),
7756        );
7757        first.save_under(&home).unwrap();
7758        let mut second = run_state(RunStatus::Merged);
7759        second.id = "20260101-000000-supe".to_owned();
7760        second.save_under(&home).unwrap();
7761
7762        let mut t = task();
7763        t.runs = vec![first.id.clone(), second.id.clone()];
7764        t.status = TaskStatus::Done;
7765        queue.put(&mut t).unwrap();
7766
7767        resweep_superseded_attempts(&queue, &home);
7768        assert_eq!(
7769            RunState::load_under(&first.id, &home).unwrap().status,
7770            RunStatus::Blocked,
7771            "still live on the first pass, so still untouched"
7772        );
7773
7774        // Stand in for the manual process no longer being the one driving
7775        // this run: same pid (this test process really is still alive), but
7776        // an identity marker that no longer matches it - see
7777        // `RunState::liveness`'s own doc for why a mismatched
7778        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
7779        let mut stale = RunState::load_under(&first.id, &home).unwrap();
7780        stale.driver_started_at = Some("1".to_owned());
7781        stale.save_under(&home).unwrap();
7782
7783        resweep_superseded_attempts(&queue, &home);
7784        assert_eq!(
7785            RunState::load_under(&first.id, &home).unwrap().status,
7786            RunStatus::Superseded,
7787            "the second pass catches up what the first one correctly skipped"
7788        );
7789    }
7790
7791    #[test]
7792    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
7793        crate::run::pin_test_home();
7794        let mut first = run_state(RunStatus::Blocked);
7795        first.id = "20260101-000000-sup3".to_owned();
7796        first.save().unwrap();
7797        let mut second = run_state(RunStatus::Blocked);
7798        second.id = "20260101-000000-sup4".to_owned();
7799        second.save().unwrap();
7800
7801        let mut t = task();
7802        t.runs = vec![first.id.clone(), second.id.clone()];
7803        // Still retrying: nothing about this task's story is settled yet, so
7804        // neither Blocked run may be relabelled, even though a later attempt
7805        // already exists.
7806        t.status = TaskStatus::Failed;
7807
7808        supersede_prior_runs(&t, &crate::run::home());
7809
7810        assert_eq!(
7811            RunState::load(&first.id).unwrap().status,
7812            RunStatus::Blocked
7813        );
7814        assert_eq!(
7815            RunState::load(&second.id).unwrap().status,
7816            RunStatus::Blocked
7817        );
7818    }
7819
7820    #[test]
7821    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
7822        // `magi task done` (or the API's equivalent) can close a task with no
7823        // run of its own ever having succeeded - there is nothing here that
7824        // counts as "the attempt that finished it", so nothing is rewritten.
7825        crate::run::pin_test_home();
7826        let mut first = run_state(RunStatus::Blocked);
7827        first.id = "20260101-000000-sup5".to_owned();
7828        first.save().unwrap();
7829
7830        let mut t = task();
7831        t.runs = vec![first.id.clone()];
7832        t.status = TaskStatus::Done;
7833
7834        supersede_prior_runs(&t, &crate::run::home());
7835
7836        assert_eq!(
7837            RunState::load(&first.id).unwrap().status,
7838            RunStatus::Blocked,
7839            "a single-attempt task has no earlier run to supersede"
7840        );
7841    }
7842
7843    #[test]
7844    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
7845        // `magi task done` (or the web/conductor equivalents) can close a
7846        // task in any status, including one whose *last* recorded attempt is
7847        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
7848        // never watched, say. `runs.last()` being `Done`-adjacent is not
7849        // proof it actually succeeded, so nothing earlier may be relabelled
7850        // on its say-so alone.
7851        crate::run::pin_test_home();
7852        let mut first = run_state(RunStatus::Blocked);
7853        first.id = "20260101-000000-supb".to_owned();
7854        first.save().unwrap();
7855        let mut second = run_state(RunStatus::Failed);
7856        second.id = "20260101-000000-supc".to_owned();
7857        second.save().unwrap();
7858
7859        let mut t = task();
7860        t.runs = vec![first.id.clone(), second.id.clone()];
7861        t.status = TaskStatus::Done;
7862
7863        supersede_prior_runs(&t, &crate::run::home());
7864
7865        assert_eq!(
7866            RunState::load(&first.id).unwrap().status,
7867            RunStatus::Blocked,
7868            "the task's last attempt never landed, so there is nothing here \
7869             actually superseding it"
7870        );
7871    }
7872
7873    #[test]
7874    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
7875        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
7876        // to look" - `Failed` and `VerifiedNoop` are already their own
7877        // terminal answers and must not be relabelled into a third one.
7878        crate::run::pin_test_home();
7879        let mut failed = run_state(RunStatus::Failed);
7880        failed.id = "20260101-000000-sup6".to_owned();
7881        failed.save().unwrap();
7882        let mut noop = run_state(RunStatus::VerifiedNoop);
7883        noop.id = "20260101-000000-sup7".to_owned();
7884        noop.save().unwrap();
7885        let mut winner = run_state(RunStatus::Ready);
7886        winner.id = "20260101-000000-sup8".to_owned();
7887        winner.save().unwrap();
7888
7889        let mut t = task();
7890        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
7891        t.status = TaskStatus::Done;
7892
7893        supersede_prior_runs(&t, &crate::run::home());
7894
7895        assert_eq!(
7896            RunState::load(&failed.id).unwrap().status,
7897            RunStatus::Failed
7898        );
7899        assert_eq!(
7900            RunState::load(&noop.id).unwrap().status,
7901            RunStatus::VerifiedNoop
7902        );
7903    }
7904
7905    fn approval_question(run: &str) -> ask::Question {
7906        ask::Question::new(
7907            run.to_owned(),
7908            land::APPROVAL_NODE.to_owned(),
7909            "land".to_owned(),
7910            "merge?".to_owned(),
7911            String::new(),
7912            vec!["merge".to_owned(), "hold".to_owned()],
7913        )
7914    }
7915
7916    #[test]
7917    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
7918        crate::run::pin_test_home();
7919        let mut state = run_state(RunStatus::Landing);
7920        state.id = "20260101-000000-fre1".to_owned();
7921        state.parked = true;
7922        state.save().unwrap();
7923        ask::Questions::open()
7924            .put(&mut approval_question(&state.id))
7925            .unwrap();
7926
7927        let mut t = task();
7928        t.runs.push(state.id.clone());
7929        assert_eq!(
7930            land_resume_state(&t),
7931            LandResume::StillWaiting,
7932            "nobody has answered and the timeout has not passed"
7933        );
7934    }
7935
7936    #[test]
7937    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
7938        crate::run::pin_test_home();
7939        let mut state = run_state(RunStatus::Gating);
7940        state.id = "20260101-000000-gt01".to_owned();
7941        state.parked = true;
7942        state.config.graph.answer_timeout = 60;
7943        state.github_text = Some(crate::run::GithubTextAsk {
7944            rewrite: None,
7945            fingerprint: "f".into(),
7946            title: true,
7947            body: false,
7948            categories: vec!["title-language".into()],
7949            question: None,
7950            asks: 1,
7951            resolved: false,
7952            chosen_title: None,
7953            choice: None,
7954        });
7955        state.save().unwrap();
7956        let store = ask::Questions::open();
7957        let mut q = ask::Question::new(
7958            state.id.clone(),
7959            crate::github_text::ASK_NODE.to_owned(),
7960            crate::github_text::ASK_SEAT.to_owned(),
7961            "s".into(),
7962            String::new(),
7963            vec!["use fallback".into()],
7964        );
7965        store.put(&mut q).unwrap();
7966        let mut t = task();
7967        t.runs.push(state.id.clone());
7968        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
7969        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7970        store.put(&mut q).unwrap();
7971        assert_eq!(land_resume_state(&t), LandResume::Ready);
7972        assert!(!store.get(&q.id).unwrap().status.open());
7973        // Once decided, a parked run is an ordinary candidate again.
7974        state.github_text.as_mut().unwrap().resolved = true;
7975        state.save().unwrap();
7976        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
7977    }
7978
7979    #[test]
7980    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
7981        // `ask::ask_and_wait`'s own deadline used to retire a question
7982        // nobody answered; land's approval bypasses that wait (see
7983        // `land::approval_gate`), so this is now the only place
7984        // `graph.answer_timeout` is enforced for a land approval at all.
7985        crate::run::pin_test_home();
7986        let mut state = run_state(RunStatus::Landing);
7987        state.id = "20260101-000000-exp1".to_owned();
7988        state.parked = true;
7989        state.config.graph.answer_timeout = 60;
7990        state.save().unwrap();
7991
7992        let store = ask::Questions::open();
7993        let mut q = approval_question(&state.id);
7994        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7995        store.put(&mut q).unwrap();
7996
7997        let mut t = task();
7998        t.runs.push(state.id.clone());
7999        assert_eq!(
8000            land_resume_state(&t),
8001            LandResume::Ready,
8002            "an expired question must not be waited on forever"
8003        );
8004
8005        let after = store.get(&q.id).unwrap();
8006        assert!(
8007            !after.status.open(),
8008            "the question is abandoned, not silently ignored"
8009        );
8010        assert!(
8011            after.resolution().is_none(),
8012            "an abandoned question is not read as a decision"
8013        );
8014    }
8015
8016    #[test]
8017    fn reclaim_settles_a_running_task_against_its_last_run() {
8018        let mut t = task();
8019        t.start("20260904-000000-4043".to_owned());
8020        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
8021        assert_eq!(
8022            t.status,
8023            TaskStatus::Done,
8024            "a run that actually finished must not stay `running` forever"
8025        );
8026    }
8027
8028    #[test]
8029    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
8030        let mut t = task();
8031        t.start("20260904-000000-4043".to_owned());
8032        t.last_error = Some("earlier trouble".to_owned());
8033        let mut state = run_state(RunStatus::Judging);
8034        state.parked = true;
8035        reclaim(&mut t, Some(state), 1, "en");
8036        assert_eq!(t.status, TaskStatus::Parked);
8037        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
8038        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8039        assert!(t.park_reason.is_some());
8040        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
8041        assert!(!t.fresh_start);
8042        assert!(t.status.runnable());
8043    }
8044
8045    #[test]
8046    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
8047        let mut t = task();
8048        t.start("20260904-000000-4043".to_owned());
8049        t.last_error = Some("earlier trouble".to_owned());
8050        settle(
8051            &mut t,
8052            Verdict {
8053                status: RunStatus::Judging,
8054                left_pr: false,
8055                quota_hit: false,
8056                parked: true,
8057                no_viable_candidates: false,
8058            },
8059            "parked after `judging`",
8060            1,
8061        );
8062        assert_eq!(t.status, TaskStatus::Parked);
8063        assert_eq!(t.attempts, 0);
8064        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8065        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
8066        assert_eq!(t.schema, crate::queue::SCHEMA);
8067        assert!(
8068            crate::notices::task_held(&t).is_none(),
8069            "a park is not news"
8070        );
8071        t.start("20260904-000000-4043".to_owned());
8072        assert_eq!(t.park_reason, None);
8073    }
8074
8075    #[test]
8076    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
8077        // A blocked run with attempts left goes back to `Failed`, exactly as
8078        // it would from `attempt` itself - `reclaim` must not invent a second
8079        // policy for a task a daemon merely stopped without reporting.
8080        let mut t = task();
8081        t.start("20260904-000000-4043".to_owned());
8082        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
8083        assert_eq!(t.status, TaskStatus::Failed);
8084        assert!(t.status.runnable());
8085    }
8086
8087    #[test]
8088    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
8089        let mut t = task();
8090        t.start("20260904-000000-4043".to_owned());
8091        assert_eq!(t.attempts, 1);
8092        let mut run = run_state(RunStatus::Implementing);
8093        run.id = "20260904-000000-4043".to_owned();
8094        run.begin_pass();
8095        let cause = crate::run::ParkCause::Upgrade {
8096            from: "0.121.0".to_owned(),
8097            to: Some("0.121.1".to_owned()),
8098        };
8099        run.end_pass_parked(cause.clone());
8100        run.parked = true;
8101        let verdict = Verdict {
8102            status: run.status,
8103            left_pr: false,
8104            quota_hit: false,
8105            parked: true,
8106            no_viable_candidates: false,
8107        };
8108        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
8109        assert_eq!(t.attempts, 0);
8110        assert_eq!(t.passes.len(), 1);
8111        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8112        assert_eq!(t.passes[0].parked, Some(cause));
8113        assert_eq!(t.passes[0].pass_index, 0);
8114
8115        // A resumed pass that then fails spends its attempt, and the earlier
8116        // pass's entry is untouched.
8117        t.start("20260904-000000-4043".to_owned());
8118        run.begin_pass();
8119        run.status = RunStatus::Failed;
8120        let verdict = Verdict {
8121            status: RunStatus::Failed,
8122            left_pr: false,
8123            quota_hit: false,
8124            parked: false,
8125            no_viable_candidates: false,
8126        };
8127        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
8128        assert_eq!(t.passes.len(), 2);
8129        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8130        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
8131        assert_eq!(t.passes[1].pass_index, 1);
8132        assert_eq!(t.attempts, 1);
8133    }
8134
8135    #[test]
8136    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
8137        let mut t = task();
8138        t.start("20260904-000000-4043".to_owned());
8139        reclaim(&mut t, None, 2, "en");
8140        assert_eq!(t.status, TaskStatus::Held);
8141        assert!(
8142            t.last_error
8143                .as_deref()
8144                .is_some_and(|e| e.contains("running")),
8145            "the operator needs to know why this task was held"
8146        );
8147    }
8148
8149    #[test]
8150    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
8151        let dir = tempfile::tempdir().unwrap();
8152        let queue = Queue::at(dir.path().to_path_buf());
8153
8154        // No run recorded, so this never has to touch `RunState::load`.
8155        let mut orphaned = task();
8156        orphaned.id = "20260904-000000-orph".to_owned();
8157        orphaned.status = TaskStatus::Running;
8158        orphaned.attempts = 1;
8159        queue.put(&mut orphaned).unwrap();
8160
8161        let mut alive = task();
8162        alive.id = "20260904-000000-live".to_owned();
8163        alive.status = TaskStatus::Running;
8164        alive.attempts = 1;
8165        queue.put(&mut alive).unwrap();
8166        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
8167
8168        let mut queued = task();
8169        queued.id = "20260904-000000-wait".to_owned();
8170        queue.put(&mut queued).unwrap();
8171
8172        let reclaimed = reclaim_orphaned_running(&queue, 2);
8173        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
8174
8175        assert_eq!(
8176            queue.get(&orphaned.id).unwrap().status,
8177            TaskStatus::Held,
8178            "nothing was driving it and there was no run to recover"
8179        );
8180        assert_eq!(
8181            queue.get(&alive.id).unwrap().status,
8182            TaskStatus::Running,
8183            "a live claim must protect the task it belongs to"
8184        );
8185        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
8186    }
8187
8188    /// Read a run.json back from an explicit `home`, the same way
8189    /// `reclaim_abandoned_runs` itself does - never through the
8190    /// process-global `RunState::load`, which this test's own `home` (an
8191    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
8192    /// use at all.
8193    fn read_run_under(home: &Path, id: &str) -> RunState {
8194        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
8195        serde_json::from_str(&body).unwrap()
8196    }
8197
8198    #[test]
8199    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
8200        let dir = tempfile::tempdir().unwrap();
8201        let home = dir.path().to_path_buf();
8202        let now = Timestamp::now();
8203        let overrun_seat = || crate::run::ActiveSeat {
8204            node: "implement".to_owned(),
8205            started_at: now - jiff::SignedDuration::new(21_000, 0),
8206            timeout_secs: 3_600,
8207            attempt: 0,
8208            task: None,
8209            command: None,
8210            index: None,
8211            total: None,
8212        };
8213
8214        let mut dead = run_state(RunStatus::Implementing);
8215        dead.id = "20260101-000000-dead".to_owned();
8216        dead.active.insert("impl-A".to_owned(), overrun_seat());
8217        // A `driver_pid` the injected query below confirms gone outright —
8218        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
8219        dead.driver_pid = Some(4242);
8220        dead.save_under(&home).unwrap();
8221
8222        // Same shape, but a live daemon's heartbeat names it: must be left
8223        // exactly alone, however far past its own timeout the seat sits.
8224        let mut alive = run_state(RunStatus::Implementing);
8225        alive.id = "20260101-000000-aliv".to_owned();
8226        alive.active.insert("impl-A".to_owned(), overrun_seat());
8227        alive.save_under(&home).unwrap();
8228        let mut status = Status::new();
8229        status.current = vec![Current {
8230            task: "20260101-000000-task".to_owned(),
8231            run: alive.id.clone(),
8232        }];
8233        write_status_to(&home.join("daemon.json"), &status).unwrap();
8234
8235        // The abandoned seat left an open question behind: nobody is left to
8236        // read an answer once the run is failed, and this must not wait for
8237        // some later daemon startup's own sweep to notice that.
8238        let questions = Questions::at(home.join("questions"));
8239        let mut q = ask::Question::new(
8240            dead.id.clone(),
8241            "implement".to_owned(),
8242            "impl-A".to_owned(),
8243            "Which storage backend?".to_owned(),
8244            String::new(),
8245            vec!["SQLite".to_owned(), "Redis".to_owned()],
8246        );
8247        questions.put(&mut q).unwrap();
8248
8249        let abandoned = reclaim_abandoned_runs_with(
8250            &home,
8251            now,
8252            |pid| if pid == 4242 { Some(false) } else { None },
8253            |_| panic!("a query answering Dead outright needs no identity corroboration"),
8254        );
8255        assert_eq!(abandoned, vec![dead.id.clone()]);
8256
8257        let reloaded = read_run_under(&home, &dead.id);
8258        assert_eq!(reloaded.status, RunStatus::Failed);
8259        assert!(reloaded.active.is_empty());
8260        assert!(
8261            !questions.get(&q.id).unwrap().status.open(),
8262            "the failed run's own open question must be settled in the same pass"
8263        );
8264
8265        let still_alive = read_run_under(&home, &alive.id);
8266        assert_eq!(
8267            still_alive.status,
8268            RunStatus::Implementing,
8269            "a live daemon's claim protects it"
8270        );
8271        assert!(!still_alive.active.is_empty());
8272    }
8273
8274    /// The exact shape a review round flagged as broken: `magi serve` running
8275    /// in this same `home` scans *every* run on disk, including a manual
8276    /// `magi review` / `magi run` this daemon never started and that
8277    /// therefore claims no heartbeat of its own. Before this scan asked
8278    /// `liveness` rather than just `is_working_on`, a manual run whose active
8279    /// seat merely ran a little past its own timeout — the CLI finishing up,
8280    /// its result still being collected — got wiped and failed by a daemon
8281    /// that had nothing to do with it, out from under a process that was
8282    /// still very much running.
8283    #[test]
8284    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
8285        let dir = tempfile::tempdir().unwrap();
8286        let home = dir.path().to_path_buf();
8287        let now = Timestamp::now();
8288
8289        let mut manual = run_state(RunStatus::Reviewing);
8290        manual.id = "20260101-000000-manl".to_owned();
8291        manual.active.insert(
8292            "review-1".to_owned(),
8293            crate::run::ActiveSeat {
8294                node: "review".to_owned(),
8295                started_at: now - jiff::SignedDuration::new(21_000, 0),
8296                timeout_secs: 3_600,
8297                attempt: 0,
8298                task: None,
8299                command: None,
8300                index: None,
8301                total: None,
8302            },
8303        );
8304        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
8305        // but a real, still-running process: `liveness` must corroborate this
8306        // as `Live`, not read the missing daemon claim as death.
8307        manual.driver_pid = Some(4242);
8308        manual.driver_started_at = Some("1790000000".to_owned());
8309        manual.save_under(&home).unwrap();
8310
8311        let abandoned = reclaim_abandoned_runs_with(
8312            &home,
8313            now,
8314            |pid| if pid == 4242 { Some(true) } else { None },
8315            |pid| {
8316                if pid == 4242 {
8317                    Some("1790000000".to_owned())
8318                } else {
8319                    None
8320                }
8321            },
8322        );
8323        assert!(
8324            abandoned.is_empty(),
8325            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
8326        );
8327
8328        let reloaded = read_run_under(&home, &manual.id);
8329        assert_eq!(reloaded.status, RunStatus::Reviewing);
8330        assert!(!reloaded.active.is_empty());
8331    }
8332
8333    #[test]
8334    fn an_already_claimed_task_is_skipped_rather_than_failed() {
8335        let dir = tempfile::tempdir().unwrap();
8336        let queue = Queue::at(dir.path().to_path_buf());
8337        let mut only = task();
8338        queue.put(&mut only).unwrap();
8339
8340        let _elsewhere = queue.claim(&only.id).unwrap();
8341        let candidates = runnable(&queue);
8342        assert_eq!(candidates.len(), 1, "the task is still runnable");
8343        assert!(
8344            queue.claim(&candidates[0].id).is_err(),
8345            "the loop cannot take a claim somebody else holds"
8346        );
8347
8348        let after = queue.get(&only.id).unwrap();
8349        assert_eq!(after.status, TaskStatus::Queued);
8350        assert_eq!(
8351            after.attempts, 0,
8352            "losing the race is not an attempt at the task"
8353        );
8354        assert_eq!(after.last_error, None);
8355    }
8356
8357    #[test]
8358    fn the_status_file_round_trips_and_its_heartbeat_advances() {
8359        let dir = tempfile::tempdir().unwrap();
8360        let path = dir.path().join("daemon.json");
8361
8362        let mut status = Status::new();
8363        status.idle = false;
8364        status.completed = 7;
8365        status.current = vec![Current {
8366            task: "20260902-000000-t111".to_owned(),
8367            run: "20260902-000001-r111".to_owned(),
8368        }];
8369        write_status_to(&path, &status).unwrap();
8370        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8371        assert_eq!(first.schema, SCHEMA);
8372        assert_eq!(first.pid, std::process::id());
8373        assert!(!first.idle);
8374        assert_eq!(first.completed, 7);
8375        assert_eq!(first.current, status.current);
8376        assert!(
8377            !path.with_extension("json.tmp").exists(),
8378            "the temp file is renamed, not left behind"
8379        );
8380
8381        std::thread::sleep(Duration::from_millis(5));
8382        status.updated_at = Timestamp::now();
8383        status.polls = 3;
8384        write_status_to(&path, &status).unwrap();
8385        let second: Status =
8386            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8387        assert!(
8388            second.updated_at > first.updated_at,
8389            "a reader can only detect staleness if the heartbeat moves"
8390        );
8391        assert_eq!(
8392            second.started_at, first.started_at,
8393            "the start time is not a heartbeat"
8394        );
8395        assert_eq!(second.polls, 3);
8396    }
8397
8398    #[test]
8399    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
8400        let dir = tempfile::tempdir().unwrap();
8401
8402        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
8403
8404        let mut status = Status::new();
8405        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
8406        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8407        let stale = read_status(dir.path()).unwrap();
8408        assert!(
8409            !stale.running(Timestamp::now()),
8410            "a minute without a heartbeat is a dead daemon, not a busy one"
8411        );
8412        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
8413
8414        status.updated_at = Timestamp::now();
8415        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8416        let fresh = read_status(dir.path()).unwrap();
8417        assert!(fresh.running(Timestamp::now()));
8418    }
8419
8420    #[test]
8421    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
8422        let dir = tempfile::tempdir().unwrap();
8423        let now = Timestamp::now();
8424        let mine = "20260903-080619-01c2";
8425
8426        assert!(
8427            !is_working_on(dir.path(), mine, now),
8428            "no status file means nobody is working on anything"
8429        );
8430
8431        let mut status = Status::new();
8432        status.current = vec![Current {
8433            task: "20260903-080340-0167".to_owned(),
8434            run: mine.to_owned(),
8435        }];
8436        status.updated_at = now;
8437        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8438        assert!(is_working_on(dir.path(), mine, now));
8439        assert!(
8440            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
8441            "a daemon busy with one run is not working on another"
8442        );
8443
8444        // A killed daemon stops writing heartbeats but leaves the file behind
8445        // naming the run it died in. That run must not be undeletable forever.
8446        status.updated_at = now - jiff::SignedDuration::from_secs(600);
8447        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8448        assert!(
8449            !is_working_on(dir.path(), mine, now),
8450            "a stale heartbeat is a dead daemon, so its run is a leftover"
8451        );
8452    }
8453
8454    #[test]
8455    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
8456        let dir = tempfile::tempdir().unwrap();
8457        let now = Timestamp::now();
8458
8459        assert!(
8460            !is_working_on_short(dir.path(), "01c2", now),
8461            "no status file means nobody is working on anything"
8462        );
8463
8464        let mut status = Status::new();
8465        status.current = vec![Current {
8466            task: "20260903-080340-0167".to_owned(),
8467            run: "20260903-080619-01c2".to_owned(),
8468        }];
8469        status.updated_at = now;
8470        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8471        assert!(
8472            is_working_on_short(dir.path(), "01c2", now),
8473            "the run's short id is the last block of its full id"
8474        );
8475        assert!(
8476            !is_working_on_short(dir.path(), "3cbf", now),
8477            "a daemon busy with one worktree bay is not working on another"
8478        );
8479    }
8480
8481    #[test]
8482    fn a_newer_status_file_still_yields_a_reading() {
8483        let dir = tempfile::tempdir().unwrap();
8484        // A field this build has never heard of must not turn the reading into
8485        // nothing at all; that is the whole reason the reader is permissive.
8486        std::fs::write(
8487            dir.path().join("daemon.json"),
8488            serde_json::json!({
8489                "schema": 2,
8490                "updated_at": Timestamp::now().to_string(),
8491                "idle": true,
8492                "surprise": { "nested": [1, 2, 3] },
8493            })
8494            .to_string(),
8495        )
8496        .unwrap();
8497
8498        let reading = read_status(dir.path()).expect("a forward-compatible read");
8499        assert!(reading.running(Timestamp::now()));
8500        assert!(reading.idle);
8501        assert!(reading.current.is_empty());
8502    }
8503
8504    #[test]
8505    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
8506        // A daemon started before `current` became a list keeps writing this
8507        // shape on every heartbeat until it is restarted. A rolling upgrade
8508        // - a newer `magi web` or `magi doctor` reading an older `magi
8509        // serve`'s heartbeat - must still see the run it is on, not "no
8510        // daemon" from a type mismatch failing the whole struct.
8511        let dir = tempfile::tempdir().unwrap();
8512        std::fs::write(
8513            dir.path().join("daemon.json"),
8514            serde_json::json!({
8515                "schema": 1,
8516                "pid": 4242,
8517                "updated_at": Timestamp::now().to_string(),
8518                "idle": false,
8519                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
8520                "completed": 3,
8521                "polls": 9,
8522            })
8523            .to_string(),
8524        )
8525        .unwrap();
8526
8527        let reading = read_status(dir.path()).expect("an older shape must still parse");
8528        assert!(reading.running(Timestamp::now()));
8529        assert_eq!(
8530            reading.current,
8531            vec![Current {
8532                task: "20260902-140501-aaaa".to_owned(),
8533                run: "20260902-140502-bbbb".to_owned(),
8534            }]
8535        );
8536    }
8537
8538    #[test]
8539    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
8540        let dir = tempfile::tempdir().unwrap();
8541        std::fs::write(
8542            dir.path().join("daemon.json"),
8543            serde_json::json!({
8544                "schema": 1,
8545                "updated_at": Timestamp::now().to_string(),
8546                "idle": true,
8547                "current": null,
8548            })
8549            .to_string(),
8550        )
8551        .unwrap();
8552        let with_null = read_status(dir.path()).expect("null must still parse");
8553        assert!(with_null.current.is_empty());
8554
8555        std::fs::write(
8556            dir.path().join("daemon.json"),
8557            serde_json::json!({
8558                "schema": 1,
8559                "updated_at": Timestamp::now().to_string(),
8560                "idle": true,
8561            })
8562            .to_string(),
8563        )
8564        .unwrap();
8565        let absent = read_status(dir.path()).expect("a missing field must still parse");
8566        assert!(absent.current.is_empty());
8567    }
8568
8569    #[test]
8570    fn a_task_without_a_repository_runs_in_the_daemons_default() {
8571        let fallback = Path::new("/default");
8572        let mut blank = task();
8573        blank.repo = PathBuf::new();
8574        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
8575        let mut dot = task();
8576        dot.repo = PathBuf::from(".");
8577        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
8578        assert_eq!(
8579            repo_for(&task(), fallback),
8580            PathBuf::from("/repo"),
8581            "a task that names a repository keeps it"
8582        );
8583    }
8584
8585    #[test]
8586    fn task_implementers_edit_inherits_daemon_config_and_merge() {
8587        let dir = tempfile::tempdir().unwrap();
8588        let path = dir.path().join("explicit.toml");
8589        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
8590        let opts = Opts {
8591            config: Some(path),
8592            merge: Some("none".into()),
8593            ..Default::default()
8594        };
8595        let mut t = task();
8596        t.set_implementers(
8597            2,
8598            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8599                .unwrap(),
8600        )
8601        .unwrap();
8602        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8603        assert_eq!(cfg.graph.implementers, 2);
8604        assert_eq!(cfg.graph.judges, 1);
8605        assert_eq!(cfg.merge.mode, MergeMode::None);
8606        t.set_implementers(1, &cfg).unwrap();
8607        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8608        apply_task_implementers(&mut cfg, &t);
8609        assert_eq!(cfg.graph.implementers, 1);
8610        assert_eq!(cfg.graph.judges, 1);
8611        assert_eq!(cfg.merge.mode, MergeMode::None);
8612    }
8613
8614    #[test]
8615    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
8616        let dir = tempfile::tempdir().unwrap();
8617        let repo = dir.path().join("repo");
8618        std::fs::create_dir(&repo).unwrap();
8619        std::fs::write(
8620            repo.join("magi.toml"),
8621            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
8622        )
8623        .unwrap();
8624        let daemon_config = dir.path().join("daemon.toml");
8625        std::fs::write(
8626            &daemon_config,
8627            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
8628        )
8629        .unwrap();
8630        let opts = Opts {
8631            config: Some(daemon_config),
8632            merge: Some("pr".into()),
8633            ..Default::default()
8634        };
8635        let q = Queue::at(dir.path().join("queue"));
8636        let validation: Config =
8637            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8638                .unwrap();
8639        // No provenance field on legacy direct tasks: both shapes stay isolated.
8640        for record in ["{}", r#"{"candidates":2}"#] {
8641            let overrides = serde_json::from_str(record).unwrap();
8642            let filing = crate::direct::Filing {
8643                instruction: "work".into(),
8644                title: "direct".into(),
8645                repo: repo.clone(),
8646                source: crate::queue::Source::Human,
8647                solo: false,
8648                overrides,
8649                review_of: None,
8650            };
8651            let filed =
8652                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
8653            let crate::direct::Filed::Standalone {
8654                mut task,
8655                claim: _claim,
8656            } = filed
8657            else {
8658                panic!("local filing")
8659            };
8660            let before = prepare_for(&repo, &opts, &task).unwrap();
8661            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
8662            assert_eq!(
8663                before.merge.mode,
8664                MergeMode::None,
8665                "daemon --merge must not leak"
8666            );
8667            for n in [2, 1, 2] {
8668                task.set_implementers(n, &validation).unwrap();
8669                q.put(&mut task).unwrap();
8670                task = q.get(&task.id).unwrap();
8671                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
8672                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
8673                apply_task_implementers(&mut cfg, &task);
8674                assert_eq!(cfg.graph.implementers, usize::from(n));
8675                assert_eq!(cfg.graph.judges, 2);
8676                assert_eq!(cfg.merge.mode, MergeMode::None);
8677            }
8678        }
8679    }
8680
8681    #[test]
8682    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
8683        let cfg: Config =
8684            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8685                .unwrap();
8686        let mut t = task();
8687        t.review_of = Some("review-target".into());
8688        t.hold_manual(Some("retry".into()));
8689        let mut previous = RunState::new(
8690            PathBuf::from("/repo"),
8691            "main".into(),
8692            "abc1234".into(),
8693            "review".into(),
8694            cfg.clone(),
8695        );
8696        previous.config.graph.implementers = 2;
8697        for count in [1, 3] {
8698            t.set_implementers(count, &cfg).unwrap();
8699            t.release();
8700            assert_eq!(t.review_of.as_deref(), Some("review-target"));
8701            for proposed in [
8702                Starter::Resume(previous.id.clone()),
8703                Starter::Review("recovery-target".into()),
8704            ] {
8705                assert_eq!(
8706                    starter_with_implementers(&t, Some(&previous), proposed),
8707                    Starter::Review("review-target".into())
8708                );
8709            }
8710            let mut configured = cfg.clone();
8711            apply_task_implementers(&mut configured, &t);
8712            assert_eq!(configured.graph.implementers, usize::from(count));
8713            assert_eq!(previous.config.graph.implementers, 2);
8714        }
8715    }
8716
8717    #[test]
8718    fn task_implementers_dispatch_and_resume_agree() {
8719        let mut t = task();
8720        let cfg: crate::config::Config =
8721            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8722                .unwrap();
8723        let mut run = RunState::new(
8724            PathBuf::from("/repo"),
8725            "main".into(),
8726            "abc1234".into(),
8727            "work".into(),
8728            cfg.clone(),
8729        );
8730        run.config.graph.implementers = 2;
8731        for n in [2, 1, 3, 2] {
8732            t.set_implementers(n, &cfg).unwrap();
8733            let mut dispatched = cfg.clone();
8734            apply_task_implementers(&mut dispatched, &t);
8735            assert_eq!(dispatched.graph.implementers, usize::from(n));
8736            assert_eq!(implementers_match(&t, &run), n == 2);
8737            for proposed in [
8738                Starter::Resume(run.id.clone()),
8739                Starter::Review("old-branch".into()),
8740            ] {
8741                let expected = if n == 2 {
8742                    proposed.clone()
8743                } else {
8744                    Starter::Start
8745                };
8746                assert_eq!(
8747                    starter_with_implementers(&t, Some(&run), proposed),
8748                    expected
8749                );
8750            }
8751            assert_eq!(
8752                run.config.graph.implementers, 2,
8753                "history must not be rewritten"
8754            );
8755        }
8756        t.solo = false;
8757        t.overrides = None;
8758        assert!(implementers_match(&t, &run));
8759    }
8760
8761    #[test]
8762    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
8763        // Three seats said out loud. What `solo` promises is one candidate
8764        // *whatever the config asks for*, so the contrast has to be a number
8765        // this test owns - it used to be `Config::default()`'s, which became
8766        // 1 when one implementation became the default and left the two
8767        // halves of this test asserting the same thing.
8768        let mut solo_cfg = Config::default();
8769        solo_cfg.graph.implementers = 3;
8770        let mut solo_task = task();
8771        solo_task.solo = true;
8772        apply_task_implementers(&mut solo_cfg, &solo_task);
8773        assert_eq!(solo_cfg.graph.implementers, 1);
8774
8775        let mut plain_cfg = Config::default();
8776        plain_cfg.graph.implementers = 3;
8777        let plain_task = task();
8778        assert!(!plain_task.solo);
8779        apply_task_implementers(&mut plain_cfg, &plain_task);
8780        assert_eq!(
8781            plain_cfg.graph.implementers, 3,
8782            "a task that did not ask to run alone keeps the config's candidates"
8783        );
8784    }
8785
8786    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
8787        QuotaLoss {
8788            seat: seat.into(),
8789            node: "judge".into(),
8790            at: at.parse().unwrap(),
8791            reset: reset.map(str::to_string),
8792        }
8793    }
8794
8795    #[test]
8796    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
8797        let old: Vec<QuotaLoss> = (1..=4)
8798            .map(|i| {
8799                loss(
8800                    &format!("judge-{i}"),
8801                    "2026-09-23T05:23:00Z",
8802                    Some("2:40pm (Asia/Tokyo)"),
8803                )
8804            })
8805            .collect();
8806        let fresh = losses_this_attempt(&old, &old);
8807        assert!(fresh.is_empty());
8808        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
8809        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
8810    }
8811
8812    #[test]
8813    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
8814        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
8815        let now = Timestamp::now();
8816        let mut after = old.clone();
8817        after.push(loss("judge-2", &now.to_string(), None));
8818        let fresh = losses_this_attempt(&old, &after);
8819        assert_eq!(fresh, vec![after[1].clone()]);
8820        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
8821        assert_eq!(
8822            until,
8823            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
8824        );
8825    }
8826
8827    #[test]
8828    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
8829        // `recover_stall` removes judge-1's loss and the retry then hits quota
8830        // again: the vector is the same length, so an index diff sees nothing.
8831        let before = vec![
8832            loss("judge-1", "2026-09-23T05:23:00Z", None),
8833            loss("judge-2", "2026-09-23T05:24:00Z", None),
8834        ];
8835        let after = vec![
8836            loss("judge-2", "2026-09-23T05:24:00Z", None),
8837            loss("judge-1", "2026-09-24T01:00:00Z", None),
8838        ];
8839        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
8840    }
8841
8842    #[test]
8843    fn merge_overrides_are_parsed_or_refused() {
8844        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
8845        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
8846        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
8847        assert!(merge_mode("squash").is_err());
8848    }
8849
8850    #[test]
8851    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
8852        let now = Timestamp::now();
8853        let fallback = Duration::from_secs(300);
8854        let cap = Duration::from_secs(1800);
8855
8856        // No reset hint at all: the fallback.
8857        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
8858
8859        // A reset ten minutes out, well inside the cap: waited for exactly.
8860        let soon = now + jiff::SignedDuration::from_secs(600);
8861        assert_eq!(
8862            quota_wait(Some(soon), now, fallback, cap),
8863            Duration::from_secs(600)
8864        );
8865
8866        // A reset already in the past is not trusted: the fallback, not a
8867        // zero or negative wait that would spin the loop right back around.
8868        let past = now - jiff::SignedDuration::from_secs(60);
8869        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
8870
8871        // A reset further out than the cap is trusted for direction but not
8872        // for magnitude: a parsing slip must not sleep the loop for a day.
8873        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
8874        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
8875    }
8876
8877    #[test]
8878    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
8879        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8880
8881        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
8882        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
8883
8884        // Same clock reading, but it has already gone by today: read as
8885        // tomorrow's, since the CLI would not still be reporting a limit past
8886        // its own stated reset.
8887        let already_past =
8888            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
8889        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
8890
8891        assert!(
8892            parse_reset_hint("session limit reached", now, now).is_none(),
8893            "free text with no recognised shape is not guessed at"
8894        );
8895        assert!(
8896            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
8897            "an unresolvable zone name is not guessed at either"
8898        );
8899    }
8900
8901    #[test]
8902    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
8903        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8904
8905        let at = parse_reset_hint(
8906            "You've hit your usage limit. Visit \
8907             https://chatgpt.com/codex/settings/usage to purchase more \
8908             credits or try again at Sep 19th, 2026 5:10 PM.",
8909            now,
8910            now,
8911        )
8912        .expect("the codex reset wording is a recognised shape");
8913        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
8914
8915        // The month is explicit, so a date already earlier in the same
8916        // sentence-implied year than `now` is trusted as written rather than
8917        // rolled forward a year the way the bracketed shape rolls a
8918        // same-day clock reading to tomorrow.
8919        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
8920            .expect("an explicit year needs no rollover");
8921        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
8922
8923        assert!(
8924            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
8925            "a two-digit year is not the documented shape and is not guessed at"
8926        );
8927        assert!(
8928            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
8929            "a four-letter month name is not the documented three-letter abbreviation"
8930        );
8931        assert!(
8932            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
8933            "an explicit zone on the dated shape is a format nobody has \
8934             documented, and is refused rather than guessed at as UTC"
8935        );
8936    }
8937
8938    #[test]
8939    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
8940        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
8941        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
8942
8943        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
8944        assert_eq!(at.as_second() - recorded.as_second(), 3769);
8945
8946        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
8947        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
8948
8949        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
8950            assert!(
8951                parse_reset_hint(bad, now, recorded).is_none(),
8952                "{bad:?} must not be guessed at"
8953            );
8954        }
8955    }
8956
8957    /// A loop whose queue lives in a temp tree and whose poll interval is far
8958    /// longer than the test's patience, so anything that waits out a poll
8959    /// instead of noticing the stop fails rather than merely being slow.
8960    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
8961        let config = dir.join("magi.toml");
8962        std::fs::write(
8963            &config,
8964            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
8965        )
8966        .unwrap();
8967        let opts = Opts {
8968            poll: Duration::from_secs(30),
8969            config: Some(config),
8970            // The explicit fixture config keeps startup cleanup from reading
8971            // machine configuration. This fictional repository likewise
8972            // keeps any best-effort git cleanup away from this checkout.
8973            repo: dir.join("repo"),
8974            ..Opts::default()
8975        };
8976        // The status file goes in a directory that does not exist yet, so its
8977        // creation is itself evidence the loop published one. `worktrees`
8978        // must be just as fictional: the janitor reclaims worktrees under it
8979        // for real, and a test that let it fall through to
8980        // `crate::run::default_worktree_root()` would have it reclaim
8981        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
8982        // which is exactly what happened before this function took the
8983        // parameter at all.
8984        let home = dir.join("home");
8985        let worktrees = dir.join("wt");
8986        (
8987            opts,
8988            Queue::at(dir.join("queue")),
8989            home.join("daemon.json"),
8990            home,
8991            worktrees,
8992        )
8993    }
8994
8995    #[test]
8996    fn a_stop_is_idempotent_and_once_set_stays_set() {
8997        let stop = Stop::new();
8998        assert!(!stop.stopped());
8999
9000        stop.stop();
9001        assert!(stop.stopped());
9002        stop.stop();
9003        assert!(stop.stopped(), "a second stop is not a toggle");
9004
9005        let shared = stop.clone();
9006        assert!(
9007            shared.stopped(),
9008            "a clone is the same stop; that is how the loop and its caller share one"
9009        );
9010    }
9011
9012    #[test]
9013    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
9014        let stop = Stop::new();
9015        stop.enter();
9016        assert!(
9017            !stop.finishing(),
9018            "a busy loop nobody has asked to stop is just running"
9019        );
9020
9021        stop.stop();
9022        assert!(
9023            stop.finishing(),
9024            "a stop asked for mid-run has not landed until the run is settled"
9025        );
9026
9027        stop.exit();
9028        assert!(
9029            !stop.finishing(),
9030            "once the run is settled the stop has landed and there is nothing to finish"
9031        );
9032    }
9033
9034    #[test]
9035    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
9036        let stop = Stop::new();
9037        stop.enter();
9038        stop.enter();
9039        stop.stop();
9040        assert!(stop.finishing(), "two runs still in flight");
9041
9042        stop.exit();
9043        assert!(
9044            stop.finishing(),
9045            "one run finished, but a sibling is still working"
9046        );
9047
9048        stop.exit();
9049        assert!(
9050            !stop.finishing(),
9051            "the last run out is what actually lands the stop"
9052        );
9053    }
9054
9055    #[tokio::test]
9056    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
9057        let dir = tempfile::tempdir().unwrap();
9058        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9059        let stop = Stop::new();
9060        stop.stop();
9061
9062        let began = std::time::Instant::now();
9063        tokio::time::timeout(
9064            Duration::from_secs(2),
9065            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9066        )
9067        .await
9068        .expect("a stopped loop must return, not sit out its poll interval")
9069        .expect("the loop's own setup and teardown must not fail");
9070        assert!(
9071            began.elapsed() < opts.poll,
9072            "returned only after {:?}, which is a poll interval, not a stop",
9073            began.elapsed()
9074        );
9075    }
9076
9077    #[tokio::test]
9078    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
9079        let dir = tempfile::tempdir().unwrap();
9080        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9081        let stop = Stop::new();
9082
9083        // Asked for after the loop is already parked on its empty queue, which
9084        // is the case an operator tapping stop on a phone actually hits.
9085        let asker = {
9086            let stop = stop.clone();
9087            tokio::spawn(async move {
9088                tokio::time::sleep(Duration::from_millis(20)).await;
9089                stop.stop();
9090            })
9091        };
9092
9093        let began = std::time::Instant::now();
9094        tokio::time::timeout(
9095            Duration::from_secs(2),
9096            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9097        )
9098        .await
9099        .expect("a stop asked for while idle must wake the wait")
9100        .expect("the loop's own setup and teardown must not fail");
9101        asker.await.unwrap();
9102        assert!(
9103            began.elapsed() < opts.poll,
9104            "returned only after {:?}, so the stop waited on the sleep",
9105            began.elapsed()
9106        );
9107    }
9108
9109    #[tokio::test]
9110    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
9111        let dir = tempfile::tempdir().unwrap();
9112        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9113        let stop = Stop::new();
9114        stop.stop();
9115
9116        tokio::time::timeout(
9117            Duration::from_secs(2),
9118            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9119        )
9120        .await
9121        .expect("a stopped loop must return")
9122        .expect("the loop's own setup and teardown must not fail");
9123
9124        assert!(
9125            home.is_dir(),
9126            "the loop did publish a status file, so its removal is the teardown and not an absence"
9127        );
9128        assert!(
9129            !status_file.exists(),
9130            "a stopped loop clears its status file"
9131        );
9132        assert!(
9133            read_status(&home).is_none(),
9134            "a reader must see no daemon at all, not a heartbeat that merely stopped"
9135        );
9136    }
9137
9138    #[tokio::test]
9139    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
9140        let dir = tempfile::tempdir().unwrap();
9141        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9142        opts.once = true;
9143
9144        let mut settled = RunState::new(
9145            dir.path().join("repo"),
9146            "main".to_owned(),
9147            "abc1234".to_owned(),
9148            "fixture".to_owned(),
9149            Config::default(),
9150        );
9151        settled.status = RunStatus::Ready;
9152        let run_dir = home.join("runs").join(&settled.id);
9153        std::fs::create_dir_all(&run_dir).unwrap();
9154        std::fs::write(
9155            run_dir.join("run.json"),
9156            serde_json::to_string_pretty(&settled).unwrap(),
9157        )
9158        .unwrap();
9159        let questions = Questions::at(home.join("questions"));
9160        let mut question = ask::Question::new(
9161            settled.id.clone(),
9162            "review".to_owned(),
9163            "reviewer-1".to_owned(),
9164            "Continue?".to_owned(),
9165            String::new(),
9166            Vec::new(),
9167        );
9168        questions.put(&mut question).unwrap();
9169
9170        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
9171            .await
9172            .unwrap();
9173
9174        assert_eq!(
9175            questions.get(&question.id).unwrap().status,
9176            ask::QuestionStatus::Abandoned,
9177            "an empty --once drain still performs startup question cleanup"
9178        );
9179    }
9180
9181    #[test]
9182    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
9183        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9184
9185        assert!(
9186            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
9187            "never checked before: due at once"
9188        );
9189
9190        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
9191        assert!(
9192            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
9193            "well inside the interval: not due yet"
9194        );
9195
9196        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
9197        assert!(
9198            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
9199            "exactly at the edge: not yet due, same convention as `clean::due`"
9200        );
9201
9202        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9203        assert!(
9204            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
9205            "past the interval: due again"
9206        );
9207    }
9208
9209    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
9210    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
9211    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
9212    /// and the congestion test below both need, and must not drift apart.
9213    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
9214        let config = dir.join("magi.toml");
9215        // A literal (single-quoted) TOML string, not a basic one: the cache
9216        // path is a Windows path full of backslashes, and a basic string
9217        // would have TOML try to interpret `\U` (from `\Users\...`) as a
9218        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
9219        // `{{ vars.cache }}` rendering documents.
9220        std::fs::write(
9221            &config,
9222            format!(
9223                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
9224                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
9225                cache_dir.display()
9226            ),
9227        )
9228        .unwrap();
9229        Opts {
9230            config: Some(config),
9231            repo: dir.join("repo"),
9232            ..Opts::default()
9233        }
9234    }
9235
9236    #[tokio::test]
9237    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
9238        let dir = tempfile::tempdir().unwrap();
9239        let home = dir.path().join("home");
9240        let cache_dir = dir.path().join("cache");
9241        std::fs::create_dir_all(&cache_dir).unwrap();
9242        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9243        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9244
9245        // Nobody has asked this daemon to stop, which is the ordinary case;
9246        // the skip that a stop buys is asserted by its own test below.
9247        let running = Stop::new();
9248        let mut last_checked = None;
9249        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9250        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
9251            .await;
9252        assert_eq!(
9253            crate::disk::dir_size(&cache_dir),
9254            0,
9255            "over the cap on the first check ever: pruned at once, no idle queue required"
9256        );
9257        assert_eq!(last_checked, Some(t0));
9258
9259        // A fresh oversized file lands, but the next check is not due yet.
9260        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
9261        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
9262        maybe_prune_cache_between_runs(
9263            &opts.repo,
9264            &opts,
9265            &home,
9266            &running,
9267            &mut last_checked,
9268            too_soon,
9269        )
9270        .await;
9271        assert_eq!(
9272            crate::disk::dir_size(&cache_dir),
9273            10,
9274            "too soon since the last check: left alone rather than rescanned every call"
9275        );
9276        assert_eq!(
9277            last_checked,
9278            Some(t0),
9279            "an idle check does not reset the clock"
9280        );
9281
9282        // Once the interval elapses, the same oversized cache is caught again.
9283        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9284        maybe_prune_cache_between_runs(
9285            &opts.repo,
9286            &opts,
9287            &home,
9288            &running,
9289            &mut last_checked,
9290            due_again,
9291        )
9292        .await;
9293        assert_eq!(
9294            crate::disk::dir_size(&cache_dir),
9295            0,
9296            "due again: pruned back under the cap"
9297        );
9298    }
9299
9300    /// A stop must not queue behind housekeeping. The prune below is a
9301    /// synchronous walk of the whole cache with no await point in it, so a
9302    /// loop that entered it could not get back to its own `stopped()` test
9303    /// until the walk finished - and because no run is in flight at this
9304    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
9305    /// the stop had already landed. The idle branch has always made this same
9306    /// check before reaching `janitor`; the between-runs path makes it too.
9307    #[tokio::test]
9308    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
9309        let dir = tempfile::tempdir().unwrap();
9310        let home = dir.path().join("home");
9311        let cache_dir = dir.path().join("cache");
9312        std::fs::create_dir_all(&cache_dir).unwrap();
9313        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9314        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9315
9316        let stop = Stop::new();
9317        stop.stop();
9318        assert!(
9319            !stop.finishing(),
9320            "no run is in flight at a between-runs boundary, so nothing else \
9321             would tell the operator this stop had not taken effect yet"
9322        );
9323
9324        let mut last_checked = None;
9325        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9326        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
9327            .await;
9328        assert_eq!(
9329            crate::disk::dir_size(&cache_dir),
9330            10,
9331            "over its cap, and due for the first check ever, but a stop outranks \
9332             it: the cap is a standing policy the next start measures again"
9333        );
9334        assert_eq!(
9335            last_checked, None,
9336            "a check that never happened must not claim the interval"
9337        );
9338    }
9339
9340    /// The regression this whole change exists for: gate timeouts on runs
9341    /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
9342    /// GiB against a 10 GiB cap, because the operator's queue never had a
9343    /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
9344    /// `janitor` pass.
9345    ///
9346    /// Reproduced with a backlog whose repository is never created:
9347    /// `Runner::start` fails at `git::toplevel`, spawning no agent CLI.
9348    /// Each task is held after one startup failure, but the remaining tasks
9349    /// keep the queue busy until an external stop ends the loop.
9350    #[tokio::test]
9351    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
9352        let dir = tempfile::tempdir().unwrap();
9353        let cache_dir = dir.path().join("cache");
9354        std::fs::create_dir_all(&cache_dir).unwrap();
9355        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
9356
9357        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
9358        opts.poll = Duration::from_millis(20);
9359        opts.max_attempts = 1_000;
9360
9361        let queue = Queue::at(dir.path().join("queue"));
9362        for i in 0..128 {
9363            let mut task = Task::new(
9364                format!("queued work {i}"),
9365                format!("queued work {i}"),
9366                opts.repo.clone(),
9367                Source::Human,
9368            );
9369            queue.put(&mut task).unwrap();
9370        }
9371
9372        let home = dir.path().join("home");
9373        let worktrees = dir.path().join("wt");
9374        let status_file = home.join("daemon.json");
9375        let stop = Stop::new();
9376        let stopper = {
9377            let stop = stop.clone();
9378            let queue = Queue::at(dir.path().join("queue"));
9379            tokio::spawn(async move {
9380                // Observe completed work rather than rely on a wall-clock
9381                // delay. Every startup failure holds only its own task; the
9382                // backlog keeps offering work at the next boundary.
9383                for _ in 0..2_000 {
9384                    if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
9385                        break;
9386                    }
9387                    tokio::time::sleep(Duration::from_millis(5)).await;
9388                }
9389                stop.stop();
9390            })
9391        };
9392
9393        tokio::time::timeout(
9394            Duration::from_secs(20),
9395            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9396        )
9397        .await
9398        .expect("the loop must not hang on a queue that keeps producing failing work")
9399        .expect("the loop's own setup and teardown must not fail");
9400        stopper.await.unwrap();
9401
9402        let after = queue.list();
9403        let completed = after.iter().filter(|t| t.attempts == 1).count();
9404        assert!(
9405            completed >= 2,
9406            "the harness must have processed multiple tasks to exercise a busy queue \
9407             (got {completed} completed task(s))"
9408        );
9409        assert!(
9410            after.iter().any(|t| t.status.runnable()),
9411            "unprocessed tasks must remain: the external stop, rather than an \
9412             exhausted backlog, must end the test"
9413        );
9414        assert!(
9415            after
9416                .iter()
9417                .filter(|t| t.attempts > 0)
9418                .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
9419            "a busy backlog must not retry a task's unchanged startup failure"
9420        );
9421
9422        assert_eq!(
9423            crate::disk::dir_size(&cache_dir),
9424            0,
9425            "an oversized cache must not be left to grow unboundedly just because the \
9426             queue kept the loop busy the whole time"
9427        );
9428    }
9429
9430    #[test]
9431    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
9432        let dir = tempfile::tempdir().unwrap();
9433        let queue = Queue::at(dir.path().join("queue"));
9434        let questions = Questions::at(dir.path().join("questions"));
9435        let mut task = task();
9436        queue.put(&mut task).unwrap();
9437
9438        let mut task_question = ask::Question::new(
9439            task.id.clone(),
9440            crate::conduct::NODE.to_owned(),
9441            "conduct".to_owned(),
9442            "Which backend?".to_owned(),
9443            String::new(),
9444            Vec::new(),
9445        );
9446        questions.put(&mut task_question).unwrap();
9447        task.block(vec![task_question.id.clone()], None);
9448        queue.put(&mut task).unwrap();
9449
9450        let mut run_question = ask::Question::new(
9451            "20260101-000000-run1".to_owned(),
9452            "review".to_owned(),
9453            "reviewer-1".to_owned(),
9454            "Run question".to_owned(),
9455            String::new(),
9456            Vec::new(),
9457        );
9458        questions.put(&mut run_question).unwrap();
9459
9460        // A question from another node whose `run` happens to equal this
9461        // task's id — the same field, filled in for an unrelated reason. Only
9462        // `crate::conduct::NODE` questions use `run` as a task id; this one
9463        // must never be touched by this reconciliation, even after release.
9464        let mut coincidental = ask::Question::new(
9465            task.id.clone(),
9466            "review".to_owned(),
9467            "reviewer-1".to_owned(),
9468            "Unrelated review question".to_owned(),
9469            String::new(),
9470            Vec::new(),
9471        );
9472        questions.put(&mut coincidental).unwrap();
9473
9474        reconcile_task_questions(&queue, &questions);
9475        assert!(questions.get(&task_question.id).unwrap().status.open());
9476        assert!(questions.get(&run_question.id).unwrap().status.open());
9477        assert!(questions.get(&coincidental.id).unwrap().status.open());
9478
9479        task.release();
9480        queue.put(&mut task).unwrap();
9481        reconcile_task_questions(&queue, &questions);
9482        assert_eq!(
9483            questions.get(&task_question.id).unwrap().status,
9484            ask::QuestionStatus::Abandoned
9485        );
9486        assert!(
9487            questions.get(&run_question.id).unwrap().status.open(),
9488            "run questions remain the run janitor's responsibility"
9489        );
9490        assert!(
9491            questions.get(&coincidental.id).unwrap().status.open(),
9492            "a non-conductor question must not be abandoned just because its \
9493             run id coincides with a task id"
9494        );
9495    }
9496
9497    #[test]
9498    fn a_freshly_started_running_task_is_never_stalled() {
9499        let dir = tempfile::tempdir().unwrap();
9500        let mut t = task();
9501        t.start("run-1".to_owned());
9502        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
9503        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
9504        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
9505    }
9506
9507    #[test]
9508    fn a_long_running_task_with_no_live_daemon_is_stalled() {
9509        let dir = tempfile::tempdir().unwrap();
9510        let mut t = task();
9511        t.start("run-1".to_owned());
9512        t.updated_at = Timestamp::now()
9513            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9514        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
9515        assert_eq!(
9516            stalled_tasks(
9517                &Queue::at(dir.path().join("q")),
9518                dir.path(),
9519                Timestamp::now()
9520            )
9521            .len(),
9522            0,
9523            "the task was never written to this queue"
9524        );
9525    }
9526
9527    #[test]
9528    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
9529        let dir = tempfile::tempdir().unwrap();
9530        let mut t = task();
9531        t.id = "20260903-080340-0167".to_owned();
9532        t.start("20260903-080619-01c2".to_owned());
9533        t.updated_at = Timestamp::now()
9534            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9535
9536        let mut status = Status::new();
9537        status.current = vec![Current {
9538            task: t.id.clone(),
9539            run: "20260903-080619-01c2".to_owned(),
9540        }];
9541        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9542
9543        assert!(
9544            !is_stalled(&t, dir.path(), Timestamp::now()),
9545            "a live daemon's own heartbeat rules out stalled, however long the task has run"
9546        );
9547    }
9548
9549    /// Rewrite a task's `updated_at` on disk directly, bypassing
9550    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
9551    /// a fixture look like it has genuinely been `running` for a while.
9552    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
9553        let path = queue.path_of(id);
9554        let body = std::fs::read_to_string(&path).unwrap();
9555        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
9556        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
9557        v["updated_at"] = serde_json::Value::String(old.to_string());
9558        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
9559    }
9560
9561    #[test]
9562    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
9563        // The realistic `poll()` ordering, not `is_stalled` in isolation:
9564        // `reclaim_orphaned_running` runs first, on every poll, and settles
9565        // any `running` task whose claim it can actually take. For most
9566        // crashes that is immediate - a dead pid is proof enough for
9567        // `sweep_stale_claims` to drop the lock the same tick, and the very
9568        // next claim attempt succeeds. But a lock whose pid cannot be parsed
9569        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
9570        // `sweep_stale_claims`'s own doc), so the lock - and the claim
9571        // failure behind it - can legitimately outlive many polls. This is
9572        // exactly the gap `stalled_tasks` exists to surface well before that
9573        // six-hour sweep would: reclaim leaves the task `running`, and it
9574        // must still reach the conductor as stalled.
9575        let dir = tempfile::tempdir().unwrap();
9576        let queue = Queue::at(dir.path().join("queue"));
9577        let home = dir.path().join("home");
9578
9579        let mut t = task();
9580        t.id = "20260101-000001-lock".to_owned();
9581        t.start("run-1".to_owned());
9582        queue.put(&mut t).unwrap();
9583        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9584        std::fs::write(
9585            dir.path().join("queue").join(format!("{}.lock", t.id)),
9586            "not a pid",
9587        )
9588        .unwrap();
9589
9590        let now = Timestamp::now();
9591        assert!(
9592            reclaim_orphaned_running(&queue, 2).is_empty(),
9593            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
9594             and reclaim must leave the task alone"
9595        );
9596        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9597
9598        let stalled = stalled_tasks(&queue, &home, now);
9599        assert_eq!(
9600            stalled.len(),
9601            1,
9602            "reclaim's inability to claim it yet must not hide it from the conductor"
9603        );
9604        assert_eq!(stalled[0].id, t.id);
9605    }
9606
9607    #[test]
9608    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
9609        let dir = tempfile::tempdir().unwrap();
9610        crate::run::set_home(dir.path().join("run-home"));
9611        let queue = Queue::at(dir.path().join("queue"));
9612        let home = dir.path().join("home");
9613        let questions = Questions::at(dir.path().join("questions"));
9614
9615        let mut t = task();
9616        t.id = "20260101-000003-dead".to_owned();
9617        t.start("missing-run".to_owned());
9618        queue.put(&mut t).unwrap();
9619        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9620
9621        // This is the real poll ordering: retain the deterministic stalled
9622        // input before a claim proves the owner is gone and reclaims it.
9623        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9624        assert_eq!(
9625            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
9626            [&t.id]
9627        );
9628        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
9629        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9630
9631        // Reclaim drops its guard before conductor decisions are applied, so
9632        // the decision for the captured stalled input has a real write path.
9633        crate::conduct::apply(
9634            &queue,
9635            &questions,
9636            &crate::conduct::Verdict {
9637                decisions: vec![crate::conduct::Decision {
9638                    id: t.id.clone(),
9639                    recovery: Some(crate::conduct::Recovery::Requeue),
9640                    ..crate::conduct::Decision::default()
9641                }],
9642            },
9643        )
9644        .unwrap();
9645        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9646    }
9647
9648    #[test]
9649    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
9650        let dir = tempfile::tempdir().unwrap();
9651        let queue = Queue::at(dir.path().join("queue"));
9652        let home = dir.path().join("home");
9653
9654        let mut fresh = task();
9655        fresh.id = "20260101-000001-aaaa".to_owned();
9656        fresh.start("run-1".to_owned());
9657        queue.put(&mut fresh).unwrap();
9658
9659        let mut old = task();
9660        old.id = "20260101-000002-bbbb".to_owned();
9661        old.start("run-2".to_owned());
9662        queue.put(&mut old).unwrap();
9663        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
9664
9665        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9666        assert_eq!(stalled.len(), 1);
9667        assert_eq!(stalled[0].id, old.id);
9668    }
9669
9670    #[test]
9671    fn queued_and_finished_task_views_partition_by_status() {
9672        let dir = tempfile::tempdir().unwrap();
9673        let queue = Queue::at(dir.path().join("queue"));
9674
9675        let mut queued = task();
9676        queued.id = "20260101-000001-aaaa".to_owned();
9677        queue.put(&mut queued).unwrap();
9678
9679        let mut failed = task();
9680        failed.id = "20260101-000002-bbbb".to_owned();
9681        failed.start("run-1".to_owned());
9682        failed.fail("gate red", 5);
9683        queue.put(&mut failed).unwrap();
9684
9685        let mut held = task();
9686        held.id = "20260101-000003-cccc".to_owned();
9687        held.hold_machine(None);
9688        queue.put(&mut held).unwrap();
9689
9690        let mut running = task();
9691        running.id = "20260101-000004-dddd".to_owned();
9692        running.start("run-2".to_owned());
9693        queue.put(&mut running).unwrap();
9694
9695        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
9696        assert_eq!(queued_ids, [queued.id.clone()]);
9697
9698        let mut finished_ids: Vec<String> =
9699            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
9700        finished_ids.sort_unstable();
9701        let mut want = vec![failed.id.clone(), held.id.clone()];
9702        want.sort_unstable();
9703        assert_eq!(finished_ids, want);
9704    }
9705
9706    #[test]
9707    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
9708        for short in [false, true] {
9709            let dir = tempfile::tempdir().unwrap();
9710            let queue = Queue::at(dir.path().join("queue"));
9711            let questions = ask::Questions::at(dir.path().join("questions"));
9712            let mut running = task();
9713            running.id = "20261013-192213-feb2".into();
9714            running.start("existing-run".into());
9715            queue.put(&mut running).unwrap();
9716            let mut middle = task();
9717            middle.id = "20261013-193611-ca5b".into();
9718            middle.block(
9719                vec![if short {
9720                    "feb2".into()
9721                } else {
9722                    running.id.clone()
9723                }],
9724                None,
9725            );
9726            queue.put(&mut middle).unwrap();
9727            let mut waiting = task();
9728            waiting.id = "20261013-202849-ee37".into();
9729            waiting.block(
9730                vec![if short {
9731                    "ca5b".into()
9732                } else {
9733                    middle.id.clone()
9734                }],
9735                Some("wait for implementation".into()),
9736            );
9737            queue.put(&mut waiting).unwrap();
9738            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
9739            let inv = crate::blockers::Inventory::load(&queue, &questions);
9740            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
9741            assert!(inv.stuck().is_empty());
9742            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9743            assert!(report.quarantined.is_empty());
9744            assert!(report.asked.is_empty());
9745            resolve_blockers(&queue, &questions);
9746            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9747            assert!(questions.list().is_empty());
9748            // Finishing the transitive prerequisite alone does not satisfy
9749            // the task's direct dependency.
9750            running.succeed();
9751            queue.put(&mut running).unwrap();
9752            resolve_blockers(&queue, &questions);
9753            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
9754            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9755            middle = queue.get(&middle.id).unwrap();
9756            middle.succeed();
9757            queue.put(&mut middle).unwrap();
9758            resolve_blockers(&queue, &questions);
9759            let after = queue.get(&waiting.id).unwrap();
9760            assert_eq!(after.status, TaskStatus::Queued);
9761            assert!(after.blocked_by.is_empty());
9762            assert_eq!(after.instruction, waiting.instruction);
9763        }
9764    }
9765
9766    #[test]
9767    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
9768        for future_schema in [false, true] {
9769            let name = "20261013-193611-ca5b";
9770            let mut future = task();
9771            future.id = name.into();
9772            future.schema = crate::queue::SCHEMA + 1;
9773            let contents = if future_schema {
9774                serde_json::to_string(&future).unwrap()
9775            } else {
9776                "corrupt".into()
9777            };
9778            let dir = tempfile::tempdir().unwrap();
9779            let queue = Queue::at(dir.path().join("queue"));
9780            let questions = ask::Questions::at(dir.path().join("questions"));
9781            let mut waiting = task();
9782            waiting.id = "20261013-202849-ee37".into();
9783            waiting.block(vec!["ca5b".into()], None);
9784            queue.put(&mut waiting).unwrap();
9785            std::fs::write(queue.path_of(name), contents).unwrap();
9786            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
9787            assert!(
9788                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
9789            );
9790            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9791            assert!(report.asked.is_empty());
9792            resolve_blockers(&queue, &questions);
9793            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9794            assert!(questions.list().is_empty());
9795        }
9796        let dir = tempfile::tempdir().unwrap();
9797        let queue = Queue::at(dir.path().join("queue"));
9798        let questions = ask::Questions::at(dir.path().join("questions"));
9799        let mut waiting = task();
9800        waiting.id = "20261013-202849-ee37".into();
9801        waiting.block(vec!["ca5b".into()], None);
9802        queue.put(&mut waiting).unwrap();
9803        let mut done = task();
9804        done.id = "20261013-193611-ca5b".into();
9805        done.succeed();
9806        queue.put(&mut done).unwrap();
9807        // An unreadable second match must not disappear from uniqueness
9808        // checks just because Queue::list skips it.
9809        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
9810        assert!(queue.get("ca5b").is_err());
9811        assert_eq!(
9812            crate::queue::dependency(&queue, &questions, "ca5b"),
9813            crate::queue::Dependency::Ambiguous
9814        );
9815        resolve_blockers(&queue, &questions);
9816        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9817        assert!(report.asked.is_empty());
9818        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9819        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
9820    }
9821
9822    #[test]
9823    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
9824        for held in [false, true] {
9825            for question in [false, true] {
9826                for reference in ["ca5b", "20261013-193611-ca5b"] {
9827                    let dir = tempfile::tempdir().unwrap();
9828                    let queue = Queue::at(dir.path().join("queue"));
9829                    let questions = ask::Questions::at(dir.path().join("questions"));
9830                    let mut prerequisite = task();
9831                    prerequisite.id = "20261013-193611-ca5b".into();
9832                    prerequisite.start("existing-run".into());
9833                    queue.put(&mut prerequisite).unwrap();
9834                    let mut waiting = task();
9835                    waiting.id = "20261013-202849-ee37".into();
9836                    if held {
9837                        waiting.hold_machine(Some("waiting for separate consent".into()));
9838                    }
9839                    queue.put(&mut waiting).unwrap();
9840                    let reason = "Deleting saved data requires separate owner consent";
9841                    crate::conduct::apply(
9842                        &queue,
9843                        &questions,
9844                        &crate::conduct::Verdict {
9845                            decisions: vec![crate::conduct::Decision {
9846                                id: waiting.id.clone(),
9847                                blocked_by: vec![reference.into()],
9848                                question: question.then(|| "May the saved data be deleted?".into()),
9849                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
9850                                reason: Some(reason.into()),
9851                                ..crate::conduct::Decision::default()
9852                            }],
9853                        },
9854                    )
9855                    .unwrap();
9856                    let before = queue.get(&waiting.id).unwrap();
9857                    if question {
9858                        assert_eq!(before.status, TaskStatus::Blocked);
9859                        let q = questions.get(&before.blocked_by[0]).unwrap();
9860                        assert_eq!(q.summary, "May the saved data be deleted?");
9861                        assert!(q.status.open());
9862                    } else {
9863                        assert_eq!(before.status, TaskStatus::Held);
9864                        let recorded_reason = before.hold_reason.as_deref().unwrap();
9865                        assert!(recorded_reason.starts_with(reason));
9866                        if held {
9867                            assert!(recorded_reason.contains("waiting for separate consent"));
9868                        }
9869                    }
9870                    prerequisite.succeed();
9871                    queue.put(&mut prerequisite).unwrap();
9872                    resolve_blockers(&queue, &questions);
9873                    let after = queue.get(&waiting.id).unwrap();
9874                    assert_eq!(after.status, before.status);
9875                    assert_eq!(after.blocked_by, before.blocked_by);
9876                    assert_eq!(after.hold_reason, before.hold_reason);
9877                    assert_eq!(after.instruction, waiting.instruction);
9878                    if question {
9879                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
9880                    }
9881                    assert!(
9882                        queue.next_runnable().is_none(),
9883                        "dependency completion is not consent"
9884                    );
9885                }
9886            }
9887        }
9888    }
9889
9890    #[test]
9891    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
9892        let dir = tempfile::tempdir().unwrap();
9893        let queue = Queue::at(dir.path().join("queue"));
9894        let questions = ask::Questions::at(dir.path().join("questions"));
9895
9896        let mut dep = task();
9897        dep.id = "20260101-000001-dep0".to_owned();
9898        dep.succeed();
9899        queue.put(&mut dep).unwrap();
9900
9901        let mut still_going = task();
9902        still_going.id = "20260101-000002-dep1".to_owned();
9903        queue.put(&mut still_going).unwrap();
9904
9905        let mut blocked = task();
9906        blocked.id = "20260101-000003-main".to_owned();
9907        blocked.block(
9908            vec![dep.id.clone(), still_going.id.clone()],
9909            Some("waits on both".to_owned()),
9910        );
9911        queue.put(&mut blocked).unwrap();
9912
9913        resolve_blockers(&queue, &questions);
9914
9915        let after = queue.get(&blocked.id).unwrap();
9916        assert_eq!(
9917            after.status,
9918            TaskStatus::Blocked,
9919            "one dependency is still outstanding"
9920        );
9921        assert_eq!(after.blocked_by, [still_going.id.clone()]);
9922    }
9923
9924    #[test]
9925    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
9926        let dir = tempfile::tempdir().unwrap();
9927        let queue = Queue::at(dir.path().join("queue"));
9928        let questions = ask::Questions::at(dir.path().join("questions"));
9929
9930        let mut q = crate::ask::Question::new(
9931            "20260101-000001-main".to_owned(),
9932            crate::conduct::NODE.to_owned(),
9933            "conduct".to_owned(),
9934            "Which backend?".to_owned(),
9935            String::new(),
9936            Vec::new(),
9937        );
9938        questions.put(&mut q).unwrap();
9939        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
9940            .unwrap();
9941        questions.put(&mut q).unwrap();
9942
9943        let mut blocked = task();
9944        blocked.id = "20260101-000001-main".to_owned();
9945        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
9946        queue.put(&mut blocked).unwrap();
9947
9948        resolve_blockers(&queue, &questions);
9949
9950        let after = queue.get(&blocked.id).unwrap();
9951        assert_eq!(
9952            after.status,
9953            TaskStatus::Queued,
9954            "the only blocker resolved"
9955        );
9956        assert_eq!(after.answers.len(), 1);
9957        assert_eq!(after.answers[0].question, "Which backend?");
9958        assert_eq!(after.answers[0].answer, "SQLite");
9959
9960        // And the run this task starts next is told about it.
9961        let instruction = instruction_for(&after);
9962        assert!(instruction.contains("Which backend?"));
9963        assert!(instruction.contains("SQLite"));
9964    }
9965
9966    #[test]
9967    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
9968        let dir = tempfile::tempdir().unwrap();
9969        let queue = Queue::at(dir.path().join("queue"));
9970        let questions = ask::Questions::at(dir.path().join("questions"));
9971
9972        let mut q = crate::ask::Question::new(
9973            "20260101-000001-main".to_owned(),
9974            crate::conduct::NODE.to_owned(),
9975            "conduct".to_owned(),
9976            "Is the setup done?".to_owned(),
9977            String::new(),
9978            Vec::new(),
9979        );
9980        q.abandon("no answer within 60s of asking");
9981        questions.put(&mut q).unwrap();
9982
9983        let mut blocked = task();
9984        blocked.id = "20260101-000001-main".to_owned();
9985        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
9986        queue.put(&mut blocked).unwrap();
9987
9988        resolve_blockers(&queue, &questions);
9989
9990        let after = queue.get(&blocked.id).unwrap();
9991        assert_eq!(
9992            after.status,
9993            TaskStatus::Held,
9994            "never left blocked on nothing"
9995        );
9996        assert!(!after.operator_held(), "a machine hold, for triage");
9997        assert!(
9998            after
9999                .hold_reason
10000                .as_deref()
10001                .unwrap_or_default()
10002                .contains("went unanswered")
10003        );
10004    }
10005
10006    #[test]
10007    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
10008        // Reproduces the reported bug (task 3958): a task held out of
10009        // attempts, blocked on a `crate::conduct` follow-up question, must
10010        // come back `held` once that question is answered - never `queued`,
10011        // whatever the answer said - or it silently re-enters the
10012        // competition queue with its attempts already exhausted.
10013        let dir = tempfile::tempdir().unwrap();
10014        let queue = Queue::at(dir.path().join("queue"));
10015        let questions = ask::Questions::at(dir.path().join("questions"));
10016
10017        let mut q = crate::ask::Question::new(
10018            "20260101-000001-main".to_owned(),
10019            crate::conduct::NODE.to_owned(),
10020            "conduct".to_owned(),
10021            "How should this be handled?".to_owned(),
10022            String::new(),
10023            Vec::new(),
10024        );
10025        questions.put(&mut q).unwrap();
10026        q.answer(crate::ask::Answer::Text(
10027            "leave it held, a human will look at it later".to_owned(),
10028        ))
10029        .unwrap();
10030        questions.put(&mut q).unwrap();
10031
10032        let mut held = task();
10033        held.id = "20260101-000001-main".to_owned();
10034        held.hold_machine(Some("out of attempts".to_owned()));
10035        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
10036        queue.put(&mut held).unwrap();
10037
10038        resolve_blockers(&queue, &questions);
10039
10040        let after = queue.get(&held.id).unwrap();
10041        assert_eq!(after.status, TaskStatus::Held);
10042        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
10043        assert_eq!(
10044            after.answers[0].answer,
10045            "leave it held, a human will look at it later"
10046        );
10047    }
10048
10049    #[test]
10050    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
10051        let dir = tempfile::tempdir().unwrap();
10052        let queue = Queue::at(dir.path().join("queue"));
10053        let questions = ask::Questions::at(dir.path().join("questions"));
10054        let mut dep = task();
10055        dep.id = "20260101-000001-gone".to_owned();
10056        queue.put(&mut dep).unwrap();
10057        let mut blocked = task();
10058        blocked.id = "20260101-000003-main".to_owned();
10059        blocked.block(vec![dep.id.clone()], None);
10060        queue.put(&mut blocked).unwrap();
10061
10062        // Claimed, so `remove` cannot rewrite it and the resolver must.
10063        let claim = queue.claim(&blocked.id).unwrap();
10064        queue.remove(&dep.id, false, &questions).unwrap();
10065        drop(claim);
10066        resolve_blockers(&queue, &questions);
10067
10068        let after = queue.get(&blocked.id).unwrap();
10069        assert_eq!(after.status, TaskStatus::Queued);
10070        assert!(after.blocked_by.is_empty());
10071    }
10072
10073    #[test]
10074    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
10075        // Reproduces the reported bug: a task blocked on a task id that was
10076        // removed (`magi task rm`, or deleted by hand) can never see that id
10077        // reach `Done`, so the ordinary per-id loop has nothing to notice and
10078        // would otherwise leave the task `blocked` forever with no way for an
10079        // operator to find out why.
10080        let dir = tempfile::tempdir().unwrap();
10081        let queue = Queue::at(dir.path().join("queue"));
10082        let questions = ask::Questions::at(dir.path().join("questions"));
10083
10084        let mut still_going = task();
10085        still_going.id = "20260101-000002-dep1".to_owned();
10086        queue.put(&mut still_going).unwrap();
10087
10088        let mut blocked = task();
10089        blocked.id = "20260101-000003-main".to_owned();
10090        blocked.block(
10091            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
10092            Some("waits on both".to_owned()),
10093        );
10094        queue.put(&mut blocked).unwrap();
10095
10096        resolve_blockers(&queue, &questions);
10097
10098        let after = queue.get(&blocked.id).unwrap();
10099        assert_eq!(
10100            after.status,
10101            TaskStatus::Held,
10102            "a missing dependency must not leave the task blocked forever"
10103        );
10104        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
10105        assert!(after.blocked_by.is_empty());
10106        let reason = after.hold_reason.as_deref().unwrap_or_default();
10107        assert!(
10108            reason.contains("20260101-000001-gone"),
10109            "the missing id must be named so an operator can tell what happened: {reason}"
10110        );
10111        assert!(
10112            reason.contains(&still_going.id),
10113            "the still-valid dependency must not silently vanish from the record: {reason}"
10114        );
10115    }
10116
10117    #[test]
10118    fn instruction_for_is_unchanged_without_any_answers() {
10119        let t = task();
10120        assert_eq!(instruction_for(&t), t.instruction);
10121    }
10122
10123    #[test]
10124    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
10125        let dir = tempfile::tempdir().unwrap();
10126        let q = Queue::at(dir.path().join("queue"));
10127        let src = dir.path().join("shot.png");
10128        std::fs::write(&src, "x").unwrap();
10129        let mut t = task();
10130        q.attach(&mut t, &[src]).unwrap();
10131        let paths = task_attachments(&q, &t).unwrap();
10132        assert_eq!(paths.len(), 1);
10133        assert!(paths[0].is_absolute() && paths[0].is_file());
10134        std::fs::remove_file(&paths[0]).unwrap();
10135        let err = task_attachments(&q, &t).unwrap_err().to_string();
10136        assert!(err.contains("shot.png"), "{err}");
10137    }
10138
10139    #[tokio::test]
10140    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
10141        let dir = tempfile::tempdir().unwrap();
10142        let queue_path = dir.path().join("queue");
10143        let queue = Queue::at(queue_path.clone());
10144        let mut t = task();
10145        t.source = Source::Agent {
10146            run: "originating-chat".into(),
10147            node: crate::queue::CHAT_NODE.into(),
10148        };
10149        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
10150            stage: "config-fetch",
10151            target: "origin/main".into(),
10152        });
10153        record_config_failure(&mut t, &fetch);
10154        t.hold_machine(Some(format!("{fetch:#}")));
10155        let fetch_key = t.chat_notice_due().unwrap();
10156        t.chat_notices.push(fetch_key.clone());
10157        queue.put(&mut t).unwrap();
10158
10159        let queue = Queue::at(queue_path);
10160        let mut t = queue.get(&t.id).unwrap();
10161        let a = dir.path().join("a.toml");
10162        let b = dir.path().join("b.toml");
10163        for (path, text, new_cause) in [
10164            (&a, "[graph", true),
10165            (&a, "[verify", false),
10166            (&a, "[graph]\nimplementers = 'invalid-type'", true),
10167            (&b, "[graph]\nimplementers = 'invalid-type'", true),
10168        ] {
10169            t.release_operator("test", None);
10170            std::fs::write(path, text).unwrap();
10171            let error = Config::discover_fetched(dir.path(), Some(path))
10172                .await
10173                .unwrap_err();
10174            record_config_failure(&mut t, &error);
10175            t.hold_machine(Some(format!("{error:#}")));
10176            let due = t.chat_notice_due();
10177            assert_eq!(due.is_some(), new_cause, "{error:#}");
10178            if let Some(key) = due {
10179                assert_ne!(key, fetch_key);
10180                t.chat_notices.push(key);
10181            }
10182        }
10183        t.succeed();
10184        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
10185    }
10186
10187    #[test]
10188    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
10189        let dir = tempfile::tempdir().unwrap();
10190        let queue_path = dir.path().join("queue");
10191        let queue = Queue::at(queue_path.clone());
10192        let mut t = task();
10193        t.source = crate::queue::Source::Agent {
10194            run: "originating-chat".into(),
10195            node: crate::queue::CHAT_NODE.into(),
10196        };
10197        let a = dir.path().join("a.png");
10198        let b = dir.path().join("b.png");
10199        std::fs::write(&a, "a").unwrap();
10200        std::fs::write(&b, "b").unwrap();
10201        queue.attach(&mut t, &[a, b]).unwrap();
10202        let paths = task_attachments(&queue, &t).unwrap();
10203        for path in &paths {
10204            std::fs::remove_file(path).unwrap();
10205        }
10206        let missing = task_attachments(&queue, &t).unwrap_err();
10207        t.attempts += 1;
10208        let reason = missing.to_string();
10209        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10210        let first = t.chat_notice_due().expect("first attachment notice");
10211        t.chat_notices.push(first.clone());
10212        queue.put(&mut t).unwrap();
10213
10214        let queue = Queue::at(queue_path.clone());
10215        let mut t = queue.get(&t.id).unwrap();
10216        assert!(t.chat_notice_due().is_none(), "restart does not replay");
10217        t.release_operator("test", None);
10218        t.attempts += 1;
10219        let missing = task_attachments(&queue, &t).unwrap_err();
10220        t.fail_startup_target(
10221            "startup-attachments",
10222            missing.name,
10223            "same missing attachment with regenerated wording",
10224            1,
10225        );
10226        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
10227
10228        std::fs::write(&paths[0], "restored").unwrap();
10229        t.release_operator("test", None);
10230        t.attempts += 1;
10231        let missing = task_attachments(&queue, &t).unwrap_err();
10232        let reason = missing.to_string();
10233        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10234        let second = t
10235            .chat_notice_due()
10236            .expect("different attachment must notify");
10237        assert_ne!(first, second);
10238        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
10239    }
10240
10241    #[test]
10242    fn resumed_instruction_is_unchanged_without_any_answers() {
10243        let t = task();
10244        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
10245    }
10246
10247    #[test]
10248    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
10249        let mut t = task();
10250        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10251        // The run's own instruction on disk predates the answer: it is the
10252        // plain original text `Runner::start` saved before the operator was
10253        // ever asked anything.
10254        let old = t.instruction.clone();
10255
10256        let refreshed = resumed_instruction(&old, &t);
10257        assert!(refreshed.starts_with(&old), "the original text is kept");
10258        assert!(refreshed.contains("Which backend?"));
10259        assert!(refreshed.contains("SQLite"));
10260    }
10261
10262    #[test]
10263    fn resumed_instruction_keeps_an_original_answers_heading() {
10264        let mut t = task();
10265        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
10266        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10267
10268        let refreshed = resumed_instruction(&t.instruction, &t);
10269
10270        assert!(
10271            refreshed.starts_with(&t.instruction),
10272            "an answers heading in the original instruction is not the appended block"
10273        );
10274        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
10275        assert!(refreshed.contains("Which backend?"));
10276        assert!(refreshed.contains("SQLite"));
10277
10278        let repeated = resumed_instruction(&refreshed, &t);
10279        assert_eq!(
10280            repeated, refreshed,
10281            "only the final appended block is refreshed"
10282        );
10283    }
10284
10285    #[test]
10286    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
10287        let mut t = task();
10288        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10289
10290        // A first resume appends the block; a second resume of the same run,
10291        // with no new answer in between, must reproduce exactly the same
10292        // text rather than appending the block a second time.
10293        let once = resumed_instruction(&t.instruction, &t);
10294        let twice = resumed_instruction(&once, &t);
10295        assert_eq!(once, twice);
10296        assert_eq!(once.matches("Which backend?").count(), 1);
10297
10298        // A later answer replaces the block wholesale rather than growing it.
10299        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
10300        let refreshed = resumed_instruction(&once, &t);
10301        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
10302        assert!(refreshed.contains("Which backend?"));
10303        assert!(refreshed.contains("Which cache?"));
10304    }
10305
10306    #[test]
10307    fn prepare_instruction_covers_all_three_starters() {
10308        let mut t = task();
10309        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10310
10311        // Start: a fresh run gets the task text plus every answer so far —
10312        // exactly `instruction_for`.
10313        assert_eq!(
10314            prepare_instruction(&Starter::Start, None, &t),
10315            Some(instruction_for(&t))
10316        );
10317
10318        // Resume: the run's prior instruction is refreshed with the answer,
10319        // not discarded and not left stale.
10320        let old = t.instruction.clone();
10321        assert_eq!(
10322            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
10323            Some(resumed_instruction(&old, &t))
10324        );
10325
10326        // Review: a review-only pass builds its own instruction from the
10327        // branch's history in `crate::graph`, with no task statement at all -
10328        // this boundary must leave it alone.
10329        assert_eq!(
10330            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
10331            None
10332        );
10333    }
10334
10335    #[test]
10336    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
10337        assert_eq!(
10338            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
10339            Starter::Review("magi/eba2/A".to_owned())
10340        );
10341    }
10342
10343    #[test]
10344    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
10345        assert_eq!(
10346            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
10347            Starter::Start,
10348            "a vanished review branch must not fall back to resuming the old run either"
10349        );
10350    }
10351
10352    #[test]
10353    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
10354        let mut t = task();
10355        t.start("old-run".to_owned());
10356        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
10357        t.release();
10358        let branch = t.review_branch.take();
10359        assert_eq!(
10360            choose_starter(branch.as_deref(), true, Some("old-run")),
10361            Starter::Review("magi/eba2/A".to_owned()),
10362            "a review wins over resuming the old run"
10363        );
10364    }
10365
10366    #[test]
10367    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
10368        assert_eq!(
10369            choose_starter(None, false, Some("some-run")),
10370            Starter::Resume("some-run".to_owned())
10371        );
10372        assert_eq!(choose_starter(None, false, None), Starter::Start);
10373    }
10374
10375    #[test]
10376    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
10377        let mut released = task();
10378        released.start("stalled-run".to_owned());
10379        released.requeue();
10380        let unfinished = (!released.fresh_start)
10381            .then(|| Some("stalled-run".to_owned()))
10382            .flatten();
10383        assert_eq!(
10384            choose_starter(None, false, unfinished.as_deref()),
10385            Starter::Start,
10386            "release keeps run history but must not resume it"
10387        );
10388        assert_eq!(released.runs, ["stalled-run"]);
10389    }
10390
10391    #[test]
10392    fn an_ordinary_release_keeps_a_resumable_run_available() {
10393        let mut released = task();
10394        released.start("stalled-run".to_owned());
10395        released.release();
10396        let unfinished = (!released.fresh_start)
10397            .then(|| Some("stalled-run".to_owned()))
10398            .flatten();
10399        assert_eq!(
10400            choose_starter(None, false, unfinished.as_deref()),
10401            Starter::Resume("stalled-run".to_owned()),
10402            "manual release must preserve the normal resume path"
10403        );
10404    }
10405
10406    #[test]
10407    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
10408        let mut state = run_state(RunStatus::Blocked);
10409        state.config.graph.review_rounds = 3;
10410        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
10411        assert!(exhausted_review_budget(&state));
10412
10413        // One round still unused: resuming can still ask a reviewer something.
10414        state.reviews.pop();
10415        assert!(!exhausted_review_budget(&state));
10416
10417        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
10418        // count: only a `Blocked` run re-enters the review loop on resume.
10419        let mut stalled = run_state(RunStatus::Stalled);
10420        stalled.config.graph.review_rounds = 1;
10421        stalled.reviews = vec![review_round(1)];
10422        assert!(!exhausted_review_budget(&stalled));
10423    }
10424
10425    fn review_round(round: usize) -> crate::run::ReviewRound {
10426        crate::run::ReviewRound {
10427            round,
10428            head: "deadbeef".to_owned(),
10429            verified_head: None,
10430            verified_at: None,
10431            reviews: Vec::new(),
10432            e2e: Vec::new(),
10433            verify_retried: false,
10434            e2e_deferred: false,
10435            e2e_defer_reason: None,
10436            fix: None,
10437            blocking: 0,
10438            answered: 1,
10439            expected: 1,
10440            clean: false,
10441            progressed: true,
10442            vote_split: false,
10443            reconsideration: Vec::new(),
10444            verdict: None,
10445        }
10446    }
10447
10448    #[test]
10449    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
10450        let mut run = RunState::new(
10451            PathBuf::from("/repo"),
10452            "main".to_owned(),
10453            "abc1234def".to_owned(),
10454            "add retries".to_owned(),
10455            Config::default(),
10456        );
10457        run.status = RunStatus::Judging;
10458        run.parked = true;
10459        let mut task = Task::new(
10460            "add retries".to_owned(),
10461            "add retries".to_owned(),
10462            PathBuf::from("/repo"),
10463            crate::queue::Source::Human,
10464        );
10465        task.status = TaskStatus::Failed;
10466        task.runs = vec![run.id.clone()];
10467        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
10468        assert!(with(&task, &run), "parked after judging is the case");
10469        let mut parked_task = task.clone();
10470        parked_task.status = TaskStatus::Parked;
10471        assert!(with(&parked_task, &run), "the Parked status is the case");
10472
10473        let mut not_parked = run.clone();
10474        not_parked.parked = false;
10475        not_parked.status = RunStatus::Stalled;
10476        assert!(!with(&task, &not_parked), "a stall is the conductor's");
10477
10478        let mut fresh = task.clone();
10479        fresh.fresh_start = true;
10480        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
10481
10482        let mut review = task.clone();
10483        review.review_branch = Some("magi/x/A".to_owned());
10484        assert!(!with(&review, &run), "review is ranked before resume");
10485
10486        let mut held = task.clone();
10487        held.status = TaskStatus::Held;
10488        assert!(!with(&held, &run), "a hold stays visible to the conductor");
10489
10490        let mut released = run.clone();
10491        released.released_to = Some("20260901-000000-new1".to_owned());
10492        assert!(!with(&task, &released), "nothing left to resume into");
10493
10494        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
10495            "unreadable"
10496        )));
10497    }
10498
10499    #[test]
10500    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
10501        let mut released = RunState::new(
10502            PathBuf::from("/repo"),
10503            "main".to_owned(),
10504            "abc1234def".to_owned(),
10505            "add retries".to_owned(),
10506            Config::default(),
10507        );
10508        released.status = RunStatus::Blocked;
10509        assert_eq!(
10510            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10511            Some(released.id.clone())
10512        );
10513        released.released_to = Some("20260901-000000-new1".to_owned());
10514        assert_eq!(
10515            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10516            None,
10517            "there is nothing left to resume it into"
10518        );
10519    }
10520
10521    #[test]
10522    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
10523        // Mirrors the failure this exists to close: a task's last run ended
10524        // `Blocked` with the review budget spent, `crate::conduct` chose
10525        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
10526        // evidence), and without this check `attempt` would go on treating
10527        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
10528        // review loop iterates zero times over an already-spent budget, so
10529        // the resumed run settles right back to `Blocked` having asked nobody
10530        // anything, and `Requeue`'s promised fresh competition never happens.
10531        let mut exhausted = RunState::new(
10532            PathBuf::from("/repo"),
10533            "main".to_owned(),
10534            "abc1234def".to_owned(),
10535            "add retries".to_owned(),
10536            Config::default(),
10537        );
10538        exhausted.status = RunStatus::Blocked;
10539        exhausted.config.graph.review_rounds = 1;
10540        exhausted.reviews = vec![review_round(1)];
10541
10542        assert_eq!(
10543            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
10544            None,
10545            "an exhausted `Blocked` run must not be offered as resumable"
10546        );
10547
10548        // A `Blocked` run with rounds still unused is genuinely worth
10549        // resuming, and must still be found.
10550        let mut has_budget_left = RunState::new(
10551            PathBuf::from("/repo"),
10552            "main".to_owned(),
10553            "abc1234def".to_owned(),
10554            "add retries".to_owned(),
10555            Config::default(),
10556        );
10557        has_budget_left.status = RunStatus::Blocked;
10558        has_budget_left.config.graph.review_rounds = 3;
10559        has_budget_left.reviews = vec![review_round(1)];
10560
10561        assert_eq!(
10562            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
10563                Ok(has_budget_left.clone())
10564            }),
10565            Some(has_budget_left.id.clone())
10566        );
10567    }
10568
10569    #[test]
10570    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
10571        let mut run = RunState::new(
10572            PathBuf::from("/repo"),
10573            "main".to_owned(),
10574            "abc1234def".to_owned(),
10575            "add retries".to_owned(),
10576            Config::default(),
10577        );
10578        run.status = RunStatus::Blocked;
10579        run.config.graph.review_rounds = 1;
10580        run.reviews = vec![review_round(1)];
10581        run.pr_publication_pending = true;
10582        assert_eq!(
10583            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
10584            Some(run.id.clone()),
10585            "a spent review budget must not turn a failed publication into a re-competition"
10586        );
10587    }
10588
10589    #[test]
10590    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
10591        let mut task = Task::new(
10592            "recover work".into(),
10593            "recover work".into(),
10594            PathBuf::from("/repo"),
10595            crate::queue::Source::Human,
10596        );
10597        let mut history = std::collections::BTreeMap::new();
10598        for index in 0..8 {
10599            let mut run = run_state(RunStatus::Blocked);
10600            run.id = format!("20260101-000000-{index:04}");
10601            run.base_commit = format!("upstream-{index}");
10602            // Seven empty newer attempts must not erase the old recovery owner.
10603            if index > 0 {
10604                run.candidates.clear();
10605            }
10606            task.runs.extend([run.id.clone(), run.id.clone()]);
10607            history.insert(run.id.clone(), run);
10608            task.requeue();
10609        }
10610        let check = |task: &Task, starter: &Starter, limit| {
10611            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
10612        };
10613        assert!(
10614            check(&task, &Starter::Start, 8)
10615                .unwrap()
10616                .contains("8 unretired")
10617        );
10618        assert!(check(&task, &Starter::Start, 9).is_none());
10619        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
10620        task.release_operator("owner", None);
10621        assert_eq!(task.attempts, 0);
10622        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
10623        assert!(check(&restored, &Starter::Start, 8).is_some());
10624        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
10625        assert!(check(&restored, &Starter::Start, 0).is_none());
10626    }
10627
10628    #[test]
10629    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
10630        let mut task = Task::new(
10631            "recover work".into(),
10632            "recover work".into(),
10633            PathBuf::from("/repo"),
10634            crate::queue::Source::Human,
10635        );
10636        let mut run = run_state(RunStatus::Superseded);
10637        run.candidates.clear();
10638        task.runs.push(run.id.clone());
10639        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
10640        run.retired_to = Some("authority".into());
10641        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10642        run.retired_to = None;
10643        run.released_to = Some("authority".into());
10644        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10645        assert!(
10646            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
10647                .unwrap()
10648                .contains("Cannot verify")
10649        );
10650        // Resuming an existing owner needs no new inventory or worktree budget.
10651        assert!(
10652            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
10653                panic!("resume must not load historical attempts")
10654            })
10655            .is_none()
10656        );
10657    }
10658
10659    #[test]
10660    fn retired_resume_requires_a_valid_same_repository_authority() {
10661        let mut source = run_state(RunStatus::Blocked);
10662        let mut empty = run_state(RunStatus::Blocked);
10663        empty.retired_to = Some(source.id.clone());
10664        let runs = vec![source.id.clone(), empty.id.clone()];
10665        let resolve = |source: &RunState, empty: &RunState| {
10666            unfinished_run_with(&runs, "fixture", |id| {
10667                if id == source.id {
10668                    Ok(source.clone())
10669                } else if id == empty.id {
10670                    Ok(empty.clone())
10671                } else {
10672                    bail!("unreadable authority")
10673                }
10674            })
10675        };
10676        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
10677        assert_eq!(
10678            choose_starter(None, false, resolve(&source, &empty).as_deref()),
10679            Starter::Resume(source.id.clone())
10680        );
10681        source.retired_to = Some(empty.id.clone());
10682        assert!(
10683            resolve(&source, &empty).is_none(),
10684            "cycles do not revive obsolete runs"
10685        );
10686        source.retired_to = None;
10687        source.repo = PathBuf::from("/another-repository");
10688        assert!(resolve(&source, &empty).is_none());
10689        source.repo = empty.repo.clone();
10690        source.released_to = Some("later".into());
10691        assert!(resolve(&source, &empty).is_none());
10692        empty.retired_to = Some("unlisted-run".into());
10693        assert!(resolve(&source, &empty).is_none());
10694    }
10695
10696    #[test]
10697    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
10698        // A task whose history holds an *older* run that still looks
10699        // resumable (say, a competition `Runner::review` was started
10700        // alongside after that older run went `Stalled`) and a *newest* run
10701        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
10702        // on this task must mean a fresh competition — falling back to the
10703        // stale, superseded `Stalled` run instead would resurrect history
10704        // nothing asked to revisit and silently defeat the requeue.
10705        let mut older_stalled = RunState::new(
10706            PathBuf::from("/repo"),
10707            "main".to_owned(),
10708            "abc1234def".to_owned(),
10709            "add retries".to_owned(),
10710            Config::default(),
10711        );
10712        older_stalled.status = RunStatus::Stalled;
10713
10714        let mut newest_exhausted = RunState::new(
10715            PathBuf::from("/repo"),
10716            "main".to_owned(),
10717            "abc1234def".to_owned(),
10718            "add retries".to_owned(),
10719            Config::default(),
10720        );
10721        newest_exhausted.status = RunStatus::Blocked;
10722        newest_exhausted.config.graph.review_rounds = 1;
10723        newest_exhausted.reviews = vec![review_round(1)];
10724
10725        assert_eq!(
10726            unfinished_run_with(
10727                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
10728                "t",
10729                |_| Ok(newest_exhausted.clone())
10730            ),
10731            None,
10732            "the newest run is exhausted, so nothing here is worth resuming - \
10733             least of all the older, already-superseded run"
10734        );
10735    }
10736
10737    #[test]
10738    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
10739        assert_eq!(
10740            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
10741                Err(anyhow::anyhow!("fixture is absent"))
10742            }),
10743            None
10744        );
10745    }
10746
10747    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
10748        let mut q = ask::Question::new(
10749            run.to_owned(),
10750            "implement".to_owned(),
10751            "impl-A".to_owned(),
10752            "continue?".to_owned(),
10753            String::new(),
10754            vec!["resume で続行する".to_owned(), "other".to_owned()],
10755        );
10756        q.actions.insert("resume で続行する".to_owned(), action);
10757        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
10758            .unwrap();
10759        q
10760    }
10761
10762    fn held_task_with(run: &str) -> Task {
10763        let mut t = task();
10764        t.runs = vec![run.to_owned()];
10765        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
10766        t
10767    }
10768
10769    fn resume_action(run: &str) -> ask::ChoiceAction {
10770        ask::ChoiceAction::Resume { run: run.into() }
10771    }
10772
10773    #[test]
10774    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
10775        for parked in [false, true] {
10776            let mut t = task();
10777            t.start("A".into());
10778            t.start("B".into());
10779            assert_eq!(t.runs, vec!["A", "B"]);
10780            t.start("A".into());
10781            let mut resumed = run_state(RunStatus::Blocked);
10782            resumed.id = "A".into();
10783            resumed.parked = parked;
10784            resumed.driver_exited = true;
10785            t.hold_machine(Some("resumed run stopped".into()));
10786            let q = action_question("A", resume_action("A"));
10787            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10788            assert_eq!(
10789                decide_action(&t, &q, &PHRASES_EN, |id| {
10790                    assert_eq!(id, "A");
10791                    Ok(resumed.clone())
10792                }),
10793                ActionDecision::Resume("A".into())
10794            );
10795            assert_eq!(
10796                action_standing(&t, &action_question("B", resume_action("B"))),
10797                ActionStanding::Stale
10798            );
10799            t.release_operator("cli", None);
10800            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
10801                assert_eq!(id, "A");
10802                Ok(resumed.clone())
10803            });
10804            assert_eq!(
10805                choose_starter(None, false, unfinished.as_deref()),
10806                Starter::Resume("A".into())
10807            );
10808            assert_eq!(t.runs, vec!["B", "A"]);
10809        }
10810    }
10811
10812    #[test]
10813    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
10814        let mut state = crate::land::tests::repair_state(true, true);
10815        state.status = RunStatus::Landing;
10816        state.parked = true;
10817        state.driver_exited = true;
10818        let mut q = ask::Question::new(
10819            state.id.clone(),
10820            land::APPROVAL_NODE.into(),
10821            "land".into(),
10822            "Merge?".into(),
10823            String::new(),
10824            vec![land::APPROVE.into(), land::HOLD.into()],
10825        );
10826        q.id = state.id.clone();
10827        state.land_approval = Some(crate::run::LandApproval {
10828            question: q.id.clone(),
10829            head: "current-head".into(),
10830        });
10831        assert!(land::upgrade_repair_choice(&mut q, &state));
10832        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10833        let mut task = held_task_with(&state.id);
10834        task.status = TaskStatus::Parked;
10835        assert_eq!(
10836            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10837            ActionDecision::Resume(state.id.clone())
10838        );
10839        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10840        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
10841        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
10842        assert_eq!(
10843            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10844            ActionDecision::Resume(state.id.clone()),
10845            "a repair answer newer than the manual hold resumes the existing owner"
10846        );
10847        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10848        for answered_at in [q.answered_at, None] {
10849            let mut older = q.clone();
10850            older.answered_at = answered_at;
10851            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
10852                panic!("a later manual hold must prevent dispatch")
10853            });
10854            let ActionDecision::Refuse(reason) = refused else {
10855                panic!("expected an actionable refusal, got {refused:?}");
10856            };
10857            assert!(reason.contains("later operator decision"));
10858            assert!(reason.contains(&format!("magi task release {}", task.id)));
10859        }
10860        task.operator_decided_at = None;
10861        let mut superseded = state.clone();
10862        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
10863        assert_eq!(
10864            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
10865            ActionDecision::Stale
10866        );
10867        for case in 1..4 {
10868            let mut changed = state.clone();
10869            match case {
10870                1 => changed.status = RunStatus::Blocked,
10871                2 => changed.released_to = Some("new-owner".into()),
10872                _ => changed.land_approval.as_mut().unwrap().head.clear(),
10873            }
10874            assert!(matches!(
10875                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
10876                ActionDecision::Refuse(_)
10877            ));
10878        }
10879        assert!(matches!(
10880            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
10881            ActionDecision::Refuse(_)
10882        ));
10883        task.runs.push("replacement".into());
10884        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10885        assert_eq!(
10886            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
10887                "old owner must not load"
10888            )),
10889            ActionDecision::Stale
10890        );
10891    }
10892
10893    #[test]
10894    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
10895        let mut state = crate::land::tests::repair_state(true, true);
10896        state.status = RunStatus::Landing;
10897        state.parked = true;
10898        state.driver_exited = true;
10899        let mut q = ask::Question::new(
10900            state.id.clone(),
10901            land::APPROVAL_NODE.into(),
10902            "land".into(),
10903            "Merge?".into(),
10904            String::new(),
10905            vec![land::APPROVE.into(), land::HOLD.into()],
10906        );
10907        q.id = state.id.clone();
10908        state.land_approval = Some(crate::run::LandApproval {
10909            question: q.id.clone(),
10910            head: "current-head".into(),
10911        });
10912        state.save().unwrap();
10913        land::upgrade_repair_choice(&mut q, &state);
10914        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10915        Questions::open().put(&mut q).unwrap();
10916        let tmp = tempfile::tempdir().unwrap();
10917        let queue = Queue::at(tmp.path().join("queue"));
10918        let mut task = held_task_with(&state.id);
10919        task.status = TaskStatus::Parked;
10920        queue.put(&mut task).unwrap();
10921        let empty = Arc::new(tokio::sync::Semaphore::new(0));
10922        let free = Arc::new(tokio::sync::Semaphore::new(1));
10923        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
10924        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
10925        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
10926        assert!(claim.permit.is_some());
10927        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
10928        drop(claim);
10929        Questions::open()
10930            .update(&q.id, |q| {
10931                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
10932                Ok(())
10933            })
10934            .unwrap();
10935        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
10936        assert!(claim.permit.is_none());
10937        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
10938    }
10939
10940    #[test]
10941    fn decide_action_resumes_only_the_latest_resumable_run() {
10942        let t = held_task_with("r1");
10943        let q = action_question("r1", resume_action("r1"));
10944        let load = |s: RunState| move |_: &str| Ok(s);
10945        assert_eq!(
10946            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
10947            ActionDecision::Resume("r1".into())
10948        );
10949        // Not the latest run of the task.
10950        let q_other = action_question("r1", resume_action("r0"));
10951        assert!(matches!(
10952            decide_action(
10953                &t,
10954                &q_other,
10955                &PHRASES_EN,
10956                load(run_state(RunStatus::Blocked))
10957            ),
10958            ActionDecision::Refuse(_)
10959        ));
10960        // A finished run cannot make progress.
10961        assert!(matches!(
10962            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
10963            ActionDecision::Refuse(_)
10964        ));
10965        // A released one either.
10966        let mut released = run_state(RunStatus::Blocked);
10967        released.released_to = Some("elsewhere".into());
10968        assert!(matches!(
10969            decide_action(&t, &q, &PHRASES_EN, load(released)),
10970            ActionDecision::Refuse(_)
10971        ));
10972        // Unreadable state is a refusal, never a fresh competition.
10973        assert!(matches!(
10974            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
10975            ActionDecision::Refuse(_)
10976        ));
10977    }
10978
10979    #[test]
10980    fn decide_action_ignores_a_question_about_an_earlier_run() {
10981        let mut t = held_task_with("r1");
10982        t.runs.push("r2".to_owned());
10983        let never = |_: &str| -> Result<RunState> { bail!("not read") };
10984        assert_eq!(
10985            decide_action(
10986                &t,
10987                &action_question("r1", ask::ChoiceAction::Done),
10988                &PHRASES_EN,
10989                never
10990            ),
10991            ActionDecision::Stale
10992        );
10993    }
10994
10995    #[test]
10996    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
10997        let mut t = held_task_with("r1");
10998        let never = |_: &str| -> Result<RunState> { bail!("not read") };
10999        assert_eq!(
11000            decide_action(
11001                &t,
11002                &action_question("r1", ask::ChoiceAction::Requeue),
11003                &PHRASES_EN,
11004                never
11005            ),
11006            ActionDecision::Requeue
11007        );
11008        let done_q = action_question("r1", ask::ChoiceAction::Done);
11009        assert_eq!(
11010            decide_action(&t, &done_q, &PHRASES_EN, never),
11011            ActionDecision::Done
11012        );
11013        t.mark_action_applied(&done_q.id);
11014        assert_eq!(
11015            decide_action(&t, &done_q, &PHRASES_EN, never),
11016            ActionDecision::Skip
11017        );
11018
11019        // A plain answer (no action for that label) does nothing.
11020        let mut plain = action_question("r1", ask::ChoiceAction::Done);
11021        plain.actions.clear();
11022        assert_eq!(
11023            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
11024            ActionDecision::Skip
11025        );
11026        // A running task is left alone.
11027        let mut running = held_task_with("r1");
11028        running.status = TaskStatus::Running;
11029        assert_eq!(
11030            decide_action(
11031                &running,
11032                &action_question("r1", ask::ChoiceAction::Done),
11033                &PHRASES_EN,
11034                never
11035            ),
11036            ActionDecision::Skip
11037        );
11038    }
11039
11040    #[test]
11041    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
11042        crate::run::pin_test_home();
11043        for legacy in [false, true] {
11044            let dir = tempfile::tempdir().unwrap();
11045            let queue = Queue::at(dir.path().join("queue"));
11046            let questions = Questions::at(dir.path().join("questions"));
11047            let run = "20260101-000000-hold";
11048            let mut task = held_task_with(run);
11049            task.status = TaskStatus::Parked;
11050            let mut q = ask::Question::new(
11051                run.into(),
11052                land::APPROVAL_NODE.into(),
11053                "land".into(),
11054                "Repair?".into(),
11055                String::new(),
11056                vec![land::REPAIR.into()],
11057            );
11058            q.actions.insert(land::REPAIR.into(), resume_action(run));
11059            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
11060            // Deterministically order the answer before the actual manual hold.
11061            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
11062            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
11063            questions.put(&mut q).unwrap();
11064            task.hold_manual(Some("Keep this PR paused".into()));
11065            if legacy {
11066                task.hold_source = None;
11067            }
11068            queue.put(&mut task).unwrap();
11069
11070            apply_task_choice_actions(&queue, &questions, dir.path());
11071            let after = queue.get(&task.id).unwrap();
11072            assert!(after.operator_held());
11073            assert_eq!(after.hold_source, task.hold_source);
11074            assert_eq!(after.operator_decided_at, task.operator_decided_at);
11075            assert_eq!(after.runs, task.runs);
11076            assert_eq!(after.instruction, task.instruction);
11077            assert!(after.resume_override.is_none());
11078            assert!(after.action_applied(&q.id));
11079            let reason = after.hold_reason.as_deref().unwrap();
11080            assert!(reason.starts_with("Keep this PR paused"));
11081            assert!(reason.contains("later operator decision"));
11082            assert!(reason.contains(&format!("magi task release {}", task.id)));
11083
11084            for recovery in [
11085                crate::conduct::Recovery::Review,
11086                crate::conduct::Recovery::Requeue,
11087            ] {
11088                crate::conduct::apply(
11089                    &queue,
11090                    &questions,
11091                    &crate::conduct::Verdict {
11092                        decisions: vec![crate::conduct::Decision {
11093                            id: task.id.clone(),
11094                            recovery: Some(recovery),
11095                            ..Default::default()
11096                        }],
11097                    },
11098                )
11099                .unwrap();
11100            }
11101            // Reconciliation is idempotent, and automatic recovery cannot
11102            // reopen this owner after it observes the rejected repair answer.
11103            apply_task_choice_actions(&queue, &questions, dir.path());
11104            let still_held = queue.get(&task.id).unwrap();
11105            assert!(still_held.operator_held());
11106            assert_eq!(still_held.hold_reason, after.hold_reason);
11107            assert_eq!(still_held.runs, task.runs);
11108            assert!(still_held.review_branch.is_none());
11109            assert!(!still_held.fresh_start);
11110            assert!(queue.next_runnable().is_none());
11111        }
11112    }
11113
11114    #[test]
11115    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
11116        for held in [false, true] {
11117            for retry in [false, true] {
11118                let dir = tempfile::tempdir().unwrap();
11119                let queue = Queue::at(dir.path().join("queue"));
11120                let questions = Questions::at(dir.path().join("questions"));
11121                let home = dir.path().join("home");
11122                let mut t = task();
11123                if held {
11124                    t.hold_machine(Some("driver state unknown".into()));
11125                }
11126                queue.put(&mut t).unwrap();
11127                let verdict = serde_json::from_value(serde_json::json!({
11128                    "decisions": [{
11129                        "id": t.id,
11130                        "question": "Driver state unknown; retry the checks or hold?",
11131                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
11132                        "actions": {
11133                            "daemon: recheck and retry": {"do": "requeue"},
11134                            "daemon: hold the task": {"do": "hold"}
11135                        }
11136                    }]
11137                }))
11138                .unwrap();
11139                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
11140                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11141                let mut q = questions.list().pop().unwrap();
11142                let choice = if retry {
11143                    "daemon: recheck and retry"
11144                } else {
11145                    "daemon: hold the task"
11146                };
11147                assert_eq!(q.actions.len(), 2);
11148                q.answer(ask::Answer::Choice(choice.into())).unwrap();
11149                questions.put(&mut q).unwrap();
11150
11151                // A Web answer does not remove the deputy's fresh lease.
11152                questions.beat(&q.id, ask::WaiterKind::Deputy);
11153                for _ in 0..2 {
11154                    resolve_blockers(&queue, &questions);
11155                    apply_task_choice_actions(&queue, &questions, &home);
11156                    let waiting = queue.get(&t.id).unwrap();
11157                    assert_eq!(waiting.status, TaskStatus::Blocked);
11158                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
11159                    assert!(waiting.answers.is_empty());
11160                    assert!(!waiting.action_applied(&q.id));
11161                    assert!(runnable(&queue).is_empty());
11162                    let free = Arc::new(tokio::sync::Semaphore::new(1));
11163                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
11164                }
11165                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11166
11167                // Releasing the blocker and applying the operation share one save.
11168                resolve_blockers(&queue, &questions);
11169                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11170                apply_task_choice_actions(&queue, &questions, &home);
11171                let after = queue.get(&t.id).unwrap();
11172                assert_eq!(
11173                    after.status,
11174                    if retry {
11175                        TaskStatus::Queued
11176                    } else {
11177                        TaskStatus::Held
11178                    }
11179                );
11180                assert!(after.action_applied(&q.id));
11181                assert_eq!(after.operator_held(), !retry);
11182                assert_eq!(after.answers.len(), 1);
11183
11184                // A later operator decision must not replay this answer.
11185                let mut changed = after;
11186                if retry {
11187                    changed.hold_manual(Some("later hold".into()));
11188                } else {
11189                    changed.release_operator("test", None);
11190                }
11191                let expected = changed.status;
11192                queue.put(&mut changed).unwrap();
11193                apply_task_choice_actions(&queue, &questions, &home);
11194                assert_eq!(queue.get(&t.id).unwrap().status, expected);
11195            }
11196        }
11197    }
11198
11199    #[test]
11200    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
11201        let dir = tempfile::tempdir().unwrap();
11202        let queue = Queue::at(dir.path().join("queue"));
11203        let questions = Questions::at(dir.path().join("questions"));
11204        let home = dir.path().join("home");
11205        let mut state = run_state(RunStatus::Blocked);
11206        state.id = "20260101-000000-act1".to_owned();
11207        state.save_under(&home).unwrap();
11208
11209        let mut t = held_task_with(&state.id);
11210        queue.put(&mut t).unwrap();
11211        let mut q = action_question(&state.id, resume_action(&state.id));
11212        questions.put(&mut q).unwrap();
11213
11214        apply_task_choice_actions(&queue, &questions, &home);
11215        let after = queue.get(&t.id).unwrap();
11216        assert_eq!(after.status, TaskStatus::Queued);
11217        assert!(!after.fresh_start);
11218        assert!(after.action_applied(&q.id));
11219        let pin = after.resume_override.clone().unwrap();
11220        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
11221        assert!(pin.forced);
11222
11223        // Held again later: the same answer does not release it a second time.
11224        let mut again = queue.get(&t.id).unwrap();
11225        again.hold_machine(Some("later".into()));
11226        queue.put(&mut again).unwrap();
11227        apply_task_choice_actions(&queue, &questions, &home);
11228        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11229    }
11230
11231    #[test]
11232    fn a_delivered_answer_is_still_acted_on_exactly_once() {
11233        let dir = tempfile::tempdir().unwrap();
11234        let queue = Queue::at(dir.path().join("queue"));
11235        let questions = Questions::at(dir.path().join("questions"));
11236        let home = dir.path().join("home");
11237        let mut state = run_state(RunStatus::Blocked);
11238        state.id = "20260101-000000-act2".to_owned();
11239        state.save_under(&home).unwrap();
11240
11241        let mut t = held_task_with(&state.id);
11242        queue.put(&mut t).unwrap();
11243        let mut q = action_question(&state.id, resume_action(&state.id));
11244        q.answer_delivered = true;
11245        questions.put(&mut q).unwrap();
11246
11247        // Delivered, and the agent then died: the task is still held, so the
11248        // chosen action applies.
11249        apply_task_choice_actions(&queue, &questions, &home);
11250        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11251        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
11252
11253        // Held again: the same answer does nothing a second time.
11254        let mut again = queue.get(&t.id).unwrap();
11255        again.hold_machine(Some("later".into()));
11256        queue.put(&mut again).unwrap();
11257        apply_task_choice_actions(&queue, &questions, &home);
11258        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11259    }
11260
11261    #[test]
11262    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
11263        let dir = tempfile::tempdir().unwrap();
11264        let queue = Queue::at(dir.path().join("queue"));
11265        let questions = Questions::at(dir.path().join("questions"));
11266        let home = dir.path().join("home");
11267        let mut state = run_state(RunStatus::Blocked);
11268        state.id = "20260101-000000-act3".to_owned();
11269        state.save_under(&home).unwrap();
11270        let mut t = held_task_with(&state.id);
11271        queue.put(&mut t).unwrap();
11272        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
11273        questions.put(&mut q).unwrap();
11274
11275        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
11276        apply_task_choice_actions(&queue, &questions, &home);
11277        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11278
11279        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11280        apply_task_choice_actions(&queue, &questions, &home);
11281        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11282    }
11283
11284    #[test]
11285    fn action_standing_tells_the_reasons_apart() {
11286        let mut t = held_task_with("r1");
11287        let q = action_question("r1", ask::ChoiceAction::Requeue);
11288        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
11289        let mut plain = q.clone();
11290        plain.actions.clear();
11291        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
11292
11293        // Applied wins over everything, even a running task.
11294        t.mark_action_applied(&q.id);
11295        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
11296
11297        // A newer attempt running: the old question is Stale, not Busy.
11298        let mut t = held_task_with("r1");
11299        t.start("r2".to_owned());
11300        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
11301        // The same question about the latest run just waits.
11302        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
11303        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11304        t.status = TaskStatus::Blocked;
11305        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11306
11307        // A conductor question is keyed by the task, never stale.
11308        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
11309        c.node = crate::conduct::NODE.to_owned();
11310        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
11311        assert!(!ActionStanding::Busy.daemon_owns());
11312    }
11313
11314    #[test]
11315    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
11316        let dir = tempfile::tempdir().unwrap();
11317        let queue = Queue::at(dir.path().join("queue"));
11318        let questions = Questions::at(dir.path().join("questions"));
11319        let home = dir.path().join("home");
11320        let mut state = run_state(RunStatus::Blocked);
11321        state.id = "20260101-000000-act4".to_owned();
11322        state.save_under(&home).unwrap();
11323        let mut t = held_task_with(&state.id);
11324        t.status = TaskStatus::Running;
11325        queue.put(&mut t).unwrap();
11326        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11327        q.cwd = Some(dir.path().display().to_string());
11328        questions.put(&mut q).unwrap();
11329
11330        // While the task runs the daemon will not act, so the waiter still
11331        // delivers the word to the dead asker's seat ...
11332        let running = queue.get(&t.id).unwrap();
11333        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
11334        assert!(matches!(
11335            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
11336            crate::waiter::Action::Deliver(_)
11337        ));
11338        // ... and the daemon waits while the task runs, then applies once.
11339        apply_task_choice_actions(&queue, &questions, &home);
11340        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11341        let mut back = queue.get(&t.id).unwrap();
11342        back.hold_machine(Some("later".into()));
11343        queue.put(&mut back).unwrap();
11344        apply_task_choice_actions(&queue, &questions, &home);
11345        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
11346        let mut again = queue.get(&t.id).unwrap();
11347        again.hold_machine(Some("again".into()));
11348        queue.put(&mut again).unwrap();
11349        apply_task_choice_actions(&queue, &questions, &home);
11350        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11351    }
11352}