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) if crate::handover::can_resume(&s) => ActionDecision::Resume(run.clone()),
988                Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
989                    q.short(),
990                    ask::short_id(run),
991                )),
992                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
993                    q.short(),
994                    ask::short_id(run),
995                    &format!("{e:#}"),
996                )),
997            }
998        }
999    }
1000}
1001
1002/// The fixed prose the daemon writes into [`Task::last_error`] and
1003/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1004/// `triage::Wording` and `land::Words`: only English and Japanese are
1005/// translated, anything else falls back to English.
1006///
1007/// Rendered when the reason is *generated*, so a reason keeps the language it
1008/// was written in if the setting changes later. The notification frame
1009/// (`Task <id> is held:`) is not here and stays English.
1010///
1011/// Deliberately **not** translated, because other code reads them back by
1012/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1013/// and `gate red`. IDs, node names, paths and external error text are embedded
1014/// as they are.
1015struct Phrases {
1016    /// `{}` = status label, then the detail.
1017    graph_stopped: fn(&str, &str) -> String,
1018    quorum_lost: &'static str,
1019    /// Followed by the seats' names.
1020    quota_took_out: &'static str,
1021    /// Followed by the status label.
1022    run_ended: &'static str,
1023    /// Followed by the question's short id.
1024    waiting_for_answer: &'static str,
1025    recovered_running: &'static str,
1026    no_run_to_recover: &'static str,
1027    could_not_start: &'static str,
1028    resume_not_latest: fn(&str, &str) -> String,
1029    resume_cannot_progress: fn(&str, &str) -> String,
1030    resume_unreadable: fn(&str, &str, &str) -> String,
1031    /// A takeover refusal: the operator-facing text. English is the error's own
1032    /// `Display`; a translation keeps the machine detail apart in parentheses.
1033    handover_refused: fn(&crate::handover::Refused) -> String,
1034    /// Appended to a refused handover's hold reason (leading space included).
1035    handover_hint: &'static str,
1036    /// (seats that never answered, review rounds) for the review loop's
1037    /// "refusing to call it clean" stop.
1038    reviewers_never_answered: fn(usize, usize) -> String,
1039}
1040
1041const PHRASES_EN: Phrases = Phrases {
1042    graph_stopped: |status, detail| {
1043        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1044    },
1045    quorum_lost: "the judging panel lost its quorum",
1046    quota_took_out: "; quota took out ",
1047    run_ended: "run ended ",
1048    waiting_for_answer: " - waiting for operator answer to question ",
1049    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1050    no_run_to_recover: "task was `running` with no live daemon and no readable \
1051                        run to recover; held for a human to check what happened",
1052    could_not_start: "could not start the run: ",
1053    resume_not_latest: |q, run| {
1054        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1055    },
1056    resume_cannot_progress: |q, run| {
1057        format!("question {q} asked to resume run {run}, which cannot make progress")
1058    },
1059    resume_unreadable: |q, run, e| {
1060        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1061    },
1062    handover_refused: |r| r.to_string(),
1063    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1064    reviewers_never_answered: |missing, rounds| {
1065        format!(
1066            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1067             refusing to call it clean"
1068        )
1069    },
1070};
1071
1072const PHRASES_JA: Phrases = Phrases {
1073    graph_stopped: |status, detail| {
1074        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1075    },
1076    quorum_lost: "審査パネルが定足数を失いました",
1077    quota_took_out: "。クォータで脱落: ",
1078    run_ended: "run 終了: ",
1079    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1080    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1081    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1082                        何が起きたか人が確認するため保留にしました",
1083    could_not_start: "run を開始できませんでした: ",
1084    resume_not_latest: |q, run| {
1085        format!(
1086            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1087        )
1088    },
1089    resume_cannot_progress: |q, run| {
1090        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1091    },
1092    resume_unreadable: |q, run, e| {
1093        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1094    },
1095    handover_refused: |r| {
1096        use crate::handover::Refused;
1097        match r {
1098            Refused::Foreign { branch, path, why } => format!(
1099                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1100                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1101                 から、やり直してください(詳細: {why})"
1102            ),
1103            Refused::Unsafe { branch, path, why } => format!(
1104                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1105                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1106                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1107            ),
1108            Refused::ReleaseFailed { branch, path, run } => format!(
1109                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1110                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1111                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1112            ),
1113        }
1114    },
1115    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1116    reviewers_never_answered: |missing, rounds| {
1117        format!(
1118            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1119             クリーンとは認めません"
1120        )
1121    },
1122};
1123
1124fn phrases(language: &str) -> &'static Phrases {
1125    if crate::lang::is_japanese(language) {
1126        &PHRASES_JA
1127    } else {
1128        &PHRASES_EN
1129    }
1130}
1131
1132/// The language of the repository a task belongs to, read best-effort for the
1133/// paths that have no run (and so no config of their own) to ask. An unreadable
1134/// config is English, not an error: a hold reason must still get written.
1135fn language_of(task: &Task, fallback: &Path) -> String {
1136    crate::lang::of_repo(&repo_for(task, fallback))
1137}
1138
1139/// The task an answered question speaks for: the one whose runs include the
1140/// question's run, or - for a conductor question, filed under the task's own
1141/// id - the task with that id.
1142pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1143    if q.node == crate::conduct::NODE {
1144        return tasks.iter().find(|t| t.id == q.run);
1145    }
1146    tasks.iter().find(|t| t.runs.contains(&q.run))
1147}
1148
1149/// Legacy conductor prose never becomes a maintenance command by inference.
1150/// Replace unsupported open labels under the question lock before dispatch.
1151fn repair_choice_offers(questions: &Questions) {
1152    for q in questions.list().into_iter().filter(|q| {
1153        q.status.open()
1154            && q.node == crate::conduct::NODE
1155            && q.choices
1156                .iter()
1157                .any(|c| crate::choice_effect::describe(q, c).is_none())
1158    }) {
1159        let _ = questions.update(&q.id, |current| {
1160            if current.status.open() {
1161                crate::choice_effect::executable_conductor(current);
1162                if let Some(deputy) = &mut current.deputy {
1163                    deputy.brief = crate::deputy::brief(
1164                        &current.run,
1165                        &current.detail,
1166                        &current.choices,
1167                        &current.actions,
1168                    );
1169                }
1170            }
1171            Ok(())
1172        });
1173    }
1174}
1175
1176/// Apply answered typed choices. Only the daemon calls this in production;
1177/// deputies settle the question and never execute its actions.
1178pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1179    apply_maintenance_choices(queue, questions, home).await;
1180    apply_task_choice_actions(queue, questions, home);
1181}
1182
1183/// Apply bounded maintenance effects independently of question ownership: a
1184/// release watcher need not have a queue task, and a predecessor is another run.
1185async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1186    for q in questions.list() {
1187        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1188            continue;
1189        };
1190        // Receipt paths use question IDs, whose format is independent of run
1191        // IDs. Apply the question store's filename safety rule to both eras.
1192        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1193            continue;
1194        }
1195        let dir = home.join("choice-actions");
1196        if std::fs::create_dir_all(&dir).is_err() {
1197            continue;
1198        }
1199        let Ok(lock) = std::fs::OpenOptions::new()
1200            .create(true)
1201            .truncate(false)
1202            .write(true)
1203            .open(dir.join(format!("{}.lock", q.id)))
1204        else {
1205            continue;
1206        };
1207        if crate::pr_head::try_lock_file(&lock).is_err() {
1208            continue;
1209        }
1210        let fresh = !home
1211            .join("choice-actions")
1212            .join(format!("{}.json", q.id))
1213            .exists();
1214        let result = async {
1215            let receipt = dir.join(format!("{}.json", q.id));
1216            if receipt.exists() {
1217                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1218                anyhow::ensure!(
1219                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1220                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1221                );
1222                return Ok::<_, anyhow::Error>(());
1223            }
1224            // Never retry an uncertain external effect. The receipt is written
1225            // before calling gh, exactly like release_watch's rerun record.
1226            let record = |status: &str| -> anyhow::Result<()> {
1227                let tmp = receipt.with_extension("tmp");
1228                std::fs::write(
1229                    &tmp,
1230                    serde_json::to_vec(&serde_json::json!({
1231                        "action": action, "status": status,
1232                    }))?,
1233                )?;
1234                std::fs::rename(tmp, &receipt)?;
1235                Ok(())
1236            };
1237            let applied = async {
1238                match action {
1239                    ask::ChoiceAction::ResumeRun { run } => {
1240                        crate::resume::validate(home, run)?;
1241                        record("started")?;
1242                        if !crate::resume::pin_queued(queue, run, Some(q.asked_at), Some(&q.id))? {
1243                            crate::resume::validate_unqueued(home, run)?;
1244                            crate::resume::start(run.clone());
1245                        }
1246                    }
1247                    ask::ChoiceAction::ReleaseTask {
1248                        task,
1249                        held_at,
1250                        reason,
1251                    } => {
1252                        anyhow::ensure!(
1253                            queue.resolve_id(task)? == *task,
1254                            "task action requires an exact task ID"
1255                        );
1256                        let _claim = queue.claim(task)?;
1257                        let mut task = queue.get(task)?;
1258                        if task.action_applied(&q.id) {
1259                            return Ok(());
1260                        }
1261                        // Filing this conductor question temporarily wraps the
1262                        // original hold in a Blocked state. Restore only that
1263                        // exact blocker on the local copy before checking the
1264                        // hold binding; unrelated waits never authorize release.
1265                        if q.node == crate::conduct::NODE
1266                            && q.run == task.id
1267                            && task.status == TaskStatus::Blocked
1268                            && task.blocked_from == Some(TaskStatus::Held)
1269                            && task.blocked_by.as_slice() == [q.id.as_str()]
1270                        {
1271                            task.unblock(&q.id);
1272                        }
1273                        anyhow::ensure!(
1274                            task.status == TaskStatus::Held
1275                                && task.held_at == Some(*held_at)
1276                                && task.hold_reason.as_deref() == reason.as_deref()
1277                                && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1278                            "task no longer has the hold this question names"
1279                        );
1280                        task.release_operator("choice", Some(&q.id));
1281                        task.mark_action_applied(&q.id);
1282                        queue.put(&mut task)?;
1283                    }
1284                    ask::ChoiceAction::AbandonRun { run } => {
1285                        record("started")?;
1286                        crate::driver::abandon_proven_dead(home, run)?;
1287                    }
1288                    ask::ChoiceAction::RerunChecks {
1289                        repo,
1290                        pr,
1291                        head,
1292                        runs,
1293                    } => {
1294                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1295                            .await?;
1296                    }
1297                    _ => unreachable!(),
1298                }
1299                Ok::<_, anyhow::Error>(())
1300            }
1301            .await;
1302            match applied {
1303                Ok(()) => record("applied"),
1304                Err(e) => {
1305                    record(&format!("refused or failed: {e:#}"))?;
1306                    Err(e)
1307                }
1308            }
1309        }
1310        .await;
1311        // Retire the originating blocker as well as the target operation.
1312        // A foreign resume leaves its issuer held instead of competing beside
1313        // the execution just started. Other successful maintenance lets the
1314        // original task retry its normal, guarded path.
1315        if home
1316            .join("choice-actions")
1317            .join(format!("{}.json", q.id))
1318            .exists()
1319            && let Some(listed) = task_of_question(&queue.list(), &q)
1320            && !listed.action_applied(&q.id)
1321            && let Ok(_claim) = queue.claim(&listed.id)
1322            && let Ok(mut origin) = queue.get(&listed.id)
1323        {
1324            if !origin.operator_held()
1325                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1326                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1327            {
1328                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1329                    origin.hold_machine(Some(format!(
1330                        "Maintenance choice {} settled; inspect its target before releasing this task",
1331                        q.id
1332                    )));
1333                } else {
1334                    origin.unblock(&q.id);
1335                }
1336            }
1337            origin.mark_action_applied(&q.id);
1338            let _ = queue.put(&mut origin);
1339        }
1340        if let Err(e) = result
1341            && fresh
1342        {
1343            notices::raise_in(
1344                home,
1345                Notice::warn(
1346                    &format!("action:{}", q.id),
1347                    format!("Choice action {} was not completed: {e:#}", q.id),
1348                ),
1349            );
1350        }
1351    }
1352}
1353
1354/// Rerun the named failed workflow runs of a pull request, each at most once
1355/// per `request` (a question id, or a chat operation identity). The head,
1356/// lifecycle and failed state are re-read from the forge first; `started` is
1357/// called once those checks pass and before the first external call, and the
1358/// ledger entry is written before every `gh` call, so an uncertain result is
1359/// never repeated automatically.
1360pub(crate) async fn rerun_checks_once(
1361    home: &Path,
1362    request: &str,
1363    repo: &Path,
1364    pr: &str,
1365    head: &str,
1366    runs: &[String],
1367    started: impl FnOnce() -> anyhow::Result<()>,
1368) -> anyhow::Result<()> {
1369    use crate::release_watch::{GhForge, ReleaseForge};
1370    anyhow::ensure!(
1371        !runs.is_empty()
1372            && runs.len() <= 20
1373            && runs
1374                .iter()
1375                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1376            && !pr.starts_with('-'),
1377        "invalid rerun targets"
1378    );
1379    let snap = GhForge.snapshot(repo, pr).await?;
1380    anyhow::ensure!(
1381        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1382        "pull request head or lifecycle changed"
1383    );
1384    anyhow::ensure!(
1385        runs.iter().all(|r| snap
1386            .checks
1387            .iter()
1388            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1389        "named workflow is no longer failed on this pull request"
1390    );
1391    started()?;
1392    let dir = home.join("choice-actions");
1393    std::fs::create_dir_all(&dir)?;
1394    let rerun_lock = std::fs::OpenOptions::new()
1395        .create(true)
1396        .truncate(false)
1397        .write(true)
1398        .open(dir.join("reruns.lock"))?;
1399    crate::pr_head::try_lock_file(&rerun_lock)?;
1400    let ledger = dir.join("reruns.json");
1401    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1402        serde_json::from_slice(&std::fs::read(&ledger)?)?
1403    } else {
1404        Default::default()
1405    };
1406    for run in runs {
1407        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1408        if !recorded.insert(key) {
1409            continue;
1410        }
1411        let tmp = ledger.with_extension("tmp");
1412        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1413        std::fs::rename(tmp, &ledger)?;
1414        GhForge.rerun(repo, run).await?;
1415    }
1416    Ok(())
1417}
1418
1419/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1420///
1421/// Runs on every poll before the conductor looks at the queue. The task is
1422/// re-read under its claim, so a task somebody completed or held by hand in
1423/// the meantime is judged on what it is now. `Resume` releases the task and
1424/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1425/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1426/// ordinary `unfinished_run` logic resumes that same run.
1427pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1428    let tasks = queue.list();
1429    for q in questions.list() {
1430        // Dismissal is committed by the question writer, never a resume.
1431        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1432            continue;
1433        }
1434        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1435            continue;
1436        }
1437        let Some(listed) = task_of_question(&tasks, &q) else {
1438            if q.node == land::APPROVAL_NODE
1439                && q.resolution().as_deref().is_some_and(|choice| {
1440                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1441                })
1442            {
1443                notices::raise_in(
1444                    home,
1445                    Notice::warn(
1446                        &format!("repair-owner:{}", q.id),
1447                        format!(
1448                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1449                            q.run, q.run
1450                        ),
1451                    ),
1452                );
1453            }
1454            continue;
1455        };
1456        if listed.action_applied(&q.id) {
1457            continue;
1458        }
1459        let Ok(_claim) = queue.claim(&listed.id) else {
1460            continue;
1461        };
1462        let Ok(mut task) = queue.get(&listed.id) else {
1463            continue;
1464        };
1465        // Work only on this local copy until the action can be committed.
1466        // In particular, a fresh lease below leaves the persisted task blocked.
1467        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1468            let blockers: Vec<_> = task
1469                .blocked_by
1470                .iter()
1471                .filter(|id| {
1472                    crate::queue::dependency(queue, questions, id)
1473                        == crate::queue::Dependency::Question(q.id.clone())
1474                })
1475                .cloned()
1476                .collect();
1477            if !blockers.is_empty() {
1478                for id in blockers {
1479                    task.unblock(&id);
1480                }
1481                let answer = match &q.answer {
1482                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1483                    None => String::new(),
1484                };
1485                task.record_answer(q.summary.clone(), answer);
1486            }
1487        }
1488        let language = language_of(&task, Path::new("."));
1489        let decision = decide_action(&task, &q, phrases(&language), |id| {
1490            RunState::load_under(id, home)
1491        });
1492        let ran = matches!(
1493            decision,
1494            ActionDecision::Resume(_)
1495                | ActionDecision::Requeue
1496                | ActionDecision::Hold
1497                | ActionDecision::Done
1498        );
1499        if ran && asker_may_still_read(questions, &q, home) {
1500            // The asking process or its seat can still take the word; act
1501            // once it has gone quiet. Bound on the remaining window: the
1502            // check is not atomic with the write below, so an asker that
1503            // takes the word in between (at most one poll, never more than
1504            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1505            // and `Task::actions_applied` under the claim keeps the action to
1506            // one application. The waiter does not deliver an answer that
1507            // carries an action (`waiter::decide_owned`), so it cannot race.
1508            continue;
1509        }
1510        let done = matches!(decision, ActionDecision::Done);
1511        match decision {
1512            ActionDecision::Skip => continue,
1513            ActionDecision::Resume(run) => {
1514                task.release_operator("choice", Some(&q.id));
1515                task.resume_override = Some(crate::queue::OperatorResume {
1516                    question_id: q.id.clone(),
1517                    at: Timestamp::now(),
1518                    conductor_rehold: None,
1519                    forced: true,
1520                    pinned_run: Some(run),
1521                });
1522            }
1523            ActionDecision::Stale => {}
1524            ActionDecision::Requeue => {
1525                task.release_operator("choice-requeue", Some(&q.id));
1526                task.requeue();
1527            }
1528            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1529            ActionDecision::Done => task.succeed(),
1530            ActionDecision::Refuse(why) => {
1531                if task.operator_held() {
1532                    // A rejected answer does not release the operator's hold
1533                    // or reclassify it as recoverable by the conductor.
1534                    task.hold_reason = Some(match task.hold_reason.take() {
1535                        Some(reason) => format!("{reason}\n\n{why}"),
1536                        None => why,
1537                    });
1538                } else {
1539                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1540                    task.hold_machine(Some(why));
1541                }
1542                notices::raise(
1543                    Notice::warn(
1544                        &format!("action:{}", q.id),
1545                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1546                    )
1547                    .link(Link::Task {
1548                        id: task.id.clone(),
1549                    }),
1550                );
1551            }
1552        }
1553        task.mark_action_applied(&q.id);
1554        // The applied id travels with the transition, so a failed save loses
1555        // neither and the answer is acted on at the next poll.
1556        record(queue, &mut task);
1557        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1558            supersede_prior_runs(&task, home);
1559        }
1560        // Delivery is only a note of who has read the answer; the task's own
1561        // mark above is the authority. Best effort.
1562        let _ = questions.update(&q.id, |r| {
1563            r.answer_delivered = true;
1564            Ok(())
1565        });
1566    }
1567}
1568
1569/// Whether something may still read the answer to `q`: a fresh lease, or the
1570/// asking seat still listed as active in its run (its CLI can outlive the
1571/// `magi ask` that was killed).
1572fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1573    let now = Timestamp::now();
1574    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1575        return true;
1576    }
1577    q.node != crate::conduct::NODE
1578        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1579            s.seats_active()
1580                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1581        })
1582}
1583
1584/// Retire an unanswered conductor question after its task no longer refers to
1585/// it. Conductor questions use the task id in `Question::run`, so run-based
1586/// cleanup cannot observe a manual release or completion.
1587///
1588/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1589/// own question also carries a `run`, and a run id that happens to collide
1590/// with some task's id is not this loop's business — only a conductor
1591/// question actually uses the task id that way. One `Questions::list()` scan
1592/// is taken up front and matched against the in-memory task set, rather than
1593/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1594fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1595    let tasks = queue.list();
1596    let by_id: std::collections::BTreeMap<&str, &Task> =
1597        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1598    let referenced: Vec<&str> = tasks
1599        .iter()
1600        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1601        .collect();
1602
1603    for mut question in questions.list() {
1604        if !question.status.open() || question.node != crate::conduct::NODE {
1605            continue;
1606        }
1607        // Keep questions a task still names, including when the reference
1608        // moved to a dependent task.
1609        // Preserve even ambiguous references: retiring a possibly referenced
1610        // question is unsafe until the operator disambiguates it.
1611        if referenced
1612            .iter()
1613            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1614        {
1615            continue;
1616        }
1617        let Some(task) = by_id.get(question.run.as_str()) else {
1618            continue;
1619        };
1620        question.abandon(format!(
1621            "task {} no longer waits for this answer",
1622            task.short()
1623        ));
1624        if let Err(e) = questions.put(&mut question) {
1625            tracing::warn!(
1626                "could not retire question {} for task {}: {e:#}",
1627                question.short(),
1628                task.short()
1629            );
1630        }
1631    }
1632}
1633
1634/// What a finished run tells the queue about the task it came from.
1635///
1636/// A struct rather than a fourth and fifth boolean argument: the two flags
1637/// answer different questions about the same run, and a call site passing
1638/// `(…, true, false)` is one transposition away from refunding attempts
1639/// forever.
1640#[derive(Debug, Clone, Copy)]
1641pub struct Verdict {
1642    /// Where the graph stopped.
1643    pub status: RunStatus,
1644    /// The run opened a pull request.
1645    pub left_pr: bool,
1646    /// At least one seat was lost to a rate limit.
1647    pub quota_hit: bool,
1648    /// The run parked at a node boundary because it was asked to.
1649    pub parked: bool,
1650    /// The run never produced a single candidate a judge could look at.
1651    ///
1652    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1653    /// still have another candidate worth judging, in which case the loss was
1654    /// not the reason nothing came of the run. This is `true` only when the
1655    /// implement wave ended with nothing viable at all.
1656    pub no_viable_candidates: bool,
1657}
1658
1659/// Record a finished run against the task it came from.
1660///
1661/// Kept pure and separate from the loop because this mapping *is* the retry
1662/// policy, and a policy that can only be exercised by spawning a graph is a
1663/// policy nobody checks. The table:
1664///
1665/// | run status                           | task becomes        | attempt spent |
1666/// |---------------------------------------|---------------------|---------------|
1667/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1668/// | `Merged`, `Ready`                      | `Done`               | yes          |
1669/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1670/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1671/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1672/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1673/// | `Blocked` with a PR                    | `Held`               | yes          |
1674/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1675/// | `VerifiedNoop`                          | `Held`               | yes          |
1676/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1677///
1678/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1679/// deliberately: every candidate agreeing there is nothing to write is not a
1680/// machine fact about a rate limit, it is an unverified claim about the
1681/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1682/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1683/// claim could be wrong (a misread instruction, a stale check), and closing
1684/// the task automatically on an implementer's say-so would be the exact
1685/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1686/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1687/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1688/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1689/// claim regardless of whether the one already-spent attempt is refunded, and
1690/// [`Task::release`] resets the count to zero anyway the moment a human looks
1691/// at the evidence and lets it run again.
1692///
1693/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1694/// twice, together. A quorum lost to rate limits is a property of the machine
1695/// and not of the task, so the attempt is refunded and a reset quota picks
1696/// the work up where it stopped — and that is just as true when every
1697/// implement seat lost the same race and `after_implement` bails with nothing
1698/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1699/// machine fact. The `no_viable_candidates` guard is what keeps that row
1700/// narrow: a `Failed` run that produced a real candidate which then lost for
1701/// some other reason still spends the attempt, exactly like the quorum lost
1702/// to judges that answered with the wrong shape is ordinary flakiness, and
1703/// refunding *that* takes the bound off the retry loop entirely: run e633
1704/// stalled with `quota: []` after two judges wrote unusable JSON, was
1705/// refunded, and the next attempt paid for a fresh hour-long implement wave
1706/// before it could fail the same way. `max_attempts` exists precisely so
1707/// that cannot repeat forever.
1708///
1709/// A non-terminal status means `execute` returned while the graph was still
1710/// mid-flight, which is a bug rather than a verdict; it is treated as a
1711/// failure so that a task cannot loop on it either.
1712///
1713/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1714/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1715pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1716    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1717}
1718
1719/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1720fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1721    // A parked run is the operator's own doing, and its work is intact on
1722    // disk. The task goes back in line with its attempt refunded so the next
1723    // loop resumes the same run - which `one_task` prefers over competing
1724    // again - and so that swapping the binary a few times cannot exhaust a
1725    // budget meant for agents that actually misbehaved.
1726    if verdict.parked {
1727        task.park(detail);
1728        return;
1729    }
1730    match verdict.status {
1731        RunStatus::Merged | RunStatus::Ready
1732            if task.pr_recovery.as_ref().is_some_and(|s| {
1733                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1734            }) =>
1735        {
1736            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()));
1737        }
1738        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1739        RunStatus::AlreadyInBase => task.already_landed(detail),
1740        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1741        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1742            task.stall(detail)
1743        }
1744        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1745        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1746        RunStatus::Blocked => task.fail(detail, max_attempts),
1747        RunStatus::VerifiedNoop => task.handed_off(detail),
1748        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1749    }
1750}
1751
1752/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1753/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1754/// itself has actually finished *and* its own last attempt is provably why:
1755/// this loads that run and requires `Merged`/`Ready` before touching
1756/// anything earlier in `runs`, since `Task::succeed` can also be called
1757/// directly on a task whose last attempt never landed at all.
1758///
1759/// Called right after whatever call set `task.status` to
1760/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1761/// `reclaim`'s, but also every other place a task can be closed by hand
1762/// without the loop ever settling it itself: `magi task done`
1763/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1764/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1765/// GitHub merge, say, exactly the workflow this repository's own
1766/// "Landing a run's winner by hand" documents — is just as much "this task's
1767/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1768/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1769/// forever, which is the exact backlog this status exists to clear. `pub`
1770/// for those two out-of-module callers; everything else about this stays
1771/// internal bookkeeping.
1772///
1773/// A run something is still actually driving is left alone: a
1774/// task cannot be `Done` while one of its *own* attempts is still in flight,
1775/// so a live one at this point can only be an unrelated process — a manual
1776/// `--resume` of this old, now-moot run — and rewriting under it would just
1777/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1778/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1779/// pair `run_report`/`run_detail` use for the same question elsewhere:
1780/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1781/// --resume` invoked by hand outside it, which `liveness` also checks via
1782/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1783/// (already terminal in some other way, or itself mid-run) is left untouched
1784/// too.
1785///
1786/// Best-effort, like the rest of this module's bookkeeping: a load or save
1787/// failure here is a `tracing::warn`, not a failed settle, and the next time
1788/// this same task's completion is recorded — or a daemon restart replays
1789/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1790/// separate reconciliation pass; if that gap ever matters in practice, one
1791/// can be added then.
1792///
1793/// `home` is a parameter, not the process-global [`crate::run::home`], for
1794/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1795/// calls this with `ui.home`, which is `crate::run::home()` in a real
1796/// process but a fixture's own directory under test — falling through to
1797/// the global there would read and write through whichever home some other
1798/// test in the same binary happened to pin into that `OnceLock` first, not
1799/// the run this call actually means.
1800pub fn supersede_prior_runs(task: &Task, home: &Path) {
1801    let now = Timestamp::now();
1802    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1803    // right behind a `Merged`/`Ready` verdict) from one set directly by
1804    // `magi task done`/its web equivalent/the conductor on a task whose last
1805    // recorded attempt never actually landed - that requires reading the
1806    // run itself, which is exactly what this does before trusting anything
1807    // in `runs` is safe to relabel.
1808    let last_run_succeeded = task
1809        .runs
1810        .last()
1811        .and_then(|id| RunState::load_under(id, home).ok())
1812        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1813    for id in task.superseded_attempts(last_run_succeeded) {
1814        let mut state = match RunState::load_under(id, home) {
1815            Ok(s) => s,
1816            Err(e) => {
1817                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1818                continue;
1819            }
1820        };
1821        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1822            continue;
1823        }
1824        let daemon_claims = is_working_on(home, id, now);
1825        if state.liveness(daemon_claims) == Liveness::Live {
1826            continue;
1827        }
1828        state.status = RunStatus::Superseded;
1829        if let Err(e) = state.save_under(home) {
1830            tracing::warn!("could not mark run {id} superseded: {e:#}");
1831        }
1832    }
1833}
1834
1835/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1836/// finish the moment it was called, because one of its earlier attempts was
1837/// still live then - a `magi run --resume` invoked by hand on an old run,
1838/// most likely.
1839///
1840/// That skip is correct at the time (rewriting under a run something is
1841/// still actively saving would just be undone), but a task only ever
1842/// reaches `Done` once, so without this nothing would ever look at it
1843/// again: if that manual process later ends anywhere other than
1844/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1845/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1846/// backlog this status exists to clear. Called on the same idle-only
1847/// cadence as [`janitor`], next to it rather than folded into it: this
1848/// walks `queue` and `janitor` never otherwise needs one.
1849///
1850/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1851/// more than one attempt, every pass: each call is a handful of local file
1852/// reads bounded by that task's own attempt count, the same order of cost
1853/// [`clean::fold_due`] already pays scanning every run on disk on the same
1854/// cadence, and a task already fully resolved costs one failed liveness
1855/// check turned no-op the moment its lingering attempt is no longer live.
1856fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1857    for task in queue.list() {
1858        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1859            continue;
1860        }
1861        supersede_prior_runs(&task, home);
1862    }
1863}
1864
1865/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1866/// task ends up held.
1867///
1868/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1869/// dead daemon never got back to) share this, so the two cannot drift into
1870/// disagreeing about which held tasks get a diagnostic.
1871fn settle_and_diagnose(
1872    task: &mut Task,
1873    verdict: Verdict,
1874    detail: &str,
1875    max_attempts: usize,
1876    state: &RunState,
1877) {
1878    let p = phrases(&state.config.graph.language);
1879    // Shared by normal completion and crash recovery, under the task claim.
1880    // No new attempt can own the task until the old driver has exited.
1881    if let Some(d) = &state.merge_decision {
1882        use crate::merge_decision as md;
1883        if task.runs.last().is_some_and(|id| id != &state.id) {
1884            return;
1885        }
1886        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1887            task.succeed();
1888        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1889            if state.liveness(false) != Liveness::Dead {
1890                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1891                return;
1892            }
1893            let replacement = md::Replacement {
1894                question: d.question.clone(),
1895                run: state.id.clone(),
1896                pr: d.target.pr.clone(),
1897                agent: agent.to_owned(),
1898                context: format!(
1899                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1900                    d.target.pr,
1901                    state.id,
1902                    serde_json::to_string(&state.reviews).unwrap_or_default()
1903                ),
1904            };
1905            task.requeue();
1906            task.pr_recovery = None;
1907            task.review_of = None;
1908            task.replacement = Some(replacement);
1909        } else {
1910            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1911                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1912            } 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())) }));
1913        }
1914        task.mark_action_applied(&d.question);
1915        if let Some(pass) = state.passes.last() {
1916            task.record_pass(&state.id, pass.index, task.attempts, None);
1917        }
1918        return;
1919    }
1920    if let Some(replacement) = &task.replacement
1921        && !state.parked
1922        && state.resource_block.is_none()
1923        && (state.viable().is_empty()
1924            || (state.status == RunStatus::Blocked && state.tally.is_none()))
1925    {
1926        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)));
1927        return;
1928    }
1929    let attempts_before = task.attempts;
1930    // A run that stopped because a shared resource stayed busy was never a
1931    // failure of the task or of any agent: nothing was asked. The attempt is
1932    // refunded and the task is held by the machine, under a reason `triage`
1933    // can re-check, so the same run resumes with the same agents once the
1934    // resource is free. A park request still wins (it is the operator's).
1935    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1936        task.notice_cause(
1937            &format!("resource:{}:{}", block.kind, block.node),
1938            None,
1939            None,
1940        );
1941        task.last_error = Some(detail.to_owned());
1942        task.diagnostic = None;
1943        task.attempts = task.attempts.saturating_sub(1);
1944        if block.kind == "disk pressure" {
1945            task.hold_machine(Some(format!(
1946                "{}{}",
1947                crate::disk::RUNNING_PRESSURE,
1948                block.detail
1949            )));
1950        } else {
1951            task.hold_machine(Some(format!(
1952                "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1953             no agent was asked and no attempt was spent",
1954                crate::cache::RESOURCE_HOLD,
1955                block.kind,
1956                block.node
1957            )));
1958        }
1959        if let Some(pass) = state.passes.last() {
1960            task.record_pass(&state.id, pass.index, attempts_before, None);
1961        }
1962        return;
1963    }
1964    let unresolved = task.hold_notice_cause.clone();
1965    if !verdict.parked
1966        && task
1967            .pr_recovery
1968            .as_ref()
1969            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
1970        && matches!(
1971            verdict.status,
1972            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
1973        )
1974    {
1975        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
1976            task.succeed();
1977        } else {
1978            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()));
1979        }
1980    } else if !verdict.parked
1981        && task.pr_recovery.is_some()
1982        && matches!(
1983            verdict.status,
1984            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
1985        )
1986        && !verdict.quota_hit
1987    {
1988        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.")));
1989    } else {
1990        settle_in(task, verdict, detail, max_attempts, p);
1991    }
1992    if !verdict.parked
1993        && !verdict.quota_hit
1994        && matches!(
1995            verdict.status,
1996            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
1997        )
1998    {
1999        task.recovery_failed(state);
2000    }
2001    if state.prep_failure.is_some() {
2002        // Minting a run whose candidates could not be prepared is not work
2003        // on a newly approved attempt. Keep the unresolved outcome anchor.
2004        task.hold_notice_cause = unresolved;
2005        task.startup_notice_cause("startup-candidates");
2006    }
2007    // Written here, where the refund (or not) is decided, so the history is a
2008    // fact and not a later guess from the run's status.
2009    if let Some(pass) = state.passes.last() {
2010        let parked = match &pass.end {
2011            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2012            _ => None,
2013        };
2014        task.record_pass(&state.id, pass.index, attempts_before, parked);
2015    }
2016    if task.status == TaskStatus::Held {
2017        if state.prep_failure.is_none() {
2018            task.notice_cause(
2019                label(verdict.status),
2020                Some(&state.id),
2021                state.passes.last().map(|p| p.index),
2022            );
2023        }
2024        task.diagnostic = diagnostic(state);
2025        note_open_question(task, &state.id, p);
2026    }
2027}
2028
2029/// If `task` is held with a `magi ask` question still open on `run`, name the
2030/// question in [`Task::hold_reason`] rather than leaving the hold reading
2031/// only [`describe`]'s run summary.
2032///
2033/// This is the shape task 20260928-191407-05fd left underspecified: an
2034/// implementer settled a verified no-op and filed a question for the
2035/// operator, and the hold that followed said nothing about the question
2036/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2037/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2038/// marker) and must keep seeing it unchanged.
2039///
2040/// Best-effort: an unreadable question store must not stop a run from
2041/// settling, so this is a no-op rather than a propagated error when
2042/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2043fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2044    let Some(home) = crate::run::try_home() else {
2045        return;
2046    };
2047    let open = Questions::at(home.join("questions")).open_for(run);
2048    let Some(q) = open.first() else {
2049        return;
2050    };
2051    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2052    decisions.sort_unstable();
2053    task.notice_cause(
2054        &format!("questions:{}", decisions.join(",")),
2055        Some(run),
2056        None,
2057    );
2058    let base = task.hold_reason.clone().unwrap_or_default();
2059    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2060}
2061
2062/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2063/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2064/// by some other means entirely, like a manual `magi run` resume that
2065/// finishes the graph outside the queue's bookkeeping.
2066///
2067/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2068/// `settle` is separate from `attempt`: a task recovered this way must land
2069/// exactly where a live daemon would have put it — the same policy table,
2070/// not a second one that quietly drifts from it — and that is only checkable
2071/// without spawning a real run.
2072fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2073    match last_run {
2074        Some(state) => {
2075            let verdict = Verdict {
2076                status: state.status,
2077                left_pr: state.pr.is_some(),
2078                quota_hit: !state.quota.is_empty(),
2079                parked: state.parked,
2080                no_viable_candidates: state.viable().is_empty(),
2081            };
2082            let detail = format!(
2083                "{}{}",
2084                phrases(&state.config.graph.language).recovered_running,
2085                describe(&state)
2086            );
2087            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2088        }
2089        None => {
2090            // No run, so no config of its own: `language` is the task's
2091            // repository's setting, read by the caller.
2092            let why = phrases(language).no_run_to_recover;
2093            task.last_error = Some(why.to_owned());
2094            // The phone shows `hold_reason`, so a task held by the machine
2095            // says why there too and not only in `last_error`.
2096            task.notice_cause("missing-run", None, None);
2097            task.hold_machine(Some(why.to_owned()));
2098        }
2099    }
2100}
2101
2102/// Find every task left at `running` that no live process is actually
2103/// driving, and settle each one against whatever its last run became.
2104///
2105/// # Why a claim is proof, not a guess
2106///
2107/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2108/// `running`, and the guard is held for the task's whole time in that status:
2109/// `attempt` does not return, and the loop does not move past the scope
2110/// holding the claim, until the run has settled. So a `running` task whose
2111/// lock is gone cannot have a live owner — this process or any other —
2112/// without needing a staleness threshold or a pid check the way
2113/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2114/// task that never got as far as `running` at all. Taking the claim here is
2115/// the whole test: it either fails, because something really does hold it
2116/// and the task is left alone, or it succeeds, which is the proof — and it is
2117/// kept for the rest of the decision so nothing else can start a competing
2118/// run while this one is being written.
2119///
2120/// Called on every poll, not only at startup, for the reason
2121/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2122/// keep noticing this, not only on the one morning it happened to restart.
2123fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
2124    let mut reclaimed = Vec::new();
2125    for listed in queue.list() {
2126        if listed.status != TaskStatus::Running {
2127            continue;
2128        }
2129        let Ok(_claim) = queue.claim(&listed.id) else {
2130            continue;
2131        };
2132        // Re-read under the claim: a release or an edit landed by a human
2133        // between the listing above and the claim just taken must not be
2134        // clobbered by a decision based on the stale copy.
2135        let Ok(mut task) = queue.get(&listed.id) else {
2136            continue;
2137        };
2138        if task.status != TaskStatus::Running {
2139            continue;
2140        }
2141        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2142        // `execute` normally abandons a run's own open questions the moment
2143        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2144        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2145        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2146        // with the question still `open`, because the process died before
2147        // reaching that call. `reclaim` itself stays pure on purpose (see its
2148        // own doc), so the same cleanup runs here instead, against the run
2149        // this reclaim is already reading. `settle_run` costs nothing when
2150        // `execute` already got there first.
2151        if let Some(state) = &last_run
2152            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2153        {
2154            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2155        }
2156        let language = if last_run.is_none() {
2157            language_of(&task, Path::new("."))
2158        } else {
2159            String::new()
2160        };
2161        reclaim(&mut task, last_run, max_attempts, &language);
2162        if task.status == TaskStatus::Done {
2163            supersede_prior_runs(&task, &crate::run::home());
2164        }
2165        record(queue, &mut task);
2166        reclaimed.push(task.id.clone());
2167    }
2168    reclaimed
2169}
2170
2171/// Find every run whose `run.json` is provably dead — every seat it still
2172/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2173/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2174/// not merely "no daemon claims it" — and fail it, clearing the leftover
2175/// active seats so the run stops reading as `implementing` (or whichever
2176/// node) forever.
2177///
2178/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2179/// `running`, using whatever `run.json` already says — but nothing in that
2180/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2181/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2182/// never got back to sits exactly where it was left: `active` full of seats
2183/// nobody will ever answer for, `status` stuck on whatever node was in
2184/// flight. `magi show` already tells an operator this in prose (`no live
2185/// daemon claims this run right now`); this is what makes that fact durable
2186/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2187/// stay stuck once nothing is driving it.
2188///
2189/// Runs on every poll, not only at startup, for the reason
2190/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2191/// daemon up for days must keep noticing a run some other, now-dead, daemon
2192/// left behind just as readily as one it trips over on the way up.
2193///
2194/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2195/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2196/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2197/// `runs` directory instead: `home` here is a parameter precisely so a test
2198/// can point it away from the operator's real history (see [`drive`]'s own
2199/// doc), and a scan that fell through to the global home anyway would walk
2200/// whichever directory some *other* process or test pinned into that
2201/// `OnceLock` first — mutating runs this call was never handed.
2202fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2203    reclaim_abandoned_runs_with(
2204        home,
2205        now,
2206        crate::proc::pid_status,
2207        crate::proc::process_started_at,
2208    )
2209}
2210
2211/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2212/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2213/// for the identical reason: this sweep's real damage (wiping a run's active
2214/// seats and failing it) has to be provable against an injected answer in a
2215/// test, not just the real process table.
2216fn reclaim_abandoned_runs_with<F, G>(
2217    home: &Path,
2218    now: Timestamp,
2219    query: F,
2220    identity: G,
2221) -> Vec<String>
2222where
2223    F: Fn(u32) -> Option<bool>,
2224    G: Fn(u32) -> Option<String>,
2225{
2226    let mut abandoned = Vec::new();
2227    for entry in std::fs::read_dir(home.join("runs"))
2228        .into_iter()
2229        .flatten()
2230        .flatten()
2231    {
2232        let id = entry.file_name().to_string_lossy().into_owned();
2233        if !crate::run::is_run_id(&id) {
2234            continue;
2235        }
2236        // Serialize the proof and save with claims and takeover: a new
2237        // execution must not be overwritten after the liveness observation.
2238        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2239            continue;
2240        };
2241        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2242        // that module's docs for why a run this cannot parse is left alone
2243        // rather than guessed at. A different schema number is not that: this
2244        // touches only `status` and `active`, never a field whose meaning a
2245        // schema bump changed, so an old record's values serve this exactly
2246        // as well as a current one's (see `clean::read_state`'s own doc for
2247        // the same reasoning applied to folding).
2248        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2249            continue;
2250        };
2251        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2252            continue;
2253        };
2254        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2255            continue;
2256        }
2257        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2258        // it", which is also the normal, healthy shape of a manual `magi
2259        // run` / `magi review` sharing this same home — this scan walks
2260        // every run on disk, not only ones this daemon itself started. Such
2261        // a run's active seats can legitimately sit past their own timeout
2262        // for a little while (the CLI finishing up, its result still being
2263        // collected) without the process driving it having died. `liveness`
2264        // is what actually tells the two apart, by corroborating
2265        // `driver_pid` against the process it names — see its own doc. Only
2266        // its strongest, provable answer licenses wiping this run's active
2267        // seats and failing it out from under whatever is still running it.
2268        let daemon_claims = is_working_on(home, &id, now);
2269        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2270            != crate::run::Liveness::Dead
2271        {
2272            continue;
2273        }
2274        state.abandon("daemon");
2275        if let Err(e) = state.save_under(home) {
2276            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2277            continue;
2278        }
2279        // This run never passes through `Runner::execute` again, so its end
2280        // is announced here.
2281        if let Some(notice) = notices::run_ended(&state) {
2282            notices::raise_in(home, notice);
2283        }
2284        // The seat that asked is gone for good now, exactly like any other
2285        // door `graph::Runner::settle_questions` closes the moment `status`
2286        // lands somewhere non-resumable - see that method's own doc. Nothing
2287        // else reaches this one before the next `janitor()` startup pass
2288        // (`clean::abandon_settled_questions`), and a daemon that stays up
2289        // for days must not leave an open question badging the operator
2290        // until it happens to restart.
2291        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2292            tracing::warn!("abandon questions for {id}: {e:#}");
2293        }
2294        abandoned.push(id);
2295    }
2296    abandoned
2297}
2298
2299/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2300///
2301/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2302/// sets, so there is one loop body rather than two that drift apart the first
2303/// time the retry policy changes on only one of them.
2304pub async fn serve(opts: Opts) -> Result<()> {
2305    serve_until(opts, Stop::new()).await
2306}
2307
2308/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2309///
2310/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
2311/// mid-node leaves worktrees, branches and agent sessions behind, and every
2312/// agent call already paid for is lost; finishing the run costs the operator a
2313/// wait and saves them a cleanup. A stop therefore only sets a flag: the
2314/// current `execute` runs to its terminal status, the task's outcome is
2315/// recorded, and only then does the loop return. That window is what
2316/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
2317/// still has a second Ctrl-C, which the runtime turns into a process kill —
2318/// and the task left `Running` then tells the next daemon, and the next human,
2319/// where to look.
2320///
2321/// While the queue is empty the stop is honoured within one wakeup rather than
2322/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2323/// caller that taps stop does not sit through the remainder of a sleep.
2324pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2325    let signal = {
2326        let stop = stop.clone();
2327        tokio::spawn(async move {
2328            if tokio::signal::ctrl_c().await.is_ok() {
2329                stop.stop();
2330                tracing::info!("shutdown requested; a run in flight will be finished first");
2331            }
2332        })
2333    };
2334
2335    let worktrees_root = opts
2336        .worktrees_root
2337        .clone()
2338        .unwrap_or_else(crate::run::default_worktree_root);
2339    let outcome = drive(
2340        &opts,
2341        &Queue::open(),
2342        &status_path(),
2343        &crate::run::home(),
2344        &worktrees_root,
2345        &stop,
2346    )
2347    .await;
2348
2349    signal.abort();
2350    outcome
2351}
2352
2353/// The loop proper: setup, poll, teardown, with the queue and the status file
2354/// supplied rather than discovered.
2355///
2356/// All three of `home`, `worktrees_root` and the queue/status paths are
2357/// parameters rather than resolved here, for the same reason:
2358/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2359/// so a unit test that pinned it would fight every other test in the binary,
2360/// and a loop that resolved its own worktree bay could only be exercised
2361/// against the operator's real `~/wt/<repo>` - publishing over a live
2362/// daemon's status file, claiming tasks out of a live backlog, and, since
2363/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2364/// whatever the operator actually has on disk.
2365async fn drive(
2366    opts: &Opts,
2367    queue: &Queue,
2368    status_file: &Path,
2369    home: &Path,
2370    worktrees_root: &Path,
2371    stop: &Stop,
2372) -> Result<()> {
2373    // The status file is a *snapshot*, not a stream of events: a reader only
2374    // ever wants the latest values, and every tick rewrites the whole file
2375    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2376    // while an mpsc channel would force the loop to re-send unchanged fields on
2377    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2378    // for no gain. The lock is only ever held across a field assignment, never
2379    // across an await.
2380    let recovery_cfg = prepare(&opts.repo, opts).ok();
2381    let daemon_cfg = recovery_cfg
2382        .as_ref()
2383        .map(|c| c.daemon.clone())
2384        .unwrap_or_default();
2385    let reconciled = crate::driver::reconcile(home);
2386    if !reconciled.is_empty() {
2387        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2388    }
2389    let mut initial_status = Status::new();
2390    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2391        recovery_cfg.as_ref(),
2392        daemon_cfg.max_deputies,
2393    ));
2394    let status = Arc::new(Mutex::new(initial_status));
2395    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2396    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2397
2398    // Read once at startup, not per task: how many runs this loop drives at
2399    // once is a property of the machine running it, not of whichever
2400    // repository a given task happens to name - see
2401    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2402    // fact in the same sense the agent roster is.
2403    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2404
2405    // Something has to be waiting on every question for as long as it is open,
2406    // whether or not the agent's own `magi ask` survived. Its own task rather
2407    // than a step of the poll loop: the poll loop is busy for the whole of a
2408    // run, and an owner's reply must not queue behind one.
2409    let waiter = tokio::spawn(crate::waiter::run(
2410        crate::waiter::Waiter::new(
2411            crate::ask::Questions::at(home.join("questions")),
2412            home.to_path_buf(),
2413            recovery_cfg.clone(),
2414        ),
2415        stop.clone(),
2416    ));
2417
2418    // The follow-up seats for the conductor's questions: the conductor files a
2419    // question and moves on, and each open one gets a deputy that reads the
2420    // owner's reply. Its own task for the same reason the waiter's is.
2421    let deputies = tokio::spawn(crate::deputy::run(
2422        crate::deputy::Deputies::new(
2423            crate::ask::Questions::at(home.join("questions")),
2424            home.to_path_buf(),
2425            recovery_cfg.clone(),
2426            opts.repo.clone(),
2427            daemon_cfg.max_deputies,
2428            {
2429                let stop = stop.clone();
2430                Arc::new(move || stop.parking())
2431            },
2432        ),
2433        stop.clone(),
2434    ));
2435
2436    // Keeps every checkout's origin/main fresh; its own task so a slow remote
2437    // never holds up the poll loop.
2438    let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
2439
2440    // Watches the release-bump pull requests until they land; its own task, not
2441    // tied to any run, because a pending bump outlives the run that opened it.
2442    let release_watch = tokio::spawn(crate::release_watch::run(
2443        crate::release_watch::Watcher::new(
2444            Box::new(crate::release_watch::GhForge),
2445            home.to_path_buf(),
2446        ),
2447        {
2448            let (repo, opts) = (opts.repo.clone(), opts.clone());
2449            move || release_watch_settings(&repo, &opts)
2450        },
2451        stop.clone(),
2452    ));
2453
2454    tracing::info!(
2455        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2456        queue.root().display(),
2457        opts.poll.as_secs(),
2458        opts.max_attempts,
2459        concurrency,
2460        if daemon_cfg.pause_for_interrupts {
2461            ", interrupts enabled"
2462        } else {
2463            ""
2464        }
2465    );
2466
2467    // `--once` drains an already-idle queue without reaching the idle wait,
2468    // but must still perform the startup cleanup.
2469    janitor(&opts.repo, opts, home, worktrees_root).await;
2470    resweep_superseded_attempts(queue, home);
2471
2472    let outcome = poll(
2473        opts,
2474        queue,
2475        &status,
2476        home,
2477        worktrees_root,
2478        stop,
2479        DispatchLimits {
2480            max_concurrent: concurrency,
2481            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2482        },
2483    )
2484    .await;
2485
2486    beat.abort();
2487    waiter.abort();
2488    deputies.abort();
2489    fetcher.abort();
2490    release_watch.abort();
2491    clear_status_at(status_file);
2492    outcome
2493}
2494
2495/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2496/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2497fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2498    let Ok(cfg) = prepare(repo, opts) else {
2499        return (Vec::new(), 0);
2500    };
2501    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2502        .into_iter()
2503        .map(|r| r.path)
2504        .collect();
2505    // Repositories the daemon has worked in, wherever they live: a task may
2506    // name one outside `[repos] roots`, and its release PR must be watched too.
2507    let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2508    let runs = crate::run::home().join("runs");
2509    for id in crate::run::list_ids_in(&runs) {
2510        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2511            .ok()
2512            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2513            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2514        known.extend(repo);
2515    }
2516    for k in known {
2517        let k = k.canonicalize().unwrap_or(k);
2518        if k.join(".git").exists() && !paths.contains(&k) {
2519            paths.push(k);
2520        }
2521    }
2522    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2523    if !paths.contains(&own) {
2524        paths.push(own);
2525    }
2526    (paths, cfg.daemon.release_stall_minutes)
2527}
2528
2529/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2530const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2531
2532/// Run [`crate::clean::fetch_origins`] every `[repos] fetch_interval` seconds
2533/// until `stop`. The config is re-read each lap; `0` (or an unreadable config)
2534/// disables the fetch for that lap. Never fails.
2535async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2536    while !stop.stopped() {
2537        let (interval, roots) = match prepare(&repo, &opts) {
2538            Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2539            Err(_) => (0, Vec::new()),
2540        };
2541        if interval > 0 && !roots.is_empty() {
2542            let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2543            tracing::debug!("fetch origins: {r:?}");
2544        }
2545        // Sleep in slices so a stop or a config change is noticed promptly.
2546        let wait = if interval > 0 { interval } else { 60 };
2547        let mut slept = 0;
2548        while slept < wait && !stop.stopped() {
2549            tokio::time::sleep(Duration::from_secs(1)).await;
2550            slept += 1;
2551        }
2552    }
2553}
2554
2555/// Refresh the status file on a fixed tick.
2556///
2557/// Separate from the loop because a run takes tens of minutes: a status file
2558/// written only between tasks would look stale for the whole of every run, and
2559/// a reader would report the daemon dead exactly while it was busiest.
2560async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2561    loop {
2562        tokio::time::sleep(HEARTBEAT).await;
2563        let snapshot = {
2564            let mut guard = lock(&status);
2565            guard.updated_at = Timestamp::now();
2566            guard.clone()
2567        };
2568        if let Err(e) = write_status_to(&path, &snapshot) {
2569            // A failed heartbeat must not take the daemon down: the loop is the
2570            // product, the status file is only the window onto it.
2571            tracing::warn!("could not refresh the daemon status file: {e:#}");
2572        }
2573    }
2574}
2575
2576/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2577/// if so, whether that wait is over.
2578#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2579enum LandResume {
2580    /// The task's last run is not parked on a land approval; schedule it
2581    /// like any other candidate.
2582    NotLanding,
2583    /// Parked in `land`, waiting on a question nobody has answered yet.
2584    /// Left alone: attempting it now would only re-observe the same pull
2585    /// request and park again, spending a `gh` call on a decision that has
2586    /// not changed since the last time this was checked.
2587    StillWaiting,
2588    /// Parked in `land`, and the question is settled - answered or
2589    /// abandoned. Resuming this is the one kind of candidate that must not
2590    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2591    Ready,
2592}
2593
2594/// Classify a runnable candidate by whether it is parked on a land-merge
2595/// approval. Read-only - no claim taken, nothing written - so it is cheap
2596/// enough to call on every candidate, every poll.
2597fn land_resume_state(task: &Task) -> LandResume {
2598    let Some(run_id) = task.runs.last() else {
2599        return LandResume::NotLanding;
2600    };
2601    let Ok(state) = RunState::load(run_id) else {
2602        return LandResume::NotLanding;
2603    };
2604    if !state.parked {
2605        return LandResume::NotLanding;
2606    }
2607    if state.status == RunStatus::Landing
2608        && state.land_approval.as_ref().is_some_and(|binding| {
2609            ask::Questions::open()
2610                .get(&binding.question)
2611                .is_ok_and(|q| {
2612                    q.run == state.id
2613                        && q.resolution()
2614                            .as_deref()
2615                            .is_some_and(crate::merge_decision::stops)
2616                })
2617        })
2618    {
2619        return LandResume::Ready;
2620    }
2621    if !implementers_match(task, &state) {
2622        return LandResume::NotLanding;
2623    }
2624    // Parked in `land` on the merge approval, or at `merge` on the owner's
2625    // word about a title/body the posting gate withheld. Told apart by the
2626    // run's own record, not by a status both can share.
2627    let node = if state.status == RunStatus::Landing {
2628        land::APPROVAL_NODE
2629    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2630        crate::github_text::ASK_NODE
2631    } else {
2632        return LandResume::NotLanding;
2633    };
2634    let store = ask::Questions::open();
2635    let waiting = store
2636        .list()
2637        .into_iter()
2638        .filter(|q| &q.run == run_id && q.node == node)
2639        .max_by(|a, b| a.id.cmp(&b.id));
2640    let Some(mut q) = waiting else {
2641        return LandResume::Ready;
2642    };
2643    if !q.status.open() {
2644        // Repair spends agent resources and must obey concurrency and quota
2645        // waits; only a merge/hold decision may use the decision-only lane.
2646        if q.resolution().as_deref() == Some(land::REPAIR) {
2647            return if state.liveness(false) == Liveness::Live {
2648                LandResume::StillWaiting
2649            } else {
2650                LandResume::NotLanding
2651            };
2652        }
2653        return LandResume::Ready;
2654    }
2655    // `ask::ask_and_wait`'s own deadline is what used to retire a question
2656    // nobody ever answered; land's approval bypasses that wait entirely (see
2657    // `land::approval_gate`), so the same deadline has to be enforced here
2658    // instead, or `graph.answer_timeout` silently stops meaning anything for
2659    // a land approval and a run can sit `StillWaiting` forever with nobody
2660    // told to look at it.
2661    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2662    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2663    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2664        q.abandon(format!(
2665            "no answer within {}s of asking",
2666            timeout.as_secs().max(1)
2667        ));
2668        // If this can't be persisted, do not treat the wait as settled on a
2669        // guess: fall through and try again next poll.
2670        if store.put(&mut q).is_ok() {
2671            return LandResume::Ready;
2672        }
2673    }
2674    LandResume::StillWaiting
2675}
2676
2677/// How often the loop rechecks for new work while something it already
2678/// started is still running, rather than sleeping out the whole
2679/// [`Opts::poll`] interval.
2680///
2681/// Short on purpose: this is what lets a land-merge approval that comes back
2682/// while another task is mid-competition be noticed and resumed within a
2683/// fraction of a second, not within the next multi-second poll.
2684const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2685
2686/// How often [`poll`] rechecks the shared build cache against its cap at a
2687/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
2688/// waiting for the queue to run dry.
2689///
2690/// A queue that never empties means the `janitor` call at the bottom of this
2691/// loop's fully-idle branch can go unreached for as long as the backlog
2692/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
2693/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
2694/// 81.8 GiB an idle-only check let it reach before this existed, and it is
2695/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
2696/// backlog of short tasks does not pay for that walk on every poll.
2697const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2698
2699/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
2700/// in `Status::current` - on drop, so both are released even if the attempt
2701/// panics rather than returning.
2702///
2703/// A `Drop` impl rather than statements written after the `.await` it
2704/// guards: a panic unwinds straight past code placed "after" a call, and
2705/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
2706/// that ruling a panic out there is not a bet this loop can make. Without
2707/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
2708/// forever - the idle branch in [`poll`], and with it the janitor, would
2709/// never run again - and a ghost entry in `Status::current` naming a task
2710/// nothing is still working on.
2711struct InFlightGuard<'a> {
2712    status: &'a Arc<Mutex<Status>>,
2713    stop: &'a Stop,
2714    task_id: &'a str,
2715}
2716
2717impl Drop for InFlightGuard<'_> {
2718    fn drop(&mut self) {
2719        lock(self.status).current.retain(|c| c.task != self.task_id);
2720        self.stop.exit();
2721    }
2722}
2723
2724/// State of [`poll`]'s own interrupt-scheduling sequence - see
2725/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
2726/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
2727/// both kept free of `Task`'s non-identity fields on purpose: every decision
2728/// here turns only on task ids and which ones are in flight, so the "never
2729/// more than one run at once" and "exactly one resume" invariants can be
2730/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
2731/// queue - which is exactly the coverage this feature's first two attempts
2732/// were missing.
2733///
2734/// Deliberately in-memory only, not written to disk anywhere: a daemon
2735/// restart mid-sequence loses track of which run it had asked to park and
2736/// which task was meant to run first, and simply falls back to `Idle` -
2737/// see [`drive`]'s own setup. The parked run itself is not lost - it is
2738/// sitting in the queue exactly like any other resumable, interrupted task,
2739/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
2740/// just resumes on the ordinary priority order rather than guaranteed to go
2741/// first. Giving that guarantee a crash-proof memory would mean a new queue
2742/// field and a recovery ordering to go with it, which is exactly the
2743/// complexity this feature's constraints rule out for the one property that
2744/// actually matters: at most one run, ever, at once.
2745#[derive(Debug, Clone, PartialEq, Eq)]
2746enum Interrupt {
2747    /// No interrupt sequence in progress. Ordinary dispatch applies.
2748    Idle,
2749    /// `interrupt_task` is runnable and exactly one other run is in flight;
2750    /// `parked` names that one task's id. Dispatch is withheld from
2751    /// everyone, including `interrupt_task` itself, until it has left
2752    /// flight - only then is `interrupt_task` let through.
2753    ///
2754    /// `parked` is a `Vec` rather than a bare id for symmetry with
2755    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
2756    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
2757    /// when exactly one run is in flight, so it is guaranteed to hold
2758    /// exactly one entry in practice - see that branch's own doc for why
2759    /// more than one is deliberately never attempted.
2760    Parking {
2761        parked: Vec<String>,
2762        interrupt_task: String,
2763    },
2764    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
2765    /// withheld from everyone until it leaves flight - merged, failed, held,
2766    /// it makes no difference - at which point the sequence moves to
2767    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
2768    /// going straight to `Idle` would hand `parked` back to ordinary
2769    /// priority-order dispatch, where a higher-priority task filed in the
2770    /// meantime could start ahead of it.
2771    Running {
2772        parked: Vec<String>,
2773        interrupt_task: String,
2774    },
2775    /// `interrupt_task` left flight; `parked` still names the one run this
2776    /// sequence owes a resume. Dispatch is withheld from everyone except
2777    /// that task - see [`interrupt_gate`] - so the resume this feature
2778    /// promises is never raced by, or run alongside, an unrelated candidate.
2779    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
2780    /// own doc on abandonment - the moment it is no longer runnable at all.
2781    Resuming { parked: Vec<String> },
2782}
2783
2784/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
2785/// and `runnable` are read-only snapshots of this tick's reality, and the
2786/// only side effect the caller still owes the world is asking whichever
2787/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
2788/// site.
2789///
2790/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
2791/// accepted rather than a narrower type because that is what [`poll`] already
2792/// has on hand from [`runnable`], and building a second, smaller list on
2793/// every tick just to satisfy this signature would cost more than it proves.
2794///
2795/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
2796/// back to a task they are waiting on no longer being [`runnable`] - held,
2797/// blocked, deleted, or finished by some other means entirely, all of which
2798/// an operator can do to a task sitting in the queue with no claim on it at
2799/// all, at any moment, interrupt sequence or not. Without this check the
2800/// sequence would wait forever for a dispatch that can never come, and
2801/// `interrupt_gate` would withhold every other task in the queue right along
2802/// with it - a single `magi task hold` on the wrong id turning into a
2803/// daemon that never dispatches anything again.
2804fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2805    match state {
2806        Interrupt::Idle => {
2807            // Not just "something to interrupt": exactly one thing. More
2808            // than one run in flight only happens above the default
2809            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
2810            // one resume, never run alongside anything else" only because
2811            // it is only ever seeded with exactly one id - see
2812            // `Interrupt::Resuming`'s own doc on why releasing more than one
2813            // parked id back to ordinary dispatch cannot be made safe
2814            // against that same setting's own extra concurrency slots.
2815            // Waiting here for the herd to settle to one is the
2816            // simplification this feature's own constraints ask for rather
2817            // than a second concurrency model to reconcile with the first.
2818            if in_flight.len() != 1 {
2819                return Interrupt::Idle;
2820            }
2821            match runnable.iter().find(|t| t.interrupt) {
2822                Some(t) => Interrupt::Parking {
2823                    parked: in_flight.to_vec(),
2824                    interrupt_task: t.id.clone(),
2825                },
2826                None => Interrupt::Idle,
2827            }
2828        }
2829        Interrupt::Parking {
2830            parked,
2831            interrupt_task,
2832        } => {
2833            if in_flight.iter().any(|id| parked.contains(id)) {
2834                // Still waiting for what was in flight to actually stop.
2835                Interrupt::Parking {
2836                    parked,
2837                    interrupt_task,
2838                }
2839            } else if in_flight.contains(&interrupt_task) {
2840                Interrupt::Running {
2841                    parked,
2842                    interrupt_task,
2843                }
2844            } else if runnable.iter().any(|t| t.id == interrupt_task) {
2845                // The parked run(s) are gone, but the interrupt task has not
2846                // been dispatched yet on this tick - `interrupt_gate` is
2847                // what lets it through next.
2848                Interrupt::Parking {
2849                    parked,
2850                    interrupt_task,
2851                }
2852            } else {
2853                // The interrupt task itself is no longer runnable - see this
2854                // function's own doc on abandonment. The parked run(s) still
2855                // get their guaranteed resume; there is simply no interrupt
2856                // to run ahead of them any longer.
2857                Interrupt::Resuming { parked }
2858            }
2859        }
2860        Interrupt::Running {
2861            parked,
2862            interrupt_task,
2863        } => {
2864            if in_flight.contains(&interrupt_task) {
2865                Interrupt::Running {
2866                    parked,
2867                    interrupt_task,
2868                }
2869            } else {
2870                // The interrupt task's own run reached a terminal status,
2871                // whichever one - this is the *only* trigger that moves the
2872                // sequence on, driven straight off the same in-flight
2873                // bookkeeping `poll` already reaps every tick, not a second,
2874                // independent poll of anything.
2875                Interrupt::Resuming { parked }
2876            }
2877        }
2878        Interrupt::Resuming { parked } => {
2879            if in_flight.iter().any(|id| parked.contains(id)) {
2880                // One of the parked runs has been dispatched - the resume
2881                // this sequence owed is fulfilled. Whatever else is left in
2882                // `parked` (ordinarily nothing, at the default concurrency
2883                // of one) rejoins ordinary priority-order dispatch, same as
2884                // any other runnable task.
2885                Interrupt::Idle
2886            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2887                Interrupt::Resuming { parked }
2888            } else {
2889                // Abandonment (see this function's own doc): nothing left in
2890                // `parked` is even runnable any longer.
2891                Interrupt::Idle
2892            }
2893        }
2894    }
2895}
2896
2897/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
2898/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
2899/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
2900/// indistinguishable from any other runnable task - exactly the "off does
2901/// nothing" this feature promises.
2902fn advance_interrupt_tick(
2903    enabled: bool,
2904    state: Interrupt,
2905    in_flight: &[String],
2906    runnable: &[Task],
2907) -> Interrupt {
2908    if !enabled {
2909        return Interrupt::Idle;
2910    }
2911    advance_interrupt(state, in_flight, runnable)
2912}
2913
2914/// Which of this tick's runnable candidates the interrupt sequence actually
2915/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
2916/// each half is assertable on its own: this is the half that keeps a
2917/// competition and an interrupt from ever running at the same moment.
2918fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2919    match state {
2920        Interrupt::Idle => candidates,
2921        Interrupt::Parking {
2922            parked,
2923            interrupt_task,
2924        } => {
2925            if in_flight.iter().any(|id| parked.contains(id)) {
2926                Vec::new()
2927            } else {
2928                candidates
2929                    .into_iter()
2930                    .filter(|t| &t.id == interrupt_task)
2931                    .collect()
2932            }
2933        }
2934        Interrupt::Running { .. } => Vec::new(),
2935        // At most one: even if `parked` names more than one id (more than
2936        // one run was in flight when the sequence began, only possible
2937        // above the default `max_concurrent_runs = 1`), only the first match
2938        // is offered. Capping this to a single candidate - not merely to
2939        // `parked`'s own ids - is what makes "exactly one resume, never two
2940        // dispatched together" true regardless of how many ordinary slots
2941        // happen to be free this tick.
2942        Interrupt::Resuming { parked } => candidates
2943            .into_iter()
2944            .find(|t| parked.contains(&t.id))
2945            .into_iter()
2946            .collect(),
2947    }
2948}
2949
2950/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
2951/// bundled into one parameter so `poll`'s own signature stays readable -
2952/// see [`drive`]'s call site for where these are actually read.
2953struct DispatchLimits {
2954    /// How many *ordinary* candidates run at once. See
2955    /// [`crate::config::Daemon::max_concurrent_runs`].
2956    max_concurrent: usize,
2957    /// See [`crate::config::Daemon::pause_for_interrupts`].
2958    pause_for_interrupts: bool,
2959}
2960
2961/// Which semaphore, if any, dispatching a candidate should draw its permit
2962/// from.
2963///
2964/// Pure and separate from [`poll`]'s loop body for the same reason
2965/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
2966/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
2967/// exactly the policy this feature adds, and a policy only exercisable by
2968/// running the whole loop is a policy nobody checks.
2969#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2970enum PermitKind {
2971    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
2972    /// Checked first - a task can be both a land resume and marked
2973    /// [`Task::urgent`], and the resume's own "must not queue behind
2974    /// anything" guarantee takes precedence.
2975    None,
2976    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
2977    /// (never in addition to trying) the ordinary pool. This is what lets
2978    /// an urgent task dispatch while every ordinary slot is already checked
2979    /// out, and what stops a second urgent task from opening a third run: it
2980    /// waits on this same one-slot semaphore rather than falling through to
2981    /// the ordinary one.
2982    Urgent,
2983    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
2984    /// above.
2985    Ordinary,
2986}
2987
2988/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
2989/// own boolean, already computed by the caller from [`land_resume_state`].
2990fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2991    if priority {
2992        PermitKind::None
2993    } else if urgent {
2994        PermitKind::Urgent
2995    } else {
2996        PermitKind::Ordinary
2997    }
2998}
2999
3000struct DispatchClaim {
3001    task: Task,
3002    claim: crate::queue::Claim,
3003    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3004}
3005
3006/// Claim and re-read before choosing a lane: a queue listing may predate an
3007/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3008fn claim_dispatch(
3009    queue: &Queue,
3010    candidate: &Task,
3011    cooling_down: bool,
3012    ordinary: &Arc<tokio::sync::Semaphore>,
3013    urgent: &Arc<tokio::sync::Semaphore>,
3014) -> Option<DispatchClaim> {
3015    let Ok(claim) = queue.claim(&candidate.id) else {
3016        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3017        return None;
3018    };
3019    let task = match queue.get(&candidate.id) {
3020        Ok(t) if t.status.runnable() => t,
3021        Ok(_) => return None,
3022        Err(e) => {
3023            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3024            return None;
3025        }
3026    };
3027    let resume = land_resume_state(&task);
3028    if resume == LandResume::StillWaiting {
3029        return None;
3030    }
3031    let priority = resume == LandResume::Ready;
3032    if !priority && cooling_down {
3033        return None;
3034    }
3035    // Never borrow an ordinary slot when the single urgent slot is busy.
3036    // Keep scanning other candidates when either pool has no free slot.
3037    let permit = match permit_kind(priority, task.urgent) {
3038        PermitKind::None => None,
3039        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3040        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3041    };
3042    Some(DispatchClaim {
3043        task,
3044        claim,
3045        permit,
3046    })
3047}
3048
3049/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3050/// teardown and cannot skip the teardown on an early return.
3051///
3052/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3053/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3054/// land approval that has since been answered is dispatched outside that
3055/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3056/// the whole point of parking there is that it must not queue behind
3057/// whatever else the loop happens to be running, even at the default of one.
3058/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3059/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3060/// these exemptions is still subject to the interrupt gate below, urgent
3061/// included: a land-resume or urgent candidate is exactly as much "something
3062/// else running" as an ordinary one from the interrupt sequence's point of
3063/// view, and letting either slip through while a run is being parked, or
3064/// while the interrupt task itself has the floor, is precisely the second
3065/// run 75dd's own "at most one run, ever, at once" guarantee must never
3066/// allow - see [`Interrupt`]'s own doc.
3067async fn poll(
3068    opts: &Opts,
3069    queue: &Queue,
3070    status: &Arc<Mutex<Status>>,
3071    home: &Path,
3072    worktrees_root: &Path,
3073    stop: &Stop,
3074    limits: DispatchLimits,
3075) -> Result<()> {
3076    let DispatchLimits {
3077        max_concurrent,
3078        pause_for_interrupts,
3079    } = limits;
3080    // Only consulted by `once`, where a task that just failed is still
3081    // `runnable` and would otherwise be picked up again inside the same drain.
3082    // In the long-running mode a later poll retrying a failed task is the point,
3083    // and the attempt counter is what bounds it.
3084    let mut attempted: Vec<String> = Vec::new();
3085    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
3086    // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
3087    // entirely separate from `sem`: an urgent candidate must dispatch
3088    // alongside whatever `sem` already has checked out, never by waiting for
3089    // one of those ordinary slots to free up and never by growing
3090    // `max_concurrent_runs` itself. Sized at one, not unbounded - see
3091    // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
3092    // first on this same slot rather than opening a third run.
3093    let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
3094    // A quota hit is a fact about the machine, not the task that happened to
3095    // surface it, and every other *ordinary* candidate is no less likely to
3096    // hit the same wall - see the warning below. A land-merge resume is
3097    // exempt: it is a human decision finishing, not a fresh competition, and
3098    // must not sit out a quota cooldown it did not cause.
3099    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
3100    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
3101    let mut conductor = Conductor::new();
3102    // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
3103    // a congested queue would otherwise starve of the fully-idle branch below.
3104    let mut cache_last_checked: Option<Timestamp> = None;
3105    let mut disk_last_checked: Option<Timestamp> = None;
3106    // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
3107    let mut interrupt = Interrupt::Idle;
3108    // The `Pause` handed to each dispatched candidate's own `Runner` - see
3109    // `attempt`'s new parameter - kept here so the tick that decides to park
3110    // a run for an interrupt can reach that specific run's handle and no
3111    // other's. Pruned to whatever is still in flight at the top of every
3112    // tick, so a finished attempt's handle does not linger.
3113    let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
3114        std::collections::HashMap::new();
3115
3116    while !stop.stopped() {
3117        lock(status).polls += 1;
3118
3119        // Reap whatever finished since the last tick without blocking on
3120        // anything still running. `InFlightGuard` already released the slot
3121        // even if the spawned attempt panicked; this only surfaces that it
3122        // happened, since a panic swallowed here otherwise leaves no trace.
3123        while let Some(result) = inflight.try_join_next() {
3124            if let Err(e) = result {
3125                tracing::error!("a spawned attempt did not finish cleanly: {e}");
3126                notices::raise(Notice::error(
3127                    "loop:attempt",
3128                    "A queued attempt ended abnormally; check the task it was running.",
3129                ));
3130            }
3131        }
3132
3133        let swept = sweep_stale_claims(queue, STALE_CLAIM);
3134        if !swept.is_empty() {
3135            tracing::warn!(
3136                "swept {} stale claim(s) left behind by an earlier daemon: {}",
3137                swept.len(),
3138                swept.join(", ")
3139            );
3140        }
3141        // Capture stalled work before reclaiming it. A dead daemon's ordinary
3142        // lock is swept and reclaimed in this same poll, but the conductor
3143        // must still see that it was stranded rather than only its mechanical
3144        // terminal state.
3145        let now = Timestamp::now();
3146
3147        // No run this daemon spawned is mid-compile right now, whether or
3148        // not another candidate is about to start - see
3149        // `maybe_prune_cache_between_runs`'s own doc for why this cannot
3150        // wait for the queue to run dry.
3151        if !stop.busy_now() {
3152            maybe_prune_cache_between_runs(
3153                &opts.repo,
3154                opts,
3155                home,
3156                stop,
3157                &mut cache_last_checked,
3158                now,
3159            )
3160            .await;
3161        }
3162
3163        if cache_check_due(disk_last_checked, now, 30) {
3164            disk_last_checked = Some(now);
3165            if let Ok(cfg) = prepare(&opts.repo, opts) {
3166                crate::retention::sweep(home, &cfg.disk, now).await;
3167                // Shared-cache ownership makes this safe even with other runs
3168                // active. Reclaim idle outputs before asking writers to park.
3169                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3170                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3171                }
3172                for current in lock(status).current.clone() {
3173                    if let Ok(state) = RunState::load_under(&current.run, home)
3174                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3175                    {
3176                        if let Some(pause) = interrupt_pauses.get(&current.task) {
3177                            pause.park_because(reason);
3178                        }
3179                        notices::raise_in(
3180                            home,
3181                            Notice::warn(
3182                                "disk:pressure",
3183                                "Disk pressure persists after cleanup; active runs were asked to checkpoint and park. New starts and resumes wait for free space.",
3184                            ),
3185                        );
3186                    }
3187                }
3188            }
3189        }
3190
3191        let stalled = stalled_tasks(queue, home, now);
3192        let stalled_ids: std::collections::BTreeSet<_> =
3193            stalled.iter().map(|task| task.id.clone()).collect();
3194        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
3195        if !reclaimed.is_empty() {
3196            tracing::warn!(
3197                "reclaimed {} task(s) left `running` by a daemon that never \
3198                 recorded the outcome: {}",
3199                reclaimed.len(),
3200                reclaimed.join(", ")
3201            );
3202        }
3203        let abandoned_runs = reclaim_abandoned_runs(home, now);
3204        if !abandoned_runs.is_empty() {
3205            tracing::warn!(
3206                "failed {} run(s) left behind by a killed process, past every \
3207                 active seat's own timeout: {}",
3208                abandoned_runs.len(),
3209                abandoned_runs.join(", ")
3210            );
3211        }
3212
3213        // `home`, not `ask::Questions::open()`'s own process-global default:
3214        // `poll` is handed its home explicitly precisely so a test can point
3215        // it elsewhere, the same reason `Queue::at` and the status file path
3216        // are parameters rather than resolved here - see `drive`'s own doc.
3217        let questions = Questions::at(home.join("questions"));
3218
3219        // Deterministic: no model, run before the conductor sees anything so
3220        // its input reflects the queue's current, already-resolved state.
3221        repair_choice_offers(&questions);
3222        resolve_blockers(queue, &questions);
3223        apply_choice_actions(queue, &questions, home).await;
3224        triage::apply_answers(queue, &questions);
3225        reconcile_task_questions(queue, &questions);
3226        // Tell the chat a filed task or watched command has ended. Reconciled
3227        // here regardless of how it ended, and started only when no
3228        // upgrade is parking (the draft then waits for a manual resume).
3229        {
3230            let talks = crate::talk::Talks::at(home.join("talks"));
3231            crate::chat_notify::sweep(queue, &talks, home);
3232            crate::chat_watch::sweep(home, &talks);
3233            crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
3234        }
3235
3236        // The conductor gets one look per cycle, right before the loop takes
3237        // its next task, and only when there is something new to look at -
3238        // see `Conductor::worth_a_look`'s own doc for why "stalled is
3239        // non-empty" is the wrong test. Checked before `prepare` so an
3240        // unchanged cycle never pays for a synchronous config load.
3241        let finished: Vec<Task> = finished_tasks(queue)
3242            .into_iter()
3243            .filter(|task| !stalled_ids.contains(&task.id))
3244            // A parked run is waiting for this loop, not for a decision: the
3245            // conductor must not get to hold it or requeue it (a requeue
3246            // sets `fresh_start` and re-competes) before `attempt` resumes.
3247            .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
3248            .collect();
3249        let queued = queued_tasks(queue);
3250        // An empty queue has nothing to arrange. In particular, do not let
3251        // the conductor's initial snapshot cause synchronous config I/O
3252        // between the caller's stop notification and the idle wait below.
3253        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3254            && conductor.worth_a_look(queue, &stalled, &finished)
3255        {
3256            match prepare(&opts.repo, opts) {
3257                Ok(cfg) => {
3258                    conductor
3259                        .maybe_run(
3260                            &cfg,
3261                            &opts.repo,
3262                            queue,
3263                            &questions,
3264                            home,
3265                            &queued,
3266                            &stalled,
3267                            &finished,
3268                            opts.max_attempts,
3269                        )
3270                        .await;
3271                }
3272                Err(e) => {
3273                    tracing::warn!("conductor: no config: {e:#}");
3274                    notices::raise(Notice::warn(
3275                        "loop:no-config",
3276                        "The loop could not read this repository's config, so held tasks are not being triaged.",
3277                    ));
3278                }
3279            }
3280        }
3281
3282        let candidates: Vec<Task> = runnable(queue)
3283            .into_iter()
3284            .filter(|t| !opts.once || !attempted.contains(&t.id))
3285            .collect();
3286
3287        // A task id only stays a key here while its attempt is genuinely in
3288        // flight; `status.current` is the same liveness fact `InFlightGuard`
3289        // maintains for the phone's own status file, so this piggybacks on
3290        // it rather than tracking a second copy of the same thing.
3291        let in_flight: Vec<String> = lock(status)
3292            .current
3293            .iter()
3294            .map(|c| c.task.clone())
3295            .collect();
3296        interrupt_pauses.retain(|id, _| in_flight.contains(id));
3297
3298        interrupt =
3299            advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
3300        if let Interrupt::Parking {
3301            parked,
3302            interrupt_task,
3303        } = &interrupt
3304        {
3305            let reason = format!(
3306                "task {} asked to run first",
3307                crate::run::short_of(interrupt_task)
3308            );
3309            for id in parked {
3310                if let Some(pause) = interrupt_pauses.get(id) {
3311                    pause.park_because(reason.clone());
3312                }
3313            }
3314        }
3315        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3316
3317        let cooling_down =
3318            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
3319
3320        let mut started_any = false;
3321        for candidate in candidates {
3322            if stop.stopped() {
3323                break;
3324            }
3325
3326            let Some(DispatchClaim {
3327                mut task,
3328                claim,
3329                permit,
3330            }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
3331            else {
3332                continue;
3333            };
3334
3335            let task_id = task.id.clone();
3336            attempted.push(task_id.clone());
3337            lock(status).idle = false;
3338            // A stop asked for from here on is "finishing", not "stopped": the
3339            // run gets to reach a terminal status before the loop returns.
3340            stop.enter();
3341            started_any = true;
3342
3343            // A fresh, unshared handle - never `stop.pause()` - so parking
3344            // this run for an interrupt cannot leak into any other run this
3345            // loop ever drives. See `Pause`'s own doc.
3346            let run_pause = crate::graph::Pause::new();
3347            interrupt_pauses.insert(task_id.clone(), run_pause.clone());
3348
3349            let opts = opts.clone();
3350            let queue = queue.clone();
3351            let status = Arc::clone(status);
3352            let stop = stop.clone();
3353            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
3354            inflight.spawn(async move {
3355                // Held for the whole attempt: dropping either at the end of
3356                // this task is what releases the claim and, for an ordinary
3357                // candidate, frees its concurrency slot back to the loop.
3358                let _claim = claim;
3359                let _permit = permit;
3360                // See `InFlightGuard`: this must survive a panic inside `attempt`.
3361                let _inflight = InFlightGuard {
3362                    status: &status,
3363                    stop: &stop,
3364                    task_id: &task_id,
3365                };
3366                let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
3367                lock(&status).completed += 1;
3368                // A quota loss is a fact about the machine, not this task, and
3369                // the next ordinary candidate the loop offers is no less
3370                // likely to hit the same wall: without a cooldown here a
3371                // whole backlog can be run - and failed - in the seconds it
3372                // takes each attempt to notice the CLI is out of quota.
3373                let now = Timestamp::now();
3374                if let Some(until) = cooldown_until(&quota, now) {
3375                    let wait = until.as_second() - now.as_second();
3376                    *lock(&quota_cooldown_until) = Some(until);
3377                    let hint = quota
3378                        .iter()
3379                        .find(|q| q.reset.is_some())
3380                        .and_then(|q| q.reset.as_deref());
3381                    match hint {
3382                        Some(h) => tracing::warn!(
3383                            "quota hit; waiting {wait}s before taking another ordinary task \
3384                             (CLI reported reset: {h})"
3385                        ),
3386                        None => tracing::warn!(
3387                            "quota hit; waiting {wait}s before taking another ordinary task \
3388                             (no reset hint reported)"
3389                        ),
3390                    }
3391                }
3392            });
3393        }
3394
3395        if started_any {
3396            continue;
3397        }
3398
3399        if stop.busy_now() {
3400            // Something started on an earlier tick is still running. Recheck
3401            // soon rather than sleeping out the whole poll interval - a freed
3402            // slot, or a land approval answered mid-run, must not sit idle
3403            // for it.
3404            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3405            continue;
3406        }
3407
3408        // Truly idle: nothing new to start and nothing still running.
3409        lock(status).idle = true;
3410        if opts.once {
3411            // A one-shot drain must perform the same post-work cleanup as a
3412            // daemon that reached a normal idle interval. The startup pass
3413            // cannot see runs or cache files produced by this drain.
3414            janitor(&opts.repo, opts, home, worktrees_root).await;
3415            resweep_superseded_attempts(queue, home);
3416            triage_held(queue, home, opts).await;
3417            break;
3418        }
3419        stop.idle(opts.poll).await;
3420        if stop.stopped() {
3421            continue;
3422        }
3423        // Housekeeping only after a full quiet interval. Running it before
3424        // the first idle wait can block the executor while an operator's
3425        // stop request is waiting to be scheduled, defeating Stop's retained
3426        // wake permit. No run can start while this branch is active, so the
3427        // janitor still never races an in-flight compile.
3428        janitor(&opts.repo, opts, home, worktrees_root).await;
3429        resweep_superseded_attempts(queue, home);
3430        triage_held(queue, home, opts).await;
3431    }
3432
3433    // Never return while a run is still in flight, whichever way the loop
3434    // above exited: a stop only sets a flag - see `serve_until` - and
3435    // returning here while `inflight` still holds spawned work would abandon
3436    // it exactly as a mid-node kill would.
3437    while let Some(result) = inflight.join_next().await {
3438        if let Err(e) = result {
3439            tracing::error!("a spawned attempt did not finish cleanly: {e}");
3440            notices::raise(Notice::error(
3441                "loop:attempt",
3442                "A queued attempt ended abnormally; check the task it was running.",
3443            ));
3444        }
3445    }
3446    Ok(())
3447}
3448
3449/// Historical successors do not revoke a still-resumable public owner. Scan
3450/// under the same lock as publication/driver claims, and fail closed on unknown
3451/// history before spending another attempt.
3452async fn public_resume_owner(
3453    home: &Path,
3454    runs: &[String],
3455    repo: &Path,
3456) -> Result<Option<RunState>> {
3457    let mut owner = None;
3458    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
3459        let _lock = crate::pr_head::owner_lock(home, id)?;
3460        let state = RunState::load_under(id, home)?;
3461        if state.released()
3462            || state.retired_to.is_some()
3463            || state.pr_taken_over_by.is_some()
3464            || !crate::handover::landing_checkpoint(&state)
3465        {
3466            continue;
3467        }
3468        anyhow::ensure!(
3469            crate::git::toplevel(&state.repo).await?.canonicalize()?
3470                == crate::git::toplevel(repo).await?.canonicalize()?,
3471            "public owner repository differs; inspect run lineage"
3472        );
3473        anyhow::ensure!(
3474            owner.is_none(),
3475            "multiple retained public owners; inspect run lineage"
3476        );
3477        anyhow::ensure!(
3478            crate::handover::can_resume(&state),
3479            "public owner cannot resume"
3480        );
3481        let claimed = is_working_on(home, id, Timestamp::now());
3482        anyhow::ensure!(
3483            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
3484            "public owner's driver is live or unknown; wait before retrying"
3485        );
3486        owner = Some(state);
3487    }
3488    Ok(owner)
3489}
3490
3491/// Run one claimed task to a terminal status and record the outcome.
3492///
3493/// Every transition is flushed to the queue as it happens, so the state on disk
3494/// is what actually occurred rather than what this process still intends to
3495/// write.
3496async fn attempt(
3497    opts: &Opts,
3498    queue: &Queue,
3499    status: &Arc<Mutex<Status>>,
3500    stop: &Stop,
3501    interrupt_pause: crate::graph::Pause,
3502    task: &mut Task,
3503) -> Vec<QuotaLoss> {
3504    let repo = repo_for(task, &opts.repo);
3505    tracing::info!(
3506        "task {} — {} (repo {})",
3507        task.short(),
3508        task.title,
3509        repo.display()
3510    );
3511
3512    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
3513        Ok(owner) => owner,
3514        Err(e) => {
3515            task.hold_machine(Some(format!(
3516                "Cannot verify existing public owner: {e:#}; no attempt started."
3517            )));
3518            record(queue, task);
3519            return Vec::new();
3520        }
3521    };
3522    let resume_runs = public_owner
3523        .as_ref()
3524        .map(|s| vec![s.id.clone()])
3525        .unwrap_or_else(|| task.runs.clone());
3526
3527    // A stop spends no agent resources and uses the saved landing owner.
3528    // Current roster edits, missing attachments or a failed config fetch must
3529    // never turn it into a new implementation, or prevent a PR from closing.
3530    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
3531        && previous
3532            .merge_decision
3533            .as_ref()
3534            .is_some_and(|decision| !decision.closed)
3535        && previous.status != RunStatus::Landing
3536        && !crate::merge_decision::resumable_hold(&previous)
3537    {
3538        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)));
3539        record(queue, task);
3540        return Vec::new();
3541    }
3542    let stop_owner = resume_runs
3543        .last()
3544        .and_then(|id| RunState::load(id).ok())
3545        .filter(|state| {
3546            crate::merge_decision::resumable_hold(state)
3547                || state.status == RunStatus::Landing
3548                    && state.land_approval.as_ref().is_some_and(|binding| {
3549                        Questions::open().get(&binding.question).is_ok_and(|q| {
3550                            q.run == state.id
3551                                && q.resolution()
3552                                    .as_deref()
3553                                    .is_some_and(crate::merge_decision::stops)
3554                        })
3555                    })
3556        });
3557    if let Some(owner) = stop_owner {
3558        let mut runner = match Runner::resume(&owner.id) {
3559            Ok(runner) => runner,
3560            Err(e) => {
3561                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
3562                record(queue, task);
3563                return Vec::new();
3564            }
3565        };
3566        runner.on_pause(stop.pause());
3567        runner.watch_interrupt(interrupt_pause);
3568        let quota_before = runner.state.quota.clone();
3569        task.start(owner.id.clone());
3570        record(queue, task);
3571        lock(status).current.push(Current {
3572            task: task.id.clone(),
3573            run: owner.id,
3574        });
3575        runner.state.next_pass_task_entry = true;
3576        let result = runner.execute().await;
3577        return finish_attempt(
3578            opts.max_attempts,
3579            queue,
3580            task,
3581            &runner.state,
3582            &quota_before,
3583            result,
3584        );
3585    }
3586
3587    if let Some(owner) = &public_owner
3588        && (task.fresh_start || !may_resume_run(owner, task))
3589    {
3590        task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. No attempt started.", owner.id)));
3591        record(queue, task);
3592        return Vec::new();
3593    }
3594
3595    let unfinished = (!task.fresh_start)
3596        .then(|| unfinished_run(&resume_runs, task.short()))
3597        .flatten()
3598        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3599    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
3600    if !task.fresh_start
3601        && task.pr_recovery.is_none()
3602        && task.review_branch.is_none()
3603        && task.resume_override.is_none()
3604        && previous
3605            .as_ref()
3606            .is_some_and(|run| run.retired_to.is_some())
3607        && unfinished.is_none()
3608    {
3609        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()));
3610        record(queue, task);
3611        return Vec::new();
3612    }
3613
3614    let saved_recovery = previous.as_ref().filter(|run| {
3615        task.replacement.is_none()
3616            && task.pr_recovery.as_ref().is_some_and(|selected| {
3617                selected.check_task(&task.id, &task.instruction).is_ok()
3618                    && selected_starter(selected, Some(run), unfinished.as_deref())
3619                        == Starter::Resume(run.id.clone())
3620            })
3621    });
3622
3623    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
3624    // failure here is the network's or the operator's, not the task's: hold
3625    // without spending an attempt, never fall back to a possibly stale copy.
3626    let explicit = match &task.overrides {
3627        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
3628        Some(_) => opts.config.as_deref(),
3629        None => opts.config.as_deref(),
3630    };
3631    let (mut config, layers) = if let Some(run) = saved_recovery {
3632        // A matching resume owns its resolved configuration and evidence;
3633        // current layers and inherited overrides only configure new work.
3634        let mut saved = run.clone();
3635        if let Err(e) = saved.configure_recovery_resume() {
3636            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
3637            record(queue, task);
3638            return Vec::new();
3639        }
3640        (saved.config, Vec::new())
3641    } else {
3642        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
3643            Ok(loaded) => loaded,
3644            Err(e) => {
3645                let reason = format!("[config] {e:#}");
3646                record_config_failure(task, &e);
3647                task.last_error = Some(reason.clone());
3648                task.hold_machine(Some(reason));
3649                record(queue, task);
3650                return Vec::new();
3651            }
3652        };
3653        if let Err(e) = apply_options(&mut config, opts, task) {
3654            task.hold_manual(Some(format!(
3655                "[config] {e:#}; correct the merge override before releasing the task"
3656            )));
3657            record(queue, task);
3658            return Vec::new();
3659        }
3660        if let Some(selected) = &task.pr_recovery
3661            && let Err(e) = selected.configure(&mut config)
3662        {
3663            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
3664            record(queue, task);
3665            return Vec::new();
3666        }
3667        (config, layers)
3668    };
3669    let config_evidence = crate::pr_recovery::ConfigEvidence {
3670        layers,
3671        overrides: task.overrides.clone(),
3672        daemon_merge: task
3673            .overrides
3674            .as_ref()
3675            .is_none_or(|o| o.inherit_daemon_options)
3676            .then(|| opts.merge.clone())
3677            .flatten(),
3678    };
3679    apply_task_implementers(&mut config, task);
3680    if let Some(replacement) = &task.replacement {
3681        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
3682            old.liveness(false) == Liveness::Dead
3683                && old.merge_decision.as_ref().is_some_and(|d| {
3684                    d.closed
3685                        && d.question == replacement.question
3686                        && d.replacement_run.as_ref().is_none_or(|run| {
3687                            task.runs.last() == Some(run)
3688                                && RunState::load(run).is_ok_and(|current| {
3689                                    current.replaces.as_ref().is_some_and(|pin| {
3690                                        pin.question == replacement.question
3691                                            && pin.agent == replacement.agent
3692                                    })
3693                                })
3694                        })
3695                })
3696        });
3697        if !safe {
3698            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()));
3699            record(queue, task);
3700            return Vec::new();
3701        }
3702        match config.agent(&replacement.agent) {
3703            Ok(agent) if crate::agent::installed(agent) => {}
3704            _ => {
3705                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)));
3706                record(queue, task);
3707                return Vec::new();
3708            }
3709        }
3710        config.graph.implementers = 1;
3711        config.graph.land_approval = true;
3712        config.merge.mode = MergeMode::Pr;
3713        config.graph.selected_implementer = Some(replacement.agent.clone());
3714    }
3715    let p = phrases(&config.graph.language);
3716    let start_failed = p.could_not_start;
3717    // Resolve once for both admission and settlement. The inputs are the
3718    // task's explicit sources (never prose), plus an explicit review source's
3719    // current head; review-only runs may rebase later, and neither fact can
3720    // refund a failed automatic generation.
3721    if let Ok(base) =
3722        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
3723            .await
3724        && let Ok(head) =
3725            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
3726    {
3727        let mut inputs = crate::queue::recovery_inputs(&task.sources);
3728        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
3729            let source = crate::git::rev_parse(&repo, branch)
3730                .await
3731                .unwrap_or_default();
3732            inputs.push_str(&format!(";review:{branch}:{source}"));
3733        }
3734        if let Some(reason) = task.recovery_exhausted(
3735            &head,
3736            &inputs,
3737            task.attempt_limit
3738                .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
3739        ) {
3740            task.hold_unrequested_retry(Some(reason));
3741            record(queue, task);
3742            return Vec::new();
3743        }
3744        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
3745    }
3746
3747    // The free-space gate, checked *before* anything is minted: a task that
3748    // waits out a full disk costs nothing yet, and must not spend an attempt
3749    // or start a run the machine cannot finish. Held tasks stay in the list
3750    // for the human to see, and `magi task release` re-queues them when space
3751    // comes back - the same recovery as any other hold. A volume whose free
3752    // space cannot be measured closes the gate too: starting a run blind on a
3753    // disk that may be full is how the machine ends up with 6.7 GB free.
3754    if let Some(reason) = disk_gate(&repo, &config) {
3755        task.notice_cause("disk-space", None, None);
3756        task.last_error = Some(reason.clone());
3757        task.hold_machine(Some(reason.clone()));
3758        record(queue, task);
3759        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
3760        // Stable wording - the free-space figures live in the task's hold
3761        // reason, and changing numbers would relight the bell every poll.
3762        notices::raise(
3763            Notice::warn(
3764                &format!("disk:{}", repo.display()),
3765                "A task was held for want of free disk space; free some, then release it from the queue.",
3766            )
3767            .link(Link::Task {
3768                id: task.id.clone(),
3769            }),
3770        );
3771        return Vec::new();
3772    }
3773
3774    // A resumable run of this task is carried on, never re-competed. The
3775    // candidates are built and paid for, and a fresh competition races a
3776    // second implementation against them.
3777    //
3778    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
3779    // started 3cbf on the same task a moment later, duplicating two and a
3780    // half hours of agent work. Then b25f stalled on a judge that timed out
3781    // and one that answered with no JSON - `quota: 0`, so nothing the machine
3782    // was to blame for - and 4043 started **one second** later, buying three
3783    // fresh implementations to reach the same panel. `RunStatus::resumable`
3784    // rather than `!done()` is what catches the second case: a stall is
3785    // terminal, and its cheap recovery re-asks only the absent seats.
3786    //
3787    // A load failure is warned about rather than silently read as "not
3788    // resumable": the alternative is exactly what let a schema mismatch on
3789    // run `eba2` fall through to a full re-competition with nobody told why.
3790    // `crate::conduct` is what actually offers a better answer than
3791    // `Runner::start` here (see `Recovery::Review`), once this task's next
3792    // failure shows it up as `held`/`failed` with the run state unreadable.
3793    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
3794    // branch survived, and this reopens exactly that branch as a
3795    // review-only pass rather than resuming or competing again. Consumed
3796    // (cleared) here whichever way this goes, so it never outlives this one
3797    // attempt - see `queue::Task::review_branch`.
3798    let review_branch = take_review_branch(task, previous.as_ref());
3799    let branch_exists = match &review_branch {
3800        Some(branch) => crate::git::branch_exists(&repo, branch)
3801            .await
3802            .unwrap_or(false),
3803        None => false,
3804    };
3805    // An explicit `magi review <branch>` is reviewed whatever happens to the
3806    // branch unless an explicit implementer change requires fresh work. An
3807    // unfinished run of the same task still wins, so a retry resumes.
3808    let proposed = match (&review_branch, &unfinished, &task.review_of) {
3809        (None, None, Some(branch)) => Starter::Review(branch.clone()),
3810        _ => choose_starter(
3811            review_branch.as_deref(),
3812            branch_exists,
3813            unfinished.as_deref(),
3814        ),
3815    };
3816    let retry_selected = task.replacement.is_some()
3817        && task.resumption.is_some()
3818        && !task.fresh_start
3819        && previous.as_ref().is_some_and(|run| {
3820            run.replaces.is_some()
3821                && ((run.status == RunStatus::Failed && run.viable().is_empty())
3822                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
3823        });
3824    let stop_pin = task
3825        .resume_override
3826        .as_ref()
3827        .filter(|pin| {
3828            Questions::open().get(&pin.question_id).is_ok_and(|q| {
3829                q.node == land::APPROVAL_NODE
3830                    && q.resolution()
3831                        .as_deref()
3832                        .is_some_and(crate::merge_decision::stops)
3833            })
3834        })
3835        .and_then(|pin| pin.pinned_run.clone());
3836    let starter = if let Some(owner) = &public_owner {
3837        Starter::Resume(owner.id.clone())
3838    } else if let Some(run) = stop_pin {
3839        // Stop actions resume their exact owner even after seat-count edits;
3840        // they must never fall through to implementation or a takeover.
3841        Starter::Resume(run)
3842    } else if retry_selected {
3843        Starter::Resume(previous.as_ref().unwrap().id.clone())
3844    } else if let Some(selected) = &task.pr_recovery {
3845        if selected.check_task(&task.id, &task.instruction).is_ok() {
3846            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3847        } else {
3848            Starter::Review(selected.branch.clone())
3849        }
3850    } else {
3851        starter_with_implementers(task, previous.as_ref(), proposed)
3852    };
3853    // An explicit resume pin must never degrade into a new competition or
3854    // takeover, including when its run stops being eligible after the answer.
3855    if let Some(pin) = &task.resume_override
3856        && let Some(run) = &pin.pinned_run
3857        && starter != Starter::Resume(run.clone())
3858    {
3859        let run = run.clone();
3860        task.notice_cause("resume-owner", Some(&run), None);
3861        task.hold_machine(Some(format!(
3862            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3863            task.id
3864        )));
3865        record(queue, task);
3866        return Vec::new();
3867    }
3868    if task.replacement.is_some()
3869        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
3870        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
3871    {
3872        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()));
3873        record(queue, task);
3874        return Vec::new();
3875    }
3876    if let Some(reason) = retained_attempt_hold(
3877        task,
3878        &starter,
3879        config.disk.retained_attempt_limit,
3880        RunState::load,
3881    ) {
3882        // The review choice was consumed above. Preserve it across this hold
3883        // so a later release cannot silently become a fresh implementation.
3884        if let Starter::Review(branch) = &starter {
3885            task.review_branch = Some(branch.clone());
3886        }
3887        task.hold_unrequested_retry(Some(reason));
3888        record(queue, task);
3889        return Vec::new();
3890    }
3891    // Absolute paths of the files the task was filed with, re-read from the
3892    // task now so a file attached while it was held reaches a resumed run
3893    // too. A stored name whose file has gone is an error before any agent is
3894    // paid for, never a silent omission the implementer cannot notice.
3895    let attachments = match task_attachments(queue, task) {
3896        Ok(a) => a,
3897        Err(e) => {
3898            task.attempts += 1;
3899            task.fail_startup_target(
3900                "startup-attachments",
3901                e.name.clone(),
3902                format!("{start_failed}{e:#}"),
3903                opts.max_attempts,
3904            );
3905            record(queue, task);
3906            return Vec::new();
3907        }
3908    };
3909    let startup_pause = stop.pause();
3910    let startup_interrupt = interrupt_pause.clone();
3911    let wait = crate::repo_lock::WaitPolicy::new(
3912        Duration::from_secs(config.graph.timeout_resource_wait),
3913        move || startup_pause.parked() || startup_interrupt.parked(),
3914    );
3915    // Startup includes review takeover and recovery. Do not embed its large
3916    // future in both the wait scope and the surrounding attempt stack frame.
3917    let started = wait.scope(Box::pin(async { match &starter {
3918        Starter::Review(_) if task.pr_recovery.is_some() => {
3919            let selected = task.pr_recovery.clone().expect("selected recovery");
3920            match selected.check_task(&task.id, &task.instruction) {
3921                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3922                    .await
3923                    .map(|mut r| {
3924                        r.state.attachments = attachments.clone();
3925                        r
3926                    }),
3927                Err(e) => Err(e),
3928            }
3929        }
3930        Starter::Review(branch) => {
3931            tracing::info!(
3932                "task {} reopens `{branch}` as a review-only pass",
3933                task.short()
3934            );
3935            // Every earlier attempt is superseded by the one being minted
3936            // now, so a branch one of them still holds may be taken over.
3937            let takeover = crate::handover::Takeover {
3938                earlier: task.earlier_attempts().to_vec(),
3939                home: crate::run::home(),
3940                choice: take_divergence_answer(branch, &config.merge.remote, task),
3941                task_instruction: Some(instruction_for(task)),
3942            };
3943            Runner::review_taking_over(
3944                &repo,
3945                branch,
3946                config,
3947                Some(takeover),
3948                crate::run::Origin::queue(&task.id),
3949            )
3950            .await
3951        }
3952        Starter::Resume(id) => {
3953            tracing::info!("resuming run {id} rather than competing again");
3954            Runner::resume(id).and_then(|mut r| {
3955                if retry_selected {
3956                    // The explicit queue release retries this same pinned
3957                    // implementation, preserving the attempt and worktrees.
3958                    for candidate in &mut r.state.candidates {
3959                        candidate.failed = None;
3960                        candidate.empty = false;
3961                        candidate.commits = 0;
3962                    }
3963                    r.state.status = RunStatus::Implementing;
3964                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
3965                }
3966                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
3967                    r.state.sources = task.sources.clone();
3968                }
3969                if r.state.prep_failure.is_some() {
3970                    let approval = task
3971                        .resumption
3972                        .as_ref()
3973                        .context("preparation retry requires an explicit task release")?;
3974                    r.retry_preparation(approval.at)?;
3975                }
3976                if let Some(instruction) =
3977                    prepare_instruction(&starter, Some(&r.state.instruction), task)
3978                {
3979                    r.state.instruction = instruction;
3980                }
3981                r.state.attachments = attachments.clone();
3982                if task.replacement.is_some() {
3983                    r.state.config.merge.mode = MergeMode::Pr;
3984                    r.state.config.graph.land_approval = true;
3985                }
3986                // Replacements publish a new PR and ask again. Selected PR
3987                // recoveries keep their saved disposition; ordinary runs can
3988                // retain the task's merge override.
3989                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
3990                    .overrides
3991                    .as_ref()
3992                    .and_then(|o| o.merge.as_deref())
3993                    .and_then(|m| merge_mode(m).ok())
3994                {
3995                    r.state.config.merge.mode = mode;
3996                }
3997                Ok(r)
3998            })
3999        }
4000        Starter::Start => {
4001            if let Some(branch) = &review_branch {
4002                tracing::warn!(
4003                    "conductor chose review for task {} but branch `{branch}` no longer \
4004                     exists; requeuing as a fresh competition instead",
4005                    task.short()
4006                );
4007            }
4008            let instruction = prepare_instruction(&starter, None, task)
4009                .unwrap_or_else(|| task.instruction.clone());
4010            Runner::start_naming(
4011                &repo,
4012                instruction,
4013                &task.title,
4014                config,
4015                crate::run::Origin::queue(&task.id),
4016            )
4017            .await
4018            .map(|mut r| {
4019                r.state.attachments = attachments.clone();
4020                r.state.sources = task.sources.clone();
4021                r
4022            })
4023        }
4024    }})).await;
4025    let mut runner = match started {
4026        Ok(r) => r,
4027        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4028            task.last_error = Some(e.to_string());
4029            if stop.parking() || interrupt_pause.parked() {
4030                let attempts = task.attempts;
4031                task.park(e.to_string());
4032                // Startup has not spent an attempt to refund.
4033                task.attempts = attempts;
4034            } else {
4035                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4036            }
4037            record(queue, task);
4038            return Vec::new();
4039        }
4040        // A branch an earlier attempt still holds and magi will not release
4041        // by itself is the operator's call, not a failed attempt: hold the
4042        // task with the reason, spend nothing, and say so on the bell.
4043        Err(e) if task.pr_recovery.is_some() => {
4044            task.startup_notice_cause("startup-public-head");
4045            task.attempts += 1;
4046            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
4047                task.link_run(&partial.run);
4048                task.record_pass(&partial.run, 0, task.attempts, None);
4049            }
4050            task.last_error = Some(format!("{start_failed}{e:#}"));
4051            task.hold_unrequested_retry(Some(format!(
4052                "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."
4053            )));
4054            record(queue, task);
4055            return Vec::new();
4056        }
4057        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4058            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4059                Some(r) => (p.handover_refused)(r),
4060                None => format!("{e:#}"),
4061            };
4062            task.startup_notice_cause("startup-handover");
4063            let reason = format!("{start_failed}{detail}");
4064            task.last_error = Some(reason.clone());
4065            // Consumed above by `take`; keep it so the released task retries
4066            // as a review of this same branch.
4067            let branch = match &starter {
4068                Starter::Review(branch) => Some(branch.clone()),
4069                _ => None,
4070            };
4071            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4072            // one page; the guidance rides in the reason, fixed per state so a
4073            // re-put never changes the wording and relights it.
4074            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4075            record(queue, task);
4076            tracing::warn!(
4077                "holding {} for a branch it cannot take over: {e:#}",
4078                task.short()
4079            );
4080            return Vec::new();
4081        }
4082        // A branch that differs between here and the remote in ways magi
4083        // cannot prove are the same change is a decision for the owner, not a
4084        // failed attempt: ask with both sides laid out, spend no attempt, and
4085        // let the answer requeue the task.
4086        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4087            let d = e
4088                .downcast_ref::<crate::reconcile::Diverged>()
4089                .expect("checked by the guard");
4090            let mut q = ask::Question::new(
4091                task.id.clone(),
4092                crate::reconcile::NODE.to_owned(),
4093                crate::reconcile::SEAT.to_owned(),
4094                d.summary(),
4095                d.detail(),
4096                d.choices(),
4097            );
4098            match Questions::open().put(&mut q) {
4099                Ok(()) => {
4100                    task.last_error = Some(format!("{e:#}"));
4101                    // Consumed above by `take`; the answer has to reach a review
4102                    // of this same branch, so keep pointing the task at it.
4103                    task.review_branch = Some(d.branch.clone());
4104                    task.review_instruction = Some(task.instruction.clone());
4105                    task.block(vec![q.id.clone()], Some(d.summary()));
4106                }
4107                Err(put) => {
4108                    tracing::warn!("could not file the divergence question: {put:#}");
4109                    task.attempts += 1;
4110                    task.fail_startup(
4111                        "startup-question-store",
4112                        format!("{start_failed}{e:#}"),
4113                        opts.max_attempts,
4114                    );
4115                }
4116            }
4117            record(queue, task);
4118            return Vec::new();
4119        }
4120        Err(e) => {
4121            // The answer was stale and nothing was applied: keep pointing at
4122            // the branch so the next attempt asks again against its new tips.
4123            // Nothing went wrong with the task, so no attempt is spent: a
4124            // budget one short of its limit must not hold it instead of
4125            // letting the question be asked again.
4126            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4127                && let Starter::Review(branch) = &starter
4128            {
4129                task.review_branch = Some(branch.clone());
4130                task.review_instruction = Some(task.instruction.clone());
4131                task.last_error = Some(format!("{start_failed}{e:#}"));
4132                task.status = crate::queue::TaskStatus::Failed;
4133                record(queue, task);
4134                return Vec::new();
4135            }
4136            task.attempts += 1;
4137            task.last_error = Some(format!("{start_failed}{e:#}"));
4138            task.startup_notice_cause("startup-source");
4139            task.hold_unrequested_retry(Some(format!(
4140                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4141            )));
4142            record(queue, task);
4143            return Vec::new();
4144        }
4145    };
4146    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4147        runner.state.recovery_config = Some(config_evidence);
4148    }
4149    if let Some(replacement) = &task.replacement {
4150        if matches!(starter, Starter::Start) {
4151            runner.state.instruction.push_str(&format!(
4152                "\n\n# Replacement review context\n{}",
4153                replacement.context
4154            ));
4155        }
4156        runner.state.replaces = Some(replacement.clone());
4157        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4158        if let Ok(mut old) = RunState::load(&replacement.run)
4159            && let Some(d) = &mut old.merge_decision
4160        {
4161            d.replacement_run = Some(runner.state.id.clone());
4162            old.event(
4163                "replacement",
4164                format!(
4165                    "replacement run {} owns the next attempt; old PR remains closed",
4166                    runner.state.id
4167                ),
4168            );
4169            if let Err(e) = old.save() {
4170                task.hold_manual(Some(format!(
4171                    "Could not link replacement history: {e}; no agents dispatched"
4172                )));
4173                record(queue, task);
4174                return Vec::new();
4175            }
4176        }
4177    }
4178    runner.state.task_instruction = Some(task.instruction.clone());
4179    // The follow-up depth is fixed now, while the task certainly exists:
4180    // deleting it later must not reset the cap (`crate::followup`).
4181    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4182    if runner.state.origin_chat.is_none() {
4183        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4184    }
4185    // A stop that means "park" reaches the graph through this handle.
4186    runner.on_pause(stop.pause());
4187    // `poll`'s interrupt scheduler reaches this one run - and no other -
4188    // through this handle. See `Pause`'s own doc for why these are never
4189    // the same one.
4190    runner.watch_interrupt(interrupt_pause);
4191
4192    // `start` has minted the run, so the task can now point at it. Persisting
4193    // `Running` before `execute` is what makes a crash mid-run legible.
4194    let run = runner.state.id.clone();
4195    task.start(run.clone());
4196    record(queue, task);
4197    lock(status).current.push(Current {
4198        task: task.id.clone(),
4199        run,
4200    });
4201
4202    // `RunState::quota` is the run's whole history across every resume, so
4203    // only what this execution added may arm the cooldown or earn a refund.
4204    let quota_before = runner.state.quota.clone();
4205    runner.state.next_pass_task_entry = true;
4206    let result = runner.execute().await;
4207    finish_attempt(
4208        opts.max_attempts,
4209        queue,
4210        task,
4211        &runner.state,
4212        &quota_before,
4213        result,
4214    )
4215}
4216
4217/// Settle `task` after its run executed: the verdict, the diagnosis, the
4218/// supersession of earlier attempts and the save. Shared by the loop and by
4219/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4220/// Returns the quota losses this execution added to the run.
4221pub fn finish_attempt(
4222    max_attempts: usize,
4223    queue: &Queue,
4224    task: &mut Task,
4225    state: &RunState,
4226    quota_before: &[QuotaLoss],
4227    result: Result<()>,
4228) -> Vec<QuotaLoss> {
4229    let detail = match result {
4230        Ok(()) => describe(state),
4231        Err(e) => format!("{e:#}"),
4232    };
4233    let fresh = losses_this_attempt(quota_before, &state.quota);
4234    let verdict = Verdict {
4235        status: state.status,
4236        // A run that opened a pull request handed its work over, whatever the
4237        // gate then decided about merging it.
4238        left_pr: state.pr.is_some(),
4239        // Only a rate limit earns the task its attempt back - and only one
4240        // suffered now: a refund justified by a previous session's loss is
4241        // the same mistake as re-arming the cooldown from it. A stalled run
4242        // resumed without hitting quota again therefore spends its attempt,
4243        // like any other failure of the task's own.
4244        quota_hit: !fresh.is_empty(),
4245        // A run that parked was asked to stop; that is not a failure and must
4246        // not spend an attempt, or replacing the binary a few times would
4247        // exhaust a task's budget without an agent ever misbehaving.
4248        parked: state.parked,
4249        // A quota loss that left nothing viable is the same machine fact as a
4250        // `Stalled` quota loss; see `settle`'s doc table.
4251        no_viable_candidates: state.viable().is_empty(),
4252    };
4253    if let Some(replacement) = &state.replaces
4254        && let Some(pr) = &state.pr
4255        && let Ok(mut old) = RunState::load(&replacement.run)
4256        && let Some(d) = &mut old.merge_decision
4257    {
4258        d.replacement_pr = Some(pr.url.clone());
4259        let _ = old.save();
4260    }
4261    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4262    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4263        task.hold_unrequested_retry(Some(format!(
4264            "Candidate setup failed: {detail}. Correct the explicit sources with `magi task sources {}` (README, \"Use\": implementation imports), or select a complete implementation with `magi task recover-pr`, then explicitly release the task.",
4265            task.short()
4266        )));
4267    }
4268    if task.status == TaskStatus::Done {
4269        supersede_prior_runs(task, &crate::run::home());
4270    }
4271    record(queue, task);
4272    tracing::info!(
4273        "task {} is {} after run {} ({})",
4274        task.short(),
4275        task.status.as_str(),
4276        state.short(),
4277        label(state.status)
4278    );
4279    fresh
4280}
4281
4282/// A task a hand-started run leaves runnable (failed with attempts to spare,
4283/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4284/// later must not spend agent calls on it. `magi task release` retries.
4285pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4286    // A run parked on the owner's word about a withheld PR title/body is not a
4287    // failure nobody asked to retry: it resumes (answer, or the neutral text on
4288    // the deadline) the moment a loop serves the queue, via `land_resume_state`.
4289    // Holding it would keep it from ever being a candidate.
4290    let waits_on_owner = withheld_text_wait(task).is_some();
4291    if task.status.runnable()
4292        && !waits_on_owner
4293        && !(task.fresh_start && task.replacement.is_some())
4294    {
4295        let why = task.last_error.clone().map_or_else(
4296            || "the run did not finish".to_owned(),
4297            |e| format!("the run did not finish: {e}"),
4298        );
4299        task.hold_unrequested_retry(Some(format!(
4300            "{why}. It was started by hand, so it is not retried \
4301             automatically; `magi task release` retries it."
4302        )));
4303        record(queue, task);
4304    }
4305}
4306
4307/// Whether an attempt at a task whose newest run is `run` would resume that
4308/// run rather than start a fresh competition. `magi run --resume` hands a run
4309/// to a live loop only when this holds.
4310#[must_use]
4311pub fn loop_would_resume(run: &str) -> bool {
4312    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4313}
4314
4315/// A loop in another process that is alive right now: a fresh heartbeat in
4316/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4317/// carries the pid it published (`None` inside when it published none - a
4318/// fresh heartbeat is still evidence of a live loop).
4319///
4320/// The one judgement of "is somebody else serving this queue", shared by the
4321/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4322/// deciding whether to hand a task to the loop. A claim file proves nothing
4323/// here: whether a claim succeeds says nothing about whether its owner lives.
4324#[must_use]
4325pub fn foreign_loop(
4326    reading: Option<&Reading>,
4327    now: Timestamp,
4328    own_pid: u32,
4329) -> Option<Option<u32>> {
4330    let reading = reading.filter(|r| r.running(now))?;
4331    match reading.pid {
4332        Some(pid) if pid == own_pid => None,
4333        pid => Some(pid),
4334    }
4335}
4336
4337/// Run one task this process has claimed, in this process, through exactly the
4338/// attempt a daemon would make: the same starter choice (start, resume,
4339/// review), the same `Task::start` / `settle` transitions, attempt counting,
4340/// quota refund and parking. No second dispatcher - `magi run` and `magi
4341/// review` call this when no daemon is alive.
4342///
4343/// The caller holds the [`Queue::claim`] for the whole call, which is what
4344/// keeps a daemon that starts meanwhile from taking the task.
4345///
4346/// The one deliberate difference from the loop: a task the attempt leaves
4347/// runnable (failed with attempts to spare, or requeued) is **held** instead.
4348/// Nobody asked for a retry, and a daemon starting later must not spend agent
4349/// calls re-running a hand-started task behind the operator's back;
4350/// `magi task release` is the explicit retry.
4351pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4352    let status = Arc::new(Mutex::new(Status::new()));
4353    let stop = Stop::new();
4354    // An attempt embeds startup and graph futures. Keep it off the standalone
4355    // caller's stack, on both the initial execution and withheld-text resume.
4356    Box::pin(attempt(
4357        opts,
4358        queue,
4359        &status,
4360        &stop,
4361        crate::graph::Pause::new(),
4362        task,
4363    ))
4364    .await;
4365    // A run parked on the owner's word about a withheld PR title/body has no
4366    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
4367    // here with the claim still held, and resume once the question is settled
4368    // (answered, or abandoned at its deadline -> the neutral text).
4369    // A rejected reply files one more question (the gate asks at most twice),
4370    // so after a resume the run may be waiting again: keep going, with a fresh
4371    // limit for the new question. `resumes` bounds it even if a resume parks
4372    // without asking anything new.
4373    let mut resumes = 0;
4374    while resumes < MAX_WITHHELD_RESUMES {
4375        let Some(timeout) = withheld_text_wait(task) else {
4376            break;
4377        };
4378        eprintln!(
4379            "waiting for the owner's answer on a withheld pull request text \
4380             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4381        );
4382        // The deadline abandons the question itself; the extra margin only
4383        // covers an abandon that could not be saved.
4384        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4385        let ready = loop {
4386            match land_resume_state(task) {
4387                LandResume::StillWaiting if std::time::Instant::now() < limit => {
4388                    tokio::time::sleep(WITHHELD_POLL).await;
4389                }
4390                LandResume::Ready => break true,
4391                _ => break false,
4392            }
4393        };
4394        if !ready {
4395            break;
4396        }
4397        resumes += 1;
4398        Box::pin(attempt(
4399            opts,
4400            queue,
4401            &status,
4402            &stop,
4403            crate::graph::Pause::new(),
4404            task,
4405        ))
4406        .await;
4407    }
4408    hold_if_runnable(queue, task);
4409}
4410
4411/// Resumes an in-process run makes for withheld-text questions: the gate asks
4412/// at most twice, plus one for a resume that asks nothing new.
4413const MAX_WITHHELD_RESUMES: u32 = 3;
4414
4415/// How often an in-process run rechecks its withheld-text question.
4416const WITHHELD_POLL: Duration = Duration::from_secs(15);
4417
4418/// The `answer_timeout` (seconds) of the task's last run when that run is
4419/// parked on an unresolved withheld-text question; `None` otherwise.
4420fn withheld_text_wait(task: &Task) -> Option<u64> {
4421    let id = task.runs.last()?;
4422    let s = RunState::load(id).ok()?;
4423    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
4424        .then_some(s.config.graph.answer_timeout)
4425}
4426
4427/// The quota losses `after` holds that `before` did not: what one execution
4428/// suffered, as opposed to the run's history.
4429///
4430/// Compared by value rather than by length or position because
4431/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
4432/// the vector can shrink and shift under a resume. A retried seat that hits
4433/// quota again is a `push` with a new `at`, so it shows up as new here.
4434/// `reclaim` deliberately keeps reading the whole history: after a crash there
4435/// is no attempt boundary to diff against.
4436fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
4437    after
4438        .iter()
4439        .filter(|q| !before.contains(q))
4440        .cloned()
4441        .collect()
4442}
4443
4444/// When the loop-wide quota cooldown should end, given this attempt's losses;
4445/// `None` when there were none. Reset-hint parsing and the cap live here.
4446fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
4447    if quota.is_empty() {
4448        return None;
4449    }
4450    let with_hint = quota.iter().find(|q| q.reset.is_some());
4451    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
4452    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
4453    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
4454    Some(
4455        now.checked_add(jiff::SignedDuration::from_secs(secs))
4456            .unwrap_or(Timestamp::MAX),
4457    )
4458}
4459
4460/// An explicit task count must agree with a run before any resume.
4461fn implementers_match(task: &Task, state: &RunState) -> bool {
4462    task.replacement.as_ref().map_or_else(
4463        || {
4464            task.implementers()
4465                .is_none_or(|n| n == state.config.graph.implementers)
4466        },
4467        |replacement| {
4468            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
4469                && state.config.graph.implementers == 1
4470        },
4471    )
4472}
4473
4474/// Never resume or take over candidate work built for a different seat count.
4475fn starter_with_implementers(
4476    task: &Task,
4477    previous: Option<&RunState>,
4478    proposed: Starter,
4479) -> Starter {
4480    if previous.is_some_and(|s| !implementers_match(task, s)) {
4481        task.review_of
4482            .as_ref()
4483            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
4484    } else {
4485        proposed
4486    }
4487}
4488
4489/// Apply this task's explicit count to the new attempt, without changing defaults.
4490fn apply_task_implementers(config: &mut Config, task: &Task) {
4491    if let Some(n) = task.implementers() {
4492        config.graph.implementers = n;
4493    }
4494}
4495
4496/// [`prepare`] for one task: its own `--config` and command-line overrides
4497/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
4498/// over the loop's, so handing a hand-started task to a daemon changes nothing
4499/// about what it does.
4500#[cfg(test)]
4501fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
4502    let explicit = match &task.overrides {
4503        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4504        _ => opts.config.as_deref(),
4505    };
4506    let (mut config, _) = Config::discover(repo, explicit)?;
4507    apply_options(&mut config, opts, task)?;
4508    Ok(config)
4509}
4510
4511fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
4512    if task
4513        .overrides
4514        .as_ref()
4515        .is_none_or(|o| o.inherit_daemon_options)
4516        && let Some(mode) = opts.merge.as_deref()
4517    {
4518        config.merge.mode = merge_mode(mode)?;
4519    }
4520    if let Some(o) = &task.overrides {
4521        o.apply(config);
4522    }
4523    Ok(())
4524}
4525
4526/// Load the config for a task's repository, with the merge override applied.
4527fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
4528    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
4529    if let Some(mode) = &opts.merge {
4530        config.merge.mode = merge_mode(mode)?;
4531    }
4532    Ok(config)
4533}
4534
4535/// Prune the shared build cache back under its cap at a safe boundary
4536/// between runs, so a queue that never empties - and so never reaches
4537/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
4538/// does not leave the cache to grow unchecked for as long as the backlog
4539/// lasts.
4540///
4541/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
4542/// same liveness fact the idle branch's own janitor call rests on - no run
4543/// this daemon spawned is still mid-compile - so pruning here races nothing.
4544/// The caller must not call this while a run is in flight; there is no
4545/// second `busy_now()` check inside this function, on purpose, because there
4546/// is nothing left to check that `busy_now()` has not already answered.
4547///
4548/// A stop that has already been asked for *is* checked here, for a different
4549/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
4550/// synchronously before it decides anything, so the poll loop cannot get back
4551/// to its own `stopped()` test until that walk is over — and a loop already
4552/// on its way out must not make the operator wait out housekeeping it is
4553/// about to stop needing. This is the same call the idle branch makes when it
4554/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
4555/// it matters more here: `busy_now()` is false throughout, so
4556/// [`Stop::finishing`] would report a stop as already landed while the walk
4557/// still held the loop. Nothing is lost by skipping — the cap is a standing
4558/// policy, and the next daemon's startup pass measures the same cache.
4559///
4560/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
4561/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
4562/// and the next has not yet claimed a task, which can be every few
4563/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
4564/// more than the growth it is guarding against.
4565async fn maybe_prune_cache_between_runs(
4566    repo: &Path,
4567    opts: &Opts,
4568    home: &Path,
4569    stop: &Stop,
4570    last_checked: &mut Option<Timestamp>,
4571    now: Timestamp,
4572) {
4573    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
4574        return;
4575    }
4576    *last_checked = Some(now);
4577    let cfg = match prepare(repo, opts) {
4578        Ok(cfg) => cfg,
4579        Err(e) => {
4580            tracing::warn!("cache check: no config: {e:#}");
4581            return;
4582        }
4583    };
4584    match clean::prune_cache_if_over_limit(&cfg, home) {
4585        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
4586            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
4587            pruned.files,
4588            pruned.freed
4589        ),
4590        Ok(_) => {}
4591        Err(e) => {
4592            tracing::warn!("housekeep: prune cache: {e:#}");
4593            notices::raise_in(
4594                home,
4595                Notice::warn(
4596                    "housekeep:cache",
4597                    "Pruning the shared build cache failed; disk usage may keep growing.",
4598                ),
4599            );
4600        }
4601    }
4602}
4603
4604/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
4605/// now, given when it last did (if ever). Pure, so the cadence is asserted
4606/// directly rather than by waiting out real minutes in a test.
4607fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
4608    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
4609}
4610
4611/// The disk janitor, with its housekeeping logged rather than fatal.
4612///
4613/// Called only at the loop's idle points, for the reason the caller documents:
4614/// a prune racing a live compile would delete files mid-build. The config is
4615/// re-read on every call because the repository that just ran may not be the
4616/// daemon's own default, and the cache directory is a repository fact.
4617///
4618/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
4619/// and [`crate::run::default_worktree_root`] read here, for the same reason
4620/// [`drive`] takes its queue and status file rather than resolving them: a
4621/// test driving the loop must not reach through to the operator's real home
4622/// or worktree bay just because the janitor runs on every idle tick.
4623/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
4624/// to get wrong silently - a test's `home` was already isolated, but nothing
4625/// exercised the parameter next to it, so a real worktree bay stayed wired in
4626/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
4627/// it for real, every test in this file that drives the loop at all started
4628/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
4629async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
4630    let cfg = match prepare(repo, opts) {
4631        Ok(cfg) => cfg,
4632        Err(e) => {
4633            tracing::warn!("housekeep: no config: {e:#}");
4634            return;
4635        }
4636    };
4637    // A run's own worktree lives under `config.graph.worktree_root` when the
4638    // repository sets one - the same precedence `RunState::worktree_root`
4639    // uses - and `worktrees_root` only stands in for the *default* an
4640    // unconfigured repository resolves to (see this function's own
4641    // parameter, or the test fixture wiring one to a fake path). Housekeeping
4642    // that always swept the default regardless of this override would never
4643    // see, and so never reclaim, a single worktree for a repository that
4644    // relocated them elsewhere.
4645    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
4646    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
4647    // Reported whenever there is anything to say, not only when `folded > 0`:
4648    // the incident this exists to prevent was 90 of 93 runs skipped and 0
4649    // folded, on every single pass, for months - a report gated on `folded`
4650    // would have stayed silent through every one of them.
4651    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
4652        let mut extra = Vec::new();
4653        if out.unreadable > 0 {
4654            extra.push(format!("{} unreadable", out.unreadable));
4655        }
4656        if out.orphaned_worktrees > 0 {
4657            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
4658        }
4659        let detail = if extra.is_empty() {
4660            String::new()
4661        } else {
4662            format!(" ({})", extra.join(", "))
4663        };
4664        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
4665    }
4666    if out.external_merges_recorded > 0 {
4667        tracing::info!(
4668            "housekeep: recorded {} run(s) as merged externally",
4669            out.external_merges_recorded
4670        );
4671    }
4672    if out.stale_pr_states_repaired > 0 {
4673        tracing::info!(
4674            "housekeep: rewrote {} run record(s) whose pull request had already settled",
4675            out.stale_pr_states_repaired
4676        );
4677    }
4678    if out.cache_files > 0 {
4679        tracing::info!(
4680            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
4681            out.cache_files,
4682            out.cache_freed
4683        );
4684    }
4685    if out.questions_abandoned > 0 {
4686        tracing::info!(
4687            "housekeep: abandoned {} question(s) left open by a finished run",
4688            out.questions_abandoned
4689        );
4690    }
4691}
4692
4693/// Run [`triage::run_once`] and log whatever it did, the same "only when
4694/// there is something to say" rule [`janitor`] follows for its own report.
4695///
4696/// Called at the same idle points as [`janitor`] - once per full poll
4697/// interval, never mid-attempt - for the same reason: it is not liveness
4698/// critical, and a task's own `hold_reason` string is the one thing this
4699/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
4700/// tick for no benefit.
4701async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
4702    let questions = Questions::at(home.join("questions"));
4703    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
4704    if report.is_empty() {
4705        return;
4706    }
4707    if !report.quarantined.is_empty() {
4708        tracing::info!(
4709            "triage: held {} blocked task(s) whose blocked-on task or \
4710             question no longer exists: {}",
4711            report.quarantined.len(),
4712            report.quarantined.join(", ")
4713        );
4714    }
4715    if !report.resumed.is_empty() {
4716        tracing::info!(
4717            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
4718            report.resumed.len(),
4719            report.resumed.join(", ")
4720        );
4721    }
4722    if !report.asked.is_empty() {
4723        tracing::info!(
4724            "triage: asked about {} held task(s): {}",
4725            report.asked.len(),
4726            report.asked.join(", ")
4727        );
4728    }
4729    if !report.answered.is_empty() {
4730        tracing::info!(
4731            "triage: applied {} operator answer(s): {}",
4732            report.answered.len(),
4733            report.answered.join(", ")
4734        );
4735    }
4736}
4737
4738/// The free-space gate: what stands between this task and a new run, if
4739/// anything. `Some(reason)` holds the task; `None` lets it start.
4740///
4741/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
4742/// the operator opted out. A measurement failure is a gate, not a pass: both
4743/// sides of "cannot tell" are served by not starting.
4744pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
4745    disk_gate_with(repo, config, crate::disk::free_bytes)
4746}
4747
4748/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
4749/// test can assert the exact wiring `attempt` runs - config's threshold in,
4750/// task-holding reason out - without asking the real machine's disk anything.
4751fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
4752    repo: &Path,
4753    config: &Config,
4754    free_bytes: F,
4755) -> Option<String> {
4756    let min = config.disk.min_free_bytes;
4757    if min == 0 {
4758        return None;
4759    }
4760    let mut paths = vec![repo.to_owned()];
4761    if let Some(cache) = config.cache_dir() {
4762        paths.push(cache);
4763    }
4764    if let Some(root) = &config.graph.worktree_root {
4765        paths.push(root.clone());
4766    }
4767    for path in paths {
4768        let probe = if path == repo {
4769            path.as_path()
4770        } else {
4771            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
4772        };
4773        let reason = match free_bytes(probe) {
4774            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
4775            Err(e) => Some(crate::disk::unmeasured_in(
4776                probe,
4777                &e,
4778                &config.graph.language,
4779            )),
4780        };
4781        if reason.is_some() {
4782            return reason;
4783        }
4784    }
4785    None
4786}
4787
4788/// How long to wait before offering another task when a run lost a seat to a
4789/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
4790/// could read, or carried nothing at all. Long enough that a quota outage
4791/// cannot burn through a whole backlog in the few seconds each doomed attempt
4792/// takes to fail; short enough that a quota which clears early is not left
4793/// idle for the fallback's sake.
4794const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
4795
4796/// Longest a parsed reset hint may push the wait out to. The hint comes from
4797/// the CLI's own words, not a contract, so a parsing slip that lands a day
4798/// away must not leave the loop asleep for a day.
4799const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
4800
4801/// How long [`poll`] should wait before offering the next task, after a run
4802/// lost at least one seat to a rate limit.
4803///
4804/// Pure and separate from the loop so the policy can be exercised without a
4805/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
4806/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
4807/// nothing to parse, or the parsed time has already passed; `cap` bounds how
4808/// far a parsed hint is trusted to push the wait out.
4809fn quota_wait(
4810    reset_at: Option<Timestamp>,
4811    now: Timestamp,
4812    fallback: Duration,
4813    cap: Duration,
4814) -> Duration {
4815    match reset_at {
4816        Some(at) if at > now => {
4817            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
4818            Duration::from_secs(secs).min(cap)
4819        }
4820        _ => fallback,
4821    }
4822}
4823
4824/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
4825///
4826/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
4827/// explains why parsing it exactly "would be a bug factory" — so this only
4828/// recognises the shapes actually observed in the wild, and returns `None`
4829/// for anything else rather than guess at a format nobody has seen.
4830///
4831/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
4832/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
4833/// said it, not from whenever this loop happens to read it: anchoring on `now`
4834/// would push the reset later on every read and would read an already-elapsed
4835/// reset as still in the future. (A long hint is still clamped by
4836/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
4837fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
4838    parse_reset_hint_zoned(text, now)
4839        .or_else(|| parse_reset_hint_dated(text))
4840        .or_else(|| parse_reset_hint_relative(text, recorded))
4841}
4842
4843/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
4844/// optional but at least one required, in that order. A bare number or any
4845/// unknown unit is refused.
4846fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
4847    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
4848    let mut rest = rest.trim();
4849    if rest.is_empty() {
4850        return None;
4851    }
4852    let mut total: i64 = 0;
4853    let mut matched = false;
4854    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
4855        if let Some((digits, tail)) = rest.split_once(unit)
4856            && !digits.is_empty()
4857            && digits.bytes().all(|b| b.is_ascii_digit())
4858        {
4859            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
4860            rest = tail;
4861            matched = true;
4862        }
4863    }
4864    if !rest.is_empty() || !matched {
4865        return None;
4866    }
4867    recorded
4868        .checked_add(jiff::SignedDuration::from_secs(total))
4869        .ok()
4870}
4871
4872/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
4873/// case-insensitive) into a 24-hour hour and minute. Shared by every
4874/// reset-hint shape below.
4875fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
4876    let clock = clock.trim().to_lowercase();
4877    let (digits, pm) = clock
4878        .strip_suffix("am")
4879        .map(|d| (d, false))
4880        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
4881    let (h, m) = digits.trim().split_once(':')?;
4882    let mut hour: i8 = h.trim().parse().ok()?;
4883    let minute: i8 = m.trim().parse().ok()?;
4884    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
4885        return None;
4886    }
4887    if pm && hour != 12 {
4888        hour += 12;
4889    } else if !pm && hour == 12 {
4890        hour = 0;
4891    }
4892    Some((hour, minute))
4893}
4894
4895/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
4896/// and a zone, never a date. A clock reading already past today is read as
4897/// tomorrow's: a CLI naming a same-day reset that has already gone by means
4898/// the window rolled over while nothing was watching.
4899fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
4900    let open = text.find('(')?;
4901    let close = text.rfind(')')?;
4902    if close <= open {
4903        return None;
4904    }
4905    let zone = text[open + 1..close].trim();
4906    let (hour, minute) = parse_12h_clock(&text[..open])?;
4907    let tz = jiff::tz::TimeZone::get(zone).ok()?;
4908    let candidate = now
4909        .to_zoned(tz)
4910        .with()
4911        .hour(hour)
4912        .minute(minute)
4913        .second(0)
4914        .millisecond(0)
4915        .microsecond(0)
4916        .nanosecond(0)
4917        .build()
4918        .ok()?;
4919    let mut at = candidate.timestamp();
4920    if at <= now {
4921        at += jiff::SignedDuration::from_hours(24);
4922    }
4923    Some(at)
4924}
4925
4926/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
4927/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
4928/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
4929/// "already past today" correction to make: the year already disambiguates
4930/// it. Scanned as a five-word window so it can be pulled out of the middle
4931/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
4932/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
4933/// any other timestamp with no zone attached.
4934fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4935    let words: Vec<&str> = text.split_whitespace().collect();
4936    if words.len() < 5 {
4937        return None;
4938    }
4939    (0..=words.len() - 5)
4940        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4941}
4942
4943/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
4944/// parenthesis right after the window is refused rather than ignored — it
4945/// reads as an explicit zone annotation on a shape that otherwise carries
4946/// none, and guessing UTC anyway would be exactly the silent misread this
4947/// module's parsing otherwise avoids.
4948fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4949    if trailing.is_some_and(|next| next.starts_with('(')) {
4950        return None;
4951    }
4952    let month = month_number(window[0])?;
4953    let day_token = window[1].strip_suffix(',')?.to_lowercase();
4954    let day_digits = ["st", "nd", "rd", "th"]
4955        .iter()
4956        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4957    let day: i8 = day_digits.parse().ok()?;
4958    let year_token = window[2];
4959    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4960        return None;
4961    }
4962    let year: i16 = year_token.parse().ok()?;
4963    // The am/pm word carries the sentence's own trailing punctuation, e.g.
4964    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
4965    // reusing the same 12-hour clock reader the bracketed shape uses.
4966    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4967    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4968    let date = jiff::civil::Date::new(year, month, day).ok()?;
4969    let candidate = date
4970        .at(hour, minute, 0, 0)
4971        .to_zoned(jiff::tz::TimeZone::UTC)
4972        .ok()?;
4973    Some(candidate.timestamp())
4974}
4975
4976/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
4977/// case-insensitively, into a 1-based month number.
4978fn month_number(name: &str) -> Option<i8> {
4979    const NAMES: [&str; 12] = [
4980        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4981    ];
4982    let lower = name.to_lowercase();
4983    NAMES
4984        .iter()
4985        .position(|n| *n == lower.as_str())
4986        .map(|i| i as i8 + 1)
4987}
4988
4989/// Test probe for the shared resume policy's review-budget exclusion.
4990#[cfg(test)]
4991fn exhausted_review_budget(state: &RunState) -> bool {
4992    // A run whose task-head publication failed has nothing left to review:
4993    // resuming it only retries the publication, so it is never "exhausted".
4994    !crate::handover::can_resume(state)
4995        && state.status == RunStatus::Blocked
4996        && !state.released()
4997        && state.retired_to.is_none()
4998}
4999
5000/// This task's *most recent* run, if resuming it would actually make
5001/// progress. `short` is only for the warning's own message.
5002///
5003/// Only ever `runs.last()` — never a search back through older history.
5004/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5005/// mint, oldest first, and every entry before the last one was already
5006/// superseded at the moment it was minted: the daemon only ever starts a new
5007/// run when the previous one was not worth resuming (unresumable, exhausted,
5008/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5009/// opens a fresh review-only run alongside an older, already-failed
5010/// competition. Searching further back would let an old run that merely
5011/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5012/// behind, say — get resumed instead of the fresh competition
5013/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5014/// nothing asked to revisit.
5015///
5016/// Two runs paid for the "prefer resuming over restarting" half of this
5017/// lesson, which is why this still checks `runs.last()` rather than always
5018/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5019/// task a moment later, duplicating two and a half hours of agent work. Then
5020/// b25f stalled on a judge that timed out and one that answered with no JSON
5021/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5022/// **one second** later, buying three fresh implementations to reach the
5023/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5024/// the second case: a stall is terminal, and its cheap recovery re-asks only
5025/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5026/// that is technically `resumable()` but provably cannot progress must not
5027/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5028/// no-op instead of the fresh competition it promises.
5029///
5030/// A load failure is warned about rather than silently read as "not
5031/// resumable": the alternative is exactly what let a schema mismatch on run
5032/// `eba2` fall through to a full re-competition with nobody told why.
5033/// `crate::conduct` is what actually offers a better answer than
5034/// `Runner::start` here (see `Recovery::Review`), once this task's next
5035/// failure shows it up as `held`/`failed` with the run state unreadable.
5036fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5037    unfinished_run_with(runs, short, RunState::load)
5038}
5039
5040/// [`unfinished_run`] with an injected state reader. Tests provide their
5041/// fixtures directly rather than touching the process-global run home.
5042pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5043where
5044    F: FnMut(&str) -> Result<RunState>,
5045{
5046    let mut id = runs.last()?.clone();
5047    let mut visited = std::collections::BTreeSet::new();
5048    let mut repo = None;
5049    loop {
5050        if !runs.contains(&id) || !visited.insert(id.clone()) {
5051            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5052            return None;
5053        }
5054        let state = match load(&id) {
5055            Ok(state) if state.id == id => state,
5056            Ok(_) => return None,
5057            Err(e) => {
5058                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5059                return None;
5060            }
5061        };
5062        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5063            return None;
5064        }
5065        repo = Some(state.repo.clone());
5066        if let Some(authority) = state.retired_to {
5067            id = authority;
5068            continue;
5069        }
5070        return (crate::handover::can_resume(&state)
5071            && state.liveness(false) != crate::run::Liveness::Live)
5072            .then_some(id);
5073    }
5074}
5075
5076/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5077/// that [`attempt`] will resume it on its own?
5078///
5079/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5080/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5081/// injected reader like its sibling. An unreadable run is not awaiting
5082/// anything: it keeps going to the conductor as before.
5083fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5084where
5085    F: FnOnce(&str) -> Result<RunState>,
5086{
5087    // `Failed` stays: a record an older build wrote for a parked run.
5088    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5089        || task.fresh_start
5090        || task.review_branch.is_some()
5091    {
5092        return false;
5093    }
5094    let Some(id) = task.runs.last() else {
5095        return false;
5096    };
5097    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5098}
5099
5100/// Which of the three ways [`attempt`] can mint or continue a run this task
5101/// should use.
5102#[derive(Debug, Clone, PartialEq, Eq)]
5103enum Starter {
5104    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5105    /// and that still exists.
5106    Review(String),
5107    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5108    Resume(String),
5109    /// `crate::graph::Runner::start`: a fresh competition.
5110    Start,
5111}
5112
5113/// A second bound independent of inputs and the resettable failure counter.
5114/// Count recovery records, not history entries: resuming appends the same id.
5115/// Unknown history is not evidence that a new set of worktrees is affordable.
5116fn retained_attempt_hold(
5117    task: &Task,
5118    starter: &Starter,
5119    limit: usize,
5120    mut load: impl FnMut(&str) -> Result<RunState>,
5121) -> Option<String> {
5122    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5123        return None;
5124    }
5125    let mut retained = 0;
5126    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5127        let state = match load(id) {
5128            Ok(state) if state.id == *id => state,
5129            _ => {
5130                return Some(format!(
5131                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5132                ));
5133            }
5134        };
5135        if state.retired_to.is_some() || state.released() {
5136            continue;
5137        }
5138        // Neither a completed status nor an empty candidate array proves that
5139        // all recovery sources (including unrecorded preparation) were retired.
5140        retained += 1;
5141    }
5142    (retained >= limit).then(|| format!(
5143        "[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."
5144    ))
5145}
5146
5147/// A selected public implementation overrides every historical candidate and pin.
5148fn selected_starter(
5149    selected: &crate::pr_recovery::Selection,
5150    previous: Option<&RunState>,
5151    unfinished: Option<&str>,
5152) -> Starter {
5153    if let Some(id) = unfinished
5154        && previous.is_some_and(|r| {
5155            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5156        })
5157    {
5158        Starter::Resume(id.to_owned())
5159    } else {
5160        Starter::Review(selected.branch.clone())
5161    }
5162}
5163
5164/// The owner's answer to this branch's divergence question, consumed from the
5165/// task so a later, different divergence asks again. The runner applies it
5166/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5167fn take_divergence_answer(
5168    branch: &str,
5169    remote: &str,
5170    task: &mut Task,
5171) -> Option<crate::reconcile::Choice> {
5172    let summary = crate::reconcile::summary_for(branch, remote);
5173    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5174        (a.question == summary)
5175            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5176            .flatten()
5177            .map(|c| (i, c))
5178    })?;
5179    task.answers.remove(idx);
5180    Some(choice)
5181}
5182
5183/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5184/// this attempt should use. Pure, and separate from [`attempt`], so the
5185/// routing itself is assertable without spawning a real graph or a git
5186/// process: `attempt`'s own `crate::git::branch_exists` call has already
5187/// happened by the time this is called.
5188///
5189/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5190/// whose branch is gone falls all the way through to [`Starter::Start`], not
5191/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5192/// old (likely `Blocked`) run in the first place, and a branch that vanished
5193/// out from under that choice is not evidence resuming it would fare better.
5194fn choose_starter(
5195    review_branch: Option<&str>,
5196    branch_exists: bool,
5197    unfinished: Option<&str>,
5198) -> Starter {
5199    match review_branch {
5200        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5201        Some(_) => Starter::Start,
5202        None => match unfinished {
5203            Some(id) => Starter::Resume(id.to_owned()),
5204            None => Starter::Start,
5205        },
5206    }
5207}
5208
5209/// Consume a retained review only while its authored criteria still match.
5210fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5211    let branch = task.review_branch.take();
5212    let instruction = task.review_instruction.take();
5213    branch.filter(|branch| match &instruction {
5214        Some(authored) => *authored == task.instruction,
5215        // Legacy retained branches must agree with their prior run; only an
5216        // explicitly pinned review can proceed without recoverable provenance.
5217        None => previous.map_or_else(
5218            || task.review_of.as_ref() == Some(branch),
5219            |run| compatible_run_instruction(run, task),
5220        ),
5221    })
5222}
5223
5224/// A current explicit pin can select an otherwise incompatible run. Edits
5225/// and subsequent approvals invalidate pins selected for earlier criteria.
5226fn may_resume_run(run: &RunState, task: &Task) -> bool {
5227    task.resume_override
5228        .as_ref()
5229        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5230        || compatible_run_instruction(run, task)
5231}
5232
5233/// Review scaffolding is execution context, not evidence of an operator edit.
5234pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5235    if let Some(authored) = &run.task_instruction {
5236        return compatible_instruction(authored, task);
5237    }
5238    if compatible_instruction(&run.instruction, task) {
5239        return true;
5240    }
5241    // Recognize only the existing generated review shapes on legacy runs.
5242    // Ordinary authored text with a similar heading is left intact.
5243    if run.reviewed_commits.is_some() {
5244        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5245            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5246        }
5247        if let Some(branch) = &task.review_of {
5248            let canonical = format!(
5249                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5250            );
5251            let generated = format!(
5252                "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"
5253            );
5254            return task.instruction == canonical && run.instruction.starts_with(&generated);
5255        }
5256    }
5257    false
5258}
5259
5260/// Compare authored instructions, excluding answer blocks appended by the daemon.
5261pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5262    strip_answers_block(old, task) == task.instruction
5263}
5264
5265/// Which repository a task runs in. A task that names none — the normal case
5266/// for one filed from a phone — runs in the daemon's own default.
5267fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5268    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5269        return fallback.to_path_buf();
5270    }
5271    task.repo.clone()
5272}
5273
5274/// The header [`append_answers`] appends operator answers under. Shared with
5275/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5276/// rather than grown a new block on every resume.
5277const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5278
5279/// Render the first `count` answers in the block appended to an instruction.
5280fn answers_block(task: &Task, count: usize) -> String {
5281    let mut s = ANSWERS_HEADER.to_owned();
5282    for a in &task.answers[..count] {
5283        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5284    }
5285    s
5286}
5287
5288/// Render the approval independently of transient task state, so historical
5289/// suffixes remain recognizable after another explicit release.
5290fn resumption_block(r: &crate::queue::Resumption) -> String {
5291    format!(
5292        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5293         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5294        r.generation, r.at, r.instruction, r.answers_through,
5295    )
5296}
5297
5298/// Append audit answers and the latest explicit approval to the instruction.
5299fn append_answers(base: &str, task: &Task) -> String {
5300    let mut s = base.to_owned();
5301    if !task.answers.is_empty() {
5302        s.push_str(&answers_block(task, task.answers.len()));
5303    }
5304    if let Some(r) = &task.resumption {
5305        s.push_str(&resumption_block(r));
5306    }
5307    s
5308}
5309
5310/// Drop the prior answer block only when it is exactly the suffix this task
5311/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5312/// the task author is ordinary instruction text, not a block to remove.
5313fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5314    let mut instruction = instruction;
5315    for approval in task
5316        .resumption
5317        .iter()
5318        .chain(task.resumption_history.iter().rev())
5319    {
5320        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5321            instruction = base;
5322            break;
5323        }
5324    }
5325    for count in (1..=task.answers.len()).rev() {
5326        let block = answers_block(task, count);
5327        if let Some(base) = instruction.strip_suffix(&block) {
5328            return base;
5329        }
5330    }
5331    instruction
5332}
5333
5334/// The instruction handed to `Runner::start`: the task's own text, plus any
5335/// operator answers `crate::conduct` collected for it (see
5336/// [`Task::answers`]), so a decision the operator actually made reaches the
5337/// implementers rather than only clearing the block that was waiting on it.
5338///
5339/// Appended rather than merged into [`Task::instruction`] itself, so the
5340/// task's own record stays exactly what its author wrote.
5341fn instruction_for(task: &Task) -> String {
5342    append_answers(&task.instruction, task)
5343}
5344
5345/// The instruction a resumed run should carry on with: whatever it already
5346/// had, refreshed with the task's *current* operator answers.
5347///
5348/// A resumable run's own `RunState::instruction` predates any answer
5349/// `crate::conduct` collects after the run parks, so resuming it unchanged —
5350/// the behaviour before this function existed — silently drops the very
5351/// decision the operator made to unblock it. Re-stripping any block this
5352/// function appended on an earlier resume before re-appending the current
5353/// list (rather than blindly appending again) is what keeps a task resumed
5354/// three times over three answered questions from carrying the same answer
5355/// three times.
5356fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5357    append_answers(strip_answers_block(old_instruction, task), task)
5358}
5359
5360/// Preserve the producer's verified boundary and target, independent of prose.
5361fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5362    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5363    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5364    if let Some(cause) = task.hold_notice_cause.as_mut() {
5365        cause.target = failure.map(|f| f.target.clone());
5366    }
5367}
5368
5369#[derive(Debug, thiserror::Error)]
5370#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5371struct MissingAttachment {
5372    name: String,
5373    path: PathBuf,
5374}
5375
5376/// The task's attachments as absolute paths, each checked to still exist.
5377fn task_attachments(
5378    queue: &Queue,
5379    task: &Task,
5380) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5381    let paths = queue.attachment_paths(task);
5382    for (name, path) in task.attachments.iter().zip(&paths) {
5383        if !path.is_file() {
5384            return Err(MissingAttachment {
5385                name: name.clone(),
5386                path: path.clone(),
5387            });
5388        }
5389    }
5390    Ok(paths)
5391}
5392
5393/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
5394/// answers before handing it to `Runner` — the actual boundary between
5395/// [`choose_starter`]'s routing and the graph, factored out so it is
5396/// assertable without a real repository, git branch, or agent CLI.
5397///
5398/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
5399/// instruction from the reviewed branch's own commit log because there is no
5400/// task statement to speak of for hand-written work, and splicing operator
5401/// answers into that text would contradict the very message it sends
5402/// reviewers ("there is no task statement").
5403fn prepare_instruction(
5404    starter: &Starter,
5405    old_instruction: Option<&str>,
5406    task: &Task,
5407) -> Option<String> {
5408    match starter {
5409        Starter::Start => Some(instruction_for(task)),
5410        Starter::Resume(_) => Some(resumed_instruction(
5411            old_instruction.expect("a resumed run always has a prior instruction"),
5412            task,
5413        )),
5414        Starter::Review(_) => None,
5415    }
5416}
5417
5418/// Persist a transition. A queue write failure is logged rather than fatal: the
5419/// run already happened, and taking the daemon down would only add a lost
5420/// backlog to a full disk.
5421fn record(queue: &Queue, task: &mut Task) {
5422    if let Err(e) = queue.put(task) {
5423        tracing::error!("could not record task {}: {e:#}", task.short());
5424        let notice = Notice::error(
5425            "loop:record",
5426            "The loop could not save a task's state; check the disk.",
5427        )
5428        .link(Link::Task {
5429            id: task.id.clone(),
5430        });
5431        // The queue lives at `<home>/queue`, so its parent is the home.
5432        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
5433            Some(home) => notices::raise_in(home, notice),
5434            None => notices::raise(notice),
5435        }
5436    }
5437}
5438
5439/// Every runnable task, in the order the loop should try them.
5440///
5441/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
5442/// tail exists so that a claim somebody else holds costs the loop the next
5443/// candidate rather than a whole poll interval of idleness.
5444fn runnable(queue: &Queue) -> Vec<Task> {
5445    let mut tasks: Vec<Task> = queue
5446        .list()
5447        .into_iter()
5448        .filter(|t| t.status.runnable())
5449        .collect();
5450    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
5451    tasks
5452}
5453
5454/// Why a run ended where it did, in one line, for [`Task::last_error`].
5455///
5456/// A stalled run names the seats the quota took out: "out of quota" is not
5457/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
5458/// agent to replace or which plan to top up.
5459///
5460/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
5461/// purpose: unlike `label`'s other callers (an internal log line, an
5462/// already-a-bug fallback message), this string becomes `Task::last_error`
5463/// verbatim, which the phone renders in the same alarm-styled box an
5464/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
5465/// `.err` styling. A bare `verified_noop` there would read exactly like the
5466/// failure this whole feature exists to tell apart from one.
5467fn describe(state: &RunState) -> String {
5468    let p = phrases(&state.config.graph.language);
5469    let mut detail = if state.status == RunStatus::Stalled {
5470        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
5471        seats.sort_unstable();
5472        seats.dedup();
5473        if seats.is_empty() {
5474            p.quorum_lost.to_owned()
5475        } else {
5476            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
5477        }
5478    } else {
5479        format!("{}{}", p.run_ended, state.status.display_label())
5480    };
5481    if let Some(last) = state.events.last() {
5482        // The review loop's "never answered" stop is the one event worth
5483        // translating; it is recognised from structured state, not by
5484        // matching the English event text (which stays as recorded).
5485        let unanswered = state
5486            .reviews
5487            .last()
5488            .filter(|r| {
5489                state.status == RunStatus::Blocked
5490                    && last.node == "review"
5491                    && r.incomplete()
5492                    && r.blocking == 0
5493                    && r.round == state.config.graph.review_rounds
5494                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
5495            })
5496            .map(|r| (r.expected - r.answered, r.round));
5497        match unanswered {
5498            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
5499                detail.push_str(&format!(
5500                    " ({}: {})",
5501                    last.node,
5502                    (p.reviewers_never_answered)(missing, rounds)
5503                ));
5504            }
5505            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
5506        }
5507    }
5508    detail.push_str(&format!(" [run {}]", state.id));
5509    detail
5510}
5511
5512/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
5513///
5514/// The task file lives in the backlog indefinitely; a diagnostic is an
5515/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
5516/// stay small regardless of how much a gate command or a candidate printed.
5517const DIAGNOSTIC_MAX: usize = 4_000;
5518
5519/// Tail kept from a single failing command's output inside a diagnostic.
5520/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
5521/// pointer for a human deciding whether to go read the full artifact by hand,
5522/// not a replacement for reading it.
5523const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
5524
5525/// Assemble a bounded diagnostic excerpt from a held task's own run, so
5526/// `magi task show` says more than the one-line reason in [`describe`].
5527///
5528/// The one-liner answers "where did the run stop"; this answers "what would a
5529/// human have found opening `artifacts/` by hand" — the point of the whole
5530/// feature is the case that one-liner actively misleads on: a run held as "no
5531/// candidate produced a change" can mean the implementer actually finished
5532/// the task (opened a PR, merged it, tagged a release) and only left a clean
5533/// local worktree behind, which reads as "nothing happened" unless someone
5534/// goes and reads what the agent actually said. `None` when the run carries
5535/// none of the three shapes this recognises — an ordinary run held for
5536/// something not diagnosable from `RunState` alone still explains itself
5537/// through `Task::last_error`.
5538fn diagnostic(state: &RunState) -> Option<String> {
5539    let mut parts: Vec<String> = Vec::new();
5540
5541    // Gate failure: which check(s), and the tail of what each printed.
5542    for o in state.gate.iter().filter(|o| !o.ok()) {
5543        parts.push(format!(
5544            "gate `{}` failed ({}):\n{}",
5545            o.command,
5546            notices::exit_status(o.code),
5547            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
5548        ));
5549    }
5550
5551    // The land loop gave up because the fixer declined while checks were
5552    // still red: the message already names them (see `land::run`).
5553    if let Some(last) = state
5554        .events
5555        .iter()
5556        .rev()
5557        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
5558    {
5559        parts.push(last.message.clone());
5560    }
5561
5562    // No viable candidate: every implementer's own final word, sanitized the
5563    // same way a judge would have read it, so a run that actually finished
5564    // the job does not read as an unexplained failure. A verified no-op is
5565    // called out ahead of its own summary and apart from an ordinary
5566    // failure's `why` — this is the one candidate shape whose diagnostic a
5567    // human is expected to actually judge, not just skim.
5568    if state.viable().is_empty() {
5569        for c in &state.candidates {
5570            if let Some(evidence) = &c.verified_noop {
5571                parts.push(format!(
5572                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
5573                    c.label
5574                ));
5575            } else if !c.summary.trim().is_empty() {
5576                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
5577            } else if let Some(why) = &c.failed {
5578                parts.push(format!("candidate {}: {why}", c.label));
5579            }
5580        }
5581    }
5582
5583    if parts.is_empty() {
5584        return None;
5585    }
5586    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
5587    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
5588    // back slightly over. Leave it enough room to always land under the
5589    // limit.
5590    Some(crate::run::tail(
5591        &parts.join("\n\n"),
5592        DIAGNOSTIC_MAX.saturating_sub(100),
5593    ))
5594}
5595
5596/// Stable lower-case name for a run status, for an internal log line and the
5597/// "graph stopped without reaching a terminal status" bug message in
5598/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
5599/// doc for why that one reads [`RunStatus::display_label`] instead. One
5600/// definition of a status's name, on the type that owns it: this table used
5601/// to live here as a second copy, and a status renamed in one place would
5602/// have gone on reading correctly in the other.
5603fn label(status: RunStatus) -> &'static str {
5604    status.as_str()
5605}
5606
5607/// Parse a merge mode override.
5608pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
5609    match mode {
5610        "none" => Ok(MergeMode::None),
5611        "local" => Ok(MergeMode::Local),
5612        "pr" => Ok(MergeMode::Pr),
5613        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
5614    }
5615}
5616
5617/// Take the status lock, recovering from a poisoned one.
5618///
5619/// A panic elsewhere must not silently stop the heartbeat: the status is plain
5620/// data, and the worst a poisoned lock can hold is a stale timestamp.
5621fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
5622    mutex
5623        .lock()
5624        .unwrap_or_else(std::sync::PoisonError::into_inner)
5625}
5626
5627#[cfg(test)]
5628mod tests {
5629    use super::*;
5630    use crate::queue::{Source, TaskStatus};
5631    use crate::run::{Candidate, CommandOutcome};
5632    use pretty_assertions::assert_eq;
5633
5634    fn task() -> Task {
5635        Task::new(
5636            "add retries".to_owned(),
5637            "add retries".to_owned(),
5638            PathBuf::from("/repo"),
5639            Source::Human,
5640        )
5641    }
5642
5643    #[test]
5644    fn selected_public_head_overrides_historical_resume_and_pin() {
5645        let mut t = task();
5646        let mut old = run_state(RunStatus::Blocked);
5647        let selection = crate::pr_recovery::Selection {
5648            url: "url".into(),
5649            branch: format!("magi/task-{}", t.id),
5650            head: "a".repeat(40),
5651            source_head: None,
5652            source_run: None,
5653            source_proof: None,
5654            disposition: Some(crate::pr_recovery::Disposition::Review),
5655            instruction: t.instruction.clone(),
5656            approved_at: Timestamp::now(),
5657        };
5658        t.resume_override = Some(crate::queue::OperatorResume {
5659            pinned_run: Some(old.id.clone()),
5660            question_id: "choice".into(),
5661            at: Timestamp::now(),
5662            conductor_rehold: None,
5663            forced: false,
5664        });
5665        assert_eq!(
5666            selected_starter(&selection, Some(&old), Some(&old.id)),
5667            Starter::Review(selection.branch.clone())
5668        );
5669        old.pr_recovery = Some(selection.clone());
5670        assert_eq!(
5671            selected_starter(&selection, Some(&old), Some(&old.id)),
5672            Starter::Review(selection.branch.clone())
5673        );
5674        old.reviewed_commits = Some(vec!["implementation".into()]);
5675        assert_eq!(
5676            selected_starter(&selection, Some(&old), Some(&old.id)),
5677            Starter::Resume(old.id.clone())
5678        );
5679        let mut changed = selection.clone();
5680        changed.head = "b".repeat(40);
5681        assert_eq!(
5682            selected_starter(&changed, Some(&old), Some(&old.id)),
5683            Starter::Review(changed.branch)
5684        );
5685    }
5686
5687    #[test]
5688    fn candidate_transplant_failure_is_one_actionable_hold() {
5689        let dir = tempfile::tempdir().unwrap();
5690        let q = Queue::at(dir.path().join("queue"));
5691        let mut t = task();
5692        let mut state = run_state(RunStatus::Blocked);
5693        state.event("prep", "cannot apply referenced commit: conflict");
5694        state.prep_failure = Some("conflict".into());
5695        t.start(state.id.clone());
5696        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
5697        assert_eq!(t.attempts, 1);
5698        assert_eq!(t.status, TaskStatus::Held);
5699        assert!(t.operator_held());
5700        assert!(!t.status.runnable());
5701        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
5702        let first = t.chat_notice_key().unwrap();
5703        t.chat_notices.push(first.clone());
5704        t.release_operator("test", None);
5705        state.id = "another-unprepared-run".into();
5706        t.start(state.id.clone());
5707        finish_attempt(
5708            3,
5709            &q,
5710            &mut t,
5711            &state,
5712            &[],
5713            Err(anyhow::anyhow!("still conflicts")),
5714        );
5715        assert_eq!(
5716            t.chat_notice_key().as_ref(),
5717            Some(&first),
5718            "no work happened"
5719        );
5720        t.release_operator("test", None);
5721        state.prep_failure = None;
5722        state.status = RunStatus::Failed;
5723        state.begin_pass();
5724        t.start(state.id.clone());
5725        finish_attempt(
5726            1,
5727            &q,
5728            &mut t,
5729            &state,
5730            &[],
5731            Err(anyhow::anyhow!("new gate failure")),
5732        );
5733        let failure = t.chat_notice_key().unwrap();
5734        assert_ne!(failure, first, "approved recovery reached a real failure");
5735        t.release_operator("test", None);
5736        state.begin_pass();
5737        t.start(state.id.clone());
5738        finish_attempt(
5739            1,
5740            &q,
5741            &mut t,
5742            &state,
5743            &[],
5744            Err(anyhow::anyhow!("new failure on resume")),
5745        );
5746        assert_ne!(
5747            t.chat_notice_key().as_ref(),
5748            Some(&failure),
5749            "a new settled pass"
5750        );
5751    }
5752
5753    #[test]
5754    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
5755        for source in ["cli", "web"] {
5756            let mut t = task();
5757            let mut run = run_state(RunStatus::Blocked);
5758            run.instruction = "Run A original criteria".into();
5759            run.task_instruction = Some(run.instruction.clone());
5760            t.start(run.id.clone());
5761            t.release_operator("choice", Some("resume-question"));
5762            t.resume_override = Some(crate::queue::OperatorResume {
5763                question_id: "resume-question".into(),
5764                at: Timestamp::now(),
5765                conductor_rehold: None,
5766                forced: true,
5767                pinned_run: Some(run.id.clone()),
5768            });
5769            t.hold_machine(Some("not enough free space to start a run".into()));
5770            let mut unchanged = t.clone();
5771            unchanged
5772                .edit("title changed".into(), unchanged.instruction.clone())
5773                .unwrap();
5774            unchanged.release_operator(source, None);
5775            assert_eq!(
5776                unchanged
5777                    .resume_override
5778                    .as_ref()
5779                    .unwrap()
5780                    .pinned_run
5781                    .as_deref(),
5782                Some(run.id.as_str())
5783            );
5784            assert!(!compatible_run_instruction(&run, &unchanged));
5785            assert!(may_resume_run(&run, &unchanged));
5786
5787            t.edit(
5788                "approved recovery".into(),
5789                "Reuse measured PR head B; fix Clippy; review".into(),
5790            )
5791            .unwrap();
5792            assert!(t.resume_override.is_none());
5793            t.release_operator(source, None);
5794            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
5795            assert!(reloaded.resume_override.is_none());
5796            assert!(!may_resume_run(&run, &reloaded));
5797            let unfinished =
5798                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
5799                    .filter(|_| may_resume_run(&run, &reloaded));
5800            assert_eq!(
5801                choose_starter(None, false, unfinished.as_deref()),
5802                Starter::Start
5803            );
5804            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
5805            assert_eq!(
5806                reloaded.resumption_history[0].question_id.as_deref(),
5807                Some("resume-question")
5808            );
5809
5810            // A revision already persisted with the old approval/pin is also
5811            // invalidated when the new operator release is recorded.
5812            unchanged.instruction = "Reuse measured PR head B".into();
5813            unchanged.hold_machine(Some("disk hold".into()));
5814            unchanged.release_operator(source, None);
5815            assert!(unchanged.resume_override.is_none());
5816            assert!(!may_resume_run(&run, &unchanged));
5817        }
5818    }
5819
5820    #[test]
5821    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
5822        let mut t = task();
5823        let mut run = run_state(RunStatus::Blocked);
5824        t.review_of = Some("approved-head".into());
5825        t.instruction =
5826            "Review the branch `approved-head` (review-only: no implementation, no judging)."
5827                .into();
5828        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();
5829        run.reviewed_commits = Some(vec!["Commit log".into()]);
5830        t.start(run.id.clone());
5831        t.hold_machine(Some("interrupted review".into()));
5832        t.release_operator("cli", None);
5833        assert!(
5834            compatible_run_instruction(&run, &t),
5835            "legacy explicit review remains resumable"
5836        );
5837        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
5838            .filter(|_| compatible_run_instruction(&run, &t));
5839        assert_eq!(
5840            choose_starter(None, false, unfinished.as_deref()),
5841            Starter::Resume(run.id.clone())
5842        );
5843        run.task_instruction = Some(t.instruction.clone());
5844        assert!(compatible_run_instruction(&run, &t));
5845        let reloaded: RunState =
5846            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
5847        assert!(compatible_run_instruction(&reloaded, &t));
5848        t.edit(
5849            "new approved head".into(),
5850            "Reuse measured PR head B".into(),
5851        )
5852        .unwrap();
5853        assert!(!compatible_run_instruction(&run, &t));
5854
5855        // Legacy recovery reviews retain the task criteria ahead of the log.
5856        t.review_of = None;
5857        t.instruction = "Fix Clippy on approved head".into();
5858        run.task_instruction = None;
5859        run.instruction = format!(
5860            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
5861            t.instruction
5862        );
5863        assert!(compatible_run_instruction(&run, &t));
5864        t.instruction.push('\n');
5865        assert!(
5866            compatible_run_instruction(&run, &t),
5867            "legacy generated review trimmed the original criteria"
5868        );
5869        t.hold_for_handover(Some("approved-head".into()), "refused".into());
5870        let mut unchanged = t.clone();
5871        assert_eq!(
5872            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
5873            Some("approved-head")
5874        );
5875        t.edit("new plan".into(), "Reuse measured PR head B".into())
5876            .unwrap();
5877        assert!(take_review_branch(&mut t, Some(&run)).is_none());
5878        assert!(!compatible_run_instruction(&run, &t));
5879        t.review_branch = Some("approved-head".into());
5880        t.review_instruction = None;
5881        assert!(
5882            take_review_branch(&mut t, Some(&run)).is_none(),
5883            "legacy retained candidate cannot replace a revised approved head"
5884        );
5885    }
5886
5887    #[test]
5888    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
5889        crate::run::pin_test_home();
5890        let dir = tempfile::tempdir().unwrap();
5891        let queue = Queue::at(dir.path().join("queue"));
5892        for resume in [true, false] {
5893            let state = run_state(RunStatus::Blocked);
5894            let mut t = task();
5895            t.start(state.id.clone());
5896            let action = if resume {
5897                ask::ChoiceAction::Resume {
5898                    run: state.id.clone(),
5899                }
5900            } else {
5901                ask::ChoiceAction::Requeue
5902            };
5903            let mut q = action_question(&state.id, action);
5904            q.status = ask::QuestionStatus::Open;
5905            q.answer = None;
5906            q.answered_at = None;
5907            t.fail("run stopped with a question", 3);
5908            hold_if_runnable(&queue, &mut t);
5909            assert!(t.operator_decided_at.is_none());
5910            assert!(t.operator_held());
5911            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
5912            let expected = if resume {
5913                ActionDecision::Resume(state.id.clone())
5914            } else {
5915                ActionDecision::Requeue
5916            };
5917            assert_eq!(
5918                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5919                expected
5920            );
5921            t.hold_manual(Some("later explicit hold".into()));
5922            assert_eq!(
5923                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5924                ActionDecision::Stale
5925            );
5926        }
5927    }
5928
5929    #[test]
5930    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
5931        let mut t = task();
5932        t.answers.push(crate::queue::AnsweredQuestion {
5933            question: "Inspect the remote?".into(),
5934            answer: "Inspect then wait".into(),
5935        });
5936        let old = instruction_for(&t);
5937        assert!(compatible_instruction(&old, &t));
5938        t.instruction = "Reuse approved PR head and review".into();
5939        t.release_operator("cli", None);
5940        assert!(!compatible_instruction(&old, &t));
5941        let approved = instruction_for(&t);
5942        assert!(approved.contains("waiting premises are superseded"));
5943        assert!(compatible_instruction(&approved, &t));
5944        assert_eq!(resumed_instruction(&approved, &t), approved);
5945        t.release_operator("web", None);
5946        assert!(compatible_instruction(&approved, &t));
5947        assert_eq!(t.resumption_history.len(), 1);
5948        t.start("run".into());
5949        assert!(instruction_for(&t).contains("Explicit operator resumption"));
5950    }
5951
5952    /// A run that stopped on an infrastructure wait asked no agent anything:
5953    /// the task is held by the machine under a `[resource]` reason (resumable,
5954    /// re-checked by triage), and the attempt it started is given back.
5955    #[test]
5956    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
5957        let mut state = RunState::new(
5958            PathBuf::from("/repo"),
5959            "main".to_owned(),
5960            "abc1234".to_owned(),
5961            "task".to_owned(),
5962            Config::default(),
5963        );
5964        state.status = RunStatus::Blocked;
5965        state.resource_block = Some(crate::run::ResourceBlock {
5966            node: "graft".to_owned(),
5967            kind: "shared build cache".to_owned(),
5968            detail: "timed out".to_owned(),
5969            at: jiff::Timestamp::now(),
5970        });
5971        let mut t = task();
5972        t.start("20260902-000000-aaaa".to_owned());
5973        assert_eq!(t.attempts, 1);
5974        let verdict = Verdict {
5975            status: RunStatus::Blocked,
5976            left_pr: false,
5977            quota_hit: false,
5978            parked: false,
5979            no_viable_candidates: false,
5980        };
5981        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5982        assert_eq!(t.status, TaskStatus::Held);
5983        assert_eq!(t.attempts, 0, "the attempt is refunded");
5984        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5985        assert!(
5986            !t.operator_held(),
5987            "a machine hold, released without a human"
5988        );
5989
5990        let mut selected = task();
5991        selected.start("20260902-000000-cccc".into());
5992        selected.replacement = Some(crate::merge_decision::Replacement {
5993            question: "fixture".into(),
5994            run: "earlier".into(),
5995            pr: "https://example.invalid/pr/1".into(),
5996            agent: "selected".into(),
5997            context: "fixture".into(),
5998        });
5999        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
6000        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
6001        assert_eq!(selected.attempts, 0);
6002        assert!(
6003            !selected.operator_held(),
6004            "a selected agent also retains a machine resource hold"
6005        );
6006        assert!(
6007            selected
6008                .hold_reason
6009                .as_deref()
6010                .unwrap()
6011                .starts_with("[resource] ")
6012        );
6013
6014        // A park request outranks it: still the operator's doing.
6015        let mut p = task();
6016        p.start("20260902-000000-bbbb".to_owned());
6017        settle_and_diagnose(
6018            &mut p,
6019            Verdict {
6020                parked: true,
6021                ..verdict
6022            },
6023            "parked",
6024            2,
6025            &state,
6026        );
6027        assert_eq!(p.status, TaskStatus::Parked);
6028    }
6029
6030    #[test]
6031    fn record_failure_notice_links_the_task() {
6032        let dir = tempfile::tempdir().unwrap();
6033        // A regular file where the queue directory should be makes every
6034        // `put` fail, on every platform and whoever runs the test.
6035        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
6036        let queue = Queue::at(dir.path().join("queue"));
6037        let mut t = interrupt_task("rec-fail-1");
6038        record(&queue, &mut t);
6039
6040        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
6041        assert_eq!(found.len(), 1);
6042        assert_eq!(found[0].key, "loop:record");
6043        assert_eq!(
6044            found[0].link,
6045            Some(Link::Task {
6046                id: "rec-fail-1".to_owned()
6047            })
6048        );
6049    }
6050
6051    /// A runnable task marked to interrupt, with an id fixed for assertions
6052    /// rather than the random one [`Task::new`] mints.
6053    fn interrupt_task(id: &str) -> Task {
6054        let mut t = task();
6055        t.id = id.to_owned();
6056        t.interrupt = true;
6057        t
6058    }
6059
6060    /// An ordinary runnable task with an id fixed for assertions.
6061    fn task_with_id(id: &str) -> Task {
6062        let mut t = task();
6063        t.id = id.to_owned();
6064        t
6065    }
6066
6067    /// A runnable task marked `--urgent`, with an id fixed for assertions.
6068    fn urgent_task(id: &str) -> Task {
6069        let mut t = task();
6070        t.id = id.to_owned();
6071        t.urgent = true;
6072        t
6073    }
6074
6075    #[test]
6076    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
6077        let dir = tempfile::tempdir().unwrap();
6078        let queue = Queue::at(dir.path().join("queue"));
6079        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6080        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6081        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
6082        let mut first = task();
6083        queue.put(&mut first).unwrap();
6084        let stale_plain = queue.get(&first.id).unwrap();
6085        first.set_urgent(true).unwrap();
6086        queue.put(&mut first).unwrap();
6087        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
6088        let mut second = urgent_task("second");
6089        queue.put(&mut second).unwrap();
6090        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
6091        drop(queue.claim(&second.id).unwrap());
6092        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
6093        drop(dispatched);
6094        let stale_urgent = queue.get(&first.id).unwrap();
6095        first.set_urgent(false).unwrap();
6096        queue.put(&mut first).unwrap();
6097        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
6098        assert_eq!(urgent.available_permits(), 1);
6099        drop(queue.claim(&first.id).unwrap());
6100        drop(occupied);
6101    }
6102
6103    #[test]
6104    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
6105        let dir = tempfile::tempdir().unwrap();
6106        let queue = Queue::at(dir.path().join("queue"));
6107        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6108        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6109        let mut t = task();
6110        queue.put(&mut t).unwrap();
6111        for enabled in [true, false] {
6112            let stale = queue.get(&t.id).unwrap();
6113            t.set_urgent(enabled).unwrap();
6114            queue.put(&mut t).unwrap();
6115            assert_ne!(stale.urgent, enabled);
6116            let DispatchClaim {
6117                task: fresh,
6118                claim,
6119                permit,
6120            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
6121            assert_eq!(fresh.urgent, enabled);
6122            assert_eq!(ordinary.available_permits(), usize::from(enabled));
6123            assert_eq!(urgent.available_permits(), usize::from(!enabled));
6124            assert!(queue.claim(&t.id).is_err());
6125            assert_eq!(fresh.attempts, stale.attempts);
6126            drop((claim, permit));
6127            assert_eq!(ordinary.available_permits(), 1);
6128            assert_eq!(urgent.available_permits(), 1);
6129        }
6130        t.set_urgent(true).unwrap();
6131        queue.put(&mut t).unwrap();
6132        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
6133        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6134        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
6135        drop(queue.claim(&t.id).unwrap());
6136        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
6137        drop(occupied);
6138        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
6139        drop(queue.claim(&t.id).unwrap());
6140        let held = queue.claim(&t.id).unwrap();
6141        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6142        drop(held);
6143        t.status = TaskStatus::Held;
6144        queue.put(&mut t).unwrap();
6145        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6146        drop(queue.claim(&t.id).unwrap());
6147        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
6148        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
6149        drop(queue.claim(&t.id).unwrap());
6150        assert_eq!(urgent.available_permits(), 1);
6151    }
6152
6153    /// The land-resume exemption wins outright, whether or not the candidate
6154    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
6155    /// queue behind anything" guarantee cannot be weaker just because the
6156    /// same task was also filed with `--urgent`.
6157    #[test]
6158    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
6159        assert_eq!(permit_kind(true, false), PermitKind::None);
6160        assert_eq!(permit_kind(true, true), PermitKind::None);
6161    }
6162
6163    /// The one property this whole feature exists for: `--urgent` draws from
6164    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
6165    /// ordinary candidate draws from the ordinary pool exactly as before,
6166    /// untouched by the urgent slot's existence.
6167    #[test]
6168    fn permit_kind_separates_urgent_from_ordinary() {
6169        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
6170        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
6171    }
6172
6173    /// The exact wiring `attempt` runs before minting anything: a config's
6174    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
6175    /// Free space is injected rather than asked of the real disk - the point
6176    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
6177    /// is deterministic on every machine this test runs on, never dependent
6178    /// on how full the CI runner's own disk happens to be.
6179    #[test]
6180    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
6181        let cfg = Config::default();
6182        let repo = Path::new("/any/repo/path");
6183
6184        let reason =
6185            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
6186        assert!(reason.contains("1024"), "{reason}");
6187        assert!(
6188            reason.contains(&cfg.disk.min_free_bytes.to_string()),
6189            "{reason}"
6190        );
6191
6192        assert_eq!(
6193            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
6194            None,
6195            "exactly at the floor is open"
6196        );
6197        assert_eq!(
6198            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
6199            None,
6200            "comfortably above the floor is open"
6201        );
6202    }
6203
6204    #[test]
6205    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
6206        let mut cfg = Config::default();
6207        cfg.disk.min_free_bytes = 0;
6208        let repo = Path::new("/any/repo/path");
6209        assert_eq!(
6210            disk_gate_with(repo, &cfg, |_| Ok(0)),
6211            None,
6212            "a zero floor never measures at all"
6213        );
6214    }
6215
6216    #[test]
6217    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
6218        let cfg = Config::default();
6219        let repo = Path::new("/any/repo/path");
6220        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
6221            .expect("a measurement failure must close the gate, not open it");
6222        assert!(reason.contains("could not measure"), "{reason}");
6223    }
6224
6225    #[test]
6226    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
6227        let ordinary = task();
6228        let next = advance_interrupt(
6229            Interrupt::Idle,
6230            std::slice::from_ref(&ordinary.id),
6231            std::slice::from_ref(&ordinary),
6232        );
6233        assert_eq!(next, Interrupt::Idle);
6234    }
6235
6236    #[test]
6237    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
6238        // Nothing to interrupt - this is just an ordinary candidate, and the
6239        // loop's normal dispatch will pick it up like any other.
6240        let marked = interrupt_task("marked");
6241        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6242        assert_eq!(next, Interrupt::Idle);
6243    }
6244
6245    #[test]
6246    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
6247        let marked = interrupt_task("marked");
6248        let next = advance_interrupt(
6249            Interrupt::Idle,
6250            &["running".to_owned()],
6251            std::slice::from_ref(&marked),
6252        );
6253        assert_eq!(
6254            next,
6255            Interrupt::Parking {
6256                parked: vec!["running".to_owned()],
6257                interrupt_task: "marked".to_owned(),
6258            }
6259        );
6260    }
6261
6262    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
6263    /// one run can be in flight when a task becomes runnable and marked.
6264    /// Parking all of them would mean `Resuming` later has more than one id
6265    /// to release back to ordinary dispatch, which cannot be made safe
6266    /// against that same setting's own extra concurrency slots letting two
6267    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
6268    /// The simplification the task's own constraints ask for: do not begin
6269    /// a sequence at all until the herd settles back to exactly one.
6270    #[test]
6271    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
6272        let marked = interrupt_task("marked");
6273
6274        let two = advance_interrupt(
6275            Interrupt::Idle,
6276            &["a".to_owned(), "b".to_owned()],
6277            std::slice::from_ref(&marked),
6278        );
6279        assert_eq!(two, Interrupt::Idle);
6280
6281        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6282        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
6283    }
6284
6285    #[test]
6286    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
6287        let state = Interrupt::Parking {
6288            parked: vec!["running".to_owned()],
6289            interrupt_task: "marked".to_owned(),
6290        };
6291        // Still in flight: no change.
6292        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
6293        assert_eq!(still_going, state);
6294
6295        // Left flight, but the interrupt task has not been dispatched yet on
6296        // this tick - stays `Parking` so `interrupt_gate` can let it through,
6297        // as long as it is still runnable.
6298        let stopped_but_not_yet_dispatched =
6299            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
6300        assert_eq!(stopped_but_not_yet_dispatched, state);
6301
6302        // Left flight, and the interrupt task is now in flight itself.
6303        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
6304        assert_eq!(
6305            dispatched,
6306            Interrupt::Running {
6307                parked: vec!["running".to_owned()],
6308                interrupt_task: "marked".to_owned(),
6309            }
6310        );
6311    }
6312
6313    #[test]
6314    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
6315        let state = Interrupt::Running {
6316            parked: vec!["running".to_owned()],
6317            interrupt_task: "marked".to_owned(),
6318        };
6319        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
6320        assert_eq!(still_running, state);
6321
6322        // Whatever it ended as - merged, failed, held - is not this
6323        // function's concern: leaving flight is the only trigger, driven
6324        // straight off the same in-flight list `poll` already reaps. It does
6325        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
6326        // why that would let an unrelated task start ahead of, or alongside,
6327        // the guaranteed resume.
6328        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
6329        assert_eq!(
6330            ended,
6331            Interrupt::Resuming {
6332                parked: vec!["running".to_owned()]
6333            }
6334        );
6335    }
6336
6337    #[test]
6338    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
6339        let state = Interrupt::Resuming {
6340            parked: vec!["running".to_owned()],
6341        };
6342        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
6343        assert_eq!(still_waiting, state);
6344
6345        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
6346        assert_eq!(dispatched, Interrupt::Idle);
6347    }
6348
6349    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
6350    /// or otherwise moved on by an operator with no claim standing in the
6351    /// way - must not wedge the sequence (and so the whole loop's dispatch,
6352    /// via `interrupt_gate`) waiting forever for a dispatch that can never
6353    /// come. The parked run still gets its resume.
6354    #[test]
6355    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
6356    {
6357        let state = Interrupt::Parking {
6358            parked: vec!["running".to_owned()],
6359            interrupt_task: "marked".to_owned(),
6360        };
6361        // `marked` has been held/blocked/deleted since the sequence began:
6362        // it no longer appears in `runnable` at all.
6363        let next = advance_interrupt(state, &[], &[]);
6364        assert_eq!(
6365            next,
6366            Interrupt::Resuming {
6367                parked: vec!["running".to_owned()]
6368            },
6369            "abandoning the interrupt must not abandon the resume it owes"
6370        );
6371    }
6372
6373    /// The same abandonment, one step later: `Resuming` itself must not wait
6374    /// forever for a parked task that has since become unrunnable.
6375    #[test]
6376    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
6377        let state = Interrupt::Resuming {
6378            parked: vec!["running".to_owned()],
6379        };
6380        let next = advance_interrupt(state, &[], &[]);
6381        assert_eq!(
6382            next,
6383            Interrupt::Idle,
6384            "nothing is left to wait for; the loop must not stay wedged"
6385        );
6386    }
6387
6388    #[test]
6389    fn disabled_by_config_the_sequence_can_never_leave_idle() {
6390        let marked = interrupt_task("marked");
6391        let next = advance_interrupt_tick(
6392            false,
6393            Interrupt::Idle,
6394            &["running".to_owned()],
6395            std::slice::from_ref(&marked),
6396        );
6397        assert_eq!(
6398            next,
6399            Interrupt::Idle,
6400            "an unmarked, unconfigured daemon must behave exactly as before"
6401        );
6402    }
6403
6404    #[test]
6405    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
6406        let state = Interrupt::Parking {
6407            parked: vec!["running".to_owned()],
6408            interrupt_task: "marked".to_owned(),
6409        };
6410        let candidates = vec![interrupt_task("marked"), task()];
6411        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6412        assert!(
6413            allowed.is_empty(),
6414            "nothing may dispatch - not even the interrupt task itself - \
6415             until the parked run has actually stopped"
6416        );
6417    }
6418
6419    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
6420    /// grow a special case for it: an urgent candidate that is not the
6421    /// interrupt task withholds exactly like an ordinary one for as long as
6422    /// the parked run it is racing has not actually left flight. A version
6423    /// of this feature once bypassed the gate for urgent candidates, on the
6424    /// theory that a genuinely separate concurrency lane could not collide
6425    /// with 75dd's own; it could, and did - the bypassed task dispatched
6426    /// alongside a run 75dd's own state machine had only *asked* to park,
6427    /// not yet confirmed gone, which is exactly the second run
6428    /// `Interrupt::Parking`'s own doc says must never happen. There is no
6429    /// tick during Parking/Running/Resuming where letting an extra
6430    /// candidate through is safe, urgent or not - the parked run may still
6431    /// be genuinely mid-call.
6432    #[test]
6433    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
6434        for state in [
6435            Interrupt::Parking {
6436                parked: vec!["running".to_owned()],
6437                interrupt_task: "marked".to_owned(),
6438            },
6439            Interrupt::Running {
6440                parked: vec!["running".to_owned()],
6441                interrupt_task: "marked".to_owned(),
6442            },
6443            Interrupt::Resuming {
6444                parked: vec!["running".to_owned()],
6445            },
6446        ] {
6447            let candidates = vec![
6448                interrupt_task("marked"),
6449                urgent_task("hot"),
6450                task_with_id("ordinary"),
6451            ];
6452            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6453            assert!(
6454                !allowed.iter().any(|t| t.id == "hot"),
6455                "an urgent candidate must wait out the same gate as anything \
6456                 else while the run it would run alongside has not actually \
6457                 left flight, for state {state:?}: {allowed:?}"
6458            );
6459        }
6460    }
6461
6462    /// The one case where marking a task `--urgent` and `interrupt` at once
6463    /// is not redundant: once the interrupt sequence's own guaranteed
6464    /// resume/dispatch actually admits the task, it is unaffected by also
6465    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
6466    /// never on the urgent flag.
6467    #[test]
6468    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
6469        let state = Interrupt::Resuming {
6470            parked: vec!["hot".to_owned()],
6471        };
6472        let candidates = vec![urgent_task("hot"), task()];
6473        let allowed = interrupt_gate(&state, &[], candidates);
6474        assert_eq!(
6475            allowed.iter().filter(|t| t.id == "hot").count(),
6476            1,
6477            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
6478        );
6479    }
6480
6481    #[test]
6482    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
6483        let state = Interrupt::Parking {
6484            parked: vec!["running".to_owned()],
6485            interrupt_task: "marked".to_owned(),
6486        };
6487        let other = task();
6488        let candidates = vec![interrupt_task("marked"), other.clone()];
6489        let allowed = interrupt_gate(&state, &[], candidates);
6490        assert_eq!(allowed.len(), 1);
6491        assert_eq!(allowed[0].id, "marked");
6492    }
6493
6494    #[test]
6495    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
6496        let state = Interrupt::Running {
6497            parked: vec!["running".to_owned()],
6498            interrupt_task: "marked".to_owned(),
6499        };
6500        let candidates = vec![task(), task()];
6501        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
6502        assert!(allowed.is_empty());
6503    }
6504
6505    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
6506    /// sequence began (only reachable above the default
6507    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
6508    /// never both in the same tick, which is what "exactly one resume, no
6509    /// simultaneous run" actually requires structurally rather than by
6510    /// coincidence of how many ordinary slots happen to be free.
6511    #[test]
6512    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
6513        let state = Interrupt::Resuming {
6514            parked: vec!["a".to_owned(), "c".to_owned()],
6515        };
6516        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
6517        let allowed = interrupt_gate(&state, &[], candidates);
6518        assert_eq!(
6519            allowed.len(),
6520            1,
6521            "at most one candidate may be offered while resuming: {allowed:?}"
6522        );
6523        assert_eq!(allowed[0].id, "a");
6524    }
6525
6526    #[test]
6527    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
6528        let state = Interrupt::Resuming {
6529            parked: vec!["a".to_owned()],
6530        };
6531        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
6532        assert!(allowed.is_empty());
6533    }
6534
6535    /// The invariant the completion criteria ask for by name: across a whole
6536    /// simulated sequence, there is never a tick where the gate would let
6537    /// through both the parked run's resume and the interrupt task, and
6538    /// exactly one candidate resumes the instant the interrupt task's run
6539    /// ends - never zero, never more than one.
6540    #[test]
6541    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
6542        let running = task(); // id: whatever `Task::new` minted
6543        let marked = interrupt_task("marked");
6544
6545        let mut state = Interrupt::Idle;
6546        // Tick 1: `running` is in flight, `marked` becomes runnable.
6547        let in_flight = vec![running.id.clone()];
6548        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
6549        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
6550        assert!(gated.is_empty(), "still waiting on `running` to park");
6551
6552        // Tick 2: `running` parked and left flight; nothing dispatched yet.
6553        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
6554        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
6555        assert_eq!(
6556            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6557            vec!["marked"],
6558            "only the interrupt task may be offered to the dispatcher now"
6559        );
6560
6561        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
6562        state = advance_interrupt_tick(
6563            true,
6564            state,
6565            &["marked".to_owned()],
6566            std::slice::from_ref(&running),
6567        );
6568        let gated = interrupt_gate(
6569            &state,
6570            &["marked".to_owned()],
6571            vec![marked.clone(), running.clone()],
6572        );
6573        assert!(
6574            gated.is_empty(),
6575            "the parked run must not be offered back while the interrupt \
6576             task is still running"
6577        );
6578
6579        // Tick 4: `marked`'s run reached a terminal status and left flight.
6580        // A higher-priority ordinary task `other` is also runnable now - it
6581        // must not be let through instead of, or alongside, `running`.
6582        let other = task_with_id("other");
6583        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
6584        assert_eq!(
6585            state,
6586            Interrupt::Resuming {
6587                parked: vec![running.id.clone()]
6588            }
6589        );
6590        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
6591        assert_eq!(
6592            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6593            vec![running.id.as_str()],
6594            "exactly the parked run resumes - not the unrelated task, even \
6595             though it was offered first"
6596        );
6597
6598        // Tick 5: `running` is now in flight (dispatched from tick 4's
6599        // gate). Only now does the sequence end and ordinary dispatch fully
6600        // resume.
6601        state = advance_interrupt_tick(
6602            true,
6603            state,
6604            std::slice::from_ref(&running.id),
6605            std::slice::from_ref(&other),
6606        );
6607        assert_eq!(state, Interrupt::Idle);
6608        let gated = interrupt_gate(
6609            &state,
6610            std::slice::from_ref(&running.id),
6611            vec![other.clone()],
6612        );
6613        assert_eq!(
6614            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6615            vec![other.id.as_str()],
6616            "ordinary dispatch is unrestricted again"
6617        );
6618    }
6619
6620    #[test]
6621    fn every_run_status_settles_the_task_it_came_from() {
6622        // run status, resulting task status, attempts still standing after one
6623        let table = [
6624            (RunStatus::Merged, TaskStatus::Done, 1),
6625            (RunStatus::Ready, TaskStatus::Done, 1),
6626            (RunStatus::Stalled, TaskStatus::Failed, 0),
6627            (RunStatus::Blocked, TaskStatus::Failed, 1),
6628            (RunStatus::Failed, TaskStatus::Failed, 1),
6629            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
6630            (RunStatus::Prep, TaskStatus::Failed, 1),
6631            (RunStatus::Implementing, TaskStatus::Failed, 1),
6632            (RunStatus::Judging, TaskStatus::Failed, 1),
6633            (RunStatus::Deliberating, TaskStatus::Failed, 1),
6634            (RunStatus::Voting, TaskStatus::Failed, 1),
6635            (RunStatus::Reviewing, TaskStatus::Failed, 1),
6636            (RunStatus::Gating, TaskStatus::Failed, 1),
6637        ];
6638        for (run, want, attempts) in table {
6639            let mut t = task();
6640            t.start("20260902-000000-aaaa".to_owned());
6641            settle(
6642                &mut t,
6643                Verdict {
6644                    status: run,
6645                    left_pr: false,
6646                    parked: false,
6647                    quota_hit: matches!(run, RunStatus::Stalled),
6648                    no_viable_candidates: false,
6649                },
6650                "why",
6651                2,
6652            );
6653            assert_eq!(t.status, want, "task status after {}", label(run));
6654            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
6655        }
6656    }
6657
6658    #[test]
6659    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
6660        let mut stalled = task();
6661        stalled.start("20260902-000000-aaaa".to_owned());
6662        settle(
6663            &mut stalled,
6664            Verdict {
6665                status: RunStatus::Stalled,
6666                left_pr: false,
6667                parked: false,
6668                quota_hit: true,
6669                no_viable_candidates: false,
6670            },
6671            "quota",
6672            1,
6673        );
6674        assert_eq!(stalled.attempts, 0);
6675        assert!(
6676            stalled.status.runnable(),
6677            "a machine problem must leave the task in line"
6678        );
6679
6680        let mut blocked = task();
6681        blocked.start("20260902-000000-aaaa".to_owned());
6682        settle(
6683            &mut blocked,
6684            Verdict {
6685                status: RunStatus::Blocked,
6686                left_pr: false,
6687                parked: false,
6688                quota_hit: false,
6689                no_viable_candidates: false,
6690            },
6691            "findings open",
6692            1,
6693        );
6694        assert_eq!(blocked.attempts, 1);
6695        assert_eq!(
6696            blocked.status,
6697            TaskStatus::Held,
6698            "the last attempt hands the task to a human"
6699        );
6700    }
6701
6702    #[test]
6703    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
6704        // Attempts to spare: without the pull request this task would go
6705        // straight back in line and run the whole competition again.
6706        let mut delivered = task();
6707        delivered.start("20260903-080619-01c2".to_owned());
6708        settle(
6709            &mut delivered,
6710            Verdict {
6711                status: RunStatus::Blocked,
6712                left_pr: true,
6713                parked: false,
6714                quota_hit: false,
6715                no_viable_candidates: false,
6716            },
6717            "no check status",
6718            4,
6719        );
6720        assert_eq!(
6721            delivered.status,
6722            TaskStatus::Held,
6723            "a pull request waiting on CI or a person is not a retryable failure"
6724        );
6725        assert!(
6726            !delivered.status.runnable(),
6727            "the loop must not pick this task up again"
6728        );
6729        assert_eq!(
6730            delivered.last_error.as_deref(),
6731            Some("no check status"),
6732            "the operator needs to be told what the gate was waiting for"
6733        );
6734
6735        // The same status without a pull request is a plain failure, and with
6736        // attempts left it is retried.
6737        let mut empty_handed = task();
6738        empty_handed.start("20260903-080619-01c2".to_owned());
6739        settle(
6740            &mut empty_handed,
6741            Verdict {
6742                status: RunStatus::Blocked,
6743                left_pr: false,
6744                parked: false,
6745                quota_hit: false,
6746                no_viable_candidates: false,
6747            },
6748            "findings open",
6749            4,
6750        );
6751        assert_eq!(empty_handed.status, TaskStatus::Failed);
6752        assert!(empty_handed.status.runnable());
6753    }
6754
6755    #[test]
6756    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
6757        // Every candidate agreed, with evidence, that nothing belonged in the
6758        // worktree. That is not a confirmed success to close automatically -
6759        // a human still has to check the claim - and it is not an ordinary
6760        // failure either, so this settles exactly like a pull request nobody
6761        // merged yet: `Held`, same as `Blocked` with a PR.
6762        let mut noop = task();
6763        noop.start("20260912-131304-391f".to_owned());
6764        settle(
6765            &mut noop,
6766            Verdict {
6767                status: RunStatus::VerifiedNoop,
6768                left_pr: false,
6769                parked: false,
6770                quota_hit: false,
6771                no_viable_candidates: true,
6772            },
6773            "candidate A: already fixed by b32cfc4, on main",
6774            4,
6775        );
6776        assert_eq!(
6777            noop.status,
6778            TaskStatus::Held,
6779            "an unverified claim is a request for a human, not a failure"
6780        );
6781        assert!(
6782            !noop.status.runnable(),
6783            "the loop must not requeue this on the same unverified claim"
6784        );
6785        // `Task::release` resets attempts to zero the moment a human looks at
6786        // the evidence and lets it run again, so it does not matter here
6787        // whether the one attempt already spent stays spent - what matters is
6788        // that nothing retries this task unattended in the meantime.
6789        assert_eq!(noop.attempts, 1);
6790    }
6791
6792    #[test]
6793    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
6794        // Parking is the operator asking for the process back - to replace the
6795        // binary, most of all. The run's work is intact on disk, so this is
6796        // not a failed attempt, and charging for it would mean a few upgrades
6797        // could exhaust a budget meant for agents that misbehaved.
6798        let mut parked = task();
6799        parked.start("20260903-183634-2d98".to_owned());
6800        settle(
6801            &mut parked,
6802            Verdict {
6803                status: RunStatus::Implementing,
6804                left_pr: false,
6805                quota_hit: false,
6806                parked: true,
6807                no_viable_candidates: false,
6808            },
6809            "parked after `implementing`",
6810            2,
6811        );
6812        assert_eq!(parked.attempts, 0, "a park is refunded");
6813        assert!(
6814            parked.status.runnable(),
6815            "and the task stays in line so the next loop resumes its run"
6816        );
6817        assert_eq!(parked.status, TaskStatus::Parked);
6818        assert_eq!(
6819            parked.park_reason.as_deref(),
6820            Some("parked after `implementing`"),
6821            "the card says where it stopped"
6822        );
6823        assert_eq!(parked.last_error, None, "nothing failed");
6824
6825        // Without the park flag the same non-terminal status is what it always
6826        // was: `execute` returning mid-flight, which is a bug and spends an
6827        // attempt so a task cannot loop on it forever.
6828        let mut broken = task();
6829        broken.start("20260903-183634-2d98".to_owned());
6830        settle(
6831            &mut broken,
6832            Verdict {
6833                status: RunStatus::Implementing,
6834                left_pr: false,
6835                quota_hit: false,
6836                parked: false,
6837                no_viable_candidates: false,
6838            },
6839            "returned mid-flight",
6840            2,
6841        );
6842        assert_eq!(broken.attempts, 1);
6843    }
6844
6845    #[test]
6846    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
6847        // Run e633: quorum lost because two judges answered with the wrong
6848        // JSON shape, `quota: []`. Refunding that takes the bound off the
6849        // retry loop, and each retry pays for a fresh hour-long implement
6850        // wave before it can fail the same way.
6851        let mut flaky = task();
6852        flaky.start("20260903-123023-e633".to_owned());
6853        settle(
6854            &mut flaky,
6855            Verdict {
6856                status: RunStatus::Stalled,
6857                left_pr: false,
6858                parked: false,
6859                quota_hit: false,
6860                no_viable_candidates: false,
6861            },
6862            "verdict rests on 1 of 3 judges",
6863            2,
6864        );
6865        assert_eq!(
6866            flaky.attempts, 1,
6867            "flakiness spends an attempt, so `max_attempts` still bounds it"
6868        );
6869        assert!(flaky.status.runnable(), "and it is still worth retrying");
6870
6871        // The same status, lost to a rate limit, is the machine's fault.
6872        let mut limited = task();
6873        limited.start("20260903-123023-e633".to_owned());
6874        settle(
6875            &mut limited,
6876            Verdict {
6877                status: RunStatus::Stalled,
6878                left_pr: false,
6879                parked: false,
6880                quota_hit: true,
6881                no_viable_candidates: false,
6882            },
6883            "judge-2, judge-3 out of quota",
6884            2,
6885        );
6886        assert_eq!(limited.attempts, 0, "a quota window is refunded");
6887        assert!(limited.status.runnable());
6888
6889        // And the bound really binds: a task that keeps stalling on flakiness
6890        // reaches a human instead of running the roster forever.
6891        let mut worn = task();
6892        for _ in 0..2 {
6893            worn.release();
6894        }
6895        worn.start("20260903-123023-e633".to_owned());
6896        worn.attempts = 2;
6897        settle(
6898            &mut worn,
6899            Verdict {
6900                status: RunStatus::Stalled,
6901                left_pr: false,
6902                parked: false,
6903                quota_hit: false,
6904                no_viable_candidates: false,
6905            },
6906            "no quorum again",
6907            2,
6908        );
6909        assert_eq!(worn.status, TaskStatus::Held);
6910        assert!(!worn.status.runnable());
6911    }
6912
6913    #[test]
6914    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
6915        // The implement wave loses every seat to the same rate limit and
6916        // `after_implement` bails with nothing viable, which surfaces as
6917        // `Failed` rather than `Stalled`. That is the same machine fact the
6918        // `Stalled`-quota row already refunds, and must be refunded the same
6919        // way, or a quota outage quietly holds every task it touches instead
6920        // of leaving them in line for the reset.
6921        let mut wiped_out = task();
6922        wiped_out.start("20260907-025000-a1b2".to_owned());
6923        settle(
6924            &mut wiped_out,
6925            Verdict {
6926                status: RunStatus::Failed,
6927                left_pr: false,
6928                parked: false,
6929                quota_hit: true,
6930                no_viable_candidates: true,
6931            },
6932            "no candidate produced a change; nothing to judge",
6933            2,
6934        );
6935        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
6936        assert!(
6937            wiped_out.status.runnable(),
6938            "a machine problem must leave the task in line"
6939        );
6940
6941        // This is the exemption that must stay narrow: a candidate that did
6942        // produce a change, and then failed for some other reason, still
6943        // spends the attempt even though a seat elsewhere hit its quota.
6944        // Otherwise every ordinary failure that happens to share a run with
6945        // an unrelated rate limit would be refunded for free.
6946        let mut partial_progress = task();
6947        partial_progress.start("20260907-025500-c3d4".to_owned());
6948        settle(
6949            &mut partial_progress,
6950            Verdict {
6951                status: RunStatus::Failed,
6952                left_pr: false,
6953                parked: false,
6954                quota_hit: true,
6955                no_viable_candidates: false,
6956            },
6957            "gate failed on the winning candidate",
6958            2,
6959        );
6960        assert_eq!(
6961            partial_progress.attempts, 1,
6962            "a candidate that actually produced a change spends the attempt \
6963             even though some other seat hit its quota"
6964        );
6965        assert!(partial_progress.status.runnable());
6966    }
6967
6968    #[test]
6969    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
6970        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
6971        // disk, and that construction must reach the same conclusion as the
6972        // one `attempt` builds from a live run, or a crash at exactly the
6973        // wrong moment gives a recovered task a different policy than one a
6974        // daemon finished settling itself.
6975        let mut t = task();
6976        t.start("20260907-025000-a1b2".to_owned());
6977        let mut state = run_state(RunStatus::Failed);
6978        state.quota.push(QuotaLoss {
6979            seat: "cand-a".to_owned(),
6980            node: "implement".to_owned(),
6981            at: Timestamp::now(),
6982            reset: None,
6983        });
6984        assert!(
6985            state.viable().is_empty(),
6986            "no candidate was added, so nothing is viable"
6987        );
6988        reclaim(&mut t, Some(state), 2, "en");
6989        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6990        assert!(t.status.runnable());
6991    }
6992
6993    #[test]
6994    fn a_held_task_is_never_offered_to_the_loop() {
6995        let dir = tempfile::tempdir().unwrap();
6996        let queue = Queue::at(dir.path().to_path_buf());
6997        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6998            let mut t = task();
6999            t.id = format!("2026090{n}-000000-000{n}");
7000            t.priority = priority;
7001            queue.put(&mut t).unwrap();
7002        }
7003        let mut held = task();
7004        held.id = "20260909-000000-9999".to_owned();
7005        held.priority = 99;
7006        held.hold_machine(None);
7007        queue.put(&mut held).unwrap();
7008
7009        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
7010        assert_eq!(order.len(), 3);
7011        assert!(!order.contains(&held.id));
7012        assert_eq!(
7013            order.first().cloned(),
7014            queue.next_runnable().map(|t| t.id),
7015            "the loop's first candidate is exactly what the queue offers"
7016        );
7017        assert_eq!(
7018            order,
7019            vec![
7020                "20260902-000000-0002".to_owned(),
7021                "20260903-000000-0003".to_owned(),
7022                "20260901-000000-0001".to_owned(),
7023            ],
7024            "priority first, then oldest, so nothing starves"
7025        );
7026    }
7027
7028    #[test]
7029    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
7030        let dir = tempfile::tempdir().unwrap();
7031        let queue = Queue::at(dir.path().to_path_buf());
7032        let mut old = task();
7033        old.id = "20260101-000000-old0".to_owned();
7034        queue.put(&mut old).unwrap();
7035        let mut fresh = task();
7036        fresh.id = "20260101-000000-new0".to_owned();
7037        queue.put(&mut fresh).unwrap();
7038
7039        // No parseable pid at all, so age is the only signal there is to
7040        // check - unlike a real `Queue::claim`, which always names a real,
7041        // and therefore alive, pid this test cannot fake as dead.
7042        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
7043        std::thread::sleep(Duration::from_millis(60));
7044        let live = queue.claim(&fresh.id).unwrap();
7045
7046        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7047        assert_eq!(swept, vec![old.id.clone()]);
7048        assert!(
7049            queue.claim(&old.id).is_ok(),
7050            "an unparseable lock older than the threshold is swept"
7051        );
7052        assert!(
7053            queue.claim(&fresh.id).is_err(),
7054            "a live pid protects its lock regardless of age"
7055        );
7056        drop(live);
7057    }
7058
7059    #[test]
7060    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
7061        // The regression this guards: `sweep` now runs concurrently with
7062        // every attempt this daemon itself has spawned (see
7063        // `InFlightGuard`), not only between them the way a single
7064        // sequential loop once did. A run that legitimately outlives
7065        // `older_than` still has this very process's own live pid sitting in
7066        // its own lock file on every later sweep, and deciding by age alone
7067        // would delete that still-valid claim out from under the attempt
7068        // that holds it - which `reclaim_orphaned_running` would then read
7069        // as abandoned and hand to a second, competing attempt.
7070        let dir = tempfile::tempdir().unwrap();
7071        let queue = Queue::at(dir.path().to_path_buf());
7072        let mut t = task();
7073        t.id = "20260101-000000-live".to_owned();
7074        queue.put(&mut t).unwrap();
7075
7076        let claim = queue.claim(&t.id).unwrap();
7077        std::thread::sleep(Duration::from_millis(60));
7078
7079        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7080        assert!(
7081            swept.is_empty(),
7082            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
7083        );
7084        assert!(
7085            queue.claim(&t.id).is_err(),
7086            "the lock still protects its task"
7087        );
7088        drop(claim);
7089    }
7090
7091    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
7092    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
7093    fn injected_dead_pid() -> u32 {
7094        std::process::id().checked_add(1).unwrap_or(1)
7095    }
7096
7097    #[test]
7098    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
7099        let dir = tempfile::tempdir().unwrap();
7100        let queue = Queue::at(dir.path().to_path_buf());
7101        let mut t = task();
7102        t.id = "20260101-000000-dead".to_owned();
7103        queue.put(&mut t).unwrap();
7104        let dead_pid = injected_dead_pid();
7105
7106        // Written directly rather than through `Queue::claim`, which would
7107        // stamp this test process's own very much alive pid and defeat the
7108        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
7109        // like moments after it died, not six hours later.
7110        std::fs::write(
7111            dir.path().join(format!("{}.lock", t.id)),
7112            dead_pid.to_string(),
7113        )
7114        .unwrap();
7115
7116        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7117            pid != dead_pid
7118        });
7119        assert_eq!(
7120            swept,
7121            vec![t.id.clone()],
7122            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
7123        );
7124        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
7125    }
7126
7127    #[test]
7128    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
7129        let dir = tempfile::tempdir().unwrap();
7130        let queue = Queue::at(dir.path().to_path_buf());
7131        let mut t = task();
7132        t.id = "20260101-000000-late".to_owned();
7133        queue.put(&mut t).unwrap();
7134        let dead_pid = injected_dead_pid();
7135
7136        // Tick one, standing in for the sweep `poll` already runs at
7137        // startup: nothing to find yet.
7138        assert!(
7139            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
7140            "nothing has claimed the task yet"
7141        );
7142
7143        // A second daemon claims the task and dies before it ever writes
7144        // `running`, well after this loop's own startup sweep already ran.
7145        std::fs::write(
7146            dir.path().join(format!("{}.lock", t.id)),
7147            dead_pid.to_string(),
7148        )
7149        .unwrap();
7150
7151        // Tick two, standing in for a poll long into this daemon's uptime:
7152        // the same function, called again, notices what only just appeared -
7153        // proving the sweep is not a one-shot startup check.
7154        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7155            pid != dead_pid
7156        });
7157        assert_eq!(swept, vec![t.id.clone()]);
7158    }
7159
7160    #[test]
7161    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
7162        // `reclaim_orphaned_running` looks up the task's last run, which
7163        // touches `run::home()`; the first call anywhere in this binary wins,
7164        // so this is a no-op if another test already pinned one, and either
7165        // way the run id below is never written under it.
7166        crate::run::pin_test_home();
7167        let dir = tempfile::tempdir().unwrap();
7168        let queue = Queue::at(dir.path().to_path_buf());
7169        let mut t = task();
7170        t.id = "20260101-000000-crsh".to_owned();
7171        t.status = TaskStatus::Running;
7172        t.attempts = 1;
7173        // No `run.json` behind this id: standing in for a run this test does
7174        // not need to make readable, since the point is the lock, not the
7175        // recovery table `reclaim` already has its own tests for.
7176        t.runs.push("20260904-000000-4043".to_owned());
7177        queue.put(&mut t).unwrap();
7178        let dead_pid = injected_dead_pid();
7179
7180        // The crashed daemon's own claim, naming a pid nothing on the
7181        // machine holds anymore.
7182        std::fs::write(
7183            dir.path().join(format!("{}.lock", t.id)),
7184            dead_pid.to_string(),
7185        )
7186        .unwrap();
7187
7188        // Before the lock is swept the task looks claimed, and
7189        // `reclaim_orphaned_running` must leave it alone - this is exactly
7190        // the bug: a `running` task stranded behind a dead daemon's lock,
7191        // invisible to the claim-as-proof check because the lock outlived
7192        // the process that wrote it.
7193        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
7194        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
7195
7196        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
7197            pid != dead_pid
7198        });
7199        assert_eq!(swept, vec![t.id.clone()]);
7200
7201        let reclaimed = reclaim_orphaned_running(&queue, 2);
7202        assert_eq!(reclaimed, vec![t.id.clone()]);
7203        let after = queue.get(&t.id).unwrap();
7204        assert_eq!(
7205            after.status,
7206            TaskStatus::Held,
7207            "no run.json to recover from, so a human is asked"
7208        );
7209        assert_eq!(
7210            after.runs,
7211            vec!["20260904-000000-4043".to_owned()],
7212            "the crashed run's id is kept as evidence, not discarded"
7213        );
7214    }
7215
7216    #[test]
7217    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
7218        let dir = tempfile::tempdir().unwrap();
7219        let queue = Queue::at(dir.path().to_path_buf());
7220        let mut t = task();
7221        t.id = "20260101-000000-unknown".to_owned();
7222        queue.put(&mut t).unwrap();
7223        let dead_pid = injected_dead_pid();
7224        std::fs::write(
7225            dir.path().join(format!("{}.lock", t.id)),
7226            dead_pid.to_string(),
7227        )
7228        .unwrap();
7229
7230        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
7231        assert!(swept.is_empty(), "an unknown pid must keep its lock");
7232        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
7233    }
7234
7235    fn run_state_in(status: RunStatus, language: &str) -> RunState {
7236        let mut s = run_state(status);
7237        s.config.graph.language = language.to_owned();
7238        s
7239    }
7240
7241    fn unstarted_verdict(status: RunStatus) -> Verdict {
7242        Verdict {
7243            status,
7244            left_pr: false,
7245            quota_hit: false,
7246            parked: false,
7247            no_viable_candidates: false,
7248        }
7249    }
7250
7251    #[test]
7252    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
7253        let mut t = task();
7254        t.attempts = 1;
7255        settle_in(
7256            &mut t,
7257            unstarted_verdict(RunStatus::AlreadyInBase),
7258            "already in main",
7259            1,
7260            phrases("en"),
7261        );
7262        assert_eq!(t.status, TaskStatus::Done);
7263        assert_eq!(t.attempts, 0);
7264    }
7265
7266    #[test]
7267    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
7268        let reason = |language: &str| {
7269            let mut t = task();
7270            settle_in(
7271                &mut t,
7272                unstarted_verdict(RunStatus::Judging),
7273                "boom",
7274                1,
7275                phrases(language),
7276            );
7277            t.last_error.or(t.hold_reason).unwrap_or_default()
7278        };
7279        assert!(
7280            reason("en").starts_with("the graph stopped at `"),
7281            "{}",
7282            reason("en")
7283        );
7284        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
7285        assert!(reason("日本語").contains("boom"));
7286        assert_eq!(reason("fr"), reason("en"));
7287    }
7288
7289    #[test]
7290    fn describe_follows_the_run_language_and_keeps_the_run_id() {
7291        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
7292        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
7293        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
7294        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
7295        assert!(ja.contains("[run "), "{ja}");
7296        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
7297        assert!(ended.starts_with("run 終了: "), "{ended}");
7298        let mut de = run_state_in(RunStatus::Failed, "de");
7299        let mut en = run_state_in(RunStatus::Failed, "en");
7300        de.id = "same".to_owned();
7301        en.id = "same".to_owned();
7302        assert_eq!(describe(&de), describe(&en));
7303    }
7304
7305    #[test]
7306    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
7307        use crate::handover::Refused;
7308        let cases = [
7309            Refused::Foreign {
7310                branch: "b".into(),
7311                path: "/w/x".into(),
7312                why: "made by hand".into(),
7313            },
7314            Refused::Unsafe {
7315                branch: "b".into(),
7316                path: "/w/x".into(),
7317                why: "its worktree has uncommitted changes (a.rs)".into(),
7318            },
7319            Refused::ReleaseFailed {
7320                branch: "b".into(),
7321                path: "/w/x".into(),
7322                run: "ab12".into(),
7323            },
7324        ];
7325        for r in &cases {
7326            let en = (phrases("en").handover_refused)(r);
7327            assert_eq!(en, r.to_string());
7328            let ja = (phrases("ja").handover_refused)(r);
7329            assert!(
7330                !ja.contains("is checked out") && !ja.contains("try again"),
7331                "{ja}"
7332            );
7333            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
7334            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
7335                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
7336            }
7337        }
7338        assert!(phrases("en").handover_hint.contains("release the task"));
7339        assert!(phrases("ja").handover_hint.contains("解放"));
7340    }
7341
7342    #[test]
7343    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
7344        let build = |lang: &str| {
7345            let mut s = run_state_in(RunStatus::Blocked, lang);
7346            s.id = "same".to_owned();
7347            s.config.graph.review_rounds = 3;
7348            let mut r = review_round(3);
7349            r.expected = 3;
7350            r.answered = 1;
7351            s.reviews.push(r);
7352            s.event(
7353                "review",
7354                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
7355            );
7356            s
7357        };
7358        let en = describe(&build("en"));
7359        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
7360        let ja = describe(&build("ja"));
7361        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
7362        assert!(!ja.contains("never answered"), "{ja}");
7363        assert!(ja.contains("[run "), "{ja}");
7364
7365        // An incomplete panel whose verification failed is a different stop:
7366        // the real event must survive in ja too.
7367        let mut failed = build("ja");
7368        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
7369            command: "cargo test".to_owned(),
7370            code: Some(1),
7371            output_tail: String::new(),
7372            duration_ms: 0,
7373            resource_blocked: false,
7374        });
7375        failed.event("review", "stopped; e2e failed: cargo test");
7376        let ja = describe(&failed);
7377        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
7378        assert!(!ja.contains("席のレビュアー"), "{ja}");
7379    }
7380
7381    #[test]
7382    fn refusals_and_recovery_prose_follow_the_language() {
7383        let t = held_task_with("r1");
7384        let q = action_question(
7385            "r1",
7386            ask::ChoiceAction::Resume {
7387                run: "r1".to_owned(),
7388            },
7389        );
7390        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
7391            ActionDecision::Refuse(s) => s,
7392            other => panic!("{other:?}"),
7393        };
7394        assert!(refuse(phrases("en")).contains("could not be read: gone"));
7395        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
7396        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
7397
7398        let mut held = task();
7399        reclaim(&mut held, None, 2, "ja");
7400        assert!(held.hold_reason.unwrap().contains("保留にしました"));
7401        let mut held = task();
7402        reclaim(&mut held, None, 2, "xx");
7403        assert!(held.hold_reason.unwrap().contains("held for a human"));
7404    }
7405
7406    fn run_state(status: RunStatus) -> RunState {
7407        let mut state = RunState::new(
7408            PathBuf::from("/repo"),
7409            "main".to_owned(),
7410            "abc1234def".to_owned(),
7411            "add retries".to_owned(),
7412            Config::default(),
7413        );
7414        state.status = status;
7415        state
7416    }
7417
7418    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
7419        Candidate {
7420            index: 0,
7421            label,
7422            agent: "claude".to_owned(),
7423            branch: format!("magi/x/{label}"),
7424            worktree: PathBuf::from("/repo"),
7425            summary: summary.to_owned(),
7426            stat: String::new(),
7427            files: 0,
7428            commits: usize::from(!empty),
7429            empty,
7430            failed: failed.map(str::to_owned),
7431            verified_noop: None,
7432            duration_ms: 0,
7433            folded: false,
7434        }
7435    }
7436
7437    #[test]
7438    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
7439        let mut state = run_state(RunStatus::Blocked);
7440        state.gate = vec![
7441            CommandOutcome {
7442                command: "cargo make check".to_owned(),
7443                code: Some(0),
7444                output_tail: "ok".to_owned(),
7445                duration_ms: 0,
7446                resource_blocked: false,
7447            },
7448            CommandOutcome {
7449                command: "cargo test".to_owned(),
7450                code: Some(101),
7451                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
7452                duration_ms: 0,
7453                resource_blocked: false,
7454            },
7455        ];
7456        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
7457        assert!(d.contains("cargo test"), "{d}");
7458        assert!(
7459            !d.contains("cargo make check"),
7460            "a passing check is not a diagnostic: {d}"
7461        );
7462        assert!(d.contains("assertion failed"), "{d}");
7463    }
7464
7465    #[test]
7466    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
7467        let mut state = run_state(RunStatus::Blocked);
7468        state.event(
7469            "land",
7470            "stopped: the fixer produced no commit while 2 check(s) were failing \
7471             (build, lint); stopping instead of looping on an unchanged tree",
7472        );
7473        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
7474        assert!(d.contains("build"), "{d}");
7475        assert!(d.contains("lint"), "{d}");
7476        assert!(d.contains("fixer produced no commit"), "{d}");
7477    }
7478
7479    #[test]
7480    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
7481        // `describe`'s output becomes `Task::last_error` verbatim, and the
7482        // phone renders that in the same alarm-styled box an ordinary
7483        // failure gets. A bare `verified_noop` there would read exactly like
7484        // the failure this status exists to be told apart from.
7485        let state = run_state(RunStatus::VerifiedNoop);
7486        let d = describe(&state);
7487        assert!(
7488            d.contains("agent-verified no-op"),
7489            "expected the display label, not the wire spelling: {d}"
7490        );
7491        assert!(!d.contains("verified_noop"), "{d}");
7492    }
7493
7494    #[test]
7495    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
7496        // The whole point of the feature: a run held as "no candidate produced
7497        // a change" can mean the implementer actually finished the task and
7498        // only left a clean local tree behind - see AGENTS.md on this exact
7499        // failure mode. The diagnostic has to carry what the agent actually
7500        // said, not just the fact that nothing was there to judge.
7501        let mut state = run_state(RunStatus::Failed);
7502        state.candidates = vec![candidate(
7503            'A',
7504            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
7505            true,
7506            None,
7507        )];
7508        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
7509        assert!(d.contains("candidate A"), "{d}");
7510        assert!(d.contains("tagged v1.2.3"), "{d}");
7511    }
7512
7513    #[test]
7514    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
7515        let mut state = run_state(RunStatus::Failed);
7516        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
7517        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
7518        assert!(d.contains("candidate A"), "{d}");
7519        assert!(d.contains("agent timed out"), "{d}");
7520    }
7521
7522    #[test]
7523    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
7524        // A viable candidate existed, the gate never ran, and nothing land
7525        // said matches - `Task::last_error` is left to explain this one alone.
7526        let mut state = run_state(RunStatus::Failed);
7527        state.candidates = vec![candidate('A', "did the work", false, None)];
7528        assert!(diagnostic(&state).is_none());
7529    }
7530
7531    #[test]
7532    fn diagnostic_is_bounded_however_much_a_run_printed() {
7533        let mut state = run_state(RunStatus::Blocked);
7534        state.gate = vec![
7535            CommandOutcome {
7536                command: "cargo test".to_owned(),
7537                code: Some(101),
7538                output_tail: "x".repeat(50_000),
7539                duration_ms: 0,
7540                resource_blocked: false,
7541            },
7542            CommandOutcome {
7543                command: "cargo clippy".to_owned(),
7544                code: Some(1),
7545                output_tail: "y".repeat(50_000),
7546                duration_ms: 0,
7547                resource_blocked: false,
7548            },
7549        ];
7550        state.candidates = vec![
7551            candidate('A', &"z".repeat(50_000), true, None),
7552            candidate('B', &"w".repeat(50_000), true, None),
7553        ];
7554        let d = diagnostic(&state).expect("plenty here to diagnose");
7555        assert!(
7556            d.len() <= DIAGNOSTIC_MAX,
7557            "diagnostic grew to {} bytes, unbounded",
7558            d.len()
7559        );
7560    }
7561
7562    #[test]
7563    fn selected_delivery_guards_survive_recovery_failure_accounting() {
7564        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
7565            let mut t = task();
7566            let mut state = run_state(status);
7567            t.pr_recovery = Some(crate::pr_recovery::Selection {
7568                url: "url".into(),
7569                branch: format!("magi/task-{}", t.id),
7570                head: "a".repeat(40),
7571                source_head: None,
7572                source_run: None,
7573                source_proof: None,
7574                disposition: Some(crate::pr_recovery::Disposition::Land),
7575                instruction: t.instruction.clone(),
7576                approved_at: Timestamp::now(),
7577            });
7578            state.pr_recovery = t.pr_recovery.clone();
7579            t.start(state.id.clone());
7580            settle_and_diagnose(
7581                &mut t,
7582                Verdict {
7583                    status,
7584                    left_pr: false,
7585                    quota_hit: false,
7586                    parked: false,
7587                    no_viable_candidates: false,
7588                },
7589                "delivery stopped",
7590                5,
7591                &state,
7592            );
7593            assert_eq!(t.status, TaskStatus::Held);
7594            let reason = t.hold_reason.as_deref().unwrap();
7595            if status == RunStatus::Ready {
7596                assert!(reason.contains("Selected PR delivery is incomplete"));
7597                assert!(t.recovery_budget.is_none());
7598            } else {
7599                assert!(reason.contains("Selected recovery stopped"));
7600                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
7601            }
7602            assert!(t.pr_recovery.is_some());
7603        }
7604    }
7605
7606    #[test]
7607    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
7608        let mut state = run_state(RunStatus::Blocked);
7609        state.gate = vec![CommandOutcome {
7610            command: "cargo test".to_owned(),
7611            code: Some(101),
7612            output_tail: "assertion failed".to_owned(),
7613            duration_ms: 0,
7614            resource_blocked: false,
7615        }];
7616        let verdict = Verdict {
7617            status: RunStatus::Blocked,
7618            left_pr: false,
7619            quota_hit: false,
7620            parked: false,
7621            no_viable_candidates: false,
7622        };
7623
7624        // Attempt one of two still has a retry coming: no diagnostic yet, the
7625        // task is going to run again and this run's evidence would go stale.
7626        let mut t = task();
7627        t.start("run-1".to_owned());
7628        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7629        assert_eq!(t.status, TaskStatus::Failed);
7630        assert!(t.diagnostic.is_none());
7631
7632        // Attempt two exhausts the budget: now it is held, and the
7633        // diagnostic is what `magi task show` has to say more than one line.
7634        t.start("run-2".to_owned());
7635        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7636        assert_eq!(t.status, TaskStatus::Held);
7637        let d = t.diagnostic.expect("a held task must carry its diagnostic");
7638        assert!(d.contains("cargo test"), "{d}");
7639    }
7640
7641    #[test]
7642    fn a_held_task_names_the_open_question_it_is_waiting_on() {
7643        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
7644        // `magi ask` question settled Held with `hold_reason: null`, so the
7645        // notification said nothing actionable. `note_open_question` should
7646        // append the question id to whatever `handed_off` already wrote.
7647        crate::run::pin_test_home();
7648        let home = crate::run::home();
7649        let state = run_state(RunStatus::VerifiedNoop);
7650        let mut q = ask::Question::new(
7651            state.id.clone(),
7652            "implement".to_owned(),
7653            "impl-A".to_owned(),
7654            "is this really a no-op?".to_owned(),
7655            String::new(),
7656            Vec::new(),
7657        );
7658        Questions::at(home.join("questions")).put(&mut q).unwrap();
7659
7660        let verdict = Verdict {
7661            status: RunStatus::VerifiedNoop,
7662            left_pr: false,
7663            quota_hit: false,
7664            parked: false,
7665            no_viable_candidates: false,
7666        };
7667        let mut t = task();
7668        t.start(state.id.clone());
7669        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7670
7671        assert_eq!(t.status, TaskStatus::Held);
7672        let reason = t.hold_reason.expect("a held task must record why");
7673        assert!(
7674            reason.starts_with("run ended agent-verified no-op"),
7675            "the original settle reason must survive unchanged: {reason}"
7676        );
7677        assert!(
7678            reason.contains(q.short()),
7679            "the open question's id must be named so the notice is actionable: {reason}"
7680        );
7681    }
7682
7683    #[test]
7684    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
7685        crate::run::pin_test_home();
7686        let state = run_state(RunStatus::VerifiedNoop);
7687
7688        let verdict = Verdict {
7689            status: RunStatus::VerifiedNoop,
7690            left_pr: false,
7691            quota_hit: false,
7692            parked: false,
7693            no_viable_candidates: false,
7694        };
7695        let mut t = task();
7696        t.start(state.id.clone());
7697        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7698
7699        assert_eq!(t.status, TaskStatus::Held);
7700        assert_eq!(
7701            t.hold_reason.as_deref(),
7702            Some("run ended agent-verified no-op"),
7703            "nothing to append when the question was already answered or never asked"
7704        );
7705    }
7706
7707    #[test]
7708    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
7709        crate::run::pin_test_home();
7710        let mut first = run_state(RunStatus::Blocked);
7711        first.id = "20260101-000000-sup1".to_owned();
7712        first.save().unwrap();
7713        let mut second = run_state(RunStatus::Merged);
7714        second.id = "20260101-000000-sup2".to_owned();
7715        second.save().unwrap();
7716
7717        let mut t = task();
7718        t.runs = vec![first.id.clone(), second.id.clone()];
7719        t.status = TaskStatus::Done;
7720
7721        supersede_prior_runs(&t, &crate::run::home());
7722
7723        assert_eq!(
7724            RunState::load(&first.id).unwrap().status,
7725            RunStatus::Superseded,
7726            "the first attempt's Blocked no longer needs anyone's attention"
7727        );
7728        assert_eq!(
7729            RunState::load(&second.id).unwrap().status,
7730            RunStatus::Merged,
7731            "the run that actually succeeded is left exactly as it was"
7732        );
7733    }
7734
7735    #[test]
7736    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
7737        // `is_working_on` alone only proves a *daemon* claim; a `magi run
7738        // --resume` invoked by hand outside the daemon never touches
7739        // `daemon.json` at all, so it would look identical to a genuinely
7740        // idle run without also consulting `RunState::liveness`, which reads
7741        // this run's own recorded `driver_pid` instead.
7742        crate::run::pin_test_home();
7743        let mut first = run_state(RunStatus::Blocked);
7744        first.id = "20260101-000000-sup9".to_owned();
7745        // This test process's own pid: guaranteed alive without needing a
7746        // real second process or daemon.
7747        first.driver_pid = Some(std::process::id());
7748        first.driver_started_at = Some(
7749            crate::proc::process_started_at(std::process::id())
7750                .expect("this test process's own start time must be queryable"),
7751        );
7752        first.save().unwrap();
7753        let mut second = run_state(RunStatus::Merged);
7754        second.id = "20260101-000000-supa".to_owned();
7755        second.save().unwrap();
7756
7757        let mut t = task();
7758        t.runs = vec![first.id.clone(), second.id.clone()];
7759        t.status = TaskStatus::Done;
7760
7761        supersede_prior_runs(&t, &crate::run::home());
7762
7763        assert_eq!(
7764            RunState::load(&first.id).unwrap().status,
7765            RunStatus::Blocked,
7766            "a live driver_pid means something is still actually working this run, \
7767             even though no daemon claims it - rewriting under it would just be \
7768             undone the next time that process saves"
7769        );
7770    }
7771
7772    #[test]
7773    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
7774        // The first resweep must skip a still-live attempt exactly like
7775        // `supersede_prior_runs` itself does; a later resweep, once that
7776        // process is no longer actually driving it, is what closes the gap
7777        // `supersede_prior_runs` alone leaves - a task only ever reaches
7778        // `Done` once, so nothing else would ever look at this run again.
7779        let dir = tempfile::tempdir().unwrap();
7780        let home = dir.path().to_path_buf();
7781        let queue = Queue::at(dir.path().join("queue"));
7782
7783        let mut first = run_state(RunStatus::Blocked);
7784        first.id = "20260101-000000-supd".to_owned();
7785        first.driver_pid = Some(std::process::id());
7786        first.driver_started_at = Some(
7787            crate::proc::process_started_at(std::process::id())
7788                .expect("this test process's own start time must be queryable"),
7789        );
7790        first.save_under(&home).unwrap();
7791        let mut second = run_state(RunStatus::Merged);
7792        second.id = "20260101-000000-supe".to_owned();
7793        second.save_under(&home).unwrap();
7794
7795        let mut t = task();
7796        t.runs = vec![first.id.clone(), second.id.clone()];
7797        t.status = TaskStatus::Done;
7798        queue.put(&mut t).unwrap();
7799
7800        resweep_superseded_attempts(&queue, &home);
7801        assert_eq!(
7802            RunState::load_under(&first.id, &home).unwrap().status,
7803            RunStatus::Blocked,
7804            "still live on the first pass, so still untouched"
7805        );
7806
7807        // Stand in for the manual process no longer being the one driving
7808        // this run: same pid (this test process really is still alive), but
7809        // an identity marker that no longer matches it - see
7810        // `RunState::liveness`'s own doc for why a mismatched
7811        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
7812        let mut stale = RunState::load_under(&first.id, &home).unwrap();
7813        stale.driver_started_at = Some("1".to_owned());
7814        stale.save_under(&home).unwrap();
7815
7816        resweep_superseded_attempts(&queue, &home);
7817        assert_eq!(
7818            RunState::load_under(&first.id, &home).unwrap().status,
7819            RunStatus::Superseded,
7820            "the second pass catches up what the first one correctly skipped"
7821        );
7822    }
7823
7824    #[test]
7825    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
7826        crate::run::pin_test_home();
7827        let mut first = run_state(RunStatus::Blocked);
7828        first.id = "20260101-000000-sup3".to_owned();
7829        first.save().unwrap();
7830        let mut second = run_state(RunStatus::Blocked);
7831        second.id = "20260101-000000-sup4".to_owned();
7832        second.save().unwrap();
7833
7834        let mut t = task();
7835        t.runs = vec![first.id.clone(), second.id.clone()];
7836        // Still retrying: nothing about this task's story is settled yet, so
7837        // neither Blocked run may be relabelled, even though a later attempt
7838        // already exists.
7839        t.status = TaskStatus::Failed;
7840
7841        supersede_prior_runs(&t, &crate::run::home());
7842
7843        assert_eq!(
7844            RunState::load(&first.id).unwrap().status,
7845            RunStatus::Blocked
7846        );
7847        assert_eq!(
7848            RunState::load(&second.id).unwrap().status,
7849            RunStatus::Blocked
7850        );
7851    }
7852
7853    #[test]
7854    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
7855        // `magi task done` (or the API's equivalent) can close a task with no
7856        // run of its own ever having succeeded - there is nothing here that
7857        // counts as "the attempt that finished it", so nothing is rewritten.
7858        crate::run::pin_test_home();
7859        let mut first = run_state(RunStatus::Blocked);
7860        first.id = "20260101-000000-sup5".to_owned();
7861        first.save().unwrap();
7862
7863        let mut t = task();
7864        t.runs = vec![first.id.clone()];
7865        t.status = TaskStatus::Done;
7866
7867        supersede_prior_runs(&t, &crate::run::home());
7868
7869        assert_eq!(
7870            RunState::load(&first.id).unwrap().status,
7871            RunStatus::Blocked,
7872            "a single-attempt task has no earlier run to supersede"
7873        );
7874    }
7875
7876    #[test]
7877    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
7878        // `magi task done` (or the web/conductor equivalents) can close a
7879        // task in any status, including one whose *last* recorded attempt is
7880        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
7881        // never watched, say. `runs.last()` being `Done`-adjacent is not
7882        // proof it actually succeeded, so nothing earlier may be relabelled
7883        // on its say-so alone.
7884        crate::run::pin_test_home();
7885        let mut first = run_state(RunStatus::Blocked);
7886        first.id = "20260101-000000-supb".to_owned();
7887        first.save().unwrap();
7888        let mut second = run_state(RunStatus::Failed);
7889        second.id = "20260101-000000-supc".to_owned();
7890        second.save().unwrap();
7891
7892        let mut t = task();
7893        t.runs = vec![first.id.clone(), second.id.clone()];
7894        t.status = TaskStatus::Done;
7895
7896        supersede_prior_runs(&t, &crate::run::home());
7897
7898        assert_eq!(
7899            RunState::load(&first.id).unwrap().status,
7900            RunStatus::Blocked,
7901            "the task's last attempt never landed, so there is nothing here \
7902             actually superseding it"
7903        );
7904    }
7905
7906    #[test]
7907    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
7908        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
7909        // to look" - `Failed` and `VerifiedNoop` are already their own
7910        // terminal answers and must not be relabelled into a third one.
7911        crate::run::pin_test_home();
7912        let mut failed = run_state(RunStatus::Failed);
7913        failed.id = "20260101-000000-sup6".to_owned();
7914        failed.save().unwrap();
7915        let mut noop = run_state(RunStatus::VerifiedNoop);
7916        noop.id = "20260101-000000-sup7".to_owned();
7917        noop.save().unwrap();
7918        let mut winner = run_state(RunStatus::Ready);
7919        winner.id = "20260101-000000-sup8".to_owned();
7920        winner.save().unwrap();
7921
7922        let mut t = task();
7923        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
7924        t.status = TaskStatus::Done;
7925
7926        supersede_prior_runs(&t, &crate::run::home());
7927
7928        assert_eq!(
7929            RunState::load(&failed.id).unwrap().status,
7930            RunStatus::Failed
7931        );
7932        assert_eq!(
7933            RunState::load(&noop.id).unwrap().status,
7934            RunStatus::VerifiedNoop
7935        );
7936    }
7937
7938    fn approval_question(run: &str) -> ask::Question {
7939        ask::Question::new(
7940            run.to_owned(),
7941            land::APPROVAL_NODE.to_owned(),
7942            "land".to_owned(),
7943            "merge?".to_owned(),
7944            String::new(),
7945            vec!["merge".to_owned(), "hold".to_owned()],
7946        )
7947    }
7948
7949    #[test]
7950    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
7951        crate::run::pin_test_home();
7952        let mut state = run_state(RunStatus::Landing);
7953        state.id = "20260101-000000-fre1".to_owned();
7954        state.parked = true;
7955        state.save().unwrap();
7956        ask::Questions::open()
7957            .put(&mut approval_question(&state.id))
7958            .unwrap();
7959
7960        let mut t = task();
7961        t.runs.push(state.id.clone());
7962        assert_eq!(
7963            land_resume_state(&t),
7964            LandResume::StillWaiting,
7965            "nobody has answered and the timeout has not passed"
7966        );
7967    }
7968
7969    #[test]
7970    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
7971        crate::run::pin_test_home();
7972        let mut state = run_state(RunStatus::Gating);
7973        state.id = "20260101-000000-gt01".to_owned();
7974        state.parked = true;
7975        state.config.graph.answer_timeout = 60;
7976        state.github_text = Some(crate::run::GithubTextAsk {
7977            rewrite: None,
7978            fingerprint: "f".into(),
7979            title: true,
7980            body: false,
7981            categories: vec!["title-language".into()],
7982            question: None,
7983            asks: 1,
7984            resolved: false,
7985            chosen_title: None,
7986            choice: None,
7987        });
7988        state.save().unwrap();
7989        let store = ask::Questions::open();
7990        let mut q = ask::Question::new(
7991            state.id.clone(),
7992            crate::github_text::ASK_NODE.to_owned(),
7993            crate::github_text::ASK_SEAT.to_owned(),
7994            "s".into(),
7995            String::new(),
7996            vec!["use fallback".into()],
7997        );
7998        store.put(&mut q).unwrap();
7999        let mut t = task();
8000        t.runs.push(state.id.clone());
8001        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
8002        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
8003        store.put(&mut q).unwrap();
8004        assert_eq!(land_resume_state(&t), LandResume::Ready);
8005        assert!(!store.get(&q.id).unwrap().status.open());
8006        // Once decided, a parked run is an ordinary candidate again.
8007        state.github_text.as_mut().unwrap().resolved = true;
8008        state.save().unwrap();
8009        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
8010    }
8011
8012    #[test]
8013    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
8014        // `ask::ask_and_wait`'s own deadline used to retire a question
8015        // nobody answered; land's approval bypasses that wait (see
8016        // `land::approval_gate`), so this is now the only place
8017        // `graph.answer_timeout` is enforced for a land approval at all.
8018        crate::run::pin_test_home();
8019        let mut state = run_state(RunStatus::Landing);
8020        state.id = "20260101-000000-exp1".to_owned();
8021        state.parked = true;
8022        state.config.graph.answer_timeout = 60;
8023        state.save().unwrap();
8024
8025        let store = ask::Questions::open();
8026        let mut q = approval_question(&state.id);
8027        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
8028        store.put(&mut q).unwrap();
8029
8030        let mut t = task();
8031        t.runs.push(state.id.clone());
8032        assert_eq!(
8033            land_resume_state(&t),
8034            LandResume::Ready,
8035            "an expired question must not be waited on forever"
8036        );
8037
8038        let after = store.get(&q.id).unwrap();
8039        assert!(
8040            !after.status.open(),
8041            "the question is abandoned, not silently ignored"
8042        );
8043        assert!(
8044            after.resolution().is_none(),
8045            "an abandoned question is not read as a decision"
8046        );
8047    }
8048
8049    #[test]
8050    fn reclaim_settles_a_running_task_against_its_last_run() {
8051        let mut t = task();
8052        t.start("20260904-000000-4043".to_owned());
8053        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
8054        assert_eq!(
8055            t.status,
8056            TaskStatus::Done,
8057            "a run that actually finished must not stay `running` forever"
8058        );
8059    }
8060
8061    #[test]
8062    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
8063        let mut t = task();
8064        t.start("20260904-000000-4043".to_owned());
8065        t.last_error = Some("earlier trouble".to_owned());
8066        let mut state = run_state(RunStatus::Judging);
8067        state.parked = true;
8068        reclaim(&mut t, Some(state), 1, "en");
8069        assert_eq!(t.status, TaskStatus::Parked);
8070        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
8071        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8072        assert!(t.park_reason.is_some());
8073        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
8074        assert!(!t.fresh_start);
8075        assert!(t.status.runnable());
8076    }
8077
8078    #[test]
8079    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
8080        let mut t = task();
8081        t.start("20260904-000000-4043".to_owned());
8082        t.last_error = Some("earlier trouble".to_owned());
8083        settle(
8084            &mut t,
8085            Verdict {
8086                status: RunStatus::Judging,
8087                left_pr: false,
8088                quota_hit: false,
8089                parked: true,
8090                no_viable_candidates: false,
8091            },
8092            "parked after `judging`",
8093            1,
8094        );
8095        assert_eq!(t.status, TaskStatus::Parked);
8096        assert_eq!(t.attempts, 0);
8097        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8098        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
8099        assert_eq!(t.schema, crate::queue::SCHEMA);
8100        assert!(
8101            crate::notices::task_held(&t).is_none(),
8102            "a park is not news"
8103        );
8104        t.start("20260904-000000-4043".to_owned());
8105        assert_eq!(t.park_reason, None);
8106    }
8107
8108    #[test]
8109    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
8110        // A blocked run with attempts left goes back to `Failed`, exactly as
8111        // it would from `attempt` itself - `reclaim` must not invent a second
8112        // policy for a task a daemon merely stopped without reporting.
8113        let mut t = task();
8114        t.start("20260904-000000-4043".to_owned());
8115        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
8116        assert_eq!(t.status, TaskStatus::Failed);
8117        assert!(t.status.runnable());
8118    }
8119
8120    #[test]
8121    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
8122        let mut t = task();
8123        t.start("20260904-000000-4043".to_owned());
8124        assert_eq!(t.attempts, 1);
8125        let mut run = run_state(RunStatus::Implementing);
8126        run.id = "20260904-000000-4043".to_owned();
8127        run.begin_pass();
8128        let cause = crate::run::ParkCause::Upgrade {
8129            from: "0.121.0".to_owned(),
8130            to: Some("0.121.1".to_owned()),
8131        };
8132        run.end_pass_parked(cause.clone());
8133        run.parked = true;
8134        let verdict = Verdict {
8135            status: run.status,
8136            left_pr: false,
8137            quota_hit: false,
8138            parked: true,
8139            no_viable_candidates: false,
8140        };
8141        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
8142        assert_eq!(t.attempts, 0);
8143        assert_eq!(t.passes.len(), 1);
8144        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8145        assert_eq!(t.passes[0].parked, Some(cause));
8146        assert_eq!(t.passes[0].pass_index, 0);
8147
8148        // A resumed pass that then fails spends its attempt, and the earlier
8149        // pass's entry is untouched.
8150        t.start("20260904-000000-4043".to_owned());
8151        run.begin_pass();
8152        run.status = RunStatus::Failed;
8153        let verdict = Verdict {
8154            status: RunStatus::Failed,
8155            left_pr: false,
8156            quota_hit: false,
8157            parked: false,
8158            no_viable_candidates: false,
8159        };
8160        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
8161        assert_eq!(t.passes.len(), 2);
8162        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8163        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
8164        assert_eq!(t.passes[1].pass_index, 1);
8165        assert_eq!(t.attempts, 1);
8166    }
8167
8168    #[test]
8169    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
8170        let mut t = task();
8171        t.start("20260904-000000-4043".to_owned());
8172        reclaim(&mut t, None, 2, "en");
8173        assert_eq!(t.status, TaskStatus::Held);
8174        assert!(
8175            t.last_error
8176                .as_deref()
8177                .is_some_and(|e| e.contains("running")),
8178            "the operator needs to know why this task was held"
8179        );
8180    }
8181
8182    #[test]
8183    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
8184        let dir = tempfile::tempdir().unwrap();
8185        let queue = Queue::at(dir.path().to_path_buf());
8186
8187        // No run recorded, so this never has to touch `RunState::load`.
8188        let mut orphaned = task();
8189        orphaned.id = "20260904-000000-orph".to_owned();
8190        orphaned.status = TaskStatus::Running;
8191        orphaned.attempts = 1;
8192        queue.put(&mut orphaned).unwrap();
8193
8194        let mut alive = task();
8195        alive.id = "20260904-000000-live".to_owned();
8196        alive.status = TaskStatus::Running;
8197        alive.attempts = 1;
8198        queue.put(&mut alive).unwrap();
8199        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
8200
8201        let mut queued = task();
8202        queued.id = "20260904-000000-wait".to_owned();
8203        queue.put(&mut queued).unwrap();
8204
8205        let reclaimed = reclaim_orphaned_running(&queue, 2);
8206        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
8207
8208        assert_eq!(
8209            queue.get(&orphaned.id).unwrap().status,
8210            TaskStatus::Held,
8211            "nothing was driving it and there was no run to recover"
8212        );
8213        assert_eq!(
8214            queue.get(&alive.id).unwrap().status,
8215            TaskStatus::Running,
8216            "a live claim must protect the task it belongs to"
8217        );
8218        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
8219    }
8220
8221    /// Read a run.json back from an explicit `home`, the same way
8222    /// `reclaim_abandoned_runs` itself does - never through the
8223    /// process-global `RunState::load`, which this test's own `home` (an
8224    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
8225    /// use at all.
8226    fn read_run_under(home: &Path, id: &str) -> RunState {
8227        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
8228        serde_json::from_str(&body).unwrap()
8229    }
8230
8231    #[test]
8232    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
8233        let dir = tempfile::tempdir().unwrap();
8234        let home = dir.path().to_path_buf();
8235        let now = Timestamp::now();
8236        let overrun_seat = || crate::run::ActiveSeat {
8237            node: "implement".to_owned(),
8238            started_at: now - jiff::SignedDuration::new(21_000, 0),
8239            timeout_secs: 3_600,
8240            attempt: 0,
8241            task: None,
8242            command: None,
8243            index: None,
8244            total: None,
8245        };
8246
8247        let mut dead = run_state(RunStatus::Implementing);
8248        dead.id = "20260101-000000-dead".to_owned();
8249        dead.active.insert("impl-A".to_owned(), overrun_seat());
8250        // A `driver_pid` the injected query below confirms gone outright —
8251        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
8252        dead.driver_pid = Some(4242);
8253        dead.save_under(&home).unwrap();
8254
8255        // Same shape, but a live daemon's heartbeat names it: must be left
8256        // exactly alone, however far past its own timeout the seat sits.
8257        let mut alive = run_state(RunStatus::Implementing);
8258        alive.id = "20260101-000000-aliv".to_owned();
8259        alive.active.insert("impl-A".to_owned(), overrun_seat());
8260        alive.save_under(&home).unwrap();
8261        let mut status = Status::new();
8262        status.current = vec![Current {
8263            task: "20260101-000000-task".to_owned(),
8264            run: alive.id.clone(),
8265        }];
8266        write_status_to(&home.join("daemon.json"), &status).unwrap();
8267
8268        // The abandoned seat left an open question behind: nobody is left to
8269        // read an answer once the run is failed, and this must not wait for
8270        // some later daemon startup's own sweep to notice that.
8271        let questions = Questions::at(home.join("questions"));
8272        let mut q = ask::Question::new(
8273            dead.id.clone(),
8274            "implement".to_owned(),
8275            "impl-A".to_owned(),
8276            "Which storage backend?".to_owned(),
8277            String::new(),
8278            vec!["SQLite".to_owned(), "Redis".to_owned()],
8279        );
8280        questions.put(&mut q).unwrap();
8281
8282        let abandoned = reclaim_abandoned_runs_with(
8283            &home,
8284            now,
8285            |pid| if pid == 4242 { Some(false) } else { None },
8286            |_| panic!("a query answering Dead outright needs no identity corroboration"),
8287        );
8288        assert_eq!(abandoned, vec![dead.id.clone()]);
8289
8290        let reloaded = read_run_under(&home, &dead.id);
8291        assert_eq!(reloaded.status, RunStatus::Failed);
8292        assert!(reloaded.active.is_empty());
8293        assert!(
8294            !questions.get(&q.id).unwrap().status.open(),
8295            "the failed run's own open question must be settled in the same pass"
8296        );
8297
8298        let still_alive = read_run_under(&home, &alive.id);
8299        assert_eq!(
8300            still_alive.status,
8301            RunStatus::Implementing,
8302            "a live daemon's claim protects it"
8303        );
8304        assert!(!still_alive.active.is_empty());
8305    }
8306
8307    /// The exact shape a review round flagged as broken: `magi serve` running
8308    /// in this same `home` scans *every* run on disk, including a manual
8309    /// `magi review` / `magi run` this daemon never started and that
8310    /// therefore claims no heartbeat of its own. Before this scan asked
8311    /// `liveness` rather than just `is_working_on`, a manual run whose active
8312    /// seat merely ran a little past its own timeout — the CLI finishing up,
8313    /// its result still being collected — got wiped and failed by a daemon
8314    /// that had nothing to do with it, out from under a process that was
8315    /// still very much running.
8316    #[test]
8317    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
8318        let dir = tempfile::tempdir().unwrap();
8319        let home = dir.path().to_path_buf();
8320        let now = Timestamp::now();
8321
8322        let mut manual = run_state(RunStatus::Reviewing);
8323        manual.id = "20260101-000000-manl".to_owned();
8324        manual.active.insert(
8325            "review-1".to_owned(),
8326            crate::run::ActiveSeat {
8327                node: "review".to_owned(),
8328                started_at: now - jiff::SignedDuration::new(21_000, 0),
8329                timeout_secs: 3_600,
8330                attempt: 0,
8331                task: None,
8332                command: None,
8333                index: None,
8334                total: None,
8335            },
8336        );
8337        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
8338        // but a real, still-running process: `liveness` must corroborate this
8339        // as `Live`, not read the missing daemon claim as death.
8340        manual.driver_pid = Some(4242);
8341        manual.driver_started_at = Some("1790000000".to_owned());
8342        manual.save_under(&home).unwrap();
8343
8344        let abandoned = reclaim_abandoned_runs_with(
8345            &home,
8346            now,
8347            |pid| if pid == 4242 { Some(true) } else { None },
8348            |pid| {
8349                if pid == 4242 {
8350                    Some("1790000000".to_owned())
8351                } else {
8352                    None
8353                }
8354            },
8355        );
8356        assert!(
8357            abandoned.is_empty(),
8358            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
8359        );
8360
8361        let reloaded = read_run_under(&home, &manual.id);
8362        assert_eq!(reloaded.status, RunStatus::Reviewing);
8363        assert!(!reloaded.active.is_empty());
8364    }
8365
8366    #[test]
8367    fn an_already_claimed_task_is_skipped_rather_than_failed() {
8368        let dir = tempfile::tempdir().unwrap();
8369        let queue = Queue::at(dir.path().to_path_buf());
8370        let mut only = task();
8371        queue.put(&mut only).unwrap();
8372
8373        let _elsewhere = queue.claim(&only.id).unwrap();
8374        let candidates = runnable(&queue);
8375        assert_eq!(candidates.len(), 1, "the task is still runnable");
8376        assert!(
8377            queue.claim(&candidates[0].id).is_err(),
8378            "the loop cannot take a claim somebody else holds"
8379        );
8380
8381        let after = queue.get(&only.id).unwrap();
8382        assert_eq!(after.status, TaskStatus::Queued);
8383        assert_eq!(
8384            after.attempts, 0,
8385            "losing the race is not an attempt at the task"
8386        );
8387        assert_eq!(after.last_error, None);
8388    }
8389
8390    #[test]
8391    fn the_status_file_round_trips_and_its_heartbeat_advances() {
8392        let dir = tempfile::tempdir().unwrap();
8393        let path = dir.path().join("daemon.json");
8394
8395        let mut status = Status::new();
8396        status.idle = false;
8397        status.completed = 7;
8398        status.current = vec![Current {
8399            task: "20260902-000000-t111".to_owned(),
8400            run: "20260902-000001-r111".to_owned(),
8401        }];
8402        write_status_to(&path, &status).unwrap();
8403        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8404        assert_eq!(first.schema, SCHEMA);
8405        assert_eq!(first.pid, std::process::id());
8406        assert!(!first.idle);
8407        assert_eq!(first.completed, 7);
8408        assert_eq!(first.current, status.current);
8409        assert!(
8410            !path.with_extension("json.tmp").exists(),
8411            "the temp file is renamed, not left behind"
8412        );
8413
8414        std::thread::sleep(Duration::from_millis(5));
8415        status.updated_at = Timestamp::now();
8416        status.polls = 3;
8417        write_status_to(&path, &status).unwrap();
8418        let second: Status =
8419            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8420        assert!(
8421            second.updated_at > first.updated_at,
8422            "a reader can only detect staleness if the heartbeat moves"
8423        );
8424        assert_eq!(
8425            second.started_at, first.started_at,
8426            "the start time is not a heartbeat"
8427        );
8428        assert_eq!(second.polls, 3);
8429    }
8430
8431    #[test]
8432    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
8433        let dir = tempfile::tempdir().unwrap();
8434
8435        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
8436
8437        let mut status = Status::new();
8438        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
8439        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8440        let stale = read_status(dir.path()).unwrap();
8441        assert!(
8442            !stale.running(Timestamp::now()),
8443            "a minute without a heartbeat is a dead daemon, not a busy one"
8444        );
8445        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
8446
8447        status.updated_at = Timestamp::now();
8448        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8449        let fresh = read_status(dir.path()).unwrap();
8450        assert!(fresh.running(Timestamp::now()));
8451    }
8452
8453    #[test]
8454    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
8455        let dir = tempfile::tempdir().unwrap();
8456        let now = Timestamp::now();
8457        let mine = "20260903-080619-01c2";
8458
8459        assert!(
8460            !is_working_on(dir.path(), mine, 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: mine.to_owned(),
8468        }];
8469        status.updated_at = now;
8470        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8471        assert!(is_working_on(dir.path(), mine, now));
8472        assert!(
8473            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
8474            "a daemon busy with one run is not working on another"
8475        );
8476
8477        // A killed daemon stops writing heartbeats but leaves the file behind
8478        // naming the run it died in. That run must not be undeletable forever.
8479        status.updated_at = now - jiff::SignedDuration::from_secs(600);
8480        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8481        assert!(
8482            !is_working_on(dir.path(), mine, now),
8483            "a stale heartbeat is a dead daemon, so its run is a leftover"
8484        );
8485    }
8486
8487    #[test]
8488    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
8489        let dir = tempfile::tempdir().unwrap();
8490        let now = Timestamp::now();
8491
8492        assert!(
8493            !is_working_on_short(dir.path(), "01c2", now),
8494            "no status file means nobody is working on anything"
8495        );
8496
8497        let mut status = Status::new();
8498        status.current = vec![Current {
8499            task: "20260903-080340-0167".to_owned(),
8500            run: "20260903-080619-01c2".to_owned(),
8501        }];
8502        status.updated_at = now;
8503        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8504        assert!(
8505            is_working_on_short(dir.path(), "01c2", now),
8506            "the run's short id is the last block of its full id"
8507        );
8508        assert!(
8509            !is_working_on_short(dir.path(), "3cbf", now),
8510            "a daemon busy with one worktree bay is not working on another"
8511        );
8512    }
8513
8514    #[test]
8515    fn a_newer_status_file_still_yields_a_reading() {
8516        let dir = tempfile::tempdir().unwrap();
8517        // A field this build has never heard of must not turn the reading into
8518        // nothing at all; that is the whole reason the reader is permissive.
8519        std::fs::write(
8520            dir.path().join("daemon.json"),
8521            serde_json::json!({
8522                "schema": 2,
8523                "updated_at": Timestamp::now().to_string(),
8524                "idle": true,
8525                "surprise": { "nested": [1, 2, 3] },
8526            })
8527            .to_string(),
8528        )
8529        .unwrap();
8530
8531        let reading = read_status(dir.path()).expect("a forward-compatible read");
8532        assert!(reading.running(Timestamp::now()));
8533        assert!(reading.idle);
8534        assert!(reading.current.is_empty());
8535    }
8536
8537    #[test]
8538    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
8539        // A daemon started before `current` became a list keeps writing this
8540        // shape on every heartbeat until it is restarted. A rolling upgrade
8541        // - a newer `magi web` or `magi doctor` reading an older `magi
8542        // serve`'s heartbeat - must still see the run it is on, not "no
8543        // daemon" from a type mismatch failing the whole struct.
8544        let dir = tempfile::tempdir().unwrap();
8545        std::fs::write(
8546            dir.path().join("daemon.json"),
8547            serde_json::json!({
8548                "schema": 1,
8549                "pid": 4242,
8550                "updated_at": Timestamp::now().to_string(),
8551                "idle": false,
8552                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
8553                "completed": 3,
8554                "polls": 9,
8555            })
8556            .to_string(),
8557        )
8558        .unwrap();
8559
8560        let reading = read_status(dir.path()).expect("an older shape must still parse");
8561        assert!(reading.running(Timestamp::now()));
8562        assert_eq!(
8563            reading.current,
8564            vec![Current {
8565                task: "20260902-140501-aaaa".to_owned(),
8566                run: "20260902-140502-bbbb".to_owned(),
8567            }]
8568        );
8569    }
8570
8571    #[test]
8572    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
8573        let dir = tempfile::tempdir().unwrap();
8574        std::fs::write(
8575            dir.path().join("daemon.json"),
8576            serde_json::json!({
8577                "schema": 1,
8578                "updated_at": Timestamp::now().to_string(),
8579                "idle": true,
8580                "current": null,
8581            })
8582            .to_string(),
8583        )
8584        .unwrap();
8585        let with_null = read_status(dir.path()).expect("null must still parse");
8586        assert!(with_null.current.is_empty());
8587
8588        std::fs::write(
8589            dir.path().join("daemon.json"),
8590            serde_json::json!({
8591                "schema": 1,
8592                "updated_at": Timestamp::now().to_string(),
8593                "idle": true,
8594            })
8595            .to_string(),
8596        )
8597        .unwrap();
8598        let absent = read_status(dir.path()).expect("a missing field must still parse");
8599        assert!(absent.current.is_empty());
8600    }
8601
8602    #[test]
8603    fn a_task_without_a_repository_runs_in_the_daemons_default() {
8604        let fallback = Path::new("/default");
8605        let mut blank = task();
8606        blank.repo = PathBuf::new();
8607        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
8608        let mut dot = task();
8609        dot.repo = PathBuf::from(".");
8610        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
8611        assert_eq!(
8612            repo_for(&task(), fallback),
8613            PathBuf::from("/repo"),
8614            "a task that names a repository keeps it"
8615        );
8616    }
8617
8618    #[test]
8619    fn task_implementers_edit_inherits_daemon_config_and_merge() {
8620        let dir = tempfile::tempdir().unwrap();
8621        let path = dir.path().join("explicit.toml");
8622        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
8623        let opts = Opts {
8624            config: Some(path),
8625            merge: Some("none".into()),
8626            ..Default::default()
8627        };
8628        let mut t = task();
8629        t.set_implementers(
8630            2,
8631            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8632                .unwrap(),
8633        )
8634        .unwrap();
8635        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8636        assert_eq!(cfg.graph.implementers, 2);
8637        assert_eq!(cfg.graph.judges, 1);
8638        assert_eq!(cfg.merge.mode, MergeMode::None);
8639        t.set_implementers(1, &cfg).unwrap();
8640        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8641        apply_task_implementers(&mut cfg, &t);
8642        assert_eq!(cfg.graph.implementers, 1);
8643        assert_eq!(cfg.graph.judges, 1);
8644        assert_eq!(cfg.merge.mode, MergeMode::None);
8645    }
8646
8647    #[test]
8648    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
8649        let dir = tempfile::tempdir().unwrap();
8650        let repo = dir.path().join("repo");
8651        std::fs::create_dir(&repo).unwrap();
8652        std::fs::write(
8653            repo.join("magi.toml"),
8654            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
8655        )
8656        .unwrap();
8657        let daemon_config = dir.path().join("daemon.toml");
8658        std::fs::write(
8659            &daemon_config,
8660            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
8661        )
8662        .unwrap();
8663        let opts = Opts {
8664            config: Some(daemon_config),
8665            merge: Some("pr".into()),
8666            ..Default::default()
8667        };
8668        let q = Queue::at(dir.path().join("queue"));
8669        let validation: Config =
8670            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8671                .unwrap();
8672        // No provenance field on legacy direct tasks: both shapes stay isolated.
8673        for record in ["{}", r#"{"candidates":2}"#] {
8674            let overrides = serde_json::from_str(record).unwrap();
8675            let filing = crate::direct::Filing {
8676                instruction: "work".into(),
8677                title: "direct".into(),
8678                repo: repo.clone(),
8679                source: crate::queue::Source::Human,
8680                solo: false,
8681                overrides,
8682                review_of: None,
8683                sources: Default::default(),
8684            };
8685            let filed =
8686                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
8687            let crate::direct::Filed::Standalone {
8688                mut task,
8689                claim: _claim,
8690            } = filed
8691            else {
8692                panic!("local filing")
8693            };
8694            let before = prepare_for(&repo, &opts, &task).unwrap();
8695            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
8696            assert_eq!(
8697                before.merge.mode,
8698                MergeMode::None,
8699                "daemon --merge must not leak"
8700            );
8701            for n in [2, 1, 2] {
8702                task.set_implementers(n, &validation).unwrap();
8703                q.put(&mut task).unwrap();
8704                task = q.get(&task.id).unwrap();
8705                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
8706                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
8707                apply_task_implementers(&mut cfg, &task);
8708                assert_eq!(cfg.graph.implementers, usize::from(n));
8709                assert_eq!(cfg.graph.judges, 2);
8710                assert_eq!(cfg.merge.mode, MergeMode::None);
8711            }
8712        }
8713    }
8714
8715    #[test]
8716    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
8717        let cfg: Config =
8718            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8719                .unwrap();
8720        let mut t = task();
8721        t.review_of = Some("review-target".into());
8722        t.hold_manual(Some("retry".into()));
8723        let mut previous = RunState::new(
8724            PathBuf::from("/repo"),
8725            "main".into(),
8726            "abc1234".into(),
8727            "review".into(),
8728            cfg.clone(),
8729        );
8730        previous.config.graph.implementers = 2;
8731        for count in [1, 3] {
8732            t.set_implementers(count, &cfg).unwrap();
8733            t.release();
8734            assert_eq!(t.review_of.as_deref(), Some("review-target"));
8735            for proposed in [
8736                Starter::Resume(previous.id.clone()),
8737                Starter::Review("recovery-target".into()),
8738            ] {
8739                assert_eq!(
8740                    starter_with_implementers(&t, Some(&previous), proposed),
8741                    Starter::Review("review-target".into())
8742                );
8743            }
8744            let mut configured = cfg.clone();
8745            apply_task_implementers(&mut configured, &t);
8746            assert_eq!(configured.graph.implementers, usize::from(count));
8747            assert_eq!(previous.config.graph.implementers, 2);
8748        }
8749    }
8750
8751    #[test]
8752    fn task_implementers_dispatch_and_resume_agree() {
8753        let mut t = task();
8754        let cfg: crate::config::Config =
8755            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8756                .unwrap();
8757        let mut run = RunState::new(
8758            PathBuf::from("/repo"),
8759            "main".into(),
8760            "abc1234".into(),
8761            "work".into(),
8762            cfg.clone(),
8763        );
8764        run.config.graph.implementers = 2;
8765        for n in [2, 1, 3, 2] {
8766            t.set_implementers(n, &cfg).unwrap();
8767            let mut dispatched = cfg.clone();
8768            apply_task_implementers(&mut dispatched, &t);
8769            assert_eq!(dispatched.graph.implementers, usize::from(n));
8770            assert_eq!(implementers_match(&t, &run), n == 2);
8771            for proposed in [
8772                Starter::Resume(run.id.clone()),
8773                Starter::Review("old-branch".into()),
8774            ] {
8775                let expected = if n == 2 {
8776                    proposed.clone()
8777                } else {
8778                    Starter::Start
8779                };
8780                assert_eq!(
8781                    starter_with_implementers(&t, Some(&run), proposed),
8782                    expected
8783                );
8784            }
8785            assert_eq!(
8786                run.config.graph.implementers, 2,
8787                "history must not be rewritten"
8788            );
8789        }
8790        t.solo = false;
8791        t.overrides = None;
8792        assert!(implementers_match(&t, &run));
8793    }
8794
8795    #[test]
8796    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
8797        // Three seats said out loud. What `solo` promises is one candidate
8798        // *whatever the config asks for*, so the contrast has to be a number
8799        // this test owns - it used to be `Config::default()`'s, which became
8800        // 1 when one implementation became the default and left the two
8801        // halves of this test asserting the same thing.
8802        let mut solo_cfg = Config::default();
8803        solo_cfg.graph.implementers = 3;
8804        let mut solo_task = task();
8805        solo_task.solo = true;
8806        apply_task_implementers(&mut solo_cfg, &solo_task);
8807        assert_eq!(solo_cfg.graph.implementers, 1);
8808
8809        let mut plain_cfg = Config::default();
8810        plain_cfg.graph.implementers = 3;
8811        let plain_task = task();
8812        assert!(!plain_task.solo);
8813        apply_task_implementers(&mut plain_cfg, &plain_task);
8814        assert_eq!(
8815            plain_cfg.graph.implementers, 3,
8816            "a task that did not ask to run alone keeps the config's candidates"
8817        );
8818    }
8819
8820    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
8821        QuotaLoss {
8822            seat: seat.into(),
8823            node: "judge".into(),
8824            at: at.parse().unwrap(),
8825            reset: reset.map(str::to_string),
8826        }
8827    }
8828
8829    #[test]
8830    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
8831        let old: Vec<QuotaLoss> = (1..=4)
8832            .map(|i| {
8833                loss(
8834                    &format!("judge-{i}"),
8835                    "2026-09-23T05:23:00Z",
8836                    Some("2:40pm (Asia/Tokyo)"),
8837                )
8838            })
8839            .collect();
8840        let fresh = losses_this_attempt(&old, &old);
8841        assert!(fresh.is_empty());
8842        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
8843        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
8844    }
8845
8846    #[test]
8847    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
8848        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
8849        let now = Timestamp::now();
8850        let mut after = old.clone();
8851        after.push(loss("judge-2", &now.to_string(), None));
8852        let fresh = losses_this_attempt(&old, &after);
8853        assert_eq!(fresh, vec![after[1].clone()]);
8854        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
8855        assert_eq!(
8856            until,
8857            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
8858        );
8859    }
8860
8861    #[test]
8862    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
8863        // `recover_stall` removes judge-1's loss and the retry then hits quota
8864        // again: the vector is the same length, so an index diff sees nothing.
8865        let before = vec![
8866            loss("judge-1", "2026-09-23T05:23:00Z", None),
8867            loss("judge-2", "2026-09-23T05:24:00Z", None),
8868        ];
8869        let after = vec![
8870            loss("judge-2", "2026-09-23T05:24:00Z", None),
8871            loss("judge-1", "2026-09-24T01:00:00Z", None),
8872        ];
8873        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
8874    }
8875
8876    #[test]
8877    fn merge_overrides_are_parsed_or_refused() {
8878        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
8879        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
8880        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
8881        assert!(merge_mode("squash").is_err());
8882    }
8883
8884    #[test]
8885    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
8886        let now = Timestamp::now();
8887        let fallback = Duration::from_secs(300);
8888        let cap = Duration::from_secs(1800);
8889
8890        // No reset hint at all: the fallback.
8891        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
8892
8893        // A reset ten minutes out, well inside the cap: waited for exactly.
8894        let soon = now + jiff::SignedDuration::from_secs(600);
8895        assert_eq!(
8896            quota_wait(Some(soon), now, fallback, cap),
8897            Duration::from_secs(600)
8898        );
8899
8900        // A reset already in the past is not trusted: the fallback, not a
8901        // zero or negative wait that would spin the loop right back around.
8902        let past = now - jiff::SignedDuration::from_secs(60);
8903        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
8904
8905        // A reset further out than the cap is trusted for direction but not
8906        // for magnitude: a parsing slip must not sleep the loop for a day.
8907        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
8908        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
8909    }
8910
8911    #[test]
8912    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
8913        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8914
8915        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
8916        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
8917
8918        // Same clock reading, but it has already gone by today: read as
8919        // tomorrow's, since the CLI would not still be reporting a limit past
8920        // its own stated reset.
8921        let already_past =
8922            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
8923        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
8924
8925        assert!(
8926            parse_reset_hint("session limit reached", now, now).is_none(),
8927            "free text with no recognised shape is not guessed at"
8928        );
8929        assert!(
8930            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
8931            "an unresolvable zone name is not guessed at either"
8932        );
8933    }
8934
8935    #[test]
8936    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
8937        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8938
8939        let at = parse_reset_hint(
8940            "You've hit your usage limit. Visit \
8941             https://chatgpt.com/codex/settings/usage to purchase more \
8942             credits or try again at Sep 19th, 2026 5:10 PM.",
8943            now,
8944            now,
8945        )
8946        .expect("the codex reset wording is a recognised shape");
8947        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
8948
8949        // The month is explicit, so a date already earlier in the same
8950        // sentence-implied year than `now` is trusted as written rather than
8951        // rolled forward a year the way the bracketed shape rolls a
8952        // same-day clock reading to tomorrow.
8953        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
8954            .expect("an explicit year needs no rollover");
8955        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
8956
8957        assert!(
8958            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
8959            "a two-digit year is not the documented shape and is not guessed at"
8960        );
8961        assert!(
8962            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
8963            "a four-letter month name is not the documented three-letter abbreviation"
8964        );
8965        assert!(
8966            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
8967            "an explicit zone on the dated shape is a format nobody has \
8968             documented, and is refused rather than guessed at as UTC"
8969        );
8970    }
8971
8972    #[test]
8973    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
8974        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
8975        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
8976
8977        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
8978        assert_eq!(at.as_second() - recorded.as_second(), 3769);
8979
8980        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
8981        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
8982
8983        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
8984            assert!(
8985                parse_reset_hint(bad, now, recorded).is_none(),
8986                "{bad:?} must not be guessed at"
8987            );
8988        }
8989    }
8990
8991    /// A loop whose queue lives in a temp tree and whose poll interval is far
8992    /// longer than the test's patience, so anything that waits out a poll
8993    /// instead of noticing the stop fails rather than merely being slow.
8994    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
8995        let config = dir.join("magi.toml");
8996        std::fs::write(
8997            &config,
8998            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
8999        )
9000        .unwrap();
9001        let opts = Opts {
9002            poll: Duration::from_secs(30),
9003            config: Some(config),
9004            // The explicit fixture config keeps startup cleanup from reading
9005            // machine configuration. This fictional repository likewise
9006            // keeps any best-effort git cleanup away from this checkout.
9007            repo: dir.join("repo"),
9008            ..Opts::default()
9009        };
9010        // The status file goes in a directory that does not exist yet, so its
9011        // creation is itself evidence the loop published one. `worktrees`
9012        // must be just as fictional: the janitor reclaims worktrees under it
9013        // for real, and a test that let it fall through to
9014        // `crate::run::default_worktree_root()` would have it reclaim
9015        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
9016        // which is exactly what happened before this function took the
9017        // parameter at all.
9018        let home = dir.join("home");
9019        let worktrees = dir.join("wt");
9020        (
9021            opts,
9022            Queue::at(dir.join("queue")),
9023            home.join("daemon.json"),
9024            home,
9025            worktrees,
9026        )
9027    }
9028
9029    #[test]
9030    fn a_stop_is_idempotent_and_once_set_stays_set() {
9031        let stop = Stop::new();
9032        assert!(!stop.stopped());
9033
9034        stop.stop();
9035        assert!(stop.stopped());
9036        stop.stop();
9037        assert!(stop.stopped(), "a second stop is not a toggle");
9038
9039        let shared = stop.clone();
9040        assert!(
9041            shared.stopped(),
9042            "a clone is the same stop; that is how the loop and its caller share one"
9043        );
9044    }
9045
9046    #[test]
9047    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
9048        let stop = Stop::new();
9049        stop.enter();
9050        assert!(
9051            !stop.finishing(),
9052            "a busy loop nobody has asked to stop is just running"
9053        );
9054
9055        stop.stop();
9056        assert!(
9057            stop.finishing(),
9058            "a stop asked for mid-run has not landed until the run is settled"
9059        );
9060
9061        stop.exit();
9062        assert!(
9063            !stop.finishing(),
9064            "once the run is settled the stop has landed and there is nothing to finish"
9065        );
9066    }
9067
9068    #[test]
9069    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
9070        let stop = Stop::new();
9071        stop.enter();
9072        stop.enter();
9073        stop.stop();
9074        assert!(stop.finishing(), "two runs still in flight");
9075
9076        stop.exit();
9077        assert!(
9078            stop.finishing(),
9079            "one run finished, but a sibling is still working"
9080        );
9081
9082        stop.exit();
9083        assert!(
9084            !stop.finishing(),
9085            "the last run out is what actually lands the stop"
9086        );
9087    }
9088
9089    #[tokio::test]
9090    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
9091        let dir = tempfile::tempdir().unwrap();
9092        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9093        let stop = Stop::new();
9094        stop.stop();
9095
9096        let began = std::time::Instant::now();
9097        tokio::time::timeout(
9098            Duration::from_secs(2),
9099            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9100        )
9101        .await
9102        .expect("a stopped loop must return, not sit out its poll interval")
9103        .expect("the loop's own setup and teardown must not fail");
9104        assert!(
9105            began.elapsed() < opts.poll,
9106            "returned only after {:?}, which is a poll interval, not a stop",
9107            began.elapsed()
9108        );
9109    }
9110
9111    #[tokio::test]
9112    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
9113        let dir = tempfile::tempdir().unwrap();
9114        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9115        let stop = Stop::new();
9116
9117        // Asked for after the loop is already parked on its empty queue, which
9118        // is the case an operator tapping stop on a phone actually hits.
9119        let asker = {
9120            let stop = stop.clone();
9121            tokio::spawn(async move {
9122                tokio::time::sleep(Duration::from_millis(20)).await;
9123                stop.stop();
9124            })
9125        };
9126
9127        let began = std::time::Instant::now();
9128        tokio::time::timeout(
9129            Duration::from_secs(2),
9130            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9131        )
9132        .await
9133        .expect("a stop asked for while idle must wake the wait")
9134        .expect("the loop's own setup and teardown must not fail");
9135        asker.await.unwrap();
9136        assert!(
9137            began.elapsed() < opts.poll,
9138            "returned only after {:?}, so the stop waited on the sleep",
9139            began.elapsed()
9140        );
9141    }
9142
9143    #[tokio::test]
9144    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
9145        let dir = tempfile::tempdir().unwrap();
9146        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9147        let stop = Stop::new();
9148        stop.stop();
9149
9150        tokio::time::timeout(
9151            Duration::from_secs(2),
9152            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9153        )
9154        .await
9155        .expect("a stopped loop must return")
9156        .expect("the loop's own setup and teardown must not fail");
9157
9158        assert!(
9159            home.is_dir(),
9160            "the loop did publish a status file, so its removal is the teardown and not an absence"
9161        );
9162        assert!(
9163            !status_file.exists(),
9164            "a stopped loop clears its status file"
9165        );
9166        assert!(
9167            read_status(&home).is_none(),
9168            "a reader must see no daemon at all, not a heartbeat that merely stopped"
9169        );
9170    }
9171
9172    #[tokio::test]
9173    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
9174        let dir = tempfile::tempdir().unwrap();
9175        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
9176        opts.once = true;
9177
9178        let mut settled = RunState::new(
9179            dir.path().join("repo"),
9180            "main".to_owned(),
9181            "abc1234".to_owned(),
9182            "fixture".to_owned(),
9183            Config::default(),
9184        );
9185        settled.status = RunStatus::Ready;
9186        let run_dir = home.join("runs").join(&settled.id);
9187        std::fs::create_dir_all(&run_dir).unwrap();
9188        std::fs::write(
9189            run_dir.join("run.json"),
9190            serde_json::to_string_pretty(&settled).unwrap(),
9191        )
9192        .unwrap();
9193        let questions = Questions::at(home.join("questions"));
9194        let mut question = ask::Question::new(
9195            settled.id.clone(),
9196            "review".to_owned(),
9197            "reviewer-1".to_owned(),
9198            "Continue?".to_owned(),
9199            String::new(),
9200            Vec::new(),
9201        );
9202        questions.put(&mut question).unwrap();
9203
9204        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
9205            .await
9206            .unwrap();
9207
9208        assert_eq!(
9209            questions.get(&question.id).unwrap().status,
9210            ask::QuestionStatus::Abandoned,
9211            "an empty --once drain still performs startup question cleanup"
9212        );
9213    }
9214
9215    #[test]
9216    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
9217        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9218
9219        assert!(
9220            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
9221            "never checked before: due at once"
9222        );
9223
9224        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
9225        assert!(
9226            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
9227            "well inside the interval: not due yet"
9228        );
9229
9230        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
9231        assert!(
9232            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
9233            "exactly at the edge: not yet due, same convention as `clean::due`"
9234        );
9235
9236        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9237        assert!(
9238            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
9239            "past the interval: due again"
9240        );
9241    }
9242
9243    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
9244    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
9245    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
9246    /// and the congestion test below both need, and must not drift apart.
9247    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
9248        let config = dir.join("magi.toml");
9249        // A literal (single-quoted) TOML string, not a basic one: the cache
9250        // path is a Windows path full of backslashes, and a basic string
9251        // would have TOML try to interpret `\U` (from `\Users\...`) as a
9252        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
9253        // `{{ vars.cache }}` rendering documents.
9254        std::fs::write(
9255            &config,
9256            format!(
9257                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
9258                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
9259                cache_dir.display()
9260            ),
9261        )
9262        .unwrap();
9263        Opts {
9264            config: Some(config),
9265            repo: dir.join("repo"),
9266            ..Opts::default()
9267        }
9268    }
9269
9270    #[tokio::test]
9271    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
9272        let dir = tempfile::tempdir().unwrap();
9273        let home = dir.path().join("home");
9274        let cache_dir = dir.path().join("cache");
9275        std::fs::create_dir_all(&cache_dir).unwrap();
9276        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9277        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9278
9279        // Nobody has asked this daemon to stop, which is the ordinary case;
9280        // the skip that a stop buys is asserted by its own test below.
9281        let running = Stop::new();
9282        let mut last_checked = None;
9283        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9284        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
9285            .await;
9286        assert_eq!(
9287            crate::disk::dir_size(&cache_dir),
9288            0,
9289            "over the cap on the first check ever: pruned at once, no idle queue required"
9290        );
9291        assert_eq!(last_checked, Some(t0));
9292
9293        // A fresh oversized file lands, but the next check is not due yet.
9294        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
9295        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
9296        maybe_prune_cache_between_runs(
9297            &opts.repo,
9298            &opts,
9299            &home,
9300            &running,
9301            &mut last_checked,
9302            too_soon,
9303        )
9304        .await;
9305        assert_eq!(
9306            crate::disk::dir_size(&cache_dir),
9307            10,
9308            "too soon since the last check: left alone rather than rescanned every call"
9309        );
9310        assert_eq!(
9311            last_checked,
9312            Some(t0),
9313            "an idle check does not reset the clock"
9314        );
9315
9316        // Once the interval elapses, the same oversized cache is caught again.
9317        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9318        maybe_prune_cache_between_runs(
9319            &opts.repo,
9320            &opts,
9321            &home,
9322            &running,
9323            &mut last_checked,
9324            due_again,
9325        )
9326        .await;
9327        assert_eq!(
9328            crate::disk::dir_size(&cache_dir),
9329            0,
9330            "due again: pruned back under the cap"
9331        );
9332    }
9333
9334    /// A stop must not queue behind housekeeping. The prune below is a
9335    /// synchronous walk of the whole cache with no await point in it, so a
9336    /// loop that entered it could not get back to its own `stopped()` test
9337    /// until the walk finished - and because no run is in flight at this
9338    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
9339    /// the stop had already landed. The idle branch has always made this same
9340    /// check before reaching `janitor`; the between-runs path makes it too.
9341    #[tokio::test]
9342    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
9343        let dir = tempfile::tempdir().unwrap();
9344        let home = dir.path().join("home");
9345        let cache_dir = dir.path().join("cache");
9346        std::fs::create_dir_all(&cache_dir).unwrap();
9347        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9348        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9349
9350        let stop = Stop::new();
9351        stop.stop();
9352        assert!(
9353            !stop.finishing(),
9354            "no run is in flight at a between-runs boundary, so nothing else \
9355             would tell the operator this stop had not taken effect yet"
9356        );
9357
9358        let mut last_checked = None;
9359        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9360        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
9361            .await;
9362        assert_eq!(
9363            crate::disk::dir_size(&cache_dir),
9364            10,
9365            "over its cap, and due for the first check ever, but a stop outranks \
9366             it: the cap is a standing policy the next start measures again"
9367        );
9368        assert_eq!(
9369            last_checked, None,
9370            "a check that never happened must not claim the interval"
9371        );
9372    }
9373
9374    /// The regression this whole change exists for: gate timeouts on runs
9375    /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
9376    /// GiB against a 10 GiB cap, because the operator's queue never had a
9377    /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
9378    /// `janitor` pass.
9379    ///
9380    /// Reproduced with a backlog whose repository is never created:
9381    /// `Runner::start` fails at `git::toplevel`, spawning no agent CLI.
9382    /// Each task is held after one startup failure, but the remaining tasks
9383    /// keep the queue busy until an external stop ends the loop.
9384    #[tokio::test]
9385    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
9386        let dir = tempfile::tempdir().unwrap();
9387        let cache_dir = dir.path().join("cache");
9388        std::fs::create_dir_all(&cache_dir).unwrap();
9389        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
9390
9391        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
9392        opts.poll = Duration::from_millis(20);
9393        opts.max_attempts = 1_000;
9394
9395        let queue = Queue::at(dir.path().join("queue"));
9396        for i in 0..128 {
9397            let mut task = Task::new(
9398                format!("queued work {i}"),
9399                format!("queued work {i}"),
9400                opts.repo.clone(),
9401                Source::Human,
9402            );
9403            queue.put(&mut task).unwrap();
9404        }
9405
9406        let home = dir.path().join("home");
9407        let worktrees = dir.path().join("wt");
9408        let status_file = home.join("daemon.json");
9409        let stop = Stop::new();
9410        let stopper = {
9411            let stop = stop.clone();
9412            let queue = Queue::at(dir.path().join("queue"));
9413            tokio::spawn(async move {
9414                // Observe completed work rather than rely on a wall-clock
9415                // delay. Every startup failure holds only its own task; the
9416                // backlog keeps offering work at the next boundary.
9417                for _ in 0..2_000 {
9418                    if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
9419                        break;
9420                    }
9421                    tokio::time::sleep(Duration::from_millis(5)).await;
9422                }
9423                stop.stop();
9424            })
9425        };
9426
9427        tokio::time::timeout(
9428            Duration::from_secs(20),
9429            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9430        )
9431        .await
9432        .expect("the loop must not hang on a queue that keeps producing failing work")
9433        .expect("the loop's own setup and teardown must not fail");
9434        stopper.await.unwrap();
9435
9436        let after = queue.list();
9437        let completed = after.iter().filter(|t| t.attempts == 1).count();
9438        assert!(
9439            completed >= 2,
9440            "the harness must have processed multiple tasks to exercise a busy queue \
9441             (got {completed} completed task(s))"
9442        );
9443        assert!(
9444            after.iter().any(|t| t.status.runnable()),
9445            "unprocessed tasks must remain: the external stop, rather than an \
9446             exhausted backlog, must end the test"
9447        );
9448        assert!(
9449            after
9450                .iter()
9451                .filter(|t| t.attempts > 0)
9452                .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
9453            "a busy backlog must not retry a task's unchanged startup failure"
9454        );
9455
9456        assert_eq!(
9457            crate::disk::dir_size(&cache_dir),
9458            0,
9459            "an oversized cache must not be left to grow unboundedly just because the \
9460             queue kept the loop busy the whole time"
9461        );
9462    }
9463
9464    #[test]
9465    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
9466        let dir = tempfile::tempdir().unwrap();
9467        let queue = Queue::at(dir.path().join("queue"));
9468        let questions = Questions::at(dir.path().join("questions"));
9469        let mut task = task();
9470        queue.put(&mut task).unwrap();
9471
9472        let mut task_question = ask::Question::new(
9473            task.id.clone(),
9474            crate::conduct::NODE.to_owned(),
9475            "conduct".to_owned(),
9476            "Which backend?".to_owned(),
9477            String::new(),
9478            Vec::new(),
9479        );
9480        questions.put(&mut task_question).unwrap();
9481        task.block(vec![task_question.id.clone()], None);
9482        queue.put(&mut task).unwrap();
9483
9484        let mut run_question = ask::Question::new(
9485            "20260101-000000-run1".to_owned(),
9486            "review".to_owned(),
9487            "reviewer-1".to_owned(),
9488            "Run question".to_owned(),
9489            String::new(),
9490            Vec::new(),
9491        );
9492        questions.put(&mut run_question).unwrap();
9493
9494        // A question from another node whose `run` happens to equal this
9495        // task's id — the same field, filled in for an unrelated reason. Only
9496        // `crate::conduct::NODE` questions use `run` as a task id; this one
9497        // must never be touched by this reconciliation, even after release.
9498        let mut coincidental = ask::Question::new(
9499            task.id.clone(),
9500            "review".to_owned(),
9501            "reviewer-1".to_owned(),
9502            "Unrelated review question".to_owned(),
9503            String::new(),
9504            Vec::new(),
9505        );
9506        questions.put(&mut coincidental).unwrap();
9507
9508        reconcile_task_questions(&queue, &questions);
9509        assert!(questions.get(&task_question.id).unwrap().status.open());
9510        assert!(questions.get(&run_question.id).unwrap().status.open());
9511        assert!(questions.get(&coincidental.id).unwrap().status.open());
9512
9513        task.release();
9514        queue.put(&mut task).unwrap();
9515        reconcile_task_questions(&queue, &questions);
9516        assert_eq!(
9517            questions.get(&task_question.id).unwrap().status,
9518            ask::QuestionStatus::Abandoned
9519        );
9520        assert!(
9521            questions.get(&run_question.id).unwrap().status.open(),
9522            "run questions remain the run janitor's responsibility"
9523        );
9524        assert!(
9525            questions.get(&coincidental.id).unwrap().status.open(),
9526            "a non-conductor question must not be abandoned just because its \
9527             run id coincides with a task id"
9528        );
9529    }
9530
9531    #[test]
9532    fn a_freshly_started_running_task_is_never_stalled() {
9533        let dir = tempfile::tempdir().unwrap();
9534        let mut t = task();
9535        t.start("run-1".to_owned());
9536        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
9537        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
9538        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
9539    }
9540
9541    #[test]
9542    fn a_long_running_task_with_no_live_daemon_is_stalled() {
9543        let dir = tempfile::tempdir().unwrap();
9544        let mut t = task();
9545        t.start("run-1".to_owned());
9546        t.updated_at = Timestamp::now()
9547            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9548        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
9549        assert_eq!(
9550            stalled_tasks(
9551                &Queue::at(dir.path().join("q")),
9552                dir.path(),
9553                Timestamp::now()
9554            )
9555            .len(),
9556            0,
9557            "the task was never written to this queue"
9558        );
9559    }
9560
9561    #[test]
9562    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
9563        let dir = tempfile::tempdir().unwrap();
9564        let mut t = task();
9565        t.id = "20260903-080340-0167".to_owned();
9566        t.start("20260903-080619-01c2".to_owned());
9567        t.updated_at = Timestamp::now()
9568            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9569
9570        let mut status = Status::new();
9571        status.current = vec![Current {
9572            task: t.id.clone(),
9573            run: "20260903-080619-01c2".to_owned(),
9574        }];
9575        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9576
9577        assert!(
9578            !is_stalled(&t, dir.path(), Timestamp::now()),
9579            "a live daemon's own heartbeat rules out stalled, however long the task has run"
9580        );
9581    }
9582
9583    /// Rewrite a task's `updated_at` on disk directly, bypassing
9584    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
9585    /// a fixture look like it has genuinely been `running` for a while.
9586    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
9587        let path = queue.path_of(id);
9588        let body = std::fs::read_to_string(&path).unwrap();
9589        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
9590        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
9591        v["updated_at"] = serde_json::Value::String(old.to_string());
9592        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
9593    }
9594
9595    #[test]
9596    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
9597        // The realistic `poll()` ordering, not `is_stalled` in isolation:
9598        // `reclaim_orphaned_running` runs first, on every poll, and settles
9599        // any `running` task whose claim it can actually take. For most
9600        // crashes that is immediate - a dead pid is proof enough for
9601        // `sweep_stale_claims` to drop the lock the same tick, and the very
9602        // next claim attempt succeeds. But a lock whose pid cannot be parsed
9603        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
9604        // `sweep_stale_claims`'s own doc), so the lock - and the claim
9605        // failure behind it - can legitimately outlive many polls. This is
9606        // exactly the gap `stalled_tasks` exists to surface well before that
9607        // six-hour sweep would: reclaim leaves the task `running`, and it
9608        // must still reach the conductor as stalled.
9609        let dir = tempfile::tempdir().unwrap();
9610        let queue = Queue::at(dir.path().join("queue"));
9611        let home = dir.path().join("home");
9612
9613        let mut t = task();
9614        t.id = "20260101-000001-lock".to_owned();
9615        t.start("run-1".to_owned());
9616        queue.put(&mut t).unwrap();
9617        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9618        std::fs::write(
9619            dir.path().join("queue").join(format!("{}.lock", t.id)),
9620            "not a pid",
9621        )
9622        .unwrap();
9623
9624        let now = Timestamp::now();
9625        assert!(
9626            reclaim_orphaned_running(&queue, 2).is_empty(),
9627            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
9628             and reclaim must leave the task alone"
9629        );
9630        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9631
9632        let stalled = stalled_tasks(&queue, &home, now);
9633        assert_eq!(
9634            stalled.len(),
9635            1,
9636            "reclaim's inability to claim it yet must not hide it from the conductor"
9637        );
9638        assert_eq!(stalled[0].id, t.id);
9639    }
9640
9641    #[test]
9642    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
9643        let dir = tempfile::tempdir().unwrap();
9644        crate::run::set_home(dir.path().join("run-home"));
9645        let queue = Queue::at(dir.path().join("queue"));
9646        let home = dir.path().join("home");
9647        let questions = Questions::at(dir.path().join("questions"));
9648
9649        let mut t = task();
9650        t.id = "20260101-000003-dead".to_owned();
9651        t.start("missing-run".to_owned());
9652        queue.put(&mut t).unwrap();
9653        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9654
9655        // This is the real poll ordering: retain the deterministic stalled
9656        // input before a claim proves the owner is gone and reclaims it.
9657        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9658        assert_eq!(
9659            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
9660            [&t.id]
9661        );
9662        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
9663        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9664
9665        // Reclaim drops its guard before conductor decisions are applied, so
9666        // the decision for the captured stalled input has a real write path.
9667        crate::conduct::apply(
9668            &queue,
9669            &questions,
9670            &crate::conduct::Verdict {
9671                decisions: vec![crate::conduct::Decision {
9672                    id: t.id.clone(),
9673                    recovery: Some(crate::conduct::Recovery::Requeue),
9674                    ..crate::conduct::Decision::default()
9675                }],
9676            },
9677        )
9678        .unwrap();
9679        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9680    }
9681
9682    #[test]
9683    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
9684        let dir = tempfile::tempdir().unwrap();
9685        let queue = Queue::at(dir.path().join("queue"));
9686        let home = dir.path().join("home");
9687
9688        let mut fresh = task();
9689        fresh.id = "20260101-000001-aaaa".to_owned();
9690        fresh.start("run-1".to_owned());
9691        queue.put(&mut fresh).unwrap();
9692
9693        let mut old = task();
9694        old.id = "20260101-000002-bbbb".to_owned();
9695        old.start("run-2".to_owned());
9696        queue.put(&mut old).unwrap();
9697        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
9698
9699        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9700        assert_eq!(stalled.len(), 1);
9701        assert_eq!(stalled[0].id, old.id);
9702    }
9703
9704    #[test]
9705    fn queued_and_finished_task_views_partition_by_status() {
9706        let dir = tempfile::tempdir().unwrap();
9707        let queue = Queue::at(dir.path().join("queue"));
9708
9709        let mut queued = task();
9710        queued.id = "20260101-000001-aaaa".to_owned();
9711        queue.put(&mut queued).unwrap();
9712
9713        let mut failed = task();
9714        failed.id = "20260101-000002-bbbb".to_owned();
9715        failed.start("run-1".to_owned());
9716        failed.fail("gate red", 5);
9717        queue.put(&mut failed).unwrap();
9718
9719        let mut held = task();
9720        held.id = "20260101-000003-cccc".to_owned();
9721        held.hold_machine(None);
9722        queue.put(&mut held).unwrap();
9723
9724        let mut running = task();
9725        running.id = "20260101-000004-dddd".to_owned();
9726        running.start("run-2".to_owned());
9727        queue.put(&mut running).unwrap();
9728
9729        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
9730        assert_eq!(queued_ids, [queued.id.clone()]);
9731
9732        let mut finished_ids: Vec<String> =
9733            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
9734        finished_ids.sort_unstable();
9735        let mut want = vec![failed.id.clone(), held.id.clone()];
9736        want.sort_unstable();
9737        assert_eq!(finished_ids, want);
9738    }
9739
9740    #[test]
9741    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
9742        for short in [false, true] {
9743            let dir = tempfile::tempdir().unwrap();
9744            let queue = Queue::at(dir.path().join("queue"));
9745            let questions = ask::Questions::at(dir.path().join("questions"));
9746            let mut running = task();
9747            running.id = "20261013-192213-feb2".into();
9748            running.start("existing-run".into());
9749            queue.put(&mut running).unwrap();
9750            let mut middle = task();
9751            middle.id = "20261013-193611-ca5b".into();
9752            middle.block(
9753                vec![if short {
9754                    "feb2".into()
9755                } else {
9756                    running.id.clone()
9757                }],
9758                None,
9759            );
9760            queue.put(&mut middle).unwrap();
9761            let mut waiting = task();
9762            waiting.id = "20261013-202849-ee37".into();
9763            waiting.block(
9764                vec![if short {
9765                    "ca5b".into()
9766                } else {
9767                    middle.id.clone()
9768                }],
9769                Some("wait for implementation".into()),
9770            );
9771            queue.put(&mut waiting).unwrap();
9772            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
9773            let inv = crate::blockers::Inventory::load(&queue, &questions);
9774            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
9775            assert!(inv.stuck().is_empty());
9776            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9777            assert!(report.quarantined.is_empty());
9778            assert!(report.asked.is_empty());
9779            resolve_blockers(&queue, &questions);
9780            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9781            assert!(questions.list().is_empty());
9782            // Finishing the transitive prerequisite alone does not satisfy
9783            // the task's direct dependency.
9784            running.succeed();
9785            queue.put(&mut running).unwrap();
9786            resolve_blockers(&queue, &questions);
9787            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
9788            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9789            middle = queue.get(&middle.id).unwrap();
9790            middle.succeed();
9791            queue.put(&mut middle).unwrap();
9792            resolve_blockers(&queue, &questions);
9793            let after = queue.get(&waiting.id).unwrap();
9794            assert_eq!(after.status, TaskStatus::Queued);
9795            assert!(after.blocked_by.is_empty());
9796            assert_eq!(after.instruction, waiting.instruction);
9797        }
9798    }
9799
9800    #[test]
9801    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
9802        for future_schema in [false, true] {
9803            let name = "20261013-193611-ca5b";
9804            let mut future = task();
9805            future.id = name.into();
9806            future.schema = crate::queue::SCHEMA + 1;
9807            let contents = if future_schema {
9808                serde_json::to_string(&future).unwrap()
9809            } else {
9810                "corrupt".into()
9811            };
9812            let dir = tempfile::tempdir().unwrap();
9813            let queue = Queue::at(dir.path().join("queue"));
9814            let questions = ask::Questions::at(dir.path().join("questions"));
9815            let mut waiting = task();
9816            waiting.id = "20261013-202849-ee37".into();
9817            waiting.block(vec!["ca5b".into()], None);
9818            queue.put(&mut waiting).unwrap();
9819            std::fs::write(queue.path_of(name), contents).unwrap();
9820            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
9821            assert!(
9822                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
9823            );
9824            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9825            assert!(report.asked.is_empty());
9826            resolve_blockers(&queue, &questions);
9827            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9828            assert!(questions.list().is_empty());
9829        }
9830        let dir = tempfile::tempdir().unwrap();
9831        let queue = Queue::at(dir.path().join("queue"));
9832        let questions = ask::Questions::at(dir.path().join("questions"));
9833        let mut waiting = task();
9834        waiting.id = "20261013-202849-ee37".into();
9835        waiting.block(vec!["ca5b".into()], None);
9836        queue.put(&mut waiting).unwrap();
9837        let mut done = task();
9838        done.id = "20261013-193611-ca5b".into();
9839        done.succeed();
9840        queue.put(&mut done).unwrap();
9841        // An unreadable second match must not disappear from uniqueness
9842        // checks just because Queue::list skips it.
9843        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
9844        assert!(queue.get("ca5b").is_err());
9845        assert_eq!(
9846            crate::queue::dependency(&queue, &questions, "ca5b"),
9847            crate::queue::Dependency::Ambiguous
9848        );
9849        resolve_blockers(&queue, &questions);
9850        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9851        assert!(report.asked.is_empty());
9852        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9853        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
9854    }
9855
9856    #[test]
9857    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
9858        for held in [false, true] {
9859            for question in [false, true] {
9860                for reference in ["ca5b", "20261013-193611-ca5b"] {
9861                    let dir = tempfile::tempdir().unwrap();
9862                    let queue = Queue::at(dir.path().join("queue"));
9863                    let questions = ask::Questions::at(dir.path().join("questions"));
9864                    let mut prerequisite = task();
9865                    prerequisite.id = "20261013-193611-ca5b".into();
9866                    prerequisite.start("existing-run".into());
9867                    queue.put(&mut prerequisite).unwrap();
9868                    let mut waiting = task();
9869                    waiting.id = "20261013-202849-ee37".into();
9870                    if held {
9871                        waiting.hold_machine(Some("waiting for separate consent".into()));
9872                    }
9873                    queue.put(&mut waiting).unwrap();
9874                    let reason = "Deleting saved data requires separate owner consent";
9875                    crate::conduct::apply(
9876                        &queue,
9877                        &questions,
9878                        &crate::conduct::Verdict {
9879                            decisions: vec![crate::conduct::Decision {
9880                                id: waiting.id.clone(),
9881                                blocked_by: vec![reference.into()],
9882                                question: question.then(|| "May the saved data be deleted?".into()),
9883                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
9884                                reason: Some(reason.into()),
9885                                ..crate::conduct::Decision::default()
9886                            }],
9887                        },
9888                    )
9889                    .unwrap();
9890                    let before = queue.get(&waiting.id).unwrap();
9891                    if question {
9892                        assert_eq!(before.status, TaskStatus::Blocked);
9893                        let q = questions.get(&before.blocked_by[0]).unwrap();
9894                        assert_eq!(q.summary, "May the saved data be deleted?");
9895                        assert!(q.status.open());
9896                    } else {
9897                        assert_eq!(before.status, TaskStatus::Held);
9898                        let recorded_reason = before.hold_reason.as_deref().unwrap();
9899                        assert!(recorded_reason.starts_with(reason));
9900                        if held {
9901                            assert!(recorded_reason.contains("waiting for separate consent"));
9902                        }
9903                    }
9904                    prerequisite.succeed();
9905                    queue.put(&mut prerequisite).unwrap();
9906                    resolve_blockers(&queue, &questions);
9907                    let after = queue.get(&waiting.id).unwrap();
9908                    assert_eq!(after.status, before.status);
9909                    assert_eq!(after.blocked_by, before.blocked_by);
9910                    assert_eq!(after.hold_reason, before.hold_reason);
9911                    assert_eq!(after.instruction, waiting.instruction);
9912                    if question {
9913                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
9914                    }
9915                    assert!(
9916                        queue.next_runnable().is_none(),
9917                        "dependency completion is not consent"
9918                    );
9919                }
9920            }
9921        }
9922    }
9923
9924    #[test]
9925    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
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 dep = task();
9931        dep.id = "20260101-000001-dep0".to_owned();
9932        dep.succeed();
9933        queue.put(&mut dep).unwrap();
9934
9935        let mut still_going = task();
9936        still_going.id = "20260101-000002-dep1".to_owned();
9937        queue.put(&mut still_going).unwrap();
9938
9939        let mut blocked = task();
9940        blocked.id = "20260101-000003-main".to_owned();
9941        blocked.block(
9942            vec![dep.id.clone(), still_going.id.clone()],
9943            Some("waits on both".to_owned()),
9944        );
9945        queue.put(&mut blocked).unwrap();
9946
9947        resolve_blockers(&queue, &questions);
9948
9949        let after = queue.get(&blocked.id).unwrap();
9950        assert_eq!(
9951            after.status,
9952            TaskStatus::Blocked,
9953            "one dependency is still outstanding"
9954        );
9955        assert_eq!(after.blocked_by, [still_going.id.clone()]);
9956    }
9957
9958    #[test]
9959    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
9960        let dir = tempfile::tempdir().unwrap();
9961        let queue = Queue::at(dir.path().join("queue"));
9962        let questions = ask::Questions::at(dir.path().join("questions"));
9963
9964        let mut q = crate::ask::Question::new(
9965            "20260101-000001-main".to_owned(),
9966            crate::conduct::NODE.to_owned(),
9967            "conduct".to_owned(),
9968            "Which backend?".to_owned(),
9969            String::new(),
9970            Vec::new(),
9971        );
9972        questions.put(&mut q).unwrap();
9973        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
9974            .unwrap();
9975        questions.put(&mut q).unwrap();
9976
9977        let mut blocked = task();
9978        blocked.id = "20260101-000001-main".to_owned();
9979        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
9980        queue.put(&mut blocked).unwrap();
9981
9982        resolve_blockers(&queue, &questions);
9983
9984        let after = queue.get(&blocked.id).unwrap();
9985        assert_eq!(
9986            after.status,
9987            TaskStatus::Queued,
9988            "the only blocker resolved"
9989        );
9990        assert_eq!(after.answers.len(), 1);
9991        assert_eq!(after.answers[0].question, "Which backend?");
9992        assert_eq!(after.answers[0].answer, "SQLite");
9993
9994        // And the run this task starts next is told about it.
9995        let instruction = instruction_for(&after);
9996        assert!(instruction.contains("Which backend?"));
9997        assert!(instruction.contains("SQLite"));
9998    }
9999
10000    #[test]
10001    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
10002        let dir = tempfile::tempdir().unwrap();
10003        let queue = Queue::at(dir.path().join("queue"));
10004        let questions = ask::Questions::at(dir.path().join("questions"));
10005
10006        let mut q = crate::ask::Question::new(
10007            "20260101-000001-main".to_owned(),
10008            crate::conduct::NODE.to_owned(),
10009            "conduct".to_owned(),
10010            "Is the setup done?".to_owned(),
10011            String::new(),
10012            Vec::new(),
10013        );
10014        q.abandon("no answer within 60s of asking");
10015        questions.put(&mut q).unwrap();
10016
10017        let mut blocked = task();
10018        blocked.id = "20260101-000001-main".to_owned();
10019        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
10020        queue.put(&mut blocked).unwrap();
10021
10022        resolve_blockers(&queue, &questions);
10023
10024        let after = queue.get(&blocked.id).unwrap();
10025        assert_eq!(
10026            after.status,
10027            TaskStatus::Held,
10028            "never left blocked on nothing"
10029        );
10030        assert!(!after.operator_held(), "a machine hold, for triage");
10031        assert!(
10032            after
10033                .hold_reason
10034                .as_deref()
10035                .unwrap_or_default()
10036                .contains("went unanswered")
10037        );
10038    }
10039
10040    #[test]
10041    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
10042        // Reproduces the reported bug (task 3958): a task held out of
10043        // attempts, blocked on a `crate::conduct` follow-up question, must
10044        // come back `held` once that question is answered - never `queued`,
10045        // whatever the answer said - or it silently re-enters the
10046        // competition queue with its attempts already exhausted.
10047        let dir = tempfile::tempdir().unwrap();
10048        let queue = Queue::at(dir.path().join("queue"));
10049        let questions = ask::Questions::at(dir.path().join("questions"));
10050
10051        let mut q = crate::ask::Question::new(
10052            "20260101-000001-main".to_owned(),
10053            crate::conduct::NODE.to_owned(),
10054            "conduct".to_owned(),
10055            "How should this be handled?".to_owned(),
10056            String::new(),
10057            Vec::new(),
10058        );
10059        questions.put(&mut q).unwrap();
10060        q.answer(crate::ask::Answer::Text(
10061            "leave it held, a human will look at it later".to_owned(),
10062        ))
10063        .unwrap();
10064        questions.put(&mut q).unwrap();
10065
10066        let mut held = task();
10067        held.id = "20260101-000001-main".to_owned();
10068        held.hold_machine(Some("out of attempts".to_owned()));
10069        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
10070        queue.put(&mut held).unwrap();
10071
10072        resolve_blockers(&queue, &questions);
10073
10074        let after = queue.get(&held.id).unwrap();
10075        assert_eq!(after.status, TaskStatus::Held);
10076        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
10077        assert_eq!(
10078            after.answers[0].answer,
10079            "leave it held, a human will look at it later"
10080        );
10081    }
10082
10083    #[test]
10084    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
10085        let dir = tempfile::tempdir().unwrap();
10086        let queue = Queue::at(dir.path().join("queue"));
10087        let questions = ask::Questions::at(dir.path().join("questions"));
10088        let mut dep = task();
10089        dep.id = "20260101-000001-gone".to_owned();
10090        queue.put(&mut dep).unwrap();
10091        let mut blocked = task();
10092        blocked.id = "20260101-000003-main".to_owned();
10093        blocked.block(vec![dep.id.clone()], None);
10094        queue.put(&mut blocked).unwrap();
10095
10096        // Claimed, so `remove` cannot rewrite it and the resolver must.
10097        let claim = queue.claim(&blocked.id).unwrap();
10098        queue.remove(&dep.id, false, &questions).unwrap();
10099        drop(claim);
10100        resolve_blockers(&queue, &questions);
10101
10102        let after = queue.get(&blocked.id).unwrap();
10103        assert_eq!(after.status, TaskStatus::Queued);
10104        assert!(after.blocked_by.is_empty());
10105    }
10106
10107    #[test]
10108    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
10109        // Reproduces the reported bug: a task blocked on a task id that was
10110        // removed (`magi task rm`, or deleted by hand) can never see that id
10111        // reach `Done`, so the ordinary per-id loop has nothing to notice and
10112        // would otherwise leave the task `blocked` forever with no way for an
10113        // operator to find out why.
10114        let dir = tempfile::tempdir().unwrap();
10115        let queue = Queue::at(dir.path().join("queue"));
10116        let questions = ask::Questions::at(dir.path().join("questions"));
10117
10118        let mut still_going = task();
10119        still_going.id = "20260101-000002-dep1".to_owned();
10120        queue.put(&mut still_going).unwrap();
10121
10122        let mut blocked = task();
10123        blocked.id = "20260101-000003-main".to_owned();
10124        blocked.block(
10125            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
10126            Some("waits on both".to_owned()),
10127        );
10128        queue.put(&mut blocked).unwrap();
10129
10130        resolve_blockers(&queue, &questions);
10131
10132        let after = queue.get(&blocked.id).unwrap();
10133        assert_eq!(
10134            after.status,
10135            TaskStatus::Held,
10136            "a missing dependency must not leave the task blocked forever"
10137        );
10138        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
10139        assert!(after.blocked_by.is_empty());
10140        let reason = after.hold_reason.as_deref().unwrap_or_default();
10141        assert!(
10142            reason.contains("20260101-000001-gone"),
10143            "the missing id must be named so an operator can tell what happened: {reason}"
10144        );
10145        assert!(
10146            reason.contains(&still_going.id),
10147            "the still-valid dependency must not silently vanish from the record: {reason}"
10148        );
10149    }
10150
10151    #[test]
10152    fn instruction_for_is_unchanged_without_any_answers() {
10153        let t = task();
10154        assert_eq!(instruction_for(&t), t.instruction);
10155    }
10156
10157    #[test]
10158    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
10159        let dir = tempfile::tempdir().unwrap();
10160        let q = Queue::at(dir.path().join("queue"));
10161        let src = dir.path().join("shot.png");
10162        std::fs::write(&src, "x").unwrap();
10163        let mut t = task();
10164        q.attach(&mut t, &[src]).unwrap();
10165        let paths = task_attachments(&q, &t).unwrap();
10166        assert_eq!(paths.len(), 1);
10167        assert!(paths[0].is_absolute() && paths[0].is_file());
10168        std::fs::remove_file(&paths[0]).unwrap();
10169        let err = task_attachments(&q, &t).unwrap_err().to_string();
10170        assert!(err.contains("shot.png"), "{err}");
10171    }
10172
10173    #[tokio::test]
10174    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
10175        let dir = tempfile::tempdir().unwrap();
10176        let queue_path = dir.path().join("queue");
10177        let queue = Queue::at(queue_path.clone());
10178        let mut t = task();
10179        t.source = Source::Agent {
10180            run: "originating-chat".into(),
10181            node: crate::queue::CHAT_NODE.into(),
10182        };
10183        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
10184            stage: "config-fetch",
10185            target: "origin/main".into(),
10186        });
10187        record_config_failure(&mut t, &fetch);
10188        t.hold_machine(Some(format!("{fetch:#}")));
10189        let fetch_key = t.chat_notice_due().unwrap();
10190        t.chat_notices.push(fetch_key.clone());
10191        queue.put(&mut t).unwrap();
10192
10193        let queue = Queue::at(queue_path);
10194        let mut t = queue.get(&t.id).unwrap();
10195        let a = dir.path().join("a.toml");
10196        let b = dir.path().join("b.toml");
10197        for (path, text, new_cause) in [
10198            (&a, "[graph", true),
10199            (&a, "[verify", false),
10200            (&a, "[graph]\nimplementers = 'invalid-type'", true),
10201            (&b, "[graph]\nimplementers = 'invalid-type'", true),
10202        ] {
10203            t.release_operator("test", None);
10204            std::fs::write(path, text).unwrap();
10205            let error = Config::discover_fetched(dir.path(), Some(path))
10206                .await
10207                .unwrap_err();
10208            record_config_failure(&mut t, &error);
10209            t.hold_machine(Some(format!("{error:#}")));
10210            let due = t.chat_notice_due();
10211            assert_eq!(due.is_some(), new_cause, "{error:#}");
10212            if let Some(key) = due {
10213                assert_ne!(key, fetch_key);
10214                t.chat_notices.push(key);
10215            }
10216        }
10217        t.succeed();
10218        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
10219    }
10220
10221    #[test]
10222    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
10223        let dir = tempfile::tempdir().unwrap();
10224        let queue_path = dir.path().join("queue");
10225        let queue = Queue::at(queue_path.clone());
10226        let mut t = task();
10227        t.source = crate::queue::Source::Agent {
10228            run: "originating-chat".into(),
10229            node: crate::queue::CHAT_NODE.into(),
10230        };
10231        let a = dir.path().join("a.png");
10232        let b = dir.path().join("b.png");
10233        std::fs::write(&a, "a").unwrap();
10234        std::fs::write(&b, "b").unwrap();
10235        queue.attach(&mut t, &[a, b]).unwrap();
10236        let paths = task_attachments(&queue, &t).unwrap();
10237        for path in &paths {
10238            std::fs::remove_file(path).unwrap();
10239        }
10240        let missing = task_attachments(&queue, &t).unwrap_err();
10241        t.attempts += 1;
10242        let reason = missing.to_string();
10243        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10244        let first = t.chat_notice_due().expect("first attachment notice");
10245        t.chat_notices.push(first.clone());
10246        queue.put(&mut t).unwrap();
10247
10248        let queue = Queue::at(queue_path.clone());
10249        let mut t = queue.get(&t.id).unwrap();
10250        assert!(t.chat_notice_due().is_none(), "restart does not replay");
10251        t.release_operator("test", None);
10252        t.attempts += 1;
10253        let missing = task_attachments(&queue, &t).unwrap_err();
10254        t.fail_startup_target(
10255            "startup-attachments",
10256            missing.name,
10257            "same missing attachment with regenerated wording",
10258            1,
10259        );
10260        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
10261
10262        std::fs::write(&paths[0], "restored").unwrap();
10263        t.release_operator("test", None);
10264        t.attempts += 1;
10265        let missing = task_attachments(&queue, &t).unwrap_err();
10266        let reason = missing.to_string();
10267        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
10268        let second = t
10269            .chat_notice_due()
10270            .expect("different attachment must notify");
10271        assert_ne!(first, second);
10272        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
10273    }
10274
10275    #[test]
10276    fn resumed_instruction_is_unchanged_without_any_answers() {
10277        let t = task();
10278        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
10279    }
10280
10281    #[test]
10282    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
10283        let mut t = task();
10284        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10285        // The run's own instruction on disk predates the answer: it is the
10286        // plain original text `Runner::start` saved before the operator was
10287        // ever asked anything.
10288        let old = t.instruction.clone();
10289
10290        let refreshed = resumed_instruction(&old, &t);
10291        assert!(refreshed.starts_with(&old), "the original text is kept");
10292        assert!(refreshed.contains("Which backend?"));
10293        assert!(refreshed.contains("SQLite"));
10294    }
10295
10296    #[test]
10297    fn resumed_instruction_keeps_an_original_answers_heading() {
10298        let mut t = task();
10299        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
10300        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10301
10302        let refreshed = resumed_instruction(&t.instruction, &t);
10303
10304        assert!(
10305            refreshed.starts_with(&t.instruction),
10306            "an answers heading in the original instruction is not the appended block"
10307        );
10308        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
10309        assert!(refreshed.contains("Which backend?"));
10310        assert!(refreshed.contains("SQLite"));
10311
10312        let repeated = resumed_instruction(&refreshed, &t);
10313        assert_eq!(
10314            repeated, refreshed,
10315            "only the final appended block is refreshed"
10316        );
10317    }
10318
10319    #[test]
10320    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
10321        let mut t = task();
10322        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10323
10324        // A first resume appends the block; a second resume of the same run,
10325        // with no new answer in between, must reproduce exactly the same
10326        // text rather than appending the block a second time.
10327        let once = resumed_instruction(&t.instruction, &t);
10328        let twice = resumed_instruction(&once, &t);
10329        assert_eq!(once, twice);
10330        assert_eq!(once.matches("Which backend?").count(), 1);
10331
10332        // A later answer replaces the block wholesale rather than growing it.
10333        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
10334        let refreshed = resumed_instruction(&once, &t);
10335        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
10336        assert!(refreshed.contains("Which backend?"));
10337        assert!(refreshed.contains("Which cache?"));
10338    }
10339
10340    #[test]
10341    fn prepare_instruction_covers_all_three_starters() {
10342        let mut t = task();
10343        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10344
10345        // Start: a fresh run gets the task text plus every answer so far —
10346        // exactly `instruction_for`.
10347        assert_eq!(
10348            prepare_instruction(&Starter::Start, None, &t),
10349            Some(instruction_for(&t))
10350        );
10351
10352        // Resume: the run's prior instruction is refreshed with the answer,
10353        // not discarded and not left stale.
10354        let old = t.instruction.clone();
10355        assert_eq!(
10356            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
10357            Some(resumed_instruction(&old, &t))
10358        );
10359
10360        // Review: a review-only pass builds its own instruction from the
10361        // branch's history in `crate::graph`, with no task statement at all -
10362        // this boundary must leave it alone.
10363        assert_eq!(
10364            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
10365            None
10366        );
10367    }
10368
10369    #[test]
10370    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
10371        assert_eq!(
10372            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
10373            Starter::Review("magi/eba2/A".to_owned())
10374        );
10375    }
10376
10377    #[test]
10378    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
10379        assert_eq!(
10380            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
10381            Starter::Start,
10382            "a vanished review branch must not fall back to resuming the old run either"
10383        );
10384    }
10385
10386    #[test]
10387    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
10388        let mut t = task();
10389        t.start("old-run".to_owned());
10390        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
10391        t.release();
10392        let branch = t.review_branch.take();
10393        assert_eq!(
10394            choose_starter(branch.as_deref(), true, Some("old-run")),
10395            Starter::Review("magi/eba2/A".to_owned()),
10396            "a review wins over resuming the old run"
10397        );
10398    }
10399
10400    #[test]
10401    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
10402        assert_eq!(
10403            choose_starter(None, false, Some("some-run")),
10404            Starter::Resume("some-run".to_owned())
10405        );
10406        assert_eq!(choose_starter(None, false, None), Starter::Start);
10407    }
10408
10409    #[test]
10410    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
10411        let mut released = task();
10412        released.start("stalled-run".to_owned());
10413        released.requeue();
10414        let unfinished = (!released.fresh_start)
10415            .then(|| Some("stalled-run".to_owned()))
10416            .flatten();
10417        assert_eq!(
10418            choose_starter(None, false, unfinished.as_deref()),
10419            Starter::Start,
10420            "release keeps run history but must not resume it"
10421        );
10422        assert_eq!(released.runs, ["stalled-run"]);
10423    }
10424
10425    fn stopped_public_run(status: RunStatus) -> RunState {
10426        let mut state = run_state(status);
10427        state.driver_exited = true;
10428        state.config.graph.land = true;
10429        state.config.graph.review_rounds = 1;
10430        state.reviews = vec![review_round(1)];
10431        state.merge = Some(crate::run::MergeOutcome {
10432            mode: MergeMode::Pr,
10433            ok: false,
10434            detail: "landing stopped".into(),
10435            empty: false,
10436        });
10437        state.pr = Some(crate::run::PrRecord {
10438            url: "https://example.test/pull/1".into(),
10439            number: 1,
10440            state: "open".into(),
10441            checks: "red".into(),
10442            round: 1,
10443            rounds: 1,
10444            red_at_merge: Vec::new(),
10445        });
10446        state
10447    }
10448
10449    #[test]
10450    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
10451        for status in [RunStatus::Blocked, RunStatus::Gating] {
10452            let home = tempfile::tempdir().unwrap();
10453            let mut state = stopped_public_run(status);
10454            state.save_under(home.path()).unwrap();
10455            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
10456            assert!(!exhausted_review_budget(&state));
10457            let mut task = held_task_with(&state.id);
10458            task.release();
10459            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
10460            assert_eq!(
10461                choose_starter(None, false, unfinished.as_deref()),
10462                Starter::Resume(state.id.clone())
10463            );
10464            let question = action_question(&state.id, resume_action(&state.id));
10465            assert_eq!(
10466                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
10467                ActionDecision::Resume(state.id.clone())
10468            );
10469            // The control-plane command uses this same preflight before pinning.
10470            assert_eq!(
10471                crate::resume::validate(home.path(), &state.id).unwrap().id,
10472                state.id
10473            );
10474            let queue = Queue::at(home.path().join("queue"));
10475            let mut controlled = Task::new(
10476                "resume land".into(),
10477                state.instruction.clone(),
10478                state.repo.clone(),
10479                Source::Agent {
10480                    run: "talk".into(),
10481                    node: crate::queue::CHAT_NODE.into(),
10482                },
10483            );
10484            controlled.runs.push(state.id.clone());
10485            controlled.hold_machine(Some("land stopped".into()));
10486            queue.put(&mut controlled).unwrap();
10487            let resumed =
10488                crate::chat_control::resume(&queue, home.path(), "talk", &state.id).unwrap();
10489            assert_eq!(resumed.status, TaskStatus::Queued);
10490            assert_eq!(
10491                resumed.resume_override.unwrap().pinned_run,
10492                Some(state.id.clone())
10493            );
10494            assert_eq!(resumed.attempts, 0);
10495        }
10496    }
10497
10498    #[test]
10499    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
10500        for review_rounds in [0, 1] {
10501            let home = tempfile::tempdir().unwrap();
10502            let mut state = run_state(RunStatus::Blocked);
10503            state.config.graph.review_rounds = review_rounds;
10504            if review_rounds > 0 {
10505                let mut review = review_round(1);
10506                review.clean = true;
10507                state.reviews = vec![review];
10508            }
10509            state.gate_ran = true;
10510            state.gate = vec![crate::run::CommandOutcome {
10511                command: "verify".into(),
10512                code: Some(1),
10513                output_tail: "gate failed after repair budget exhausted".into(),
10514                duration_ms: 0,
10515                resource_blocked: false,
10516            }];
10517            state.save_under(home.path()).unwrap();
10518            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
10519            assert!(exhausted_review_budget(&state));
10520            let mut task = held_task_with(&state.id);
10521            task.release();
10522            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
10523            let question = action_question(&state.id, resume_action(&state.id));
10524            assert_ne!(
10525                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
10526                ActionDecision::Resume(state.id.clone())
10527            );
10528            assert!(crate::resume::validate(home.path(), &state.id).is_err());
10529
10530            // An unexecuted gate still has work to do with or without reviews.
10531            state.gate_ran = false;
10532            state.gate.clear();
10533            assert!(!exhausted_review_budget(&state));
10534            assert_eq!(
10535                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
10536                Some(state.id)
10537            );
10538        }
10539    }
10540
10541    #[test]
10542    fn resource_blocked_verification_resumes_the_same_run() {
10543        for (kind, stage) in [
10544            ("cache", "clean"),
10545            ("coordination", "clean"),
10546            ("cache", "review-e2e"),
10547            ("coordination", "no-reviews"),
10548            ("coordination", "handoff"),
10549        ] {
10550            let home = tempfile::tempdir().unwrap();
10551            let mut state = run_state(RunStatus::Blocked);
10552            state.config.graph.review_rounds = 1;
10553            let mut review = review_round(1);
10554            review.clean = true;
10555            state.reviews = vec![review];
10556            if stage == "review-e2e" {
10557                let review = &mut state.reviews[0];
10558                review.clean = false;
10559                review.blocking = 1;
10560                review.e2e = vec![crate::run::CommandOutcome {
10561                    command: "verify".into(),
10562                    code: None,
10563                    output_tail: "resource wait expired".into(),
10564                    duration_ms: 0,
10565                    resource_blocked: true,
10566                }];
10567            } else if stage == "no-reviews" {
10568                state.config.graph.review_rounds = 0;
10569                state.reviews.clear();
10570            } else if stage == "handoff" {
10571                // A completed final verification can hand off to the gate
10572                // even when the review still carries contested findings.
10573                let review = &mut state.reviews[0];
10574                review.clean = false;
10575                review.blocking = 1;
10576                review.e2e = vec![crate::run::CommandOutcome {
10577                    command: "verify".into(),
10578                    code: Some(0),
10579                    output_tail: String::new(),
10580                    duration_ms: 0,
10581                    resource_blocked: false,
10582                }];
10583            }
10584            state.gate_ran = false;
10585            state.resource_block = Some(crate::run::ResourceBlock {
10586                node: if stage == "review-e2e" {
10587                    "review"
10588                } else {
10589                    "gate"
10590                }
10591                .into(),
10592                kind: kind.into(),
10593                detail: "resource wait expired".into(),
10594                at: jiff::Timestamp::now(),
10595            });
10596            state.save_under(home.path()).unwrap();
10597            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
10598            assert!(!exhausted_review_budget(&state));
10599            let mut task = held_task_with(&state.id);
10600            task.release();
10601            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
10602            assert_eq!(
10603                choose_starter(None, false, unfinished.as_deref()),
10604                Starter::Resume(state.id.clone())
10605            );
10606            let question = action_question(&state.id, resume_action(&state.id));
10607            assert_eq!(
10608                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
10609                ActionDecision::Resume(state.id.clone())
10610            );
10611            assert_eq!(
10612                crate::resume::validate(home.path(), &state.id).unwrap().id,
10613                state.id
10614            );
10615            let queue = Queue::at(home.path().join("queue"));
10616            let mut controlled = Task::new(
10617                "resume verification".into(),
10618                state.instruction.clone(),
10619                state.repo.clone(),
10620                Source::Agent {
10621                    run: "talk".into(),
10622                    node: crate::queue::CHAT_NODE.into(),
10623                },
10624            );
10625            controlled.runs.push(state.id.clone());
10626            controlled.hold_machine(Some("verification resource unavailable".into()));
10627            queue.put(&mut controlled).unwrap();
10628            let resumed =
10629                crate::chat_control::resume(&queue, home.path(), "talk", &state.id).unwrap();
10630            assert_eq!(resumed.status, TaskStatus::Queued);
10631            assert_eq!(
10632                resumed.resume_override.unwrap().pinned_run,
10633                Some(state.id.clone())
10634            );
10635            assert_eq!(resumed.attempts, 0);
10636
10637            // A genuinely unresolved final review still exhausts the budget.
10638            state.config.graph.review_rounds = 1;
10639            let mut unresolved = review_round(1);
10640            unresolved.blocking = 1;
10641            state.reviews = vec![unresolved];
10642            state.resource_block = None;
10643            state.save_under(home.path()).unwrap();
10644            assert!(exhausted_review_budget(&state));
10645            assert!(crate::resume::validate(home.path(), &state.id).is_err());
10646        }
10647    }
10648
10649    #[tokio::test]
10650    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
10651        let home = tempfile::tempdir().unwrap();
10652        let mut owner = stopped_public_run(RunStatus::Blocked);
10653        let repo = tempfile::tempdir().unwrap();
10654        crate::git::git(repo.path(), &["init"]).await.unwrap();
10655        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
10656        owner.id = "20260101-000000-aaaa".into();
10657        owner.save_under(home.path()).unwrap();
10658        let mut successor = run_state(RunStatus::Blocked);
10659        successor.id = "20260101-000001-bbbb".into();
10660        successor.save_under(home.path()).unwrap();
10661        let runs = vec![owner.id.clone(), successor.id.clone()];
10662        assert_eq!(
10663            public_resume_owner(home.path(), &runs, &owner.repo)
10664                .await
10665                .unwrap()
10666                .unwrap()
10667                .id,
10668            owner.id
10669        );
10670        let subdir = owner.repo.join("nested");
10671        std::fs::create_dir(&subdir).unwrap();
10672        assert_eq!(
10673            public_resume_owner(home.path(), &runs, &subdir)
10674                .await
10675                .unwrap()
10676                .unwrap()
10677                .id,
10678            owner.id
10679        );
10680        #[cfg(unix)]
10681        {
10682            let alias = home.path().join("repo-alias");
10683            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
10684            assert_eq!(
10685                public_resume_owner(home.path(), &runs, &alias.join("nested"))
10686                    .await
10687                    .unwrap()
10688                    .unwrap()
10689                    .id,
10690                owner.id
10691            );
10692        }
10693        let different = tempfile::tempdir().unwrap();
10694        crate::git::git(different.path(), &["init"]).await.unwrap();
10695        assert!(
10696            public_resume_owner(home.path(), &runs, different.path())
10697                .await
10698                .is_err()
10699        );
10700        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
10701        assert!(
10702            public_resume_owner(home.path(), &runs, &owner.repo)
10703                .await
10704                .is_err()
10705        );
10706        drop(lock);
10707        std::fs::remove_file(
10708            home.path()
10709                .join("runs")
10710                .join(&successor.id)
10711                .join("run.json"),
10712        )
10713        .unwrap();
10714        assert!(
10715            public_resume_owner(home.path(), &runs, &owner.repo)
10716                .await
10717                .is_err()
10718        );
10719    }
10720
10721    #[test]
10722    fn an_ordinary_release_keeps_a_resumable_run_available() {
10723        let mut released = task();
10724        released.start("stalled-run".to_owned());
10725        released.release();
10726        let unfinished = (!released.fresh_start)
10727            .then(|| Some("stalled-run".to_owned()))
10728            .flatten();
10729        assert_eq!(
10730            choose_starter(None, false, unfinished.as_deref()),
10731            Starter::Resume("stalled-run".to_owned()),
10732            "manual release must preserve the normal resume path"
10733        );
10734    }
10735
10736    #[test]
10737    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
10738        let mut state = run_state(RunStatus::Blocked);
10739        state.config.graph.review_rounds = 3;
10740        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
10741        assert!(exhausted_review_budget(&state));
10742
10743        // One round still unused: resuming can still ask a reviewer something.
10744        state.reviews.pop();
10745        assert!(!exhausted_review_budget(&state));
10746
10747        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
10748        // count: only a `Blocked` run re-enters the review loop on resume.
10749        let mut stalled = run_state(RunStatus::Stalled);
10750        stalled.config.graph.review_rounds = 1;
10751        stalled.reviews = vec![review_round(1)];
10752        assert!(!exhausted_review_budget(&stalled));
10753    }
10754
10755    fn review_round(round: usize) -> crate::run::ReviewRound {
10756        crate::run::ReviewRound {
10757            round,
10758            head: "deadbeef".to_owned(),
10759            verified_head: None,
10760            verified_at: None,
10761            reviews: Vec::new(),
10762            e2e: Vec::new(),
10763            verify_retried: false,
10764            e2e_deferred: false,
10765            e2e_defer_reason: None,
10766            fix: None,
10767            blocking: 0,
10768            answered: 1,
10769            expected: 1,
10770            clean: false,
10771            progressed: true,
10772            vote_split: false,
10773            reconsideration: Vec::new(),
10774            verdict: None,
10775        }
10776    }
10777
10778    #[test]
10779    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
10780        let mut run = RunState::new(
10781            PathBuf::from("/repo"),
10782            "main".to_owned(),
10783            "abc1234def".to_owned(),
10784            "add retries".to_owned(),
10785            Config::default(),
10786        );
10787        run.status = RunStatus::Judging;
10788        run.parked = true;
10789        let mut task = Task::new(
10790            "add retries".to_owned(),
10791            "add retries".to_owned(),
10792            PathBuf::from("/repo"),
10793            crate::queue::Source::Human,
10794        );
10795        task.status = TaskStatus::Failed;
10796        task.runs = vec![run.id.clone()];
10797        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
10798        assert!(with(&task, &run), "parked after judging is the case");
10799        let mut parked_task = task.clone();
10800        parked_task.status = TaskStatus::Parked;
10801        assert!(with(&parked_task, &run), "the Parked status is the case");
10802
10803        let mut not_parked = run.clone();
10804        not_parked.parked = false;
10805        not_parked.status = RunStatus::Stalled;
10806        assert!(!with(&task, &not_parked), "a stall is the conductor's");
10807
10808        let mut fresh = task.clone();
10809        fresh.fresh_start = true;
10810        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
10811
10812        let mut review = task.clone();
10813        review.review_branch = Some("magi/x/A".to_owned());
10814        assert!(!with(&review, &run), "review is ranked before resume");
10815
10816        let mut held = task.clone();
10817        held.status = TaskStatus::Held;
10818        assert!(!with(&held, &run), "a hold stays visible to the conductor");
10819
10820        let mut released = run.clone();
10821        released.released_to = Some("20260901-000000-new1".to_owned());
10822        assert!(!with(&task, &released), "nothing left to resume into");
10823
10824        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
10825            "unreadable"
10826        )));
10827    }
10828
10829    #[test]
10830    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
10831        let mut released = RunState::new(
10832            PathBuf::from("/repo"),
10833            "main".to_owned(),
10834            "abc1234def".to_owned(),
10835            "add retries".to_owned(),
10836            Config::default(),
10837        );
10838        released.status = RunStatus::Blocked;
10839        assert_eq!(
10840            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10841            Some(released.id.clone())
10842        );
10843        released.released_to = Some("20260901-000000-new1".to_owned());
10844        assert_eq!(
10845            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10846            None,
10847            "there is nothing left to resume it into"
10848        );
10849    }
10850
10851    #[test]
10852    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
10853        // Mirrors the failure this exists to close: a task's last run ended
10854        // `Blocked` with the review budget spent, `crate::conduct` chose
10855        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
10856        // evidence), and without this check `attempt` would go on treating
10857        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
10858        // review loop iterates zero times over an already-spent budget, so
10859        // the resumed run settles right back to `Blocked` having asked nobody
10860        // anything, and `Requeue`'s promised fresh competition never happens.
10861        let mut exhausted = RunState::new(
10862            PathBuf::from("/repo"),
10863            "main".to_owned(),
10864            "abc1234def".to_owned(),
10865            "add retries".to_owned(),
10866            Config::default(),
10867        );
10868        exhausted.status = RunStatus::Blocked;
10869        exhausted.config.graph.review_rounds = 1;
10870        exhausted.reviews = vec![review_round(1)];
10871
10872        assert_eq!(
10873            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
10874            None,
10875            "an exhausted `Blocked` run must not be offered as resumable"
10876        );
10877
10878        // A `Blocked` run with rounds still unused is genuinely worth
10879        // resuming, and must still be found.
10880        let mut has_budget_left = RunState::new(
10881            PathBuf::from("/repo"),
10882            "main".to_owned(),
10883            "abc1234def".to_owned(),
10884            "add retries".to_owned(),
10885            Config::default(),
10886        );
10887        has_budget_left.status = RunStatus::Blocked;
10888        has_budget_left.config.graph.review_rounds = 3;
10889        has_budget_left.reviews = vec![review_round(1)];
10890
10891        assert_eq!(
10892            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
10893                Ok(has_budget_left.clone())
10894            }),
10895            Some(has_budget_left.id.clone())
10896        );
10897    }
10898
10899    #[test]
10900    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
10901        let mut run = RunState::new(
10902            PathBuf::from("/repo"),
10903            "main".to_owned(),
10904            "abc1234def".to_owned(),
10905            "add retries".to_owned(),
10906            Config::default(),
10907        );
10908        run.status = RunStatus::Blocked;
10909        run.config.graph.review_rounds = 1;
10910        run.reviews = vec![review_round(1)];
10911        run.pr_publication_pending = true;
10912        assert_eq!(
10913            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
10914            Some(run.id.clone()),
10915            "a spent review budget must not turn a failed publication into a re-competition"
10916        );
10917    }
10918
10919    #[test]
10920    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
10921        let mut task = Task::new(
10922            "recover work".into(),
10923            "recover work".into(),
10924            PathBuf::from("/repo"),
10925            crate::queue::Source::Human,
10926        );
10927        let mut history = std::collections::BTreeMap::new();
10928        for index in 0..8 {
10929            let mut run = run_state(RunStatus::Blocked);
10930            run.id = format!("20260101-000000-{index:04}");
10931            run.base_commit = format!("upstream-{index}");
10932            // Seven empty newer attempts must not erase the old recovery owner.
10933            if index > 0 {
10934                run.candidates.clear();
10935            }
10936            task.runs.extend([run.id.clone(), run.id.clone()]);
10937            history.insert(run.id.clone(), run);
10938            task.requeue();
10939        }
10940        let check = |task: &Task, starter: &Starter, limit| {
10941            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
10942        };
10943        assert!(
10944            check(&task, &Starter::Start, 8)
10945                .unwrap()
10946                .contains("8 unretired")
10947        );
10948        assert!(check(&task, &Starter::Start, 9).is_none());
10949        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
10950        task.release_operator("owner", None);
10951        assert_eq!(task.attempts, 0);
10952        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
10953        assert!(check(&restored, &Starter::Start, 8).is_some());
10954        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
10955        assert!(check(&restored, &Starter::Start, 0).is_none());
10956    }
10957
10958    #[test]
10959    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
10960        let mut task = Task::new(
10961            "recover work".into(),
10962            "recover work".into(),
10963            PathBuf::from("/repo"),
10964            crate::queue::Source::Human,
10965        );
10966        let mut run = run_state(RunStatus::Superseded);
10967        run.candidates.clear();
10968        task.runs.push(run.id.clone());
10969        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
10970        run.retired_to = Some("authority".into());
10971        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10972        run.retired_to = None;
10973        run.released_to = Some("authority".into());
10974        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
10975        assert!(
10976            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
10977                .unwrap()
10978                .contains("Cannot verify")
10979        );
10980        // Resuming an existing owner needs no new inventory or worktree budget.
10981        assert!(
10982            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
10983                panic!("resume must not load historical attempts")
10984            })
10985            .is_none()
10986        );
10987    }
10988
10989    #[test]
10990    fn retired_resume_requires_a_valid_same_repository_authority() {
10991        let mut source = run_state(RunStatus::Blocked);
10992        let mut empty = run_state(RunStatus::Blocked);
10993        empty.retired_to = Some(source.id.clone());
10994        let runs = vec![source.id.clone(), empty.id.clone()];
10995        let resolve = |source: &RunState, empty: &RunState| {
10996            unfinished_run_with(&runs, "fixture", |id| {
10997                if id == source.id {
10998                    Ok(source.clone())
10999                } else if id == empty.id {
11000                    Ok(empty.clone())
11001                } else {
11002                    bail!("unreadable authority")
11003                }
11004            })
11005        };
11006        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
11007        assert_eq!(
11008            choose_starter(None, false, resolve(&source, &empty).as_deref()),
11009            Starter::Resume(source.id.clone())
11010        );
11011        source.retired_to = Some(empty.id.clone());
11012        assert!(
11013            resolve(&source, &empty).is_none(),
11014            "cycles do not revive obsolete runs"
11015        );
11016        source.retired_to = None;
11017        source.repo = PathBuf::from("/another-repository");
11018        assert!(resolve(&source, &empty).is_none());
11019        source.repo = empty.repo.clone();
11020        source.released_to = Some("later".into());
11021        assert!(resolve(&source, &empty).is_none());
11022        empty.retired_to = Some("unlisted-run".into());
11023        assert!(resolve(&source, &empty).is_none());
11024    }
11025
11026    #[test]
11027    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
11028        // A task whose history holds an *older* run that still looks
11029        // resumable (say, a competition `Runner::review` was started
11030        // alongside after that older run went `Stalled`) and a *newest* run
11031        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
11032        // on this task must mean a fresh competition — falling back to the
11033        // stale, superseded `Stalled` run instead would resurrect history
11034        // nothing asked to revisit and silently defeat the requeue.
11035        let mut older_stalled = RunState::new(
11036            PathBuf::from("/repo"),
11037            "main".to_owned(),
11038            "abc1234def".to_owned(),
11039            "add retries".to_owned(),
11040            Config::default(),
11041        );
11042        older_stalled.status = RunStatus::Stalled;
11043
11044        let mut newest_exhausted = RunState::new(
11045            PathBuf::from("/repo"),
11046            "main".to_owned(),
11047            "abc1234def".to_owned(),
11048            "add retries".to_owned(),
11049            Config::default(),
11050        );
11051        newest_exhausted.status = RunStatus::Blocked;
11052        newest_exhausted.config.graph.review_rounds = 1;
11053        newest_exhausted.reviews = vec![review_round(1)];
11054
11055        assert_eq!(
11056            unfinished_run_with(
11057                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
11058                "t",
11059                |_| Ok(newest_exhausted.clone())
11060            ),
11061            None,
11062            "the newest run is exhausted, so nothing here is worth resuming - \
11063             least of all the older, already-superseded run"
11064        );
11065    }
11066
11067    #[test]
11068    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
11069        assert_eq!(
11070            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
11071                Err(anyhow::anyhow!("fixture is absent"))
11072            }),
11073            None
11074        );
11075    }
11076
11077    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
11078        let mut q = ask::Question::new(
11079            run.to_owned(),
11080            "implement".to_owned(),
11081            "impl-A".to_owned(),
11082            "continue?".to_owned(),
11083            String::new(),
11084            vec!["resume で続行する".to_owned(), "other".to_owned()],
11085        );
11086        q.actions.insert("resume で続行する".to_owned(), action);
11087        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
11088            .unwrap();
11089        q
11090    }
11091
11092    fn held_task_with(run: &str) -> Task {
11093        let mut t = task();
11094        t.runs = vec![run.to_owned()];
11095        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
11096        t
11097    }
11098
11099    fn resume_action(run: &str) -> ask::ChoiceAction {
11100        ask::ChoiceAction::Resume { run: run.into() }
11101    }
11102
11103    #[test]
11104    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
11105        for parked in [false, true] {
11106            let mut t = task();
11107            t.start("A".into());
11108            t.start("B".into());
11109            assert_eq!(t.runs, vec!["A", "B"]);
11110            t.start("A".into());
11111            let mut resumed = run_state(RunStatus::Blocked);
11112            resumed.id = "A".into();
11113            resumed.parked = parked;
11114            resumed.driver_exited = true;
11115            t.hold_machine(Some("resumed run stopped".into()));
11116            let q = action_question("A", resume_action("A"));
11117            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
11118            assert_eq!(
11119                decide_action(&t, &q, &PHRASES_EN, |id| {
11120                    assert_eq!(id, "A");
11121                    Ok(resumed.clone())
11122                }),
11123                ActionDecision::Resume("A".into())
11124            );
11125            assert_eq!(
11126                action_standing(&t, &action_question("B", resume_action("B"))),
11127                ActionStanding::Stale
11128            );
11129            t.release_operator("cli", None);
11130            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
11131                assert_eq!(id, "A");
11132                Ok(resumed.clone())
11133            });
11134            assert_eq!(
11135                choose_starter(None, false, unfinished.as_deref()),
11136                Starter::Resume("A".into())
11137            );
11138            assert_eq!(t.runs, vec!["B", "A"]);
11139        }
11140    }
11141
11142    #[test]
11143    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
11144        let mut state = crate::land::tests::repair_state(true, true);
11145        state.status = RunStatus::Landing;
11146        state.parked = true;
11147        state.driver_exited = true;
11148        let mut q = ask::Question::new(
11149            state.id.clone(),
11150            land::APPROVAL_NODE.into(),
11151            "land".into(),
11152            "Merge?".into(),
11153            String::new(),
11154            vec![land::APPROVE.into(), land::HOLD.into()],
11155        );
11156        q.id = state.id.clone();
11157        state.land_approval = Some(crate::run::LandApproval {
11158            question: q.id.clone(),
11159            head: "current-head".into(),
11160        });
11161        assert!(land::upgrade_repair_choice(&mut q, &state));
11162        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
11163        let mut task = held_task_with(&state.id);
11164        task.status = TaskStatus::Parked;
11165        assert_eq!(
11166            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
11167            ActionDecision::Resume(state.id.clone())
11168        );
11169        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
11170        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
11171        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
11172        assert_eq!(
11173            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
11174            ActionDecision::Resume(state.id.clone()),
11175            "a repair answer newer than the manual hold resumes the existing owner"
11176        );
11177        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
11178        for answered_at in [q.answered_at, None] {
11179            let mut older = q.clone();
11180            older.answered_at = answered_at;
11181            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
11182                panic!("a later manual hold must prevent dispatch")
11183            });
11184            let ActionDecision::Refuse(reason) = refused else {
11185                panic!("expected an actionable refusal, got {refused:?}");
11186            };
11187            assert!(reason.contains("later operator decision"));
11188            assert!(reason.contains(&format!("magi task release {}", task.id)));
11189        }
11190        task.operator_decided_at = None;
11191        let mut superseded = state.clone();
11192        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
11193        assert_eq!(
11194            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
11195            ActionDecision::Stale
11196        );
11197        for case in 1..4 {
11198            let mut changed = state.clone();
11199            match case {
11200                1 => changed.status = RunStatus::Blocked,
11201                2 => changed.released_to = Some("new-owner".into()),
11202                _ => changed.land_approval.as_mut().unwrap().head.clear(),
11203            }
11204            assert!(matches!(
11205                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
11206                ActionDecision::Refuse(_)
11207            ));
11208        }
11209        assert!(matches!(
11210            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
11211            ActionDecision::Refuse(_)
11212        ));
11213        task.runs.push("replacement".into());
11214        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
11215        assert_eq!(
11216            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
11217                "old owner must not load"
11218            )),
11219            ActionDecision::Stale
11220        );
11221    }
11222
11223    #[test]
11224    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
11225        let mut state = crate::land::tests::repair_state(true, true);
11226        state.status = RunStatus::Landing;
11227        state.parked = true;
11228        state.driver_exited = true;
11229        let mut q = ask::Question::new(
11230            state.id.clone(),
11231            land::APPROVAL_NODE.into(),
11232            "land".into(),
11233            "Merge?".into(),
11234            String::new(),
11235            vec![land::APPROVE.into(), land::HOLD.into()],
11236        );
11237        q.id = state.id.clone();
11238        state.land_approval = Some(crate::run::LandApproval {
11239            question: q.id.clone(),
11240            head: "current-head".into(),
11241        });
11242        state.save().unwrap();
11243        land::upgrade_repair_choice(&mut q, &state);
11244        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
11245        Questions::open().put(&mut q).unwrap();
11246        let tmp = tempfile::tempdir().unwrap();
11247        let queue = Queue::at(tmp.path().join("queue"));
11248        let mut task = held_task_with(&state.id);
11249        task.status = TaskStatus::Parked;
11250        queue.put(&mut task).unwrap();
11251        let empty = Arc::new(tokio::sync::Semaphore::new(0));
11252        let free = Arc::new(tokio::sync::Semaphore::new(1));
11253        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
11254        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
11255        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
11256        assert!(claim.permit.is_some());
11257        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
11258        drop(claim);
11259        Questions::open()
11260            .update(&q.id, |q| {
11261                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
11262                Ok(())
11263            })
11264            .unwrap();
11265        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
11266        assert!(claim.permit.is_none());
11267        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
11268    }
11269
11270    #[test]
11271    fn decide_action_resumes_only_the_latest_resumable_run() {
11272        let t = held_task_with("r1");
11273        let q = action_question("r1", resume_action("r1"));
11274        let load = |s: RunState| move |_: &str| Ok(s);
11275        assert_eq!(
11276            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
11277            ActionDecision::Resume("r1".into())
11278        );
11279        // Not the latest run of the task.
11280        let q_other = action_question("r1", resume_action("r0"));
11281        assert!(matches!(
11282            decide_action(
11283                &t,
11284                &q_other,
11285                &PHRASES_EN,
11286                load(run_state(RunStatus::Blocked))
11287            ),
11288            ActionDecision::Refuse(_)
11289        ));
11290        // A finished run cannot make progress.
11291        assert!(matches!(
11292            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
11293            ActionDecision::Refuse(_)
11294        ));
11295        // A released one either.
11296        let mut released = run_state(RunStatus::Blocked);
11297        released.released_to = Some("elsewhere".into());
11298        assert!(matches!(
11299            decide_action(&t, &q, &PHRASES_EN, load(released)),
11300            ActionDecision::Refuse(_)
11301        ));
11302        // Unreadable state is a refusal, never a fresh competition.
11303        assert!(matches!(
11304            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
11305            ActionDecision::Refuse(_)
11306        ));
11307    }
11308
11309    #[test]
11310    fn decide_action_ignores_a_question_about_an_earlier_run() {
11311        let mut t = held_task_with("r1");
11312        t.runs.push("r2".to_owned());
11313        let never = |_: &str| -> Result<RunState> { bail!("not read") };
11314        assert_eq!(
11315            decide_action(
11316                &t,
11317                &action_question("r1", ask::ChoiceAction::Done),
11318                &PHRASES_EN,
11319                never
11320            ),
11321            ActionDecision::Stale
11322        );
11323    }
11324
11325    #[test]
11326    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
11327        let mut t = held_task_with("r1");
11328        let never = |_: &str| -> Result<RunState> { bail!("not read") };
11329        assert_eq!(
11330            decide_action(
11331                &t,
11332                &action_question("r1", ask::ChoiceAction::Requeue),
11333                &PHRASES_EN,
11334                never
11335            ),
11336            ActionDecision::Requeue
11337        );
11338        let done_q = action_question("r1", ask::ChoiceAction::Done);
11339        assert_eq!(
11340            decide_action(&t, &done_q, &PHRASES_EN, never),
11341            ActionDecision::Done
11342        );
11343        t.mark_action_applied(&done_q.id);
11344        assert_eq!(
11345            decide_action(&t, &done_q, &PHRASES_EN, never),
11346            ActionDecision::Skip
11347        );
11348
11349        // A plain answer (no action for that label) does nothing.
11350        let mut plain = action_question("r1", ask::ChoiceAction::Done);
11351        plain.actions.clear();
11352        assert_eq!(
11353            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
11354            ActionDecision::Skip
11355        );
11356        // A running task is left alone.
11357        let mut running = held_task_with("r1");
11358        running.status = TaskStatus::Running;
11359        assert_eq!(
11360            decide_action(
11361                &running,
11362                &action_question("r1", ask::ChoiceAction::Done),
11363                &PHRASES_EN,
11364                never
11365            ),
11366            ActionDecision::Skip
11367        );
11368    }
11369
11370    #[test]
11371    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
11372        crate::run::pin_test_home();
11373        for legacy in [false, true] {
11374            let dir = tempfile::tempdir().unwrap();
11375            let queue = Queue::at(dir.path().join("queue"));
11376            let questions = Questions::at(dir.path().join("questions"));
11377            let run = "20260101-000000-hold";
11378            let mut task = held_task_with(run);
11379            task.status = TaskStatus::Parked;
11380            let mut q = ask::Question::new(
11381                run.into(),
11382                land::APPROVAL_NODE.into(),
11383                "land".into(),
11384                "Repair?".into(),
11385                String::new(),
11386                vec![land::REPAIR.into()],
11387            );
11388            q.actions.insert(land::REPAIR.into(), resume_action(run));
11389            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
11390            // Deterministically order the answer before the actual manual hold.
11391            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
11392            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
11393            questions.put(&mut q).unwrap();
11394            task.hold_manual(Some("Keep this PR paused".into()));
11395            if legacy {
11396                task.hold_source = None;
11397            }
11398            queue.put(&mut task).unwrap();
11399
11400            apply_task_choice_actions(&queue, &questions, dir.path());
11401            let after = queue.get(&task.id).unwrap();
11402            assert!(after.operator_held());
11403            assert_eq!(after.hold_source, task.hold_source);
11404            assert_eq!(after.operator_decided_at, task.operator_decided_at);
11405            assert_eq!(after.runs, task.runs);
11406            assert_eq!(after.instruction, task.instruction);
11407            assert!(after.resume_override.is_none());
11408            assert!(after.action_applied(&q.id));
11409            let reason = after.hold_reason.as_deref().unwrap();
11410            assert!(reason.starts_with("Keep this PR paused"));
11411            assert!(reason.contains("later operator decision"));
11412            assert!(reason.contains(&format!("magi task release {}", task.id)));
11413
11414            for recovery in [
11415                crate::conduct::Recovery::Review,
11416                crate::conduct::Recovery::Requeue,
11417            ] {
11418                crate::conduct::apply(
11419                    &queue,
11420                    &questions,
11421                    &crate::conduct::Verdict {
11422                        decisions: vec![crate::conduct::Decision {
11423                            id: task.id.clone(),
11424                            recovery: Some(recovery),
11425                            ..Default::default()
11426                        }],
11427                    },
11428                )
11429                .unwrap();
11430            }
11431            // Reconciliation is idempotent, and automatic recovery cannot
11432            // reopen this owner after it observes the rejected repair answer.
11433            apply_task_choice_actions(&queue, &questions, dir.path());
11434            let still_held = queue.get(&task.id).unwrap();
11435            assert!(still_held.operator_held());
11436            assert_eq!(still_held.hold_reason, after.hold_reason);
11437            assert_eq!(still_held.runs, task.runs);
11438            assert!(still_held.review_branch.is_none());
11439            assert!(!still_held.fresh_start);
11440            assert!(queue.next_runnable().is_none());
11441        }
11442    }
11443
11444    #[test]
11445    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
11446        for held in [false, true] {
11447            for retry in [false, true] {
11448                let dir = tempfile::tempdir().unwrap();
11449                let queue = Queue::at(dir.path().join("queue"));
11450                let questions = Questions::at(dir.path().join("questions"));
11451                let home = dir.path().join("home");
11452                let mut t = task();
11453                if held {
11454                    t.hold_machine(Some("driver state unknown".into()));
11455                }
11456                queue.put(&mut t).unwrap();
11457                let verdict = serde_json::from_value(serde_json::json!({
11458                    "decisions": [{
11459                        "id": t.id,
11460                        "question": "Driver state unknown; retry the checks or hold?",
11461                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
11462                        "actions": {
11463                            "daemon: recheck and retry": {"do": "requeue"},
11464                            "daemon: hold the task": {"do": "hold"}
11465                        }
11466                    }]
11467                }))
11468                .unwrap();
11469                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
11470                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11471                let mut q = questions.list().pop().unwrap();
11472                let choice = if retry {
11473                    "daemon: recheck and retry"
11474                } else {
11475                    "daemon: hold the task"
11476                };
11477                assert_eq!(q.actions.len(), 2);
11478                q.answer(ask::Answer::Choice(choice.into())).unwrap();
11479                questions.put(&mut q).unwrap();
11480
11481                // A Web answer does not remove the deputy's fresh lease.
11482                questions.beat(&q.id, ask::WaiterKind::Deputy);
11483                for _ in 0..2 {
11484                    resolve_blockers(&queue, &questions);
11485                    apply_task_choice_actions(&queue, &questions, &home);
11486                    let waiting = queue.get(&t.id).unwrap();
11487                    assert_eq!(waiting.status, TaskStatus::Blocked);
11488                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
11489                    assert!(waiting.answers.is_empty());
11490                    assert!(!waiting.action_applied(&q.id));
11491                    assert!(runnable(&queue).is_empty());
11492                    let free = Arc::new(tokio::sync::Semaphore::new(1));
11493                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
11494                }
11495                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11496
11497                // Releasing the blocker and applying the operation share one save.
11498                resolve_blockers(&queue, &questions);
11499                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
11500                apply_task_choice_actions(&queue, &questions, &home);
11501                let after = queue.get(&t.id).unwrap();
11502                assert_eq!(
11503                    after.status,
11504                    if retry {
11505                        TaskStatus::Queued
11506                    } else {
11507                        TaskStatus::Held
11508                    }
11509                );
11510                assert!(after.action_applied(&q.id));
11511                assert_eq!(after.operator_held(), !retry);
11512                assert_eq!(after.answers.len(), 1);
11513
11514                // A later operator decision must not replay this answer.
11515                let mut changed = after;
11516                if retry {
11517                    changed.hold_manual(Some("later hold".into()));
11518                } else {
11519                    changed.release_operator("test", None);
11520                }
11521                let expected = changed.status;
11522                queue.put(&mut changed).unwrap();
11523                apply_task_choice_actions(&queue, &questions, &home);
11524                assert_eq!(queue.get(&t.id).unwrap().status, expected);
11525            }
11526        }
11527    }
11528
11529    #[test]
11530    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
11531        let dir = tempfile::tempdir().unwrap();
11532        let queue = Queue::at(dir.path().join("queue"));
11533        let questions = Questions::at(dir.path().join("questions"));
11534        let home = dir.path().join("home");
11535        let mut state = run_state(RunStatus::Blocked);
11536        state.id = "20260101-000000-act1".to_owned();
11537        state.save_under(&home).unwrap();
11538
11539        let mut t = held_task_with(&state.id);
11540        queue.put(&mut t).unwrap();
11541        let mut q = action_question(&state.id, resume_action(&state.id));
11542        questions.put(&mut q).unwrap();
11543
11544        apply_task_choice_actions(&queue, &questions, &home);
11545        let after = queue.get(&t.id).unwrap();
11546        assert_eq!(after.status, TaskStatus::Queued);
11547        assert!(!after.fresh_start);
11548        assert!(after.action_applied(&q.id));
11549        let pin = after.resume_override.clone().unwrap();
11550        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
11551        assert!(pin.forced);
11552
11553        // Held again later: the same answer does not release it a second time.
11554        let mut again = queue.get(&t.id).unwrap();
11555        again.hold_machine(Some("later".into()));
11556        queue.put(&mut again).unwrap();
11557        apply_task_choice_actions(&queue, &questions, &home);
11558        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11559    }
11560
11561    #[test]
11562    fn a_delivered_answer_is_still_acted_on_exactly_once() {
11563        let dir = tempfile::tempdir().unwrap();
11564        let queue = Queue::at(dir.path().join("queue"));
11565        let questions = Questions::at(dir.path().join("questions"));
11566        let home = dir.path().join("home");
11567        let mut state = run_state(RunStatus::Blocked);
11568        state.id = "20260101-000000-act2".to_owned();
11569        state.save_under(&home).unwrap();
11570
11571        let mut t = held_task_with(&state.id);
11572        queue.put(&mut t).unwrap();
11573        let mut q = action_question(&state.id, resume_action(&state.id));
11574        q.answer_delivered = true;
11575        questions.put(&mut q).unwrap();
11576
11577        // Delivered, and the agent then died: the task is still held, so the
11578        // chosen action applies.
11579        apply_task_choice_actions(&queue, &questions, &home);
11580        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11581        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
11582
11583        // Held again: the same answer does nothing a second time.
11584        let mut again = queue.get(&t.id).unwrap();
11585        again.hold_machine(Some("later".into()));
11586        queue.put(&mut again).unwrap();
11587        apply_task_choice_actions(&queue, &questions, &home);
11588        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11589    }
11590
11591    #[test]
11592    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
11593        let dir = tempfile::tempdir().unwrap();
11594        let queue = Queue::at(dir.path().join("queue"));
11595        let questions = Questions::at(dir.path().join("questions"));
11596        let home = dir.path().join("home");
11597        let mut state = run_state(RunStatus::Blocked);
11598        state.id = "20260101-000000-act3".to_owned();
11599        state.save_under(&home).unwrap();
11600        let mut t = held_task_with(&state.id);
11601        queue.put(&mut t).unwrap();
11602        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
11603        questions.put(&mut q).unwrap();
11604
11605        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
11606        apply_task_choice_actions(&queue, &questions, &home);
11607        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11608
11609        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
11610        apply_task_choice_actions(&queue, &questions, &home);
11611        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11612    }
11613
11614    #[test]
11615    fn action_standing_tells_the_reasons_apart() {
11616        let mut t = held_task_with("r1");
11617        let q = action_question("r1", ask::ChoiceAction::Requeue);
11618        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
11619        let mut plain = q.clone();
11620        plain.actions.clear();
11621        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
11622
11623        // Applied wins over everything, even a running task.
11624        t.mark_action_applied(&q.id);
11625        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
11626
11627        // A newer attempt running: the old question is Stale, not Busy.
11628        let mut t = held_task_with("r1");
11629        t.start("r2".to_owned());
11630        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
11631        // The same question about the latest run just waits.
11632        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
11633        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11634        t.status = TaskStatus::Blocked;
11635        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
11636
11637        // A conductor question is keyed by the task, never stale.
11638        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
11639        c.node = crate::conduct::NODE.to_owned();
11640        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
11641        assert!(!ActionStanding::Busy.daemon_owns());
11642    }
11643
11644    #[test]
11645    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
11646        let dir = tempfile::tempdir().unwrap();
11647        let queue = Queue::at(dir.path().join("queue"));
11648        let questions = Questions::at(dir.path().join("questions"));
11649        let home = dir.path().join("home");
11650        let mut state = run_state(RunStatus::Blocked);
11651        state.id = "20260101-000000-act4".to_owned();
11652        state.save_under(&home).unwrap();
11653        let mut t = held_task_with(&state.id);
11654        t.status = TaskStatus::Running;
11655        queue.put(&mut t).unwrap();
11656        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11657        q.cwd = Some(dir.path().display().to_string());
11658        questions.put(&mut q).unwrap();
11659
11660        // While the task runs the daemon will not act, so the waiter still
11661        // delivers the word to the dead asker's seat ...
11662        let running = queue.get(&t.id).unwrap();
11663        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
11664        assert!(matches!(
11665            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
11666            crate::waiter::Action::Deliver(_)
11667        ));
11668        // ... and the daemon waits while the task runs, then applies once.
11669        apply_task_choice_actions(&queue, &questions, &home);
11670        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11671        let mut back = queue.get(&t.id).unwrap();
11672        back.hold_machine(Some("later".into()));
11673        queue.put(&mut back).unwrap();
11674        apply_task_choice_actions(&queue, &questions, &home);
11675        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
11676        let mut again = queue.get(&t.id).unwrap();
11677        again.hold_machine(Some("again".into()));
11678        queue.put(&mut again).unwrap();
11679        apply_task_choice_actions(&queue, &questions, &home);
11680        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11681    }
11682}