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 && !s.released() {
947                        ActionDecision::Resume(run.clone())
948                    } else {
949                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
950                    }
951                }
952                Ok(s)
953                    if q.node == land::APPROVAL_NODE
954                        && q.resolution().as_deref() == Some(land::REPAIR) =>
955                {
956                    if s.merge_repairs.iter().any(|r| r.question == q.id)
957                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
958                    {
959                        // A live/manual driver already consumed or superseded
960                        // this answer. Do not hold its fresh approval wait.
961                        ActionDecision::Stale
962                    } else if s.liveness(false) == Liveness::Live {
963                        ActionDecision::Skip
964                    } else if s.status != RunStatus::Landing
965                        || s.released()
966                        || s.reviews.is_empty()
967                        || !implementers_match(task, &s)
968                        || !s
969                            .land_approval
970                            .as_ref()
971                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
972                    {
973                        ActionDecision::Refuse(format!(
974                            "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",
975                            q.id, run, run
976                        ))
977                    } else {
978                        ActionDecision::Resume(run.clone())
979                    }
980                }
981                Ok(s) if s.liveness(false) == Liveness::Live => {
982                    ActionDecision::Refuse("run already has a live driver".into())
983                }
984                Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
985                    ActionDecision::Resume(run.clone())
986                }
987                Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
988                    q.short(),
989                    ask::short_id(run),
990                )),
991                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
992                    q.short(),
993                    ask::short_id(run),
994                    &format!("{e:#}"),
995                )),
996            }
997        }
998    }
999}
1000
1001/// The fixed prose the daemon writes into [`Task::last_error`] and
1002/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1003/// `triage::Wording` and `land::Words`: only English and Japanese are
1004/// translated, anything else falls back to English.
1005///
1006/// Rendered when the reason is *generated*, so a reason keeps the language it
1007/// was written in if the setting changes later. The notification frame
1008/// (`Task <id> is held:`) is not here and stays English.
1009///
1010/// Deliberately **not** translated, because other code reads them back by
1011/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1012/// and `gate red`. IDs, node names, paths and external error text are embedded
1013/// as they are.
1014struct Phrases {
1015    /// `{}` = status label, then the detail.
1016    graph_stopped: fn(&str, &str) -> String,
1017    quorum_lost: &'static str,
1018    /// Followed by the seats' names.
1019    quota_took_out: &'static str,
1020    /// Followed by the status label.
1021    run_ended: &'static str,
1022    /// Followed by the question's short id.
1023    waiting_for_answer: &'static str,
1024    recovered_running: &'static str,
1025    no_run_to_recover: &'static str,
1026    could_not_start: &'static str,
1027    resume_not_latest: fn(&str, &str) -> String,
1028    resume_cannot_progress: fn(&str, &str) -> String,
1029    resume_unreadable: fn(&str, &str, &str) -> String,
1030    /// A takeover refusal: the operator-facing text. English is the error's own
1031    /// `Display`; a translation keeps the machine detail apart in parentheses.
1032    handover_refused: fn(&crate::handover::Refused) -> String,
1033    /// Appended to a refused handover's hold reason (leading space included).
1034    handover_hint: &'static str,
1035    /// (seats that never answered, review rounds) for the review loop's
1036    /// "refusing to call it clean" stop.
1037    reviewers_never_answered: fn(usize, usize) -> String,
1038}
1039
1040const PHRASES_EN: Phrases = Phrases {
1041    graph_stopped: |status, detail| {
1042        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1043    },
1044    quorum_lost: "the judging panel lost its quorum",
1045    quota_took_out: "; quota took out ",
1046    run_ended: "run ended ",
1047    waiting_for_answer: " - waiting for operator answer to question ",
1048    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1049    no_run_to_recover: "task was `running` with no live daemon and no readable \
1050                        run to recover; held for a human to check what happened",
1051    could_not_start: "could not start the run: ",
1052    resume_not_latest: |q, run| {
1053        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1054    },
1055    resume_cannot_progress: |q, run| {
1056        format!("question {q} asked to resume run {run}, which cannot make progress")
1057    },
1058    resume_unreadable: |q, run, e| {
1059        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1060    },
1061    handover_refused: |r| r.to_string(),
1062    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1063    reviewers_never_answered: |missing, rounds| {
1064        format!(
1065            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1066             refusing to call it clean"
1067        )
1068    },
1069};
1070
1071const PHRASES_JA: Phrases = Phrases {
1072    graph_stopped: |status, detail| {
1073        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1074    },
1075    quorum_lost: "審査パネルが定足数を失いました",
1076    quota_took_out: "。クォータで脱落: ",
1077    run_ended: "run 終了: ",
1078    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1079    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1080    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1081                        何が起きたか人が確認するため保留にしました",
1082    could_not_start: "run を開始できませんでした: ",
1083    resume_not_latest: |q, run| {
1084        format!(
1085            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1086        )
1087    },
1088    resume_cannot_progress: |q, run| {
1089        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1090    },
1091    resume_unreadable: |q, run, e| {
1092        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1093    },
1094    handover_refused: |r| {
1095        use crate::handover::Refused;
1096        match r {
1097            Refused::Foreign { branch, path, why } => format!(
1098                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1099                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1100                 から、やり直してください(詳細: {why})"
1101            ),
1102            Refused::Unsafe { branch, path, why } => format!(
1103                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1104                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1105                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1106            ),
1107            Refused::ReleaseFailed { branch, path, run } => format!(
1108                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1109                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1110                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1111            ),
1112        }
1113    },
1114    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1115    reviewers_never_answered: |missing, rounds| {
1116        format!(
1117            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1118             クリーンとは認めません"
1119        )
1120    },
1121};
1122
1123fn phrases(language: &str) -> &'static Phrases {
1124    if crate::lang::is_japanese(language) {
1125        &PHRASES_JA
1126    } else {
1127        &PHRASES_EN
1128    }
1129}
1130
1131/// The language of the repository a task belongs to, read best-effort for the
1132/// paths that have no run (and so no config of their own) to ask. An unreadable
1133/// config is English, not an error: a hold reason must still get written.
1134fn language_of(task: &Task, fallback: &Path) -> String {
1135    crate::lang::of_repo(&repo_for(task, fallback))
1136}
1137
1138/// The task an answered question speaks for: the one whose runs include the
1139/// question's run, or - for a conductor question, filed under the task's own
1140/// id - the task with that id.
1141pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1142    if q.node == crate::conduct::NODE {
1143        return tasks.iter().find(|t| t.id == q.run);
1144    }
1145    tasks.iter().find(|t| t.runs.contains(&q.run))
1146}
1147
1148/// Legacy conductor prose never becomes a maintenance command by inference.
1149/// Replace unsupported open labels under the question lock before dispatch.
1150fn repair_choice_offers(questions: &Questions) {
1151    for q in questions.list().into_iter().filter(|q| {
1152        q.status.open()
1153            && q.node == crate::conduct::NODE
1154            && q.choices
1155                .iter()
1156                .any(|c| crate::choice_effect::describe(q, c).is_none())
1157    }) {
1158        let _ = questions.update(&q.id, |current| {
1159            if current.status.open() {
1160                crate::choice_effect::executable_conductor(current);
1161                if let Some(deputy) = &mut current.deputy {
1162                    deputy.brief = crate::deputy::brief(
1163                        &current.run,
1164                        &current.detail,
1165                        &current.choices,
1166                        &current.actions,
1167                    );
1168                }
1169            }
1170            Ok(())
1171        });
1172    }
1173}
1174
1175/// Apply answered typed choices. Only the daemon calls this in production;
1176/// deputies settle the question and never execute its actions.
1177pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1178    apply_maintenance_choices(queue, questions, home).await;
1179    apply_task_choice_actions(queue, questions, home);
1180}
1181
1182/// Apply bounded maintenance effects independently of question ownership: a
1183/// release watcher need not have a queue task, and a predecessor is another run.
1184async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1185    use crate::release_watch::{GhForge, ReleaseForge};
1186    for q in questions.list() {
1187        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1188            continue;
1189        };
1190        if asker_may_still_read(questions, &q, home) || !crate::run::is_run_id(&q.id) {
1191            continue;
1192        }
1193        let dir = home.join("choice-actions");
1194        if std::fs::create_dir_all(&dir).is_err() {
1195            continue;
1196        }
1197        let Ok(lock) = std::fs::OpenOptions::new()
1198            .create(true)
1199            .truncate(false)
1200            .write(true)
1201            .open(dir.join(format!("{}.lock", q.id)))
1202        else {
1203            continue;
1204        };
1205        if crate::pr_head::try_lock_file(&lock).is_err() {
1206            continue;
1207        }
1208        let fresh = !home
1209            .join("choice-actions")
1210            .join(format!("{}.json", q.id))
1211            .exists();
1212        let result = async {
1213            let receipt = dir.join(format!("{}.json", q.id));
1214            if receipt.exists() {
1215                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1216                anyhow::ensure!(
1217                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1218                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1219                );
1220                return Ok::<_, anyhow::Error>(());
1221            }
1222            // Never retry an uncertain external effect. The receipt is written
1223            // before calling gh, exactly like release_watch's rerun record.
1224            let record = |status: &str| -> anyhow::Result<()> {
1225                let tmp = receipt.with_extension("tmp");
1226                std::fs::write(
1227                    &tmp,
1228                    serde_json::to_vec(&serde_json::json!({
1229                        "action": action, "status": status,
1230                    }))?,
1231                )?;
1232                std::fs::rename(tmp, &receipt)?;
1233                Ok(())
1234            };
1235            let applied = async {
1236                match action {
1237                    ask::ChoiceAction::ResumeRun { run } => {
1238                        crate::resume::validate(home, run)?;
1239                        record("started")?;
1240                        if let Some(listed) = queue
1241                            .list()
1242                            .into_iter()
1243                            .find(|t| t.runs.last() == Some(run))
1244                        {
1245                            let _claim = queue.claim(&listed.id)?;
1246                            let mut task = queue.get(&listed.id)?;
1247                            anyhow::ensure!(
1248                                task.runs.last() == Some(run)
1249                                    && !matches!(
1250                                        task.status,
1251                                        TaskStatus::Running | TaskStatus::Done
1252                                    ),
1253                                "run queue owner changed"
1254                            );
1255                            anyhow::ensure!(
1256                                !task.operator_held()
1257                                    && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1258                                "resume was superseded by an operator hold or newer operator decision"
1259                            );
1260                            task.release_operator("choice", Some(&q.id));
1261                            task.resume_override = Some(crate::queue::OperatorResume {
1262                                question_id: q.id.clone(),
1263                                at: Timestamp::now(),
1264                                conductor_rehold: None,
1265                                forced: true,
1266                                pinned_run: Some(run.clone()),
1267                            });
1268                            task.mark_action_applied(&q.id);
1269                            queue.put(&mut task)?;
1270                        } else {
1271                            crate::resume::validate_unqueued(home, run)?;
1272                            crate::resume::start(run.clone());
1273                        }
1274                    }
1275                    ask::ChoiceAction::ReleaseTask {
1276                        task,
1277                        held_at,
1278                        reason,
1279                    } => {
1280                        anyhow::ensure!(
1281                            queue.resolve_id(task)? == *task,
1282                            "task action requires an exact task ID"
1283                        );
1284                        let _claim = queue.claim(task)?;
1285                        let mut task = queue.get(task)?;
1286                        if task.action_applied(&q.id) {
1287                            return Ok(());
1288                        }
1289                        // Filing this conductor question temporarily wraps the
1290                        // original hold in a Blocked state. Restore only that
1291                        // exact blocker on the local copy before checking the
1292                        // hold binding; unrelated waits never authorize release.
1293                        if q.node == crate::conduct::NODE
1294                            && q.run == task.id
1295                            && task.status == TaskStatus::Blocked
1296                            && task.blocked_from == Some(TaskStatus::Held)
1297                            && task.blocked_by.as_slice() == [q.id.as_str()]
1298                        {
1299                            task.unblock(&q.id);
1300                        }
1301                        anyhow::ensure!(
1302                            task.status == TaskStatus::Held
1303                                && task.held_at == Some(*held_at)
1304                                && task.hold_reason.as_deref() == reason.as_deref()
1305                                && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1306                            "task no longer has the hold this question names"
1307                        );
1308                        task.release_operator("choice", Some(&q.id));
1309                        task.mark_action_applied(&q.id);
1310                        queue.put(&mut task)?;
1311                    }
1312                    ask::ChoiceAction::AbandonRun { run } => {
1313                        record("started")?;
1314                        crate::driver::abandon_proven_dead(home, run)?;
1315                    }
1316                    ask::ChoiceAction::RerunChecks {
1317                        repo,
1318                        pr,
1319                        head,
1320                        runs,
1321                    } => {
1322                        anyhow::ensure!(
1323                            !runs.is_empty()
1324                                && runs.len() <= 20
1325                                && runs
1326                                    .iter()
1327                                    .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1328                                && !pr.starts_with('-'),
1329                            "invalid rerun targets"
1330                        );
1331                        let snap = GhForge.snapshot(repo, pr).await?;
1332                        anyhow::ensure!(
1333                            snap.head == *head && snap.state == crate::land::PrLifecycle::Open,
1334                            "pull request head or lifecycle changed"
1335                        );
1336                        anyhow::ensure!(
1337                            runs.iter().all(|r| snap
1338                                .checks
1339                                .iter()
1340                                .any(|c| c.run.as_ref() == Some(r)
1341                                    && crate::release_watch::is_failed(c.verdict))),
1342                            "named workflow is no longer failed on this pull request"
1343                        );
1344                        record("started")?;
1345                        let rerun_lock = std::fs::OpenOptions::new()
1346                            .create(true)
1347                            .truncate(false)
1348                            .write(true)
1349                            .open(dir.join("reruns.lock"))?;
1350                        crate::pr_head::try_lock_file(&rerun_lock)?;
1351                        let ledger = dir.join("reruns.json");
1352                        let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1353                            serde_json::from_slice(&std::fs::read(&ledger)?)?
1354                        } else {
1355                            Default::default()
1356                        };
1357                        for run in runs {
1358                            let key = serde_json::to_string(&(&q.id, repo, pr, head, run))?;
1359                            if !recorded.insert(key) {
1360                                continue;
1361                            }
1362                            let tmp = ledger.with_extension("tmp");
1363                            std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1364                            std::fs::rename(tmp, &ledger)?;
1365                            GhForge.rerun(repo, run).await?;
1366                        }
1367                    }
1368                    _ => unreachable!(),
1369                }
1370                Ok::<_, anyhow::Error>(())
1371            }
1372            .await;
1373            match applied {
1374                Ok(()) => record("applied"),
1375                Err(e) => {
1376                    record(&format!("refused or failed: {e:#}"))?;
1377                    Err(e)
1378                }
1379            }
1380        }
1381        .await;
1382        // Retire the originating blocker as well as the target operation.
1383        // A foreign resume leaves its issuer held instead of competing beside
1384        // the execution just started. Other successful maintenance lets the
1385        // original task retry its normal, guarded path.
1386        if home
1387            .join("choice-actions")
1388            .join(format!("{}.json", q.id))
1389            .exists()
1390            && let Some(listed) = task_of_question(&queue.list(), &q)
1391            && !listed.action_applied(&q.id)
1392            && let Ok(_claim) = queue.claim(&listed.id)
1393            && let Ok(mut origin) = queue.get(&listed.id)
1394        {
1395            if !origin.operator_held()
1396                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1397                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1398            {
1399                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1400                    origin.hold_machine(Some(format!(
1401                        "Maintenance choice {} settled; inspect its target before releasing this task",
1402                        q.id
1403                    )));
1404                } else {
1405                    origin.unblock(&q.id);
1406                }
1407            }
1408            origin.mark_action_applied(&q.id);
1409            let _ = queue.put(&mut origin);
1410        }
1411        if let Err(e) = result
1412            && fresh
1413        {
1414            notices::raise_in(
1415                home,
1416                Notice::warn(
1417                    &format!("action:{}", q.id),
1418                    format!("Choice action {} was not completed: {e:#}", q.id),
1419                ),
1420            );
1421        }
1422    }
1423}
1424
1425/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1426///
1427/// Runs on every poll before the conductor looks at the queue. The task is
1428/// re-read under its claim, so a task somebody completed or held by hand in
1429/// the meantime is judged on what it is now. `Resume` releases the task and
1430/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1431/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1432/// ordinary `unfinished_run` logic resumes that same run.
1433pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1434    let tasks = queue.list();
1435    for q in questions.list() {
1436        // Dismissal is committed by the question writer, never a resume.
1437        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1438            continue;
1439        }
1440        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1441            continue;
1442        }
1443        let Some(listed) = task_of_question(&tasks, &q) else {
1444            if q.node == land::APPROVAL_NODE
1445                && q.resolution().as_deref().is_some_and(|choice| {
1446                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1447                })
1448            {
1449                notices::raise_in(
1450                    home,
1451                    Notice::warn(
1452                        &format!("repair-owner:{}", q.id),
1453                        format!(
1454                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1455                            q.run, q.run
1456                        ),
1457                    ),
1458                );
1459            }
1460            continue;
1461        };
1462        if listed.action_applied(&q.id) {
1463            continue;
1464        }
1465        let Ok(_claim) = queue.claim(&listed.id) else {
1466            continue;
1467        };
1468        let Ok(mut task) = queue.get(&listed.id) else {
1469            continue;
1470        };
1471        // Work only on this local copy until the action can be committed.
1472        // In particular, a fresh lease below leaves the persisted task blocked.
1473        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1474            let blockers: Vec<_> = task
1475                .blocked_by
1476                .iter()
1477                .filter(|id| {
1478                    crate::queue::dependency(queue, questions, id)
1479                        == crate::queue::Dependency::Question(q.id.clone())
1480                })
1481                .cloned()
1482                .collect();
1483            if !blockers.is_empty() {
1484                for id in blockers {
1485                    task.unblock(&id);
1486                }
1487                let answer = match &q.answer {
1488                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1489                    None => String::new(),
1490                };
1491                task.record_answer(q.summary.clone(), answer);
1492            }
1493        }
1494        let language = language_of(&task, Path::new("."));
1495        let decision = decide_action(&task, &q, phrases(&language), |id| {
1496            RunState::load_under(id, home)
1497        });
1498        let ran = matches!(
1499            decision,
1500            ActionDecision::Resume(_)
1501                | ActionDecision::Requeue
1502                | ActionDecision::Hold
1503                | ActionDecision::Done
1504        );
1505        if ran && asker_may_still_read(questions, &q, home) {
1506            // The asking process or its seat can still take the word; act
1507            // once it has gone quiet. Bound on the remaining window: the
1508            // check is not atomic with the write below, so an asker that
1509            // takes the word in between (at most one poll, never more than
1510            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1511            // and `Task::actions_applied` under the claim keeps the action to
1512            // one application. The waiter does not deliver an answer that
1513            // carries an action (`waiter::decide_owned`), so it cannot race.
1514            continue;
1515        }
1516        let done = matches!(decision, ActionDecision::Done);
1517        match decision {
1518            ActionDecision::Skip => continue,
1519            ActionDecision::Resume(run) => {
1520                task.release_operator("choice", Some(&q.id));
1521                task.resume_override = Some(crate::queue::OperatorResume {
1522                    question_id: q.id.clone(),
1523                    at: Timestamp::now(),
1524                    conductor_rehold: None,
1525                    forced: true,
1526                    pinned_run: Some(run),
1527                });
1528            }
1529            ActionDecision::Stale => {}
1530            ActionDecision::Requeue => {
1531                task.release_operator("choice-requeue", Some(&q.id));
1532                task.requeue();
1533            }
1534            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1535            ActionDecision::Done => task.succeed(),
1536            ActionDecision::Refuse(why) => {
1537                if task.operator_held() {
1538                    // A rejected answer does not release the operator's hold
1539                    // or reclassify it as recoverable by the conductor.
1540                    task.hold_reason = Some(match task.hold_reason.take() {
1541                        Some(reason) => format!("{reason}\n\n{why}"),
1542                        None => why,
1543                    });
1544                } else {
1545                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1546                    task.hold_machine(Some(why));
1547                }
1548                notices::raise(
1549                    Notice::warn(
1550                        &format!("action:{}", q.id),
1551                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1552                    )
1553                    .link(Link::Task {
1554                        id: task.id.clone(),
1555                    }),
1556                );
1557            }
1558        }
1559        task.mark_action_applied(&q.id);
1560        // The applied id travels with the transition, so a failed save loses
1561        // neither and the answer is acted on at the next poll.
1562        record(queue, &mut task);
1563        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1564            supersede_prior_runs(&task, home);
1565        }
1566        // Delivery is only a note of who has read the answer; the task's own
1567        // mark above is the authority. Best effort.
1568        let _ = questions.update(&q.id, |r| {
1569            r.answer_delivered = true;
1570            Ok(())
1571        });
1572    }
1573}
1574
1575/// Whether something may still read the answer to `q`: a fresh lease, or the
1576/// asking seat still listed as active in its run (its CLI can outlive the
1577/// `magi ask` that was killed).
1578fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1579    let now = Timestamp::now();
1580    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1581        return true;
1582    }
1583    q.node != crate::conduct::NODE
1584        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1585            s.seats_active()
1586                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1587        })
1588}
1589
1590/// Retire an unanswered conductor question after its task no longer refers to
1591/// it. Conductor questions use the task id in `Question::run`, so run-based
1592/// cleanup cannot observe a manual release or completion.
1593///
1594/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1595/// own question also carries a `run`, and a run id that happens to collide
1596/// with some task's id is not this loop's business — only a conductor
1597/// question actually uses the task id that way. One `Questions::list()` scan
1598/// is taken up front and matched against the in-memory task set, rather than
1599/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1600fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1601    let tasks = queue.list();
1602    let by_id: std::collections::BTreeMap<&str, &Task> =
1603        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1604    let referenced: Vec<&str> = tasks
1605        .iter()
1606        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1607        .collect();
1608
1609    for mut question in questions.list() {
1610        if !question.status.open() || question.node != crate::conduct::NODE {
1611            continue;
1612        }
1613        // Keep questions a task still names, including when the reference
1614        // moved to a dependent task.
1615        // Preserve even ambiguous references: retiring a possibly referenced
1616        // question is unsafe until the operator disambiguates it.
1617        if referenced
1618            .iter()
1619            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1620        {
1621            continue;
1622        }
1623        let Some(task) = by_id.get(question.run.as_str()) else {
1624            continue;
1625        };
1626        question.abandon(format!(
1627            "task {} no longer waits for this answer",
1628            task.short()
1629        ));
1630        if let Err(e) = questions.put(&mut question) {
1631            tracing::warn!(
1632                "could not retire question {} for task {}: {e:#}",
1633                question.short(),
1634                task.short()
1635            );
1636        }
1637    }
1638}
1639
1640/// What a finished run tells the queue about the task it came from.
1641///
1642/// A struct rather than a fourth and fifth boolean argument: the two flags
1643/// answer different questions about the same run, and a call site passing
1644/// `(…, true, false)` is one transposition away from refunding attempts
1645/// forever.
1646#[derive(Debug, Clone, Copy)]
1647pub struct Verdict {
1648    /// Where the graph stopped.
1649    pub status: RunStatus,
1650    /// The run opened a pull request.
1651    pub left_pr: bool,
1652    /// At least one seat was lost to a rate limit.
1653    pub quota_hit: bool,
1654    /// The run parked at a node boundary because it was asked to.
1655    pub parked: bool,
1656    /// The run never produced a single candidate a judge could look at.
1657    ///
1658    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1659    /// still have another candidate worth judging, in which case the loss was
1660    /// not the reason nothing came of the run. This is `true` only when the
1661    /// implement wave ended with nothing viable at all.
1662    pub no_viable_candidates: bool,
1663}
1664
1665/// Record a finished run against the task it came from.
1666///
1667/// Kept pure and separate from the loop because this mapping *is* the retry
1668/// policy, and a policy that can only be exercised by spawning a graph is a
1669/// policy nobody checks. The table:
1670///
1671/// | run status                           | task becomes        | attempt spent |
1672/// |---------------------------------------|---------------------|---------------|
1673/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1674/// | `Merged`, `Ready`                      | `Done`               | yes          |
1675/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1676/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1677/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1678/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1679/// | `Blocked` with a PR                    | `Held`               | yes          |
1680/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1681/// | `VerifiedNoop`                          | `Held`               | yes          |
1682/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1683///
1684/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1685/// deliberately: every candidate agreeing there is nothing to write is not a
1686/// machine fact about a rate limit, it is an unverified claim about the
1687/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1688/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1689/// claim could be wrong (a misread instruction, a stale check), and closing
1690/// the task automatically on an implementer's say-so would be the exact
1691/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1692/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1693/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1694/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1695/// claim regardless of whether the one already-spent attempt is refunded, and
1696/// [`Task::release`] resets the count to zero anyway the moment a human looks
1697/// at the evidence and lets it run again.
1698///
1699/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1700/// twice, together. A quorum lost to rate limits is a property of the machine
1701/// and not of the task, so the attempt is refunded and a reset quota picks
1702/// the work up where it stopped — and that is just as true when every
1703/// implement seat lost the same race and `after_implement` bails with nothing
1704/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1705/// machine fact. The `no_viable_candidates` guard is what keeps that row
1706/// narrow: a `Failed` run that produced a real candidate which then lost for
1707/// some other reason still spends the attempt, exactly like the quorum lost
1708/// to judges that answered with the wrong shape is ordinary flakiness, and
1709/// refunding *that* takes the bound off the retry loop entirely: run e633
1710/// stalled with `quota: []` after two judges wrote unusable JSON, was
1711/// refunded, and the next attempt paid for a fresh hour-long implement wave
1712/// before it could fail the same way. `max_attempts` exists precisely so
1713/// that cannot repeat forever.
1714///
1715/// A non-terminal status means `execute` returned while the graph was still
1716/// mid-flight, which is a bug rather than a verdict; it is treated as a
1717/// failure so that a task cannot loop on it either.
1718///
1719/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1720/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1721pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1722    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1723}
1724
1725/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1726fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1727    // A parked run is the operator's own doing, and its work is intact on
1728    // disk. The task goes back in line with its attempt refunded so the next
1729    // loop resumes the same run - which `one_task` prefers over competing
1730    // again - and so that swapping the binary a few times cannot exhaust a
1731    // budget meant for agents that actually misbehaved.
1732    if verdict.parked {
1733        task.park(detail);
1734        return;
1735    }
1736    match verdict.status {
1737        RunStatus::Merged | RunStatus::Ready
1738            if task.pr_recovery.as_ref().is_some_and(|s| {
1739                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1740            }) =>
1741        {
1742            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()));
1743        }
1744        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1745        RunStatus::AlreadyInBase => task.already_landed(detail),
1746        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1747        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1748            task.stall(detail)
1749        }
1750        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1751        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1752        RunStatus::Blocked => task.fail(detail, max_attempts),
1753        RunStatus::VerifiedNoop => task.handed_off(detail),
1754        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1755    }
1756}
1757
1758/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1759/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1760/// itself has actually finished *and* its own last attempt is provably why:
1761/// this loads that run and requires `Merged`/`Ready` before touching
1762/// anything earlier in `runs`, since `Task::succeed` can also be called
1763/// directly on a task whose last attempt never landed at all.
1764///
1765/// Called right after whatever call set `task.status` to
1766/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1767/// `reclaim`'s, but also every other place a task can be closed by hand
1768/// without the loop ever settling it itself: `magi task done`
1769/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1770/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1771/// GitHub merge, say, exactly the workflow this repository's own
1772/// "Landing a run's winner by hand" documents — is just as much "this task's
1773/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1774/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1775/// forever, which is the exact backlog this status exists to clear. `pub`
1776/// for those two out-of-module callers; everything else about this stays
1777/// internal bookkeeping.
1778///
1779/// A run something is still actually driving is left alone: a
1780/// task cannot be `Done` while one of its *own* attempts is still in flight,
1781/// so a live one at this point can only be an unrelated process — a manual
1782/// `--resume` of this old, now-moot run — and rewriting under it would just
1783/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1784/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1785/// pair `run_report`/`run_detail` use for the same question elsewhere:
1786/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1787/// --resume` invoked by hand outside it, which `liveness` also checks via
1788/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1789/// (already terminal in some other way, or itself mid-run) is left untouched
1790/// too.
1791///
1792/// Best-effort, like the rest of this module's bookkeeping: a load or save
1793/// failure here is a `tracing::warn`, not a failed settle, and the next time
1794/// this same task's completion is recorded — or a daemon restart replays
1795/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1796/// separate reconciliation pass; if that gap ever matters in practice, one
1797/// can be added then.
1798///
1799/// `home` is a parameter, not the process-global [`crate::run::home`], for
1800/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1801/// calls this with `ui.home`, which is `crate::run::home()` in a real
1802/// process but a fixture's own directory under test — falling through to
1803/// the global there would read and write through whichever home some other
1804/// test in the same binary happened to pin into that `OnceLock` first, not
1805/// the run this call actually means.
1806pub fn supersede_prior_runs(task: &Task, home: &Path) {
1807    let now = Timestamp::now();
1808    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1809    // right behind a `Merged`/`Ready` verdict) from one set directly by
1810    // `magi task done`/its web equivalent/the conductor on a task whose last
1811    // recorded attempt never actually landed - that requires reading the
1812    // run itself, which is exactly what this does before trusting anything
1813    // in `runs` is safe to relabel.
1814    let last_run_succeeded = task
1815        .runs
1816        .last()
1817        .and_then(|id| RunState::load_under(id, home).ok())
1818        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1819    for id in task.superseded_attempts(last_run_succeeded) {
1820        let mut state = match RunState::load_under(id, home) {
1821            Ok(s) => s,
1822            Err(e) => {
1823                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1824                continue;
1825            }
1826        };
1827        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1828            continue;
1829        }
1830        let daemon_claims = is_working_on(home, id, now);
1831        if state.liveness(daemon_claims) == Liveness::Live {
1832            continue;
1833        }
1834        state.status = RunStatus::Superseded;
1835        if let Err(e) = state.save_under(home) {
1836            tracing::warn!("could not mark run {id} superseded: {e:#}");
1837        }
1838    }
1839}
1840
1841/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1842/// finish the moment it was called, because one of its earlier attempts was
1843/// still live then - a `magi run --resume` invoked by hand on an old run,
1844/// most likely.
1845///
1846/// That skip is correct at the time (rewriting under a run something is
1847/// still actively saving would just be undone), but a task only ever
1848/// reaches `Done` once, so without this nothing would ever look at it
1849/// again: if that manual process later ends anywhere other than
1850/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1851/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1852/// backlog this status exists to clear. Called on the same idle-only
1853/// cadence as [`janitor`], next to it rather than folded into it: this
1854/// walks `queue` and `janitor` never otherwise needs one.
1855///
1856/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1857/// more than one attempt, every pass: each call is a handful of local file
1858/// reads bounded by that task's own attempt count, the same order of cost
1859/// [`clean::fold_due`] already pays scanning every run on disk on the same
1860/// cadence, and a task already fully resolved costs one failed liveness
1861/// check turned no-op the moment its lingering attempt is no longer live.
1862fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1863    for task in queue.list() {
1864        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1865            continue;
1866        }
1867        supersede_prior_runs(&task, home);
1868    }
1869}
1870
1871/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1872/// task ends up held.
1873///
1874/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1875/// dead daemon never got back to) share this, so the two cannot drift into
1876/// disagreeing about which held tasks get a diagnostic.
1877fn settle_and_diagnose(
1878    task: &mut Task,
1879    verdict: Verdict,
1880    detail: &str,
1881    max_attempts: usize,
1882    state: &RunState,
1883) {
1884    let p = phrases(&state.config.graph.language);
1885    // Shared by normal completion and crash recovery, under the task claim.
1886    // No new attempt can own the task until the old driver has exited.
1887    if let Some(d) = &state.merge_decision {
1888        use crate::merge_decision as md;
1889        if task.runs.last().is_some_and(|id| id != &state.id) {
1890            return;
1891        }
1892        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1893            task.succeed();
1894        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1895            if state.liveness(false) != Liveness::Dead {
1896                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1897                return;
1898            }
1899            let replacement = md::Replacement {
1900                question: d.question.clone(),
1901                run: state.id.clone(),
1902                pr: d.target.pr.clone(),
1903                agent: agent.to_owned(),
1904                context: format!(
1905                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1906                    d.target.pr,
1907                    state.id,
1908                    serde_json::to_string(&state.reviews).unwrap_or_default()
1909                ),
1910            };
1911            task.requeue();
1912            task.pr_recovery = None;
1913            task.review_of = None;
1914            task.replacement = Some(replacement);
1915        } else {
1916            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1917                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1918            } 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())) }));
1919        }
1920        task.mark_action_applied(&d.question);
1921        if let Some(pass) = state.passes.last() {
1922            task.record_pass(&state.id, pass.index, task.attempts, None);
1923        }
1924        return;
1925    }
1926    if let Some(replacement) = &task.replacement
1927        && !state.parked
1928        && state.resource_block.is_none()
1929        && (state.viable().is_empty()
1930            || (state.status == RunStatus::Blocked && state.tally.is_none()))
1931    {
1932        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)));
1933        return;
1934    }
1935    let attempts_before = task.attempts;
1936    // A run that stopped because a shared resource stayed busy was never a
1937    // failure of the task or of any agent: nothing was asked. The attempt is
1938    // refunded and the task is held by the machine, under a reason `triage`
1939    // can re-check, so the same run resumes with the same agents once the
1940    // resource is free. A park request still wins (it is the operator's).
1941    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
1942        task.notice_cause(
1943            &format!("resource:{}:{}", block.kind, block.node),
1944            None,
1945            None,
1946        );
1947        task.last_error = Some(detail.to_owned());
1948        task.diagnostic = None;
1949        task.attempts = task.attempts.saturating_sub(1);
1950        task.hold_machine(Some(format!(
1951            "{}{} stayed busy past the resource-wait limit before `{}` could start; \
1952             no agent was asked and no attempt was spent",
1953            crate::cache::RESOURCE_HOLD,
1954            block.kind,
1955            block.node
1956        )));
1957        if let Some(pass) = state.passes.last() {
1958            task.record_pass(&state.id, pass.index, attempts_before, None);
1959        }
1960        return;
1961    }
1962    let unresolved = task.hold_notice_cause.clone();
1963    if !verdict.parked
1964        && task
1965            .pr_recovery
1966            .as_ref()
1967            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
1968        && matches!(
1969            verdict.status,
1970            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
1971        )
1972    {
1973        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
1974            task.succeed();
1975        } else {
1976            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()));
1977        }
1978    } else if !verdict.parked
1979        && task.pr_recovery.is_some()
1980        && matches!(
1981            verdict.status,
1982            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
1983        )
1984        && !verdict.quota_hit
1985    {
1986        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.")));
1987    } else {
1988        settle_in(task, verdict, detail, max_attempts, p);
1989    }
1990    if state.prep_failure.is_some() {
1991        // Minting a run whose candidates could not be prepared is not work
1992        // on a newly approved attempt. Keep the unresolved outcome anchor.
1993        task.hold_notice_cause = unresolved;
1994        task.startup_notice_cause("startup-candidates");
1995    }
1996    // Written here, where the refund (or not) is decided, so the history is a
1997    // fact and not a later guess from the run's status.
1998    if let Some(pass) = state.passes.last() {
1999        let parked = match &pass.end {
2000            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2001            _ => None,
2002        };
2003        task.record_pass(&state.id, pass.index, attempts_before, parked);
2004    }
2005    if task.status == TaskStatus::Held {
2006        if state.prep_failure.is_none() {
2007            task.notice_cause(
2008                label(verdict.status),
2009                Some(&state.id),
2010                state.passes.last().map(|p| p.index),
2011            );
2012        }
2013        task.diagnostic = diagnostic(state);
2014        note_open_question(task, &state.id, p);
2015    }
2016}
2017
2018/// If `task` is held with a `magi ask` question still open on `run`, name the
2019/// question in [`Task::hold_reason`] rather than leaving the hold reading
2020/// only [`describe`]'s run summary.
2021///
2022/// This is the shape task 20260928-191407-05fd left underspecified: an
2023/// implementer settled a verified no-op and filed a question for the
2024/// operator, and the hold that followed said nothing about the question
2025/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2026/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2027/// marker) and must keep seeing it unchanged.
2028///
2029/// Best-effort: an unreadable question store must not stop a run from
2030/// settling, so this is a no-op rather than a propagated error when
2031/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2032fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2033    let Some(home) = crate::run::try_home() else {
2034        return;
2035    };
2036    let open = Questions::at(home.join("questions")).open_for(run);
2037    let Some(q) = open.first() else {
2038        return;
2039    };
2040    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2041    decisions.sort_unstable();
2042    task.notice_cause(
2043        &format!("questions:{}", decisions.join(",")),
2044        Some(run),
2045        None,
2046    );
2047    let base = task.hold_reason.clone().unwrap_or_default();
2048    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2049}
2050
2051/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2052/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2053/// by some other means entirely, like a manual `magi run` resume that
2054/// finishes the graph outside the queue's bookkeeping.
2055///
2056/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2057/// `settle` is separate from `attempt`: a task recovered this way must land
2058/// exactly where a live daemon would have put it — the same policy table,
2059/// not a second one that quietly drifts from it — and that is only checkable
2060/// without spawning a real run.
2061fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2062    match last_run {
2063        Some(state) => {
2064            let verdict = Verdict {
2065                status: state.status,
2066                left_pr: state.pr.is_some(),
2067                quota_hit: !state.quota.is_empty(),
2068                parked: state.parked,
2069                no_viable_candidates: state.viable().is_empty(),
2070            };
2071            let detail = format!(
2072                "{}{}",
2073                phrases(&state.config.graph.language).recovered_running,
2074                describe(&state)
2075            );
2076            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2077        }
2078        None => {
2079            // No run, so no config of its own: `language` is the task's
2080            // repository's setting, read by the caller.
2081            let why = phrases(language).no_run_to_recover;
2082            task.last_error = Some(why.to_owned());
2083            // The phone shows `hold_reason`, so a task held by the machine
2084            // says why there too and not only in `last_error`.
2085            task.notice_cause("missing-run", None, None);
2086            task.hold_machine(Some(why.to_owned()));
2087        }
2088    }
2089}
2090
2091/// Find every task left at `running` that no live process is actually
2092/// driving, and settle each one against whatever its last run became.
2093///
2094/// # Why a claim is proof, not a guess
2095///
2096/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2097/// `running`, and the guard is held for the task's whole time in that status:
2098/// `attempt` does not return, and the loop does not move past the scope
2099/// holding the claim, until the run has settled. So a `running` task whose
2100/// lock is gone cannot have a live owner — this process or any other —
2101/// without needing a staleness threshold or a pid check the way
2102/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2103/// task that never got as far as `running` at all. Taking the claim here is
2104/// the whole test: it either fails, because something really does hold it
2105/// and the task is left alone, or it succeeds, which is the proof — and it is
2106/// kept for the rest of the decision so nothing else can start a competing
2107/// run while this one is being written.
2108///
2109/// Called on every poll, not only at startup, for the reason
2110/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2111/// keep noticing this, not only on the one morning it happened to restart.
2112fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
2113    let mut reclaimed = Vec::new();
2114    for listed in queue.list() {
2115        if listed.status != TaskStatus::Running {
2116            continue;
2117        }
2118        let Ok(_claim) = queue.claim(&listed.id) else {
2119            continue;
2120        };
2121        // Re-read under the claim: a release or an edit landed by a human
2122        // between the listing above and the claim just taken must not be
2123        // clobbered by a decision based on the stale copy.
2124        let Ok(mut task) = queue.get(&listed.id) else {
2125            continue;
2126        };
2127        if task.status != TaskStatus::Running {
2128            continue;
2129        }
2130        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2131        // `execute` normally abandons a run's own open questions the moment
2132        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2133        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2134        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2135        // with the question still `open`, because the process died before
2136        // reaching that call. `reclaim` itself stays pure on purpose (see its
2137        // own doc), so the same cleanup runs here instead, against the run
2138        // this reclaim is already reading. `settle_run` costs nothing when
2139        // `execute` already got there first.
2140        if let Some(state) = &last_run
2141            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2142        {
2143            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2144        }
2145        let language = if last_run.is_none() {
2146            language_of(&task, Path::new("."))
2147        } else {
2148            String::new()
2149        };
2150        reclaim(&mut task, last_run, max_attempts, &language);
2151        if task.status == TaskStatus::Done {
2152            supersede_prior_runs(&task, &crate::run::home());
2153        }
2154        record(queue, &mut task);
2155        reclaimed.push(task.id.clone());
2156    }
2157    reclaimed
2158}
2159
2160/// Find every run whose `run.json` is provably dead — every seat it still
2161/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2162/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2163/// not merely "no daemon claims it" — and fail it, clearing the leftover
2164/// active seats so the run stops reading as `implementing` (or whichever
2165/// node) forever.
2166///
2167/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2168/// `running`, using whatever `run.json` already says — but nothing in that
2169/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2170/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2171/// never got back to sits exactly where it was left: `active` full of seats
2172/// nobody will ever answer for, `status` stuck on whatever node was in
2173/// flight. `magi show` already tells an operator this in prose (`no live
2174/// daemon claims this run right now`); this is what makes that fact durable
2175/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2176/// stay stuck once nothing is driving it.
2177///
2178/// Runs on every poll, not only at startup, for the reason
2179/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2180/// daemon up for days must keep noticing a run some other, now-dead, daemon
2181/// left behind just as readily as one it trips over on the way up.
2182///
2183/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2184/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2185/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2186/// `runs` directory instead: `home` here is a parameter precisely so a test
2187/// can point it away from the operator's real history (see [`drive`]'s own
2188/// doc), and a scan that fell through to the global home anyway would walk
2189/// whichever directory some *other* process or test pinned into that
2190/// `OnceLock` first — mutating runs this call was never handed.
2191fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2192    reclaim_abandoned_runs_with(
2193        home,
2194        now,
2195        crate::proc::pid_status,
2196        crate::proc::process_started_at,
2197    )
2198}
2199
2200/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2201/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2202/// for the identical reason: this sweep's real damage (wiping a run's active
2203/// seats and failing it) has to be provable against an injected answer in a
2204/// test, not just the real process table.
2205fn reclaim_abandoned_runs_with<F, G>(
2206    home: &Path,
2207    now: Timestamp,
2208    query: F,
2209    identity: G,
2210) -> Vec<String>
2211where
2212    F: Fn(u32) -> Option<bool>,
2213    G: Fn(u32) -> Option<String>,
2214{
2215    let mut abandoned = Vec::new();
2216    for entry in std::fs::read_dir(home.join("runs"))
2217        .into_iter()
2218        .flatten()
2219        .flatten()
2220    {
2221        let id = entry.file_name().to_string_lossy().into_owned();
2222        if !crate::run::is_run_id(&id) {
2223            continue;
2224        }
2225        // Serialize the proof and save with claims and takeover: a new
2226        // execution must not be overwritten after the liveness observation.
2227        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2228            continue;
2229        };
2230        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2231        // that module's docs for why a run this cannot parse is left alone
2232        // rather than guessed at. A different schema number is not that: this
2233        // touches only `status` and `active`, never a field whose meaning a
2234        // schema bump changed, so an old record's values serve this exactly
2235        // as well as a current one's (see `clean::read_state`'s own doc for
2236        // the same reasoning applied to folding).
2237        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2238            continue;
2239        };
2240        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2241            continue;
2242        };
2243        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2244            continue;
2245        }
2246        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2247        // it", which is also the normal, healthy shape of a manual `magi
2248        // run` / `magi review` sharing this same home — this scan walks
2249        // every run on disk, not only ones this daemon itself started. Such
2250        // a run's active seats can legitimately sit past their own timeout
2251        // for a little while (the CLI finishing up, its result still being
2252        // collected) without the process driving it having died. `liveness`
2253        // is what actually tells the two apart, by corroborating
2254        // `driver_pid` against the process it names — see its own doc. Only
2255        // its strongest, provable answer licenses wiping this run's active
2256        // seats and failing it out from under whatever is still running it.
2257        let daemon_claims = is_working_on(home, &id, now);
2258        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2259            != crate::run::Liveness::Dead
2260        {
2261            continue;
2262        }
2263        state.abandon("daemon");
2264        if let Err(e) = state.save_under(home) {
2265            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2266            continue;
2267        }
2268        // This run never passes through `Runner::execute` again, so its end
2269        // is announced here.
2270        if let Some(notice) = notices::run_ended(&state) {
2271            notices::raise_in(home, notice);
2272        }
2273        // The seat that asked is gone for good now, exactly like any other
2274        // door `graph::Runner::settle_questions` closes the moment `status`
2275        // lands somewhere non-resumable - see that method's own doc. Nothing
2276        // else reaches this one before the next `janitor()` startup pass
2277        // (`clean::abandon_settled_questions`), and a daemon that stays up
2278        // for days must not leave an open question badging the operator
2279        // until it happens to restart.
2280        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2281            tracing::warn!("abandon questions for {id}: {e:#}");
2282        }
2283        abandoned.push(id);
2284    }
2285    abandoned
2286}
2287
2288/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2289///
2290/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2291/// sets, so there is one loop body rather than two that drift apart the first
2292/// time the retry policy changes on only one of them.
2293pub async fn serve(opts: Opts) -> Result<()> {
2294    serve_until(opts, Stop::new()).await
2295}
2296
2297/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2298///
2299/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
2300/// mid-node leaves worktrees, branches and agent sessions behind, and every
2301/// agent call already paid for is lost; finishing the run costs the operator a
2302/// wait and saves them a cleanup. A stop therefore only sets a flag: the
2303/// current `execute` runs to its terminal status, the task's outcome is
2304/// recorded, and only then does the loop return. That window is what
2305/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
2306/// still has a second Ctrl-C, which the runtime turns into a process kill —
2307/// and the task left `Running` then tells the next daemon, and the next human,
2308/// where to look.
2309///
2310/// While the queue is empty the stop is honoured within one wakeup rather than
2311/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2312/// caller that taps stop does not sit through the remainder of a sleep.
2313pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2314    let signal = {
2315        let stop = stop.clone();
2316        tokio::spawn(async move {
2317            if tokio::signal::ctrl_c().await.is_ok() {
2318                stop.stop();
2319                tracing::info!("shutdown requested; a run in flight will be finished first");
2320            }
2321        })
2322    };
2323
2324    let worktrees_root = opts
2325        .worktrees_root
2326        .clone()
2327        .unwrap_or_else(crate::run::default_worktree_root);
2328    let outcome = drive(
2329        &opts,
2330        &Queue::open(),
2331        &status_path(),
2332        &crate::run::home(),
2333        &worktrees_root,
2334        &stop,
2335    )
2336    .await;
2337
2338    signal.abort();
2339    outcome
2340}
2341
2342/// The loop proper: setup, poll, teardown, with the queue and the status file
2343/// supplied rather than discovered.
2344///
2345/// All three of `home`, `worktrees_root` and the queue/status paths are
2346/// parameters rather than resolved here, for the same reason:
2347/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2348/// so a unit test that pinned it would fight every other test in the binary,
2349/// and a loop that resolved its own worktree bay could only be exercised
2350/// against the operator's real `~/wt/<repo>` - publishing over a live
2351/// daemon's status file, claiming tasks out of a live backlog, and, since
2352/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2353/// whatever the operator actually has on disk.
2354async fn drive(
2355    opts: &Opts,
2356    queue: &Queue,
2357    status_file: &Path,
2358    home: &Path,
2359    worktrees_root: &Path,
2360    stop: &Stop,
2361) -> Result<()> {
2362    // The status file is a *snapshot*, not a stream of events: a reader only
2363    // ever wants the latest values, and every tick rewrites the whole file
2364    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2365    // while an mpsc channel would force the loop to re-send unchanged fields on
2366    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2367    // for no gain. The lock is only ever held across a field assignment, never
2368    // across an await.
2369    let recovery_cfg = prepare(&opts.repo, opts).ok();
2370    let daemon_cfg = recovery_cfg
2371        .as_ref()
2372        .map(|c| c.daemon.clone())
2373        .unwrap_or_default();
2374    let reconciled = crate::driver::reconcile(home);
2375    if !reconciled.is_empty() {
2376        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2377    }
2378    let mut initial_status = Status::new();
2379    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2380        recovery_cfg.as_ref(),
2381        daemon_cfg.max_deputies,
2382    ));
2383    let status = Arc::new(Mutex::new(initial_status));
2384    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2385    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2386
2387    // Read once at startup, not per task: how many runs this loop drives at
2388    // once is a property of the machine running it, not of whichever
2389    // repository a given task happens to name - see
2390    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2391    // fact in the same sense the agent roster is.
2392    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2393
2394    // Something has to be waiting on every question for as long as it is open,
2395    // whether or not the agent's own `magi ask` survived. Its own task rather
2396    // than a step of the poll loop: the poll loop is busy for the whole of a
2397    // run, and an owner's reply must not queue behind one.
2398    let waiter = tokio::spawn(crate::waiter::run(
2399        crate::waiter::Waiter::new(
2400            crate::ask::Questions::at(home.join("questions")),
2401            home.to_path_buf(),
2402            recovery_cfg.clone(),
2403        ),
2404        stop.clone(),
2405    ));
2406
2407    // The follow-up seats for the conductor's questions: the conductor files a
2408    // question and moves on, and each open one gets a deputy that reads the
2409    // owner's reply. Its own task for the same reason the waiter's is.
2410    let deputies = tokio::spawn(crate::deputy::run(
2411        crate::deputy::Deputies::new(
2412            crate::ask::Questions::at(home.join("questions")),
2413            home.to_path_buf(),
2414            recovery_cfg.clone(),
2415            opts.repo.clone(),
2416            daemon_cfg.max_deputies,
2417            {
2418                let stop = stop.clone();
2419                Arc::new(move || stop.parking())
2420            },
2421        ),
2422        stop.clone(),
2423    ));
2424
2425    // Keeps every checkout's origin/main fresh; its own task so a slow remote
2426    // never holds up the poll loop.
2427    let fetcher = tokio::spawn(fetch_loop(opts.repo.clone(), opts.clone(), stop.clone()));
2428
2429    // Watches the release-bump pull requests until they land; its own task, not
2430    // tied to any run, because a pending bump outlives the run that opened it.
2431    let release_watch = tokio::spawn(crate::release_watch::run(
2432        crate::release_watch::Watcher::new(
2433            Box::new(crate::release_watch::GhForge),
2434            home.to_path_buf(),
2435        ),
2436        {
2437            let (repo, opts) = (opts.repo.clone(), opts.clone());
2438            move || release_watch_settings(&repo, &opts)
2439        },
2440        stop.clone(),
2441    ));
2442
2443    tracing::info!(
2444        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2445        queue.root().display(),
2446        opts.poll.as_secs(),
2447        opts.max_attempts,
2448        concurrency,
2449        if daemon_cfg.pause_for_interrupts {
2450            ", interrupts enabled"
2451        } else {
2452            ""
2453        }
2454    );
2455
2456    // `--once` drains an already-idle queue without reaching the idle wait,
2457    // but must still perform the startup cleanup.
2458    janitor(&opts.repo, opts, home, worktrees_root).await;
2459    resweep_superseded_attempts(queue, home);
2460
2461    let outcome = poll(
2462        opts,
2463        queue,
2464        &status,
2465        home,
2466        worktrees_root,
2467        stop,
2468        DispatchLimits {
2469            max_concurrent: concurrency,
2470            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2471        },
2472    )
2473    .await;
2474
2475    beat.abort();
2476    waiter.abort();
2477    deputies.abort();
2478    fetcher.abort();
2479    release_watch.abort();
2480    clear_status_at(status_file);
2481    outcome
2482}
2483
2484/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2485/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2486fn release_watch_settings(repo: &Path, opts: &Opts) -> (Vec<PathBuf>, u64) {
2487    let Ok(cfg) = prepare(repo, opts) else {
2488        return (Vec::new(), 0);
2489    };
2490    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2491        .into_iter()
2492        .map(|r| r.path)
2493        .collect();
2494    // Repositories the daemon has worked in, wherever they live: a task may
2495    // name one outside `[repos] roots`, and its release PR must be watched too.
2496    let mut known: Vec<PathBuf> = Queue::open().list().into_iter().map(|t| t.repo).collect();
2497    let runs = crate::run::home().join("runs");
2498    for id in crate::run::list_ids_in(&runs) {
2499        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2500            .ok()
2501            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2502            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2503        known.extend(repo);
2504    }
2505    for k in known {
2506        let k = k.canonicalize().unwrap_or(k);
2507        if k.join(".git").exists() && !paths.contains(&k) {
2508            paths.push(k);
2509        }
2510    }
2511    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2512    if !paths.contains(&own) {
2513        paths.push(own);
2514    }
2515    (paths, cfg.daemon.release_stall_minutes)
2516}
2517
2518/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2519const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2520
2521/// Run [`crate::clean::fetch_origins`] every `[repos] fetch_interval` seconds
2522/// until `stop`. The config is re-read each lap; `0` (or an unreadable config)
2523/// disables the fetch for that lap. Never fails.
2524async fn fetch_loop(repo: PathBuf, opts: Opts, stop: Stop) {
2525    while !stop.stopped() {
2526        let (interval, roots) = match prepare(&repo, &opts) {
2527            Ok(c) => (c.repos.fetch_interval, c.repos.roots),
2528            Err(_) => (0, Vec::new()),
2529        };
2530        if interval > 0 && !roots.is_empty() {
2531            let r = crate::clean::fetch_origins(&roots, FETCH_TIMEOUT, || stop.stopped()).await;
2532            tracing::debug!("fetch origins: {r:?}");
2533        }
2534        // Sleep in slices so a stop or a config change is noticed promptly.
2535        let wait = if interval > 0 { interval } else { 60 };
2536        let mut slept = 0;
2537        while slept < wait && !stop.stopped() {
2538            tokio::time::sleep(Duration::from_secs(1)).await;
2539            slept += 1;
2540        }
2541    }
2542}
2543
2544/// Refresh the status file on a fixed tick.
2545///
2546/// Separate from the loop because a run takes tens of minutes: a status file
2547/// written only between tasks would look stale for the whole of every run, and
2548/// a reader would report the daemon dead exactly while it was busiest.
2549async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2550    loop {
2551        tokio::time::sleep(HEARTBEAT).await;
2552        let snapshot = {
2553            let mut guard = lock(&status);
2554            guard.updated_at = Timestamp::now();
2555            guard.clone()
2556        };
2557        if let Err(e) = write_status_to(&path, &snapshot) {
2558            // A failed heartbeat must not take the daemon down: the loop is the
2559            // product, the status file is only the window onto it.
2560            tracing::warn!("could not refresh the daemon status file: {e:#}");
2561        }
2562    }
2563}
2564
2565/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2566/// if so, whether that wait is over.
2567#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2568enum LandResume {
2569    /// The task's last run is not parked on a land approval; schedule it
2570    /// like any other candidate.
2571    NotLanding,
2572    /// Parked in `land`, waiting on a question nobody has answered yet.
2573    /// Left alone: attempting it now would only re-observe the same pull
2574    /// request and park again, spending a `gh` call on a decision that has
2575    /// not changed since the last time this was checked.
2576    StillWaiting,
2577    /// Parked in `land`, and the question is settled - answered or
2578    /// abandoned. Resuming this is the one kind of candidate that must not
2579    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2580    Ready,
2581}
2582
2583/// Classify a runnable candidate by whether it is parked on a land-merge
2584/// approval. Read-only - no claim taken, nothing written - so it is cheap
2585/// enough to call on every candidate, every poll.
2586fn land_resume_state(task: &Task) -> LandResume {
2587    let Some(run_id) = task.runs.last() else {
2588        return LandResume::NotLanding;
2589    };
2590    let Ok(state) = RunState::load(run_id) else {
2591        return LandResume::NotLanding;
2592    };
2593    if !state.parked {
2594        return LandResume::NotLanding;
2595    }
2596    if state.status == RunStatus::Landing
2597        && state.land_approval.as_ref().is_some_and(|binding| {
2598            ask::Questions::open()
2599                .get(&binding.question)
2600                .is_ok_and(|q| {
2601                    q.run == state.id
2602                        && q.resolution()
2603                            .as_deref()
2604                            .is_some_and(crate::merge_decision::stops)
2605                })
2606        })
2607    {
2608        return LandResume::Ready;
2609    }
2610    if !implementers_match(task, &state) {
2611        return LandResume::NotLanding;
2612    }
2613    // Parked in `land` on the merge approval, or at `merge` on the owner's
2614    // word about a title/body the posting gate withheld. Told apart by the
2615    // run's own record, not by a status both can share.
2616    let node = if state.status == RunStatus::Landing {
2617        land::APPROVAL_NODE
2618    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
2619        crate::github_text::ASK_NODE
2620    } else {
2621        return LandResume::NotLanding;
2622    };
2623    let store = ask::Questions::open();
2624    let waiting = store
2625        .list()
2626        .into_iter()
2627        .filter(|q| &q.run == run_id && q.node == node)
2628        .max_by(|a, b| a.id.cmp(&b.id));
2629    let Some(mut q) = waiting else {
2630        return LandResume::Ready;
2631    };
2632    if !q.status.open() {
2633        // Repair spends agent resources and must obey concurrency and quota
2634        // waits; only a merge/hold decision may use the decision-only lane.
2635        if q.resolution().as_deref() == Some(land::REPAIR) {
2636            return if state.liveness(false) == Liveness::Live {
2637                LandResume::StillWaiting
2638            } else {
2639                LandResume::NotLanding
2640            };
2641        }
2642        return LandResume::Ready;
2643    }
2644    // `ask::ask_and_wait`'s own deadline is what used to retire a question
2645    // nobody ever answered; land's approval bypasses that wait entirely (see
2646    // `land::approval_gate`), so the same deadline has to be enforced here
2647    // instead, or `graph.answer_timeout` silently stops meaning anything for
2648    // a land approval and a run can sit `StillWaiting` forever with nobody
2649    // told to look at it.
2650    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
2651    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
2652    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
2653        q.abandon(format!(
2654            "no answer within {}s of asking",
2655            timeout.as_secs().max(1)
2656        ));
2657        // If this can't be persisted, do not treat the wait as settled on a
2658        // guess: fall through and try again next poll.
2659        if store.put(&mut q).is_ok() {
2660            return LandResume::Ready;
2661        }
2662    }
2663    LandResume::StillWaiting
2664}
2665
2666/// How often the loop rechecks for new work while something it already
2667/// started is still running, rather than sleeping out the whole
2668/// [`Opts::poll`] interval.
2669///
2670/// Short on purpose: this is what lets a land-merge approval that comes back
2671/// while another task is mid-competition be noticed and resumed within a
2672/// fraction of a second, not within the next multi-second poll.
2673const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
2674
2675/// How often [`poll`] rechecks the shared build cache against its cap at a
2676/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
2677/// waiting for the queue to run dry.
2678///
2679/// A queue that never empties means the `janitor` call at the bottom of this
2680/// loop's fully-idle branch can go unreached for as long as the backlog
2681/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
2682/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
2683/// 81.8 GiB an idle-only check let it reach before this existed, and it is
2684/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
2685/// backlog of short tasks does not pay for that walk on every poll.
2686const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
2687
2688/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
2689/// in `Status::current` - on drop, so both are released even if the attempt
2690/// panics rather than returning.
2691///
2692/// A `Drop` impl rather than statements written after the `.await` it
2693/// guards: a panic unwinds straight past code placed "after" a call, and
2694/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
2695/// that ruling a panic out there is not a bet this loop can make. Without
2696/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
2697/// forever - the idle branch in [`poll`], and with it the janitor, would
2698/// never run again - and a ghost entry in `Status::current` naming a task
2699/// nothing is still working on.
2700struct InFlightGuard<'a> {
2701    status: &'a Arc<Mutex<Status>>,
2702    stop: &'a Stop,
2703    task_id: &'a str,
2704}
2705
2706impl Drop for InFlightGuard<'_> {
2707    fn drop(&mut self) {
2708        lock(self.status).current.retain(|c| c.task != self.task_id);
2709        self.stop.exit();
2710    }
2711}
2712
2713/// State of [`poll`]'s own interrupt-scheduling sequence - see
2714/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
2715/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
2716/// both kept free of `Task`'s non-identity fields on purpose: every decision
2717/// here turns only on task ids and which ones are in flight, so the "never
2718/// more than one run at once" and "exactly one resume" invariants can be
2719/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
2720/// queue - which is exactly the coverage this feature's first two attempts
2721/// were missing.
2722///
2723/// Deliberately in-memory only, not written to disk anywhere: a daemon
2724/// restart mid-sequence loses track of which run it had asked to park and
2725/// which task was meant to run first, and simply falls back to `Idle` -
2726/// see [`drive`]'s own setup. The parked run itself is not lost - it is
2727/// sitting in the queue exactly like any other resumable, interrupted task,
2728/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
2729/// just resumes on the ordinary priority order rather than guaranteed to go
2730/// first. Giving that guarantee a crash-proof memory would mean a new queue
2731/// field and a recovery ordering to go with it, which is exactly the
2732/// complexity this feature's constraints rule out for the one property that
2733/// actually matters: at most one run, ever, at once.
2734#[derive(Debug, Clone, PartialEq, Eq)]
2735enum Interrupt {
2736    /// No interrupt sequence in progress. Ordinary dispatch applies.
2737    Idle,
2738    /// `interrupt_task` is runnable and exactly one other run is in flight;
2739    /// `parked` names that one task's id. Dispatch is withheld from
2740    /// everyone, including `interrupt_task` itself, until it has left
2741    /// flight - only then is `interrupt_task` let through.
2742    ///
2743    /// `parked` is a `Vec` rather than a bare id for symmetry with
2744    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
2745    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
2746    /// when exactly one run is in flight, so it is guaranteed to hold
2747    /// exactly one entry in practice - see that branch's own doc for why
2748    /// more than one is deliberately never attempted.
2749    Parking {
2750        parked: Vec<String>,
2751        interrupt_task: String,
2752    },
2753    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
2754    /// withheld from everyone until it leaves flight - merged, failed, held,
2755    /// it makes no difference - at which point the sequence moves to
2756    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
2757    /// going straight to `Idle` would hand `parked` back to ordinary
2758    /// priority-order dispatch, where a higher-priority task filed in the
2759    /// meantime could start ahead of it.
2760    Running {
2761        parked: Vec<String>,
2762        interrupt_task: String,
2763    },
2764    /// `interrupt_task` left flight; `parked` still names the one run this
2765    /// sequence owes a resume. Dispatch is withheld from everyone except
2766    /// that task - see [`interrupt_gate`] - so the resume this feature
2767    /// promises is never raced by, or run alongside, an unrelated candidate.
2768    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
2769    /// own doc on abandonment - the moment it is no longer runnable at all.
2770    Resuming { parked: Vec<String> },
2771}
2772
2773/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
2774/// and `runnable` are read-only snapshots of this tick's reality, and the
2775/// only side effect the caller still owes the world is asking whichever
2776/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
2777/// site.
2778///
2779/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
2780/// accepted rather than a narrower type because that is what [`poll`] already
2781/// has on hand from [`runnable`], and building a second, smaller list on
2782/// every tick just to satisfy this signature would cost more than it proves.
2783///
2784/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
2785/// back to a task they are waiting on no longer being [`runnable`] - held,
2786/// blocked, deleted, or finished by some other means entirely, all of which
2787/// an operator can do to a task sitting in the queue with no claim on it at
2788/// all, at any moment, interrupt sequence or not. Without this check the
2789/// sequence would wait forever for a dispatch that can never come, and
2790/// `interrupt_gate` would withhold every other task in the queue right along
2791/// with it - a single `magi task hold` on the wrong id turning into a
2792/// daemon that never dispatches anything again.
2793fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
2794    match state {
2795        Interrupt::Idle => {
2796            // Not just "something to interrupt": exactly one thing. More
2797            // than one run in flight only happens above the default
2798            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
2799            // one resume, never run alongside anything else" only because
2800            // it is only ever seeded with exactly one id - see
2801            // `Interrupt::Resuming`'s own doc on why releasing more than one
2802            // parked id back to ordinary dispatch cannot be made safe
2803            // against that same setting's own extra concurrency slots.
2804            // Waiting here for the herd to settle to one is the
2805            // simplification this feature's own constraints ask for rather
2806            // than a second concurrency model to reconcile with the first.
2807            if in_flight.len() != 1 {
2808                return Interrupt::Idle;
2809            }
2810            match runnable.iter().find(|t| t.interrupt) {
2811                Some(t) => Interrupt::Parking {
2812                    parked: in_flight.to_vec(),
2813                    interrupt_task: t.id.clone(),
2814                },
2815                None => Interrupt::Idle,
2816            }
2817        }
2818        Interrupt::Parking {
2819            parked,
2820            interrupt_task,
2821        } => {
2822            if in_flight.iter().any(|id| parked.contains(id)) {
2823                // Still waiting for what was in flight to actually stop.
2824                Interrupt::Parking {
2825                    parked,
2826                    interrupt_task,
2827                }
2828            } else if in_flight.contains(&interrupt_task) {
2829                Interrupt::Running {
2830                    parked,
2831                    interrupt_task,
2832                }
2833            } else if runnable.iter().any(|t| t.id == interrupt_task) {
2834                // The parked run(s) are gone, but the interrupt task has not
2835                // been dispatched yet on this tick - `interrupt_gate` is
2836                // what lets it through next.
2837                Interrupt::Parking {
2838                    parked,
2839                    interrupt_task,
2840                }
2841            } else {
2842                // The interrupt task itself is no longer runnable - see this
2843                // function's own doc on abandonment. The parked run(s) still
2844                // get their guaranteed resume; there is simply no interrupt
2845                // to run ahead of them any longer.
2846                Interrupt::Resuming { parked }
2847            }
2848        }
2849        Interrupt::Running {
2850            parked,
2851            interrupt_task,
2852        } => {
2853            if in_flight.contains(&interrupt_task) {
2854                Interrupt::Running {
2855                    parked,
2856                    interrupt_task,
2857                }
2858            } else {
2859                // The interrupt task's own run reached a terminal status,
2860                // whichever one - this is the *only* trigger that moves the
2861                // sequence on, driven straight off the same in-flight
2862                // bookkeeping `poll` already reaps every tick, not a second,
2863                // independent poll of anything.
2864                Interrupt::Resuming { parked }
2865            }
2866        }
2867        Interrupt::Resuming { parked } => {
2868            if in_flight.iter().any(|id| parked.contains(id)) {
2869                // One of the parked runs has been dispatched - the resume
2870                // this sequence owed is fulfilled. Whatever else is left in
2871                // `parked` (ordinarily nothing, at the default concurrency
2872                // of one) rejoins ordinary priority-order dispatch, same as
2873                // any other runnable task.
2874                Interrupt::Idle
2875            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
2876                Interrupt::Resuming { parked }
2877            } else {
2878                // Abandonment (see this function's own doc): nothing left in
2879                // `parked` is even runnable any longer.
2880                Interrupt::Idle
2881            }
2882        }
2883    }
2884}
2885
2886/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
2887/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
2888/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
2889/// indistinguishable from any other runnable task - exactly the "off does
2890/// nothing" this feature promises.
2891fn advance_interrupt_tick(
2892    enabled: bool,
2893    state: Interrupt,
2894    in_flight: &[String],
2895    runnable: &[Task],
2896) -> Interrupt {
2897    if !enabled {
2898        return Interrupt::Idle;
2899    }
2900    advance_interrupt(state, in_flight, runnable)
2901}
2902
2903/// Which of this tick's runnable candidates the interrupt sequence actually
2904/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
2905/// each half is assertable on its own: this is the half that keeps a
2906/// competition and an interrupt from ever running at the same moment.
2907fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
2908    match state {
2909        Interrupt::Idle => candidates,
2910        Interrupt::Parking {
2911            parked,
2912            interrupt_task,
2913        } => {
2914            if in_flight.iter().any(|id| parked.contains(id)) {
2915                Vec::new()
2916            } else {
2917                candidates
2918                    .into_iter()
2919                    .filter(|t| &t.id == interrupt_task)
2920                    .collect()
2921            }
2922        }
2923        Interrupt::Running { .. } => Vec::new(),
2924        // At most one: even if `parked` names more than one id (more than
2925        // one run was in flight when the sequence began, only possible
2926        // above the default `max_concurrent_runs = 1`), only the first match
2927        // is offered. Capping this to a single candidate - not merely to
2928        // `parked`'s own ids - is what makes "exactly one resume, never two
2929        // dispatched together" true regardless of how many ordinary slots
2930        // happen to be free this tick.
2931        Interrupt::Resuming { parked } => candidates
2932            .into_iter()
2933            .find(|t| parked.contains(&t.id))
2934            .into_iter()
2935            .collect(),
2936    }
2937}
2938
2939/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
2940/// bundled into one parameter so `poll`'s own signature stays readable -
2941/// see [`drive`]'s call site for where these are actually read.
2942struct DispatchLimits {
2943    /// How many *ordinary* candidates run at once. See
2944    /// [`crate::config::Daemon::max_concurrent_runs`].
2945    max_concurrent: usize,
2946    /// See [`crate::config::Daemon::pause_for_interrupts`].
2947    pause_for_interrupts: bool,
2948}
2949
2950/// Which semaphore, if any, dispatching a candidate should draw its permit
2951/// from.
2952///
2953/// Pure and separate from [`poll`]'s loop body for the same reason
2954/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
2955/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
2956/// exactly the policy this feature adds, and a policy only exercisable by
2957/// running the whole loop is a policy nobody checks.
2958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2959enum PermitKind {
2960    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
2961    /// Checked first - a task can be both a land resume and marked
2962    /// [`Task::urgent`], and the resume's own "must not queue behind
2963    /// anything" guarantee takes precedence.
2964    None,
2965    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
2966    /// (never in addition to trying) the ordinary pool. This is what lets
2967    /// an urgent task dispatch while every ordinary slot is already checked
2968    /// out, and what stops a second urgent task from opening a third run: it
2969    /// waits on this same one-slot semaphore rather than falling through to
2970    /// the ordinary one.
2971    Urgent,
2972    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
2973    /// above.
2974    Ordinary,
2975}
2976
2977/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
2978/// own boolean, already computed by the caller from [`land_resume_state`].
2979fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
2980    if priority {
2981        PermitKind::None
2982    } else if urgent {
2983        PermitKind::Urgent
2984    } else {
2985        PermitKind::Ordinary
2986    }
2987}
2988
2989struct DispatchClaim {
2990    task: Task,
2991    claim: crate::queue::Claim,
2992    permit: Option<tokio::sync::OwnedSemaphorePermit>,
2993}
2994
2995/// Claim and re-read before choosing a lane: a queue listing may predate an
2996/// urgent toggle. All unsuccessful paths release the claim without an attempt.
2997fn claim_dispatch(
2998    queue: &Queue,
2999    candidate: &Task,
3000    cooling_down: bool,
3001    ordinary: &Arc<tokio::sync::Semaphore>,
3002    urgent: &Arc<tokio::sync::Semaphore>,
3003) -> Option<DispatchClaim> {
3004    let Ok(claim) = queue.claim(&candidate.id) else {
3005        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3006        return None;
3007    };
3008    let task = match queue.get(&candidate.id) {
3009        Ok(t) if t.status.runnable() => t,
3010        Ok(_) => return None,
3011        Err(e) => {
3012            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3013            return None;
3014        }
3015    };
3016    let resume = land_resume_state(&task);
3017    if resume == LandResume::StillWaiting {
3018        return None;
3019    }
3020    let priority = resume == LandResume::Ready;
3021    if !priority && cooling_down {
3022        return None;
3023    }
3024    // Never borrow an ordinary slot when the single urgent slot is busy.
3025    // Keep scanning other candidates when either pool has no free slot.
3026    let permit = match permit_kind(priority, task.urgent) {
3027        PermitKind::None => None,
3028        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3029        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3030    };
3031    Some(DispatchClaim {
3032        task,
3033        claim,
3034        permit,
3035    })
3036}
3037
3038/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3039/// teardown and cannot skip the teardown on an early return.
3040///
3041/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3042/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3043/// land approval that has since been answered is dispatched outside that
3044/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3045/// the whole point of parking there is that it must not queue behind
3046/// whatever else the loop happens to be running, even at the default of one.
3047/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3048/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3049/// these exemptions is still subject to the interrupt gate below, urgent
3050/// included: a land-resume or urgent candidate is exactly as much "something
3051/// else running" as an ordinary one from the interrupt sequence's point of
3052/// view, and letting either slip through while a run is being parked, or
3053/// while the interrupt task itself has the floor, is precisely the second
3054/// run 75dd's own "at most one run, ever, at once" guarantee must never
3055/// allow - see [`Interrupt`]'s own doc.
3056async fn poll(
3057    opts: &Opts,
3058    queue: &Queue,
3059    status: &Arc<Mutex<Status>>,
3060    home: &Path,
3061    worktrees_root: &Path,
3062    stop: &Stop,
3063    limits: DispatchLimits,
3064) -> Result<()> {
3065    let DispatchLimits {
3066        max_concurrent,
3067        pause_for_interrupts,
3068    } = limits;
3069    // Only consulted by `once`, where a task that just failed is still
3070    // `runnable` and would otherwise be picked up again inside the same drain.
3071    // In the long-running mode a later poll retrying a failed task is the point,
3072    // and the attempt counter is what bounds it.
3073    let mut attempted: Vec<String> = Vec::new();
3074    let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
3075    // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
3076    // entirely separate from `sem`: an urgent candidate must dispatch
3077    // alongside whatever `sem` already has checked out, never by waiting for
3078    // one of those ordinary slots to free up and never by growing
3079    // `max_concurrent_runs` itself. Sized at one, not unbounded - see
3080    // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
3081    // first on this same slot rather than opening a third run.
3082    let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
3083    // A quota hit is a fact about the machine, not the task that happened to
3084    // surface it, and every other *ordinary* candidate is no less likely to
3085    // hit the same wall - see the warning below. A land-merge resume is
3086    // exempt: it is a human decision finishing, not a fresh competition, and
3087    // must not sit out a quota cooldown it did not cause.
3088    let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
3089    let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
3090    let mut conductor = Conductor::new();
3091    // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
3092    // a congested queue would otherwise starve of the fully-idle branch below.
3093    let mut cache_last_checked: Option<Timestamp> = None;
3094    // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
3095    let mut interrupt = Interrupt::Idle;
3096    // The `Pause` handed to each dispatched candidate's own `Runner` - see
3097    // `attempt`'s new parameter - kept here so the tick that decides to park
3098    // a run for an interrupt can reach that specific run's handle and no
3099    // other's. Pruned to whatever is still in flight at the top of every
3100    // tick, so a finished attempt's handle does not linger.
3101    let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
3102        std::collections::HashMap::new();
3103
3104    while !stop.stopped() {
3105        lock(status).polls += 1;
3106
3107        // Reap whatever finished since the last tick without blocking on
3108        // anything still running. `InFlightGuard` already released the slot
3109        // even if the spawned attempt panicked; this only surfaces that it
3110        // happened, since a panic swallowed here otherwise leaves no trace.
3111        while let Some(result) = inflight.try_join_next() {
3112            if let Err(e) = result {
3113                tracing::error!("a spawned attempt did not finish cleanly: {e}");
3114                notices::raise(Notice::error(
3115                    "loop:attempt",
3116                    "A queued attempt ended abnormally; check the task it was running.",
3117                ));
3118            }
3119        }
3120
3121        let swept = sweep_stale_claims(queue, STALE_CLAIM);
3122        if !swept.is_empty() {
3123            tracing::warn!(
3124                "swept {} stale claim(s) left behind by an earlier daemon: {}",
3125                swept.len(),
3126                swept.join(", ")
3127            );
3128        }
3129        // Capture stalled work before reclaiming it. A dead daemon's ordinary
3130        // lock is swept and reclaimed in this same poll, but the conductor
3131        // must still see that it was stranded rather than only its mechanical
3132        // terminal state.
3133        let now = Timestamp::now();
3134
3135        // No run this daemon spawned is mid-compile right now, whether or
3136        // not another candidate is about to start - see
3137        // `maybe_prune_cache_between_runs`'s own doc for why this cannot
3138        // wait for the queue to run dry.
3139        if !stop.busy_now() {
3140            maybe_prune_cache_between_runs(
3141                &opts.repo,
3142                opts,
3143                home,
3144                stop,
3145                &mut cache_last_checked,
3146                now,
3147            )
3148            .await;
3149        }
3150
3151        let stalled = stalled_tasks(queue, home, now);
3152        let stalled_ids: std::collections::BTreeSet<_> =
3153            stalled.iter().map(|task| task.id.clone()).collect();
3154        let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
3155        if !reclaimed.is_empty() {
3156            tracing::warn!(
3157                "reclaimed {} task(s) left `running` by a daemon that never \
3158                 recorded the outcome: {}",
3159                reclaimed.len(),
3160                reclaimed.join(", ")
3161            );
3162        }
3163        let abandoned_runs = reclaim_abandoned_runs(home, now);
3164        if !abandoned_runs.is_empty() {
3165            tracing::warn!(
3166                "failed {} run(s) left behind by a killed process, past every \
3167                 active seat's own timeout: {}",
3168                abandoned_runs.len(),
3169                abandoned_runs.join(", ")
3170            );
3171        }
3172
3173        // `home`, not `ask::Questions::open()`'s own process-global default:
3174        // `poll` is handed its home explicitly precisely so a test can point
3175        // it elsewhere, the same reason `Queue::at` and the status file path
3176        // are parameters rather than resolved here - see `drive`'s own doc.
3177        let questions = Questions::at(home.join("questions"));
3178
3179        // Deterministic: no model, run before the conductor sees anything so
3180        // its input reflects the queue's current, already-resolved state.
3181        repair_choice_offers(&questions);
3182        resolve_blockers(queue, &questions);
3183        apply_choice_actions(queue, &questions, home).await;
3184        triage::apply_answers(queue, &questions);
3185        reconcile_task_questions(queue, &questions);
3186        // Tell the chat a filed task or watched command has ended. Reconciled
3187        // here regardless of how it ended, and started only when no
3188        // upgrade is parking (the draft then waits for a manual resume).
3189        {
3190            let talks = crate::talk::Talks::at(home.join("talks"));
3191            crate::chat_notify::sweep(queue, &talks, home);
3192            crate::chat_watch::sweep(home, &talks);
3193            crate::chat_notify::start_turns(&talks, stop.parking(), &mut inflight);
3194        }
3195
3196        // The conductor gets one look per cycle, right before the loop takes
3197        // its next task, and only when there is something new to look at -
3198        // see `Conductor::worth_a_look`'s own doc for why "stalled is
3199        // non-empty" is the wrong test. Checked before `prepare` so an
3200        // unchanged cycle never pays for a synchronous config load.
3201        let finished: Vec<Task> = finished_tasks(queue)
3202            .into_iter()
3203            .filter(|task| !stalled_ids.contains(&task.id))
3204            // A parked run is waiting for this loop, not for a decision: the
3205            // conductor must not get to hold it or requeue it (a requeue
3206            // sets `fresh_start` and re-competes) before `attempt` resumes.
3207            .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
3208            .collect();
3209        let queued = queued_tasks(queue);
3210        // An empty queue has nothing to arrange. In particular, do not let
3211        // the conductor's initial snapshot cause synchronous config I/O
3212        // between the caller's stop notification and the idle wait below.
3213        if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3214            && conductor.worth_a_look(queue, &stalled, &finished)
3215        {
3216            match prepare(&opts.repo, opts) {
3217                Ok(cfg) => {
3218                    conductor
3219                        .maybe_run(
3220                            &cfg,
3221                            &opts.repo,
3222                            queue,
3223                            &questions,
3224                            home,
3225                            &queued,
3226                            &stalled,
3227                            &finished,
3228                            opts.max_attempts,
3229                        )
3230                        .await;
3231                }
3232                Err(e) => {
3233                    tracing::warn!("conductor: no config: {e:#}");
3234                    notices::raise(Notice::warn(
3235                        "loop:no-config",
3236                        "The loop could not read this repository's config, so held tasks are not being triaged.",
3237                    ));
3238                }
3239            }
3240        }
3241
3242        let candidates: Vec<Task> = runnable(queue)
3243            .into_iter()
3244            .filter(|t| !opts.once || !attempted.contains(&t.id))
3245            .collect();
3246
3247        // A task id only stays a key here while its attempt is genuinely in
3248        // flight; `status.current` is the same liveness fact `InFlightGuard`
3249        // maintains for the phone's own status file, so this piggybacks on
3250        // it rather than tracking a second copy of the same thing.
3251        let in_flight: Vec<String> = lock(status)
3252            .current
3253            .iter()
3254            .map(|c| c.task.clone())
3255            .collect();
3256        interrupt_pauses.retain(|id, _| in_flight.contains(id));
3257
3258        interrupt =
3259            advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
3260        if let Interrupt::Parking {
3261            parked,
3262            interrupt_task,
3263        } = &interrupt
3264        {
3265            let reason = format!(
3266                "task {} asked to run first",
3267                crate::run::short_of(interrupt_task)
3268            );
3269            for id in parked {
3270                if let Some(pause) = interrupt_pauses.get(id) {
3271                    pause.park_because(reason.clone());
3272                }
3273            }
3274        }
3275        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3276
3277        let cooling_down =
3278            lock(&quota_cooldown_until).is_some_and(|until| Timestamp::now() < until);
3279
3280        let mut started_any = false;
3281        for candidate in candidates {
3282            if stop.stopped() {
3283                break;
3284            }
3285
3286            let Some(DispatchClaim {
3287                mut task,
3288                claim,
3289                permit,
3290            }) = claim_dispatch(queue, &candidate, cooling_down, &sem, &urgent_sem)
3291            else {
3292                continue;
3293            };
3294
3295            let task_id = task.id.clone();
3296            attempted.push(task_id.clone());
3297            lock(status).idle = false;
3298            // A stop asked for from here on is "finishing", not "stopped": the
3299            // run gets to reach a terminal status before the loop returns.
3300            stop.enter();
3301            started_any = true;
3302
3303            // A fresh, unshared handle - never `stop.pause()` - so parking
3304            // this run for an interrupt cannot leak into any other run this
3305            // loop ever drives. See `Pause`'s own doc.
3306            let run_pause = crate::graph::Pause::new();
3307            interrupt_pauses.insert(task_id.clone(), run_pause.clone());
3308
3309            let opts = opts.clone();
3310            let queue = queue.clone();
3311            let status = Arc::clone(status);
3312            let stop = stop.clone();
3313            let quota_cooldown_until = Arc::clone(&quota_cooldown_until);
3314            inflight.spawn(async move {
3315                // Held for the whole attempt: dropping either at the end of
3316                // this task is what releases the claim and, for an ordinary
3317                // candidate, frees its concurrency slot back to the loop.
3318                let _claim = claim;
3319                let _permit = permit;
3320                // See `InFlightGuard`: this must survive a panic inside `attempt`.
3321                let _inflight = InFlightGuard {
3322                    status: &status,
3323                    stop: &stop,
3324                    task_id: &task_id,
3325                };
3326                let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
3327                lock(&status).completed += 1;
3328                // A quota loss is a fact about the machine, not this task, and
3329                // the next ordinary candidate the loop offers is no less
3330                // likely to hit the same wall: without a cooldown here a
3331                // whole backlog can be run - and failed - in the seconds it
3332                // takes each attempt to notice the CLI is out of quota.
3333                let now = Timestamp::now();
3334                if let Some(until) = cooldown_until(&quota, now) {
3335                    let wait = until.as_second() - now.as_second();
3336                    *lock(&quota_cooldown_until) = Some(until);
3337                    let hint = quota
3338                        .iter()
3339                        .find(|q| q.reset.is_some())
3340                        .and_then(|q| q.reset.as_deref());
3341                    match hint {
3342                        Some(h) => tracing::warn!(
3343                            "quota hit; waiting {wait}s before taking another ordinary task \
3344                             (CLI reported reset: {h})"
3345                        ),
3346                        None => tracing::warn!(
3347                            "quota hit; waiting {wait}s before taking another ordinary task \
3348                             (no reset hint reported)"
3349                        ),
3350                    }
3351                }
3352            });
3353        }
3354
3355        if started_any {
3356            continue;
3357        }
3358
3359        if stop.busy_now() {
3360            // Something started on an earlier tick is still running. Recheck
3361            // soon rather than sleeping out the whole poll interval - a freed
3362            // slot, or a land approval answered mid-run, must not sit idle
3363            // for it.
3364            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3365            continue;
3366        }
3367
3368        // Truly idle: nothing new to start and nothing still running.
3369        lock(status).idle = true;
3370        if opts.once {
3371            // A one-shot drain must perform the same post-work cleanup as a
3372            // daemon that reached a normal idle interval. The startup pass
3373            // cannot see runs or cache files produced by this drain.
3374            janitor(&opts.repo, opts, home, worktrees_root).await;
3375            resweep_superseded_attempts(queue, home);
3376            triage_held(queue, home, opts).await;
3377            break;
3378        }
3379        stop.idle(opts.poll).await;
3380        if stop.stopped() {
3381            continue;
3382        }
3383        // Housekeeping only after a full quiet interval. Running it before
3384        // the first idle wait can block the executor while an operator's
3385        // stop request is waiting to be scheduled, defeating Stop's retained
3386        // wake permit. No run can start while this branch is active, so the
3387        // janitor still never races an in-flight compile.
3388        janitor(&opts.repo, opts, home, worktrees_root).await;
3389        resweep_superseded_attempts(queue, home);
3390        triage_held(queue, home, opts).await;
3391    }
3392
3393    // Never return while a run is still in flight, whichever way the loop
3394    // above exited: a stop only sets a flag - see `serve_until` - and
3395    // returning here while `inflight` still holds spawned work would abandon
3396    // it exactly as a mid-node kill would.
3397    while let Some(result) = inflight.join_next().await {
3398        if let Err(e) = result {
3399            tracing::error!("a spawned attempt did not finish cleanly: {e}");
3400            notices::raise(Notice::error(
3401                "loop:attempt",
3402                "A queued attempt ended abnormally; check the task it was running.",
3403            ));
3404        }
3405    }
3406    Ok(())
3407}
3408
3409/// Run one claimed task to a terminal status and record the outcome.
3410///
3411/// Every transition is flushed to the queue as it happens, so the state on disk
3412/// is what actually occurred rather than what this process still intends to
3413/// write.
3414async fn attempt(
3415    opts: &Opts,
3416    queue: &Queue,
3417    status: &Arc<Mutex<Status>>,
3418    stop: &Stop,
3419    interrupt_pause: crate::graph::Pause,
3420    task: &mut Task,
3421) -> Vec<QuotaLoss> {
3422    let repo = repo_for(task, &opts.repo);
3423    tracing::info!(
3424        "task {} — {} (repo {})",
3425        task.short(),
3426        task.title,
3427        repo.display()
3428    );
3429
3430    // A stop spends no agent resources and uses the saved landing owner.
3431    // Current roster edits, missing attachments or a failed config fetch must
3432    // never turn it into a new implementation, or prevent a PR from closing.
3433    if let Some(previous) = task.runs.last().and_then(|id| RunState::load(id).ok())
3434        && previous
3435            .merge_decision
3436            .as_ref()
3437            .is_some_and(|decision| !decision.closed)
3438        && previous.status != RunStatus::Landing
3439        && !crate::merge_decision::resumable_hold(&previous)
3440    {
3441        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)));
3442        record(queue, task);
3443        return Vec::new();
3444    }
3445    let stop_owner = task
3446        .runs
3447        .last()
3448        .and_then(|id| RunState::load(id).ok())
3449        .filter(|state| {
3450            crate::merge_decision::resumable_hold(state)
3451                || state.status == RunStatus::Landing
3452                    && state.land_approval.as_ref().is_some_and(|binding| {
3453                        Questions::open().get(&binding.question).is_ok_and(|q| {
3454                            q.run == state.id
3455                                && q.resolution()
3456                                    .as_deref()
3457                                    .is_some_and(crate::merge_decision::stops)
3458                        })
3459                    })
3460        });
3461    if let Some(owner) = stop_owner {
3462        let mut runner = match Runner::resume(&owner.id) {
3463            Ok(runner) => runner,
3464            Err(e) => {
3465                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
3466                record(queue, task);
3467                return Vec::new();
3468            }
3469        };
3470        runner.on_pause(stop.pause());
3471        runner.watch_interrupt(interrupt_pause);
3472        let quota_before = runner.state.quota.clone();
3473        task.start(owner.id.clone());
3474        record(queue, task);
3475        lock(status).current.push(Current {
3476            task: task.id.clone(),
3477            run: owner.id,
3478        });
3479        runner.state.next_pass_task_entry = true;
3480        let result = runner.execute().await;
3481        return finish_attempt(
3482            opts.max_attempts,
3483            queue,
3484            task,
3485            &runner.state,
3486            &quota_before,
3487            result,
3488        );
3489    }
3490
3491    let unfinished = (!task.fresh_start)
3492        .then(|| unfinished_run(&task.runs, task.short()))
3493        .flatten()
3494        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
3495    let previous = task.runs.last().and_then(|id| RunState::load(id).ok());
3496    let saved_recovery = previous.as_ref().filter(|run| {
3497        task.replacement.is_none()
3498            && task.pr_recovery.as_ref().is_some_and(|selected| {
3499                selected.check_task(&task.id, &task.instruction).is_ok()
3500                    && selected_starter(selected, Some(run), unfinished.as_deref())
3501                        == Starter::Resume(run.id.clone())
3502            })
3503    });
3504
3505    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
3506    // failure here is the network's or the operator's, not the task's: hold
3507    // without spending an attempt, never fall back to a possibly stale copy.
3508    let explicit = match &task.overrides {
3509        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
3510        Some(_) => opts.config.as_deref(),
3511        None => opts.config.as_deref(),
3512    };
3513    let (mut config, layers) = if let Some(run) = saved_recovery {
3514        // A matching resume owns its resolved configuration and evidence;
3515        // current layers and inherited overrides only configure new work.
3516        let mut saved = run.clone();
3517        if let Err(e) = saved.configure_recovery_resume() {
3518            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
3519            record(queue, task);
3520            return Vec::new();
3521        }
3522        (saved.config, Vec::new())
3523    } else {
3524        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
3525            Ok(loaded) => loaded,
3526            Err(e) => {
3527                let reason = format!("[config] {e:#}");
3528                record_config_failure(task, &e);
3529                task.last_error = Some(reason.clone());
3530                task.hold_machine(Some(reason));
3531                record(queue, task);
3532                return Vec::new();
3533            }
3534        };
3535        if let Err(e) = apply_options(&mut config, opts, task) {
3536            task.hold_manual(Some(format!(
3537                "[config] {e:#}; correct the merge override before releasing the task"
3538            )));
3539            record(queue, task);
3540            return Vec::new();
3541        }
3542        if let Some(selected) = &task.pr_recovery
3543            && let Err(e) = selected.configure(&mut config)
3544        {
3545            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
3546            record(queue, task);
3547            return Vec::new();
3548        }
3549        (config, layers)
3550    };
3551    let config_evidence = crate::pr_recovery::ConfigEvidence {
3552        layers,
3553        overrides: task.overrides.clone(),
3554        daemon_merge: task
3555            .overrides
3556            .as_ref()
3557            .is_none_or(|o| o.inherit_daemon_options)
3558            .then(|| opts.merge.clone())
3559            .flatten(),
3560    };
3561    apply_task_implementers(&mut config, task);
3562    if let Some(replacement) = &task.replacement {
3563        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
3564            old.liveness(false) == Liveness::Dead
3565                && old.merge_decision.as_ref().is_some_and(|d| {
3566                    d.closed
3567                        && d.question == replacement.question
3568                        && d.replacement_run.as_ref().is_none_or(|run| {
3569                            task.runs.last() == Some(run)
3570                                && RunState::load(run).is_ok_and(|current| {
3571                                    current.replaces.as_ref().is_some_and(|pin| {
3572                                        pin.question == replacement.question
3573                                            && pin.agent == replacement.agent
3574                                    })
3575                                })
3576                        })
3577                })
3578        });
3579        if !safe {
3580            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()));
3581            record(queue, task);
3582            return Vec::new();
3583        }
3584        match config.agent(&replacement.agent) {
3585            Ok(agent) if crate::agent::installed(agent) => {}
3586            _ => {
3587                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)));
3588                record(queue, task);
3589                return Vec::new();
3590            }
3591        }
3592        config.graph.implementers = 1;
3593        config.graph.land_approval = true;
3594        config.merge.mode = MergeMode::Pr;
3595        config.graph.selected_implementer = Some(replacement.agent.clone());
3596    }
3597    let p = phrases(&config.graph.language);
3598    let start_failed = p.could_not_start;
3599
3600    // The free-space gate, checked *before* anything is minted: a task that
3601    // waits out a full disk costs nothing yet, and must not spend an attempt
3602    // or start a run the machine cannot finish. Held tasks stay in the list
3603    // for the human to see, and `magi task release` re-queues them when space
3604    // comes back - the same recovery as any other hold. A volume whose free
3605    // space cannot be measured closes the gate too: starting a run blind on a
3606    // disk that may be full is how the machine ends up with 6.7 GB free.
3607    if let Some(reason) = disk_gate(&repo, &config) {
3608        task.notice_cause("disk-space", None, None);
3609        task.last_error = Some(reason.clone());
3610        task.hold_machine(Some(reason.clone()));
3611        record(queue, task);
3612        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
3613        // Stable wording - the free-space figures live in the task's hold
3614        // reason, and changing numbers would relight the bell every poll.
3615        notices::raise(
3616            Notice::warn(
3617                &format!("disk:{}", repo.display()),
3618                "A task was held for want of free disk space; free some, then release it from the queue.",
3619            )
3620            .link(Link::Task {
3621                id: task.id.clone(),
3622            }),
3623        );
3624        return Vec::new();
3625    }
3626
3627    // A resumable run of this task is carried on, never re-competed. The
3628    // candidates are built and paid for, and a fresh competition races a
3629    // second implementation against them.
3630    //
3631    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
3632    // started 3cbf on the same task a moment later, duplicating two and a
3633    // half hours of agent work. Then b25f stalled on a judge that timed out
3634    // and one that answered with no JSON - `quota: 0`, so nothing the machine
3635    // was to blame for - and 4043 started **one second** later, buying three
3636    // fresh implementations to reach the same panel. `RunStatus::resumable`
3637    // rather than `!done()` is what catches the second case: a stall is
3638    // terminal, and its cheap recovery re-asks only the absent seats.
3639    //
3640    // A load failure is warned about rather than silently read as "not
3641    // resumable": the alternative is exactly what let a schema mismatch on
3642    // run `eba2` fall through to a full re-competition with nobody told why.
3643    // `crate::conduct` is what actually offers a better answer than
3644    // `Runner::start` here (see `Recovery::Review`), once this task's next
3645    // failure shows it up as `held`/`failed` with the run state unreadable.
3646    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
3647    // branch survived, and this reopens exactly that branch as a
3648    // review-only pass rather than resuming or competing again. Consumed
3649    // (cleared) here whichever way this goes, so it never outlives this one
3650    // attempt - see `queue::Task::review_branch`.
3651    let review_branch = take_review_branch(task, previous.as_ref());
3652    let branch_exists = match &review_branch {
3653        Some(branch) => crate::git::branch_exists(&repo, branch)
3654            .await
3655            .unwrap_or(false),
3656        None => false,
3657    };
3658    // An explicit `magi review <branch>` is reviewed whatever happens to the
3659    // branch unless an explicit implementer change requires fresh work. An
3660    // unfinished run of the same task still wins, so a retry resumes.
3661    let proposed = match (&review_branch, &unfinished, &task.review_of) {
3662        (None, None, Some(branch)) => Starter::Review(branch.clone()),
3663        _ => choose_starter(
3664            review_branch.as_deref(),
3665            branch_exists,
3666            unfinished.as_deref(),
3667        ),
3668    };
3669    let retry_selected = task.replacement.is_some()
3670        && task.resumption.is_some()
3671        && !task.fresh_start
3672        && previous.as_ref().is_some_and(|run| {
3673            run.replaces.is_some()
3674                && ((run.status == RunStatus::Failed && run.viable().is_empty())
3675                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
3676        });
3677    let stop_pin = task
3678        .resume_override
3679        .as_ref()
3680        .filter(|pin| {
3681            Questions::open().get(&pin.question_id).is_ok_and(|q| {
3682                q.node == land::APPROVAL_NODE
3683                    && q.resolution()
3684                        .as_deref()
3685                        .is_some_and(crate::merge_decision::stops)
3686            })
3687        })
3688        .and_then(|pin| pin.pinned_run.clone());
3689    let starter = if let Some(run) = stop_pin {
3690        // Stop actions resume their exact owner even after seat-count edits;
3691        // they must never fall through to implementation or a takeover.
3692        Starter::Resume(run)
3693    } else if retry_selected {
3694        Starter::Resume(previous.as_ref().unwrap().id.clone())
3695    } else if let Some(selected) = &task.pr_recovery {
3696        if selected.check_task(&task.id, &task.instruction).is_ok() {
3697            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
3698        } else {
3699            Starter::Review(selected.branch.clone())
3700        }
3701    } else {
3702        starter_with_implementers(task, previous.as_ref(), proposed)
3703    };
3704    // An explicit resume pin must never degrade into a new competition or
3705    // takeover, including when its run stops being eligible after the answer.
3706    if let Some(pin) = &task.resume_override
3707        && let Some(run) = &pin.pinned_run
3708        && starter != Starter::Resume(run.clone())
3709    {
3710        let run = run.clone();
3711        task.notice_cause("resume-owner", Some(&run), None);
3712        task.hold_machine(Some(format!(
3713            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
3714            task.id
3715        )));
3716        record(queue, task);
3717        return Vec::new();
3718    }
3719    if task.replacement.is_some()
3720        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
3721        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
3722    {
3723        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()));
3724        record(queue, task);
3725        return Vec::new();
3726    }
3727    // Absolute paths of the files the task was filed with, re-read from the
3728    // task now so a file attached while it was held reaches a resumed run
3729    // too. A stored name whose file has gone is an error before any agent is
3730    // paid for, never a silent omission the implementer cannot notice.
3731    let attachments = match task_attachments(queue, task) {
3732        Ok(a) => a,
3733        Err(e) => {
3734            task.attempts += 1;
3735            task.fail_startup_target(
3736                "startup-attachments",
3737                e.name.clone(),
3738                format!("{start_failed}{e:#}"),
3739                opts.max_attempts,
3740            );
3741            record(queue, task);
3742            return Vec::new();
3743        }
3744    };
3745    let startup_pause = stop.pause();
3746    let startup_interrupt = interrupt_pause.clone();
3747    let wait = crate::repo_lock::WaitPolicy::new(
3748        Duration::from_secs(config.graph.timeout_resource_wait),
3749        move || startup_pause.parked() || startup_interrupt.parked(),
3750    );
3751    let started = wait.scope(async { match &starter {
3752        Starter::Review(_) if task.pr_recovery.is_some() => {
3753            let selected = task.pr_recovery.clone().expect("selected recovery");
3754            match selected.check_task(&task.id, &task.instruction) {
3755                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
3756                    .await
3757                    .map(|mut r| {
3758                        r.state.attachments = attachments.clone();
3759                        r
3760                    }),
3761                Err(e) => Err(e),
3762            }
3763        }
3764        Starter::Review(branch) => {
3765            tracing::info!(
3766                "task {} reopens `{branch}` as a review-only pass",
3767                task.short()
3768            );
3769            // Every earlier attempt is superseded by the one being minted
3770            // now, so a branch one of them still holds may be taken over.
3771            let takeover = crate::handover::Takeover {
3772                earlier: task.earlier_attempts().to_vec(),
3773                home: crate::run::home(),
3774                choice: take_divergence_answer(branch, &config.merge.remote, task),
3775                task_instruction: Some(instruction_for(task)),
3776            };
3777            Runner::review_taking_over(
3778                &repo,
3779                branch,
3780                config,
3781                Some(takeover),
3782                crate::run::Origin::queue(&task.id),
3783            )
3784            .await
3785        }
3786        Starter::Resume(id) => {
3787            tracing::info!("resuming run {id} rather than competing again");
3788            Runner::resume(id).and_then(|mut r| {
3789                if retry_selected {
3790                    // The explicit queue release retries this same pinned
3791                    // implementation, preserving the attempt and worktrees.
3792                    for candidate in &mut r.state.candidates {
3793                        candidate.failed = None;
3794                        candidate.empty = false;
3795                        candidate.commits = 0;
3796                    }
3797                    r.state.status = RunStatus::Implementing;
3798                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
3799                }
3800                if r.state.prep_failure.is_some() {
3801                    let approval = task
3802                        .resumption
3803                        .as_ref()
3804                        .context("preparation retry requires an explicit task release")?;
3805                    r.retry_preparation(approval.at)?;
3806                }
3807                if let Some(instruction) =
3808                    prepare_instruction(&starter, Some(&r.state.instruction), task)
3809                {
3810                    r.state.instruction = instruction;
3811                }
3812                r.state.attachments = attachments.clone();
3813                if task.replacement.is_some() {
3814                    r.state.config.merge.mode = MergeMode::Pr;
3815                    r.state.config.graph.land_approval = true;
3816                }
3817                // Replacements publish a new PR and ask again. Selected PR
3818                // recoveries keep their saved disposition; ordinary runs can
3819                // retain the task's merge override.
3820                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
3821                    .overrides
3822                    .as_ref()
3823                    .and_then(|o| o.merge.as_deref())
3824                    .and_then(|m| merge_mode(m).ok())
3825                {
3826                    r.state.config.merge.mode = mode;
3827                }
3828                Ok(r)
3829            })
3830        }
3831        Starter::Start => {
3832            if let Some(branch) = &review_branch {
3833                tracing::warn!(
3834                    "conductor chose review for task {} but branch `{branch}` no longer \
3835                     exists; requeuing as a fresh competition instead",
3836                    task.short()
3837                );
3838            }
3839            let instruction = prepare_instruction(&starter, None, task)
3840                .unwrap_or_else(|| task.instruction.clone());
3841            Runner::start_naming(
3842                &repo,
3843                instruction,
3844                &task.title,
3845                config,
3846                crate::run::Origin::queue(&task.id),
3847            )
3848            .await
3849            .map(|mut r| {
3850                r.state.attachments = attachments.clone();
3851                r
3852            })
3853        }
3854    }}).await;
3855    let mut runner = match started {
3856        Ok(r) => r,
3857        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
3858            task.last_error = Some(e.to_string());
3859            if stop.parking() || interrupt_pause.parked() {
3860                let attempts = task.attempts;
3861                task.park(e.to_string());
3862                // Startup has not spent an attempt to refund.
3863                task.attempts = attempts;
3864            } else {
3865                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
3866            }
3867            record(queue, task);
3868            return Vec::new();
3869        }
3870        // A branch an earlier attempt still holds and magi will not release
3871        // by itself is the operator's call, not a failed attempt: hold the
3872        // task with the reason, spend nothing, and say so on the bell.
3873        Err(e) if task.pr_recovery.is_some() => {
3874            task.startup_notice_cause("startup-public-head");
3875            task.attempts += 1;
3876            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
3877                task.link_run(&partial.run);
3878                task.record_pass(&partial.run, 0, task.attempts, None);
3879            }
3880            task.last_error = Some(format!("{start_failed}{e:#}"));
3881            task.hold_unrequested_retry(Some(format!(
3882                "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."
3883            )));
3884            record(queue, task);
3885            return Vec::new();
3886        }
3887        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
3888            let detail = match e.downcast_ref::<crate::handover::Refused>() {
3889                Some(r) => (p.handover_refused)(r),
3890                None => format!("{e:#}"),
3891            };
3892            task.startup_notice_cause("startup-handover");
3893            let reason = format!("{start_failed}{detail}");
3894            task.last_error = Some(reason.clone());
3895            // Consumed above by `take`; keep it so the released task retries
3896            // as a review of this same branch.
3897            let branch = match &starter {
3898                Starter::Review(branch) => Some(branch.clone()),
3899                _ => None,
3900            };
3901            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
3902            // one page; the guidance rides in the reason, fixed per state so a
3903            // re-put never changes the wording and relights it.
3904            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
3905            record(queue, task);
3906            tracing::warn!(
3907                "holding {} for a branch it cannot take over: {e:#}",
3908                task.short()
3909            );
3910            return Vec::new();
3911        }
3912        // A branch that differs between here and the remote in ways magi
3913        // cannot prove are the same change is a decision for the owner, not a
3914        // failed attempt: ask with both sides laid out, spend no attempt, and
3915        // let the answer requeue the task.
3916        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
3917            let d = e
3918                .downcast_ref::<crate::reconcile::Diverged>()
3919                .expect("checked by the guard");
3920            let mut q = ask::Question::new(
3921                task.id.clone(),
3922                crate::reconcile::NODE.to_owned(),
3923                crate::reconcile::SEAT.to_owned(),
3924                d.summary(),
3925                d.detail(),
3926                d.choices(),
3927            );
3928            match Questions::open().put(&mut q) {
3929                Ok(()) => {
3930                    task.last_error = Some(format!("{e:#}"));
3931                    // Consumed above by `take`; the answer has to reach a review
3932                    // of this same branch, so keep pointing the task at it.
3933                    task.review_branch = Some(d.branch.clone());
3934                    task.review_instruction = Some(task.instruction.clone());
3935                    task.block(vec![q.id.clone()], Some(d.summary()));
3936                }
3937                Err(put) => {
3938                    tracing::warn!("could not file the divergence question: {put:#}");
3939                    task.attempts += 1;
3940                    task.fail_startup(
3941                        "startup-question-store",
3942                        format!("{start_failed}{e:#}"),
3943                        opts.max_attempts,
3944                    );
3945                }
3946            }
3947            record(queue, task);
3948            return Vec::new();
3949        }
3950        Err(e) => {
3951            // The answer was stale and nothing was applied: keep pointing at
3952            // the branch so the next attempt asks again against its new tips.
3953            // Nothing went wrong with the task, so no attempt is spent: a
3954            // budget one short of its limit must not hold it instead of
3955            // letting the question be asked again.
3956            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
3957                && let Starter::Review(branch) = &starter
3958            {
3959                task.review_branch = Some(branch.clone());
3960                task.review_instruction = Some(task.instruction.clone());
3961                task.last_error = Some(format!("{start_failed}{e:#}"));
3962                task.status = crate::queue::TaskStatus::Failed;
3963                record(queue, task);
3964                return Vec::new();
3965            }
3966            task.attempts += 1;
3967            task.last_error = Some(format!("{start_failed}{e:#}"));
3968            task.startup_notice_cause("startup-source");
3969            task.hold_unrequested_retry(Some(format!(
3970                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
3971            )));
3972            record(queue, task);
3973            return Vec::new();
3974        }
3975    };
3976    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
3977        runner.state.recovery_config = Some(config_evidence);
3978    }
3979    if let Some(replacement) = &task.replacement {
3980        if matches!(starter, Starter::Start) {
3981            runner.state.instruction.push_str(&format!(
3982                "\n\n# Replacement review context\n{}",
3983                replacement.context
3984            ));
3985        }
3986        runner.state.replaces = Some(replacement.clone());
3987        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
3988        if let Ok(mut old) = RunState::load(&replacement.run)
3989            && let Some(d) = &mut old.merge_decision
3990        {
3991            d.replacement_run = Some(runner.state.id.clone());
3992            old.event(
3993                "replacement",
3994                format!(
3995                    "replacement run {} owns the next attempt; old PR remains closed",
3996                    runner.state.id
3997                ),
3998            );
3999            if let Err(e) = old.save() {
4000                task.hold_manual(Some(format!(
4001                    "Could not link replacement history: {e}; no agents dispatched"
4002                )));
4003                record(queue, task);
4004                return Vec::new();
4005            }
4006        }
4007    }
4008    runner.state.task_instruction = Some(task.instruction.clone());
4009    // The follow-up depth is fixed now, while the task certainly exists:
4010    // deleting it later must not reset the cap (`crate::followup`).
4011    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4012    if runner.state.origin_chat.is_none() {
4013        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4014    }
4015    // A stop that means "park" reaches the graph through this handle.
4016    runner.on_pause(stop.pause());
4017    // `poll`'s interrupt scheduler reaches this one run - and no other -
4018    // through this handle. See `Pause`'s own doc for why these are never
4019    // the same one.
4020    runner.watch_interrupt(interrupt_pause);
4021
4022    // `start` has minted the run, so the task can now point at it. Persisting
4023    // `Running` before `execute` is what makes a crash mid-run legible.
4024    let run = runner.state.id.clone();
4025    task.start(run.clone());
4026    record(queue, task);
4027    lock(status).current.push(Current {
4028        task: task.id.clone(),
4029        run,
4030    });
4031
4032    // `RunState::quota` is the run's whole history across every resume, so
4033    // only what this execution added may arm the cooldown or earn a refund.
4034    let quota_before = runner.state.quota.clone();
4035    runner.state.next_pass_task_entry = true;
4036    let result = runner.execute().await;
4037    finish_attempt(
4038        opts.max_attempts,
4039        queue,
4040        task,
4041        &runner.state,
4042        &quota_before,
4043        result,
4044    )
4045}
4046
4047/// Settle `task` after its run executed: the verdict, the diagnosis, the
4048/// supersession of earlier attempts and the save. Shared by the loop and by
4049/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4050/// Returns the quota losses this execution added to the run.
4051pub fn finish_attempt(
4052    max_attempts: usize,
4053    queue: &Queue,
4054    task: &mut Task,
4055    state: &RunState,
4056    quota_before: &[QuotaLoss],
4057    result: Result<()>,
4058) -> Vec<QuotaLoss> {
4059    let detail = match result {
4060        Ok(()) => describe(state),
4061        Err(e) => format!("{e:#}"),
4062    };
4063    let fresh = losses_this_attempt(quota_before, &state.quota);
4064    let verdict = Verdict {
4065        status: state.status,
4066        // A run that opened a pull request handed its work over, whatever the
4067        // gate then decided about merging it.
4068        left_pr: state.pr.is_some(),
4069        // Only a rate limit earns the task its attempt back - and only one
4070        // suffered now: a refund justified by a previous session's loss is
4071        // the same mistake as re-arming the cooldown from it. A stalled run
4072        // resumed without hitting quota again therefore spends its attempt,
4073        // like any other failure of the task's own.
4074        quota_hit: !fresh.is_empty(),
4075        // A run that parked was asked to stop; that is not a failure and must
4076        // not spend an attempt, or replacing the binary a few times would
4077        // exhaust a task's budget without an agent ever misbehaving.
4078        parked: state.parked,
4079        // A quota loss that left nothing viable is the same machine fact as a
4080        // `Stalled` quota loss; see `settle`'s doc table.
4081        no_viable_candidates: state.viable().is_empty(),
4082    };
4083    if let Some(replacement) = &state.replaces
4084        && let Some(pr) = &state.pr
4085        && let Ok(mut old) = RunState::load(&replacement.run)
4086        && let Some(d) = &mut old.merge_decision
4087    {
4088        d.replacement_pr = Some(pr.url.clone());
4089        let _ = old.save();
4090    }
4091    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4092    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4093        task.hold_unrequested_retry(Some(format!(
4094            "Candidate setup failed: {detail}. Select a complete implementation with `magi task recover-pr`, or correct the referenced source before explicitly releasing the task."
4095        )));
4096    }
4097    if task.status == TaskStatus::Done {
4098        supersede_prior_runs(task, &crate::run::home());
4099    }
4100    record(queue, task);
4101    tracing::info!(
4102        "task {} is {} after run {} ({})",
4103        task.short(),
4104        task.status.as_str(),
4105        state.short(),
4106        label(state.status)
4107    );
4108    fresh
4109}
4110
4111/// A task a hand-started run leaves runnable (failed with attempts to spare,
4112/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4113/// later must not spend agent calls on it. `magi task release` retries.
4114pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4115    // A run parked on the owner's word about a withheld PR title/body is not a
4116    // failure nobody asked to retry: it resumes (answer, or the neutral text on
4117    // the deadline) the moment a loop serves the queue, via `land_resume_state`.
4118    // Holding it would keep it from ever being a candidate.
4119    let waits_on_owner = withheld_text_wait(task).is_some();
4120    if task.status.runnable()
4121        && !waits_on_owner
4122        && !(task.fresh_start && task.replacement.is_some())
4123    {
4124        let why = task.last_error.clone().map_or_else(
4125            || "the run did not finish".to_owned(),
4126            |e| format!("the run did not finish: {e}"),
4127        );
4128        task.hold_unrequested_retry(Some(format!(
4129            "{why}. It was started by hand, so it is not retried \
4130             automatically; `magi task release` retries it."
4131        )));
4132        record(queue, task);
4133    }
4134}
4135
4136/// Whether an attempt at a task whose newest run is `run` would resume that
4137/// run rather than start a fresh competition. `magi run --resume` hands a run
4138/// to a live loop only when this holds.
4139#[must_use]
4140pub fn loop_would_resume(run: &str) -> bool {
4141    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4142}
4143
4144/// A loop in another process that is alive right now: a fresh heartbeat in
4145/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4146/// carries the pid it published (`None` inside when it published none - a
4147/// fresh heartbeat is still evidence of a live loop).
4148///
4149/// The one judgement of "is somebody else serving this queue", shared by the
4150/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4151/// deciding whether to hand a task to the loop. A claim file proves nothing
4152/// here: whether a claim succeeds says nothing about whether its owner lives.
4153#[must_use]
4154pub fn foreign_loop(
4155    reading: Option<&Reading>,
4156    now: Timestamp,
4157    own_pid: u32,
4158) -> Option<Option<u32>> {
4159    let reading = reading.filter(|r| r.running(now))?;
4160    match reading.pid {
4161        Some(pid) if pid == own_pid => None,
4162        pid => Some(pid),
4163    }
4164}
4165
4166/// Run one task this process has claimed, in this process, through exactly the
4167/// attempt a daemon would make: the same starter choice (start, resume,
4168/// review), the same `Task::start` / `settle` transitions, attempt counting,
4169/// quota refund and parking. No second dispatcher - `magi run` and `magi
4170/// review` call this when no daemon is alive.
4171///
4172/// The caller holds the [`Queue::claim`] for the whole call, which is what
4173/// keeps a daemon that starts meanwhile from taking the task.
4174///
4175/// The one deliberate difference from the loop: a task the attempt leaves
4176/// runnable (failed with attempts to spare, or requeued) is **held** instead.
4177/// Nobody asked for a retry, and a daemon starting later must not spend agent
4178/// calls re-running a hand-started task behind the operator's back;
4179/// `magi task release` is the explicit retry.
4180pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4181    let status = Arc::new(Mutex::new(Status::new()));
4182    let stop = Stop::new();
4183    attempt(
4184        opts,
4185        queue,
4186        &status,
4187        &stop,
4188        crate::graph::Pause::new(),
4189        task,
4190    )
4191    .await;
4192    // A run parked on the owner's word about a withheld PR title/body has no
4193    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
4194    // here with the claim still held, and resume once the question is settled
4195    // (answered, or abandoned at its deadline -> the neutral text).
4196    // A rejected reply files one more question (the gate asks at most twice),
4197    // so after a resume the run may be waiting again: keep going, with a fresh
4198    // limit for the new question. `resumes` bounds it even if a resume parks
4199    // without asking anything new.
4200    let mut resumes = 0;
4201    while resumes < MAX_WITHHELD_RESUMES {
4202        let Some(timeout) = withheld_text_wait(task) else {
4203            break;
4204        };
4205        eprintln!(
4206            "waiting for the owner's answer on a withheld pull request text \
4207             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4208        );
4209        // The deadline abandons the question itself; the extra margin only
4210        // covers an abandon that could not be saved.
4211        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4212        let ready = loop {
4213            match land_resume_state(task) {
4214                LandResume::StillWaiting if std::time::Instant::now() < limit => {
4215                    tokio::time::sleep(WITHHELD_POLL).await;
4216                }
4217                LandResume::Ready => break true,
4218                _ => break false,
4219            }
4220        };
4221        if !ready {
4222            break;
4223        }
4224        resumes += 1;
4225        attempt(
4226            opts,
4227            queue,
4228            &status,
4229            &stop,
4230            crate::graph::Pause::new(),
4231            task,
4232        )
4233        .await;
4234    }
4235    hold_if_runnable(queue, task);
4236}
4237
4238/// Resumes an in-process run makes for withheld-text questions: the gate asks
4239/// at most twice, plus one for a resume that asks nothing new.
4240const MAX_WITHHELD_RESUMES: u32 = 3;
4241
4242/// How often an in-process run rechecks its withheld-text question.
4243const WITHHELD_POLL: Duration = Duration::from_secs(15);
4244
4245/// The `answer_timeout` (seconds) of the task's last run when that run is
4246/// parked on an unresolved withheld-text question; `None` otherwise.
4247fn withheld_text_wait(task: &Task) -> Option<u64> {
4248    let id = task.runs.last()?;
4249    let s = RunState::load(id).ok()?;
4250    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
4251        .then_some(s.config.graph.answer_timeout)
4252}
4253
4254/// The quota losses `after` holds that `before` did not: what one execution
4255/// suffered, as opposed to the run's history.
4256///
4257/// Compared by value rather than by length or position because
4258/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
4259/// the vector can shrink and shift under a resume. A retried seat that hits
4260/// quota again is a `push` with a new `at`, so it shows up as new here.
4261/// `reclaim` deliberately keeps reading the whole history: after a crash there
4262/// is no attempt boundary to diff against.
4263fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
4264    after
4265        .iter()
4266        .filter(|q| !before.contains(q))
4267        .cloned()
4268        .collect()
4269}
4270
4271/// When the loop-wide quota cooldown should end, given this attempt's losses;
4272/// `None` when there were none. Reset-hint parsing and the cap live here.
4273fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
4274    if quota.is_empty() {
4275        return None;
4276    }
4277    let with_hint = quota.iter().find(|q| q.reset.is_some());
4278    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
4279    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
4280    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
4281    Some(
4282        now.checked_add(jiff::SignedDuration::from_secs(secs))
4283            .unwrap_or(Timestamp::MAX),
4284    )
4285}
4286
4287/// An explicit task count must agree with a run before any resume.
4288fn implementers_match(task: &Task, state: &RunState) -> bool {
4289    task.replacement.as_ref().map_or_else(
4290        || {
4291            task.implementers()
4292                .is_none_or(|n| n == state.config.graph.implementers)
4293        },
4294        |replacement| {
4295            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
4296                && state.config.graph.implementers == 1
4297        },
4298    )
4299}
4300
4301/// Never resume or take over candidate work built for a different seat count.
4302fn starter_with_implementers(
4303    task: &Task,
4304    previous: Option<&RunState>,
4305    proposed: Starter,
4306) -> Starter {
4307    if previous.is_some_and(|s| !implementers_match(task, s)) {
4308        task.review_of
4309            .as_ref()
4310            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
4311    } else {
4312        proposed
4313    }
4314}
4315
4316/// Apply this task's explicit count to the new attempt, without changing defaults.
4317fn apply_task_implementers(config: &mut Config, task: &Task) {
4318    if let Some(n) = task.implementers() {
4319        config.graph.implementers = n;
4320    }
4321}
4322
4323/// [`prepare`] for one task: its own `--config` and command-line overrides
4324/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
4325/// over the loop's, so handing a hand-started task to a daemon changes nothing
4326/// about what it does.
4327#[cfg(test)]
4328fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
4329    let explicit = match &task.overrides {
4330        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4331        _ => opts.config.as_deref(),
4332    };
4333    let (mut config, _) = Config::discover(repo, explicit)?;
4334    apply_options(&mut config, opts, task)?;
4335    Ok(config)
4336}
4337
4338fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
4339    if task
4340        .overrides
4341        .as_ref()
4342        .is_none_or(|o| o.inherit_daemon_options)
4343        && let Some(mode) = opts.merge.as_deref()
4344    {
4345        config.merge.mode = merge_mode(mode)?;
4346    }
4347    if let Some(o) = &task.overrides {
4348        o.apply(config);
4349    }
4350    Ok(())
4351}
4352
4353/// Load the config for a task's repository, with the merge override applied.
4354fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
4355    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
4356    if let Some(mode) = &opts.merge {
4357        config.merge.mode = merge_mode(mode)?;
4358    }
4359    Ok(config)
4360}
4361
4362/// Prune the shared build cache back under its cap at a safe boundary
4363/// between runs, so a queue that never empties - and so never reaches
4364/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
4365/// does not leave the cache to grow unchecked for as long as the backlog
4366/// lasts.
4367///
4368/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
4369/// same liveness fact the idle branch's own janitor call rests on - no run
4370/// this daemon spawned is still mid-compile - so pruning here races nothing.
4371/// The caller must not call this while a run is in flight; there is no
4372/// second `busy_now()` check inside this function, on purpose, because there
4373/// is nothing left to check that `busy_now()` has not already answered.
4374///
4375/// A stop that has already been asked for *is* checked here, for a different
4376/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
4377/// synchronously before it decides anything, so the poll loop cannot get back
4378/// to its own `stopped()` test until that walk is over — and a loop already
4379/// on its way out must not make the operator wait out housekeeping it is
4380/// about to stop needing. This is the same call the idle branch makes when it
4381/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
4382/// it matters more here: `busy_now()` is false throughout, so
4383/// [`Stop::finishing`] would report a stop as already landed while the walk
4384/// still held the loop. Nothing is lost by skipping — the cap is a standing
4385/// policy, and the next daemon's startup pass measures the same cache.
4386///
4387/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
4388/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
4389/// and the next has not yet claimed a task, which can be every few
4390/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
4391/// more than the growth it is guarding against.
4392async fn maybe_prune_cache_between_runs(
4393    repo: &Path,
4394    opts: &Opts,
4395    home: &Path,
4396    stop: &Stop,
4397    last_checked: &mut Option<Timestamp>,
4398    now: Timestamp,
4399) {
4400    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
4401        return;
4402    }
4403    *last_checked = Some(now);
4404    let cfg = match prepare(repo, opts) {
4405        Ok(cfg) => cfg,
4406        Err(e) => {
4407            tracing::warn!("cache check: no config: {e:#}");
4408            return;
4409        }
4410    };
4411    match clean::prune_cache_if_over_limit(&cfg, home) {
4412        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
4413            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
4414            pruned.files,
4415            pruned.freed
4416        ),
4417        Ok(_) => {}
4418        Err(e) => {
4419            tracing::warn!("housekeep: prune cache: {e:#}");
4420            notices::raise_in(
4421                home,
4422                Notice::warn(
4423                    "housekeep:cache",
4424                    "Pruning the shared build cache failed; disk usage may keep growing.",
4425                ),
4426            );
4427        }
4428    }
4429}
4430
4431/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
4432/// now, given when it last did (if ever). Pure, so the cadence is asserted
4433/// directly rather than by waiting out real minutes in a test.
4434fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
4435    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
4436}
4437
4438/// The disk janitor, with its housekeeping logged rather than fatal.
4439///
4440/// Called only at the loop's idle points, for the reason the caller documents:
4441/// a prune racing a live compile would delete files mid-build. The config is
4442/// re-read on every call because the repository that just ran may not be the
4443/// daemon's own default, and the cache directory is a repository fact.
4444///
4445/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
4446/// and [`crate::run::default_worktree_root`] read here, for the same reason
4447/// [`drive`] takes its queue and status file rather than resolving them: a
4448/// test driving the loop must not reach through to the operator's real home
4449/// or worktree bay just because the janitor runs on every idle tick.
4450/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
4451/// to get wrong silently - a test's `home` was already isolated, but nothing
4452/// exercised the parameter next to it, so a real worktree bay stayed wired in
4453/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
4454/// it for real, every test in this file that drives the loop at all started
4455/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
4456async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
4457    let cfg = match prepare(repo, opts) {
4458        Ok(cfg) => cfg,
4459        Err(e) => {
4460            tracing::warn!("housekeep: no config: {e:#}");
4461            return;
4462        }
4463    };
4464    // A run's own worktree lives under `config.graph.worktree_root` when the
4465    // repository sets one - the same precedence `RunState::worktree_root`
4466    // uses - and `worktrees_root` only stands in for the *default* an
4467    // unconfigured repository resolves to (see this function's own
4468    // parameter, or the test fixture wiring one to a fake path). Housekeeping
4469    // that always swept the default regardless of this override would never
4470    // see, and so never reclaim, a single worktree for a repository that
4471    // relocated them elsewhere.
4472    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
4473    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
4474    // Reported whenever there is anything to say, not only when `folded > 0`:
4475    // the incident this exists to prevent was 90 of 93 runs skipped and 0
4476    // folded, on every single pass, for months - a report gated on `folded`
4477    // would have stayed silent through every one of them.
4478    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
4479        let mut extra = Vec::new();
4480        if out.unreadable > 0 {
4481            extra.push(format!("{} unreadable", out.unreadable));
4482        }
4483        if out.orphaned_worktrees > 0 {
4484            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
4485        }
4486        let detail = if extra.is_empty() {
4487            String::new()
4488        } else {
4489            format!(" ({})", extra.join(", "))
4490        };
4491        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
4492    }
4493    if out.external_merges_recorded > 0 {
4494        tracing::info!(
4495            "housekeep: recorded {} run(s) as merged externally",
4496            out.external_merges_recorded
4497        );
4498    }
4499    if out.stale_pr_states_repaired > 0 {
4500        tracing::info!(
4501            "housekeep: rewrote {} run record(s) whose pull request had already settled",
4502            out.stale_pr_states_repaired
4503        );
4504    }
4505    if out.cache_files > 0 {
4506        tracing::info!(
4507            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
4508            out.cache_files,
4509            out.cache_freed
4510        );
4511    }
4512    if out.questions_abandoned > 0 {
4513        tracing::info!(
4514            "housekeep: abandoned {} question(s) left open by a finished run",
4515            out.questions_abandoned
4516        );
4517    }
4518}
4519
4520/// Run [`triage::run_once`] and log whatever it did, the same "only when
4521/// there is something to say" rule [`janitor`] follows for its own report.
4522///
4523/// Called at the same idle points as [`janitor`] - once per full poll
4524/// interval, never mid-attempt - for the same reason: it is not liveness
4525/// critical, and a task's own `hold_reason` string is the one thing this
4526/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
4527/// tick for no benefit.
4528async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
4529    let questions = Questions::at(home.join("questions"));
4530    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
4531    if report.is_empty() {
4532        return;
4533    }
4534    if !report.quarantined.is_empty() {
4535        tracing::info!(
4536            "triage: held {} blocked task(s) whose blocked-on task or \
4537             question no longer exists: {}",
4538            report.quarantined.len(),
4539            report.quarantined.join(", ")
4540        );
4541    }
4542    if !report.resumed.is_empty() {
4543        tracing::info!(
4544            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
4545            report.resumed.len(),
4546            report.resumed.join(", ")
4547        );
4548    }
4549    if !report.asked.is_empty() {
4550        tracing::info!(
4551            "triage: asked about {} held task(s): {}",
4552            report.asked.len(),
4553            report.asked.join(", ")
4554        );
4555    }
4556    if !report.answered.is_empty() {
4557        tracing::info!(
4558            "triage: applied {} operator answer(s): {}",
4559            report.answered.len(),
4560            report.answered.join(", ")
4561        );
4562    }
4563}
4564
4565/// The free-space gate: what stands between this task and a new run, if
4566/// anything. `Some(reason)` holds the task; `None` lets it start.
4567///
4568/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
4569/// the operator opted out. A measurement failure is a gate, not a pass: both
4570/// sides of "cannot tell" are served by not starting.
4571fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
4572    disk_gate_with(repo, config, crate::disk::free_bytes)
4573}
4574
4575/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
4576/// test can assert the exact wiring `attempt` runs - config's threshold in,
4577/// task-holding reason out - without asking the real machine's disk anything.
4578fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
4579    repo: &Path,
4580    config: &Config,
4581    free_bytes: F,
4582) -> Option<String> {
4583    let min = config.disk.min_free_bytes;
4584    if min == 0 {
4585        return None;
4586    }
4587    match free_bytes(repo) {
4588        Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
4589        Err(e) => Some(crate::disk::unmeasured_in(repo, &e, &config.graph.language)),
4590    }
4591}
4592
4593/// How long to wait before offering another task when a run lost a seat to a
4594/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
4595/// could read, or carried nothing at all. Long enough that a quota outage
4596/// cannot burn through a whole backlog in the few seconds each doomed attempt
4597/// takes to fail; short enough that a quota which clears early is not left
4598/// idle for the fallback's sake.
4599const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
4600
4601/// Longest a parsed reset hint may push the wait out to. The hint comes from
4602/// the CLI's own words, not a contract, so a parsing slip that lands a day
4603/// away must not leave the loop asleep for a day.
4604const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
4605
4606/// How long [`poll`] should wait before offering the next task, after a run
4607/// lost at least one seat to a rate limit.
4608///
4609/// Pure and separate from the loop so the policy can be exercised without a
4610/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
4611/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
4612/// nothing to parse, or the parsed time has already passed; `cap` bounds how
4613/// far a parsed hint is trusted to push the wait out.
4614fn quota_wait(
4615    reset_at: Option<Timestamp>,
4616    now: Timestamp,
4617    fallback: Duration,
4618    cap: Duration,
4619) -> Duration {
4620    match reset_at {
4621        Some(at) if at > now => {
4622            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
4623            Duration::from_secs(secs).min(cap)
4624        }
4625        _ => fallback,
4626    }
4627}
4628
4629/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
4630///
4631/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
4632/// explains why parsing it exactly "would be a bug factory" — so this only
4633/// recognises the shapes actually observed in the wild, and returns `None`
4634/// for anything else rather than guess at a format nobody has seen.
4635///
4636/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
4637/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
4638/// said it, not from whenever this loop happens to read it: anchoring on `now`
4639/// would push the reset later on every read and would read an already-elapsed
4640/// reset as still in the future. (A long hint is still clamped by
4641/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
4642fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
4643    parse_reset_hint_zoned(text, now)
4644        .or_else(|| parse_reset_hint_dated(text))
4645        .or_else(|| parse_reset_hint_relative(text, recorded))
4646}
4647
4648/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
4649/// optional but at least one required, in that order. A bare number or any
4650/// unknown unit is refused.
4651fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
4652    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
4653    let mut rest = rest.trim();
4654    if rest.is_empty() {
4655        return None;
4656    }
4657    let mut total: i64 = 0;
4658    let mut matched = false;
4659    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
4660        if let Some((digits, tail)) = rest.split_once(unit)
4661            && !digits.is_empty()
4662            && digits.bytes().all(|b| b.is_ascii_digit())
4663        {
4664            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
4665            rest = tail;
4666            matched = true;
4667        }
4668    }
4669    if !rest.is_empty() || !matched {
4670        return None;
4671    }
4672    recorded
4673        .checked_add(jiff::SignedDuration::from_secs(total))
4674        .ok()
4675}
4676
4677/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
4678/// case-insensitive) into a 24-hour hour and minute. Shared by every
4679/// reset-hint shape below.
4680fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
4681    let clock = clock.trim().to_lowercase();
4682    let (digits, pm) = clock
4683        .strip_suffix("am")
4684        .map(|d| (d, false))
4685        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
4686    let (h, m) = digits.trim().split_once(':')?;
4687    let mut hour: i8 = h.trim().parse().ok()?;
4688    let minute: i8 = m.trim().parse().ok()?;
4689    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
4690        return None;
4691    }
4692    if pm && hour != 12 {
4693        hour += 12;
4694    } else if !pm && hour == 12 {
4695        hour = 0;
4696    }
4697    Some((hour, minute))
4698}
4699
4700/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
4701/// and a zone, never a date. A clock reading already past today is read as
4702/// tomorrow's: a CLI naming a same-day reset that has already gone by means
4703/// the window rolled over while nothing was watching.
4704fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
4705    let open = text.find('(')?;
4706    let close = text.rfind(')')?;
4707    if close <= open {
4708        return None;
4709    }
4710    let zone = text[open + 1..close].trim();
4711    let (hour, minute) = parse_12h_clock(&text[..open])?;
4712    let tz = jiff::tz::TimeZone::get(zone).ok()?;
4713    let candidate = now
4714        .to_zoned(tz)
4715        .with()
4716        .hour(hour)
4717        .minute(minute)
4718        .second(0)
4719        .millisecond(0)
4720        .microsecond(0)
4721        .nanosecond(0)
4722        .build()
4723        .ok()?;
4724    let mut at = candidate.timestamp();
4725    if at <= now {
4726        at += jiff::SignedDuration::from_hours(24);
4727    }
4728    Some(at)
4729}
4730
4731/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
4732/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
4733/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
4734/// "already past today" correction to make: the year already disambiguates
4735/// it. Scanned as a five-word window so it can be pulled out of the middle
4736/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
4737/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
4738/// any other timestamp with no zone attached.
4739fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
4740    let words: Vec<&str> = text.split_whitespace().collect();
4741    if words.len() < 5 {
4742        return None;
4743    }
4744    (0..=words.len() - 5)
4745        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
4746}
4747
4748/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
4749/// parenthesis right after the window is refused rather than ignored — it
4750/// reads as an explicit zone annotation on a shape that otherwise carries
4751/// none, and guessing UTC anyway would be exactly the silent misread this
4752/// module's parsing otherwise avoids.
4753fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
4754    if trailing.is_some_and(|next| next.starts_with('(')) {
4755        return None;
4756    }
4757    let month = month_number(window[0])?;
4758    let day_token = window[1].strip_suffix(',')?.to_lowercase();
4759    let day_digits = ["st", "nd", "rd", "th"]
4760        .iter()
4761        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
4762    let day: i8 = day_digits.parse().ok()?;
4763    let year_token = window[2];
4764    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
4765        return None;
4766    }
4767    let year: i16 = year_token.parse().ok()?;
4768    // The am/pm word carries the sentence's own trailing punctuation, e.g.
4769    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
4770    // reusing the same 12-hour clock reader the bracketed shape uses.
4771    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
4772    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
4773    let date = jiff::civil::Date::new(year, month, day).ok()?;
4774    let candidate = date
4775        .at(hour, minute, 0, 0)
4776        .to_zoned(jiff::tz::TimeZone::UTC)
4777        .ok()?;
4778    Some(candidate.timestamp())
4779}
4780
4781/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
4782/// case-insensitively, into a 1-based month number.
4783fn month_number(name: &str) -> Option<i8> {
4784    const NAMES: [&str; 12] = [
4785        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
4786    ];
4787    let lower = name.to_lowercase();
4788    NAMES
4789        .iter()
4790        .position(|n| *n == lower.as_str())
4791        .map(|i| i as i8 + 1)
4792}
4793
4794/// Resuming a `Blocked` run that already spent every review round its own
4795/// config allowed cannot make progress: `graph::Runner`'s review loop walks
4796/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
4797/// reached `max_rounds`, so `execute` would settle straight back to
4798/// `Blocked` without asking anyone anything. Read-only against a state this
4799/// build never mutates — `src/graph.rs` stays untouched — but without this
4800/// check, [`unfinished_run`] would keep reporting such a run as still
4801/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
4802/// promise is a fresh competition when a design needs to change) would
4803/// silently resume the exhausted run instead, spending an attempt on a
4804/// cycle that cannot change anything.
4805fn exhausted_review_budget(state: &RunState) -> bool {
4806    // A run whose task-head publication failed has nothing left to review:
4807    // resuming it only retries the publication, so it is never "exhausted".
4808    state.status == RunStatus::Blocked
4809        && !state.pr_publication_pending
4810        && state.reviews.len() >= state.config.graph.review_rounds
4811}
4812
4813/// This task's *most recent* run, if resuming it would actually make
4814/// progress. `short` is only for the warning's own message.
4815///
4816/// Only ever `runs.last()` — never a search back through older history.
4817/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
4818/// mint, oldest first, and every entry before the last one was already
4819/// superseded at the moment it was minted: the daemon only ever starts a new
4820/// run when the previous one was not worth resuming (unresumable, exhausted,
4821/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
4822/// opens a fresh review-only run alongside an older, already-failed
4823/// competition. Searching further back would let an old run that merely
4824/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
4825/// behind, say — get resumed instead of the fresh competition
4826/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
4827/// nothing asked to revisit.
4828///
4829/// Two runs paid for the "prefer resuming over restarting" half of this
4830/// lesson, which is why this still checks `runs.last()` rather than always
4831/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
4832/// task a moment later, duplicating two and a half hours of agent work. Then
4833/// b25f stalled on a judge that timed out and one that answered with no JSON
4834/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
4835/// **one second** later, buying three fresh implementations to reach the
4836/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
4837/// the second case: a stall is terminal, and its cheap recovery re-asks only
4838/// the absent seats. [`exhausted_review_budget`] is the other half: a run
4839/// that is technically `resumable()` but provably cannot progress must not
4840/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
4841/// no-op instead of the fresh competition it promises.
4842///
4843/// A load failure is warned about rather than silently read as "not
4844/// resumable": the alternative is exactly what let a schema mismatch on run
4845/// `eba2` fall through to a full re-competition with nobody told why.
4846/// `crate::conduct` is what actually offers a better answer than
4847/// `Runner::start` here (see `Recovery::Review`), once this task's next
4848/// failure shows it up as `held`/`failed` with the run state unreadable.
4849fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
4850    unfinished_run_with(runs, short, RunState::load)
4851}
4852
4853/// [`unfinished_run`] with an injected state reader. Tests provide their
4854/// fixtures directly rather than touching the process-global run home.
4855fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
4856where
4857    F: FnOnce(&str) -> Result<RunState>,
4858{
4859    let id = runs.last()?;
4860    match load(id) {
4861        // A run some process is driving right now is not "unfinished" in the
4862        // sense of waiting to be picked up: a run started by hand is in
4863        // `runs` while it is still executing, and resuming it here
4864        // would put a second driver on the same worktrees.
4865        Ok(s)
4866            if s.status.resumable()
4867                && !s.released()
4868                && !exhausted_review_budget(&s)
4869                && s.liveness(false) != crate::run::Liveness::Live =>
4870        {
4871            Some(id.clone())
4872        }
4873        Ok(_) => None,
4874        Err(e) => {
4875            tracing::warn!("could not read run {id} for task {short}: {e:#}");
4876            None
4877        }
4878    }
4879}
4880
4881/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
4882/// that [`attempt`] will resume it on its own?
4883///
4884/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
4885/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
4886/// injected reader like its sibling. An unreadable run is not awaiting
4887/// anything: it keeps going to the conductor as before.
4888fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
4889where
4890    F: FnOnce(&str) -> Result<RunState>,
4891{
4892    // `Failed` stays: a record an older build wrote for a parked run.
4893    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
4894        || task.fresh_start
4895        || task.review_branch.is_some()
4896    {
4897        return false;
4898    }
4899    let Some(id) = task.runs.last() else {
4900        return false;
4901    };
4902    load(id).is_ok_and(|s| {
4903        s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
4904    })
4905}
4906
4907/// Which of the three ways [`attempt`] can mint or continue a run this task
4908/// should use.
4909#[derive(Debug, Clone, PartialEq, Eq)]
4910enum Starter {
4911    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
4912    /// and that still exists.
4913    Review(String),
4914    /// `crate::graph::Runner::resume` on an unfinished run of this task.
4915    Resume(String),
4916    /// `crate::graph::Runner::start`: a fresh competition.
4917    Start,
4918}
4919
4920/// A selected public implementation overrides every historical candidate and pin.
4921fn selected_starter(
4922    selected: &crate::pr_recovery::Selection,
4923    previous: Option<&RunState>,
4924    unfinished: Option<&str>,
4925) -> Starter {
4926    if let Some(id) = unfinished
4927        && previous.is_some_and(|r| {
4928            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
4929        })
4930    {
4931        Starter::Resume(id.to_owned())
4932    } else {
4933        Starter::Review(selected.branch.clone())
4934    }
4935}
4936
4937/// The owner's answer to this branch's divergence question, consumed from the
4938/// task so a later, different divergence asks again. The runner applies it
4939/// (see `Runner::review_taking_over`), after the earlier worktree is released.
4940fn take_divergence_answer(
4941    branch: &str,
4942    remote: &str,
4943    task: &mut Task,
4944) -> Option<crate::reconcile::Choice> {
4945    let summary = crate::reconcile::summary_for(branch, remote);
4946    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
4947        (a.question == summary)
4948            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
4949            .flatten()
4950            .map(|c| (i, c))
4951    })?;
4952    task.answers.remove(idx);
4953    Some(choice)
4954}
4955
4956/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
4957/// this attempt should use. Pure, and separate from [`attempt`], so the
4958/// routing itself is assertable without spawning a real graph or a git
4959/// process: `attempt`'s own `crate::git::branch_exists` call has already
4960/// happened by the time this is called.
4961///
4962/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
4963/// whose branch is gone falls all the way through to [`Starter::Start`], not
4964/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
4965/// old (likely `Blocked`) run in the first place, and a branch that vanished
4966/// out from under that choice is not evidence resuming it would fare better.
4967fn choose_starter(
4968    review_branch: Option<&str>,
4969    branch_exists: bool,
4970    unfinished: Option<&str>,
4971) -> Starter {
4972    match review_branch {
4973        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
4974        Some(_) => Starter::Start,
4975        None => match unfinished {
4976            Some(id) => Starter::Resume(id.to_owned()),
4977            None => Starter::Start,
4978        },
4979    }
4980}
4981
4982/// Consume a retained review only while its authored criteria still match.
4983fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
4984    let branch = task.review_branch.take();
4985    let instruction = task.review_instruction.take();
4986    branch.filter(|branch| match &instruction {
4987        Some(authored) => *authored == task.instruction,
4988        // Legacy retained branches must agree with their prior run; only an
4989        // explicitly pinned review can proceed without recoverable provenance.
4990        None => previous.map_or_else(
4991            || task.review_of.as_ref() == Some(branch),
4992            |run| compatible_run_instruction(run, task),
4993        ),
4994    })
4995}
4996
4997/// A current explicit pin can select an otherwise incompatible run. Edits
4998/// and subsequent approvals invalidate pins selected for earlier criteria.
4999fn may_resume_run(run: &RunState, task: &Task) -> bool {
5000    task.resume_override
5001        .as_ref()
5002        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5003        || compatible_run_instruction(run, task)
5004}
5005
5006/// Review scaffolding is execution context, not evidence of an operator edit.
5007pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5008    if let Some(authored) = &run.task_instruction {
5009        return compatible_instruction(authored, task);
5010    }
5011    if compatible_instruction(&run.instruction, task) {
5012        return true;
5013    }
5014    // Recognize only the existing generated review shapes on legacy runs.
5015    // Ordinary authored text with a similar heading is left intact.
5016    if run.reviewed_commits.is_some() {
5017        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5018            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5019        }
5020        if let Some(branch) = &task.review_of {
5021            let canonical = format!(
5022                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5023            );
5024            let generated = format!(
5025                "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"
5026            );
5027            return task.instruction == canonical && run.instruction.starts_with(&generated);
5028        }
5029    }
5030    false
5031}
5032
5033/// Compare authored instructions, excluding answer blocks appended by the daemon.
5034pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5035    strip_answers_block(old, task) == task.instruction
5036}
5037
5038/// Which repository a task runs in. A task that names none — the normal case
5039/// for one filed from a phone — runs in the daemon's own default.
5040fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5041    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5042        return fallback.to_path_buf();
5043    }
5044    task.repo.clone()
5045}
5046
5047/// The header [`append_answers`] appends operator answers under. Shared with
5048/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5049/// rather than grown a new block on every resume.
5050const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5051
5052/// Render the first `count` answers in the block appended to an instruction.
5053fn answers_block(task: &Task, count: usize) -> String {
5054    let mut s = ANSWERS_HEADER.to_owned();
5055    for a in &task.answers[..count] {
5056        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5057    }
5058    s
5059}
5060
5061/// Render the approval independently of transient task state, so historical
5062/// suffixes remain recognizable after another explicit release.
5063fn resumption_block(r: &crate::queue::Resumption) -> String {
5064    format!(
5065        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5066         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5067        r.generation, r.at, r.instruction, r.answers_through,
5068    )
5069}
5070
5071/// Append audit answers and the latest explicit approval to the instruction.
5072fn append_answers(base: &str, task: &Task) -> String {
5073    let mut s = base.to_owned();
5074    if !task.answers.is_empty() {
5075        s.push_str(&answers_block(task, task.answers.len()));
5076    }
5077    if let Some(r) = &task.resumption {
5078        s.push_str(&resumption_block(r));
5079    }
5080    s
5081}
5082
5083/// Drop the prior answer block only when it is exactly the suffix this task
5084/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5085/// the task author is ordinary instruction text, not a block to remove.
5086fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5087    let mut instruction = instruction;
5088    for approval in task
5089        .resumption
5090        .iter()
5091        .chain(task.resumption_history.iter().rev())
5092    {
5093        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5094            instruction = base;
5095            break;
5096        }
5097    }
5098    for count in (1..=task.answers.len()).rev() {
5099        let block = answers_block(task, count);
5100        if let Some(base) = instruction.strip_suffix(&block) {
5101            return base;
5102        }
5103    }
5104    instruction
5105}
5106
5107/// The instruction handed to `Runner::start`: the task's own text, plus any
5108/// operator answers `crate::conduct` collected for it (see
5109/// [`Task::answers`]), so a decision the operator actually made reaches the
5110/// implementers rather than only clearing the block that was waiting on it.
5111///
5112/// Appended rather than merged into [`Task::instruction`] itself, so the
5113/// task's own record stays exactly what its author wrote.
5114fn instruction_for(task: &Task) -> String {
5115    append_answers(&task.instruction, task)
5116}
5117
5118/// The instruction a resumed run should carry on with: whatever it already
5119/// had, refreshed with the task's *current* operator answers.
5120///
5121/// A resumable run's own `RunState::instruction` predates any answer
5122/// `crate::conduct` collects after the run parks, so resuming it unchanged —
5123/// the behaviour before this function existed — silently drops the very
5124/// decision the operator made to unblock it. Re-stripping any block this
5125/// function appended on an earlier resume before re-appending the current
5126/// list (rather than blindly appending again) is what keeps a task resumed
5127/// three times over three answered questions from carrying the same answer
5128/// three times.
5129fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5130    append_answers(strip_answers_block(old_instruction, task), task)
5131}
5132
5133/// Preserve the producer's verified boundary and target, independent of prose.
5134fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5135    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5136    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5137    if let Some(cause) = task.hold_notice_cause.as_mut() {
5138        cause.target = failure.map(|f| f.target.clone());
5139    }
5140}
5141
5142#[derive(Debug, thiserror::Error)]
5143#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5144struct MissingAttachment {
5145    name: String,
5146    path: PathBuf,
5147}
5148
5149/// The task's attachments as absolute paths, each checked to still exist.
5150fn task_attachments(
5151    queue: &Queue,
5152    task: &Task,
5153) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5154    let paths = queue.attachment_paths(task);
5155    for (name, path) in task.attachments.iter().zip(&paths) {
5156        if !path.is_file() {
5157            return Err(MissingAttachment {
5158                name: name.clone(),
5159                path: path.clone(),
5160            });
5161        }
5162    }
5163    Ok(paths)
5164}
5165
5166/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
5167/// answers before handing it to `Runner` — the actual boundary between
5168/// [`choose_starter`]'s routing and the graph, factored out so it is
5169/// assertable without a real repository, git branch, or agent CLI.
5170///
5171/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
5172/// instruction from the reviewed branch's own commit log because there is no
5173/// task statement to speak of for hand-written work, and splicing operator
5174/// answers into that text would contradict the very message it sends
5175/// reviewers ("there is no task statement").
5176fn prepare_instruction(
5177    starter: &Starter,
5178    old_instruction: Option<&str>,
5179    task: &Task,
5180) -> Option<String> {
5181    match starter {
5182        Starter::Start => Some(instruction_for(task)),
5183        Starter::Resume(_) => Some(resumed_instruction(
5184            old_instruction.expect("a resumed run always has a prior instruction"),
5185            task,
5186        )),
5187        Starter::Review(_) => None,
5188    }
5189}
5190
5191/// Persist a transition. A queue write failure is logged rather than fatal: the
5192/// run already happened, and taking the daemon down would only add a lost
5193/// backlog to a full disk.
5194fn record(queue: &Queue, task: &mut Task) {
5195    if let Err(e) = queue.put(task) {
5196        tracing::error!("could not record task {}: {e:#}", task.short());
5197        let notice = Notice::error(
5198            "loop:record",
5199            "The loop could not save a task's state; check the disk.",
5200        )
5201        .link(Link::Task {
5202            id: task.id.clone(),
5203        });
5204        // The queue lives at `<home>/queue`, so its parent is the home.
5205        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
5206            Some(home) => notices::raise_in(home, notice),
5207            None => notices::raise(notice),
5208        }
5209    }
5210}
5211
5212/// Every runnable task, in the order the loop should try them.
5213///
5214/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
5215/// tail exists so that a claim somebody else holds costs the loop the next
5216/// candidate rather than a whole poll interval of idleness.
5217fn runnable(queue: &Queue) -> Vec<Task> {
5218    let mut tasks: Vec<Task> = queue
5219        .list()
5220        .into_iter()
5221        .filter(|t| t.status.runnable())
5222        .collect();
5223    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
5224    tasks
5225}
5226
5227/// Why a run ended where it did, in one line, for [`Task::last_error`].
5228///
5229/// A stalled run names the seats the quota took out: "out of quota" is not
5230/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
5231/// agent to replace or which plan to top up.
5232///
5233/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
5234/// purpose: unlike `label`'s other callers (an internal log line, an
5235/// already-a-bug fallback message), this string becomes `Task::last_error`
5236/// verbatim, which the phone renders in the same alarm-styled box an
5237/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
5238/// `.err` styling. A bare `verified_noop` there would read exactly like the
5239/// failure this whole feature exists to tell apart from one.
5240fn describe(state: &RunState) -> String {
5241    let p = phrases(&state.config.graph.language);
5242    let mut detail = if state.status == RunStatus::Stalled {
5243        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
5244        seats.sort_unstable();
5245        seats.dedup();
5246        if seats.is_empty() {
5247            p.quorum_lost.to_owned()
5248        } else {
5249            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
5250        }
5251    } else {
5252        format!("{}{}", p.run_ended, state.status.display_label())
5253    };
5254    if let Some(last) = state.events.last() {
5255        // The review loop's "never answered" stop is the one event worth
5256        // translating; it is recognised from structured state, not by
5257        // matching the English event text (which stays as recorded).
5258        let unanswered = state
5259            .reviews
5260            .last()
5261            .filter(|r| {
5262                state.status == RunStatus::Blocked
5263                    && last.node == "review"
5264                    && r.incomplete()
5265                    && r.blocking == 0
5266                    && r.round == state.config.graph.review_rounds
5267                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
5268            })
5269            .map(|r| (r.expected - r.answered, r.round));
5270        match unanswered {
5271            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
5272                detail.push_str(&format!(
5273                    " ({}: {})",
5274                    last.node,
5275                    (p.reviewers_never_answered)(missing, rounds)
5276                ));
5277            }
5278            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
5279        }
5280    }
5281    detail.push_str(&format!(" [run {}]", state.id));
5282    detail
5283}
5284
5285/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
5286///
5287/// The task file lives in the backlog indefinitely; a diagnostic is an
5288/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
5289/// stay small regardless of how much a gate command or a candidate printed.
5290const DIAGNOSTIC_MAX: usize = 4_000;
5291
5292/// Tail kept from a single failing command's output inside a diagnostic.
5293/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
5294/// pointer for a human deciding whether to go read the full artifact by hand,
5295/// not a replacement for reading it.
5296const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
5297
5298/// Assemble a bounded diagnostic excerpt from a held task's own run, so
5299/// `magi task show` says more than the one-line reason in [`describe`].
5300///
5301/// The one-liner answers "where did the run stop"; this answers "what would a
5302/// human have found opening `artifacts/` by hand" — the point of the whole
5303/// feature is the case that one-liner actively misleads on: a run held as "no
5304/// candidate produced a change" can mean the implementer actually finished
5305/// the task (opened a PR, merged it, tagged a release) and only left a clean
5306/// local worktree behind, which reads as "nothing happened" unless someone
5307/// goes and reads what the agent actually said. `None` when the run carries
5308/// none of the three shapes this recognises — an ordinary run held for
5309/// something not diagnosable from `RunState` alone still explains itself
5310/// through `Task::last_error`.
5311fn diagnostic(state: &RunState) -> Option<String> {
5312    let mut parts: Vec<String> = Vec::new();
5313
5314    // Gate failure: which check(s), and the tail of what each printed.
5315    for o in state.gate.iter().filter(|o| !o.ok()) {
5316        parts.push(format!(
5317            "gate `{}` failed ({}):\n{}",
5318            o.command,
5319            notices::exit_status(o.code),
5320            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
5321        ));
5322    }
5323
5324    // The land loop gave up because the fixer declined while checks were
5325    // still red: the message already names them (see `land::run`).
5326    if let Some(last) = state
5327        .events
5328        .iter()
5329        .rev()
5330        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
5331    {
5332        parts.push(last.message.clone());
5333    }
5334
5335    // No viable candidate: every implementer's own final word, sanitized the
5336    // same way a judge would have read it, so a run that actually finished
5337    // the job does not read as an unexplained failure. A verified no-op is
5338    // called out ahead of its own summary and apart from an ordinary
5339    // failure's `why` — this is the one candidate shape whose diagnostic a
5340    // human is expected to actually judge, not just skim.
5341    if state.viable().is_empty() {
5342        for c in &state.candidates {
5343            if let Some(evidence) = &c.verified_noop {
5344                parts.push(format!(
5345                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
5346                    c.label
5347                ));
5348            } else if !c.summary.trim().is_empty() {
5349                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
5350            } else if let Some(why) = &c.failed {
5351                parts.push(format!("candidate {}: {why}", c.label));
5352            }
5353        }
5354    }
5355
5356    if parts.is_empty() {
5357        return None;
5358    }
5359    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
5360    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
5361    // back slightly over. Leave it enough room to always land under the
5362    // limit.
5363    Some(crate::run::tail(
5364        &parts.join("\n\n"),
5365        DIAGNOSTIC_MAX.saturating_sub(100),
5366    ))
5367}
5368
5369/// Stable lower-case name for a run status, for an internal log line and the
5370/// "graph stopped without reaching a terminal status" bug message in
5371/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
5372/// doc for why that one reads [`RunStatus::display_label`] instead. One
5373/// definition of a status's name, on the type that owns it: this table used
5374/// to live here as a second copy, and a status renamed in one place would
5375/// have gone on reading correctly in the other.
5376fn label(status: RunStatus) -> &'static str {
5377    status.as_str()
5378}
5379
5380/// Parse a merge mode override.
5381pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
5382    match mode {
5383        "none" => Ok(MergeMode::None),
5384        "local" => Ok(MergeMode::Local),
5385        "pr" => Ok(MergeMode::Pr),
5386        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
5387    }
5388}
5389
5390/// Take the status lock, recovering from a poisoned one.
5391///
5392/// A panic elsewhere must not silently stop the heartbeat: the status is plain
5393/// data, and the worst a poisoned lock can hold is a stale timestamp.
5394fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
5395    mutex
5396        .lock()
5397        .unwrap_or_else(std::sync::PoisonError::into_inner)
5398}
5399
5400#[cfg(test)]
5401mod tests {
5402    use super::*;
5403    use crate::queue::{Source, TaskStatus};
5404    use crate::run::{Candidate, CommandOutcome};
5405    use pretty_assertions::assert_eq;
5406
5407    fn task() -> Task {
5408        Task::new(
5409            "add retries".to_owned(),
5410            "add retries".to_owned(),
5411            PathBuf::from("/repo"),
5412            Source::Human,
5413        )
5414    }
5415
5416    #[test]
5417    fn selected_public_head_overrides_historical_resume_and_pin() {
5418        let mut t = task();
5419        let mut old = run_state(RunStatus::Blocked);
5420        let selection = crate::pr_recovery::Selection {
5421            url: "url".into(),
5422            branch: format!("magi/task-{}", t.id),
5423            head: "a".repeat(40),
5424            source_head: None,
5425            source_run: None,
5426            source_proof: None,
5427            disposition: Some(crate::pr_recovery::Disposition::Review),
5428            instruction: t.instruction.clone(),
5429            approved_at: Timestamp::now(),
5430        };
5431        t.resume_override = Some(crate::queue::OperatorResume {
5432            pinned_run: Some(old.id.clone()),
5433            question_id: "choice".into(),
5434            at: Timestamp::now(),
5435            conductor_rehold: None,
5436            forced: false,
5437        });
5438        assert_eq!(
5439            selected_starter(&selection, Some(&old), Some(&old.id)),
5440            Starter::Review(selection.branch.clone())
5441        );
5442        old.pr_recovery = Some(selection.clone());
5443        assert_eq!(
5444            selected_starter(&selection, Some(&old), Some(&old.id)),
5445            Starter::Review(selection.branch.clone())
5446        );
5447        old.reviewed_commits = Some(vec!["implementation".into()]);
5448        assert_eq!(
5449            selected_starter(&selection, Some(&old), Some(&old.id)),
5450            Starter::Resume(old.id.clone())
5451        );
5452        let mut changed = selection.clone();
5453        changed.head = "b".repeat(40);
5454        assert_eq!(
5455            selected_starter(&changed, Some(&old), Some(&old.id)),
5456            Starter::Review(changed.branch)
5457        );
5458    }
5459
5460    #[test]
5461    fn candidate_transplant_failure_is_one_actionable_hold() {
5462        let dir = tempfile::tempdir().unwrap();
5463        let q = Queue::at(dir.path().join("queue"));
5464        let mut t = task();
5465        let mut state = run_state(RunStatus::Blocked);
5466        state.event("prep", "cannot apply referenced commit: conflict");
5467        state.prep_failure = Some("conflict".into());
5468        t.start(state.id.clone());
5469        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
5470        assert_eq!(t.attempts, 1);
5471        assert_eq!(t.status, TaskStatus::Held);
5472        assert!(t.operator_held());
5473        assert!(!t.status.runnable());
5474        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
5475        let first = t.chat_notice_key().unwrap();
5476        t.chat_notices.push(first.clone());
5477        t.release_operator("test", None);
5478        state.id = "another-unprepared-run".into();
5479        t.start(state.id.clone());
5480        finish_attempt(
5481            3,
5482            &q,
5483            &mut t,
5484            &state,
5485            &[],
5486            Err(anyhow::anyhow!("still conflicts")),
5487        );
5488        assert_eq!(
5489            t.chat_notice_key().as_ref(),
5490            Some(&first),
5491            "no work happened"
5492        );
5493        t.release_operator("test", None);
5494        state.prep_failure = None;
5495        state.status = RunStatus::Failed;
5496        state.begin_pass();
5497        t.start(state.id.clone());
5498        finish_attempt(
5499            1,
5500            &q,
5501            &mut t,
5502            &state,
5503            &[],
5504            Err(anyhow::anyhow!("new gate failure")),
5505        );
5506        let failure = t.chat_notice_key().unwrap();
5507        assert_ne!(failure, first, "approved recovery reached a real failure");
5508        t.release_operator("test", None);
5509        state.begin_pass();
5510        t.start(state.id.clone());
5511        finish_attempt(
5512            1,
5513            &q,
5514            &mut t,
5515            &state,
5516            &[],
5517            Err(anyhow::anyhow!("new failure on resume")),
5518        );
5519        assert_ne!(
5520            t.chat_notice_key().as_ref(),
5521            Some(&failure),
5522            "a new settled pass"
5523        );
5524    }
5525
5526    #[test]
5527    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
5528        for source in ["cli", "web"] {
5529            let mut t = task();
5530            let mut run = run_state(RunStatus::Blocked);
5531            run.instruction = "Run A original criteria".into();
5532            run.task_instruction = Some(run.instruction.clone());
5533            t.start(run.id.clone());
5534            t.release_operator("choice", Some("resume-question"));
5535            t.resume_override = Some(crate::queue::OperatorResume {
5536                question_id: "resume-question".into(),
5537                at: Timestamp::now(),
5538                conductor_rehold: None,
5539                forced: true,
5540                pinned_run: Some(run.id.clone()),
5541            });
5542            t.hold_machine(Some("not enough free space to start a run".into()));
5543            let mut unchanged = t.clone();
5544            unchanged
5545                .edit("title changed".into(), unchanged.instruction.clone())
5546                .unwrap();
5547            unchanged.release_operator(source, None);
5548            assert_eq!(
5549                unchanged
5550                    .resume_override
5551                    .as_ref()
5552                    .unwrap()
5553                    .pinned_run
5554                    .as_deref(),
5555                Some(run.id.as_str())
5556            );
5557            assert!(!compatible_run_instruction(&run, &unchanged));
5558            assert!(may_resume_run(&run, &unchanged));
5559
5560            t.edit(
5561                "approved recovery".into(),
5562                "Reuse measured PR head B; fix Clippy; review".into(),
5563            )
5564            .unwrap();
5565            assert!(t.resume_override.is_none());
5566            t.release_operator(source, None);
5567            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
5568            assert!(reloaded.resume_override.is_none());
5569            assert!(!may_resume_run(&run, &reloaded));
5570            let unfinished =
5571                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
5572                    .filter(|_| may_resume_run(&run, &reloaded));
5573            assert_eq!(
5574                choose_starter(None, false, unfinished.as_deref()),
5575                Starter::Start
5576            );
5577            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
5578            assert_eq!(
5579                reloaded.resumption_history[0].question_id.as_deref(),
5580                Some("resume-question")
5581            );
5582
5583            // A revision already persisted with the old approval/pin is also
5584            // invalidated when the new operator release is recorded.
5585            unchanged.instruction = "Reuse measured PR head B".into();
5586            unchanged.hold_machine(Some("disk hold".into()));
5587            unchanged.release_operator(source, None);
5588            assert!(unchanged.resume_override.is_none());
5589            assert!(!may_resume_run(&run, &unchanged));
5590        }
5591    }
5592
5593    #[test]
5594    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
5595        let mut t = task();
5596        let mut run = run_state(RunStatus::Blocked);
5597        t.review_of = Some("approved-head".into());
5598        t.instruction =
5599            "Review the branch `approved-head` (review-only: no implementation, no judging)."
5600                .into();
5601        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();
5602        run.reviewed_commits = Some(vec!["Commit log".into()]);
5603        t.start(run.id.clone());
5604        t.hold_machine(Some("interrupted review".into()));
5605        t.release_operator("cli", None);
5606        assert!(
5607            compatible_run_instruction(&run, &t),
5608            "legacy explicit review remains resumable"
5609        );
5610        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
5611            .filter(|_| compatible_run_instruction(&run, &t));
5612        assert_eq!(
5613            choose_starter(None, false, unfinished.as_deref()),
5614            Starter::Resume(run.id.clone())
5615        );
5616        run.task_instruction = Some(t.instruction.clone());
5617        assert!(compatible_run_instruction(&run, &t));
5618        let reloaded: RunState =
5619            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
5620        assert!(compatible_run_instruction(&reloaded, &t));
5621        t.edit(
5622            "new approved head".into(),
5623            "Reuse measured PR head B".into(),
5624        )
5625        .unwrap();
5626        assert!(!compatible_run_instruction(&run, &t));
5627
5628        // Legacy recovery reviews retain the task criteria ahead of the log.
5629        t.review_of = None;
5630        t.instruction = "Fix Clippy on approved head".into();
5631        run.task_instruction = None;
5632        run.instruction = format!(
5633            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
5634            t.instruction
5635        );
5636        assert!(compatible_run_instruction(&run, &t));
5637        t.instruction.push('\n');
5638        assert!(
5639            compatible_run_instruction(&run, &t),
5640            "legacy generated review trimmed the original criteria"
5641        );
5642        t.hold_for_handover(Some("approved-head".into()), "refused".into());
5643        let mut unchanged = t.clone();
5644        assert_eq!(
5645            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
5646            Some("approved-head")
5647        );
5648        t.edit("new plan".into(), "Reuse measured PR head B".into())
5649            .unwrap();
5650        assert!(take_review_branch(&mut t, Some(&run)).is_none());
5651        assert!(!compatible_run_instruction(&run, &t));
5652        t.review_branch = Some("approved-head".into());
5653        t.review_instruction = None;
5654        assert!(
5655            take_review_branch(&mut t, Some(&run)).is_none(),
5656            "legacy retained candidate cannot replace a revised approved head"
5657        );
5658    }
5659
5660    #[test]
5661    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
5662        crate::run::pin_test_home();
5663        let dir = tempfile::tempdir().unwrap();
5664        let queue = Queue::at(dir.path().join("queue"));
5665        for resume in [true, false] {
5666            let state = run_state(RunStatus::Blocked);
5667            let mut t = task();
5668            t.start(state.id.clone());
5669            let action = if resume {
5670                ask::ChoiceAction::Resume {
5671                    run: state.id.clone(),
5672                }
5673            } else {
5674                ask::ChoiceAction::Requeue
5675            };
5676            let mut q = action_question(&state.id, action);
5677            q.status = ask::QuestionStatus::Open;
5678            q.answer = None;
5679            q.answered_at = None;
5680            t.fail("run stopped with a question", 3);
5681            hold_if_runnable(&queue, &mut t);
5682            assert!(t.operator_decided_at.is_none());
5683            assert!(t.operator_held());
5684            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
5685            let expected = if resume {
5686                ActionDecision::Resume(state.id.clone())
5687            } else {
5688                ActionDecision::Requeue
5689            };
5690            assert_eq!(
5691                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5692                expected
5693            );
5694            t.hold_manual(Some("later explicit hold".into()));
5695            assert_eq!(
5696                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
5697                ActionDecision::Stale
5698            );
5699        }
5700    }
5701
5702    #[test]
5703    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
5704        let mut t = task();
5705        t.answers.push(crate::queue::AnsweredQuestion {
5706            question: "Inspect the remote?".into(),
5707            answer: "Inspect then wait".into(),
5708        });
5709        let old = instruction_for(&t);
5710        assert!(compatible_instruction(&old, &t));
5711        t.instruction = "Reuse approved PR head and review".into();
5712        t.release_operator("cli", None);
5713        assert!(!compatible_instruction(&old, &t));
5714        let approved = instruction_for(&t);
5715        assert!(approved.contains("waiting premises are superseded"));
5716        assert!(compatible_instruction(&approved, &t));
5717        assert_eq!(resumed_instruction(&approved, &t), approved);
5718        t.release_operator("web", None);
5719        assert!(compatible_instruction(&approved, &t));
5720        assert_eq!(t.resumption_history.len(), 1);
5721        t.start("run".into());
5722        assert!(instruction_for(&t).contains("Explicit operator resumption"));
5723    }
5724
5725    /// A run that stopped on an infrastructure wait asked no agent anything:
5726    /// the task is held by the machine under a `[resource]` reason (resumable,
5727    /// re-checked by triage), and the attempt it started is given back.
5728    #[test]
5729    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
5730        let mut state = RunState::new(
5731            PathBuf::from("/repo"),
5732            "main".to_owned(),
5733            "abc1234".to_owned(),
5734            "task".to_owned(),
5735            Config::default(),
5736        );
5737        state.status = RunStatus::Blocked;
5738        state.resource_block = Some(crate::run::ResourceBlock {
5739            node: "graft".to_owned(),
5740            kind: "shared build cache".to_owned(),
5741            detail: "timed out".to_owned(),
5742            at: jiff::Timestamp::now(),
5743        });
5744        let mut t = task();
5745        t.start("20260902-000000-aaaa".to_owned());
5746        assert_eq!(t.attempts, 1);
5747        let verdict = Verdict {
5748            status: RunStatus::Blocked,
5749            left_pr: false,
5750            quota_hit: false,
5751            parked: false,
5752            no_viable_candidates: false,
5753        };
5754        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
5755        assert_eq!(t.status, TaskStatus::Held);
5756        assert_eq!(t.attempts, 0, "the attempt is refunded");
5757        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
5758        assert!(
5759            !t.operator_held(),
5760            "a machine hold, released without a human"
5761        );
5762
5763        let mut selected = task();
5764        selected.start("20260902-000000-cccc".into());
5765        selected.replacement = Some(crate::merge_decision::Replacement {
5766            question: "fixture".into(),
5767            run: "earlier".into(),
5768            pr: "https://example.invalid/pr/1".into(),
5769            agent: "selected".into(),
5770            context: "fixture".into(),
5771        });
5772        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
5773        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
5774        assert_eq!(selected.attempts, 0);
5775        assert!(
5776            !selected.operator_held(),
5777            "a selected agent also retains a machine resource hold"
5778        );
5779        assert!(
5780            selected
5781                .hold_reason
5782                .as_deref()
5783                .unwrap()
5784                .starts_with("[resource] ")
5785        );
5786
5787        // A park request outranks it: still the operator's doing.
5788        let mut p = task();
5789        p.start("20260902-000000-bbbb".to_owned());
5790        settle_and_diagnose(
5791            &mut p,
5792            Verdict {
5793                parked: true,
5794                ..verdict
5795            },
5796            "parked",
5797            2,
5798            &state,
5799        );
5800        assert_eq!(p.status, TaskStatus::Parked);
5801    }
5802
5803    #[test]
5804    fn record_failure_notice_links_the_task() {
5805        let dir = tempfile::tempdir().unwrap();
5806        // A regular file where the queue directory should be makes every
5807        // `put` fail, on every platform and whoever runs the test.
5808        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
5809        let queue = Queue::at(dir.path().join("queue"));
5810        let mut t = interrupt_task("rec-fail-1");
5811        record(&queue, &mut t);
5812
5813        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
5814        assert_eq!(found.len(), 1);
5815        assert_eq!(found[0].key, "loop:record");
5816        assert_eq!(
5817            found[0].link,
5818            Some(Link::Task {
5819                id: "rec-fail-1".to_owned()
5820            })
5821        );
5822    }
5823
5824    /// A runnable task marked to interrupt, with an id fixed for assertions
5825    /// rather than the random one [`Task::new`] mints.
5826    fn interrupt_task(id: &str) -> Task {
5827        let mut t = task();
5828        t.id = id.to_owned();
5829        t.interrupt = true;
5830        t
5831    }
5832
5833    /// An ordinary runnable task with an id fixed for assertions.
5834    fn task_with_id(id: &str) -> Task {
5835        let mut t = task();
5836        t.id = id.to_owned();
5837        t
5838    }
5839
5840    /// A runnable task marked `--urgent`, with an id fixed for assertions.
5841    fn urgent_task(id: &str) -> Task {
5842        let mut t = task();
5843        t.id = id.to_owned();
5844        t.urgent = true;
5845        t
5846    }
5847
5848    #[test]
5849    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
5850        let dir = tempfile::tempdir().unwrap();
5851        let queue = Queue::at(dir.path().join("queue"));
5852        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5853        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5854        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
5855        let mut first = task();
5856        queue.put(&mut first).unwrap();
5857        let stale_plain = queue.get(&first.id).unwrap();
5858        first.set_urgent(true).unwrap();
5859        queue.put(&mut first).unwrap();
5860        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
5861        let mut second = urgent_task("second");
5862        queue.put(&mut second).unwrap();
5863        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
5864        drop(queue.claim(&second.id).unwrap());
5865        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
5866        drop(dispatched);
5867        let stale_urgent = queue.get(&first.id).unwrap();
5868        first.set_urgent(false).unwrap();
5869        queue.put(&mut first).unwrap();
5870        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
5871        assert_eq!(urgent.available_permits(), 1);
5872        drop(queue.claim(&first.id).unwrap());
5873        drop(occupied);
5874    }
5875
5876    #[test]
5877    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
5878        let dir = tempfile::tempdir().unwrap();
5879        let queue = Queue::at(dir.path().join("queue"));
5880        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
5881        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
5882        let mut t = task();
5883        queue.put(&mut t).unwrap();
5884        for enabled in [true, false] {
5885            let stale = queue.get(&t.id).unwrap();
5886            t.set_urgent(enabled).unwrap();
5887            queue.put(&mut t).unwrap();
5888            assert_ne!(stale.urgent, enabled);
5889            let DispatchClaim {
5890                task: fresh,
5891                claim,
5892                permit,
5893            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
5894            assert_eq!(fresh.urgent, enabled);
5895            assert_eq!(ordinary.available_permits(), usize::from(enabled));
5896            assert_eq!(urgent.available_permits(), usize::from(!enabled));
5897            assert!(queue.claim(&t.id).is_err());
5898            assert_eq!(fresh.attempts, stale.attempts);
5899            drop((claim, permit));
5900            assert_eq!(ordinary.available_permits(), 1);
5901            assert_eq!(urgent.available_permits(), 1);
5902        }
5903        t.set_urgent(true).unwrap();
5904        queue.put(&mut t).unwrap();
5905        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
5906        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5907        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
5908        drop(queue.claim(&t.id).unwrap());
5909        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
5910        drop(occupied);
5911        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
5912        drop(queue.claim(&t.id).unwrap());
5913        let held = queue.claim(&t.id).unwrap();
5914        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5915        drop(held);
5916        t.status = TaskStatus::Held;
5917        queue.put(&mut t).unwrap();
5918        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5919        drop(queue.claim(&t.id).unwrap());
5920        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
5921        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
5922        drop(queue.claim(&t.id).unwrap());
5923        assert_eq!(urgent.available_permits(), 1);
5924    }
5925
5926    /// The land-resume exemption wins outright, whether or not the candidate
5927    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
5928    /// queue behind anything" guarantee cannot be weaker just because the
5929    /// same task was also filed with `--urgent`.
5930    #[test]
5931    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
5932        assert_eq!(permit_kind(true, false), PermitKind::None);
5933        assert_eq!(permit_kind(true, true), PermitKind::None);
5934    }
5935
5936    /// The one property this whole feature exists for: `--urgent` draws from
5937    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
5938    /// ordinary candidate draws from the ordinary pool exactly as before,
5939    /// untouched by the urgent slot's existence.
5940    #[test]
5941    fn permit_kind_separates_urgent_from_ordinary() {
5942        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
5943        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
5944    }
5945
5946    /// The exact wiring `attempt` runs before minting anything: a config's
5947    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
5948    /// Free space is injected rather than asked of the real disk - the point
5949    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
5950    /// is deterministic on every machine this test runs on, never dependent
5951    /// on how full the CI runner's own disk happens to be.
5952    #[test]
5953    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
5954        let cfg = Config::default();
5955        let repo = Path::new("/any/repo/path");
5956
5957        let reason =
5958            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
5959        assert!(reason.contains("1024"), "{reason}");
5960        assert!(
5961            reason.contains(&cfg.disk.min_free_bytes.to_string()),
5962            "{reason}"
5963        );
5964
5965        assert_eq!(
5966            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
5967            None,
5968            "exactly at the floor is open"
5969        );
5970        assert_eq!(
5971            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
5972            None,
5973            "comfortably above the floor is open"
5974        );
5975    }
5976
5977    #[test]
5978    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
5979        let mut cfg = Config::default();
5980        cfg.disk.min_free_bytes = 0;
5981        let repo = Path::new("/any/repo/path");
5982        assert_eq!(
5983            disk_gate_with(repo, &cfg, |_| Ok(0)),
5984            None,
5985            "a zero floor never measures at all"
5986        );
5987    }
5988
5989    #[test]
5990    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
5991        let cfg = Config::default();
5992        let repo = Path::new("/any/repo/path");
5993        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
5994            .expect("a measurement failure must close the gate, not open it");
5995        assert!(reason.contains("could not measure"), "{reason}");
5996    }
5997
5998    #[test]
5999    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
6000        let ordinary = task();
6001        let next = advance_interrupt(
6002            Interrupt::Idle,
6003            std::slice::from_ref(&ordinary.id),
6004            std::slice::from_ref(&ordinary),
6005        );
6006        assert_eq!(next, Interrupt::Idle);
6007    }
6008
6009    #[test]
6010    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
6011        // Nothing to interrupt - this is just an ordinary candidate, and the
6012        // loop's normal dispatch will pick it up like any other.
6013        let marked = interrupt_task("marked");
6014        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6015        assert_eq!(next, Interrupt::Idle);
6016    }
6017
6018    #[test]
6019    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
6020        let marked = interrupt_task("marked");
6021        let next = advance_interrupt(
6022            Interrupt::Idle,
6023            &["running".to_owned()],
6024            std::slice::from_ref(&marked),
6025        );
6026        assert_eq!(
6027            next,
6028            Interrupt::Parking {
6029                parked: vec!["running".to_owned()],
6030                interrupt_task: "marked".to_owned(),
6031            }
6032        );
6033    }
6034
6035    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
6036    /// one run can be in flight when a task becomes runnable and marked.
6037    /// Parking all of them would mean `Resuming` later has more than one id
6038    /// to release back to ordinary dispatch, which cannot be made safe
6039    /// against that same setting's own extra concurrency slots letting two
6040    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
6041    /// The simplification the task's own constraints ask for: do not begin
6042    /// a sequence at all until the herd settles back to exactly one.
6043    #[test]
6044    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
6045        let marked = interrupt_task("marked");
6046
6047        let two = advance_interrupt(
6048            Interrupt::Idle,
6049            &["a".to_owned(), "b".to_owned()],
6050            std::slice::from_ref(&marked),
6051        );
6052        assert_eq!(two, Interrupt::Idle);
6053
6054        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
6055        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
6056    }
6057
6058    #[test]
6059    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
6060        let state = Interrupt::Parking {
6061            parked: vec!["running".to_owned()],
6062            interrupt_task: "marked".to_owned(),
6063        };
6064        // Still in flight: no change.
6065        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
6066        assert_eq!(still_going, state);
6067
6068        // Left flight, but the interrupt task has not been dispatched yet on
6069        // this tick - stays `Parking` so `interrupt_gate` can let it through,
6070        // as long as it is still runnable.
6071        let stopped_but_not_yet_dispatched =
6072            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
6073        assert_eq!(stopped_but_not_yet_dispatched, state);
6074
6075        // Left flight, and the interrupt task is now in flight itself.
6076        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
6077        assert_eq!(
6078            dispatched,
6079            Interrupt::Running {
6080                parked: vec!["running".to_owned()],
6081                interrupt_task: "marked".to_owned(),
6082            }
6083        );
6084    }
6085
6086    #[test]
6087    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
6088        let state = Interrupt::Running {
6089            parked: vec!["running".to_owned()],
6090            interrupt_task: "marked".to_owned(),
6091        };
6092        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
6093        assert_eq!(still_running, state);
6094
6095        // Whatever it ended as - merged, failed, held - is not this
6096        // function's concern: leaving flight is the only trigger, driven
6097        // straight off the same in-flight list `poll` already reaps. It does
6098        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
6099        // why that would let an unrelated task start ahead of, or alongside,
6100        // the guaranteed resume.
6101        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
6102        assert_eq!(
6103            ended,
6104            Interrupt::Resuming {
6105                parked: vec!["running".to_owned()]
6106            }
6107        );
6108    }
6109
6110    #[test]
6111    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
6112        let state = Interrupt::Resuming {
6113            parked: vec!["running".to_owned()],
6114        };
6115        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
6116        assert_eq!(still_waiting, state);
6117
6118        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
6119        assert_eq!(dispatched, Interrupt::Idle);
6120    }
6121
6122    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
6123    /// or otherwise moved on by an operator with no claim standing in the
6124    /// way - must not wedge the sequence (and so the whole loop's dispatch,
6125    /// via `interrupt_gate`) waiting forever for a dispatch that can never
6126    /// come. The parked run still gets its resume.
6127    #[test]
6128    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
6129    {
6130        let state = Interrupt::Parking {
6131            parked: vec!["running".to_owned()],
6132            interrupt_task: "marked".to_owned(),
6133        };
6134        // `marked` has been held/blocked/deleted since the sequence began:
6135        // it no longer appears in `runnable` at all.
6136        let next = advance_interrupt(state, &[], &[]);
6137        assert_eq!(
6138            next,
6139            Interrupt::Resuming {
6140                parked: vec!["running".to_owned()]
6141            },
6142            "abandoning the interrupt must not abandon the resume it owes"
6143        );
6144    }
6145
6146    /// The same abandonment, one step later: `Resuming` itself must not wait
6147    /// forever for a parked task that has since become unrunnable.
6148    #[test]
6149    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
6150        let state = Interrupt::Resuming {
6151            parked: vec!["running".to_owned()],
6152        };
6153        let next = advance_interrupt(state, &[], &[]);
6154        assert_eq!(
6155            next,
6156            Interrupt::Idle,
6157            "nothing is left to wait for; the loop must not stay wedged"
6158        );
6159    }
6160
6161    #[test]
6162    fn disabled_by_config_the_sequence_can_never_leave_idle() {
6163        let marked = interrupt_task("marked");
6164        let next = advance_interrupt_tick(
6165            false,
6166            Interrupt::Idle,
6167            &["running".to_owned()],
6168            std::slice::from_ref(&marked),
6169        );
6170        assert_eq!(
6171            next,
6172            Interrupt::Idle,
6173            "an unmarked, unconfigured daemon must behave exactly as before"
6174        );
6175    }
6176
6177    #[test]
6178    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
6179        let state = Interrupt::Parking {
6180            parked: vec!["running".to_owned()],
6181            interrupt_task: "marked".to_owned(),
6182        };
6183        let candidates = vec![interrupt_task("marked"), task()];
6184        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6185        assert!(
6186            allowed.is_empty(),
6187            "nothing may dispatch - not even the interrupt task itself - \
6188             until the parked run has actually stopped"
6189        );
6190    }
6191
6192    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
6193    /// grow a special case for it: an urgent candidate that is not the
6194    /// interrupt task withholds exactly like an ordinary one for as long as
6195    /// the parked run it is racing has not actually left flight. A version
6196    /// of this feature once bypassed the gate for urgent candidates, on the
6197    /// theory that a genuinely separate concurrency lane could not collide
6198    /// with 75dd's own; it could, and did - the bypassed task dispatched
6199    /// alongside a run 75dd's own state machine had only *asked* to park,
6200    /// not yet confirmed gone, which is exactly the second run
6201    /// `Interrupt::Parking`'s own doc says must never happen. There is no
6202    /// tick during Parking/Running/Resuming where letting an extra
6203    /// candidate through is safe, urgent or not - the parked run may still
6204    /// be genuinely mid-call.
6205    #[test]
6206    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
6207        for state in [
6208            Interrupt::Parking {
6209                parked: vec!["running".to_owned()],
6210                interrupt_task: "marked".to_owned(),
6211            },
6212            Interrupt::Running {
6213                parked: vec!["running".to_owned()],
6214                interrupt_task: "marked".to_owned(),
6215            },
6216            Interrupt::Resuming {
6217                parked: vec!["running".to_owned()],
6218            },
6219        ] {
6220            let candidates = vec![
6221                interrupt_task("marked"),
6222                urgent_task("hot"),
6223                task_with_id("ordinary"),
6224            ];
6225            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
6226            assert!(
6227                !allowed.iter().any(|t| t.id == "hot"),
6228                "an urgent candidate must wait out the same gate as anything \
6229                 else while the run it would run alongside has not actually \
6230                 left flight, for state {state:?}: {allowed:?}"
6231            );
6232        }
6233    }
6234
6235    /// The one case where marking a task `--urgent` and `interrupt` at once
6236    /// is not redundant: once the interrupt sequence's own guaranteed
6237    /// resume/dispatch actually admits the task, it is unaffected by also
6238    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
6239    /// never on the urgent flag.
6240    #[test]
6241    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
6242        let state = Interrupt::Resuming {
6243            parked: vec!["hot".to_owned()],
6244        };
6245        let candidates = vec![urgent_task("hot"), task()];
6246        let allowed = interrupt_gate(&state, &[], candidates);
6247        assert_eq!(
6248            allowed.iter().filter(|t| t.id == "hot").count(),
6249            1,
6250            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
6251        );
6252    }
6253
6254    #[test]
6255    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
6256        let state = Interrupt::Parking {
6257            parked: vec!["running".to_owned()],
6258            interrupt_task: "marked".to_owned(),
6259        };
6260        let other = task();
6261        let candidates = vec![interrupt_task("marked"), other.clone()];
6262        let allowed = interrupt_gate(&state, &[], candidates);
6263        assert_eq!(allowed.len(), 1);
6264        assert_eq!(allowed[0].id, "marked");
6265    }
6266
6267    #[test]
6268    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
6269        let state = Interrupt::Running {
6270            parked: vec!["running".to_owned()],
6271            interrupt_task: "marked".to_owned(),
6272        };
6273        let candidates = vec![task(), task()];
6274        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
6275        assert!(allowed.is_empty());
6276    }
6277
6278    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
6279    /// sequence began (only reachable above the default
6280    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
6281    /// never both in the same tick, which is what "exactly one resume, no
6282    /// simultaneous run" actually requires structurally rather than by
6283    /// coincidence of how many ordinary slots happen to be free.
6284    #[test]
6285    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
6286        let state = Interrupt::Resuming {
6287            parked: vec!["a".to_owned(), "c".to_owned()],
6288        };
6289        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
6290        let allowed = interrupt_gate(&state, &[], candidates);
6291        assert_eq!(
6292            allowed.len(),
6293            1,
6294            "at most one candidate may be offered while resuming: {allowed:?}"
6295        );
6296        assert_eq!(allowed[0].id, "a");
6297    }
6298
6299    #[test]
6300    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
6301        let state = Interrupt::Resuming {
6302            parked: vec!["a".to_owned()],
6303        };
6304        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
6305        assert!(allowed.is_empty());
6306    }
6307
6308    /// The invariant the completion criteria ask for by name: across a whole
6309    /// simulated sequence, there is never a tick where the gate would let
6310    /// through both the parked run's resume and the interrupt task, and
6311    /// exactly one candidate resumes the instant the interrupt task's run
6312    /// ends - never zero, never more than one.
6313    #[test]
6314    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
6315        let running = task(); // id: whatever `Task::new` minted
6316        let marked = interrupt_task("marked");
6317
6318        let mut state = Interrupt::Idle;
6319        // Tick 1: `running` is in flight, `marked` becomes runnable.
6320        let in_flight = vec![running.id.clone()];
6321        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
6322        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
6323        assert!(gated.is_empty(), "still waiting on `running` to park");
6324
6325        // Tick 2: `running` parked and left flight; nothing dispatched yet.
6326        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
6327        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
6328        assert_eq!(
6329            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6330            vec!["marked"],
6331            "only the interrupt task may be offered to the dispatcher now"
6332        );
6333
6334        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
6335        state = advance_interrupt_tick(
6336            true,
6337            state,
6338            &["marked".to_owned()],
6339            std::slice::from_ref(&running),
6340        );
6341        let gated = interrupt_gate(
6342            &state,
6343            &["marked".to_owned()],
6344            vec![marked.clone(), running.clone()],
6345        );
6346        assert!(
6347            gated.is_empty(),
6348            "the parked run must not be offered back while the interrupt \
6349             task is still running"
6350        );
6351
6352        // Tick 4: `marked`'s run reached a terminal status and left flight.
6353        // A higher-priority ordinary task `other` is also runnable now - it
6354        // must not be let through instead of, or alongside, `running`.
6355        let other = task_with_id("other");
6356        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
6357        assert_eq!(
6358            state,
6359            Interrupt::Resuming {
6360                parked: vec![running.id.clone()]
6361            }
6362        );
6363        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
6364        assert_eq!(
6365            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6366            vec![running.id.as_str()],
6367            "exactly the parked run resumes - not the unrelated task, even \
6368             though it was offered first"
6369        );
6370
6371        // Tick 5: `running` is now in flight (dispatched from tick 4's
6372        // gate). Only now does the sequence end and ordinary dispatch fully
6373        // resume.
6374        state = advance_interrupt_tick(
6375            true,
6376            state,
6377            std::slice::from_ref(&running.id),
6378            std::slice::from_ref(&other),
6379        );
6380        assert_eq!(state, Interrupt::Idle);
6381        let gated = interrupt_gate(
6382            &state,
6383            std::slice::from_ref(&running.id),
6384            vec![other.clone()],
6385        );
6386        assert_eq!(
6387            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6388            vec![other.id.as_str()],
6389            "ordinary dispatch is unrestricted again"
6390        );
6391    }
6392
6393    #[test]
6394    fn every_run_status_settles_the_task_it_came_from() {
6395        // run status, resulting task status, attempts still standing after one
6396        let table = [
6397            (RunStatus::Merged, TaskStatus::Done, 1),
6398            (RunStatus::Ready, TaskStatus::Done, 1),
6399            (RunStatus::Stalled, TaskStatus::Failed, 0),
6400            (RunStatus::Blocked, TaskStatus::Failed, 1),
6401            (RunStatus::Failed, TaskStatus::Failed, 1),
6402            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
6403            (RunStatus::Prep, TaskStatus::Failed, 1),
6404            (RunStatus::Implementing, TaskStatus::Failed, 1),
6405            (RunStatus::Judging, TaskStatus::Failed, 1),
6406            (RunStatus::Deliberating, TaskStatus::Failed, 1),
6407            (RunStatus::Voting, TaskStatus::Failed, 1),
6408            (RunStatus::Reviewing, TaskStatus::Failed, 1),
6409            (RunStatus::Gating, TaskStatus::Failed, 1),
6410        ];
6411        for (run, want, attempts) in table {
6412            let mut t = task();
6413            t.start("20260902-000000-aaaa".to_owned());
6414            settle(
6415                &mut t,
6416                Verdict {
6417                    status: run,
6418                    left_pr: false,
6419                    parked: false,
6420                    quota_hit: matches!(run, RunStatus::Stalled),
6421                    no_viable_candidates: false,
6422                },
6423                "why",
6424                2,
6425            );
6426            assert_eq!(t.status, want, "task status after {}", label(run));
6427            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
6428        }
6429    }
6430
6431    #[test]
6432    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
6433        let mut stalled = task();
6434        stalled.start("20260902-000000-aaaa".to_owned());
6435        settle(
6436            &mut stalled,
6437            Verdict {
6438                status: RunStatus::Stalled,
6439                left_pr: false,
6440                parked: false,
6441                quota_hit: true,
6442                no_viable_candidates: false,
6443            },
6444            "quota",
6445            1,
6446        );
6447        assert_eq!(stalled.attempts, 0);
6448        assert!(
6449            stalled.status.runnable(),
6450            "a machine problem must leave the task in line"
6451        );
6452
6453        let mut blocked = task();
6454        blocked.start("20260902-000000-aaaa".to_owned());
6455        settle(
6456            &mut blocked,
6457            Verdict {
6458                status: RunStatus::Blocked,
6459                left_pr: false,
6460                parked: false,
6461                quota_hit: false,
6462                no_viable_candidates: false,
6463            },
6464            "findings open",
6465            1,
6466        );
6467        assert_eq!(blocked.attempts, 1);
6468        assert_eq!(
6469            blocked.status,
6470            TaskStatus::Held,
6471            "the last attempt hands the task to a human"
6472        );
6473    }
6474
6475    #[test]
6476    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
6477        // Attempts to spare: without the pull request this task would go
6478        // straight back in line and run the whole competition again.
6479        let mut delivered = task();
6480        delivered.start("20260903-080619-01c2".to_owned());
6481        settle(
6482            &mut delivered,
6483            Verdict {
6484                status: RunStatus::Blocked,
6485                left_pr: true,
6486                parked: false,
6487                quota_hit: false,
6488                no_viable_candidates: false,
6489            },
6490            "no check status",
6491            4,
6492        );
6493        assert_eq!(
6494            delivered.status,
6495            TaskStatus::Held,
6496            "a pull request waiting on CI or a person is not a retryable failure"
6497        );
6498        assert!(
6499            !delivered.status.runnable(),
6500            "the loop must not pick this task up again"
6501        );
6502        assert_eq!(
6503            delivered.last_error.as_deref(),
6504            Some("no check status"),
6505            "the operator needs to be told what the gate was waiting for"
6506        );
6507
6508        // The same status without a pull request is a plain failure, and with
6509        // attempts left it is retried.
6510        let mut empty_handed = task();
6511        empty_handed.start("20260903-080619-01c2".to_owned());
6512        settle(
6513            &mut empty_handed,
6514            Verdict {
6515                status: RunStatus::Blocked,
6516                left_pr: false,
6517                parked: false,
6518                quota_hit: false,
6519                no_viable_candidates: false,
6520            },
6521            "findings open",
6522            4,
6523        );
6524        assert_eq!(empty_handed.status, TaskStatus::Failed);
6525        assert!(empty_handed.status.runnable());
6526    }
6527
6528    #[test]
6529    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
6530        // Every candidate agreed, with evidence, that nothing belonged in the
6531        // worktree. That is not a confirmed success to close automatically -
6532        // a human still has to check the claim - and it is not an ordinary
6533        // failure either, so this settles exactly like a pull request nobody
6534        // merged yet: `Held`, same as `Blocked` with a PR.
6535        let mut noop = task();
6536        noop.start("20260912-131304-391f".to_owned());
6537        settle(
6538            &mut noop,
6539            Verdict {
6540                status: RunStatus::VerifiedNoop,
6541                left_pr: false,
6542                parked: false,
6543                quota_hit: false,
6544                no_viable_candidates: true,
6545            },
6546            "candidate A: already fixed by b32cfc4, on main",
6547            4,
6548        );
6549        assert_eq!(
6550            noop.status,
6551            TaskStatus::Held,
6552            "an unverified claim is a request for a human, not a failure"
6553        );
6554        assert!(
6555            !noop.status.runnable(),
6556            "the loop must not requeue this on the same unverified claim"
6557        );
6558        // `Task::release` resets attempts to zero the moment a human looks at
6559        // the evidence and lets it run again, so it does not matter here
6560        // whether the one attempt already spent stays spent - what matters is
6561        // that nothing retries this task unattended in the meantime.
6562        assert_eq!(noop.attempts, 1);
6563    }
6564
6565    #[test]
6566    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
6567        // Parking is the operator asking for the process back - to replace the
6568        // binary, most of all. The run's work is intact on disk, so this is
6569        // not a failed attempt, and charging for it would mean a few upgrades
6570        // could exhaust a budget meant for agents that misbehaved.
6571        let mut parked = task();
6572        parked.start("20260903-183634-2d98".to_owned());
6573        settle(
6574            &mut parked,
6575            Verdict {
6576                status: RunStatus::Implementing,
6577                left_pr: false,
6578                quota_hit: false,
6579                parked: true,
6580                no_viable_candidates: false,
6581            },
6582            "parked after `implementing`",
6583            2,
6584        );
6585        assert_eq!(parked.attempts, 0, "a park is refunded");
6586        assert!(
6587            parked.status.runnable(),
6588            "and the task stays in line so the next loop resumes its run"
6589        );
6590        assert_eq!(parked.status, TaskStatus::Parked);
6591        assert_eq!(
6592            parked.park_reason.as_deref(),
6593            Some("parked after `implementing`"),
6594            "the card says where it stopped"
6595        );
6596        assert_eq!(parked.last_error, None, "nothing failed");
6597
6598        // Without the park flag the same non-terminal status is what it always
6599        // was: `execute` returning mid-flight, which is a bug and spends an
6600        // attempt so a task cannot loop on it forever.
6601        let mut broken = task();
6602        broken.start("20260903-183634-2d98".to_owned());
6603        settle(
6604            &mut broken,
6605            Verdict {
6606                status: RunStatus::Implementing,
6607                left_pr: false,
6608                quota_hit: false,
6609                parked: false,
6610                no_viable_candidates: false,
6611            },
6612            "returned mid-flight",
6613            2,
6614        );
6615        assert_eq!(broken.attempts, 1);
6616    }
6617
6618    #[test]
6619    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
6620        // Run e633: quorum lost because two judges answered with the wrong
6621        // JSON shape, `quota: []`. Refunding that takes the bound off the
6622        // retry loop, and each retry pays for a fresh hour-long implement
6623        // wave before it can fail the same way.
6624        let mut flaky = task();
6625        flaky.start("20260903-123023-e633".to_owned());
6626        settle(
6627            &mut flaky,
6628            Verdict {
6629                status: RunStatus::Stalled,
6630                left_pr: false,
6631                parked: false,
6632                quota_hit: false,
6633                no_viable_candidates: false,
6634            },
6635            "verdict rests on 1 of 3 judges",
6636            2,
6637        );
6638        assert_eq!(
6639            flaky.attempts, 1,
6640            "flakiness spends an attempt, so `max_attempts` still bounds it"
6641        );
6642        assert!(flaky.status.runnable(), "and it is still worth retrying");
6643
6644        // The same status, lost to a rate limit, is the machine's fault.
6645        let mut limited = task();
6646        limited.start("20260903-123023-e633".to_owned());
6647        settle(
6648            &mut limited,
6649            Verdict {
6650                status: RunStatus::Stalled,
6651                left_pr: false,
6652                parked: false,
6653                quota_hit: true,
6654                no_viable_candidates: false,
6655            },
6656            "judge-2, judge-3 out of quota",
6657            2,
6658        );
6659        assert_eq!(limited.attempts, 0, "a quota window is refunded");
6660        assert!(limited.status.runnable());
6661
6662        // And the bound really binds: a task that keeps stalling on flakiness
6663        // reaches a human instead of running the roster forever.
6664        let mut worn = task();
6665        for _ in 0..2 {
6666            worn.release();
6667        }
6668        worn.start("20260903-123023-e633".to_owned());
6669        worn.attempts = 2;
6670        settle(
6671            &mut worn,
6672            Verdict {
6673                status: RunStatus::Stalled,
6674                left_pr: false,
6675                parked: false,
6676                quota_hit: false,
6677                no_viable_candidates: false,
6678            },
6679            "no quorum again",
6680            2,
6681        );
6682        assert_eq!(worn.status, TaskStatus::Held);
6683        assert!(!worn.status.runnable());
6684    }
6685
6686    #[test]
6687    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
6688        // The implement wave loses every seat to the same rate limit and
6689        // `after_implement` bails with nothing viable, which surfaces as
6690        // `Failed` rather than `Stalled`. That is the same machine fact the
6691        // `Stalled`-quota row already refunds, and must be refunded the same
6692        // way, or a quota outage quietly holds every task it touches instead
6693        // of leaving them in line for the reset.
6694        let mut wiped_out = task();
6695        wiped_out.start("20260907-025000-a1b2".to_owned());
6696        settle(
6697            &mut wiped_out,
6698            Verdict {
6699                status: RunStatus::Failed,
6700                left_pr: false,
6701                parked: false,
6702                quota_hit: true,
6703                no_viable_candidates: true,
6704            },
6705            "no candidate produced a change; nothing to judge",
6706            2,
6707        );
6708        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
6709        assert!(
6710            wiped_out.status.runnable(),
6711            "a machine problem must leave the task in line"
6712        );
6713
6714        // This is the exemption that must stay narrow: a candidate that did
6715        // produce a change, and then failed for some other reason, still
6716        // spends the attempt even though a seat elsewhere hit its quota.
6717        // Otherwise every ordinary failure that happens to share a run with
6718        // an unrelated rate limit would be refunded for free.
6719        let mut partial_progress = task();
6720        partial_progress.start("20260907-025500-c3d4".to_owned());
6721        settle(
6722            &mut partial_progress,
6723            Verdict {
6724                status: RunStatus::Failed,
6725                left_pr: false,
6726                parked: false,
6727                quota_hit: true,
6728                no_viable_candidates: false,
6729            },
6730            "gate failed on the winning candidate",
6731            2,
6732        );
6733        assert_eq!(
6734            partial_progress.attempts, 1,
6735            "a candidate that actually produced a change spends the attempt \
6736             even though some other seat hit its quota"
6737        );
6738        assert!(partial_progress.status.runnable());
6739    }
6740
6741    #[test]
6742    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
6743        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
6744        // disk, and that construction must reach the same conclusion as the
6745        // one `attempt` builds from a live run, or a crash at exactly the
6746        // wrong moment gives a recovered task a different policy than one a
6747        // daemon finished settling itself.
6748        let mut t = task();
6749        t.start("20260907-025000-a1b2".to_owned());
6750        let mut state = run_state(RunStatus::Failed);
6751        state.quota.push(QuotaLoss {
6752            seat: "cand-a".to_owned(),
6753            node: "implement".to_owned(),
6754            at: Timestamp::now(),
6755            reset: None,
6756        });
6757        assert!(
6758            state.viable().is_empty(),
6759            "no candidate was added, so nothing is viable"
6760        );
6761        reclaim(&mut t, Some(state), 2, "en");
6762        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
6763        assert!(t.status.runnable());
6764    }
6765
6766    #[test]
6767    fn a_held_task_is_never_offered_to_the_loop() {
6768        let dir = tempfile::tempdir().unwrap();
6769        let queue = Queue::at(dir.path().to_path_buf());
6770        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
6771            let mut t = task();
6772            t.id = format!("2026090{n}-000000-000{n}");
6773            t.priority = priority;
6774            queue.put(&mut t).unwrap();
6775        }
6776        let mut held = task();
6777        held.id = "20260909-000000-9999".to_owned();
6778        held.priority = 99;
6779        held.hold_machine(None);
6780        queue.put(&mut held).unwrap();
6781
6782        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
6783        assert_eq!(order.len(), 3);
6784        assert!(!order.contains(&held.id));
6785        assert_eq!(
6786            order.first().cloned(),
6787            queue.next_runnable().map(|t| t.id),
6788            "the loop's first candidate is exactly what the queue offers"
6789        );
6790        assert_eq!(
6791            order,
6792            vec![
6793                "20260902-000000-0002".to_owned(),
6794                "20260903-000000-0003".to_owned(),
6795                "20260901-000000-0001".to_owned(),
6796            ],
6797            "priority first, then oldest, so nothing starves"
6798        );
6799    }
6800
6801    #[test]
6802    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
6803        let dir = tempfile::tempdir().unwrap();
6804        let queue = Queue::at(dir.path().to_path_buf());
6805        let mut old = task();
6806        old.id = "20260101-000000-old0".to_owned();
6807        queue.put(&mut old).unwrap();
6808        let mut fresh = task();
6809        fresh.id = "20260101-000000-new0".to_owned();
6810        queue.put(&mut fresh).unwrap();
6811
6812        // No parseable pid at all, so age is the only signal there is to
6813        // check - unlike a real `Queue::claim`, which always names a real,
6814        // and therefore alive, pid this test cannot fake as dead.
6815        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
6816        std::thread::sleep(Duration::from_millis(60));
6817        let live = queue.claim(&fresh.id).unwrap();
6818
6819        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6820        assert_eq!(swept, vec![old.id.clone()]);
6821        assert!(
6822            queue.claim(&old.id).is_ok(),
6823            "an unparseable lock older than the threshold is swept"
6824        );
6825        assert!(
6826            queue.claim(&fresh.id).is_err(),
6827            "a live pid protects its lock regardless of age"
6828        );
6829        drop(live);
6830    }
6831
6832    #[test]
6833    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
6834        // The regression this guards: `sweep` now runs concurrently with
6835        // every attempt this daemon itself has spawned (see
6836        // `InFlightGuard`), not only between them the way a single
6837        // sequential loop once did. A run that legitimately outlives
6838        // `older_than` still has this very process's own live pid sitting in
6839        // its own lock file on every later sweep, and deciding by age alone
6840        // would delete that still-valid claim out from under the attempt
6841        // that holds it - which `reclaim_orphaned_running` would then read
6842        // as abandoned and hand to a second, competing attempt.
6843        let dir = tempfile::tempdir().unwrap();
6844        let queue = Queue::at(dir.path().to_path_buf());
6845        let mut t = task();
6846        t.id = "20260101-000000-live".to_owned();
6847        queue.put(&mut t).unwrap();
6848
6849        let claim = queue.claim(&t.id).unwrap();
6850        std::thread::sleep(Duration::from_millis(60));
6851
6852        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
6853        assert!(
6854            swept.is_empty(),
6855            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
6856        );
6857        assert!(
6858            queue.claim(&t.id).is_err(),
6859            "the lock still protects its task"
6860        );
6861        drop(claim);
6862    }
6863
6864    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
6865    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
6866    fn injected_dead_pid() -> u32 {
6867        std::process::id().checked_add(1).unwrap_or(1)
6868    }
6869
6870    #[test]
6871    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
6872        let dir = tempfile::tempdir().unwrap();
6873        let queue = Queue::at(dir.path().to_path_buf());
6874        let mut t = task();
6875        t.id = "20260101-000000-dead".to_owned();
6876        queue.put(&mut t).unwrap();
6877        let dead_pid = injected_dead_pid();
6878
6879        // Written directly rather than through `Queue::claim`, which would
6880        // stamp this test process's own very much alive pid and defeat the
6881        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
6882        // like moments after it died, not six hours later.
6883        std::fs::write(
6884            dir.path().join(format!("{}.lock", t.id)),
6885            dead_pid.to_string(),
6886        )
6887        .unwrap();
6888
6889        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6890            pid != dead_pid
6891        });
6892        assert_eq!(
6893            swept,
6894            vec![t.id.clone()],
6895            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
6896        );
6897        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
6898    }
6899
6900    #[test]
6901    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
6902        let dir = tempfile::tempdir().unwrap();
6903        let queue = Queue::at(dir.path().to_path_buf());
6904        let mut t = task();
6905        t.id = "20260101-000000-late".to_owned();
6906        queue.put(&mut t).unwrap();
6907        let dead_pid = injected_dead_pid();
6908
6909        // Tick one, standing in for the sweep `poll` already runs at
6910        // startup: nothing to find yet.
6911        assert!(
6912            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
6913            "nothing has claimed the task yet"
6914        );
6915
6916        // A second daemon claims the task and dies before it ever writes
6917        // `running`, well after this loop's own startup sweep already ran.
6918        std::fs::write(
6919            dir.path().join(format!("{}.lock", t.id)),
6920            dead_pid.to_string(),
6921        )
6922        .unwrap();
6923
6924        // Tick two, standing in for a poll long into this daemon's uptime:
6925        // the same function, called again, notices what only just appeared -
6926        // proving the sweep is not a one-shot startup check.
6927        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6928            pid != dead_pid
6929        });
6930        assert_eq!(swept, vec![t.id.clone()]);
6931    }
6932
6933    #[test]
6934    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
6935        // `reclaim_orphaned_running` looks up the task's last run, which
6936        // touches `run::home()`; the first call anywhere in this binary wins,
6937        // so this is a no-op if another test already pinned one, and either
6938        // way the run id below is never written under it.
6939        crate::run::pin_test_home();
6940        let dir = tempfile::tempdir().unwrap();
6941        let queue = Queue::at(dir.path().to_path_buf());
6942        let mut t = task();
6943        t.id = "20260101-000000-crsh".to_owned();
6944        t.status = TaskStatus::Running;
6945        t.attempts = 1;
6946        // No `run.json` behind this id: standing in for a run this test does
6947        // not need to make readable, since the point is the lock, not the
6948        // recovery table `reclaim` already has its own tests for.
6949        t.runs.push("20260904-000000-4043".to_owned());
6950        queue.put(&mut t).unwrap();
6951        let dead_pid = injected_dead_pid();
6952
6953        // The crashed daemon's own claim, naming a pid nothing on the
6954        // machine holds anymore.
6955        std::fs::write(
6956            dir.path().join(format!("{}.lock", t.id)),
6957            dead_pid.to_string(),
6958        )
6959        .unwrap();
6960
6961        // Before the lock is swept the task looks claimed, and
6962        // `reclaim_orphaned_running` must leave it alone - this is exactly
6963        // the bug: a `running` task stranded behind a dead daemon's lock,
6964        // invisible to the claim-as-proof check because the lock outlived
6965        // the process that wrote it.
6966        assert!(reclaim_orphaned_running(&queue, 2).is_empty());
6967        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6968
6969        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
6970            pid != dead_pid
6971        });
6972        assert_eq!(swept, vec![t.id.clone()]);
6973
6974        let reclaimed = reclaim_orphaned_running(&queue, 2);
6975        assert_eq!(reclaimed, vec![t.id.clone()]);
6976        let after = queue.get(&t.id).unwrap();
6977        assert_eq!(
6978            after.status,
6979            TaskStatus::Held,
6980            "no run.json to recover from, so a human is asked"
6981        );
6982        assert_eq!(
6983            after.runs,
6984            vec!["20260904-000000-4043".to_owned()],
6985            "the crashed run's id is kept as evidence, not discarded"
6986        );
6987    }
6988
6989    #[test]
6990    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
6991        let dir = tempfile::tempdir().unwrap();
6992        let queue = Queue::at(dir.path().to_path_buf());
6993        let mut t = task();
6994        t.id = "20260101-000000-unknown".to_owned();
6995        queue.put(&mut t).unwrap();
6996        let dead_pid = injected_dead_pid();
6997        std::fs::write(
6998            dir.path().join(format!("{}.lock", t.id)),
6999            dead_pid.to_string(),
7000        )
7001        .unwrap();
7002
7003        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
7004        assert!(swept.is_empty(), "an unknown pid must keep its lock");
7005        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
7006    }
7007
7008    fn run_state_in(status: RunStatus, language: &str) -> RunState {
7009        let mut s = run_state(status);
7010        s.config.graph.language = language.to_owned();
7011        s
7012    }
7013
7014    fn unstarted_verdict(status: RunStatus) -> Verdict {
7015        Verdict {
7016            status,
7017            left_pr: false,
7018            quota_hit: false,
7019            parked: false,
7020            no_viable_candidates: false,
7021        }
7022    }
7023
7024    #[test]
7025    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
7026        let mut t = task();
7027        t.attempts = 1;
7028        settle_in(
7029            &mut t,
7030            unstarted_verdict(RunStatus::AlreadyInBase),
7031            "already in main",
7032            1,
7033            phrases("en"),
7034        );
7035        assert_eq!(t.status, TaskStatus::Done);
7036        assert_eq!(t.attempts, 0);
7037    }
7038
7039    #[test]
7040    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
7041        let reason = |language: &str| {
7042            let mut t = task();
7043            settle_in(
7044                &mut t,
7045                unstarted_verdict(RunStatus::Judging),
7046                "boom",
7047                1,
7048                phrases(language),
7049            );
7050            t.last_error.or(t.hold_reason).unwrap_or_default()
7051        };
7052        assert!(
7053            reason("en").starts_with("the graph stopped at `"),
7054            "{}",
7055            reason("en")
7056        );
7057        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
7058        assert!(reason("日本語").contains("boom"));
7059        assert_eq!(reason("fr"), reason("en"));
7060    }
7061
7062    #[test]
7063    fn describe_follows_the_run_language_and_keeps_the_run_id() {
7064        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
7065        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
7066        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
7067        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
7068        assert!(ja.contains("[run "), "{ja}");
7069        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
7070        assert!(ended.starts_with("run 終了: "), "{ended}");
7071        let mut de = run_state_in(RunStatus::Failed, "de");
7072        let mut en = run_state_in(RunStatus::Failed, "en");
7073        de.id = "same".to_owned();
7074        en.id = "same".to_owned();
7075        assert_eq!(describe(&de), describe(&en));
7076    }
7077
7078    #[test]
7079    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
7080        use crate::handover::Refused;
7081        let cases = [
7082            Refused::Foreign {
7083                branch: "b".into(),
7084                path: "/w/x".into(),
7085                why: "made by hand".into(),
7086            },
7087            Refused::Unsafe {
7088                branch: "b".into(),
7089                path: "/w/x".into(),
7090                why: "its worktree has uncommitted changes (a.rs)".into(),
7091            },
7092            Refused::ReleaseFailed {
7093                branch: "b".into(),
7094                path: "/w/x".into(),
7095                run: "ab12".into(),
7096            },
7097        ];
7098        for r in &cases {
7099            let en = (phrases("en").handover_refused)(r);
7100            assert_eq!(en, r.to_string());
7101            let ja = (phrases("ja").handover_refused)(r);
7102            assert!(
7103                !ja.contains("is checked out") && !ja.contains("try again"),
7104                "{ja}"
7105            );
7106            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
7107            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
7108                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
7109            }
7110        }
7111        assert!(phrases("en").handover_hint.contains("release the task"));
7112        assert!(phrases("ja").handover_hint.contains("解放"));
7113    }
7114
7115    #[test]
7116    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
7117        let build = |lang: &str| {
7118            let mut s = run_state_in(RunStatus::Blocked, lang);
7119            s.id = "same".to_owned();
7120            s.config.graph.review_rounds = 3;
7121            let mut r = review_round(3);
7122            r.expected = 3;
7123            r.answered = 1;
7124            s.reviews.push(r);
7125            s.event(
7126                "review",
7127                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
7128            );
7129            s
7130        };
7131        let en = describe(&build("en"));
7132        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
7133        let ja = describe(&build("ja"));
7134        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
7135        assert!(!ja.contains("never answered"), "{ja}");
7136        assert!(ja.contains("[run "), "{ja}");
7137
7138        // An incomplete panel whose verification failed is a different stop:
7139        // the real event must survive in ja too.
7140        let mut failed = build("ja");
7141        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
7142            command: "cargo test".to_owned(),
7143            code: Some(1),
7144            output_tail: String::new(),
7145            duration_ms: 0,
7146            resource_blocked: false,
7147        });
7148        failed.event("review", "stopped; e2e failed: cargo test");
7149        let ja = describe(&failed);
7150        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
7151        assert!(!ja.contains("席のレビュアー"), "{ja}");
7152    }
7153
7154    #[test]
7155    fn refusals_and_recovery_prose_follow_the_language() {
7156        let t = held_task_with("r1");
7157        let q = action_question(
7158            "r1",
7159            ask::ChoiceAction::Resume {
7160                run: "r1".to_owned(),
7161            },
7162        );
7163        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
7164            ActionDecision::Refuse(s) => s,
7165            other => panic!("{other:?}"),
7166        };
7167        assert!(refuse(phrases("en")).contains("could not be read: gone"));
7168        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
7169        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
7170
7171        let mut held = task();
7172        reclaim(&mut held, None, 2, "ja");
7173        assert!(held.hold_reason.unwrap().contains("保留にしました"));
7174        let mut held = task();
7175        reclaim(&mut held, None, 2, "xx");
7176        assert!(held.hold_reason.unwrap().contains("held for a human"));
7177    }
7178
7179    fn run_state(status: RunStatus) -> RunState {
7180        let mut state = RunState::new(
7181            PathBuf::from("/repo"),
7182            "main".to_owned(),
7183            "abc1234def".to_owned(),
7184            "add retries".to_owned(),
7185            Config::default(),
7186        );
7187        state.status = status;
7188        state
7189    }
7190
7191    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
7192        Candidate {
7193            index: 0,
7194            label,
7195            agent: "claude".to_owned(),
7196            branch: format!("magi/x/{label}"),
7197            worktree: PathBuf::from("/repo"),
7198            summary: summary.to_owned(),
7199            stat: String::new(),
7200            files: 0,
7201            commits: usize::from(!empty),
7202            empty,
7203            failed: failed.map(str::to_owned),
7204            verified_noop: None,
7205            duration_ms: 0,
7206            folded: false,
7207        }
7208    }
7209
7210    #[test]
7211    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
7212        let mut state = run_state(RunStatus::Blocked);
7213        state.gate = vec![
7214            CommandOutcome {
7215                command: "cargo make check".to_owned(),
7216                code: Some(0),
7217                output_tail: "ok".to_owned(),
7218                duration_ms: 0,
7219                resource_blocked: false,
7220            },
7221            CommandOutcome {
7222                command: "cargo test".to_owned(),
7223                code: Some(101),
7224                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
7225                duration_ms: 0,
7226                resource_blocked: false,
7227            },
7228        ];
7229        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
7230        assert!(d.contains("cargo test"), "{d}");
7231        assert!(
7232            !d.contains("cargo make check"),
7233            "a passing check is not a diagnostic: {d}"
7234        );
7235        assert!(d.contains("assertion failed"), "{d}");
7236    }
7237
7238    #[test]
7239    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
7240        let mut state = run_state(RunStatus::Blocked);
7241        state.event(
7242            "land",
7243            "stopped: the fixer produced no commit while 2 check(s) were failing \
7244             (build, lint); stopping instead of looping on an unchanged tree",
7245        );
7246        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
7247        assert!(d.contains("build"), "{d}");
7248        assert!(d.contains("lint"), "{d}");
7249        assert!(d.contains("fixer produced no commit"), "{d}");
7250    }
7251
7252    #[test]
7253    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
7254        // `describe`'s output becomes `Task::last_error` verbatim, and the
7255        // phone renders that in the same alarm-styled box an ordinary
7256        // failure gets. A bare `verified_noop` there would read exactly like
7257        // the failure this status exists to be told apart from.
7258        let state = run_state(RunStatus::VerifiedNoop);
7259        let d = describe(&state);
7260        assert!(
7261            d.contains("agent-verified no-op"),
7262            "expected the display label, not the wire spelling: {d}"
7263        );
7264        assert!(!d.contains("verified_noop"), "{d}");
7265    }
7266
7267    #[test]
7268    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
7269        // The whole point of the feature: a run held as "no candidate produced
7270        // a change" can mean the implementer actually finished the task and
7271        // only left a clean local tree behind - see AGENTS.md on this exact
7272        // failure mode. The diagnostic has to carry what the agent actually
7273        // said, not just the fact that nothing was there to judge.
7274        let mut state = run_state(RunStatus::Failed);
7275        state.candidates = vec![candidate(
7276            'A',
7277            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
7278            true,
7279            None,
7280        )];
7281        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
7282        assert!(d.contains("candidate A"), "{d}");
7283        assert!(d.contains("tagged v1.2.3"), "{d}");
7284    }
7285
7286    #[test]
7287    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
7288        let mut state = run_state(RunStatus::Failed);
7289        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
7290        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
7291        assert!(d.contains("candidate A"), "{d}");
7292        assert!(d.contains("agent timed out"), "{d}");
7293    }
7294
7295    #[test]
7296    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
7297        // A viable candidate existed, the gate never ran, and nothing land
7298        // said matches - `Task::last_error` is left to explain this one alone.
7299        let mut state = run_state(RunStatus::Failed);
7300        state.candidates = vec![candidate('A', "did the work", false, None)];
7301        assert!(diagnostic(&state).is_none());
7302    }
7303
7304    #[test]
7305    fn diagnostic_is_bounded_however_much_a_run_printed() {
7306        let mut state = run_state(RunStatus::Blocked);
7307        state.gate = vec![
7308            CommandOutcome {
7309                command: "cargo test".to_owned(),
7310                code: Some(101),
7311                output_tail: "x".repeat(50_000),
7312                duration_ms: 0,
7313                resource_blocked: false,
7314            },
7315            CommandOutcome {
7316                command: "cargo clippy".to_owned(),
7317                code: Some(1),
7318                output_tail: "y".repeat(50_000),
7319                duration_ms: 0,
7320                resource_blocked: false,
7321            },
7322        ];
7323        state.candidates = vec![
7324            candidate('A', &"z".repeat(50_000), true, None),
7325            candidate('B', &"w".repeat(50_000), true, None),
7326        ];
7327        let d = diagnostic(&state).expect("plenty here to diagnose");
7328        assert!(
7329            d.len() <= DIAGNOSTIC_MAX,
7330            "diagnostic grew to {} bytes, unbounded",
7331            d.len()
7332        );
7333    }
7334
7335    #[test]
7336    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
7337        let mut state = run_state(RunStatus::Blocked);
7338        state.gate = vec![CommandOutcome {
7339            command: "cargo test".to_owned(),
7340            code: Some(101),
7341            output_tail: "assertion failed".to_owned(),
7342            duration_ms: 0,
7343            resource_blocked: false,
7344        }];
7345        let verdict = Verdict {
7346            status: RunStatus::Blocked,
7347            left_pr: false,
7348            quota_hit: false,
7349            parked: false,
7350            no_viable_candidates: false,
7351        };
7352
7353        // Attempt one of two still has a retry coming: no diagnostic yet, the
7354        // task is going to run again and this run's evidence would go stale.
7355        let mut t = task();
7356        t.start("run-1".to_owned());
7357        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7358        assert_eq!(t.status, TaskStatus::Failed);
7359        assert!(t.diagnostic.is_none());
7360
7361        // Attempt two exhausts the budget: now it is held, and the
7362        // diagnostic is what `magi task show` has to say more than one line.
7363        t.start("run-2".to_owned());
7364        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
7365        assert_eq!(t.status, TaskStatus::Held);
7366        let d = t.diagnostic.expect("a held task must carry its diagnostic");
7367        assert!(d.contains("cargo test"), "{d}");
7368    }
7369
7370    #[test]
7371    fn a_held_task_names_the_open_question_it_is_waiting_on() {
7372        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
7373        // `magi ask` question settled Held with `hold_reason: null`, so the
7374        // notification said nothing actionable. `note_open_question` should
7375        // append the question id to whatever `handed_off` already wrote.
7376        crate::run::pin_test_home();
7377        let home = crate::run::home();
7378        let state = run_state(RunStatus::VerifiedNoop);
7379        let mut q = ask::Question::new(
7380            state.id.clone(),
7381            "implement".to_owned(),
7382            "impl-A".to_owned(),
7383            "is this really a no-op?".to_owned(),
7384            String::new(),
7385            Vec::new(),
7386        );
7387        Questions::at(home.join("questions")).put(&mut q).unwrap();
7388
7389        let verdict = Verdict {
7390            status: RunStatus::VerifiedNoop,
7391            left_pr: false,
7392            quota_hit: false,
7393            parked: false,
7394            no_viable_candidates: false,
7395        };
7396        let mut t = task();
7397        t.start(state.id.clone());
7398        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7399
7400        assert_eq!(t.status, TaskStatus::Held);
7401        let reason = t.hold_reason.expect("a held task must record why");
7402        assert!(
7403            reason.starts_with("run ended agent-verified no-op"),
7404            "the original settle reason must survive unchanged: {reason}"
7405        );
7406        assert!(
7407            reason.contains(q.short()),
7408            "the open question's id must be named so the notice is actionable: {reason}"
7409        );
7410    }
7411
7412    #[test]
7413    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
7414        crate::run::pin_test_home();
7415        let state = run_state(RunStatus::VerifiedNoop);
7416
7417        let verdict = Verdict {
7418            status: RunStatus::VerifiedNoop,
7419            left_pr: false,
7420            quota_hit: false,
7421            parked: false,
7422            no_viable_candidates: false,
7423        };
7424        let mut t = task();
7425        t.start(state.id.clone());
7426        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
7427
7428        assert_eq!(t.status, TaskStatus::Held);
7429        assert_eq!(
7430            t.hold_reason.as_deref(),
7431            Some("run ended agent-verified no-op"),
7432            "nothing to append when the question was already answered or never asked"
7433        );
7434    }
7435
7436    #[test]
7437    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
7438        crate::run::pin_test_home();
7439        let mut first = run_state(RunStatus::Blocked);
7440        first.id = "20260101-000000-sup1".to_owned();
7441        first.save().unwrap();
7442        let mut second = run_state(RunStatus::Merged);
7443        second.id = "20260101-000000-sup2".to_owned();
7444        second.save().unwrap();
7445
7446        let mut t = task();
7447        t.runs = vec![first.id.clone(), second.id.clone()];
7448        t.status = TaskStatus::Done;
7449
7450        supersede_prior_runs(&t, &crate::run::home());
7451
7452        assert_eq!(
7453            RunState::load(&first.id).unwrap().status,
7454            RunStatus::Superseded,
7455            "the first attempt's Blocked no longer needs anyone's attention"
7456        );
7457        assert_eq!(
7458            RunState::load(&second.id).unwrap().status,
7459            RunStatus::Merged,
7460            "the run that actually succeeded is left exactly as it was"
7461        );
7462    }
7463
7464    #[test]
7465    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
7466        // `is_working_on` alone only proves a *daemon* claim; a `magi run
7467        // --resume` invoked by hand outside the daemon never touches
7468        // `daemon.json` at all, so it would look identical to a genuinely
7469        // idle run without also consulting `RunState::liveness`, which reads
7470        // this run's own recorded `driver_pid` instead.
7471        crate::run::pin_test_home();
7472        let mut first = run_state(RunStatus::Blocked);
7473        first.id = "20260101-000000-sup9".to_owned();
7474        // This test process's own pid: guaranteed alive without needing a
7475        // real second process or daemon.
7476        first.driver_pid = Some(std::process::id());
7477        first.driver_started_at = Some(
7478            crate::proc::process_started_at(std::process::id())
7479                .expect("this test process's own start time must be queryable"),
7480        );
7481        first.save().unwrap();
7482        let mut second = run_state(RunStatus::Merged);
7483        second.id = "20260101-000000-supa".to_owned();
7484        second.save().unwrap();
7485
7486        let mut t = task();
7487        t.runs = vec![first.id.clone(), second.id.clone()];
7488        t.status = TaskStatus::Done;
7489
7490        supersede_prior_runs(&t, &crate::run::home());
7491
7492        assert_eq!(
7493            RunState::load(&first.id).unwrap().status,
7494            RunStatus::Blocked,
7495            "a live driver_pid means something is still actually working this run, \
7496             even though no daemon claims it - rewriting under it would just be \
7497             undone the next time that process saves"
7498        );
7499    }
7500
7501    #[test]
7502    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
7503        // The first resweep must skip a still-live attempt exactly like
7504        // `supersede_prior_runs` itself does; a later resweep, once that
7505        // process is no longer actually driving it, is what closes the gap
7506        // `supersede_prior_runs` alone leaves - a task only ever reaches
7507        // `Done` once, so nothing else would ever look at this run again.
7508        let dir = tempfile::tempdir().unwrap();
7509        let home = dir.path().to_path_buf();
7510        let queue = Queue::at(dir.path().join("queue"));
7511
7512        let mut first = run_state(RunStatus::Blocked);
7513        first.id = "20260101-000000-supd".to_owned();
7514        first.driver_pid = Some(std::process::id());
7515        first.driver_started_at = Some(
7516            crate::proc::process_started_at(std::process::id())
7517                .expect("this test process's own start time must be queryable"),
7518        );
7519        first.save_under(&home).unwrap();
7520        let mut second = run_state(RunStatus::Merged);
7521        second.id = "20260101-000000-supe".to_owned();
7522        second.save_under(&home).unwrap();
7523
7524        let mut t = task();
7525        t.runs = vec![first.id.clone(), second.id.clone()];
7526        t.status = TaskStatus::Done;
7527        queue.put(&mut t).unwrap();
7528
7529        resweep_superseded_attempts(&queue, &home);
7530        assert_eq!(
7531            RunState::load_under(&first.id, &home).unwrap().status,
7532            RunStatus::Blocked,
7533            "still live on the first pass, so still untouched"
7534        );
7535
7536        // Stand in for the manual process no longer being the one driving
7537        // this run: same pid (this test process really is still alive), but
7538        // an identity marker that no longer matches it - see
7539        // `RunState::liveness`'s own doc for why a mismatched
7540        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
7541        let mut stale = RunState::load_under(&first.id, &home).unwrap();
7542        stale.driver_started_at = Some("1".to_owned());
7543        stale.save_under(&home).unwrap();
7544
7545        resweep_superseded_attempts(&queue, &home);
7546        assert_eq!(
7547            RunState::load_under(&first.id, &home).unwrap().status,
7548            RunStatus::Superseded,
7549            "the second pass catches up what the first one correctly skipped"
7550        );
7551    }
7552
7553    #[test]
7554    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
7555        crate::run::pin_test_home();
7556        let mut first = run_state(RunStatus::Blocked);
7557        first.id = "20260101-000000-sup3".to_owned();
7558        first.save().unwrap();
7559        let mut second = run_state(RunStatus::Blocked);
7560        second.id = "20260101-000000-sup4".to_owned();
7561        second.save().unwrap();
7562
7563        let mut t = task();
7564        t.runs = vec![first.id.clone(), second.id.clone()];
7565        // Still retrying: nothing about this task's story is settled yet, so
7566        // neither Blocked run may be relabelled, even though a later attempt
7567        // already exists.
7568        t.status = TaskStatus::Failed;
7569
7570        supersede_prior_runs(&t, &crate::run::home());
7571
7572        assert_eq!(
7573            RunState::load(&first.id).unwrap().status,
7574            RunStatus::Blocked
7575        );
7576        assert_eq!(
7577            RunState::load(&second.id).unwrap().status,
7578            RunStatus::Blocked
7579        );
7580    }
7581
7582    #[test]
7583    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
7584        // `magi task done` (or the API's equivalent) can close a task with no
7585        // run of its own ever having succeeded - there is nothing here that
7586        // counts as "the attempt that finished it", so nothing is rewritten.
7587        crate::run::pin_test_home();
7588        let mut first = run_state(RunStatus::Blocked);
7589        first.id = "20260101-000000-sup5".to_owned();
7590        first.save().unwrap();
7591
7592        let mut t = task();
7593        t.runs = vec![first.id.clone()];
7594        t.status = TaskStatus::Done;
7595
7596        supersede_prior_runs(&t, &crate::run::home());
7597
7598        assert_eq!(
7599            RunState::load(&first.id).unwrap().status,
7600            RunStatus::Blocked,
7601            "a single-attempt task has no earlier run to supersede"
7602        );
7603    }
7604
7605    #[test]
7606    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
7607        // `magi task done` (or the web/conductor equivalents) can close a
7608        // task in any status, including one whose *last* recorded attempt is
7609        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
7610        // never watched, say. `runs.last()` being `Done`-adjacent is not
7611        // proof it actually succeeded, so nothing earlier may be relabelled
7612        // on its say-so alone.
7613        crate::run::pin_test_home();
7614        let mut first = run_state(RunStatus::Blocked);
7615        first.id = "20260101-000000-supb".to_owned();
7616        first.save().unwrap();
7617        let mut second = run_state(RunStatus::Failed);
7618        second.id = "20260101-000000-supc".to_owned();
7619        second.save().unwrap();
7620
7621        let mut t = task();
7622        t.runs = vec![first.id.clone(), second.id.clone()];
7623        t.status = TaskStatus::Done;
7624
7625        supersede_prior_runs(&t, &crate::run::home());
7626
7627        assert_eq!(
7628            RunState::load(&first.id).unwrap().status,
7629            RunStatus::Blocked,
7630            "the task's last attempt never landed, so there is nothing here \
7631             actually superseding it"
7632        );
7633    }
7634
7635    #[test]
7636    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
7637        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
7638        // to look" - `Failed` and `VerifiedNoop` are already their own
7639        // terminal answers and must not be relabelled into a third one.
7640        crate::run::pin_test_home();
7641        let mut failed = run_state(RunStatus::Failed);
7642        failed.id = "20260101-000000-sup6".to_owned();
7643        failed.save().unwrap();
7644        let mut noop = run_state(RunStatus::VerifiedNoop);
7645        noop.id = "20260101-000000-sup7".to_owned();
7646        noop.save().unwrap();
7647        let mut winner = run_state(RunStatus::Ready);
7648        winner.id = "20260101-000000-sup8".to_owned();
7649        winner.save().unwrap();
7650
7651        let mut t = task();
7652        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
7653        t.status = TaskStatus::Done;
7654
7655        supersede_prior_runs(&t, &crate::run::home());
7656
7657        assert_eq!(
7658            RunState::load(&failed.id).unwrap().status,
7659            RunStatus::Failed
7660        );
7661        assert_eq!(
7662            RunState::load(&noop.id).unwrap().status,
7663            RunStatus::VerifiedNoop
7664        );
7665    }
7666
7667    fn approval_question(run: &str) -> ask::Question {
7668        ask::Question::new(
7669            run.to_owned(),
7670            land::APPROVAL_NODE.to_owned(),
7671            "land".to_owned(),
7672            "merge?".to_owned(),
7673            String::new(),
7674            vec!["merge".to_owned(), "hold".to_owned()],
7675        )
7676    }
7677
7678    #[test]
7679    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
7680        crate::run::pin_test_home();
7681        let mut state = run_state(RunStatus::Landing);
7682        state.id = "20260101-000000-fre1".to_owned();
7683        state.parked = true;
7684        state.save().unwrap();
7685        ask::Questions::open()
7686            .put(&mut approval_question(&state.id))
7687            .unwrap();
7688
7689        let mut t = task();
7690        t.runs.push(state.id.clone());
7691        assert_eq!(
7692            land_resume_state(&t),
7693            LandResume::StillWaiting,
7694            "nobody has answered and the timeout has not passed"
7695        );
7696    }
7697
7698    #[test]
7699    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
7700        crate::run::pin_test_home();
7701        let mut state = run_state(RunStatus::Gating);
7702        state.id = "20260101-000000-gt01".to_owned();
7703        state.parked = true;
7704        state.config.graph.answer_timeout = 60;
7705        state.github_text = Some(crate::run::GithubTextAsk {
7706            rewrite: None,
7707            fingerprint: "f".into(),
7708            title: true,
7709            body: false,
7710            categories: vec!["title-language".into()],
7711            question: None,
7712            asks: 1,
7713            resolved: false,
7714            chosen_title: None,
7715            choice: None,
7716        });
7717        state.save().unwrap();
7718        let store = ask::Questions::open();
7719        let mut q = ask::Question::new(
7720            state.id.clone(),
7721            crate::github_text::ASK_NODE.to_owned(),
7722            crate::github_text::ASK_SEAT.to_owned(),
7723            "s".into(),
7724            String::new(),
7725            vec!["use fallback".into()],
7726        );
7727        store.put(&mut q).unwrap();
7728        let mut t = task();
7729        t.runs.push(state.id.clone());
7730        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
7731        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7732        store.put(&mut q).unwrap();
7733        assert_eq!(land_resume_state(&t), LandResume::Ready);
7734        assert!(!store.get(&q.id).unwrap().status.open());
7735        // Once decided, a parked run is an ordinary candidate again.
7736        state.github_text.as_mut().unwrap().resolved = true;
7737        state.save().unwrap();
7738        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
7739    }
7740
7741    #[test]
7742    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
7743        // `ask::ask_and_wait`'s own deadline used to retire a question
7744        // nobody answered; land's approval bypasses that wait (see
7745        // `land::approval_gate`), so this is now the only place
7746        // `graph.answer_timeout` is enforced for a land approval at all.
7747        crate::run::pin_test_home();
7748        let mut state = run_state(RunStatus::Landing);
7749        state.id = "20260101-000000-exp1".to_owned();
7750        state.parked = true;
7751        state.config.graph.answer_timeout = 60;
7752        state.save().unwrap();
7753
7754        let store = ask::Questions::open();
7755        let mut q = approval_question(&state.id);
7756        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
7757        store.put(&mut q).unwrap();
7758
7759        let mut t = task();
7760        t.runs.push(state.id.clone());
7761        assert_eq!(
7762            land_resume_state(&t),
7763            LandResume::Ready,
7764            "an expired question must not be waited on forever"
7765        );
7766
7767        let after = store.get(&q.id).unwrap();
7768        assert!(
7769            !after.status.open(),
7770            "the question is abandoned, not silently ignored"
7771        );
7772        assert!(
7773            after.resolution().is_none(),
7774            "an abandoned question is not read as a decision"
7775        );
7776    }
7777
7778    #[test]
7779    fn reclaim_settles_a_running_task_against_its_last_run() {
7780        let mut t = task();
7781        t.start("20260904-000000-4043".to_owned());
7782        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
7783        assert_eq!(
7784            t.status,
7785            TaskStatus::Done,
7786            "a run that actually finished must not stay `running` forever"
7787        );
7788    }
7789
7790    #[test]
7791    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
7792        let mut t = task();
7793        t.start("20260904-000000-4043".to_owned());
7794        t.last_error = Some("earlier trouble".to_owned());
7795        let mut state = run_state(RunStatus::Judging);
7796        state.parked = true;
7797        reclaim(&mut t, Some(state), 1, "en");
7798        assert_eq!(t.status, TaskStatus::Parked);
7799        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
7800        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7801        assert!(t.park_reason.is_some());
7802        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
7803        assert!(!t.fresh_start);
7804        assert!(t.status.runnable());
7805    }
7806
7807    #[test]
7808    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
7809        let mut t = task();
7810        t.start("20260904-000000-4043".to_owned());
7811        t.last_error = Some("earlier trouble".to_owned());
7812        settle(
7813            &mut t,
7814            Verdict {
7815                status: RunStatus::Judging,
7816                left_pr: false,
7817                quota_hit: false,
7818                parked: true,
7819                no_viable_candidates: false,
7820            },
7821            "parked after `judging`",
7822            1,
7823        );
7824        assert_eq!(t.status, TaskStatus::Parked);
7825        assert_eq!(t.attempts, 0);
7826        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
7827        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
7828        assert_eq!(t.schema, crate::queue::SCHEMA);
7829        assert!(
7830            crate::notices::task_held(&t).is_none(),
7831            "a park is not news"
7832        );
7833        t.start("20260904-000000-4043".to_owned());
7834        assert_eq!(t.park_reason, None);
7835    }
7836
7837    #[test]
7838    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
7839        // A blocked run with attempts left goes back to `Failed`, exactly as
7840        // it would from `attempt` itself - `reclaim` must not invent a second
7841        // policy for a task a daemon merely stopped without reporting.
7842        let mut t = task();
7843        t.start("20260904-000000-4043".to_owned());
7844        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
7845        assert_eq!(t.status, TaskStatus::Failed);
7846        assert!(t.status.runnable());
7847    }
7848
7849    #[test]
7850    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
7851        let mut t = task();
7852        t.start("20260904-000000-4043".to_owned());
7853        assert_eq!(t.attempts, 1);
7854        let mut run = run_state(RunStatus::Implementing);
7855        run.id = "20260904-000000-4043".to_owned();
7856        run.begin_pass();
7857        let cause = crate::run::ParkCause::Upgrade {
7858            from: "0.121.0".to_owned(),
7859            to: Some("0.121.1".to_owned()),
7860        };
7861        run.end_pass_parked(cause.clone());
7862        run.parked = true;
7863        let verdict = Verdict {
7864            status: run.status,
7865            left_pr: false,
7866            quota_hit: false,
7867            parked: true,
7868            no_viable_candidates: false,
7869        };
7870        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
7871        assert_eq!(t.attempts, 0);
7872        assert_eq!(t.passes.len(), 1);
7873        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7874        assert_eq!(t.passes[0].parked, Some(cause));
7875        assert_eq!(t.passes[0].pass_index, 0);
7876
7877        // A resumed pass that then fails spends its attempt, and the earlier
7878        // pass's entry is untouched.
7879        t.start("20260904-000000-4043".to_owned());
7880        run.begin_pass();
7881        run.status = RunStatus::Failed;
7882        let verdict = Verdict {
7883            status: RunStatus::Failed,
7884            left_pr: false,
7885            quota_hit: false,
7886            parked: false,
7887            no_viable_candidates: false,
7888        };
7889        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
7890        assert_eq!(t.passes.len(), 2);
7891        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7892        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
7893        assert_eq!(t.passes[1].pass_index, 1);
7894        assert_eq!(t.attempts, 1);
7895    }
7896
7897    #[test]
7898    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
7899        let mut t = task();
7900        t.start("20260904-000000-4043".to_owned());
7901        reclaim(&mut t, None, 2, "en");
7902        assert_eq!(t.status, TaskStatus::Held);
7903        assert!(
7904            t.last_error
7905                .as_deref()
7906                .is_some_and(|e| e.contains("running")),
7907            "the operator needs to know why this task was held"
7908        );
7909    }
7910
7911    #[test]
7912    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
7913        let dir = tempfile::tempdir().unwrap();
7914        let queue = Queue::at(dir.path().to_path_buf());
7915
7916        // No run recorded, so this never has to touch `RunState::load`.
7917        let mut orphaned = task();
7918        orphaned.id = "20260904-000000-orph".to_owned();
7919        orphaned.status = TaskStatus::Running;
7920        orphaned.attempts = 1;
7921        queue.put(&mut orphaned).unwrap();
7922
7923        let mut alive = task();
7924        alive.id = "20260904-000000-live".to_owned();
7925        alive.status = TaskStatus::Running;
7926        alive.attempts = 1;
7927        queue.put(&mut alive).unwrap();
7928        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
7929
7930        let mut queued = task();
7931        queued.id = "20260904-000000-wait".to_owned();
7932        queue.put(&mut queued).unwrap();
7933
7934        let reclaimed = reclaim_orphaned_running(&queue, 2);
7935        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
7936
7937        assert_eq!(
7938            queue.get(&orphaned.id).unwrap().status,
7939            TaskStatus::Held,
7940            "nothing was driving it and there was no run to recover"
7941        );
7942        assert_eq!(
7943            queue.get(&alive.id).unwrap().status,
7944            TaskStatus::Running,
7945            "a live claim must protect the task it belongs to"
7946        );
7947        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
7948    }
7949
7950    /// Read a run.json back from an explicit `home`, the same way
7951    /// `reclaim_abandoned_runs` itself does - never through the
7952    /// process-global `RunState::load`, which this test's own `home` (an
7953    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
7954    /// use at all.
7955    fn read_run_under(home: &Path, id: &str) -> RunState {
7956        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
7957        serde_json::from_str(&body).unwrap()
7958    }
7959
7960    #[test]
7961    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
7962        let dir = tempfile::tempdir().unwrap();
7963        let home = dir.path().to_path_buf();
7964        let now = Timestamp::now();
7965        let overrun_seat = || crate::run::ActiveSeat {
7966            node: "implement".to_owned(),
7967            started_at: now - jiff::SignedDuration::new(21_000, 0),
7968            timeout_secs: 3_600,
7969            attempt: 0,
7970            task: None,
7971            command: None,
7972            index: None,
7973            total: None,
7974        };
7975
7976        let mut dead = run_state(RunStatus::Implementing);
7977        dead.id = "20260101-000000-dead".to_owned();
7978        dead.active.insert("impl-A".to_owned(), overrun_seat());
7979        // A `driver_pid` the injected query below confirms gone outright —
7980        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
7981        dead.driver_pid = Some(4242);
7982        dead.save_under(&home).unwrap();
7983
7984        // Same shape, but a live daemon's heartbeat names it: must be left
7985        // exactly alone, however far past its own timeout the seat sits.
7986        let mut alive = run_state(RunStatus::Implementing);
7987        alive.id = "20260101-000000-aliv".to_owned();
7988        alive.active.insert("impl-A".to_owned(), overrun_seat());
7989        alive.save_under(&home).unwrap();
7990        let mut status = Status::new();
7991        status.current = vec![Current {
7992            task: "20260101-000000-task".to_owned(),
7993            run: alive.id.clone(),
7994        }];
7995        write_status_to(&home.join("daemon.json"), &status).unwrap();
7996
7997        // The abandoned seat left an open question behind: nobody is left to
7998        // read an answer once the run is failed, and this must not wait for
7999        // some later daemon startup's own sweep to notice that.
8000        let questions = Questions::at(home.join("questions"));
8001        let mut q = ask::Question::new(
8002            dead.id.clone(),
8003            "implement".to_owned(),
8004            "impl-A".to_owned(),
8005            "Which storage backend?".to_owned(),
8006            String::new(),
8007            vec!["SQLite".to_owned(), "Redis".to_owned()],
8008        );
8009        questions.put(&mut q).unwrap();
8010
8011        let abandoned = reclaim_abandoned_runs_with(
8012            &home,
8013            now,
8014            |pid| if pid == 4242 { Some(false) } else { None },
8015            |_| panic!("a query answering Dead outright needs no identity corroboration"),
8016        );
8017        assert_eq!(abandoned, vec![dead.id.clone()]);
8018
8019        let reloaded = read_run_under(&home, &dead.id);
8020        assert_eq!(reloaded.status, RunStatus::Failed);
8021        assert!(reloaded.active.is_empty());
8022        assert!(
8023            !questions.get(&q.id).unwrap().status.open(),
8024            "the failed run's own open question must be settled in the same pass"
8025        );
8026
8027        let still_alive = read_run_under(&home, &alive.id);
8028        assert_eq!(
8029            still_alive.status,
8030            RunStatus::Implementing,
8031            "a live daemon's claim protects it"
8032        );
8033        assert!(!still_alive.active.is_empty());
8034    }
8035
8036    /// The exact shape a review round flagged as broken: `magi serve` running
8037    /// in this same `home` scans *every* run on disk, including a manual
8038    /// `magi review` / `magi run` this daemon never started and that
8039    /// therefore claims no heartbeat of its own. Before this scan asked
8040    /// `liveness` rather than just `is_working_on`, a manual run whose active
8041    /// seat merely ran a little past its own timeout — the CLI finishing up,
8042    /// its result still being collected — got wiped and failed by a daemon
8043    /// that had nothing to do with it, out from under a process that was
8044    /// still very much running.
8045    #[test]
8046    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
8047        let dir = tempfile::tempdir().unwrap();
8048        let home = dir.path().to_path_buf();
8049        let now = Timestamp::now();
8050
8051        let mut manual = run_state(RunStatus::Reviewing);
8052        manual.id = "20260101-000000-manl".to_owned();
8053        manual.active.insert(
8054            "review-1".to_owned(),
8055            crate::run::ActiveSeat {
8056                node: "review".to_owned(),
8057                started_at: now - jiff::SignedDuration::new(21_000, 0),
8058                timeout_secs: 3_600,
8059                attempt: 0,
8060                task: None,
8061                command: None,
8062                index: None,
8063                total: None,
8064            },
8065        );
8066        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
8067        // but a real, still-running process: `liveness` must corroborate this
8068        // as `Live`, not read the missing daemon claim as death.
8069        manual.driver_pid = Some(4242);
8070        manual.driver_started_at = Some("1790000000".to_owned());
8071        manual.save_under(&home).unwrap();
8072
8073        let abandoned = reclaim_abandoned_runs_with(
8074            &home,
8075            now,
8076            |pid| if pid == 4242 { Some(true) } else { None },
8077            |pid| {
8078                if pid == 4242 {
8079                    Some("1790000000".to_owned())
8080                } else {
8081                    None
8082                }
8083            },
8084        );
8085        assert!(
8086            abandoned.is_empty(),
8087            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
8088        );
8089
8090        let reloaded = read_run_under(&home, &manual.id);
8091        assert_eq!(reloaded.status, RunStatus::Reviewing);
8092        assert!(!reloaded.active.is_empty());
8093    }
8094
8095    #[test]
8096    fn an_already_claimed_task_is_skipped_rather_than_failed() {
8097        let dir = tempfile::tempdir().unwrap();
8098        let queue = Queue::at(dir.path().to_path_buf());
8099        let mut only = task();
8100        queue.put(&mut only).unwrap();
8101
8102        let _elsewhere = queue.claim(&only.id).unwrap();
8103        let candidates = runnable(&queue);
8104        assert_eq!(candidates.len(), 1, "the task is still runnable");
8105        assert!(
8106            queue.claim(&candidates[0].id).is_err(),
8107            "the loop cannot take a claim somebody else holds"
8108        );
8109
8110        let after = queue.get(&only.id).unwrap();
8111        assert_eq!(after.status, TaskStatus::Queued);
8112        assert_eq!(
8113            after.attempts, 0,
8114            "losing the race is not an attempt at the task"
8115        );
8116        assert_eq!(after.last_error, None);
8117    }
8118
8119    #[test]
8120    fn the_status_file_round_trips_and_its_heartbeat_advances() {
8121        let dir = tempfile::tempdir().unwrap();
8122        let path = dir.path().join("daemon.json");
8123
8124        let mut status = Status::new();
8125        status.idle = false;
8126        status.completed = 7;
8127        status.current = vec![Current {
8128            task: "20260902-000000-t111".to_owned(),
8129            run: "20260902-000001-r111".to_owned(),
8130        }];
8131        write_status_to(&path, &status).unwrap();
8132        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8133        assert_eq!(first.schema, SCHEMA);
8134        assert_eq!(first.pid, std::process::id());
8135        assert!(!first.idle);
8136        assert_eq!(first.completed, 7);
8137        assert_eq!(first.current, status.current);
8138        assert!(
8139            !path.with_extension("json.tmp").exists(),
8140            "the temp file is renamed, not left behind"
8141        );
8142
8143        std::thread::sleep(Duration::from_millis(5));
8144        status.updated_at = Timestamp::now();
8145        status.polls = 3;
8146        write_status_to(&path, &status).unwrap();
8147        let second: Status =
8148            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
8149        assert!(
8150            second.updated_at > first.updated_at,
8151            "a reader can only detect staleness if the heartbeat moves"
8152        );
8153        assert_eq!(
8154            second.started_at, first.started_at,
8155            "the start time is not a heartbeat"
8156        );
8157        assert_eq!(second.polls, 3);
8158    }
8159
8160    #[test]
8161    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
8162        let dir = tempfile::tempdir().unwrap();
8163
8164        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
8165
8166        let mut status = Status::new();
8167        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
8168        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8169        let stale = read_status(dir.path()).unwrap();
8170        assert!(
8171            !stale.running(Timestamp::now()),
8172            "a minute without a heartbeat is a dead daemon, not a busy one"
8173        );
8174        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
8175
8176        status.updated_at = Timestamp::now();
8177        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8178        let fresh = read_status(dir.path()).unwrap();
8179        assert!(fresh.running(Timestamp::now()));
8180    }
8181
8182    #[test]
8183    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
8184        let dir = tempfile::tempdir().unwrap();
8185        let now = Timestamp::now();
8186        let mine = "20260903-080619-01c2";
8187
8188        assert!(
8189            !is_working_on(dir.path(), mine, now),
8190            "no status file means nobody is working on anything"
8191        );
8192
8193        let mut status = Status::new();
8194        status.current = vec![Current {
8195            task: "20260903-080340-0167".to_owned(),
8196            run: mine.to_owned(),
8197        }];
8198        status.updated_at = now;
8199        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8200        assert!(is_working_on(dir.path(), mine, now));
8201        assert!(
8202            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
8203            "a daemon busy with one run is not working on another"
8204        );
8205
8206        // A killed daemon stops writing heartbeats but leaves the file behind
8207        // naming the run it died in. That run must not be undeletable forever.
8208        status.updated_at = now - jiff::SignedDuration::from_secs(600);
8209        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8210        assert!(
8211            !is_working_on(dir.path(), mine, now),
8212            "a stale heartbeat is a dead daemon, so its run is a leftover"
8213        );
8214    }
8215
8216    #[test]
8217    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
8218        let dir = tempfile::tempdir().unwrap();
8219        let now = Timestamp::now();
8220
8221        assert!(
8222            !is_working_on_short(dir.path(), "01c2", now),
8223            "no status file means nobody is working on anything"
8224        );
8225
8226        let mut status = Status::new();
8227        status.current = vec![Current {
8228            task: "20260903-080340-0167".to_owned(),
8229            run: "20260903-080619-01c2".to_owned(),
8230        }];
8231        status.updated_at = now;
8232        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
8233        assert!(
8234            is_working_on_short(dir.path(), "01c2", now),
8235            "the run's short id is the last block of its full id"
8236        );
8237        assert!(
8238            !is_working_on_short(dir.path(), "3cbf", now),
8239            "a daemon busy with one worktree bay is not working on another"
8240        );
8241    }
8242
8243    #[test]
8244    fn a_newer_status_file_still_yields_a_reading() {
8245        let dir = tempfile::tempdir().unwrap();
8246        // A field this build has never heard of must not turn the reading into
8247        // nothing at all; that is the whole reason the reader is permissive.
8248        std::fs::write(
8249            dir.path().join("daemon.json"),
8250            serde_json::json!({
8251                "schema": 2,
8252                "updated_at": Timestamp::now().to_string(),
8253                "idle": true,
8254                "surprise": { "nested": [1, 2, 3] },
8255            })
8256            .to_string(),
8257        )
8258        .unwrap();
8259
8260        let reading = read_status(dir.path()).expect("a forward-compatible read");
8261        assert!(reading.running(Timestamp::now()));
8262        assert!(reading.idle);
8263        assert!(reading.current.is_empty());
8264    }
8265
8266    #[test]
8267    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
8268        // A daemon started before `current` became a list keeps writing this
8269        // shape on every heartbeat until it is restarted. A rolling upgrade
8270        // - a newer `magi web` or `magi doctor` reading an older `magi
8271        // serve`'s heartbeat - must still see the run it is on, not "no
8272        // daemon" from a type mismatch failing the whole struct.
8273        let dir = tempfile::tempdir().unwrap();
8274        std::fs::write(
8275            dir.path().join("daemon.json"),
8276            serde_json::json!({
8277                "schema": 1,
8278                "pid": 4242,
8279                "updated_at": Timestamp::now().to_string(),
8280                "idle": false,
8281                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
8282                "completed": 3,
8283                "polls": 9,
8284            })
8285            .to_string(),
8286        )
8287        .unwrap();
8288
8289        let reading = read_status(dir.path()).expect("an older shape must still parse");
8290        assert!(reading.running(Timestamp::now()));
8291        assert_eq!(
8292            reading.current,
8293            vec![Current {
8294                task: "20260902-140501-aaaa".to_owned(),
8295                run: "20260902-140502-bbbb".to_owned(),
8296            }]
8297        );
8298    }
8299
8300    #[test]
8301    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
8302        let dir = tempfile::tempdir().unwrap();
8303        std::fs::write(
8304            dir.path().join("daemon.json"),
8305            serde_json::json!({
8306                "schema": 1,
8307                "updated_at": Timestamp::now().to_string(),
8308                "idle": true,
8309                "current": null,
8310            })
8311            .to_string(),
8312        )
8313        .unwrap();
8314        let with_null = read_status(dir.path()).expect("null must still parse");
8315        assert!(with_null.current.is_empty());
8316
8317        std::fs::write(
8318            dir.path().join("daemon.json"),
8319            serde_json::json!({
8320                "schema": 1,
8321                "updated_at": Timestamp::now().to_string(),
8322                "idle": true,
8323            })
8324            .to_string(),
8325        )
8326        .unwrap();
8327        let absent = read_status(dir.path()).expect("a missing field must still parse");
8328        assert!(absent.current.is_empty());
8329    }
8330
8331    #[test]
8332    fn a_task_without_a_repository_runs_in_the_daemons_default() {
8333        let fallback = Path::new("/default");
8334        let mut blank = task();
8335        blank.repo = PathBuf::new();
8336        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
8337        let mut dot = task();
8338        dot.repo = PathBuf::from(".");
8339        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
8340        assert_eq!(
8341            repo_for(&task(), fallback),
8342            PathBuf::from("/repo"),
8343            "a task that names a repository keeps it"
8344        );
8345    }
8346
8347    #[test]
8348    fn task_implementers_edit_inherits_daemon_config_and_merge() {
8349        let dir = tempfile::tempdir().unwrap();
8350        let path = dir.path().join("explicit.toml");
8351        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
8352        let opts = Opts {
8353            config: Some(path),
8354            merge: Some("none".into()),
8355            ..Default::default()
8356        };
8357        let mut t = task();
8358        t.set_implementers(
8359            2,
8360            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8361                .unwrap(),
8362        )
8363        .unwrap();
8364        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8365        assert_eq!(cfg.graph.implementers, 2);
8366        assert_eq!(cfg.graph.judges, 1);
8367        assert_eq!(cfg.merge.mode, MergeMode::None);
8368        t.set_implementers(1, &cfg).unwrap();
8369        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
8370        apply_task_implementers(&mut cfg, &t);
8371        assert_eq!(cfg.graph.implementers, 1);
8372        assert_eq!(cfg.graph.judges, 1);
8373        assert_eq!(cfg.merge.mode, MergeMode::None);
8374    }
8375
8376    #[test]
8377    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
8378        let dir = tempfile::tempdir().unwrap();
8379        let repo = dir.path().join("repo");
8380        std::fs::create_dir(&repo).unwrap();
8381        std::fs::write(
8382            repo.join("magi.toml"),
8383            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
8384        )
8385        .unwrap();
8386        let daemon_config = dir.path().join("daemon.toml");
8387        std::fs::write(
8388            &daemon_config,
8389            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
8390        )
8391        .unwrap();
8392        let opts = Opts {
8393            config: Some(daemon_config),
8394            merge: Some("pr".into()),
8395            ..Default::default()
8396        };
8397        let q = Queue::at(dir.path().join("queue"));
8398        let validation: Config =
8399            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8400                .unwrap();
8401        // No provenance field on legacy direct tasks: both shapes stay isolated.
8402        for record in ["{}", r#"{"candidates":2}"#] {
8403            let overrides = serde_json::from_str(record).unwrap();
8404            let filing = crate::direct::Filing {
8405                instruction: "work".into(),
8406                title: "direct".into(),
8407                repo: repo.clone(),
8408                source: crate::queue::Source::Human,
8409                solo: false,
8410                overrides,
8411                review_of: None,
8412            };
8413            let filed =
8414                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
8415            let crate::direct::Filed::Standalone {
8416                mut task,
8417                claim: _claim,
8418            } = filed
8419            else {
8420                panic!("local filing")
8421            };
8422            let before = prepare_for(&repo, &opts, &task).unwrap();
8423            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
8424            assert_eq!(
8425                before.merge.mode,
8426                MergeMode::None,
8427                "daemon --merge must not leak"
8428            );
8429            for n in [2, 1, 2] {
8430                task.set_implementers(n, &validation).unwrap();
8431                q.put(&mut task).unwrap();
8432                task = q.get(&task.id).unwrap();
8433                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
8434                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
8435                apply_task_implementers(&mut cfg, &task);
8436                assert_eq!(cfg.graph.implementers, usize::from(n));
8437                assert_eq!(cfg.graph.judges, 2);
8438                assert_eq!(cfg.merge.mode, MergeMode::None);
8439            }
8440        }
8441    }
8442
8443    #[test]
8444    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
8445        let cfg: Config =
8446            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8447                .unwrap();
8448        let mut t = task();
8449        t.review_of = Some("review-target".into());
8450        t.hold_manual(Some("retry".into()));
8451        let mut previous = RunState::new(
8452            PathBuf::from("/repo"),
8453            "main".into(),
8454            "abc1234".into(),
8455            "review".into(),
8456            cfg.clone(),
8457        );
8458        previous.config.graph.implementers = 2;
8459        for count in [1, 3] {
8460            t.set_implementers(count, &cfg).unwrap();
8461            t.release();
8462            assert_eq!(t.review_of.as_deref(), Some("review-target"));
8463            for proposed in [
8464                Starter::Resume(previous.id.clone()),
8465                Starter::Review("recovery-target".into()),
8466            ] {
8467                assert_eq!(
8468                    starter_with_implementers(&t, Some(&previous), proposed),
8469                    Starter::Review("review-target".into())
8470                );
8471            }
8472            let mut configured = cfg.clone();
8473            apply_task_implementers(&mut configured, &t);
8474            assert_eq!(configured.graph.implementers, usize::from(count));
8475            assert_eq!(previous.config.graph.implementers, 2);
8476        }
8477    }
8478
8479    #[test]
8480    fn task_implementers_dispatch_and_resume_agree() {
8481        let mut t = task();
8482        let cfg: crate::config::Config =
8483            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
8484                .unwrap();
8485        let mut run = RunState::new(
8486            PathBuf::from("/repo"),
8487            "main".into(),
8488            "abc1234".into(),
8489            "work".into(),
8490            cfg.clone(),
8491        );
8492        run.config.graph.implementers = 2;
8493        for n in [2, 1, 3, 2] {
8494            t.set_implementers(n, &cfg).unwrap();
8495            let mut dispatched = cfg.clone();
8496            apply_task_implementers(&mut dispatched, &t);
8497            assert_eq!(dispatched.graph.implementers, usize::from(n));
8498            assert_eq!(implementers_match(&t, &run), n == 2);
8499            for proposed in [
8500                Starter::Resume(run.id.clone()),
8501                Starter::Review("old-branch".into()),
8502            ] {
8503                let expected = if n == 2 {
8504                    proposed.clone()
8505                } else {
8506                    Starter::Start
8507                };
8508                assert_eq!(
8509                    starter_with_implementers(&t, Some(&run), proposed),
8510                    expected
8511                );
8512            }
8513            assert_eq!(
8514                run.config.graph.implementers, 2,
8515                "history must not be rewritten"
8516            );
8517        }
8518        t.solo = false;
8519        t.overrides = None;
8520        assert!(implementers_match(&t, &run));
8521    }
8522
8523    #[test]
8524    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
8525        // Three seats said out loud. What `solo` promises is one candidate
8526        // *whatever the config asks for*, so the contrast has to be a number
8527        // this test owns - it used to be `Config::default()`'s, which became
8528        // 1 when one implementation became the default and left the two
8529        // halves of this test asserting the same thing.
8530        let mut solo_cfg = Config::default();
8531        solo_cfg.graph.implementers = 3;
8532        let mut solo_task = task();
8533        solo_task.solo = true;
8534        apply_task_implementers(&mut solo_cfg, &solo_task);
8535        assert_eq!(solo_cfg.graph.implementers, 1);
8536
8537        let mut plain_cfg = Config::default();
8538        plain_cfg.graph.implementers = 3;
8539        let plain_task = task();
8540        assert!(!plain_task.solo);
8541        apply_task_implementers(&mut plain_cfg, &plain_task);
8542        assert_eq!(
8543            plain_cfg.graph.implementers, 3,
8544            "a task that did not ask to run alone keeps the config's candidates"
8545        );
8546    }
8547
8548    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
8549        QuotaLoss {
8550            seat: seat.into(),
8551            node: "judge".into(),
8552            at: at.parse().unwrap(),
8553            reset: reset.map(str::to_string),
8554        }
8555    }
8556
8557    #[test]
8558    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
8559        let old: Vec<QuotaLoss> = (1..=4)
8560            .map(|i| {
8561                loss(
8562                    &format!("judge-{i}"),
8563                    "2026-09-23T05:23:00Z",
8564                    Some("2:40pm (Asia/Tokyo)"),
8565                )
8566            })
8567            .collect();
8568        let fresh = losses_this_attempt(&old, &old);
8569        assert!(fresh.is_empty());
8570        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
8571        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
8572    }
8573
8574    #[test]
8575    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
8576        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
8577        let now = Timestamp::now();
8578        let mut after = old.clone();
8579        after.push(loss("judge-2", &now.to_string(), None));
8580        let fresh = losses_this_attempt(&old, &after);
8581        assert_eq!(fresh, vec![after[1].clone()]);
8582        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
8583        assert_eq!(
8584            until,
8585            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
8586        );
8587    }
8588
8589    #[test]
8590    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
8591        // `recover_stall` removes judge-1's loss and the retry then hits quota
8592        // again: the vector is the same length, so an index diff sees nothing.
8593        let before = vec![
8594            loss("judge-1", "2026-09-23T05:23:00Z", None),
8595            loss("judge-2", "2026-09-23T05:24:00Z", None),
8596        ];
8597        let after = vec![
8598            loss("judge-2", "2026-09-23T05:24:00Z", None),
8599            loss("judge-1", "2026-09-24T01:00:00Z", None),
8600        ];
8601        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
8602    }
8603
8604    #[test]
8605    fn merge_overrides_are_parsed_or_refused() {
8606        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
8607        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
8608        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
8609        assert!(merge_mode("squash").is_err());
8610    }
8611
8612    #[test]
8613    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
8614        let now = Timestamp::now();
8615        let fallback = Duration::from_secs(300);
8616        let cap = Duration::from_secs(1800);
8617
8618        // No reset hint at all: the fallback.
8619        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
8620
8621        // A reset ten minutes out, well inside the cap: waited for exactly.
8622        let soon = now + jiff::SignedDuration::from_secs(600);
8623        assert_eq!(
8624            quota_wait(Some(soon), now, fallback, cap),
8625            Duration::from_secs(600)
8626        );
8627
8628        // A reset already in the past is not trusted: the fallback, not a
8629        // zero or negative wait that would spin the loop right back around.
8630        let past = now - jiff::SignedDuration::from_secs(60);
8631        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
8632
8633        // A reset further out than the cap is trusted for direction but not
8634        // for magnitude: a parsing slip must not sleep the loop for a day.
8635        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
8636        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
8637    }
8638
8639    #[test]
8640    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
8641        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8642
8643        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
8644        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
8645
8646        // Same clock reading, but it has already gone by today: read as
8647        // tomorrow's, since the CLI would not still be reporting a limit past
8648        // its own stated reset.
8649        let already_past =
8650            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
8651        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
8652
8653        assert!(
8654            parse_reset_hint("session limit reached", now, now).is_none(),
8655            "free text with no recognised shape is not guessed at"
8656        );
8657        assert!(
8658            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
8659            "an unresolvable zone name is not guessed at either"
8660        );
8661    }
8662
8663    #[test]
8664    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
8665        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
8666
8667        let at = parse_reset_hint(
8668            "You've hit your usage limit. Visit \
8669             https://chatgpt.com/codex/settings/usage to purchase more \
8670             credits or try again at Sep 19th, 2026 5:10 PM.",
8671            now,
8672            now,
8673        )
8674        .expect("the codex reset wording is a recognised shape");
8675        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
8676
8677        // The month is explicit, so a date already earlier in the same
8678        // sentence-implied year than `now` is trusted as written rather than
8679        // rolled forward a year the way the bracketed shape rolls a
8680        // same-day clock reading to tomorrow.
8681        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
8682            .expect("an explicit year needs no rollover");
8683        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
8684
8685        assert!(
8686            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
8687            "a two-digit year is not the documented shape and is not guessed at"
8688        );
8689        assert!(
8690            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
8691            "a four-letter month name is not the documented three-letter abbreviation"
8692        );
8693        assert!(
8694            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
8695            "an explicit zone on the dated shape is a format nobody has \
8696             documented, and is refused rather than guessed at as UTC"
8697        );
8698    }
8699
8700    #[test]
8701    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
8702        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
8703        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
8704
8705        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
8706        assert_eq!(at.as_second() - recorded.as_second(), 3769);
8707
8708        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
8709        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
8710
8711        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
8712            assert!(
8713                parse_reset_hint(bad, now, recorded).is_none(),
8714                "{bad:?} must not be guessed at"
8715            );
8716        }
8717    }
8718
8719    /// A loop whose queue lives in a temp tree and whose poll interval is far
8720    /// longer than the test's patience, so anything that waits out a poll
8721    /// instead of noticing the stop fails rather than merely being slow.
8722    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
8723        let config = dir.join("magi.toml");
8724        std::fs::write(
8725            &config,
8726            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
8727        )
8728        .unwrap();
8729        let opts = Opts {
8730            poll: Duration::from_secs(30),
8731            config: Some(config),
8732            // The explicit fixture config keeps startup cleanup from reading
8733            // machine configuration. This fictional repository likewise
8734            // keeps any best-effort git cleanup away from this checkout.
8735            repo: dir.join("repo"),
8736            ..Opts::default()
8737        };
8738        // The status file goes in a directory that does not exist yet, so its
8739        // creation is itself evidence the loop published one. `worktrees`
8740        // must be just as fictional: the janitor reclaims worktrees under it
8741        // for real, and a test that let it fall through to
8742        // `crate::run::default_worktree_root()` would have it reclaim
8743        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
8744        // which is exactly what happened before this function took the
8745        // parameter at all.
8746        let home = dir.join("home");
8747        let worktrees = dir.join("wt");
8748        (
8749            opts,
8750            Queue::at(dir.join("queue")),
8751            home.join("daemon.json"),
8752            home,
8753            worktrees,
8754        )
8755    }
8756
8757    #[test]
8758    fn a_stop_is_idempotent_and_once_set_stays_set() {
8759        let stop = Stop::new();
8760        assert!(!stop.stopped());
8761
8762        stop.stop();
8763        assert!(stop.stopped());
8764        stop.stop();
8765        assert!(stop.stopped(), "a second stop is not a toggle");
8766
8767        let shared = stop.clone();
8768        assert!(
8769            shared.stopped(),
8770            "a clone is the same stop; that is how the loop and its caller share one"
8771        );
8772    }
8773
8774    #[test]
8775    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
8776        let stop = Stop::new();
8777        stop.enter();
8778        assert!(
8779            !stop.finishing(),
8780            "a busy loop nobody has asked to stop is just running"
8781        );
8782
8783        stop.stop();
8784        assert!(
8785            stop.finishing(),
8786            "a stop asked for mid-run has not landed until the run is settled"
8787        );
8788
8789        stop.exit();
8790        assert!(
8791            !stop.finishing(),
8792            "once the run is settled the stop has landed and there is nothing to finish"
8793        );
8794    }
8795
8796    #[test]
8797    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
8798        let stop = Stop::new();
8799        stop.enter();
8800        stop.enter();
8801        stop.stop();
8802        assert!(stop.finishing(), "two runs still in flight");
8803
8804        stop.exit();
8805        assert!(
8806            stop.finishing(),
8807            "one run finished, but a sibling is still working"
8808        );
8809
8810        stop.exit();
8811        assert!(
8812            !stop.finishing(),
8813            "the last run out is what actually lands the stop"
8814        );
8815    }
8816
8817    #[tokio::test]
8818    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
8819        let dir = tempfile::tempdir().unwrap();
8820        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8821        let stop = Stop::new();
8822        stop.stop();
8823
8824        let began = std::time::Instant::now();
8825        tokio::time::timeout(
8826            Duration::from_secs(2),
8827            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8828        )
8829        .await
8830        .expect("a stopped loop must return, not sit out its poll interval")
8831        .expect("the loop's own setup and teardown must not fail");
8832        assert!(
8833            began.elapsed() < opts.poll,
8834            "returned only after {:?}, which is a poll interval, not a stop",
8835            began.elapsed()
8836        );
8837    }
8838
8839    #[tokio::test]
8840    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
8841        let dir = tempfile::tempdir().unwrap();
8842        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8843        let stop = Stop::new();
8844
8845        // Asked for after the loop is already parked on its empty queue, which
8846        // is the case an operator tapping stop on a phone actually hits.
8847        let asker = {
8848            let stop = stop.clone();
8849            tokio::spawn(async move {
8850                tokio::time::sleep(Duration::from_millis(20)).await;
8851                stop.stop();
8852            })
8853        };
8854
8855        let began = std::time::Instant::now();
8856        tokio::time::timeout(
8857            Duration::from_secs(2),
8858            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8859        )
8860        .await
8861        .expect("a stop asked for while idle must wake the wait")
8862        .expect("the loop's own setup and teardown must not fail");
8863        asker.await.unwrap();
8864        assert!(
8865            began.elapsed() < opts.poll,
8866            "returned only after {:?}, so the stop waited on the sleep",
8867            began.elapsed()
8868        );
8869    }
8870
8871    #[tokio::test]
8872    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
8873        let dir = tempfile::tempdir().unwrap();
8874        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8875        let stop = Stop::new();
8876        stop.stop();
8877
8878        tokio::time::timeout(
8879            Duration::from_secs(2),
8880            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
8881        )
8882        .await
8883        .expect("a stopped loop must return")
8884        .expect("the loop's own setup and teardown must not fail");
8885
8886        assert!(
8887            home.is_dir(),
8888            "the loop did publish a status file, so its removal is the teardown and not an absence"
8889        );
8890        assert!(
8891            !status_file.exists(),
8892            "a stopped loop clears its status file"
8893        );
8894        assert!(
8895            read_status(&home).is_none(),
8896            "a reader must see no daemon at all, not a heartbeat that merely stopped"
8897        );
8898    }
8899
8900    #[tokio::test]
8901    async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
8902        let dir = tempfile::tempdir().unwrap();
8903        let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
8904        opts.once = true;
8905
8906        let mut settled = RunState::new(
8907            dir.path().join("repo"),
8908            "main".to_owned(),
8909            "abc1234".to_owned(),
8910            "fixture".to_owned(),
8911            Config::default(),
8912        );
8913        settled.status = RunStatus::Ready;
8914        let run_dir = home.join("runs").join(&settled.id);
8915        std::fs::create_dir_all(&run_dir).unwrap();
8916        std::fs::write(
8917            run_dir.join("run.json"),
8918            serde_json::to_string_pretty(&settled).unwrap(),
8919        )
8920        .unwrap();
8921        let questions = Questions::at(home.join("questions"));
8922        let mut question = ask::Question::new(
8923            settled.id.clone(),
8924            "review".to_owned(),
8925            "reviewer-1".to_owned(),
8926            "Continue?".to_owned(),
8927            String::new(),
8928            Vec::new(),
8929        );
8930        questions.put(&mut question).unwrap();
8931
8932        drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
8933            .await
8934            .unwrap();
8935
8936        assert_eq!(
8937            questions.get(&question.id).unwrap().status,
8938            ask::QuestionStatus::Abandoned,
8939            "an empty --once drain still performs startup question cleanup"
8940        );
8941    }
8942
8943    #[test]
8944    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
8945        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
8946
8947        assert!(
8948            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
8949            "never checked before: due at once"
8950        );
8951
8952        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
8953        assert!(
8954            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
8955            "well inside the interval: not due yet"
8956        );
8957
8958        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
8959        assert!(
8960            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
8961            "exactly at the edge: not yet due, same convention as `clean::due`"
8962        );
8963
8964        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
8965        assert!(
8966            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
8967            "past the interval: due again"
8968        );
8969    }
8970
8971    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
8972    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
8973    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
8974    /// and the congestion test below both need, and must not drift apart.
8975    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
8976        let config = dir.join("magi.toml");
8977        // A literal (single-quoted) TOML string, not a basic one: the cache
8978        // path is a Windows path full of backslashes, and a basic string
8979        // would have TOML try to interpret `\U` (from `\Users\...`) as a
8980        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
8981        // `{{ vars.cache }}` rendering documents.
8982        std::fs::write(
8983            &config,
8984            format!(
8985                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
8986                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
8987                cache_dir.display()
8988            ),
8989        )
8990        .unwrap();
8991        Opts {
8992            config: Some(config),
8993            repo: dir.join("repo"),
8994            ..Opts::default()
8995        }
8996    }
8997
8998    #[tokio::test]
8999    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
9000        let dir = tempfile::tempdir().unwrap();
9001        let home = dir.path().join("home");
9002        let cache_dir = dir.path().join("cache");
9003        std::fs::create_dir_all(&cache_dir).unwrap();
9004        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9005        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9006
9007        // Nobody has asked this daemon to stop, which is the ordinary case;
9008        // the skip that a stop buys is asserted by its own test below.
9009        let running = Stop::new();
9010        let mut last_checked = None;
9011        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9012        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
9013            .await;
9014        assert_eq!(
9015            crate::disk::dir_size(&cache_dir),
9016            0,
9017            "over the cap on the first check ever: pruned at once, no idle queue required"
9018        );
9019        assert_eq!(last_checked, Some(t0));
9020
9021        // A fresh oversized file lands, but the next check is not due yet.
9022        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
9023        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
9024        maybe_prune_cache_between_runs(
9025            &opts.repo,
9026            &opts,
9027            &home,
9028            &running,
9029            &mut last_checked,
9030            too_soon,
9031        )
9032        .await;
9033        assert_eq!(
9034            crate::disk::dir_size(&cache_dir),
9035            10,
9036            "too soon since the last check: left alone rather than rescanned every call"
9037        );
9038        assert_eq!(
9039            last_checked,
9040            Some(t0),
9041            "an idle check does not reset the clock"
9042        );
9043
9044        // Once the interval elapses, the same oversized cache is caught again.
9045        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
9046        maybe_prune_cache_between_runs(
9047            &opts.repo,
9048            &opts,
9049            &home,
9050            &running,
9051            &mut last_checked,
9052            due_again,
9053        )
9054        .await;
9055        assert_eq!(
9056            crate::disk::dir_size(&cache_dir),
9057            0,
9058            "due again: pruned back under the cap"
9059        );
9060    }
9061
9062    /// A stop must not queue behind housekeeping. The prune below is a
9063    /// synchronous walk of the whole cache with no await point in it, so a
9064    /// loop that entered it could not get back to its own `stopped()` test
9065    /// until the walk finished - and because no run is in flight at this
9066    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
9067    /// the stop had already landed. The idle branch has always made this same
9068    /// check before reaching `janitor`; the between-runs path makes it too.
9069    #[tokio::test]
9070    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
9071        let dir = tempfile::tempdir().unwrap();
9072        let home = dir.path().join("home");
9073        let cache_dir = dir.path().join("cache");
9074        std::fs::create_dir_all(&cache_dir).unwrap();
9075        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
9076        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
9077
9078        let stop = Stop::new();
9079        stop.stop();
9080        assert!(
9081            !stop.finishing(),
9082            "no run is in flight at a between-runs boundary, so nothing else \
9083             would tell the operator this stop had not taken effect yet"
9084        );
9085
9086        let mut last_checked = None;
9087        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
9088        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
9089            .await;
9090        assert_eq!(
9091            crate::disk::dir_size(&cache_dir),
9092            10,
9093            "over its cap, and due for the first check ever, but a stop outranks \
9094             it: the cap is a standing policy the next start measures again"
9095        );
9096        assert_eq!(
9097            last_checked, None,
9098            "a check that never happened must not claim the interval"
9099        );
9100    }
9101
9102    /// The regression this whole change exists for: gate timeouts on runs
9103    /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
9104    /// GiB against a 10 GiB cap, because the operator's queue never had a
9105    /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
9106    /// `janitor` pass.
9107    ///
9108    /// Reproduced with a backlog whose repository is never created:
9109    /// `Runner::start` fails at `git::toplevel`, spawning no agent CLI.
9110    /// Each task is held after one startup failure, but the remaining tasks
9111    /// keep the queue busy until an external stop ends the loop.
9112    #[tokio::test]
9113    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
9114        let dir = tempfile::tempdir().unwrap();
9115        let cache_dir = dir.path().join("cache");
9116        std::fs::create_dir_all(&cache_dir).unwrap();
9117        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
9118
9119        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
9120        opts.poll = Duration::from_millis(20);
9121        opts.max_attempts = 1_000;
9122
9123        let queue = Queue::at(dir.path().join("queue"));
9124        for i in 0..128 {
9125            let mut task = Task::new(
9126                format!("queued work {i}"),
9127                format!("queued work {i}"),
9128                opts.repo.clone(),
9129                Source::Human,
9130            );
9131            queue.put(&mut task).unwrap();
9132        }
9133
9134        let home = dir.path().join("home");
9135        let worktrees = dir.path().join("wt");
9136        let status_file = home.join("daemon.json");
9137        let stop = Stop::new();
9138        let stopper = {
9139            let stop = stop.clone();
9140            let queue = Queue::at(dir.path().join("queue"));
9141            tokio::spawn(async move {
9142                // Observe completed work rather than rely on a wall-clock
9143                // delay. Every startup failure holds only its own task; the
9144                // backlog keeps offering work at the next boundary.
9145                for _ in 0..2_000 {
9146                    if queue.list().iter().filter(|t| t.attempts == 1).count() >= 2 {
9147                        break;
9148                    }
9149                    tokio::time::sleep(Duration::from_millis(5)).await;
9150                }
9151                stop.stop();
9152            })
9153        };
9154
9155        tokio::time::timeout(
9156            Duration::from_secs(20),
9157            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
9158        )
9159        .await
9160        .expect("the loop must not hang on a queue that keeps producing failing work")
9161        .expect("the loop's own setup and teardown must not fail");
9162        stopper.await.unwrap();
9163
9164        let after = queue.list();
9165        let completed = after.iter().filter(|t| t.attempts == 1).count();
9166        assert!(
9167            completed >= 2,
9168            "the harness must have processed multiple tasks to exercise a busy queue \
9169             (got {completed} completed task(s))"
9170        );
9171        assert!(
9172            after.iter().any(|t| t.status.runnable()),
9173            "unprocessed tasks must remain: the external stop, rather than an \
9174             exhausted backlog, must end the test"
9175        );
9176        assert!(
9177            after
9178                .iter()
9179                .filter(|t| t.attempts > 0)
9180                .all(|t| { t.attempts == 1 && t.status == TaskStatus::Held }),
9181            "a busy backlog must not retry a task's unchanged startup failure"
9182        );
9183
9184        assert_eq!(
9185            crate::disk::dir_size(&cache_dir),
9186            0,
9187            "an oversized cache must not be left to grow unboundedly just because the \
9188             queue kept the loop busy the whole time"
9189        );
9190    }
9191
9192    #[test]
9193    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
9194        let dir = tempfile::tempdir().unwrap();
9195        let queue = Queue::at(dir.path().join("queue"));
9196        let questions = Questions::at(dir.path().join("questions"));
9197        let mut task = task();
9198        queue.put(&mut task).unwrap();
9199
9200        let mut task_question = ask::Question::new(
9201            task.id.clone(),
9202            crate::conduct::NODE.to_owned(),
9203            "conduct".to_owned(),
9204            "Which backend?".to_owned(),
9205            String::new(),
9206            Vec::new(),
9207        );
9208        questions.put(&mut task_question).unwrap();
9209        task.block(vec![task_question.id.clone()], None);
9210        queue.put(&mut task).unwrap();
9211
9212        let mut run_question = ask::Question::new(
9213            "20260101-000000-run1".to_owned(),
9214            "review".to_owned(),
9215            "reviewer-1".to_owned(),
9216            "Run question".to_owned(),
9217            String::new(),
9218            Vec::new(),
9219        );
9220        questions.put(&mut run_question).unwrap();
9221
9222        // A question from another node whose `run` happens to equal this
9223        // task's id — the same field, filled in for an unrelated reason. Only
9224        // `crate::conduct::NODE` questions use `run` as a task id; this one
9225        // must never be touched by this reconciliation, even after release.
9226        let mut coincidental = ask::Question::new(
9227            task.id.clone(),
9228            "review".to_owned(),
9229            "reviewer-1".to_owned(),
9230            "Unrelated review question".to_owned(),
9231            String::new(),
9232            Vec::new(),
9233        );
9234        questions.put(&mut coincidental).unwrap();
9235
9236        reconcile_task_questions(&queue, &questions);
9237        assert!(questions.get(&task_question.id).unwrap().status.open());
9238        assert!(questions.get(&run_question.id).unwrap().status.open());
9239        assert!(questions.get(&coincidental.id).unwrap().status.open());
9240
9241        task.release();
9242        queue.put(&mut task).unwrap();
9243        reconcile_task_questions(&queue, &questions);
9244        assert_eq!(
9245            questions.get(&task_question.id).unwrap().status,
9246            ask::QuestionStatus::Abandoned
9247        );
9248        assert!(
9249            questions.get(&run_question.id).unwrap().status.open(),
9250            "run questions remain the run janitor's responsibility"
9251        );
9252        assert!(
9253            questions.get(&coincidental.id).unwrap().status.open(),
9254            "a non-conductor question must not be abandoned just because its \
9255             run id coincides with a task id"
9256        );
9257    }
9258
9259    #[test]
9260    fn a_freshly_started_running_task_is_never_stalled() {
9261        let dir = tempfile::tempdir().unwrap();
9262        let mut t = task();
9263        t.start("run-1".to_owned());
9264        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
9265        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
9266        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
9267    }
9268
9269    #[test]
9270    fn a_long_running_task_with_no_live_daemon_is_stalled() {
9271        let dir = tempfile::tempdir().unwrap();
9272        let mut t = task();
9273        t.start("run-1".to_owned());
9274        t.updated_at = Timestamp::now()
9275            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9276        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
9277        assert_eq!(
9278            stalled_tasks(
9279                &Queue::at(dir.path().join("q")),
9280                dir.path(),
9281                Timestamp::now()
9282            )
9283            .len(),
9284            0,
9285            "the task was never written to this queue"
9286        );
9287    }
9288
9289    #[test]
9290    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
9291        let dir = tempfile::tempdir().unwrap();
9292        let mut t = task();
9293        t.id = "20260903-080340-0167".to_owned();
9294        t.start("20260903-080619-01c2".to_owned());
9295        t.updated_at = Timestamp::now()
9296            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
9297
9298        let mut status = Status::new();
9299        status.current = vec![Current {
9300            task: t.id.clone(),
9301            run: "20260903-080619-01c2".to_owned(),
9302        }];
9303        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9304
9305        assert!(
9306            !is_stalled(&t, dir.path(), Timestamp::now()),
9307            "a live daemon's own heartbeat rules out stalled, however long the task has run"
9308        );
9309    }
9310
9311    /// Rewrite a task's `updated_at` on disk directly, bypassing
9312    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
9313    /// a fixture look like it has genuinely been `running` for a while.
9314    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
9315        let path = queue.path_of(id);
9316        let body = std::fs::read_to_string(&path).unwrap();
9317        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
9318        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
9319        v["updated_at"] = serde_json::Value::String(old.to_string());
9320        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
9321    }
9322
9323    #[test]
9324    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
9325        // The realistic `poll()` ordering, not `is_stalled` in isolation:
9326        // `reclaim_orphaned_running` runs first, on every poll, and settles
9327        // any `running` task whose claim it can actually take. For most
9328        // crashes that is immediate - a dead pid is proof enough for
9329        // `sweep_stale_claims` to drop the lock the same tick, and the very
9330        // next claim attempt succeeds. But a lock whose pid cannot be parsed
9331        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
9332        // `sweep_stale_claims`'s own doc), so the lock - and the claim
9333        // failure behind it - can legitimately outlive many polls. This is
9334        // exactly the gap `stalled_tasks` exists to surface well before that
9335        // six-hour sweep would: reclaim leaves the task `running`, and it
9336        // must still reach the conductor as stalled.
9337        let dir = tempfile::tempdir().unwrap();
9338        let queue = Queue::at(dir.path().join("queue"));
9339        let home = dir.path().join("home");
9340
9341        let mut t = task();
9342        t.id = "20260101-000001-lock".to_owned();
9343        t.start("run-1".to_owned());
9344        queue.put(&mut t).unwrap();
9345        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9346        std::fs::write(
9347            dir.path().join("queue").join(format!("{}.lock", t.id)),
9348            "not a pid",
9349        )
9350        .unwrap();
9351
9352        let now = Timestamp::now();
9353        assert!(
9354            reclaim_orphaned_running(&queue, 2).is_empty(),
9355            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
9356             and reclaim must leave the task alone"
9357        );
9358        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9359
9360        let stalled = stalled_tasks(&queue, &home, now);
9361        assert_eq!(
9362            stalled.len(),
9363            1,
9364            "reclaim's inability to claim it yet must not hide it from the conductor"
9365        );
9366        assert_eq!(stalled[0].id, t.id);
9367    }
9368
9369    #[test]
9370    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
9371        let dir = tempfile::tempdir().unwrap();
9372        crate::run::set_home(dir.path().join("run-home"));
9373        let queue = Queue::at(dir.path().join("queue"));
9374        let home = dir.path().join("home");
9375        let questions = Questions::at(dir.path().join("questions"));
9376
9377        let mut t = task();
9378        t.id = "20260101-000003-dead".to_owned();
9379        t.start("missing-run".to_owned());
9380        queue.put(&mut t).unwrap();
9381        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
9382
9383        // This is the real poll ordering: retain the deterministic stalled
9384        // input before a claim proves the owner is gone and reclaims it.
9385        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9386        assert_eq!(
9387            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
9388            [&t.id]
9389        );
9390        assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
9391        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
9392
9393        // Reclaim drops its guard before conductor decisions are applied, so
9394        // the decision for the captured stalled input has a real write path.
9395        crate::conduct::apply(
9396            &queue,
9397            &questions,
9398            &crate::conduct::Verdict {
9399                decisions: vec![crate::conduct::Decision {
9400                    id: t.id.clone(),
9401                    recovery: Some(crate::conduct::Recovery::Requeue),
9402                    ..crate::conduct::Decision::default()
9403                }],
9404            },
9405        )
9406        .unwrap();
9407        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
9408    }
9409
9410    #[test]
9411    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
9412        let dir = tempfile::tempdir().unwrap();
9413        let queue = Queue::at(dir.path().join("queue"));
9414        let home = dir.path().join("home");
9415
9416        let mut fresh = task();
9417        fresh.id = "20260101-000001-aaaa".to_owned();
9418        fresh.start("run-1".to_owned());
9419        queue.put(&mut fresh).unwrap();
9420
9421        let mut old = task();
9422        old.id = "20260101-000002-bbbb".to_owned();
9423        old.start("run-2".to_owned());
9424        queue.put(&mut old).unwrap();
9425        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
9426
9427        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
9428        assert_eq!(stalled.len(), 1);
9429        assert_eq!(stalled[0].id, old.id);
9430    }
9431
9432    #[test]
9433    fn queued_and_finished_task_views_partition_by_status() {
9434        let dir = tempfile::tempdir().unwrap();
9435        let queue = Queue::at(dir.path().join("queue"));
9436
9437        let mut queued = task();
9438        queued.id = "20260101-000001-aaaa".to_owned();
9439        queue.put(&mut queued).unwrap();
9440
9441        let mut failed = task();
9442        failed.id = "20260101-000002-bbbb".to_owned();
9443        failed.start("run-1".to_owned());
9444        failed.fail("gate red", 5);
9445        queue.put(&mut failed).unwrap();
9446
9447        let mut held = task();
9448        held.id = "20260101-000003-cccc".to_owned();
9449        held.hold_machine(None);
9450        queue.put(&mut held).unwrap();
9451
9452        let mut running = task();
9453        running.id = "20260101-000004-dddd".to_owned();
9454        running.start("run-2".to_owned());
9455        queue.put(&mut running).unwrap();
9456
9457        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
9458        assert_eq!(queued_ids, [queued.id.clone()]);
9459
9460        let mut finished_ids: Vec<String> =
9461            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
9462        finished_ids.sort_unstable();
9463        let mut want = vec![failed.id.clone(), held.id.clone()];
9464        want.sort_unstable();
9465        assert_eq!(finished_ids, want);
9466    }
9467
9468    #[test]
9469    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
9470        for short in [false, true] {
9471            let dir = tempfile::tempdir().unwrap();
9472            let queue = Queue::at(dir.path().join("queue"));
9473            let questions = ask::Questions::at(dir.path().join("questions"));
9474            let mut running = task();
9475            running.id = "20261013-192213-feb2".into();
9476            running.start("existing-run".into());
9477            queue.put(&mut running).unwrap();
9478            let mut middle = task();
9479            middle.id = "20261013-193611-ca5b".into();
9480            middle.block(
9481                vec![if short {
9482                    "feb2".into()
9483                } else {
9484                    running.id.clone()
9485                }],
9486                None,
9487            );
9488            queue.put(&mut middle).unwrap();
9489            let mut waiting = task();
9490            waiting.id = "20261013-202849-ee37".into();
9491            waiting.block(
9492                vec![if short {
9493                    "ca5b".into()
9494                } else {
9495                    middle.id.clone()
9496                }],
9497                Some("wait for implementation".into()),
9498            );
9499            queue.put(&mut waiting).unwrap();
9500            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
9501            let inv = crate::blockers::Inventory::load(&queue, &questions);
9502            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
9503            assert!(inv.stuck().is_empty());
9504            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9505            assert!(report.quarantined.is_empty());
9506            assert!(report.asked.is_empty());
9507            resolve_blockers(&queue, &questions);
9508            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9509            assert!(questions.list().is_empty());
9510            // Finishing the transitive prerequisite alone does not satisfy
9511            // the task's direct dependency.
9512            running.succeed();
9513            queue.put(&mut running).unwrap();
9514            resolve_blockers(&queue, &questions);
9515            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
9516            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9517            middle = queue.get(&middle.id).unwrap();
9518            middle.succeed();
9519            queue.put(&mut middle).unwrap();
9520            resolve_blockers(&queue, &questions);
9521            let after = queue.get(&waiting.id).unwrap();
9522            assert_eq!(after.status, TaskStatus::Queued);
9523            assert!(after.blocked_by.is_empty());
9524            assert_eq!(after.instruction, waiting.instruction);
9525        }
9526    }
9527
9528    #[test]
9529    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
9530        for future_schema in [false, true] {
9531            let name = "20261013-193611-ca5b";
9532            let mut future = task();
9533            future.id = name.into();
9534            future.schema = crate::queue::SCHEMA + 1;
9535            let contents = if future_schema {
9536                serde_json::to_string(&future).unwrap()
9537            } else {
9538                "corrupt".into()
9539            };
9540            let dir = tempfile::tempdir().unwrap();
9541            let queue = Queue::at(dir.path().join("queue"));
9542            let questions = ask::Questions::at(dir.path().join("questions"));
9543            let mut waiting = task();
9544            waiting.id = "20261013-202849-ee37".into();
9545            waiting.block(vec!["ca5b".into()], None);
9546            queue.put(&mut waiting).unwrap();
9547            std::fs::write(queue.path_of(name), contents).unwrap();
9548            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
9549            assert!(
9550                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
9551            );
9552            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9553            assert!(report.asked.is_empty());
9554            resolve_blockers(&queue, &questions);
9555            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9556            assert!(questions.list().is_empty());
9557        }
9558        let dir = tempfile::tempdir().unwrap();
9559        let queue = Queue::at(dir.path().join("queue"));
9560        let questions = ask::Questions::at(dir.path().join("questions"));
9561        let mut waiting = task();
9562        waiting.id = "20261013-202849-ee37".into();
9563        waiting.block(vec!["ca5b".into()], None);
9564        queue.put(&mut waiting).unwrap();
9565        let mut done = task();
9566        done.id = "20261013-193611-ca5b".into();
9567        done.succeed();
9568        queue.put(&mut done).unwrap();
9569        // An unreadable second match must not disappear from uniqueness
9570        // checks just because Queue::list skips it.
9571        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
9572        assert!(queue.get("ca5b").is_err());
9573        assert_eq!(
9574            crate::queue::dependency(&queue, &questions, "ca5b"),
9575            crate::queue::Dependency::Ambiguous
9576        );
9577        resolve_blockers(&queue, &questions);
9578        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
9579        assert!(report.asked.is_empty());
9580        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
9581        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
9582    }
9583
9584    #[test]
9585    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
9586        for held in [false, true] {
9587            for question in [false, true] {
9588                for reference in ["ca5b", "20261013-193611-ca5b"] {
9589                    let dir = tempfile::tempdir().unwrap();
9590                    let queue = Queue::at(dir.path().join("queue"));
9591                    let questions = ask::Questions::at(dir.path().join("questions"));
9592                    let mut prerequisite = task();
9593                    prerequisite.id = "20261013-193611-ca5b".into();
9594                    prerequisite.start("existing-run".into());
9595                    queue.put(&mut prerequisite).unwrap();
9596                    let mut waiting = task();
9597                    waiting.id = "20261013-202849-ee37".into();
9598                    if held {
9599                        waiting.hold_machine(Some("waiting for separate consent".into()));
9600                    }
9601                    queue.put(&mut waiting).unwrap();
9602                    let reason = "Deleting saved data requires separate owner consent";
9603                    crate::conduct::apply(
9604                        &queue,
9605                        &questions,
9606                        &crate::conduct::Verdict {
9607                            decisions: vec![crate::conduct::Decision {
9608                                id: waiting.id.clone(),
9609                                blocked_by: vec![reference.into()],
9610                                question: question.then(|| "May the saved data be deleted?".into()),
9611                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
9612                                reason: Some(reason.into()),
9613                                ..crate::conduct::Decision::default()
9614                            }],
9615                        },
9616                    )
9617                    .unwrap();
9618                    let before = queue.get(&waiting.id).unwrap();
9619                    if question {
9620                        assert_eq!(before.status, TaskStatus::Blocked);
9621                        let q = questions.get(&before.blocked_by[0]).unwrap();
9622                        assert_eq!(q.summary, "May the saved data be deleted?");
9623                        assert!(q.status.open());
9624                    } else {
9625                        assert_eq!(before.status, TaskStatus::Held);
9626                        let recorded_reason = before.hold_reason.as_deref().unwrap();
9627                        assert!(recorded_reason.starts_with(reason));
9628                        if held {
9629                            assert!(recorded_reason.contains("waiting for separate consent"));
9630                        }
9631                    }
9632                    prerequisite.succeed();
9633                    queue.put(&mut prerequisite).unwrap();
9634                    resolve_blockers(&queue, &questions);
9635                    let after = queue.get(&waiting.id).unwrap();
9636                    assert_eq!(after.status, before.status);
9637                    assert_eq!(after.blocked_by, before.blocked_by);
9638                    assert_eq!(after.hold_reason, before.hold_reason);
9639                    assert_eq!(after.instruction, waiting.instruction);
9640                    if question {
9641                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
9642                    }
9643                    assert!(
9644                        queue.next_runnable().is_none(),
9645                        "dependency completion is not consent"
9646                    );
9647                }
9648            }
9649        }
9650    }
9651
9652    #[test]
9653    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
9654        let dir = tempfile::tempdir().unwrap();
9655        let queue = Queue::at(dir.path().join("queue"));
9656        let questions = ask::Questions::at(dir.path().join("questions"));
9657
9658        let mut dep = task();
9659        dep.id = "20260101-000001-dep0".to_owned();
9660        dep.succeed();
9661        queue.put(&mut dep).unwrap();
9662
9663        let mut still_going = task();
9664        still_going.id = "20260101-000002-dep1".to_owned();
9665        queue.put(&mut still_going).unwrap();
9666
9667        let mut blocked = task();
9668        blocked.id = "20260101-000003-main".to_owned();
9669        blocked.block(
9670            vec![dep.id.clone(), still_going.id.clone()],
9671            Some("waits on both".to_owned()),
9672        );
9673        queue.put(&mut blocked).unwrap();
9674
9675        resolve_blockers(&queue, &questions);
9676
9677        let after = queue.get(&blocked.id).unwrap();
9678        assert_eq!(
9679            after.status,
9680            TaskStatus::Blocked,
9681            "one dependency is still outstanding"
9682        );
9683        assert_eq!(after.blocked_by, [still_going.id.clone()]);
9684    }
9685
9686    #[test]
9687    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
9688        let dir = tempfile::tempdir().unwrap();
9689        let queue = Queue::at(dir.path().join("queue"));
9690        let questions = ask::Questions::at(dir.path().join("questions"));
9691
9692        let mut q = crate::ask::Question::new(
9693            "20260101-000001-main".to_owned(),
9694            crate::conduct::NODE.to_owned(),
9695            "conduct".to_owned(),
9696            "Which backend?".to_owned(),
9697            String::new(),
9698            Vec::new(),
9699        );
9700        questions.put(&mut q).unwrap();
9701        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
9702            .unwrap();
9703        questions.put(&mut q).unwrap();
9704
9705        let mut blocked = task();
9706        blocked.id = "20260101-000001-main".to_owned();
9707        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
9708        queue.put(&mut blocked).unwrap();
9709
9710        resolve_blockers(&queue, &questions);
9711
9712        let after = queue.get(&blocked.id).unwrap();
9713        assert_eq!(
9714            after.status,
9715            TaskStatus::Queued,
9716            "the only blocker resolved"
9717        );
9718        assert_eq!(after.answers.len(), 1);
9719        assert_eq!(after.answers[0].question, "Which backend?");
9720        assert_eq!(after.answers[0].answer, "SQLite");
9721
9722        // And the run this task starts next is told about it.
9723        let instruction = instruction_for(&after);
9724        assert!(instruction.contains("Which backend?"));
9725        assert!(instruction.contains("SQLite"));
9726    }
9727
9728    #[test]
9729    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
9730        let dir = tempfile::tempdir().unwrap();
9731        let queue = Queue::at(dir.path().join("queue"));
9732        let questions = ask::Questions::at(dir.path().join("questions"));
9733
9734        let mut q = crate::ask::Question::new(
9735            "20260101-000001-main".to_owned(),
9736            crate::conduct::NODE.to_owned(),
9737            "conduct".to_owned(),
9738            "Is the setup done?".to_owned(),
9739            String::new(),
9740            Vec::new(),
9741        );
9742        q.abandon("no answer within 60s of asking");
9743        questions.put(&mut q).unwrap();
9744
9745        let mut blocked = task();
9746        blocked.id = "20260101-000001-main".to_owned();
9747        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
9748        queue.put(&mut blocked).unwrap();
9749
9750        resolve_blockers(&queue, &questions);
9751
9752        let after = queue.get(&blocked.id).unwrap();
9753        assert_eq!(
9754            after.status,
9755            TaskStatus::Held,
9756            "never left blocked on nothing"
9757        );
9758        assert!(!after.operator_held(), "a machine hold, for triage");
9759        assert!(
9760            after
9761                .hold_reason
9762                .as_deref()
9763                .unwrap_or_default()
9764                .contains("went unanswered")
9765        );
9766    }
9767
9768    #[test]
9769    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
9770        // Reproduces the reported bug (task 3958): a task held out of
9771        // attempts, blocked on a `crate::conduct` follow-up question, must
9772        // come back `held` once that question is answered - never `queued`,
9773        // whatever the answer said - or it silently re-enters the
9774        // competition queue with its attempts already exhausted.
9775        let dir = tempfile::tempdir().unwrap();
9776        let queue = Queue::at(dir.path().join("queue"));
9777        let questions = ask::Questions::at(dir.path().join("questions"));
9778
9779        let mut q = crate::ask::Question::new(
9780            "20260101-000001-main".to_owned(),
9781            crate::conduct::NODE.to_owned(),
9782            "conduct".to_owned(),
9783            "How should this be handled?".to_owned(),
9784            String::new(),
9785            Vec::new(),
9786        );
9787        questions.put(&mut q).unwrap();
9788        q.answer(crate::ask::Answer::Text(
9789            "leave it held, a human will look at it later".to_owned(),
9790        ))
9791        .unwrap();
9792        questions.put(&mut q).unwrap();
9793
9794        let mut held = task();
9795        held.id = "20260101-000001-main".to_owned();
9796        held.hold_machine(Some("out of attempts".to_owned()));
9797        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
9798        queue.put(&mut held).unwrap();
9799
9800        resolve_blockers(&queue, &questions);
9801
9802        let after = queue.get(&held.id).unwrap();
9803        assert_eq!(after.status, TaskStatus::Held);
9804        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
9805        assert_eq!(
9806            after.answers[0].answer,
9807            "leave it held, a human will look at it later"
9808        );
9809    }
9810
9811    #[test]
9812    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
9813        let dir = tempfile::tempdir().unwrap();
9814        let queue = Queue::at(dir.path().join("queue"));
9815        let questions = ask::Questions::at(dir.path().join("questions"));
9816        let mut dep = task();
9817        dep.id = "20260101-000001-gone".to_owned();
9818        queue.put(&mut dep).unwrap();
9819        let mut blocked = task();
9820        blocked.id = "20260101-000003-main".to_owned();
9821        blocked.block(vec![dep.id.clone()], None);
9822        queue.put(&mut blocked).unwrap();
9823
9824        // Claimed, so `remove` cannot rewrite it and the resolver must.
9825        let claim = queue.claim(&blocked.id).unwrap();
9826        queue.remove(&dep.id, false, &questions).unwrap();
9827        drop(claim);
9828        resolve_blockers(&queue, &questions);
9829
9830        let after = queue.get(&blocked.id).unwrap();
9831        assert_eq!(after.status, TaskStatus::Queued);
9832        assert!(after.blocked_by.is_empty());
9833    }
9834
9835    #[test]
9836    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
9837        // Reproduces the reported bug: a task blocked on a task id that was
9838        // removed (`magi task rm`, or deleted by hand) can never see that id
9839        // reach `Done`, so the ordinary per-id loop has nothing to notice and
9840        // would otherwise leave the task `blocked` forever with no way for an
9841        // operator to find out why.
9842        let dir = tempfile::tempdir().unwrap();
9843        let queue = Queue::at(dir.path().join("queue"));
9844        let questions = ask::Questions::at(dir.path().join("questions"));
9845
9846        let mut still_going = task();
9847        still_going.id = "20260101-000002-dep1".to_owned();
9848        queue.put(&mut still_going).unwrap();
9849
9850        let mut blocked = task();
9851        blocked.id = "20260101-000003-main".to_owned();
9852        blocked.block(
9853            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
9854            Some("waits on both".to_owned()),
9855        );
9856        queue.put(&mut blocked).unwrap();
9857
9858        resolve_blockers(&queue, &questions);
9859
9860        let after = queue.get(&blocked.id).unwrap();
9861        assert_eq!(
9862            after.status,
9863            TaskStatus::Held,
9864            "a missing dependency must not leave the task blocked forever"
9865        );
9866        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
9867        assert!(after.blocked_by.is_empty());
9868        let reason = after.hold_reason.as_deref().unwrap_or_default();
9869        assert!(
9870            reason.contains("20260101-000001-gone"),
9871            "the missing id must be named so an operator can tell what happened: {reason}"
9872        );
9873        assert!(
9874            reason.contains(&still_going.id),
9875            "the still-valid dependency must not silently vanish from the record: {reason}"
9876        );
9877    }
9878
9879    #[test]
9880    fn instruction_for_is_unchanged_without_any_answers() {
9881        let t = task();
9882        assert_eq!(instruction_for(&t), t.instruction);
9883    }
9884
9885    #[test]
9886    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
9887        let dir = tempfile::tempdir().unwrap();
9888        let q = Queue::at(dir.path().join("queue"));
9889        let src = dir.path().join("shot.png");
9890        std::fs::write(&src, "x").unwrap();
9891        let mut t = task();
9892        q.attach(&mut t, &[src]).unwrap();
9893        let paths = task_attachments(&q, &t).unwrap();
9894        assert_eq!(paths.len(), 1);
9895        assert!(paths[0].is_absolute() && paths[0].is_file());
9896        std::fs::remove_file(&paths[0]).unwrap();
9897        let err = task_attachments(&q, &t).unwrap_err().to_string();
9898        assert!(err.contains("shot.png"), "{err}");
9899    }
9900
9901    #[tokio::test]
9902    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
9903        let dir = tempfile::tempdir().unwrap();
9904        let queue_path = dir.path().join("queue");
9905        let queue = Queue::at(queue_path.clone());
9906        let mut t = task();
9907        t.source = Source::Agent {
9908            run: "originating-chat".into(),
9909            node: crate::queue::CHAT_NODE.into(),
9910        };
9911        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
9912            stage: "config-fetch",
9913            target: "origin/main".into(),
9914        });
9915        record_config_failure(&mut t, &fetch);
9916        t.hold_machine(Some(format!("{fetch:#}")));
9917        let fetch_key = t.chat_notice_due().unwrap();
9918        t.chat_notices.push(fetch_key.clone());
9919        queue.put(&mut t).unwrap();
9920
9921        let queue = Queue::at(queue_path);
9922        let mut t = queue.get(&t.id).unwrap();
9923        let a = dir.path().join("a.toml");
9924        let b = dir.path().join("b.toml");
9925        for (path, text, new_cause) in [
9926            (&a, "[graph", true),
9927            (&a, "[verify", false),
9928            (&a, "[graph]\nimplementers = 'invalid-type'", true),
9929            (&b, "[graph]\nimplementers = 'invalid-type'", true),
9930        ] {
9931            t.release_operator("test", None);
9932            std::fs::write(path, text).unwrap();
9933            let error = Config::discover_fetched(dir.path(), Some(path))
9934                .await
9935                .unwrap_err();
9936            record_config_failure(&mut t, &error);
9937            t.hold_machine(Some(format!("{error:#}")));
9938            let due = t.chat_notice_due();
9939            assert_eq!(due.is_some(), new_cause, "{error:#}");
9940            if let Some(key) = due {
9941                assert_ne!(key, fetch_key);
9942                t.chat_notices.push(key);
9943            }
9944        }
9945        t.succeed();
9946        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
9947    }
9948
9949    #[test]
9950    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
9951        let dir = tempfile::tempdir().unwrap();
9952        let queue_path = dir.path().join("queue");
9953        let queue = Queue::at(queue_path.clone());
9954        let mut t = task();
9955        t.source = crate::queue::Source::Agent {
9956            run: "originating-chat".into(),
9957            node: crate::queue::CHAT_NODE.into(),
9958        };
9959        let a = dir.path().join("a.png");
9960        let b = dir.path().join("b.png");
9961        std::fs::write(&a, "a").unwrap();
9962        std::fs::write(&b, "b").unwrap();
9963        queue.attach(&mut t, &[a, b]).unwrap();
9964        let paths = task_attachments(&queue, &t).unwrap();
9965        for path in &paths {
9966            std::fs::remove_file(path).unwrap();
9967        }
9968        let missing = task_attachments(&queue, &t).unwrap_err();
9969        t.attempts += 1;
9970        let reason = missing.to_string();
9971        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9972        let first = t.chat_notice_due().expect("first attachment notice");
9973        t.chat_notices.push(first.clone());
9974        queue.put(&mut t).unwrap();
9975
9976        let queue = Queue::at(queue_path.clone());
9977        let mut t = queue.get(&t.id).unwrap();
9978        assert!(t.chat_notice_due().is_none(), "restart does not replay");
9979        t.release_operator("test", None);
9980        t.attempts += 1;
9981        let missing = task_attachments(&queue, &t).unwrap_err();
9982        t.fail_startup_target(
9983            "startup-attachments",
9984            missing.name,
9985            "same missing attachment with regenerated wording",
9986            1,
9987        );
9988        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
9989
9990        std::fs::write(&paths[0], "restored").unwrap();
9991        t.release_operator("test", None);
9992        t.attempts += 1;
9993        let missing = task_attachments(&queue, &t).unwrap_err();
9994        let reason = missing.to_string();
9995        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
9996        let second = t
9997            .chat_notice_due()
9998            .expect("different attachment must notify");
9999        assert_ne!(first, second);
10000        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
10001    }
10002
10003    #[test]
10004    fn resumed_instruction_is_unchanged_without_any_answers() {
10005        let t = task();
10006        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
10007    }
10008
10009    #[test]
10010    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
10011        let mut t = task();
10012        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10013        // The run's own instruction on disk predates the answer: it is the
10014        // plain original text `Runner::start` saved before the operator was
10015        // ever asked anything.
10016        let old = t.instruction.clone();
10017
10018        let refreshed = resumed_instruction(&old, &t);
10019        assert!(refreshed.starts_with(&old), "the original text is kept");
10020        assert!(refreshed.contains("Which backend?"));
10021        assert!(refreshed.contains("SQLite"));
10022    }
10023
10024    #[test]
10025    fn resumed_instruction_keeps_an_original_answers_heading() {
10026        let mut t = task();
10027        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
10028        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10029
10030        let refreshed = resumed_instruction(&t.instruction, &t);
10031
10032        assert!(
10033            refreshed.starts_with(&t.instruction),
10034            "an answers heading in the original instruction is not the appended block"
10035        );
10036        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
10037        assert!(refreshed.contains("Which backend?"));
10038        assert!(refreshed.contains("SQLite"));
10039
10040        let repeated = resumed_instruction(&refreshed, &t);
10041        assert_eq!(
10042            repeated, refreshed,
10043            "only the final appended block is refreshed"
10044        );
10045    }
10046
10047    #[test]
10048    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
10049        let mut t = task();
10050        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10051
10052        // A first resume appends the block; a second resume of the same run,
10053        // with no new answer in between, must reproduce exactly the same
10054        // text rather than appending the block a second time.
10055        let once = resumed_instruction(&t.instruction, &t);
10056        let twice = resumed_instruction(&once, &t);
10057        assert_eq!(once, twice);
10058        assert_eq!(once.matches("Which backend?").count(), 1);
10059
10060        // A later answer replaces the block wholesale rather than growing it.
10061        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
10062        let refreshed = resumed_instruction(&once, &t);
10063        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
10064        assert!(refreshed.contains("Which backend?"));
10065        assert!(refreshed.contains("Which cache?"));
10066    }
10067
10068    #[test]
10069    fn prepare_instruction_covers_all_three_starters() {
10070        let mut t = task();
10071        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
10072
10073        // Start: a fresh run gets the task text plus every answer so far —
10074        // exactly `instruction_for`.
10075        assert_eq!(
10076            prepare_instruction(&Starter::Start, None, &t),
10077            Some(instruction_for(&t))
10078        );
10079
10080        // Resume: the run's prior instruction is refreshed with the answer,
10081        // not discarded and not left stale.
10082        let old = t.instruction.clone();
10083        assert_eq!(
10084            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
10085            Some(resumed_instruction(&old, &t))
10086        );
10087
10088        // Review: a review-only pass builds its own instruction from the
10089        // branch's history in `crate::graph`, with no task statement at all -
10090        // this boundary must leave it alone.
10091        assert_eq!(
10092            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
10093            None
10094        );
10095    }
10096
10097    #[test]
10098    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
10099        assert_eq!(
10100            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
10101            Starter::Review("magi/eba2/A".to_owned())
10102        );
10103    }
10104
10105    #[test]
10106    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
10107        assert_eq!(
10108            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
10109            Starter::Start,
10110            "a vanished review branch must not fall back to resuming the old run either"
10111        );
10112    }
10113
10114    #[test]
10115    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
10116        let mut t = task();
10117        t.start("old-run".to_owned());
10118        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
10119        t.release();
10120        let branch = t.review_branch.take();
10121        assert_eq!(
10122            choose_starter(branch.as_deref(), true, Some("old-run")),
10123            Starter::Review("magi/eba2/A".to_owned()),
10124            "a review wins over resuming the old run"
10125        );
10126    }
10127
10128    #[test]
10129    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
10130        assert_eq!(
10131            choose_starter(None, false, Some("some-run")),
10132            Starter::Resume("some-run".to_owned())
10133        );
10134        assert_eq!(choose_starter(None, false, None), Starter::Start);
10135    }
10136
10137    #[test]
10138    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
10139        let mut released = task();
10140        released.start("stalled-run".to_owned());
10141        released.requeue();
10142        let unfinished = (!released.fresh_start)
10143            .then(|| Some("stalled-run".to_owned()))
10144            .flatten();
10145        assert_eq!(
10146            choose_starter(None, false, unfinished.as_deref()),
10147            Starter::Start,
10148            "release keeps run history but must not resume it"
10149        );
10150        assert_eq!(released.runs, ["stalled-run"]);
10151    }
10152
10153    #[test]
10154    fn an_ordinary_release_keeps_a_resumable_run_available() {
10155        let mut released = task();
10156        released.start("stalled-run".to_owned());
10157        released.release();
10158        let unfinished = (!released.fresh_start)
10159            .then(|| Some("stalled-run".to_owned()))
10160            .flatten();
10161        assert_eq!(
10162            choose_starter(None, false, unfinished.as_deref()),
10163            Starter::Resume("stalled-run".to_owned()),
10164            "manual release must preserve the normal resume path"
10165        );
10166    }
10167
10168    #[test]
10169    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
10170        let mut state = run_state(RunStatus::Blocked);
10171        state.config.graph.review_rounds = 3;
10172        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
10173        assert!(exhausted_review_budget(&state));
10174
10175        // One round still unused: resuming can still ask a reviewer something.
10176        state.reviews.pop();
10177        assert!(!exhausted_review_budget(&state));
10178
10179        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
10180        // count: only a `Blocked` run re-enters the review loop on resume.
10181        let mut stalled = run_state(RunStatus::Stalled);
10182        stalled.config.graph.review_rounds = 1;
10183        stalled.reviews = vec![review_round(1)];
10184        assert!(!exhausted_review_budget(&stalled));
10185    }
10186
10187    fn review_round(round: usize) -> crate::run::ReviewRound {
10188        crate::run::ReviewRound {
10189            round,
10190            head: "deadbeef".to_owned(),
10191            verified_head: None,
10192            verified_at: None,
10193            reviews: Vec::new(),
10194            e2e: Vec::new(),
10195            verify_retried: false,
10196            e2e_deferred: false,
10197            e2e_defer_reason: None,
10198            fix: None,
10199            blocking: 0,
10200            answered: 1,
10201            expected: 1,
10202            clean: false,
10203            progressed: true,
10204            vote_split: false,
10205            reconsideration: Vec::new(),
10206            verdict: None,
10207        }
10208    }
10209
10210    #[test]
10211    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
10212        let mut run = RunState::new(
10213            PathBuf::from("/repo"),
10214            "main".to_owned(),
10215            "abc1234def".to_owned(),
10216            "add retries".to_owned(),
10217            Config::default(),
10218        );
10219        run.status = RunStatus::Judging;
10220        run.parked = true;
10221        let mut task = Task::new(
10222            "add retries".to_owned(),
10223            "add retries".to_owned(),
10224            PathBuf::from("/repo"),
10225            crate::queue::Source::Human,
10226        );
10227        task.status = TaskStatus::Failed;
10228        task.runs = vec![run.id.clone()];
10229        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
10230        assert!(with(&task, &run), "parked after judging is the case");
10231        let mut parked_task = task.clone();
10232        parked_task.status = TaskStatus::Parked;
10233        assert!(with(&parked_task, &run), "the Parked status is the case");
10234
10235        let mut not_parked = run.clone();
10236        not_parked.parked = false;
10237        not_parked.status = RunStatus::Stalled;
10238        assert!(!with(&task, &not_parked), "a stall is the conductor's");
10239
10240        let mut fresh = task.clone();
10241        fresh.fresh_start = true;
10242        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
10243
10244        let mut review = task.clone();
10245        review.review_branch = Some("magi/x/A".to_owned());
10246        assert!(!with(&review, &run), "review is ranked before resume");
10247
10248        let mut held = task.clone();
10249        held.status = TaskStatus::Held;
10250        assert!(!with(&held, &run), "a hold stays visible to the conductor");
10251
10252        let mut released = run.clone();
10253        released.released_to = Some("20260901-000000-new1".to_owned());
10254        assert!(!with(&task, &released), "nothing left to resume into");
10255
10256        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
10257            "unreadable"
10258        )));
10259    }
10260
10261    #[test]
10262    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
10263        let mut released = RunState::new(
10264            PathBuf::from("/repo"),
10265            "main".to_owned(),
10266            "abc1234def".to_owned(),
10267            "add retries".to_owned(),
10268            Config::default(),
10269        );
10270        released.status = RunStatus::Blocked;
10271        assert_eq!(
10272            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10273            Some(released.id.clone())
10274        );
10275        released.released_to = Some("20260901-000000-new1".to_owned());
10276        assert_eq!(
10277            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
10278            None,
10279            "there is nothing left to resume it into"
10280        );
10281    }
10282
10283    #[test]
10284    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
10285        // Mirrors the failure this exists to close: a task's last run ended
10286        // `Blocked` with the review budget spent, `crate::conduct` chose
10287        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
10288        // evidence), and without this check `attempt` would go on treating
10289        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
10290        // review loop iterates zero times over an already-spent budget, so
10291        // the resumed run settles right back to `Blocked` having asked nobody
10292        // anything, and `Requeue`'s promised fresh competition never happens.
10293        let mut exhausted = RunState::new(
10294            PathBuf::from("/repo"),
10295            "main".to_owned(),
10296            "abc1234def".to_owned(),
10297            "add retries".to_owned(),
10298            Config::default(),
10299        );
10300        exhausted.status = RunStatus::Blocked;
10301        exhausted.config.graph.review_rounds = 1;
10302        exhausted.reviews = vec![review_round(1)];
10303
10304        assert_eq!(
10305            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
10306            None,
10307            "an exhausted `Blocked` run must not be offered as resumable"
10308        );
10309
10310        // A `Blocked` run with rounds still unused is genuinely worth
10311        // resuming, and must still be found.
10312        let mut has_budget_left = RunState::new(
10313            PathBuf::from("/repo"),
10314            "main".to_owned(),
10315            "abc1234def".to_owned(),
10316            "add retries".to_owned(),
10317            Config::default(),
10318        );
10319        has_budget_left.status = RunStatus::Blocked;
10320        has_budget_left.config.graph.review_rounds = 3;
10321        has_budget_left.reviews = vec![review_round(1)];
10322
10323        assert_eq!(
10324            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
10325                Ok(has_budget_left.clone())
10326            }),
10327            Some(has_budget_left.id.clone())
10328        );
10329    }
10330
10331    #[test]
10332    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
10333        let mut run = RunState::new(
10334            PathBuf::from("/repo"),
10335            "main".to_owned(),
10336            "abc1234def".to_owned(),
10337            "add retries".to_owned(),
10338            Config::default(),
10339        );
10340        run.status = RunStatus::Blocked;
10341        run.config.graph.review_rounds = 1;
10342        run.reviews = vec![review_round(1)];
10343        run.pr_publication_pending = true;
10344        assert_eq!(
10345            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
10346            Some(run.id.clone()),
10347            "a spent review budget must not turn a failed publication into a re-competition"
10348        );
10349    }
10350
10351    #[test]
10352    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
10353        // A task whose history holds an *older* run that still looks
10354        // resumable (say, a competition `Runner::review` was started
10355        // alongside after that older run went `Stalled`) and a *newest* run
10356        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
10357        // on this task must mean a fresh competition — falling back to the
10358        // stale, superseded `Stalled` run instead would resurrect history
10359        // nothing asked to revisit and silently defeat the requeue.
10360        let mut older_stalled = RunState::new(
10361            PathBuf::from("/repo"),
10362            "main".to_owned(),
10363            "abc1234def".to_owned(),
10364            "add retries".to_owned(),
10365            Config::default(),
10366        );
10367        older_stalled.status = RunStatus::Stalled;
10368
10369        let mut newest_exhausted = RunState::new(
10370            PathBuf::from("/repo"),
10371            "main".to_owned(),
10372            "abc1234def".to_owned(),
10373            "add retries".to_owned(),
10374            Config::default(),
10375        );
10376        newest_exhausted.status = RunStatus::Blocked;
10377        newest_exhausted.config.graph.review_rounds = 1;
10378        newest_exhausted.reviews = vec![review_round(1)];
10379
10380        assert_eq!(
10381            unfinished_run_with(
10382                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
10383                "t",
10384                |_| Ok(newest_exhausted.clone())
10385            ),
10386            None,
10387            "the newest run is exhausted, so nothing here is worth resuming - \
10388             least of all the older, already-superseded run"
10389        );
10390    }
10391
10392    #[test]
10393    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
10394        assert_eq!(
10395            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
10396                Err(anyhow::anyhow!("fixture is absent"))
10397            }),
10398            None
10399        );
10400    }
10401
10402    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
10403        let mut q = ask::Question::new(
10404            run.to_owned(),
10405            "implement".to_owned(),
10406            "impl-A".to_owned(),
10407            "continue?".to_owned(),
10408            String::new(),
10409            vec!["resume で続行する".to_owned(), "other".to_owned()],
10410        );
10411        q.actions.insert("resume で続行する".to_owned(), action);
10412        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
10413            .unwrap();
10414        q
10415    }
10416
10417    fn held_task_with(run: &str) -> Task {
10418        let mut t = task();
10419        t.runs = vec![run.to_owned()];
10420        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
10421        t
10422    }
10423
10424    fn resume_action(run: &str) -> ask::ChoiceAction {
10425        ask::ChoiceAction::Resume { run: run.into() }
10426    }
10427
10428    #[test]
10429    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
10430        for parked in [false, true] {
10431            let mut t = task();
10432            t.start("A".into());
10433            t.start("B".into());
10434            assert_eq!(t.runs, vec!["A", "B"]);
10435            t.start("A".into());
10436            let mut resumed = run_state(RunStatus::Blocked);
10437            resumed.id = "A".into();
10438            resumed.parked = parked;
10439            resumed.driver_exited = true;
10440            t.hold_machine(Some("resumed run stopped".into()));
10441            let q = action_question("A", resume_action("A"));
10442            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10443            assert_eq!(
10444                decide_action(&t, &q, &PHRASES_EN, |id| {
10445                    assert_eq!(id, "A");
10446                    Ok(resumed.clone())
10447                }),
10448                ActionDecision::Resume("A".into())
10449            );
10450            assert_eq!(
10451                action_standing(&t, &action_question("B", resume_action("B"))),
10452                ActionStanding::Stale
10453            );
10454            t.release_operator("cli", None);
10455            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
10456                assert_eq!(id, "A");
10457                Ok(resumed.clone())
10458            });
10459            assert_eq!(
10460                choose_starter(None, false, unfinished.as_deref()),
10461                Starter::Resume("A".into())
10462            );
10463            assert_eq!(t.runs, vec!["B", "A"]);
10464        }
10465    }
10466
10467    #[test]
10468    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
10469        let mut state = crate::land::tests::repair_state(true, true);
10470        state.status = RunStatus::Landing;
10471        state.parked = true;
10472        state.driver_exited = true;
10473        let mut q = ask::Question::new(
10474            state.id.clone(),
10475            land::APPROVAL_NODE.into(),
10476            "land".into(),
10477            "Merge?".into(),
10478            String::new(),
10479            vec![land::APPROVE.into(), land::HOLD.into()],
10480        );
10481        q.id = state.id.clone();
10482        state.land_approval = Some(crate::run::LandApproval {
10483            question: q.id.clone(),
10484            head: "current-head".into(),
10485        });
10486        assert!(land::upgrade_repair_choice(&mut q, &state));
10487        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10488        let mut task = held_task_with(&state.id);
10489        task.status = TaskStatus::Parked;
10490        assert_eq!(
10491            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10492            ActionDecision::Resume(state.id.clone())
10493        );
10494        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10495        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
10496        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
10497        assert_eq!(
10498            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
10499            ActionDecision::Resume(state.id.clone()),
10500            "a repair answer newer than the manual hold resumes the existing owner"
10501        );
10502        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10503        for answered_at in [q.answered_at, None] {
10504            let mut older = q.clone();
10505            older.answered_at = answered_at;
10506            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
10507                panic!("a later manual hold must prevent dispatch")
10508            });
10509            let ActionDecision::Refuse(reason) = refused else {
10510                panic!("expected an actionable refusal, got {refused:?}");
10511            };
10512            assert!(reason.contains("later operator decision"));
10513            assert!(reason.contains(&format!("magi task release {}", task.id)));
10514        }
10515        task.operator_decided_at = None;
10516        let mut superseded = state.clone();
10517        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
10518        assert_eq!(
10519            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
10520            ActionDecision::Stale
10521        );
10522        for case in 1..4 {
10523            let mut changed = state.clone();
10524            match case {
10525                1 => changed.status = RunStatus::Blocked,
10526                2 => changed.released_to = Some("new-owner".into()),
10527                _ => changed.land_approval.as_mut().unwrap().head.clear(),
10528            }
10529            assert!(matches!(
10530                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
10531                ActionDecision::Refuse(_)
10532            ));
10533        }
10534        assert!(matches!(
10535            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
10536            ActionDecision::Refuse(_)
10537        ));
10538        task.runs.push("replacement".into());
10539        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
10540        assert_eq!(
10541            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
10542                "old owner must not load"
10543            )),
10544            ActionDecision::Stale
10545        );
10546    }
10547
10548    #[test]
10549    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
10550        let mut state = crate::land::tests::repair_state(true, true);
10551        state.status = RunStatus::Landing;
10552        state.parked = true;
10553        state.driver_exited = true;
10554        let mut q = ask::Question::new(
10555            state.id.clone(),
10556            land::APPROVAL_NODE.into(),
10557            "land".into(),
10558            "Merge?".into(),
10559            String::new(),
10560            vec![land::APPROVE.into(), land::HOLD.into()],
10561        );
10562        q.id = state.id.clone();
10563        state.land_approval = Some(crate::run::LandApproval {
10564            question: q.id.clone(),
10565            head: "current-head".into(),
10566        });
10567        state.save().unwrap();
10568        land::upgrade_repair_choice(&mut q, &state);
10569        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10570        Questions::open().put(&mut q).unwrap();
10571        let tmp = tempfile::tempdir().unwrap();
10572        let queue = Queue::at(tmp.path().join("queue"));
10573        let mut task = held_task_with(&state.id);
10574        task.status = TaskStatus::Parked;
10575        queue.put(&mut task).unwrap();
10576        let empty = Arc::new(tokio::sync::Semaphore::new(0));
10577        let free = Arc::new(tokio::sync::Semaphore::new(1));
10578        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
10579        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
10580        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
10581        assert!(claim.permit.is_some());
10582        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
10583        drop(claim);
10584        Questions::open()
10585            .update(&q.id, |q| {
10586                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
10587                Ok(())
10588            })
10589            .unwrap();
10590        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
10591        assert!(claim.permit.is_none());
10592        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
10593    }
10594
10595    #[test]
10596    fn decide_action_resumes_only_the_latest_resumable_run() {
10597        let t = held_task_with("r1");
10598        let q = action_question("r1", resume_action("r1"));
10599        let load = |s: RunState| move |_: &str| Ok(s);
10600        assert_eq!(
10601            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
10602            ActionDecision::Resume("r1".into())
10603        );
10604        // Not the latest run of the task.
10605        let q_other = action_question("r1", resume_action("r0"));
10606        assert!(matches!(
10607            decide_action(
10608                &t,
10609                &q_other,
10610                &PHRASES_EN,
10611                load(run_state(RunStatus::Blocked))
10612            ),
10613            ActionDecision::Refuse(_)
10614        ));
10615        // A finished run cannot make progress.
10616        assert!(matches!(
10617            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
10618            ActionDecision::Refuse(_)
10619        ));
10620        // A released one either.
10621        let mut released = run_state(RunStatus::Blocked);
10622        released.released_to = Some("elsewhere".into());
10623        assert!(matches!(
10624            decide_action(&t, &q, &PHRASES_EN, load(released)),
10625            ActionDecision::Refuse(_)
10626        ));
10627        // Unreadable state is a refusal, never a fresh competition.
10628        assert!(matches!(
10629            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
10630            ActionDecision::Refuse(_)
10631        ));
10632    }
10633
10634    #[test]
10635    fn decide_action_ignores_a_question_about_an_earlier_run() {
10636        let mut t = held_task_with("r1");
10637        t.runs.push("r2".to_owned());
10638        let never = |_: &str| -> Result<RunState> { bail!("not read") };
10639        assert_eq!(
10640            decide_action(
10641                &t,
10642                &action_question("r1", ask::ChoiceAction::Done),
10643                &PHRASES_EN,
10644                never
10645            ),
10646            ActionDecision::Stale
10647        );
10648    }
10649
10650    #[test]
10651    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
10652        let mut t = held_task_with("r1");
10653        let never = |_: &str| -> Result<RunState> { bail!("not read") };
10654        assert_eq!(
10655            decide_action(
10656                &t,
10657                &action_question("r1", ask::ChoiceAction::Requeue),
10658                &PHRASES_EN,
10659                never
10660            ),
10661            ActionDecision::Requeue
10662        );
10663        let done_q = action_question("r1", ask::ChoiceAction::Done);
10664        assert_eq!(
10665            decide_action(&t, &done_q, &PHRASES_EN, never),
10666            ActionDecision::Done
10667        );
10668        t.mark_action_applied(&done_q.id);
10669        assert_eq!(
10670            decide_action(&t, &done_q, &PHRASES_EN, never),
10671            ActionDecision::Skip
10672        );
10673
10674        // A plain answer (no action for that label) does nothing.
10675        let mut plain = action_question("r1", ask::ChoiceAction::Done);
10676        plain.actions.clear();
10677        assert_eq!(
10678            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
10679            ActionDecision::Skip
10680        );
10681        // A running task is left alone.
10682        let mut running = held_task_with("r1");
10683        running.status = TaskStatus::Running;
10684        assert_eq!(
10685            decide_action(
10686                &running,
10687                &action_question("r1", ask::ChoiceAction::Done),
10688                &PHRASES_EN,
10689                never
10690            ),
10691            ActionDecision::Skip
10692        );
10693    }
10694
10695    #[test]
10696    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
10697        crate::run::pin_test_home();
10698        for legacy in [false, true] {
10699            let dir = tempfile::tempdir().unwrap();
10700            let queue = Queue::at(dir.path().join("queue"));
10701            let questions = Questions::at(dir.path().join("questions"));
10702            let run = "20260101-000000-hold";
10703            let mut task = held_task_with(run);
10704            task.status = TaskStatus::Parked;
10705            let mut q = ask::Question::new(
10706                run.into(),
10707                land::APPROVAL_NODE.into(),
10708                "land".into(),
10709                "Repair?".into(),
10710                String::new(),
10711                vec![land::REPAIR.into()],
10712            );
10713            q.actions.insert(land::REPAIR.into(), resume_action(run));
10714            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
10715            // Deterministically order the answer before the actual manual hold.
10716            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
10717            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
10718            questions.put(&mut q).unwrap();
10719            task.hold_manual(Some("Keep this PR paused".into()));
10720            if legacy {
10721                task.hold_source = None;
10722            }
10723            queue.put(&mut task).unwrap();
10724
10725            apply_task_choice_actions(&queue, &questions, dir.path());
10726            let after = queue.get(&task.id).unwrap();
10727            assert!(after.operator_held());
10728            assert_eq!(after.hold_source, task.hold_source);
10729            assert_eq!(after.operator_decided_at, task.operator_decided_at);
10730            assert_eq!(after.runs, task.runs);
10731            assert_eq!(after.instruction, task.instruction);
10732            assert!(after.resume_override.is_none());
10733            assert!(after.action_applied(&q.id));
10734            let reason = after.hold_reason.as_deref().unwrap();
10735            assert!(reason.starts_with("Keep this PR paused"));
10736            assert!(reason.contains("later operator decision"));
10737            assert!(reason.contains(&format!("magi task release {}", task.id)));
10738
10739            for recovery in [
10740                crate::conduct::Recovery::Review,
10741                crate::conduct::Recovery::Requeue,
10742            ] {
10743                crate::conduct::apply(
10744                    &queue,
10745                    &questions,
10746                    &crate::conduct::Verdict {
10747                        decisions: vec![crate::conduct::Decision {
10748                            id: task.id.clone(),
10749                            recovery: Some(recovery),
10750                            ..Default::default()
10751                        }],
10752                    },
10753                )
10754                .unwrap();
10755            }
10756            // Reconciliation is idempotent, and automatic recovery cannot
10757            // reopen this owner after it observes the rejected repair answer.
10758            apply_task_choice_actions(&queue, &questions, dir.path());
10759            let still_held = queue.get(&task.id).unwrap();
10760            assert!(still_held.operator_held());
10761            assert_eq!(still_held.hold_reason, after.hold_reason);
10762            assert_eq!(still_held.runs, task.runs);
10763            assert!(still_held.review_branch.is_none());
10764            assert!(!still_held.fresh_start);
10765            assert!(queue.next_runnable().is_none());
10766        }
10767    }
10768
10769    #[test]
10770    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
10771        for held in [false, true] {
10772            for retry in [false, true] {
10773                let dir = tempfile::tempdir().unwrap();
10774                let queue = Queue::at(dir.path().join("queue"));
10775                let questions = Questions::at(dir.path().join("questions"));
10776                let home = dir.path().join("home");
10777                let mut t = task();
10778                if held {
10779                    t.hold_machine(Some("driver state unknown".into()));
10780                }
10781                queue.put(&mut t).unwrap();
10782                let verdict = serde_json::from_value(serde_json::json!({
10783                    "decisions": [{
10784                        "id": t.id,
10785                        "question": "Driver state unknown; retry the checks or hold?",
10786                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
10787                        "actions": {
10788                            "daemon: recheck and retry": {"do": "requeue"},
10789                            "daemon: hold the task": {"do": "hold"}
10790                        }
10791                    }]
10792                }))
10793                .unwrap();
10794                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
10795                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
10796                let mut q = questions.list().pop().unwrap();
10797                let choice = if retry {
10798                    "daemon: recheck and retry"
10799                } else {
10800                    "daemon: hold the task"
10801                };
10802                assert_eq!(q.actions.len(), 2);
10803                q.answer(ask::Answer::Choice(choice.into())).unwrap();
10804                questions.put(&mut q).unwrap();
10805
10806                // A Web answer does not remove the deputy's fresh lease.
10807                questions.beat(&q.id, ask::WaiterKind::Deputy);
10808                for _ in 0..2 {
10809                    resolve_blockers(&queue, &questions);
10810                    apply_task_choice_actions(&queue, &questions, &home);
10811                    let waiting = queue.get(&t.id).unwrap();
10812                    assert_eq!(waiting.status, TaskStatus::Blocked);
10813                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
10814                    assert!(waiting.answers.is_empty());
10815                    assert!(!waiting.action_applied(&q.id));
10816                    assert!(runnable(&queue).is_empty());
10817                    let free = Arc::new(tokio::sync::Semaphore::new(1));
10818                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
10819                }
10820                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10821
10822                // Releasing the blocker and applying the operation share one save.
10823                resolve_blockers(&queue, &questions);
10824                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
10825                apply_task_choice_actions(&queue, &questions, &home);
10826                let after = queue.get(&t.id).unwrap();
10827                assert_eq!(
10828                    after.status,
10829                    if retry {
10830                        TaskStatus::Queued
10831                    } else {
10832                        TaskStatus::Held
10833                    }
10834                );
10835                assert!(after.action_applied(&q.id));
10836                assert_eq!(after.operator_held(), !retry);
10837                assert_eq!(after.answers.len(), 1);
10838
10839                // A later operator decision must not replay this answer.
10840                let mut changed = after;
10841                if retry {
10842                    changed.hold_manual(Some("later hold".into()));
10843                } else {
10844                    changed.release_operator("test", None);
10845                }
10846                let expected = changed.status;
10847                queue.put(&mut changed).unwrap();
10848                apply_task_choice_actions(&queue, &questions, &home);
10849                assert_eq!(queue.get(&t.id).unwrap().status, expected);
10850            }
10851        }
10852    }
10853
10854    #[test]
10855    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
10856        let dir = tempfile::tempdir().unwrap();
10857        let queue = Queue::at(dir.path().join("queue"));
10858        let questions = Questions::at(dir.path().join("questions"));
10859        let home = dir.path().join("home");
10860        let mut state = run_state(RunStatus::Blocked);
10861        state.id = "20260101-000000-act1".to_owned();
10862        state.save_under(&home).unwrap();
10863
10864        let mut t = held_task_with(&state.id);
10865        queue.put(&mut t).unwrap();
10866        let mut q = action_question(&state.id, resume_action(&state.id));
10867        questions.put(&mut q).unwrap();
10868
10869        apply_task_choice_actions(&queue, &questions, &home);
10870        let after = queue.get(&t.id).unwrap();
10871        assert_eq!(after.status, TaskStatus::Queued);
10872        assert!(!after.fresh_start);
10873        assert!(after.action_applied(&q.id));
10874        let pin = after.resume_override.clone().unwrap();
10875        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
10876        assert!(pin.forced);
10877
10878        // Held again later: the same answer does not release it a second time.
10879        let mut again = queue.get(&t.id).unwrap();
10880        again.hold_machine(Some("later".into()));
10881        queue.put(&mut again).unwrap();
10882        apply_task_choice_actions(&queue, &questions, &home);
10883        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10884    }
10885
10886    #[test]
10887    fn a_delivered_answer_is_still_acted_on_exactly_once() {
10888        let dir = tempfile::tempdir().unwrap();
10889        let queue = Queue::at(dir.path().join("queue"));
10890        let questions = Questions::at(dir.path().join("questions"));
10891        let home = dir.path().join("home");
10892        let mut state = run_state(RunStatus::Blocked);
10893        state.id = "20260101-000000-act2".to_owned();
10894        state.save_under(&home).unwrap();
10895
10896        let mut t = held_task_with(&state.id);
10897        queue.put(&mut t).unwrap();
10898        let mut q = action_question(&state.id, resume_action(&state.id));
10899        q.answer_delivered = true;
10900        questions.put(&mut q).unwrap();
10901
10902        // Delivered, and the agent then died: the task is still held, so the
10903        // chosen action applies.
10904        apply_task_choice_actions(&queue, &questions, &home);
10905        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10906        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
10907
10908        // Held again: the same answer does nothing a second time.
10909        let mut again = queue.get(&t.id).unwrap();
10910        again.hold_machine(Some("later".into()));
10911        queue.put(&mut again).unwrap();
10912        apply_task_choice_actions(&queue, &questions, &home);
10913        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10914    }
10915
10916    #[test]
10917    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
10918        let dir = tempfile::tempdir().unwrap();
10919        let queue = Queue::at(dir.path().join("queue"));
10920        let questions = Questions::at(dir.path().join("questions"));
10921        let home = dir.path().join("home");
10922        let mut state = run_state(RunStatus::Blocked);
10923        state.id = "20260101-000000-act3".to_owned();
10924        state.save_under(&home).unwrap();
10925        let mut t = held_task_with(&state.id);
10926        queue.put(&mut t).unwrap();
10927        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
10928        questions.put(&mut q).unwrap();
10929
10930        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
10931        apply_task_choice_actions(&queue, &questions, &home);
10932        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10933
10934        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
10935        apply_task_choice_actions(&queue, &questions, &home);
10936        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10937    }
10938
10939    #[test]
10940    fn action_standing_tells_the_reasons_apart() {
10941        let mut t = held_task_with("r1");
10942        let q = action_question("r1", ask::ChoiceAction::Requeue);
10943        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
10944        let mut plain = q.clone();
10945        plain.actions.clear();
10946        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
10947
10948        // Applied wins over everything, even a running task.
10949        t.mark_action_applied(&q.id);
10950        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
10951
10952        // A newer attempt running: the old question is Stale, not Busy.
10953        let mut t = held_task_with("r1");
10954        t.start("r2".to_owned());
10955        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
10956        // The same question about the latest run just waits.
10957        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
10958        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10959        t.status = TaskStatus::Blocked;
10960        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
10961
10962        // A conductor question is keyed by the task, never stale.
10963        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
10964        c.node = crate::conduct::NODE.to_owned();
10965        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
10966        assert!(!ActionStanding::Busy.daemon_owns());
10967    }
10968
10969    #[test]
10970    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
10971        let dir = tempfile::tempdir().unwrap();
10972        let queue = Queue::at(dir.path().join("queue"));
10973        let questions = Questions::at(dir.path().join("questions"));
10974        let home = dir.path().join("home");
10975        let mut state = run_state(RunStatus::Blocked);
10976        state.id = "20260101-000000-act4".to_owned();
10977        state.save_under(&home).unwrap();
10978        let mut t = held_task_with(&state.id);
10979        t.status = TaskStatus::Running;
10980        queue.put(&mut t).unwrap();
10981        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
10982        q.cwd = Some(dir.path().display().to_string());
10983        questions.put(&mut q).unwrap();
10984
10985        // While the task runs the daemon will not act, so the waiter still
10986        // delivers the word to the dead asker's seat ...
10987        let running = queue.get(&t.id).unwrap();
10988        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
10989        assert!(matches!(
10990            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
10991            crate::waiter::Action::Deliver(_)
10992        ));
10993        // ... and the daemon waits while the task runs, then applies once.
10994        apply_task_choice_actions(&queue, &questions, &home);
10995        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10996        let mut back = queue.get(&t.id).unwrap();
10997        back.hold_machine(Some("later".into()));
10998        queue.put(&mut back).unwrap();
10999        apply_task_choice_actions(&queue, &questions, &home);
11000        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
11001        let mut again = queue.get(&t.id).unwrap();
11002        again.hold_machine(Some("again".into()));
11003        queue.put(&mut again).unwrap();
11004        apply_task_choice_actions(&queue, &questions, &home);
11005        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11006    }
11007}