Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// Effective startup capabilities of the question recovery loops.
137    #[serde(default)]
138    pub question_recovery: Option<crate::question_delivery::Recovery>,
139    /// Independent-worker control protocol supported by this scheduler.
140    #[serde(default)]
141    pub worker_protocol: Option<u32>,
142}
143
144impl Status {
145    /// A fresh, idle status for this process.
146    #[must_use]
147    pub fn new() -> Self {
148        let now = Timestamp::now();
149        Self {
150            schema: SCHEMA,
151            pid: std::process::id(),
152            started_at: now,
153            updated_at: now,
154            idle: true,
155            current: Vec::new(),
156            completed: 0,
157            polls: 0,
158            question_recovery: None,
159            worker_protocol: Some(1),
160        }
161    }
162}
163
164impl Default for Status {
165    fn default() -> Self {
166        Self::new()
167    }
168}
169
170/// How the loop should behave.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(default)]
173pub struct Opts {
174    /// Repository used by tasks that name none.
175    pub repo: PathBuf,
176    /// Explicit `magi.toml`, instead of the discovered layer stack.
177    pub config: Option<PathBuf>,
178    /// Queue poll interval.
179    pub poll: Duration,
180    /// Attempts a task gets before it is held for a human.
181    pub max_attempts: usize,
182    /// Drain what is runnable now, then return, instead of waiting for more.
183    pub once: bool,
184    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
185    pub merge: Option<String>,
186    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
187    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
188    /// `None` resolves to [`crate::run::default_worktree_root`] - the
189    /// operator's real `~/wt/<repo>` - the same way a run with no
190    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
191    /// that does not own that directory (a test, an embedding that manages
192    /// worktrees itself) must set this, or every idle tick reclaims worktrees
193    /// out from under whoever actually does.
194    pub worktrees_root: Option<PathBuf>,
195}
196
197impl Default for Opts {
198    fn default() -> Self {
199        Self {
200            repo: PathBuf::from("."),
201            config: None,
202            poll: POLL,
203            max_attempts: 2,
204            once: false,
205            merge: None,
206            worktrees_root: None,
207        }
208    }
209}
210
211impl Opts {
212    fn absolute(&self) -> Result<Self> {
213        let mut opts = self.clone();
214        opts.repo = std::path::absolute(&opts.repo)?;
215        opts.config = opts
216            .config
217            .as_deref()
218            .map(std::path::absolute)
219            .transpose()?;
220        opts.worktrees_root = opts
221            .worktrees_root
222            .as_deref()
223            .map(std::path::absolute)
224            .transpose()?;
225        Ok(opts)
226    }
227}
228
229/// How many runs a plain `usize` from config may drive concurrently, floored
230/// at one. A `0` in a config file would otherwise stall the loop entirely -
231/// no runnable task could ever start - which is never what an operator who
232/// wrote `0` meant.
233fn max_concurrent(n: usize) -> usize {
234    n.max(1)
235}
236
237/// Where the status file lives.
238#[must_use]
239pub fn status_path() -> PathBuf {
240    crate::run::home().join("daemon.json")
241}
242
243/// Publish the status file for this process.
244pub fn write_status(status: &Status) -> Result<()> {
245    write_status_to(&status_path(), status)
246}
247
248/// Publish a status to an explicit path.
249///
250/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
251/// on every health poll and must never see a half-written one.
252pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
253    if let Some(parent) = path.parent() {
254        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
255    }
256    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
257    let tmp = path.with_extension("json.tmp");
258    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
259    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
260    Ok(())
261}
262
263/// Delete the status file. Called on the way out so a clean exit reads as
264/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
265pub fn clear_status() {
266    clear_status_at(&status_path());
267}
268
269/// Delete a status file at an explicit path, so the loop's teardown and
270/// [`clear_status`] cannot drift apart: the loop is handed the path it
271/// published to, and a test can watch a temp file disappear.
272fn clear_status_at(path: &Path) {
273    let _ = std::fs::remove_file(path);
274}
275
276/// A cooperative stop, shared with whoever asked the loop to run.
277///
278/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
279/// Ctrl-C listener and the web UI keep others, and every clone points at the
280/// same flag. There is no channel because there is nothing to send — the only
281/// message is "stop", it is idempotent, and a flag cannot be missed by a
282/// receiver that was not listening yet.
283///
284/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
285/// detached task workers keep their own lifetimes and ownership after this
286/// handle's scheduler exits.
287#[derive(Debug, Clone, Default)]
288pub struct Stop {
289    /// Set once, never cleared: a stop is not something an operator takes back
290    /// half way through, and a clearable flag would let a start racing a stop
291    /// resurrect a loop that is already unwinding.
292    stopped: Arc<AtomicBool>,
293    /// Live task workers observed by the scheduler's latest dispatch snapshot.
294    busy: Arc<std::sync::atomic::AtomicUsize>,
295    /// Wakes the idle wait. Without this a stop would not be seen until the
296    /// poll interval elapsed, and an operator tapping stop on a phone would
297    /// watch a button do nothing for five seconds.
298    wake: Arc<Notify>,
299    /// Handed to the run in flight, so a stop can also mean "park at the next
300    /// node boundary" instead of "finish the whole competition first".
301    pause: crate::graph::Pause,
302}
303
304impl Stop {
305    /// A stop nobody has asked for yet.
306    #[must_use]
307    pub fn new() -> Self {
308        Self::default()
309    }
310
311    /// Ask the loop to stop. Idempotent, and safe to call before the loop
312    /// starts: the flag is checked before the first poll.
313    pub fn stop(&self) {
314        self.stopped.store(true, Ordering::SeqCst);
315        // `notify_one` rather than `notify_waiters` because the loop may not be
316        // parked yet: this stores a permit, so a wait that registers a moment
317        // later returns at once instead of sleeping out the whole interval.
318        self.wake.notify_one();
319    }
320
321    /// Has a stop been asked for?
322    #[must_use]
323    pub fn stopped(&self) -> bool {
324        self.stopped.load(Ordering::SeqCst)
325    }
326
327    /// Whether a requested scheduler retirement still has an active snapshot.
328    /// Workers continue independently after the scheduler has retired.
329    #[must_use]
330    pub fn finishing(&self) -> bool {
331        self.stopped() && self.busy_now()
332    }
333
334    /// Ask the loop to stop *and* the run in flight to park at its next node
335    /// boundary.
336    ///
337    /// Unlike plain stop, explicit park asks workers to checkpoint at their
338    /// existing safe boundaries. Binary replacement never needs a park.
339    pub fn park(&self, cause: crate::run::ParkCause) {
340        self.pause.park_for(cause);
341        self.stop();
342    }
343
344    /// Has a park been asked for?
345    #[must_use]
346    pub fn parking(&self) -> bool {
347        self.pause.parked()
348    }
349
350    /// The pause handle to give a runner.
351    #[must_use]
352    pub fn pause(&self) -> crate::graph::Pause {
353        self.pause.clone()
354    }
355
356    /// Whether the scheduler's latest snapshot contains active task workers.
357    #[must_use]
358    pub fn busy_now(&self) -> bool {
359        self.busy.load(Ordering::SeqCst) > 0
360    }
361
362    /// Wait out one poll interval, returning early once a stop is asked for.
363    async fn idle(&self, poll: Duration) {
364        tokio::select! {
365            () = tokio::time::sleep(poll) => {}
366            () = self.wake.notified() => {}
367        }
368    }
369}
370
371/// The daemon's published state, read permissively.
372///
373/// This mirrors [`Status`], but is a separate declaration on purpose: every
374/// field defaults, so a status file from an older or newer magi still yields
375/// a usable reading — one this build has never heard of — instead of a parse
376/// error that hides the daemon entirely.
377#[derive(Debug, Clone, Default, Deserialize)]
378#[serde(default)]
379pub struct Reading {
380    /// Format version the daemon claims.
381    pub schema: u32,
382    /// Daemon process id, for an operator who wants to stop it.
383    pub pid: Option<u32>,
384    /// When that process started.
385    pub started_at: Option<Timestamp>,
386    /// Last heartbeat. Absent means the file is unusable, hence not running.
387    pub updated_at: Option<Timestamp>,
388    /// True when the queue had nothing runnable at the last poll.
389    pub idle: bool,
390    /// What the daemon is working on. Empty means idle; more than one entry
391    /// means more than one run is in flight at once.
392    ///
393    /// `deserialize_with` rather than the plain derive: a daemon started
394    /// before this field became a list is still out there writing the old
395    /// shape — a single `{"task":...,"run":...}` object, or its absence —
396    /// on every heartbeat until it is restarted, and a live process reading
397    /// that file during the rollout must still see it as running rather than
398    /// as absent. A bare type change here would fail the whole struct's
399    /// deserialization on a type mismatch, defeating the permissiveness this
400    /// type exists for.
401    #[serde(deserialize_with = "de_current")]
402    pub current: Vec<Current>,
403    /// Tasks this daemon process has finished.
404    pub completed: u64,
405    /// Queue polls this daemon process has made.
406    pub polls: u64,
407    /// Effective startup capabilities of the question recovery loops.
408    #[serde(default)]
409    pub question_recovery: Option<crate::question_delivery::Recovery>,
410    /// Independent-worker control protocol, absent on legacy embedded loops.
411    pub worker_protocol: Option<u32>,
412}
413
414/// Accept the old single-`Current`-or-absent shape as well as the current
415/// list, so a reader never has to know which build wrote the file.
416fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
417where
418    D: serde::Deserializer<'de>,
419{
420    #[derive(Deserialize)]
421    #[serde(untagged)]
422    enum Shape {
423        Many(Vec<Current>),
424        One(Current),
425    }
426    Ok(
427        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
428            Shape::Many(v) => v,
429            Shape::One(c) => vec![c],
430        }),
431    )
432}
433
434impl Reading {
435    /// Seconds since the last heartbeat, or `None` when there has never been
436    /// one.
437    #[must_use]
438    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
439        self.updated_at
440            .map(|at| (now.as_second() - at.as_second()).max(0))
441    }
442
443    /// Whether the loop counts as running: a heartbeat no older than
444    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
445    /// progress hours after the daemon that owned it was killed.
446    #[must_use]
447    pub fn running(&self, now: Timestamp) -> bool {
448        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
449    }
450}
451
452/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
453/// usable there.
454///
455/// Missing, half-written and unparseable all collapse to `None`, because the
456/// only question a reader asks is whether a daemon is alive, and a file it
457/// cannot read is not evidence that one is.
458#[must_use]
459pub fn read_status(home: &Path) -> Option<Reading> {
460    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
461    serde_json::from_str(&body).ok()
462}
463
464/// Read-only evidence of runs owned by a live daemon or independent worker.
465///
466/// CLI, sandboxed conversation controls and Web cleanup share this observation.
467/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
468/// Starting reservations and unknown worker state remain protected; observing
469/// them never creates, reconciles or archives files in the worker store.
470/// Callers interested in one identity use [`is_working_on`] or
471/// [`is_working_on_task`].
472#[must_use]
473pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
474    let mut current = read_status(home)
475        .filter(|reading| reading.running(now))
476        .map(|reading| reading.current)
477        .unwrap_or_default();
478    let workers = crate::worker::observe_active(home).and_then(|jobs| {
479        jobs.into_iter()
480            .filter(|job| job.kind == "task")
481            .map(|job| {
482                let request: TaskWorker = serde_json::from_value(job.payload)?;
483                let run = Queue::at(request.queue)
484                    .get(&request.task)
485                    .ok()
486                    .and_then(|task| task.runs.last().cloned())
487                    .unwrap_or_default();
488                Ok(Current {
489                    worker: Some(job.id),
490                    task: request.task,
491                    run,
492                })
493            })
494            .collect::<Result<Vec<_>>>()
495    });
496    match workers {
497        Ok(workers) => {
498            for worker in workers {
499                if !current.iter().any(|claim| {
500                    claim.task == worker.task
501                        && claim.run == worker.run
502                        && claim.worker == worker.worker
503                }) {
504                    current.push(worker);
505                }
506            }
507        }
508        Err(error) => {
509            // This API gates destructive cleanup. Unknown worker ownership
510            // protects every known task/run instead of pretending it is idle.
511            tracing::error!("cannot determine active workers: {error:#}");
512            current.extend(
513                Queue::at(home.join("queue"))
514                    .list()
515                    .into_iter()
516                    .map(|task| Current {
517                        worker: None,
518                        task: task.id,
519                        run: task.runs.last().cloned().unwrap_or_default(),
520                    }),
521            );
522            current.extend(
523                crate::run::list_ids_in(&home.join("runs"))
524                    .into_iter()
525                    .map(|run| Current {
526                        worker: None,
527                        task: String::new(),
528                        run,
529                    }),
530            );
531        }
532    }
533    current
534}
535
536/// Whether a live daemon is working on this run at this moment.
537#[must_use]
538pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
539    current_work(home, now).iter().any(|c| c.run == run)
540}
541
542/// Admission may ignore only this process's confirmed worker reservation.
543/// Keep anonymous/legacy daemon claims and every other worker, even for the
544/// same task. The run's execution lease and process identity are checked by
545/// the caller under the owner lock as well.
546pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
547    // A helper or test may inherit an identity from a different run store.
548    // That identity grants no exception here; retain all ownership evidence.
549    let same_home = std::env::var_os("MAGI_WORKER_HOME")
550        .is_some_and(|worker_home| Path::new(&worker_home) == home);
551    let caller = if same_home {
552        crate::worker::current_job(home)?
553    } else {
554        None
555    }
556    .filter(|job| {
557        job.kind == "task"
558            && job.status == crate::worker::Status::Running
559            && job.pid == Some(std::process::id())
560    });
561    Ok(other_claims_run(
562        &current_work(home, now),
563        run,
564        caller.as_ref().map(|job| job.id.as_str()),
565    ))
566}
567
568fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
569    claims
570        .iter()
571        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
572}
573
574/// Whether a live daemon is working on a run whose short id is this one.
575///
576/// For a worktree that has no run record to compare against at all -
577/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
578/// id is not available to hand to [`is_working_on`]. The short id is: a run's
579/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
580/// and it is exactly the gap between the daemon claiming a task and
581/// `RunState::new` saving the first `run.json` that this exists to protect -
582/// a run genuinely in flight but invisible to a scan of `runs/`.
583#[must_use]
584pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
585    current_work(home, now)
586        .iter()
587        .any(|c| crate::run::short_of(&c.run) == short)
588}
589
590/// Whether a live daemon is working on this task at this moment.
591#[must_use]
592pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
593    current_work(home, now).iter().any(|c| c.task == task)
594}
595
596/// Remove claim files whose owner is provably dead, or that have simply
597/// outlived `older_than`, and return the task ids swept.
598///
599/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
600/// destructor, and the orphaned `.lock` file would make its task permanently
601/// unclaimable — the backlog would stop for good at exactly the task that was
602/// in flight when the machine went down.
603///
604/// The pid recorded in the lock is the authority whenever it can be read at
605/// all; age is only a fallback for when it cannot be.
606///
607/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
608///   full stop — dead sweeps the lock immediately, regardless of age; alive
609///   protects it, regardless of age. This is what lets a lock be reclaimed in
610///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
611///   before this daemon even started, next to a `queued` task, no longer has
612///   to sit for six hours before anything notices its owner is gone.
613/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
614///   falls back to `older_than`, since there is nothing else to check.
615///
616/// Age must never override a *positive* liveness confirmation. `sweep`
617/// polls concurrently with independently running task workers. A worker may
618/// legitimately run longer than `older_than`; its live pid must still protect
619/// its claim. Age alone must never turn that claim into a second task attempt,
620/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
621/// to a second attempt — two `Runner`s writing the same `run.json` and the
622/// same worktree at once. `pid_alive` answering "alive" for anything it
623/// cannot determine (a live process, a pid this build cannot check, one
624/// under another account) is exactly what keeps that path from ever
625/// firing on a guess.
626///
627/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
628/// output unreadable must not be license to guess, and the risk of an
629/// unparseable lock outliving a genuinely dead owner is bounded by an order
630/// of magnitude above any plausible run rather than by a positive check.
631///
632/// Runs on every poll, not only at startup — a daemon up for days must keep
633/// noticing a lock some other, now-dead, daemon left behind just as readily
634/// as one it trips over on the way up.
635pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
636    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
637}
638
639/// [`sweep_stale_claims`] with its process-query boundary supplied by the
640/// caller. This keeps the lock policy testable where process listing is
641/// unavailable, while production still uses the platform query above.
642fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
643where
644    F: Fn(u32) -> bool,
645{
646    let this_process = std::process::id();
647    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
648        .into_iter()
649        .flatten()
650        .flatten()
651        .map(|e| e.path())
652        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
653        .filter(|p| {
654            match std::fs::read_to_string(p)
655                .ok()
656                .and_then(|body| body.trim().parse::<u32>().ok())
657            {
658                // This process wrote it and is asking the question right
659                // now, so it is definitionally still alive - settled without
660                // spawning a helper process at all.
661                Some(pid) if pid == this_process => false,
662                Some(pid) => !pid_alive(pid),
663                None => p
664                    .metadata()
665                    .and_then(|m| m.modified())
666                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
667                    .is_ok_and(|age| age >= older_than),
668            }
669        })
670        .filter(|p| std::fs::remove_file(p).is_ok())
671        .filter_map(|p| {
672            p.file_stem()
673                .and_then(|s| s.to_str())
674                .map(std::borrow::ToOwned::to_owned)
675        })
676        .collect();
677    swept.sort_unstable();
678    swept
679}
680
681/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
682/// no live daemon's heartbeat naming it? Deterministic — no model call, and
683/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
684/// shown.
685fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
686    task.status == TaskStatus::Running
687        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
688        && !is_working_on_task(home, &task.id, now)
689}
690
691/// Every task [`is_stalled`] right now — "止まったタスク" in
692/// `crate::conduct`'s vocabulary.
693fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
694    queue
695        .list()
696        .into_iter()
697        .filter(|t| is_stalled(t, home, now))
698        .collect()
699}
700
701/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
702/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
703/// `Failed`-and-so-also-runnable: a task that already attempted and lost
704/// belongs in [`finished_tasks`], where the question is a recovery, not a
705/// dependency.
706fn queued_tasks(queue: &Queue) -> Vec<Task> {
707    queue
708        .list()
709        .into_iter()
710        .filter(|t| t.status == TaskStatus::Queued)
711        .collect()
712}
713
714/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
715/// タスク" in `crate::conduct`'s vocabulary.
716fn finished_tasks(queue: &Queue) -> Vec<Task> {
717    queue
718        .list()
719        .into_iter()
720        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
721        .collect()
722}
723
724/// Deterministically resolve `Task::blocked_by`: a dependency task that
725/// reached `Done`, or a question that was answered, is removed — no model
726/// involved, on every poll. An answered question's content is copied onto
727/// the task ([`Task::record_answer`]) before its id is dropped, so it
728/// reaches the next `crate::conduct` prompt and the next run's instruction
729/// (see [`instruction_for`]) rather than only clearing the block.
730///
731/// A `blocked_by` id that names neither an existing task nor an existing
732/// question - `magi task rm` (or an operator by hand) deleted it while this
733/// task was still waiting - is caught before any of that: it can never
734/// become `Done` or `Answered`, so the ordinary loop below would otherwise
735/// leave the task `blocked` forever with nothing to notice. Such a task is
736/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
737/// which puts it in front of `crate::triage::run_once`'s own walk the next
738/// time it runs - see that module's doc for why the choice is "ask a human",
739/// never "assume the missing dependency was satisfied and unblock anyway".
740fn resolve_blockers(queue: &Queue, questions: &Questions) {
741    for listed in queue.list() {
742        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
743            continue;
744        }
745        let Ok(_claim) = queue.claim(&listed.id) else {
746            continue;
747        };
748        let Ok(mut task) = queue.get(&listed.id) else {
749            continue;
750        };
751        if task.status != TaskStatus::Blocked {
752            continue;
753        }
754        // A dependency deleted on purpose is released, not held - and before
755        // the missing check, so a pass that races the delete (or a claim that
756        // made `Queue::remove` skip this task) settles it quietly.
757        let deleted = queue.apply_deleted_blockers(&mut task, questions);
758        if !deleted.is_empty() {
759            record(queue, &mut task);
760            for id in &deleted {
761                queue.note_dependency_deleted(&task, id);
762            }
763            if task.status != TaskStatus::Blocked {
764                continue;
765            }
766        }
767        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
768        if !missing.is_empty() {
769            let language = language_of(&task, Path::new("."));
770            let mut cause = missing.clone();
771            cause.sort();
772            cause.dedup();
773            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
774            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
775                &task.blocked_by,
776                &missing,
777                &language,
778            )));
779            record(queue, &mut task);
780            continue;
781        }
782        // A conductor question nobody answered in time is retired by the
783        // waiter, and nothing else would ever move the task it blocks.
784        if let Some(q) = task.blocked_by.iter().find_map(|id| {
785            let crate::queue::Dependency::Question(full) =
786                crate::queue::dependency(queue, questions, id)
787            else {
788                return None;
789            };
790            questions.get(&full).ok().filter(|q| {
791                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
792            })
793        }) {
794            let language = language_of(&task, Path::new("."));
795            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
796            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
797            record(queue, &mut task);
798            continue;
799        }
800        let mut changed = false;
801        for id in task.blocked_by.clone() {
802            let resolved = crate::queue::dependency(queue, questions, &id);
803            if let crate::queue::Dependency::Task(full) = &resolved {
804                if queue
805                    .get(full)
806                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
807                {
808                    task.unblock(&id);
809                    changed = true;
810                }
811                continue;
812            }
813            if let crate::queue::Dependency::Question(full) = resolved
814                && let Ok(q) = questions.get(&full)
815                && q.status == ask::QuestionStatus::Answered
816            {
817                // The action sweep releases conductor blockers atomically
818                // with their selected operation. A fresh deputy lease must
819                // never leave an answered hold temporarily runnable.
820                if q.node == crate::conduct::NODE
821                    && q.chosen_action().is_some()
822                    && !task.action_applied(&q.id)
823                {
824                    continue;
825                }
826                let answer = match &q.answer {
827                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
828                    None => String::new(),
829                };
830                task.record_answer(q.summary.clone(), answer);
831                task.unblock(&id);
832                changed = true;
833            }
834        }
835        if changed {
836            record(queue, &mut task);
837        }
838    }
839}
840
841/// The `hold_reason` of a task whose conductor question went unanswered.
842fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
843    if crate::lang::is_japanese(language) {
844        format!(
845            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
846            q.short(),
847            q.summary
848        )
849    } else {
850        format!(
851            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
852            q.short(),
853            q.summary
854        )
855    }
856}
857
858/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
859/// for several unrelated reasons, and the waiter must not read them alike.
860#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub(crate) enum ActionStanding {
862    /// The answer carries no action: the waiter delivers it as before.
863    NoAction,
864    /// The daemon will apply it (not applied, task idle, current attempt).
865    Pending,
866    /// Already applied (`Task::actions_applied`): the daemon has acted, so
867    /// delivering the word to the old seat would run it beside the new work.
868    Applied,
869    /// The question is about an earlier attempt than the task's latest.
870    Stale,
871    /// The task is running / blocked / done: the daemon defers for now.
872    Busy,
873}
874
875impl ActionStanding {
876    /// The daemon has acted or will act: the waiter must not deliver.
877    pub(crate) fn daemon_owns(self) -> bool {
878        matches!(self, Self::Pending | Self::Applied | Self::Stale)
879    }
880}
881
882/// Classify `q`'s chosen action against `task`. `Stale` is judged before
883/// `Busy`: a question about an earlier attempt must be stopped even while a
884/// newer competition is running.
885pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
886    if q.chosen_action().is_none() {
887        ActionStanding::NoAction
888    } else if task.action_applied(&q.id) {
889        ActionStanding::Applied
890    } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891        ActionStanding::Stale
892    } else if matches!(
893        task.status,
894        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
895    ) {
896        ActionStanding::Busy
897    } else {
898        ActionStanding::Pending
899    }
900}
901
902/// What [`decide_action`] concluded about one answered question.
903#[derive(Debug, Clone, PartialEq, Eq)]
904enum ActionDecision {
905    /// Nothing to do now (no action, already applied, or the task is busy).
906    Skip,
907    /// Continue the named run instead of competing again.
908    Resume(String),
909    /// Requeue as a fresh competition.
910    Requeue,
911    /// Hold the task by explicit operator choice.
912    Hold,
913    /// Close the task as done.
914    Done,
915    /// The question is about an earlier attempt than the task's latest; it
916    /// is recorded as handled and changes nothing.
917    Stale,
918    /// The action cannot be carried out; hold the task and say why. Never
919    /// falls back to something else, because the operator chose this one.
920    Refuse(String),
921}
922
923/// Decide what the choice answered on `q` means for `task`. Pure: `load`
924/// reads a run's state, as with [`unfinished_run_with`].
925///
926/// `Resume` only fires on the task's *latest* run, and only while that run
927/// could actually make progress ([`RunStatus::resumable`], not released, review
928/// budget left); an answer naming anything else is refused rather than
929/// reinterpreted as a fresh competition.
930fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
931where
932    F: FnOnce(&str) -> Result<RunState>,
933{
934    let Some(action) = q.chosen_action() else {
935        return ActionDecision::Skip;
936    };
937    if task.action_applied(&q.id)
938        || matches!(
939            task.status,
940            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
941        )
942    {
943        return ActionDecision::Skip;
944    }
945    // A question about an earlier attempt must not act on a newer one. A
946    // conductor question is keyed by the task id, not a run, so it is exempt.
947    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
948        return ActionDecision::Stale;
949    }
950    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
951    let stopping = q.node == land::APPROVAL_NODE
952        && q.resolution()
953            .as_deref()
954            .is_some_and(crate::merge_decision::stops);
955    // An answer is the owner's decision as of when it was given: a manual hold
956    // placed before it (even after the question was asked) was seen and
957    // overruled by it, while a hold or release after it supersedes it.
958    let decision_at = q.answered_at.unwrap_or(q.asked_at);
959    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
960        return if repair || stopping {
961            ActionDecision::Refuse(format!(
962                "{} 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 {}`",
963                if repair { "repair" } else { "stop" },
964                q.id,
965                q.run,
966                task.id
967            ))
968        } else {
969            ActionDecision::Stale
970        };
971    }
972    match action {
973        a if a.maintenance() => ActionDecision::Skip,
974        ask::ChoiceAction::ResumeRun { .. }
975        | ask::ChoiceAction::ReleaseTask { .. }
976        | ask::ChoiceAction::RerunChecks { .. }
977        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
978        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
979        ask::ChoiceAction::Hold => ActionDecision::Hold,
980        ask::ChoiceAction::Done => ActionDecision::Done,
981        ask::ChoiceAction::Resume { run } => {
982            if task.runs.last() != Some(run) {
983                return ActionDecision::Refuse((p.resume_not_latest)(
984                    q.short(),
985                    ask::short_id(run),
986                ));
987            }
988            match load(run) {
989                Ok(s) if stopping => {
990                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
991                        || !s
992                            .land_approval
993                            .as_ref()
994                            .is_some_and(|binding| binding.question == q.id)
995                    {
996                        ActionDecision::Stale
997                    } else if s.liveness(false) == Liveness::Live {
998                        ActionDecision::Skip
999                    } else if s.status == RunStatus::Landing
1000                        && !s.released()
1001                        && s.retired_to.is_none()
1002                    {
1003                        ActionDecision::Resume(run.clone())
1004                    } else {
1005                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1006                    }
1007                }
1008                Ok(s)
1009                    if q.node == land::APPROVAL_NODE
1010                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1011                {
1012                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1013                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1014                    {
1015                        // A live/manual driver already consumed or superseded
1016                        // this answer. Do not hold its fresh approval wait.
1017                        ActionDecision::Stale
1018                    } else if s.liveness(false) == Liveness::Live {
1019                        ActionDecision::Skip
1020                    } else if s.status != RunStatus::Landing
1021                        || s.released()
1022                        || s.reviews.is_empty()
1023                        || !implementers_match(task, &s)
1024                        || !s
1025                            .land_approval
1026                            .as_ref()
1027                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1028                    {
1029                        ActionDecision::Refuse(format!(
1030                            "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",
1031                            q.id, run, run
1032                        ))
1033                    } else {
1034                        ActionDecision::Resume(run.clone())
1035                    }
1036                }
1037                Ok(s) if s.liveness(false) == Liveness::Live => {
1038                    ActionDecision::Refuse("run already has a live driver".into())
1039                }
1040                Ok(s) => match crate::handover::resume_refusal(&s) {
1041                    None => ActionDecision::Resume(run.clone()),
1042                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1043                        q.short(),
1044                        ask::short_id(run),
1045                        &reason.diagnostic(&s),
1046                    )),
1047                },
1048                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1049                    q.short(),
1050                    ask::short_id(run),
1051                    &format!("{e:#}"),
1052                )),
1053            }
1054        }
1055    }
1056}
1057
1058/// The fixed prose the daemon writes into [`Task::last_error`] and
1059/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1060/// `triage::Wording` and `land::Words`: only English and Japanese are
1061/// translated, anything else falls back to English.
1062///
1063/// Rendered when the reason is *generated*, so a reason keeps the language it
1064/// was written in if the setting changes later. The notification frame
1065/// (`Task <id> is held:`) is not here and stays English.
1066///
1067/// Deliberately **not** translated, because other code reads them back by
1068/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1069/// and `gate red`. IDs, node names, paths and external error text are embedded
1070/// as they are.
1071struct Phrases {
1072    /// `{}` = status label, then the detail.
1073    graph_stopped: fn(&str, &str) -> String,
1074    quorum_lost: &'static str,
1075    /// Followed by the seats' names.
1076    quota_took_out: &'static str,
1077    /// Followed by the status label.
1078    run_ended: &'static str,
1079    /// Followed by the question's short id.
1080    waiting_for_answer: &'static str,
1081    recovered_running: &'static str,
1082    no_run_to_recover: &'static str,
1083    could_not_start: &'static str,
1084    resume_not_latest: fn(&str, &str) -> String,
1085    resume_cannot_progress: fn(&str, &str, &str) -> String,
1086    resume_unreadable: fn(&str, &str, &str) -> String,
1087    /// A takeover refusal: the operator-facing text. English is the error's own
1088    /// `Display`; a translation keeps the machine detail apart in parentheses.
1089    handover_refused: fn(&crate::handover::Refused) -> String,
1090    /// Appended to a refused handover's hold reason (leading space included).
1091    handover_hint: &'static str,
1092    /// (seats that never answered, review rounds) for the review loop's
1093    /// "refusing to call it clean" stop.
1094    reviewers_never_answered: fn(usize, usize) -> String,
1095}
1096
1097const PHRASES_EN: Phrases = Phrases {
1098    graph_stopped: |status, detail| {
1099        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1100    },
1101    quorum_lost: "the judging panel lost its quorum",
1102    quota_took_out: "; quota took out ",
1103    run_ended: "run ended ",
1104    waiting_for_answer: " - waiting for operator answer to question ",
1105    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1106    no_run_to_recover: "task was `running` with no live daemon and no readable \
1107                        run to recover; held for a human to check what happened",
1108    could_not_start: "could not start the run: ",
1109    resume_not_latest: |q, run| {
1110        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1111    },
1112    resume_cannot_progress: |q, run, reason| {
1113        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1114    },
1115    resume_unreadable: |q, run, e| {
1116        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1117    },
1118    handover_refused: |r| r.to_string(),
1119    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1120    reviewers_never_answered: |missing, rounds| {
1121        format!(
1122            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1123             refusing to call it clean"
1124        )
1125    },
1126};
1127
1128const PHRASES_JA: Phrases = Phrases {
1129    graph_stopped: |status, detail| {
1130        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1131    },
1132    quorum_lost: "審査パネルが定足数を失いました",
1133    quota_took_out: "。クォータで脱落: ",
1134    run_ended: "run 終了: ",
1135    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1136    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1137    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1138                        何が起きたか人が確認するため保留にしました",
1139    could_not_start: "run を開始できませんでした: ",
1140    resume_not_latest: |q, run| {
1141        format!(
1142            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1143        )
1144    },
1145    resume_cannot_progress: |q, run, reason| {
1146        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1147    },
1148    resume_unreadable: |q, run, e| {
1149        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1150    },
1151    handover_refused: |r| {
1152        use crate::handover::Refused;
1153        match r {
1154            Refused::Foreign { branch, path, why } => format!(
1155                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1156                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1157                 から、やり直してください(詳細: {why})"
1158            ),
1159            Refused::Unsafe { branch, path, why } => format!(
1160                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1161                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1162                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1163            ),
1164            Refused::ReleaseFailed { branch, path, run } => format!(
1165                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1166                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1167                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1168            ),
1169        }
1170    },
1171    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1172    reviewers_never_answered: |missing, rounds| {
1173        format!(
1174            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1175             クリーンとは認めません"
1176        )
1177    },
1178};
1179
1180fn phrases(language: &str) -> &'static Phrases {
1181    if crate::lang::is_japanese(language) {
1182        &PHRASES_JA
1183    } else {
1184        &PHRASES_EN
1185    }
1186}
1187
1188/// The language of the repository a task belongs to, read best-effort for the
1189/// paths that have no run (and so no config of their own) to ask. An unreadable
1190/// config is English, not an error: a hold reason must still get written.
1191fn language_of(task: &Task, fallback: &Path) -> String {
1192    crate::lang::of_repo(&repo_for(task, fallback))
1193}
1194
1195/// The task an answered question speaks for: the one whose runs include the
1196/// question's run, or - for a conductor question, filed under the task's own
1197/// id - the task with that id.
1198pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1199    if q.node == crate::conduct::NODE {
1200        return tasks.iter().find(|t| t.id == q.run);
1201    }
1202    tasks.iter().find(|t| t.runs.contains(&q.run))
1203}
1204
1205/// Legacy conductor prose never becomes a maintenance command by inference.
1206/// Replace unsupported open labels under the question lock before dispatch.
1207fn repair_choice_offers(questions: &Questions) {
1208    for q in questions.list().into_iter().filter(|q| {
1209        q.status.open()
1210            && q.node == crate::conduct::NODE
1211            && q.choices
1212                .iter()
1213                .any(|c| crate::choice_effect::describe(q, c).is_none())
1214    }) {
1215        let _ = questions.update(&q.id, |current| {
1216            if current.status.open() {
1217                crate::choice_effect::executable_conductor(current);
1218                if let Some(deputy) = &mut current.deputy {
1219                    deputy.brief = crate::deputy::brief(
1220                        &current.run,
1221                        &current.detail,
1222                        &current.choices,
1223                        &current.actions,
1224                    );
1225                }
1226            }
1227            Ok(())
1228        });
1229    }
1230}
1231
1232/// Apply answered typed choices. Only the daemon calls this in production;
1233/// deputies settle the question and never execute its actions.
1234pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1235    apply_maintenance_choices(queue, questions, home).await;
1236    apply_task_choice_actions(queue, questions, home);
1237}
1238
1239/// Apply bounded maintenance effects independently of question ownership: a
1240/// release watcher need not have a queue task, and a predecessor is another run.
1241async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1242    for q in questions.list() {
1243        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1244            continue;
1245        };
1246        // Receipt paths use question IDs, whose format is independent of run
1247        // IDs. Apply the question store's filename safety rule to both eras.
1248        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1249            continue;
1250        }
1251        let dir = home.join("choice-actions");
1252        if std::fs::create_dir_all(&dir).is_err() {
1253            continue;
1254        }
1255        let Ok(lock) = std::fs::OpenOptions::new()
1256            .create(true)
1257            .truncate(false)
1258            .write(true)
1259            .open(dir.join(format!("{}.lock", q.id)))
1260        else {
1261            continue;
1262        };
1263        if crate::pr_head::try_lock_file(&lock).is_err() {
1264            continue;
1265        }
1266        let fresh = !home
1267            .join("choice-actions")
1268            .join(format!("{}.json", q.id))
1269            .exists();
1270        let result = async {
1271            let receipt = dir.join(format!("{}.json", q.id));
1272            if receipt.exists() {
1273                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1274                anyhow::ensure!(
1275                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1276                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1277                );
1278                return Ok::<_, anyhow::Error>(());
1279            }
1280            // Never retry an uncertain external effect. The receipt is written
1281            // before calling gh, exactly like release_watch's rerun record.
1282            let record = |status: &str| -> anyhow::Result<()> {
1283                let tmp = receipt.with_extension("tmp");
1284                std::fs::write(
1285                    &tmp,
1286                    serde_json::to_vec(&serde_json::json!({
1287                        "action": action, "status": status,
1288                    }))?,
1289                )?;
1290                std::fs::rename(tmp, &receipt)?;
1291                Ok(())
1292            };
1293            let applied = async {
1294                match action {
1295                    ask::ChoiceAction::ResumeRun { run } => {
1296                        crate::resume::validate(home, run)?;
1297                        record("started")?;
1298                        let decided = q.answered_at.unwrap_or(q.asked_at);
1299                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1300                            crate::resume::validate_unqueued(home, run)?;
1301                            crate::resume::start(home, run.clone()).await?;
1302                        }
1303                    }
1304                    ask::ChoiceAction::ReleaseTask {
1305                        task,
1306                        held_at,
1307                        reason,
1308                    } => {
1309                        anyhow::ensure!(
1310                            queue.resolve_id(task)? == *task,
1311                            "task action requires an exact task ID"
1312                        );
1313                        let _claim = queue.claim(task)?;
1314                        let mut task = queue.get(task)?;
1315                        if task.action_applied(&q.id) {
1316                            return Ok(());
1317                        }
1318                        // Filing this conductor question temporarily wraps the
1319                        // original hold in a Blocked state. Restore only that
1320                        // exact blocker on the local copy before checking the
1321                        // hold binding; unrelated waits never authorize release.
1322                        if q.node == crate::conduct::NODE
1323                            && q.run == task.id
1324                            && task.status == TaskStatus::Blocked
1325                            && task.blocked_from == Some(TaskStatus::Held)
1326                            && task.blocked_by.as_slice() == [q.id.as_str()]
1327                        {
1328                            task.unblock(&q.id);
1329                        }
1330                        anyhow::ensure!(
1331                            task.status == TaskStatus::Held
1332                                && task.held_at == Some(*held_at)
1333                                && task.hold_reason.as_deref() == reason.as_deref()
1334                                && task
1335                                    .operator_decided_at
1336                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1337                            "task no longer has the hold this question names"
1338                        );
1339                        task.release_operator("choice", Some(&q.id));
1340                        task.mark_action_applied(&q.id);
1341                        queue.put(&mut task)?;
1342                    }
1343                    ask::ChoiceAction::AbandonRun { run } => {
1344                        record("started")?;
1345                        crate::driver::abandon_proven_dead(home, run)?;
1346                    }
1347                    ask::ChoiceAction::RerunChecks {
1348                        repo,
1349                        pr,
1350                        head,
1351                        runs,
1352                    } => {
1353                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1354                            .await?;
1355                    }
1356                    _ => unreachable!(),
1357                }
1358                Ok::<_, anyhow::Error>(())
1359            }
1360            .await;
1361            match applied {
1362                Ok(()) => record("applied"),
1363                Err(e) => {
1364                    record(&format!("refused or failed: {e:#}"))?;
1365                    Err(e)
1366                }
1367            }
1368        }
1369        .await;
1370        // Retire the originating blocker as well as the target operation.
1371        // A foreign resume leaves its issuer held instead of competing beside
1372        // the execution just started. Other successful maintenance lets the
1373        // original task retry its normal, guarded path.
1374        if home
1375            .join("choice-actions")
1376            .join(format!("{}.json", q.id))
1377            .exists()
1378            && let Some(listed) = task_of_question(&queue.list(), &q)
1379            && !listed.action_applied(&q.id)
1380            && let Ok(_claim) = queue.claim(&listed.id)
1381            && let Ok(mut origin) = queue.get(&listed.id)
1382        {
1383            if !origin.operator_held()
1384                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1385                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1386            {
1387                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1388                    origin.hold_machine(Some(format!(
1389                        "Maintenance choice {} settled; inspect its target before releasing this task",
1390                        q.id
1391                    )));
1392                } else {
1393                    origin.unblock(&q.id);
1394                }
1395            }
1396            origin.mark_action_applied(&q.id);
1397            let _ = queue.put(&mut origin);
1398        }
1399        if let Err(e) = result
1400            && fresh
1401        {
1402            notices::raise_in(
1403                home,
1404                Notice::warn(
1405                    &format!("action:{}", q.id),
1406                    format!("Choice action {} was not completed: {e:#}", q.id),
1407                )
1408                .link(if q.run_names_task() {
1409                    Link::Task { id: q.run.clone() }
1410                } else {
1411                    Link::Run { id: q.run.clone() }
1412                }),
1413            );
1414        }
1415    }
1416}
1417
1418/// Rerun the named failed workflow runs of a pull request, each at most once
1419/// per `request` (a question id, or a chat operation identity). The head,
1420/// lifecycle and failed state are re-read from the forge first; `started` is
1421/// called once those checks pass and before the first external call, and the
1422/// ledger entry is written before every `gh` call, so an uncertain result is
1423/// never repeated automatically.
1424pub(crate) async fn rerun_checks_once(
1425    home: &Path,
1426    request: &str,
1427    repo: &Path,
1428    pr: &str,
1429    head: &str,
1430    runs: &[String],
1431    started: impl FnOnce() -> anyhow::Result<()>,
1432) -> anyhow::Result<()> {
1433    use crate::release_watch::{GhForge, ReleaseForge};
1434    anyhow::ensure!(
1435        !runs.is_empty()
1436            && runs.len() <= 20
1437            && runs
1438                .iter()
1439                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1440            && !pr.starts_with('-'),
1441        "invalid rerun targets"
1442    );
1443    let snap = GhForge.snapshot(repo, pr).await?;
1444    anyhow::ensure!(
1445        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1446        "pull request head or lifecycle changed"
1447    );
1448    anyhow::ensure!(
1449        runs.iter().all(|r| snap
1450            .checks
1451            .iter()
1452            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1453        "named workflow is no longer failed on this pull request"
1454    );
1455    started()?;
1456    let dir = home.join("choice-actions");
1457    std::fs::create_dir_all(&dir)?;
1458    let rerun_lock = std::fs::OpenOptions::new()
1459        .create(true)
1460        .truncate(false)
1461        .write(true)
1462        .open(dir.join("reruns.lock"))?;
1463    crate::pr_head::try_lock_file(&rerun_lock)?;
1464    let ledger = dir.join("reruns.json");
1465    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1466        serde_json::from_slice(&std::fs::read(&ledger)?)?
1467    } else {
1468        Default::default()
1469    };
1470    for run in runs {
1471        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1472        if !recorded.insert(key) {
1473            continue;
1474        }
1475        let tmp = ledger.with_extension("tmp");
1476        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1477        std::fs::rename(tmp, &ledger)?;
1478        GhForge.rerun(repo, run).await?;
1479    }
1480    Ok(())
1481}
1482
1483/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1484///
1485/// Runs on every poll before the conductor looks at the queue. The task is
1486/// re-read under its claim, so a task somebody completed or held by hand in
1487/// the meantime is judged on what it is now. `Resume` releases the task and
1488/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1489/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1490/// ordinary `unfinished_run` logic resumes that same run.
1491pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1492    let tasks = queue.list();
1493    for q in questions.list() {
1494        // Dismissal is committed by the question writer, never a resume.
1495        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1496            continue;
1497        }
1498        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1499            continue;
1500        }
1501        let Some(listed) = task_of_question(&tasks, &q) else {
1502            if q.node == land::APPROVAL_NODE
1503                && q.resolution().as_deref().is_some_and(|choice| {
1504                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1505                })
1506            {
1507                notices::raise_in(
1508                    home,
1509                    Notice::warn(
1510                        &format!("repair-owner:{}", q.id),
1511                        format!(
1512                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1513                            q.run, q.run
1514                        ),
1515                    ).link(Link::Run { id: q.run.clone() }),
1516                );
1517            }
1518            continue;
1519        };
1520        if listed.action_applied(&q.id) {
1521            continue;
1522        }
1523        let Ok(_claim) = queue.claim(&listed.id) else {
1524            continue;
1525        };
1526        let Ok(mut task) = queue.get(&listed.id) else {
1527            continue;
1528        };
1529        // Work only on this local copy until the action can be committed.
1530        // In particular, a fresh lease below leaves the persisted task blocked.
1531        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1532            let blockers: Vec<_> = task
1533                .blocked_by
1534                .iter()
1535                .filter(|id| {
1536                    crate::queue::dependency(queue, questions, id)
1537                        == crate::queue::Dependency::Question(q.id.clone())
1538                })
1539                .cloned()
1540                .collect();
1541            if !blockers.is_empty() {
1542                for id in blockers {
1543                    task.unblock(&id);
1544                }
1545                let answer = match &q.answer {
1546                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1547                    None => String::new(),
1548                };
1549                task.record_answer(q.summary.clone(), answer);
1550            }
1551        }
1552        let language = language_of(&task, Path::new("."));
1553        let decision = decide_action(&task, &q, phrases(&language), |id| {
1554            RunState::load_under(id, home)
1555        });
1556        let ran = matches!(
1557            decision,
1558            ActionDecision::Resume(_)
1559                | ActionDecision::Requeue
1560                | ActionDecision::Hold
1561                | ActionDecision::Done
1562        );
1563        if ran && asker_may_still_read(questions, &q, home) {
1564            // The asking process or its seat can still take the word; act
1565            // once it has gone quiet. Bound on the remaining window: the
1566            // check is not atomic with the write below, so an asker that
1567            // takes the word in between (at most one poll, never more than
1568            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1569            // and `Task::actions_applied` under the claim keeps the action to
1570            // one application. The waiter does not deliver an answer that
1571            // carries an action (`waiter::decide_owned`), so it cannot race.
1572            continue;
1573        }
1574        let done = matches!(decision, ActionDecision::Done);
1575        match decision {
1576            ActionDecision::Skip => continue,
1577            ActionDecision::Resume(run) => {
1578                task.release_operator("choice", Some(&q.id));
1579                task.resume_override = Some(crate::queue::OperatorResume {
1580                    question_id: q.id.clone(),
1581                    at: Timestamp::now(),
1582                    conductor_rehold: None,
1583                    forced: true,
1584                    pinned_run: Some(run),
1585                });
1586            }
1587            ActionDecision::Stale => {}
1588            ActionDecision::Requeue => {
1589                task.release_operator("choice-requeue", Some(&q.id));
1590                task.requeue();
1591            }
1592            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1593            ActionDecision::Done => task.succeed(),
1594            ActionDecision::Refuse(why) => {
1595                if task.operator_held() {
1596                    // A rejected answer does not release the operator's hold
1597                    // or reclassify it as recoverable by the conductor.
1598                    task.hold_reason = Some(match task.hold_reason.take() {
1599                        Some(reason) => format!("{reason}\n\n{why}"),
1600                        None => why,
1601                    });
1602                } else {
1603                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1604                    task.hold_machine(Some(why));
1605                }
1606                notices::raise(
1607                    Notice::warn(
1608                        &format!("action:{}", q.id),
1609                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1610                    )
1611                    .link(Link::Task {
1612                        id: task.id.clone(),
1613                    }),
1614                );
1615            }
1616        }
1617        task.mark_action_applied(&q.id);
1618        // The applied id travels with the transition, so a failed save loses
1619        // neither and the answer is acted on at the next poll.
1620        record(queue, &mut task);
1621        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1622            supersede_prior_runs(&task, home);
1623        }
1624        // Delivery is only a note of who has read the answer; the task's own
1625        // mark above is the authority. Best effort.
1626        let _ = questions.update(&q.id, |r| {
1627            r.answer_delivered = true;
1628            Ok(())
1629        });
1630    }
1631}
1632
1633/// Whether something may still read the answer to `q`: a fresh lease, or the
1634/// asking seat still listed as active in its run (its CLI can outlive the
1635/// `magi ask` that was killed).
1636fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1637    let now = Timestamp::now();
1638    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1639        return true;
1640    }
1641    q.node != crate::conduct::NODE
1642        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1643            s.seats_active()
1644                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1645        })
1646}
1647
1648/// Retire an unanswered conductor question after its task no longer refers to
1649/// it. Conductor questions use the task id in `Question::run`, so run-based
1650/// cleanup cannot observe a manual release or completion.
1651///
1652/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1653/// own question also carries a `run`, and a run id that happens to collide
1654/// with some task's id is not this loop's business — only a conductor
1655/// question actually uses the task id that way. One `Questions::list()` scan
1656/// is taken up front and matched against the in-memory task set, rather than
1657/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1658fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1659    let tasks = queue.list();
1660    let by_id: std::collections::BTreeMap<&str, &Task> =
1661        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1662    let referenced: Vec<&str> = tasks
1663        .iter()
1664        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1665        .collect();
1666
1667    for mut question in questions.list() {
1668        if !question.status.open() || question.node != crate::conduct::NODE {
1669            continue;
1670        }
1671        // Keep questions a task still names, including when the reference
1672        // moved to a dependent task.
1673        // Preserve even ambiguous references: retiring a possibly referenced
1674        // question is unsafe until the operator disambiguates it.
1675        if referenced
1676            .iter()
1677            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1678        {
1679            continue;
1680        }
1681        let Some(task) = by_id.get(question.run.as_str()) else {
1682            continue;
1683        };
1684        question.abandon(format!(
1685            "task {} no longer waits for this answer",
1686            task.short()
1687        ));
1688        if let Err(e) = questions.put(&mut question) {
1689            tracing::warn!(
1690                "could not retire question {} for task {}: {e:#}",
1691                question.short(),
1692                task.short()
1693            );
1694        }
1695    }
1696}
1697
1698/// What a finished run tells the queue about the task it came from.
1699///
1700/// A struct rather than a fourth and fifth boolean argument: the two flags
1701/// answer different questions about the same run, and a call site passing
1702/// `(…, true, false)` is one transposition away from refunding attempts
1703/// forever.
1704#[derive(Debug, Clone, Copy)]
1705pub struct Verdict {
1706    /// Where the graph stopped.
1707    pub status: RunStatus,
1708    /// The run opened a pull request.
1709    pub left_pr: bool,
1710    /// At least one seat was lost to a rate limit.
1711    pub quota_hit: bool,
1712    /// The run parked at a node boundary because it was asked to.
1713    pub parked: bool,
1714    /// The run never produced a single candidate a judge could look at.
1715    ///
1716    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1717    /// still have another candidate worth judging, in which case the loss was
1718    /// not the reason nothing came of the run. This is `true` only when the
1719    /// implement wave ended with nothing viable at all.
1720    pub no_viable_candidates: bool,
1721}
1722
1723/// Record a finished run against the task it came from.
1724///
1725/// Kept pure and separate from the loop because this mapping *is* the retry
1726/// policy, and a policy that can only be exercised by spawning a graph is a
1727/// policy nobody checks. The table:
1728///
1729/// | run status                           | task becomes        | attempt spent |
1730/// |---------------------------------------|---------------------|---------------|
1731/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1732/// | `Merged`, `Ready`                      | `Done`               | yes          |
1733/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1734/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1735/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1736/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1737/// | `Blocked` with a PR                    | `Held`               | yes          |
1738/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1739/// | `VerifiedNoop`                          | `Held`               | yes          |
1740/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1741///
1742/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1743/// deliberately: every candidate agreeing there is nothing to write is not a
1744/// machine fact about a rate limit, it is an unverified claim about the
1745/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1746/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1747/// claim could be wrong (a misread instruction, a stale check), and closing
1748/// the task automatically on an implementer's say-so would be the exact
1749/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1750/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1751/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1752/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1753/// claim regardless of whether the one already-spent attempt is refunded, and
1754/// [`Task::release`] resets the count to zero anyway the moment a human looks
1755/// at the evidence and lets it run again.
1756///
1757/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1758/// twice, together. A quorum lost to rate limits is a property of the machine
1759/// and not of the task, so the attempt is refunded and a reset quota picks
1760/// the work up where it stopped — and that is just as true when every
1761/// implement seat lost the same race and `after_implement` bails with nothing
1762/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1763/// machine fact. The `no_viable_candidates` guard is what keeps that row
1764/// narrow: a `Failed` run that produced a real candidate which then lost for
1765/// some other reason still spends the attempt, exactly like the quorum lost
1766/// to judges that answered with the wrong shape is ordinary flakiness, and
1767/// refunding *that* takes the bound off the retry loop entirely: run e633
1768/// stalled with `quota: []` after two judges wrote unusable JSON, was
1769/// refunded, and the next attempt paid for a fresh hour-long implement wave
1770/// before it could fail the same way. `max_attempts` exists precisely so
1771/// that cannot repeat forever.
1772///
1773/// A non-terminal status means `execute` returned while the graph was still
1774/// mid-flight, which is a bug rather than a verdict; it is treated as a
1775/// failure so that a task cannot loop on it either.
1776///
1777/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1778/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1779pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1780    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1781}
1782
1783/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1784fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1785    // A parked run is the operator's own doing, and its work is intact on
1786    // disk. The task goes back in line with its attempt refunded so the next
1787    // loop resumes the same run - which `one_task` prefers over competing
1788    // again - and so that swapping the binary a few times cannot exhaust a
1789    // budget meant for agents that actually misbehaved.
1790    if verdict.parked {
1791        task.park(detail);
1792        return;
1793    }
1794    match verdict.status {
1795        RunStatus::Merged | RunStatus::Ready
1796            if task.pr_recovery.as_ref().is_some_and(|s| {
1797                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1798            }) =>
1799        {
1800            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()));
1801        }
1802        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1803        RunStatus::AlreadyInBase => task.already_landed(detail),
1804        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1805        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1806            task.stall(detail)
1807        }
1808        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1809        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1810        RunStatus::Blocked => task.fail(detail, max_attempts),
1811        RunStatus::VerifiedNoop => task.handed_off(detail),
1812        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1813    }
1814}
1815
1816/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1817/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1818/// itself has actually finished *and* its own last attempt is provably why:
1819/// this loads that run and requires `Merged`/`Ready` before touching
1820/// anything earlier in `runs`, since `Task::succeed` can also be called
1821/// directly on a task whose last attempt never landed at all.
1822///
1823/// Called right after whatever call set `task.status` to
1824/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1825/// `reclaim`'s, but also every other place a task can be closed by hand
1826/// without the loop ever settling it itself: `magi task done`
1827/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1828/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1829/// GitHub merge, say, exactly the workflow this repository's own
1830/// "Landing a run's winner by hand" documents — is just as much "this task's
1831/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1832/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1833/// forever, which is the exact backlog this status exists to clear. `pub`
1834/// for those two out-of-module callers; everything else about this stays
1835/// internal bookkeeping.
1836///
1837/// A run something is still actually driving is left alone: a
1838/// task cannot be `Done` while one of its *own* attempts is still in flight,
1839/// so a live one at this point can only be an unrelated process — a manual
1840/// `--resume` of this old, now-moot run — and rewriting under it would just
1841/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1842/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1843/// pair `run_report`/`run_detail` use for the same question elsewhere:
1844/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1845/// --resume` invoked by hand outside it, which `liveness` also checks via
1846/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1847/// (already terminal in some other way, or itself mid-run) is left untouched
1848/// too.
1849///
1850/// Best-effort, like the rest of this module's bookkeeping: a load or save
1851/// failure here is a `tracing::warn`, not a failed settle, and the next time
1852/// this same task's completion is recorded — or a daemon restart replays
1853/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1854/// separate reconciliation pass; if that gap ever matters in practice, one
1855/// can be added then.
1856///
1857/// `home` is a parameter, not the process-global [`crate::run::home`], for
1858/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1859/// calls this with `ui.home`, which is `crate::run::home()` in a real
1860/// process but a fixture's own directory under test — falling through to
1861/// the global there would read and write through whichever home some other
1862/// test in the same binary happened to pin into that `OnceLock` first, not
1863/// the run this call actually means.
1864pub fn supersede_prior_runs(task: &Task, home: &Path) {
1865    let now = Timestamp::now();
1866    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1867    // right behind a `Merged`/`Ready` verdict) from one set directly by
1868    // `magi task done`/its web equivalent/the conductor on a task whose last
1869    // recorded attempt never actually landed - that requires reading the
1870    // run itself, which is exactly what this does before trusting anything
1871    // in `runs` is safe to relabel.
1872    let last_run_succeeded = task
1873        .runs
1874        .last()
1875        .and_then(|id| RunState::load_under(id, home).ok())
1876        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1877    for id in task.superseded_attempts(last_run_succeeded) {
1878        let mut state = match RunState::load_under(id, home) {
1879            Ok(s) => s,
1880            Err(e) => {
1881                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1882                continue;
1883            }
1884        };
1885        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1886            continue;
1887        }
1888        let daemon_claims = is_working_on(home, id, now);
1889        if state.liveness(daemon_claims) == Liveness::Live {
1890            continue;
1891        }
1892        state.status = RunStatus::Superseded;
1893        if let Err(e) = state.save_under(home) {
1894            tracing::warn!("could not mark run {id} superseded: {e:#}");
1895        }
1896    }
1897}
1898
1899/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1900/// finish the moment it was called, because one of its earlier attempts was
1901/// still live then - a `magi run --resume` invoked by hand on an old run,
1902/// most likely.
1903///
1904/// That skip is correct at the time (rewriting under a run something is
1905/// still actively saving would just be undone), but a task only ever
1906/// reaches `Done` once, so without this nothing would ever look at it
1907/// again: if that manual process later ends anywhere other than
1908/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1909/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1910/// backlog this status exists to clear. Called on the same idle-only
1911/// cadence as [`janitor`], next to it rather than folded into it: this
1912/// walks `queue` and `janitor` never otherwise needs one.
1913///
1914/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1915/// more than one attempt, every pass: each call is a handful of local file
1916/// reads bounded by that task's own attempt count, the same order of cost
1917/// [`clean::fold_due`] already pays scanning every run on disk on the same
1918/// cadence, and a task already fully resolved costs one failed liveness
1919/// check turned no-op the moment its lingering attempt is no longer live.
1920fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1921    for task in queue.list() {
1922        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1923            continue;
1924        }
1925        supersede_prior_runs(&task, home);
1926    }
1927}
1928
1929/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1930/// task ends up held.
1931///
1932/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1933/// dead daemon never got back to) share this, so the two cannot drift into
1934/// disagreeing about which held tasks get a diagnostic.
1935fn settle_and_diagnose(
1936    task: &mut Task,
1937    verdict: Verdict,
1938    detail: &str,
1939    max_attempts: usize,
1940    state: &RunState,
1941) {
1942    let p = phrases(&state.config.graph.language);
1943    // Shared by normal completion and crash recovery, under the task claim.
1944    // No new attempt can own the task until the old driver has exited.
1945    if let Some(d) = &state.merge_decision {
1946        use crate::merge_decision as md;
1947        if task.runs.last().is_some_and(|id| id != &state.id) {
1948            return;
1949        }
1950        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1951            task.succeed();
1952        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1953            if state.liveness(false) != Liveness::Dead {
1954                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1955                return;
1956            }
1957            let replacement = md::Replacement {
1958                question: d.question.clone(),
1959                run: state.id.clone(),
1960                pr: d.target.pr.clone(),
1961                agent: agent.to_owned(),
1962                context: format!(
1963                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1964                    d.target.pr,
1965                    state.id,
1966                    serde_json::to_string(&state.reviews).unwrap_or_default()
1967                ),
1968            };
1969            task.requeue();
1970            task.pr_recovery = None;
1971            task.review_of = None;
1972            task.replacement = Some(replacement);
1973        } else {
1974            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1975                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1976            } 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())) }));
1977        }
1978        task.mark_action_applied(&d.question);
1979        if let Some(pass) = state.passes.last() {
1980            task.record_pass_at(
1981                &state.id,
1982                pass.index,
1983                Some(pass.started_at),
1984                task.attempts,
1985                None,
1986            );
1987        }
1988        return;
1989    }
1990    if let Some(replacement) = &task.replacement
1991        && !state.parked
1992        && state.resource_block.is_none()
1993        && (state.viable().is_empty()
1994            || (state.status == RunStatus::Blocked && state.tally.is_none()))
1995    {
1996        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)));
1997        return;
1998    }
1999    let attempts_before = task.attempts;
2000    // A run that stopped because a shared resource stayed busy was never a
2001    // failure of the task or of an agent. Earlier nodes may have run; only
2002    // the blocked operation lacks a result. The attempt is
2003    // refunded and the task is held by the machine, under a reason `triage`
2004    // can re-check, so the same run resumes with the same agents once the
2005    // resource is free. A park request still wins (it is the operator's).
2006    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2007        task.notice_cause(
2008            &format!("resource:{}:{}", block.kind, block.node),
2009            None,
2010            None,
2011        );
2012        task.last_error = Some(detail.to_owned());
2013        task.diagnostic = None;
2014        task.attempts = task.attempts.saturating_sub(1);
2015        if block.kind == "disk pressure" {
2016            task.hold_machine(Some(format!(
2017                "{}{}",
2018                crate::disk::RUNNING_PRESSURE,
2019                block.detail
2020            )));
2021        } else {
2022            task.hold_machine(Some(format!(
2023                "{}{}; no attempt was spent; resume to retry the affected operation",
2024                crate::cache::RESOURCE_HOLD,
2025                block.description()
2026            )));
2027        }
2028        if let Some(pass) = state.passes.last() {
2029            task.record_pass_at(
2030                &state.id,
2031                pass.index,
2032                Some(pass.started_at),
2033                attempts_before,
2034                None,
2035            );
2036        }
2037        return;
2038    }
2039    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2040        state.parked
2041            && state.status == RunStatus::Landing
2042            && state
2043                .pr_pushed_head
2044                .as_ref()
2045                .is_none_or(|h| h == &hold.head)
2046            && task.runs.last() == Some(&state.id)
2047    }) {
2048        // Settlement and crash recovery share this idempotency key. A later
2049        // explicit resume is a new pass and may refund its own attempt once.
2050        let pass = state.passes.last().map_or(0, |p| p.index);
2051        if !task
2052            .passes
2053            .iter()
2054            .any(|p| p.run == state.id && p.pass_index == pass)
2055        {
2056            task.attempts = task.attempts.saturating_sub(1);
2057        }
2058        task.hold_machine(Some(format!(
2059            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2060            hold.question
2061        )));
2062        task.last_error = Some(detail.to_owned());
2063        task.diagnostic = None;
2064        task.record_pass_at(
2065            &state.id,
2066            pass,
2067            state.passes.last().map(|p| p.started_at),
2068            attempts_before,
2069            Some(crate::run::ParkCause::Question),
2070        );
2071        return;
2072    }
2073    let unresolved = task.hold_notice_cause.clone();
2074    if state.base_sync_blocked() {
2075        // No automatic retry may turn a retained sync stop into a new competition.
2076        task.hold_machine(Some(detail.to_owned()));
2077        task.last_error = Some(detail.to_owned());
2078    } else if !verdict.parked
2079        && task
2080            .pr_recovery
2081            .as_ref()
2082            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2083        && matches!(
2084            verdict.status,
2085            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2086        )
2087    {
2088        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2089            task.succeed();
2090        } else {
2091            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()));
2092        }
2093    } else if !verdict.parked
2094        && task.pr_recovery.is_some()
2095        && matches!(
2096            verdict.status,
2097            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2098        )
2099        && !verdict.quota_hit
2100    {
2101        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.")));
2102    } else {
2103        settle_in(task, verdict, detail, max_attempts, p);
2104    }
2105    if !verdict.parked
2106        && !verdict.quota_hit
2107        && matches!(
2108            verdict.status,
2109            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2110        )
2111    {
2112        task.recovery_failed(state);
2113    }
2114    if state.prep_failure.is_some() {
2115        // Minting a run whose candidates could not be prepared is not work
2116        // on a newly approved attempt. Keep the unresolved outcome anchor.
2117        task.hold_notice_cause = unresolved;
2118        task.startup_notice_cause("startup-candidates");
2119    }
2120    // Written here, where the refund (or not) is decided, so the history is a
2121    // fact and not a later guess from the run's status.
2122    if let Some(pass) = state.passes.last() {
2123        let parked = match &pass.end {
2124            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2125            _ => None,
2126        };
2127        task.record_pass_at(
2128            &state.id,
2129            pass.index,
2130            Some(pass.started_at),
2131            attempts_before,
2132            parked,
2133        );
2134    }
2135    if task.status == TaskStatus::Held {
2136        if state.base_sync_blocked() {
2137            task.base_sync_notice(state);
2138        } else if state.prep_failure.is_none() {
2139            task.notice_cause(
2140                label(verdict.status),
2141                Some(&state.id),
2142                state.passes.last().map(|p| p.index),
2143            );
2144        }
2145        task.diagnostic = diagnostic(state);
2146        note_open_question(task, &state.id, p);
2147    }
2148}
2149
2150/// If `task` is held with a `magi ask` question still open on `run`, name the
2151/// question in [`Task::hold_reason`] rather than leaving the hold reading
2152/// only [`describe`]'s run summary.
2153///
2154/// This is the shape task 20260928-191407-05fd left underspecified: an
2155/// implementer settled a verified no-op and filed a question for the
2156/// operator, and the hold that followed said nothing about the question
2157/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2158/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2159/// marker) and must keep seeing it unchanged.
2160///
2161/// Best-effort: an unreadable question store must not stop a run from
2162/// settling, so this is a no-op rather than a propagated error when
2163/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2164fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2165    let Some(home) = crate::run::try_home() else {
2166        return;
2167    };
2168    let open = Questions::at(home.join("questions")).open_for(run);
2169    let Some(q) = open.first() else {
2170        return;
2171    };
2172    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2173    decisions.sort_unstable();
2174    task.notice_cause(
2175        &format!("questions:{}", decisions.join(",")),
2176        Some(run),
2177        None,
2178    );
2179    let base = task.hold_reason.clone().unwrap_or_default();
2180    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2181}
2182
2183/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2184/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2185/// by some other means entirely, like a manual `magi run` resume that
2186/// finishes the graph outside the queue's bookkeeping.
2187///
2188/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2189/// `settle` is separate from `attempt`: a task recovered this way must land
2190/// exactly where a live daemon would have put it — the same policy table,
2191/// not a second one that quietly drifts from it — and that is only checkable
2192/// without spawning a real run.
2193fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2194    match last_run {
2195        Some(state) => {
2196            let verdict = Verdict {
2197                status: state.status,
2198                left_pr: state.pr.is_some(),
2199                quota_hit: !state.quota.is_empty(),
2200                parked: state.parked,
2201                no_viable_candidates: state.viable().is_empty(),
2202            };
2203            let detail = format!(
2204                "{}{}",
2205                phrases(&state.config.graph.language).recovered_running,
2206                describe(&state)
2207            );
2208            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2209        }
2210        None => {
2211            // No run, so no config of its own: `language` is the task's
2212            // repository's setting, read by the caller.
2213            let why = phrases(language).no_run_to_recover;
2214            task.last_error = Some(why.to_owned());
2215            // The phone shows `hold_reason`, so a task held by the machine
2216            // says why there too and not only in `last_error`.
2217            task.notice_cause("missing-run", None, None);
2218            task.hold_machine(Some(why.to_owned()));
2219        }
2220    }
2221}
2222
2223/// Find every task left at `running` that no live process is actually
2224/// driving, and settle each one against whatever its last run became.
2225///
2226/// # Why a claim is proof, not a guess
2227///
2228/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2229/// `running`, and the guard is held for the task's whole time in that status:
2230/// `attempt` does not return, and the loop does not move past the scope
2231/// holding the claim, until the run has settled. So a `running` task whose
2232/// lock is gone cannot have a live owner — this process or any other —
2233/// without needing a staleness threshold or a pid check the way
2234/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2235/// task that never got as far as `running` at all. Taking the claim here is
2236/// the whole test: it either fails, because something really does hold it
2237/// and the task is left alone, or it succeeds, which is the proof — and it is
2238/// kept for the rest of the decision so nothing else can start a competing
2239/// run while this one is being written.
2240///
2241/// Called on every poll, not only at startup, for the reason
2242/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2243/// keep noticing this, not only on the one morning it happened to restart.
2244fn reclaim_orphaned_running(
2245    queue: &Queue,
2246    max_attempts: usize,
2247    live_workers: &std::collections::BTreeSet<String>,
2248) -> Vec<String> {
2249    let mut reclaimed = Vec::new();
2250    for listed in queue.list() {
2251        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2252            continue;
2253        }
2254        let Ok(_claim) = queue.claim(&listed.id) else {
2255            continue;
2256        };
2257        // Re-read under the claim: a release or an edit landed by a human
2258        // between the listing above and the claim just taken must not be
2259        // clobbered by a decision based on the stale copy.
2260        let Ok(mut task) = queue.get(&listed.id) else {
2261            continue;
2262        };
2263        if task.status != TaskStatus::Running {
2264            continue;
2265        }
2266        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2267        // `execute` normally abandons a run's own open questions the moment
2268        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2269        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2270        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2271        // with the question still `open`, because the process died before
2272        // reaching that call. `reclaim` itself stays pure on purpose (see its
2273        // own doc), so the same cleanup runs here instead, against the run
2274        // this reclaim is already reading. `settle_run` costs nothing when
2275        // `execute` already got there first.
2276        if let Some(state) = &last_run
2277            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2278        {
2279            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2280        }
2281        let language = if last_run.is_none() {
2282            language_of(&task, Path::new("."))
2283        } else {
2284            String::new()
2285        };
2286        reclaim(&mut task, last_run, max_attempts, &language);
2287        if task.status == TaskStatus::Done {
2288            supersede_prior_runs(&task, &crate::run::home());
2289        }
2290        record(queue, &mut task);
2291        reclaimed.push(task.id.clone());
2292    }
2293    reclaimed
2294}
2295
2296/// Find every run whose `run.json` is provably dead — every seat it still
2297/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2298/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2299/// not merely "no daemon claims it" — and fail it, clearing the leftover
2300/// active seats so the run stops reading as `implementing` (or whichever
2301/// node) forever.
2302///
2303/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2304/// `running`, using whatever `run.json` already says — but nothing in that
2305/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2306/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2307/// never got back to sits exactly where it was left: `active` full of seats
2308/// nobody will ever answer for, `status` stuck on whatever node was in
2309/// flight. `magi show` already tells an operator this in prose (`no live
2310/// daemon claims this run right now`); this is what makes that fact durable
2311/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2312/// stay stuck once nothing is driving it.
2313///
2314/// Runs on every poll, not only at startup, for the reason
2315/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2316/// daemon up for days must keep noticing a run some other, now-dead, daemon
2317/// left behind just as readily as one it trips over on the way up.
2318///
2319/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2320/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2321/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2322/// `runs` directory instead: `home` here is a parameter precisely so a test
2323/// can point it away from the operator's real history (see [`drive`]'s own
2324/// doc), and a scan that fell through to the global home anyway would walk
2325/// whichever directory some *other* process or test pinned into that
2326/// `OnceLock` first — mutating runs this call was never handed.
2327fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2328    reclaim_abandoned_runs_with(
2329        home,
2330        now,
2331        crate::proc::pid_status,
2332        crate::proc::process_started_at,
2333    )
2334}
2335
2336/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2337/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2338/// for the identical reason: this sweep's real damage (wiping a run's active
2339/// seats and failing it) has to be provable against an injected answer in a
2340/// test, not just the real process table.
2341fn reclaim_abandoned_runs_with<F, G>(
2342    home: &Path,
2343    now: Timestamp,
2344    query: F,
2345    identity: G,
2346) -> Vec<String>
2347where
2348    F: Fn(u32) -> Option<bool>,
2349    G: Fn(u32) -> Option<String>,
2350{
2351    let mut abandoned = Vec::new();
2352    for entry in std::fs::read_dir(home.join("runs"))
2353        .into_iter()
2354        .flatten()
2355        .flatten()
2356    {
2357        let id = entry.file_name().to_string_lossy().into_owned();
2358        if !crate::run::is_run_id(&id) {
2359            continue;
2360        }
2361        // Serialize the proof and save with claims and takeover: a new
2362        // execution must not be overwritten after the liveness observation.
2363        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2364            continue;
2365        };
2366        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2367        // that module's docs for why a run this cannot parse is left alone
2368        // rather than guessed at. A different schema number is not that: this
2369        // touches only `status` and `active`, never a field whose meaning a
2370        // schema bump changed, so an old record's values serve this exactly
2371        // as well as a current one's (see `clean::read_state`'s own doc for
2372        // the same reasoning applied to folding).
2373        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2374            continue;
2375        };
2376        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2377            continue;
2378        };
2379        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2380            continue;
2381        }
2382        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2383        // it", which is also the normal, healthy shape of a manual `magi
2384        // run` / `magi review` sharing this same home — this scan walks
2385        // every run on disk, not only ones this daemon itself started. Such
2386        // a run's active seats can legitimately sit past their own timeout
2387        // for a little while (the CLI finishing up, its result still being
2388        // collected) without the process driving it having died. `liveness`
2389        // is what actually tells the two apart, by corroborating
2390        // `driver_pid` against the process it names — see its own doc. Only
2391        // its strongest, provable answer licenses wiping this run's active
2392        // seats and failing it out from under whatever is still running it.
2393        let daemon_claims = is_working_on(home, &id, now);
2394        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2395            != crate::run::Liveness::Dead
2396        {
2397            continue;
2398        }
2399        state.abandon("daemon");
2400        if let Err(e) = state.save_under(home) {
2401            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2402            continue;
2403        }
2404        // This run never passes through `Runner::execute` again, so its end
2405        // is announced here.
2406        if let Some(notice) = notices::run_ended(&state) {
2407            notices::raise_in(home, notice);
2408        }
2409        // The seat that asked is gone for good now, exactly like any other
2410        // door `graph::Runner::settle_questions` closes the moment `status`
2411        // lands somewhere non-resumable - see that method's own doc. Nothing
2412        // else reaches this one before the next `janitor()` startup pass
2413        // (`clean::abandon_settled_questions`), and a daemon that stays up
2414        // for days must not leave an open question badging the operator
2415        // until it happens to restart.
2416        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2417            tracing::warn!("abandon questions for {id}: {e:#}");
2418        }
2419        abandoned.push(id);
2420    }
2421    abandoned
2422}
2423
2424#[derive(Debug, Clone, Serialize, Deserialize)]
2425struct TaskWorker {
2426    opts: Opts,
2427    queue: PathBuf,
2428    task: String,
2429    #[serde(default)]
2430    lane: PermitKind,
2431    #[serde(default)]
2432    standalone: bool,
2433}
2434
2435fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2436    Ok(crate::worker::active(home)?
2437        .into_iter()
2438        .filter(|job| job.kind == "task")
2439        .collect())
2440}
2441
2442fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2443    task_jobs(home)?
2444        .into_iter()
2445        .filter_map(
2446            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2447                Ok(request) if !request.standalone => Some(Ok(job)),
2448                Ok(_) => None,
2449                Err(error) => Some(Err(error.into())),
2450            },
2451        )
2452        .collect()
2453}
2454
2455/// Whether an independent scheduler can be controlled without its web parent.
2456#[must_use]
2457pub fn managed(home: &Path) -> bool {
2458    match crate::worker::active(home) {
2459        Err(error) => {
2460            tracing::error!("cannot determine scheduler ownership: {error:#}");
2461            true
2462        }
2463        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2464        Ok(_) => {
2465            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2466                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2467        }
2468    }
2469}
2470
2471/// Start a detached, singleton scheduler using this executable generation.
2472pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2473    anyhow::ensure!(
2474        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2475        "the scheduler is stopping; wait for retirement before starting it again"
2476    );
2477    crate::worker::spawn(
2478        home,
2479        "scheduler",
2480        "scheduler",
2481        serde_json::to_value(opts.absolute()?)?,
2482    )
2483    .await
2484}
2485
2486fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2487    home.join("worker-parks").join(format!("{}.json", job.id))
2488}
2489
2490fn request_task_park(
2491    home: &Path,
2492    job: &crate::worker::Job,
2493    cause: crate::run::ParkCause,
2494) -> Result<()> {
2495    let path = park_request_path(home, job);
2496    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2497    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2498    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2499}
2500
2501/// Stop dispatch immediately; only an explicit park reaches existing workers.
2502pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2503    if control == crate::worker::Control::Park {
2504        for job in owned_task_jobs(home)? {
2505            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2506        }
2507    }
2508    crate::worker::request(home, "scheduler", control)
2509}
2510
2511/// Replace the scheduler, leaving all active task and conversation jobs alone.
2512pub async fn restart_detached(home: &Path) -> Result<()> {
2513    let active = crate::worker::active(home)?;
2514    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2515    if prior.is_none() && !managed(home) {
2516        return Ok(());
2517    }
2518    let opts: Opts = match prior {
2519        Some(job) => serde_json::from_value(job.payload)?,
2520        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2521    };
2522    request_control(home, crate::worker::Control::Stop)?;
2523    loop {
2524        let reserved = crate::worker::active(home)?
2525            .iter()
2526            .any(|job| job.kind == "scheduler");
2527        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2528            break;
2529        }
2530        tokio::time::sleep(Duration::from_millis(100)).await;
2531    }
2532    spawn_detached(home, &opts).await?;
2533    Ok(())
2534}
2535
2536/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2537pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2538    let opts: Opts = serde_json::from_value(payload)?;
2539    let _ = home;
2540    serve_until(opts, Stop::new()).await
2541}
2542
2543/// Execute and settle one task with the queue claim owned by this process.
2544pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2545    let request: TaskWorker = serde_json::from_value(payload)?;
2546    let queue = Queue::at(request.queue);
2547    let key = format!("task:{}", request.task);
2548    let job = task_jobs(home)?
2549        .into_iter()
2550        .find(|job| job.key == key)
2551        .context("task worker reservation is missing")?;
2552    let park_path = park_request_path(home, &job);
2553    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2554    // our durable reservation. Never execute before that ownership hand-off.
2555    let _claim = loop {
2556        match queue.claim(&request.task) {
2557            Ok(claim) => break claim,
2558            // Only contention (the claim file exists) is worth waiting out; an
2559            // I/O failure must end this worker instead of pinning its lane.
2560            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2561                return Err(e.context("claim the task for its worker"));
2562            }
2563            Err(_) => {
2564                sweep_stale_claims(&queue, STALE_CLAIM);
2565                tokio::time::sleep(Duration::from_millis(50)).await;
2566            }
2567        }
2568    };
2569    let mut task = queue.get(&request.task)?;
2570    if !task.status.runnable()
2571        || (!request.standalone
2572            && request.lane
2573                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2574    {
2575        return Ok(());
2576    }
2577    let stop = Stop::new();
2578    let watcher = {
2579        let home = home.to_path_buf();
2580        let stop = stop.clone();
2581        let park_path = park_path.clone();
2582        tokio::spawn(async move {
2583            loop {
2584                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2585                    let cause = std::fs::read(&park_path)
2586                        .ok()
2587                        .and_then(|body| serde_json::from_slice(&body).ok())
2588                        .unwrap_or(crate::run::ParkCause::Operator);
2589                    stop.park(cause);
2590                    return;
2591                }
2592                tokio::time::sleep(Duration::from_millis(200)).await;
2593            }
2594        })
2595    };
2596    let quota = if request.standalone {
2597        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2598    } else {
2599        let status = Arc::new(Mutex::new(Status::new()));
2600        Box::pin(attempt(
2601            &request.opts,
2602            &queue,
2603            &status,
2604            &stop,
2605            crate::graph::Pause::new(),
2606            &mut task,
2607        ))
2608        .await
2609    };
2610    watcher.abort();
2611    let _ = std::fs::remove_file(park_path);
2612    persist_cooldown(home, &quota).await?;
2613    Ok(())
2614}
2615
2616/// Launch the standalone task worker with a claim-to-reservation handoff.
2617/// Returns only after the worker owns a durable execution reservation.
2618pub async fn spawn_claimed(
2619    home: &Path,
2620    opts: &Opts,
2621    queue: &Queue,
2622    task: &Task,
2623    claim: crate::queue::Claim,
2624) -> Result<crate::worker::Job> {
2625    let request = TaskWorker {
2626        opts: opts.absolute()?,
2627        queue: std::path::absolute(queue.root())?,
2628        task: task.id.clone(),
2629        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2630        standalone: true,
2631    };
2632    let job = crate::worker::spawn(
2633        home,
2634        "task",
2635        &format!("task:{}", task.id),
2636        serde_json::to_value(request)?,
2637    )
2638    .await?;
2639    drop(claim);
2640    Ok(job)
2641}
2642
2643/// Transfer a standalone caller's claim only after the detached worker is live,
2644/// then follow that worker to its final (non-automatically-retrying) outcome.
2645pub async fn run_detached_claimed(
2646    opts: &Opts,
2647    queue: &Queue,
2648    task: &mut Task,
2649    claim: crate::queue::Claim,
2650) -> Result<()> {
2651    let home = crate::run::home();
2652    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2653    loop {
2654        // Reconcile execution leases even without a scheduler. A dead worker
2655        // must become a reported failure, never an infinite persisted wait.
2656        crate::worker::active(&home)?;
2657        let current = crate::worker::get(&home, &job.id)?;
2658        if matches!(
2659            current.status,
2660            crate::worker::Status::Finished | crate::worker::Status::Failed
2661        ) {
2662            *task = queue.get(&task.id)?;
2663            anyhow::ensure!(
2664                current.status != crate::worker::Status::Failed,
2665                "task worker failed: {}",
2666                current.result.as_deref().unwrap_or("unknown failure")
2667            );
2668            return Ok(());
2669        }
2670        tokio::time::sleep(Duration::from_millis(200)).await;
2671    }
2672}
2673
2674async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2675    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2676        let _lease = loop {
2677            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2678                break lease;
2679            }
2680            tokio::time::sleep(Duration::from_millis(10)).await;
2681        };
2682        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2683            let path = home.join("task-quota-cooldown.json");
2684            let temporary = path.with_extension("json.tmp");
2685            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2686            std::fs::rename(temporary, path)?;
2687        }
2688    }
2689    Ok(())
2690}
2691
2692fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2693    match std::fs::read(home.join("task-quota-cooldown.json")) {
2694        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2695        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2696        Err(error) => Err(error.into()),
2697    }
2698}
2699
2700/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2701///
2702/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2703/// sets, so there is one loop body rather than two that drift apart the first
2704/// time the retry policy changes on only one of them.
2705pub async fn serve(opts: Opts) -> Result<()> {
2706    tracing::info!(
2707        "automatic update and restart requires magi web; standalone serve does not restart"
2708    );
2709    serve_until(opts, Stop::new()).await
2710}
2711
2712/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2713///
2714/// A stop retires dispatch promptly, including while a worker launch is being
2715/// acknowledged. Already reserved workers own their attempts independently and
2716/// finish with their started executable. Explicit park additionally forwards
2717/// durable park requests; neither scheduler retirement nor update does so.
2718///
2719/// While the queue is empty the stop is honoured within one wakeup rather than
2720/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2721/// caller that taps stop does not sit through the remainder of a sleep.
2722pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2723    let opts = opts.absolute()?;
2724    let home = crate::run::home();
2725    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2726        .context("another scheduler already owns this home")?;
2727    if let Some(reading) = read_status(&home)
2728        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2729    {
2730        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2731    }
2732    if !crate::worker::active(&home)?
2733        .iter()
2734        .any(|job| job.kind == "scheduler")
2735    {
2736        crate::worker::clear_control(&home, "scheduler")?;
2737    }
2738    std::fs::write(
2739        home.join("scheduler-options.json"),
2740        serde_json::to_vec(&opts)?,
2741    )?;
2742    let control = {
2743        let home = home.clone();
2744        let stop = stop.clone();
2745        tokio::spawn(async move {
2746            loop {
2747                match crate::worker::control(&home, "scheduler").ok().flatten() {
2748                    Some(crate::worker::Control::Park) => {
2749                        let _ = request_control(&home, crate::worker::Control::Park);
2750                        stop.park(crate::run::ParkCause::Operator);
2751                        break;
2752                    }
2753                    Some(crate::worker::Control::Stop) => {
2754                        stop.stop();
2755                        break;
2756                    }
2757                    None => {}
2758                }
2759                tokio::time::sleep(Duration::from_millis(100)).await;
2760            }
2761        })
2762    };
2763    let signal = {
2764        let stop = stop.clone();
2765        tokio::spawn(async move {
2766            if tokio::signal::ctrl_c().await.is_ok() {
2767                stop.stop();
2768                tracing::info!("scheduler shutdown requested; independent workers continue");
2769            }
2770        })
2771    };
2772
2773    let worktrees_root = opts
2774        .worktrees_root
2775        .clone()
2776        .unwrap_or_else(crate::run::default_worktree_root);
2777    let outcome = drive(
2778        &opts,
2779        &Queue::open(),
2780        &status_path(),
2781        &crate::run::home(),
2782        &worktrees_root,
2783        &stop,
2784    )
2785    .await;
2786
2787    signal.abort();
2788    control.abort();
2789    outcome
2790}
2791
2792/// The loop proper: setup, poll, teardown, with the queue and the status file
2793/// supplied rather than discovered.
2794///
2795/// All three of `home`, `worktrees_root` and the queue/status paths are
2796/// parameters rather than resolved here, for the same reason:
2797/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2798/// so a unit test that pinned it would fight every other test in the binary,
2799/// and a loop that resolved its own worktree bay could only be exercised
2800/// against the operator's real `~/wt/<repo>` - publishing over a live
2801/// daemon's status file, claiming tasks out of a live backlog, and, since
2802/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2803/// whatever the operator actually has on disk.
2804async fn drive(
2805    opts: &Opts,
2806    queue: &Queue,
2807    status_file: &Path,
2808    home: &Path,
2809    worktrees_root: &Path,
2810    stop: &Stop,
2811) -> Result<()> {
2812    // The status file is a *snapshot*, not a stream of events: a reader only
2813    // ever wants the latest values, and every tick rewrites the whole file
2814    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2815    // while an mpsc channel would force the loop to re-send unchanged fields on
2816    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2817    // for no gain. The lock is only ever held across a field assignment, never
2818    // across an await.
2819    let recovery_cfg = prepare(&opts.repo, opts).ok();
2820    let daemon_cfg = recovery_cfg
2821        .as_ref()
2822        .map(|c| c.daemon.clone())
2823        .unwrap_or_default();
2824    let reconciled = crate::driver::reconcile(home);
2825    if !reconciled.is_empty() {
2826        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2827    }
2828    let mut initial_status = Status::new();
2829    let owned = owned_task_jobs(home)?;
2830    initial_status.current = current_work(home, Timestamp::now())
2831        .into_iter()
2832        .filter(|current| {
2833            owned
2834                .iter()
2835                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2836        })
2837        .collect();
2838    initial_status.idle = initial_status.current.is_empty();
2839    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2840        recovery_cfg.as_ref(),
2841        daemon_cfg.max_deputies,
2842    ));
2843    let status = Arc::new(Mutex::new(initial_status));
2844    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2845    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2846
2847    // Read once at startup, not per task: how many runs this loop drives at
2848    // once is a property of the machine running it, not of whichever
2849    // repository a given task happens to name - see
2850    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2851    // fact in the same sense the agent roster is.
2852    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2853
2854    tracing::info!(
2855        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2856        queue.root().display(),
2857        opts.poll.as_secs(),
2858        opts.max_attempts,
2859        concurrency,
2860        if daemon_cfg.pause_for_interrupts {
2861            ", interrupts enabled"
2862        } else {
2863            ""
2864        }
2865    );
2866
2867    let outcome = tokio::select! {
2868        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2869            max_concurrent: concurrency,
2870            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2871            recovery_cfg,
2872        }) => outcome,
2873        () = async {
2874            while !stop.stopped() {
2875                tokio::time::sleep(Duration::from_millis(25)).await;
2876            }
2877        } => {
2878            if stop.parking() {
2879                request_control(home, crate::worker::Control::Park)?;
2880            }
2881            Ok(())
2882        }
2883    };
2884
2885    stop.busy.store(0, Ordering::SeqCst);
2886    beat.abort();
2887    clear_status_at(status_file);
2888    outcome
2889}
2890
2891/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2892/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2893pub(crate) fn release_watch_settings_from_config(
2894    home: &Path,
2895    repo: &Path,
2896    cfg: &Config,
2897) -> (Vec<PathBuf>, u64) {
2898    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2899        .into_iter()
2900        .map(|r| r.path)
2901        .collect();
2902    // Repositories the daemon has worked in, wherever they live: a task may
2903    // name one outside `[repos] roots`, and its release PR must be watched too.
2904    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
2905        .list()
2906        .into_iter()
2907        .map(|t| t.repo)
2908        .collect();
2909    let runs = home.join("runs");
2910    for id in crate::run::list_ids_in(&runs) {
2911        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2912            .ok()
2913            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2914            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2915        known.extend(repo);
2916    }
2917    for k in known {
2918        let k = k.canonicalize().unwrap_or(k);
2919        if k.join(".git").exists() && !paths.contains(&k) {
2920            paths.push(k);
2921        }
2922    }
2923    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2924    if !paths.contains(&own) {
2925        paths.push(own);
2926    }
2927    (paths, cfg.daemon.release_stall_minutes)
2928}
2929
2930/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2931const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2932
2933/// Refresh the status file on a fixed tick.
2934///
2935/// Separate from the loop because a run takes tens of minutes: a status file
2936/// written only between tasks would look stale for the whole of every run, and
2937/// a reader would report the daemon dead exactly while it was busiest.
2938async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2939    loop {
2940        tokio::time::sleep(HEARTBEAT).await;
2941        let snapshot = {
2942            let mut guard = lock(&status);
2943            guard.updated_at = Timestamp::now();
2944            guard.clone()
2945        };
2946        if let Err(e) = write_status_to(&path, &snapshot) {
2947            // A failed heartbeat must not take the daemon down: the loop is the
2948            // product, the status file is only the window onto it.
2949            tracing::warn!("could not refresh the daemon status file: {e:#}");
2950        }
2951    }
2952}
2953
2954/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2955/// if so, whether that wait is over.
2956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2957enum LandResume {
2958    /// The task's last run is not parked on a land approval; schedule it
2959    /// like any other candidate.
2960    NotLanding,
2961    /// Parked in `land`, waiting on a question nobody has answered yet.
2962    /// Left alone: attempting it now would only re-observe the same pull
2963    /// request and park again, spending a `gh` call on a decision that has
2964    /// not changed since the last time this was checked.
2965    StillWaiting,
2966    /// Parked in `land`, and the question is settled - answered or
2967    /// abandoned. Resuming this is the one kind of candidate that must not
2968    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2969    Ready,
2970}
2971
2972/// Classify a runnable candidate by whether it is parked on a land-merge
2973/// approval. Read-only - no claim taken, nothing written - so it is cheap
2974/// enough to call on every candidate, every poll.
2975fn land_resume_state(task: &Task) -> LandResume {
2976    let Some(run_id) = task.runs.last() else {
2977        return LandResume::NotLanding;
2978    };
2979    let Ok(state) = RunState::load(run_id) else {
2980        return LandResume::NotLanding;
2981    };
2982    if !state.parked {
2983        return LandResume::NotLanding;
2984    }
2985    if state.status == RunStatus::Landing
2986        && state.land_approval.as_ref().is_some_and(|binding| {
2987            ask::Questions::open()
2988                .get(&binding.question)
2989                .is_ok_and(|q| {
2990                    q.run == state.id
2991                        && q.resolution()
2992                            .as_deref()
2993                            .is_some_and(crate::merge_decision::stops)
2994                })
2995        })
2996    {
2997        return LandResume::Ready;
2998    }
2999    if !implementers_match(task, &state) {
3000        return LandResume::NotLanding;
3001    }
3002    // Parked in `land` on the merge approval, or at `merge` on the owner's
3003    // word about a title/body the posting gate withheld. Told apart by the
3004    // run's own record, not by a status both can share.
3005    let node = if state.status == RunStatus::Landing {
3006        land::APPROVAL_NODE
3007    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3008        crate::github_text::ASK_NODE
3009    } else {
3010        return LandResume::NotLanding;
3011    };
3012    let store = ask::Questions::open();
3013    let waiting = store
3014        .list()
3015        .into_iter()
3016        .filter(|q| &q.run == run_id && q.node == node)
3017        .max_by(|a, b| a.id.cmp(&b.id));
3018    let Some(mut q) = waiting else {
3019        return LandResume::Ready;
3020    };
3021    if !q.status.open() {
3022        // Repair spends agent resources and must obey concurrency and quota
3023        // waits; only a merge/hold decision may use the decision-only lane.
3024        if q.resolution().as_deref() == Some(land::REPAIR) {
3025            return if state.liveness(false) == Liveness::Live {
3026                LandResume::StillWaiting
3027            } else {
3028                LandResume::NotLanding
3029            };
3030        }
3031        return LandResume::Ready;
3032    }
3033    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3034    // nobody ever answered; land's approval bypasses that wait entirely (see
3035    // `land::approval_gate`), so the same deadline has to be enforced here
3036    // instead, or `graph.answer_timeout` silently stops meaning anything for
3037    // a land approval and a run can sit `StillWaiting` forever with nobody
3038    // told to look at it.
3039    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3040    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3041    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3042        q.abandon(format!(
3043            "no answer within {}s of asking",
3044            timeout.as_secs().max(1)
3045        ));
3046        // If this can't be persisted, do not treat the wait as settled on a
3047        // guess: fall through and try again next poll.
3048        if store.put(&mut q).is_ok() {
3049            return LandResume::Ready;
3050        }
3051    }
3052    LandResume::StillWaiting
3053}
3054
3055/// How often the loop rechecks for new work while something it already
3056/// started is still running, rather than sleeping out the whole
3057/// [`Opts::poll`] interval.
3058///
3059/// Short on purpose: this is what lets a land-merge approval that comes back
3060/// while another task is mid-competition be noticed and resumed within a
3061/// fraction of a second, not within the next multi-second poll.
3062const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3063
3064/// How often [`poll`] rechecks the shared build cache against its cap at a
3065/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3066/// waiting for the queue to run dry.
3067///
3068/// A queue that never empties means the `janitor` call at the bottom of this
3069/// loop's fully-idle branch can go unreached for as long as the backlog
3070/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3071/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3072/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3073/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3074/// backlog of short tasks does not pay for that walk on every poll.
3075const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3076
3077/// State of [`poll`]'s own interrupt-scheduling sequence - see
3078/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3079/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3080/// both kept free of `Task`'s non-identity fields on purpose: every decision
3081/// here turns only on task ids and which ones are in flight, so the "never
3082/// more than one run at once" and "exactly one resume" invariants can be
3083/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3084/// queue - which is exactly the coverage this feature's first two attempts
3085/// were missing.
3086///
3087/// Persisted after every transition, so scheduler replacement preserves the
3088/// interrupt's exclusive turn and the interrupted task's priority resume.
3089#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3090enum Interrupt {
3091    /// No interrupt sequence in progress. Ordinary dispatch applies.
3092    Idle,
3093    /// `interrupt_task` is runnable and exactly one other run is in flight;
3094    /// `parked` names that one task's id. Dispatch is withheld from
3095    /// everyone, including `interrupt_task` itself, until it has left
3096    /// flight - only then is `interrupt_task` let through.
3097    ///
3098    /// `parked` is a `Vec` rather than a bare id for symmetry with
3099    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3100    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3101    /// when exactly one run is in flight, so it is guaranteed to hold
3102    /// exactly one entry in practice - see that branch's own doc for why
3103    /// more than one is deliberately never attempted.
3104    Parking {
3105        parked: Vec<String>,
3106        interrupt_task: String,
3107    },
3108    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3109    /// withheld from everyone until it leaves flight - merged, failed, held,
3110    /// it makes no difference - at which point the sequence moves to
3111    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3112    /// going straight to `Idle` would hand `parked` back to ordinary
3113    /// priority-order dispatch, where a higher-priority task filed in the
3114    /// meantime could start ahead of it.
3115    Running {
3116        parked: Vec<String>,
3117        interrupt_task: String,
3118    },
3119    /// `interrupt_task` left flight; `parked` still names the one run this
3120    /// sequence owes a resume. Dispatch is withheld from everyone except
3121    /// that task - see [`interrupt_gate`] - so the resume this feature
3122    /// promises is never raced by, or run alongside, an unrelated candidate.
3123    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3124    /// own doc on abandonment - the moment it is no longer runnable at all.
3125    Resuming { parked: Vec<String> },
3126}
3127
3128/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3129/// and `runnable` are read-only snapshots of this tick's reality, and the
3130/// only side effect the caller still owes the world is asking whichever
3131/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3132/// site.
3133///
3134/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3135/// accepted rather than a narrower type because that is what [`poll`] already
3136/// has on hand from [`runnable`], and building a second, smaller list on
3137/// every tick just to satisfy this signature would cost more than it proves.
3138///
3139/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3140/// back to a task they are waiting on no longer being [`runnable`] - held,
3141/// blocked, deleted, or finished by some other means entirely, all of which
3142/// an operator can do to a task sitting in the queue with no claim on it at
3143/// all, at any moment, interrupt sequence or not. Without this check the
3144/// sequence would wait forever for a dispatch that can never come, and
3145/// `interrupt_gate` would withhold every other task in the queue right along
3146/// with it - a single `magi task hold` on the wrong id turning into a
3147/// daemon that never dispatches anything again.
3148fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3149    match state {
3150        Interrupt::Idle => {
3151            // Not just "something to interrupt": exactly one thing. More
3152            // than one run in flight only happens above the default
3153            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3154            // one resume, never run alongside anything else" only because
3155            // it is only ever seeded with exactly one id - see
3156            // `Interrupt::Resuming`'s own doc on why releasing more than one
3157            // parked id back to ordinary dispatch cannot be made safe
3158            // against that same setting's own extra concurrency slots.
3159            // Waiting here for the herd to settle to one is the
3160            // simplification this feature's own constraints ask for rather
3161            // than a second concurrency model to reconcile with the first.
3162            if in_flight.len() != 1 {
3163                return Interrupt::Idle;
3164            }
3165            match runnable.iter().find(|t| t.interrupt) {
3166                Some(t) => Interrupt::Parking {
3167                    parked: in_flight.to_vec(),
3168                    interrupt_task: t.id.clone(),
3169                },
3170                None => Interrupt::Idle,
3171            }
3172        }
3173        Interrupt::Parking {
3174            parked,
3175            interrupt_task,
3176        } => {
3177            if in_flight.iter().any(|id| parked.contains(id)) {
3178                // Still waiting for what was in flight to actually stop.
3179                Interrupt::Parking {
3180                    parked,
3181                    interrupt_task,
3182                }
3183            } else if in_flight.contains(&interrupt_task) {
3184                Interrupt::Running {
3185                    parked,
3186                    interrupt_task,
3187                }
3188            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3189                // The parked run(s) are gone, but the interrupt task has not
3190                // been dispatched yet on this tick - `interrupt_gate` is
3191                // what lets it through next.
3192                Interrupt::Parking {
3193                    parked,
3194                    interrupt_task,
3195                }
3196            } else {
3197                // The interrupt task itself is no longer runnable - see this
3198                // function's own doc on abandonment. The parked run(s) still
3199                // get their guaranteed resume; there is simply no interrupt
3200                // to run ahead of them any longer.
3201                Interrupt::Resuming { parked }
3202            }
3203        }
3204        Interrupt::Running {
3205            parked,
3206            interrupt_task,
3207        } => {
3208            if in_flight.contains(&interrupt_task) {
3209                Interrupt::Running {
3210                    parked,
3211                    interrupt_task,
3212                }
3213            } else {
3214                // The interrupt task's own run reached a terminal status,
3215                // whichever one - this is the *only* trigger that moves the
3216                // sequence on, driven straight off the same in-flight
3217                // bookkeeping `poll` already reaps every tick, not a second,
3218                // independent poll of anything.
3219                Interrupt::Resuming { parked }
3220            }
3221        }
3222        Interrupt::Resuming { parked } => {
3223            if in_flight.iter().any(|id| parked.contains(id)) {
3224                // One of the parked runs has been dispatched - the resume
3225                // this sequence owed is fulfilled. Whatever else is left in
3226                // `parked` (ordinarily nothing, at the default concurrency
3227                // of one) rejoins ordinary priority-order dispatch, same as
3228                // any other runnable task.
3229                Interrupt::Idle
3230            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3231                Interrupt::Resuming { parked }
3232            } else {
3233                // Abandonment (see this function's own doc): nothing left in
3234                // `parked` is even runnable any longer.
3235                Interrupt::Idle
3236            }
3237        }
3238    }
3239}
3240
3241/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3242/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3243/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3244/// indistinguishable from any other runnable task - exactly the "off does
3245/// nothing" this feature promises.
3246fn advance_interrupt_tick(
3247    enabled: bool,
3248    state: Interrupt,
3249    in_flight: &[String],
3250    runnable: &[Task],
3251) -> Interrupt {
3252    if !enabled {
3253        return Interrupt::Idle;
3254    }
3255    advance_interrupt(state, in_flight, runnable)
3256}
3257
3258/// Which of this tick's runnable candidates the interrupt sequence actually
3259/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3260/// each half is assertable on its own: this is the half that keeps a
3261/// competition and an interrupt from ever running at the same moment.
3262fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3263    match state {
3264        Interrupt::Idle => candidates,
3265        Interrupt::Parking {
3266            parked,
3267            interrupt_task,
3268        } => {
3269            if in_flight.iter().any(|id| parked.contains(id)) {
3270                Vec::new()
3271            } else {
3272                candidates
3273                    .into_iter()
3274                    .filter(|t| &t.id == interrupt_task)
3275                    .collect()
3276            }
3277        }
3278        Interrupt::Running { .. } => Vec::new(),
3279        // At most one: even if `parked` names more than one id (more than
3280        // one run was in flight when the sequence began, only possible
3281        // above the default `max_concurrent_runs = 1`), only the first match
3282        // is offered. Capping this to a single candidate - not merely to
3283        // `parked`'s own ids - is what makes "exactly one resume, never two
3284        // dispatched together" true regardless of how many ordinary slots
3285        // happen to be free this tick.
3286        Interrupt::Resuming { parked } => candidates
3287            .into_iter()
3288            .find(|t| parked.contains(&t.id))
3289            .into_iter()
3290            .collect(),
3291    }
3292}
3293
3294/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3295/// bundled into one parameter so `poll`'s own signature stays readable -
3296/// see [`drive`]'s call site for where these are actually read.
3297struct DispatchLimits {
3298    /// How many *ordinary* candidates run at once. See
3299    /// [`crate::config::Daemon::max_concurrent_runs`].
3300    max_concurrent: usize,
3301    /// See [`crate::config::Daemon::pause_for_interrupts`].
3302    pause_for_interrupts: bool,
3303    recovery_cfg: Option<Config>,
3304}
3305
3306/// Which semaphore, if any, dispatching a candidate should draw its permit
3307/// from.
3308///
3309/// Pure and separate from [`poll`]'s loop body for the same reason
3310/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3311/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3312/// exactly the policy this feature adds, and a policy only exercisable by
3313/// running the whole loop is a policy nobody checks.
3314#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3315enum PermitKind {
3316    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3317    /// Checked first - a task can be both a land resume and marked
3318    /// [`Task::urgent`], and the resume's own "must not queue behind
3319    /// anything" guarantee takes precedence.
3320    None,
3321    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3322    /// (never in addition to trying) the ordinary pool. This is what lets
3323    /// an urgent task dispatch while every ordinary slot is already checked
3324    /// out, and what stops a second urgent task from opening a third run: it
3325    /// waits on this same one-slot semaphore rather than falling through to
3326    /// the ordinary one.
3327    Urgent,
3328    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3329    /// above.
3330    #[default]
3331    Ordinary,
3332}
3333
3334/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3335/// own boolean, already computed by the caller from [`land_resume_state`].
3336fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3337    if priority {
3338        PermitKind::None
3339    } else if urgent {
3340        PermitKind::Urgent
3341    } else {
3342        PermitKind::Ordinary
3343    }
3344}
3345
3346fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3347    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3348        (0usize, 0usize),
3349        |(ordinary, urgent), request| match request.lane {
3350            PermitKind::Ordinary => (ordinary + 1, urgent),
3351            PermitKind::Urgent => (ordinary, urgent + 1),
3352            PermitKind::None => (ordinary, urgent),
3353        },
3354    );
3355    (
3356        limit.saturating_sub(ordinary),
3357        1usize.saturating_sub(urgent),
3358    )
3359}
3360
3361struct DispatchClaim {
3362    task: Task,
3363    claim: crate::queue::Claim,
3364    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3365}
3366
3367/// Claim and re-read before choosing a lane: a queue listing may predate an
3368/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3369fn claim_dispatch(
3370    queue: &Queue,
3371    candidate: &Task,
3372    cooling_down: bool,
3373    ordinary: &Arc<tokio::sync::Semaphore>,
3374    urgent: &Arc<tokio::sync::Semaphore>,
3375) -> Option<DispatchClaim> {
3376    let Ok(claim) = queue.claim(&candidate.id) else {
3377        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3378        return None;
3379    };
3380    let task = match queue.get(&candidate.id) {
3381        Ok(t) if t.status.runnable() => t,
3382        Ok(_) => return None,
3383        Err(e) => {
3384            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3385            return None;
3386        }
3387    };
3388    let resume = land_resume_state(&task);
3389    if resume == LandResume::StillWaiting {
3390        return None;
3391    }
3392    let priority = resume == LandResume::Ready;
3393    if !priority && cooling_down {
3394        return None;
3395    }
3396    // Never borrow an ordinary slot when the single urgent slot is busy.
3397    // Keep scanning other candidates when either pool has no free slot.
3398    let permit = match permit_kind(priority, task.urgent) {
3399        PermitKind::None => None,
3400        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3401        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3402    };
3403    // Persist the dispatch order under the claim, before config discovery or
3404    // coordination waits can reorder concurrent starts.
3405    let stamp = Timestamp::now();
3406    let mut task = task;
3407    task.dispatched_at = Some(stamp);
3408    if let Err(e) = queue.modify(&task.id, |t| {
3409        t.dispatched_at = Some(stamp);
3410        true
3411    }) {
3412        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3413    }
3414    Some(DispatchClaim {
3415        task,
3416        claim,
3417        permit,
3418    })
3419}
3420
3421/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3422/// teardown and cannot skip the teardown on an early return.
3423///
3424/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3425/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3426/// land approval that has since been answered is dispatched outside that
3427/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3428/// the whole point of parking there is that it must not queue behind
3429/// whatever else the loop happens to be running, even at the default of one.
3430/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3431/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3432/// these exemptions is still subject to the interrupt gate below, urgent
3433/// included: a land-resume or urgent candidate is exactly as much "something
3434/// else running" as an ordinary one from the interrupt sequence's point of
3435/// view, and letting either slip through while a run is being parked, or
3436/// while the interrupt task itself has the floor, is precisely the second
3437/// run 75dd's own "at most one run, ever, at once" guarantee must never
3438/// allow - see [`Interrupt`]'s own doc.
3439#[derive(Serialize, Deserialize)]
3440struct ServiceWorker {
3441    opts: Opts,
3442    queue: PathBuf,
3443    worktrees_root: PathBuf,
3444    operation: String,
3445}
3446
3447fn load_conductor(home: &Path) -> Result<Conductor> {
3448    match std::fs::read(home.join("conductor-state.json")) {
3449        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3450        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3451        Err(error) => Err(error.into()),
3452    }
3453}
3454
3455fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3456    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3457        .into_iter()
3458        .map(|c| c.task)
3459        .collect();
3460    let stalled = stalled_tasks(queue, home, Timestamp::now());
3461    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3462    let finished = finished_tasks(queue)
3463        .into_iter()
3464        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3465        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3466        .collect();
3467    let queued = queued_tasks(queue)
3468        .into_iter()
3469        .filter(|t| !live.contains(&t.id))
3470        .collect();
3471    (queued, stalled, finished)
3472}
3473
3474async fn start_service(
3475    home: &Path,
3476    opts: &Opts,
3477    queue: &Queue,
3478    worktrees_root: &Path,
3479    operation: &str,
3480    cfg: Option<&Config>,
3481    busy: bool,
3482) -> Result<()> {
3483    // Fetch policy is live configuration, unlike question recovery capacity.
3484    // Reload before both cadence and eligibility, including disabled -> enabled.
3485    let fetch_cfg = if operation == "fetch" {
3486        match prepare(&opts.repo, opts) {
3487            Ok(cfg) => Some(cfg),
3488            Err(error) => {
3489                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3490                return Ok(());
3491            }
3492        }
3493    } else {
3494        None
3495    };
3496    let cfg = fetch_cfg.as_ref().or(cfg);
3497    let ticks = home.join("service-ticks");
3498    std::fs::create_dir_all(&ticks)?;
3499    let receipt = ticks.join(format!("daemon-{operation}"));
3500    let last = std::fs::read(&receipt)
3501        .ok()
3502        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3503    let interval = match operation {
3504        "disk-pressure" => 30,
3505        "cache" => CACHE_CHECK_INTERVAL_SECS,
3506        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3507        _ => opts.poll.as_secs().max(1),
3508    };
3509    let now = Timestamp::now();
3510    if !cache_check_due(last, now, interval) {
3511        return Ok(());
3512    }
3513    let key = format!("service:daemon-{operation}");
3514    if crate::worker::active(home)?
3515        .iter()
3516        .any(|job| job.key == key)
3517    {
3518        return Ok(());
3519    }
3520    let eligible = match operation {
3521        "conductor" => {
3522            let (queued, stalled, finished) = conductor_work(queue, home);
3523            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3524                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3525        }
3526        "maintenance" => Questions::at(home.join("questions"))
3527            .list()
3528            .iter()
3529            .any(|q| {
3530                q.chosen_action().is_some_and(|action| action.maintenance())
3531                    && !home
3532                        .join("choice-actions")
3533                        .join(format!("{}.json", q.id))
3534                        .exists()
3535            }),
3536        "housekeeping" => !busy && runnable(queue).is_empty(),
3537        "cache" => {
3538            !busy
3539                && !runnable(queue).is_empty()
3540                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3541        }
3542        "disk-pressure" => busy,
3543        "fetch" => {
3544            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3545        }
3546        _ => false,
3547    };
3548    if !eligible {
3549        return Ok(());
3550    }
3551    let request = ServiceWorker {
3552        opts: opts.absolute()?,
3553        queue: std::path::absolute(queue.root())?,
3554        worktrees_root: std::path::absolute(worktrees_root)?,
3555        operation: operation.to_owned(),
3556    };
3557    if let Err(error) =
3558        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3559    {
3560        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3561    }
3562    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3563    Ok(())
3564}
3565
3566/// Finite maintenance jobs survive scheduler replacement without duplicating
3567/// agent calls or cancelling an operation between its effect and receipt.
3568pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3569    let request: ServiceWorker = serde_json::from_value(payload)?;
3570    let opts = &request.opts;
3571    let queue = Queue::at(request.queue);
3572    let questions = Questions::at(home.join("questions"));
3573    match request.operation.as_str() {
3574        "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3575        "conductor" => {
3576            let path = home.join("conductor-state.json");
3577            let mut conductor = load_conductor(home)?;
3578            let (queued, stalled, finished) = conductor_work(&queue, home);
3579            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3580                && conductor.worth_a_look(&queue, &stalled, &finished)
3581            {
3582                let cfg = prepare(&opts.repo, opts)?;
3583                conductor
3584                    .maybe_run(
3585                        &cfg,
3586                        &opts.repo,
3587                        &queue,
3588                        &questions,
3589                        home,
3590                        &queued,
3591                        &stalled,
3592                        &finished,
3593                        opts.max_attempts,
3594                    )
3595                    .await;
3596                let temporary = path.with_extension("json.tmp");
3597                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3598                std::fs::rename(temporary, path)?;
3599            }
3600        }
3601        "fetch" => {
3602            let cfg = prepare(&opts.repo, opts)?;
3603            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3604                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3605                tracing::debug!("fetch origins: {outcome:?}");
3606            }
3607        }
3608        "cache" => {
3609            if task_jobs(home)?.is_empty() {
3610                let mut checked = None;
3611                maybe_prune_cache_between_runs(
3612                    &opts.repo,
3613                    opts,
3614                    home,
3615                    &Stop::new(),
3616                    &mut checked,
3617                    Timestamp::now(),
3618                )
3619                .await;
3620            }
3621        }
3622        "disk-pressure" => {
3623            if let Ok(cfg) = prepare(&opts.repo, opts) {
3624                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3625                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3626                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3627                }
3628                for current in current_work(home, Timestamp::now()) {
3629                    if let Ok(state) = RunState::load_under(&current.run, home)
3630                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3631                    {
3632                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3633                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3634                        }) {
3635                            request_task_park(
3636                                home,
3637                                &job,
3638                                crate::run::ParkCause::Interrupt {
3639                                    reason: reason.clone(),
3640                                },
3641                            )?;
3642                        }
3643                        notices::raise_in(
3644                            home,
3645                            Notice::warn(
3646                                "disk:pressure",
3647                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3648                            ),
3649                        );
3650                    }
3651                }
3652            }
3653        }
3654        "housekeeping" => {
3655            if task_jobs(home)?.is_empty() {
3656                if let Ok(cfg) = prepare(&opts.repo, opts) {
3657                    crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3658                }
3659                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3660                resweep_superseded_attempts(&queue, home);
3661                triage_held(&queue, home, opts).await;
3662            }
3663        }
3664        operation => bail!("unknown daemon service {operation}"),
3665    }
3666    Ok(())
3667}
3668
3669/// Only a different request under the same key is a dispatch handoff race.
3670/// Our own unacknowledged reservation is a startup failure, not competing work:
3671/// stop dispatch without fencing it, so an already detached child may still run.
3672fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3673    let key = format!("task:{}", request.task);
3674    let payload = serde_json::to_value(request)?;
3675    if crate::worker::active(home)?
3676        .iter()
3677        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3678    {
3679        tracing::warn!(
3680            "task {} acquired a competing worker reservation: {error:#}",
3681            crate::run::short_of(&request.task)
3682        );
3683        return Ok(());
3684    }
3685    tracing::error!("task worker startup stopped dispatch: {error:#}");
3686    notices::raise_in(
3687        home,
3688        Notice::error(
3689            "loop:worker-startup",
3690            // Startup diagnostics may contain private child-process details;
3691            // keep them in the local error/log rather than the chat or notifier.
3692            format!("Task {} worker could not be started or acknowledged. Scheduler dispatch stopped; already reserved workers may still complete. Inspect the local execution log and reservation worker.log for startup details.", request.task),
3693        ).link(Link::Task { id: request.task.clone() }),
3694    );
3695    Err(error).with_context(|| {
3696        format!(
3697            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3698            crate::run::short_of(&request.task)
3699        )
3700    })
3701}
3702
3703async fn poll(
3704    opts: &Opts,
3705    queue: &Queue,
3706    status: &Arc<Mutex<Status>>,
3707    home: &Path,
3708    worktrees_root: &Path,
3709    stop: &Stop,
3710    limits: DispatchLimits,
3711) -> Result<()> {
3712    let mut attempted = Vec::new();
3713    let mut settling_once_services = false;
3714    let interrupt_path = home.join("scheduler-interrupt.json");
3715    let mut interrupt = match std::fs::read(&interrupt_path) {
3716        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3717        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3718        Err(error) => return Err(error.into()),
3719    };
3720    let mut previous = std::collections::BTreeSet::<String>::new();
3721    while !stop.stopped() {
3722        let jobs: Vec<_> = crate::worker::active(home)?
3723            .into_iter()
3724            .filter(|job| job.kind == "task")
3725            .collect();
3726        let requests: Vec<_> = jobs
3727            .iter()
3728            .map(|job| {
3729                serde_json::from_value::<TaskWorker>(job.payload.clone())
3730                    .with_context(|| format!("read live task worker {}", job.id))
3731            })
3732            .collect::<Result<_>>()?;
3733        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3734        let owned: std::collections::BTreeSet<_> = requests
3735            .iter()
3736            .filter(|r| !r.standalone)
3737            .map(|r| r.task.clone())
3738            .collect();
3739        let current: Vec<_> = requests
3740            .iter()
3741            .zip(&jobs)
3742            .filter(|(request, _)| !request.standalone)
3743            .map(|(request, job)| Current {
3744                worker: Some(job.id.clone()),
3745                task: request.task.clone(),
3746                run: queue
3747                    .get(&request.task)
3748                    .ok()
3749                    .and_then(|task| task.runs.last().cloned())
3750                    .unwrap_or_default(),
3751            })
3752            .collect();
3753        {
3754            let mut snapshot = lock(status);
3755            snapshot.polls += 1;
3756            snapshot.completed += previous.difference(&owned).count();
3757            snapshot.current = current;
3758            snapshot.idle = owned.is_empty();
3759        }
3760        previous = owned.clone();
3761        stop.busy.store(owned.len(), Ordering::SeqCst);
3762
3763        // Slots are reconstructed from durable reservations and OS-held worker
3764        // leases, not this scheduler's lifetime or mutable task urgency.
3765        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3766        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3767        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3768        let mut permits = Vec::new();
3769        sweep_stale_claims(queue, STALE_CLAIM);
3770        reclaim_orphaned_running(queue, opts.max_attempts, &live);
3771        reclaim_abandoned_runs(home, Timestamp::now());
3772        let questions = Questions::at(home.join("questions"));
3773
3774        // Deterministic: no model, run before the conductor sees anything so
3775        // its input reflects the queue's current, already-resolved state.
3776        crate::task_chat::sweep(
3777            queue,
3778            &crate::talk::Talks::at(home.join("talks")),
3779            &questions,
3780            home,
3781        );
3782        repair_choice_offers(&questions);
3783        resolve_blockers(queue, &questions);
3784        apply_task_choice_actions(queue, &questions, home);
3785        triage::apply_answers(queue, &questions);
3786        reconcile_task_questions(queue, &questions);
3787        let talks = crate::talk::Talks::at(home.join("talks"));
3788        crate::chat_notify::sweep(queue, &talks, home);
3789        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3790        crate::chat_watch::sweep(home, &talks);
3791        let mut turns = tokio::task::JoinSet::new();
3792        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3793        // start_turns dispatches detached turns; no paid work lives in this set.
3794        while turns.join_next().await.is_some() {}
3795
3796        crate::consult::start_services(
3797            home,
3798            &opts.repo,
3799            limits.recovery_cfg.as_ref(),
3800            opts.config.as_deref(),
3801        )
3802        .await?;
3803        for operation in [
3804            "conductor",
3805            "maintenance",
3806            "housekeeping",
3807            "disk-pressure",
3808            "cache",
3809            "fetch",
3810        ] {
3811            // Once an idle --once drain starts settling services, subsequent
3812            // scans only consume their effects. An expired cadence receipt
3813            // must not start another service and keep the drain alive.
3814            if settling_once_services {
3815                break;
3816            }
3817            start_service(
3818                home,
3819                opts,
3820                queue,
3821                worktrees_root,
3822                operation,
3823                limits.recovery_cfg.as_ref(),
3824                !live.is_empty(),
3825            )
3826            .await?;
3827        }
3828        let latest = crate::worker::active(home)?;
3829        if latest.iter().any(|job| job.key == "service:daemon-cache")
3830            || latest
3831                .iter()
3832                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3833        {
3834            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3835            continue;
3836        }
3837        let candidates: Vec<Task> = runnable(queue)
3838            .into_iter()
3839            .filter(|task| !live.contains(&task.id))
3840            .filter(|task| !opts.once || !attempted.contains(&task.id))
3841            .collect();
3842        let in_flight: Vec<_> = owned.iter().cloned().collect();
3843        let prior_interrupt = std::mem::discriminant(&interrupt);
3844        interrupt = advance_interrupt_tick(
3845            limits.pause_for_interrupts,
3846            interrupt,
3847            &in_flight,
3848            &candidates,
3849        );
3850        // Same-variant transitions preserve their identities. Only an actual
3851        // transition needs a durable write, atomically before sending controls.
3852        if prior_interrupt != std::mem::discriminant(&interrupt) {
3853            let temporary = interrupt_path.with_extension("json.tmp");
3854            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3855            std::fs::rename(temporary, &interrupt_path)?;
3856        }
3857        if let Interrupt::Parking {
3858            parked,
3859            interrupt_task,
3860        } = &interrupt
3861        {
3862            for job in jobs.iter().filter(|job| {
3863                parked
3864                    .iter()
3865                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3866            }) {
3867                if crate::worker::control(home, &job.key)?.is_none() {
3868                    request_task_park(
3869                        home,
3870                        job,
3871                        crate::run::ParkCause::Interrupt {
3872                            reason: format!(
3873                                "task {} asked to run first",
3874                                crate::run::short_of(interrupt_task)
3875                            ),
3876                        },
3877                    )?;
3878                }
3879            }
3880        }
3881        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3882        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3883        let mut started = false;
3884        let mut resync = false;
3885        for candidate in candidates {
3886            if stop.stopped() {
3887                break;
3888            }
3889            let Some(DispatchClaim {
3890                task,
3891                claim,
3892                permit,
3893            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
3894            else {
3895                continue;
3896            };
3897            if crate::worker::active(home)?
3898                .iter()
3899                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3900            {
3901                drop(claim);
3902                resync = true;
3903                break;
3904            }
3905            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
3906            let request = TaskWorker {
3907                opts: opts.absolute()?,
3908                queue: std::path::absolute(queue.root())?,
3909                task: task.id.clone(),
3910                lane,
3911                standalone: false,
3912            };
3913            // Keep the claim until spawn acknowledges the worker's durable
3914            // reservation. The worker then claims and re-reads before attempt.
3915            if let Err(error) = crate::worker::spawn(
3916                home,
3917                "task",
3918                &format!("task:{}", task.id),
3919                serde_json::to_value(&request)?,
3920            )
3921            .await
3922            {
3923                task_worker_spawn_error(home, &request, error)?;
3924                drop(claim);
3925                resync = true;
3926                break;
3927            }
3928            drop(claim);
3929            permits.extend(permit);
3930            attempted.push(task.id);
3931            started = true;
3932        }
3933        if started || resync {
3934            continue;
3935        }
3936        if owned.is_empty() && opts.once {
3937            settling_once_services = true;
3938            // These finite services can own queue claims or publish answers.
3939            // A skipped claim is not an idle queue until they have finished;
3940            // scan again afterwards so their changes are actually scheduled.
3941            if crate::worker::active(home)?.iter().any(|job| {
3942                job.kind == "daemon-service"
3943                    && matches!(
3944                        job.key.as_str(),
3945                        "service:daemon-housekeeping"
3946                            | "service:daemon-conductor"
3947                            | "service:daemon-maintenance"
3948                    )
3949            }) {
3950                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3951                continue;
3952            }
3953            break;
3954        }
3955        stop.idle(if live.is_empty() {
3956            opts.poll
3957        } else {
3958            RECHECK_WHILE_BUSY.min(opts.poll)
3959        })
3960        .await;
3961    }
3962    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
3963    // every queue claim and Runner driver lease through outcome settlement.
3964    stop.busy.store(0, Ordering::SeqCst);
3965    Ok(())
3966}
3967
3968/// A maintenance pass may briefly own the same record while a worker starts.
3969/// Wait without blocking the executor or charging an agent attempt, then read
3970/// ownership again under the acquired lock. Other I/O failures still fail closed.
3971async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
3972    let busy = |error: &anyhow::Error| {
3973        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
3974            error.kind() == std::io::ErrorKind::WouldBlock
3975                || cfg!(windows) && error.raw_os_error() == Some(33)
3976        })
3977    };
3978    match crate::pr_head::owner_lock(home, id) {
3979        Ok(lock) => return Ok(lock),
3980        Err(error) if busy(&error) => {}
3981        Err(error) => return Err(error),
3982    }
3983    let wait = RunState::load_under(id, home)?
3984        .config
3985        .graph
3986        .timeout_resource_wait;
3987    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
3988}
3989
3990/// Historical successors do not revoke a still-resumable public owner. Scan
3991/// under the same lock as publication/driver claims, and fail closed on unknown
3992/// history before spending another attempt.
3993async fn public_resume_owner(
3994    home: &Path,
3995    runs: &[String],
3996    repo: &Path,
3997) -> Result<Option<RunState>> {
3998    let mut owner = None;
3999    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4000        let _lock = resume_owner_lock(home, id).await?;
4001        let state = RunState::load_under(id, home)?;
4002        if state.released()
4003            || state.retired_to.is_some()
4004            || state.pr_taken_over_by.is_some()
4005            || !crate::handover::landing_checkpoint(&state)
4006        {
4007            continue;
4008        }
4009        anyhow::ensure!(
4010            crate::git::toplevel(&state.repo).await?.canonicalize()?
4011                == crate::git::toplevel(repo).await?.canonicalize()?,
4012            "public owner repository differs; inspect run lineage"
4013        );
4014        anyhow::ensure!(
4015            owner.is_none(),
4016            "multiple retained public owners; inspect run lineage"
4017        );
4018        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4019            anyhow::bail!(reason.diagnostic(&state));
4020        }
4021        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4022        anyhow::ensure!(
4023            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4024            "public owner's driver is live or unknown; wait before retrying"
4025        );
4026        owner = Some(state);
4027    }
4028    Ok(owner)
4029}
4030
4031/// Run one claimed task to a terminal status and record the outcome.
4032///
4033/// Every transition is flushed to the queue as it happens, so the state on disk
4034/// is what actually occurred rather than what this process still intends to
4035/// write.
4036async fn attempt(
4037    opts: &Opts,
4038    queue: &Queue,
4039    status: &Arc<Mutex<Status>>,
4040    stop: &Stop,
4041    interrupt_pause: crate::graph::Pause,
4042    task: &mut Task,
4043) -> Vec<QuotaLoss> {
4044    let repo = repo_for(task, &opts.repo);
4045    tracing::info!(
4046        "task {} — {} (repo {})",
4047        task.short(),
4048        task.title,
4049        repo.display()
4050    );
4051
4052    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4053        Ok(owner) => owner,
4054        Err(e) => {
4055            task.hold_machine(Some(format!(
4056                "Cannot verify existing public owner: {e:#}; no attempt started."
4057            )));
4058            record(queue, task);
4059            return Vec::new();
4060        }
4061    };
4062    let resume_runs = public_owner
4063        .as_ref()
4064        .map(|s| vec![s.id.clone()])
4065        .unwrap_or_else(|| task.runs.clone());
4066
4067    // A stop spends no agent resources and uses the saved landing owner.
4068    // Current roster edits, missing attachments or a failed config fetch must
4069    // never turn it into a new implementation, or prevent a PR from closing.
4070    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4071        && previous
4072            .merge_decision
4073            .as_ref()
4074            .is_some_and(|decision| !decision.closed)
4075        && previous.status != RunStatus::Landing
4076        && !crate::merge_decision::resumable_hold(&previous)
4077    {
4078        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)));
4079        record(queue, task);
4080        return Vec::new();
4081    }
4082    let stop_owner = resume_runs
4083        .last()
4084        .and_then(|id| RunState::load(id).ok())
4085        .filter(|state| {
4086            crate::merge_decision::resumable_hold(state)
4087                || state.status == RunStatus::Landing
4088                    && state.land_approval.as_ref().is_some_and(|binding| {
4089                        Questions::open().get(&binding.question).is_ok_and(|q| {
4090                            q.run == state.id
4091                                && q.resolution()
4092                                    .as_deref()
4093                                    .is_some_and(crate::merge_decision::stops)
4094                        })
4095                    })
4096        });
4097    if let Some(owner) = stop_owner {
4098        let mut runner = match Runner::resume(&owner.id) {
4099            Ok(runner) => runner,
4100            Err(e) => {
4101                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4102                record(queue, task);
4103                return Vec::new();
4104            }
4105        };
4106        runner.on_pause(stop.pause());
4107        runner.watch_interrupt(interrupt_pause);
4108        let quota_before = runner.state.quota.clone();
4109        task.start(owner.id.clone());
4110        record(queue, task);
4111        lock(status).current.push(Current {
4112            worker: None,
4113            task: task.id.clone(),
4114            run: owner.id,
4115        });
4116        runner.state.next_pass_task_entry = true;
4117        let result = runner.execute().await;
4118        return finish_attempt(
4119            opts.max_attempts,
4120            queue,
4121            task,
4122            &runner.state,
4123            &quota_before,
4124            result,
4125        );
4126    }
4127
4128    if let Some(owner) = &public_owner
4129        && (task.fresh_start || !may_resume_run(owner, task))
4130    {
4131        task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. No attempt started.", owner.id)));
4132        record(queue, task);
4133        return Vec::new();
4134    }
4135
4136    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4137        && !task.fresh_start
4138        && task.review_branch.is_none()
4139        && task.pr_recovery.is_none()
4140    {
4141        // Authorization still takes the owner lock and execution lease and
4142        // rechecks liveness, retained HEAD and ownership before saving.
4143        let authorized = if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4144            let home = queue.root().parent().expect("queue has a home");
4145            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4146                Ok(()) => true,
4147                Err(error) => {
4148                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4149                    false
4150                }
4151            }
4152        } else {
4153            false
4154        };
4155        if !authorized {
4156            task.hold_machine(Some("Base synchronization remains stopped. Inspect the retained run; for movement exhaustion, explicitly use `magi run --resume <run> --recover-base`. A release without a new owner approval grants no additional rebase and starts no replacement competition.".into()));
4157            // Retain the existing stop identity when an old release reached the queue.
4158            task.base_sync_notice(&held);
4159            task.resume_override = None;
4160            record(queue, task);
4161            return Vec::new();
4162        }
4163    }
4164    let unfinished = (!task.fresh_start)
4165        .then(|| unfinished_run(&resume_runs, task.short()))
4166        .flatten()
4167        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4168    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4169    if !task.fresh_start
4170        && task.pr_recovery.is_none()
4171        && task.review_branch.is_none()
4172        && task.resume_override.is_none()
4173        && previous
4174            .as_ref()
4175            .is_some_and(|run| run.retired_to.is_some())
4176        && unfinished.is_none()
4177    {
4178        task.hold_unrequested_retry(Some("Recorded recovery authority is unavailable, no longer resumable or no longer authorized for these instructions. Inspect the retained lineage and select a recovery source explicitly; no replacement competition was started.".into()));
4179        record(queue, task);
4180        return Vec::new();
4181    }
4182
4183    let saved_recovery = previous.as_ref().filter(|run| {
4184        task.replacement.is_none()
4185            && task.pr_recovery.as_ref().is_some_and(|selected| {
4186                selected.check_task(&task.id, &task.instruction).is_ok()
4187                    && selected_starter(selected, Some(run), unfinished.as_deref())
4188                        == Starter::Resume(run.id.clone())
4189            })
4190    });
4191
4192    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4193    // failure here is the network's or the operator's, not the task's: hold
4194    // without spending an attempt, never fall back to a possibly stale copy.
4195    let explicit = match &task.overrides {
4196        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4197        Some(_) => opts.config.as_deref(),
4198        None => opts.config.as_deref(),
4199    };
4200    let (mut config, layers) = if let Some(run) = saved_recovery {
4201        // A matching resume owns its resolved configuration and evidence;
4202        // current layers and inherited overrides only configure new work.
4203        let mut saved = run.clone();
4204        if let Err(e) = saved.configure_recovery_resume() {
4205            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4206            record(queue, task);
4207            return Vec::new();
4208        }
4209        (saved.config, Vec::new())
4210    } else {
4211        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4212            Ok(loaded) => loaded,
4213            Err(e) => {
4214                let reason = format!("[config] {e:#}");
4215                record_config_failure(task, &e);
4216                task.last_error = Some(reason.clone());
4217                task.hold_machine(Some(reason));
4218                record(queue, task);
4219                return Vec::new();
4220            }
4221        };
4222        if let Err(e) = apply_options(&mut config, opts, task) {
4223            task.hold_manual(Some(format!(
4224                "[config] {e:#}; correct the merge override before releasing the task"
4225            )));
4226            record(queue, task);
4227            return Vec::new();
4228        }
4229        if let Some(selected) = &task.pr_recovery
4230            && let Err(e) = selected.configure(&mut config)
4231        {
4232            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4233            record(queue, task);
4234            return Vec::new();
4235        }
4236        (config, layers)
4237    };
4238    let config_evidence = crate::pr_recovery::ConfigEvidence {
4239        layers,
4240        overrides: task.overrides.clone(),
4241        daemon_merge: task
4242            .overrides
4243            .as_ref()
4244            .is_none_or(|o| o.inherit_daemon_options)
4245            .then(|| opts.merge.clone())
4246            .flatten(),
4247    };
4248    apply_task_implementers(&mut config, task);
4249    if let Some(replacement) = &task.replacement {
4250        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4251            old.liveness(false) == Liveness::Dead
4252                && old.merge_decision.as_ref().is_some_and(|d| {
4253                    d.closed
4254                        && d.question == replacement.question
4255                        && d.replacement_run.as_ref().is_none_or(|run| {
4256                            task.runs.last() == Some(run)
4257                                && RunState::load(run).is_ok_and(|current| {
4258                                    current.replaces.as_ref().is_some_and(|pin| {
4259                                        pin.question == replacement.question
4260                                            && pin.agent == replacement.agent
4261                                    })
4262                                })
4263                        })
4264                })
4265        });
4266        if !safe {
4267            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()));
4268            record(queue, task);
4269            return Vec::new();
4270        }
4271        match config.agent(&replacement.agent) {
4272            Ok(agent) if crate::agent::installed(agent) => {}
4273            _ => {
4274                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)));
4275                record(queue, task);
4276                return Vec::new();
4277            }
4278        }
4279        config.graph.implementers = 1;
4280        config.graph.land_approval = true;
4281        config.merge.mode = MergeMode::Pr;
4282        config.graph.selected_implementer = Some(replacement.agent.clone());
4283    }
4284    let p = phrases(&config.graph.language);
4285    let start_failed = p.could_not_start;
4286    // Resolve once for both admission and settlement. The inputs are the
4287    // task's explicit sources (never prose), plus an explicit review source's
4288    // current head; review-only runs may rebase later, and neither fact can
4289    // refund a failed automatic generation.
4290    if let Ok(base) =
4291        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4292            .await
4293        && let Ok(head) =
4294            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4295    {
4296        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4297        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4298            let source = crate::git::rev_parse(&repo, branch)
4299                .await
4300                .unwrap_or_default();
4301            inputs.push_str(&format!(";review:{branch}:{source}"));
4302        }
4303        if let Some(reason) = task.recovery_exhausted(
4304            &head,
4305            &inputs,
4306            task.attempt_limit
4307                .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4308        ) {
4309            task.hold_unrequested_retry(Some(reason));
4310            record(queue, task);
4311            return Vec::new();
4312        }
4313        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4314    }
4315
4316    // The free-space gate, checked *before* anything is minted: a task that
4317    // waits out a full disk costs nothing yet, and must not spend an attempt
4318    // or start a run the machine cannot finish. Held tasks stay in the list
4319    // for the human to see, and `magi task release` re-queues them when space
4320    // comes back - the same recovery as any other hold. A volume whose free
4321    // space cannot be measured closes the gate too: starting a run blind on a
4322    // disk that may be full is how the machine ends up with 6.7 GB free.
4323    if let Some(reason) = disk_gate(&repo, &config) {
4324        task.notice_cause("disk-space", None, None);
4325        task.last_error = Some(reason.clone());
4326        task.hold_machine(Some(reason.clone()));
4327        record(queue, task);
4328        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4329        // Stable wording - the free-space figures live in the task's hold
4330        // reason, and changing numbers would relight the bell every poll.
4331        notices::raise(
4332            Notice::warn(
4333                &format!("disk:{}", repo.display()),
4334                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4335            )
4336            .link(Link::Task {
4337                id: task.id.clone(),
4338            }),
4339        );
4340        return Vec::new();
4341    }
4342
4343    // A resumable run of this task is carried on, never re-competed. The
4344    // candidates are built and paid for, and a fresh competition races a
4345    // second implementation against them.
4346    //
4347    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4348    // started 3cbf on the same task a moment later, duplicating two and a
4349    // half hours of agent work. Then b25f stalled on a judge that timed out
4350    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4351    // was to blame for - and 4043 started **one second** later, buying three
4352    // fresh implementations to reach the same panel. `RunStatus::resumable`
4353    // rather than `!done()` is what catches the second case: a stall is
4354    // terminal, and its cheap recovery re-asks only the absent seats.
4355    //
4356    // A load failure is warned about rather than silently read as "not
4357    // resumable": the alternative is exactly what let a schema mismatch on
4358    // run `eba2` fall through to a full re-competition with nobody told why.
4359    // `crate::conduct` is what actually offers a better answer than
4360    // `Runner::start` here (see `Recovery::Review`), once this task's next
4361    // failure shows it up as `held`/`failed` with the run state unreadable.
4362    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4363    // branch survived, and this reopens exactly that branch as a
4364    // review-only pass rather than resuming or competing again. Consumed
4365    // (cleared) here whichever way this goes, so it never outlives this one
4366    // attempt - see `queue::Task::review_branch`.
4367    let review_branch = take_review_branch(task, previous.as_ref());
4368    let branch_exists = match &review_branch {
4369        Some(branch) => crate::git::branch_exists(&repo, branch)
4370            .await
4371            .unwrap_or(false),
4372        None => false,
4373    };
4374    // An explicit `magi review <branch>` is reviewed whatever happens to the
4375    // branch unless an explicit implementer change requires fresh work. An
4376    // unfinished run of the same task still wins, so a retry resumes.
4377    let proposed = review_retry_starter(
4378        task,
4379        previous.as_ref(),
4380        review_branch.as_deref(),
4381        branch_exists,
4382        unfinished.as_deref(),
4383    );
4384    let retry_selected = task.replacement.is_some()
4385        && task.resumption.is_some()
4386        && !task.fresh_start
4387        && previous.as_ref().is_some_and(|run| {
4388            run.replaces.is_some()
4389                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4390                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4391        });
4392    let stop_pin = task
4393        .resume_override
4394        .as_ref()
4395        .filter(|pin| {
4396            Questions::open().get(&pin.question_id).is_ok_and(|q| {
4397                q.node == land::APPROVAL_NODE
4398                    && q.resolution()
4399                        .as_deref()
4400                        .is_some_and(crate::merge_decision::stops)
4401            })
4402        })
4403        .and_then(|pin| pin.pinned_run.clone());
4404    let starter = if let Some(owner) = &public_owner {
4405        Starter::Resume(owner.id.clone())
4406    } else if let Some(run) = stop_pin {
4407        // Stop actions resume their exact owner even after seat-count edits;
4408        // they must never fall through to implementation or a takeover.
4409        Starter::Resume(run)
4410    } else if retry_selected {
4411        Starter::Resume(previous.as_ref().unwrap().id.clone())
4412    } else if let Some(selected) = &task.pr_recovery {
4413        if selected.check_task(&task.id, &task.instruction).is_ok() {
4414            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4415        } else {
4416            Starter::Review(selected.branch.clone())
4417        }
4418    } else {
4419        starter_with_implementers(task, previous.as_ref(), proposed)
4420    };
4421    // An explicit resume pin must never degrade into a new competition or
4422    // takeover, including when its run stops being eligible after the answer.
4423    if let Some(pin) = &task.resume_override
4424        && let Some(run) = &pin.pinned_run
4425        && starter != Starter::Resume(run.clone())
4426    {
4427        let run = run.clone();
4428        task.notice_cause("resume-owner", Some(&run), None);
4429        task.hold_machine(Some(format!(
4430            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4431            task.id
4432        )));
4433        record(queue, task);
4434        return Vec::new();
4435    }
4436    if task.replacement.is_some()
4437        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4438        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4439    {
4440        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()));
4441        record(queue, task);
4442        return Vec::new();
4443    }
4444    if let Some(reason) = retained_attempt_hold(
4445        task,
4446        &starter,
4447        config.disk.retained_attempt_limit,
4448        RunState::load,
4449    ) {
4450        // The review choice was consumed above. Preserve it across this hold
4451        // so a later release cannot silently become a fresh implementation.
4452        if let Starter::Review(branch) = &starter {
4453            task.review_branch = Some(branch.clone());
4454        }
4455        task.hold_unrequested_retry(Some(reason));
4456        record(queue, task);
4457        return Vec::new();
4458    }
4459    // Absolute paths of the files the task was filed with, re-read from the
4460    // task now so a file attached while it was held reaches a resumed run
4461    // too. A stored name whose file has gone is an error before any agent is
4462    // paid for, never a silent omission the implementer cannot notice.
4463    let attachments = match task_attachments(queue, task) {
4464        Ok(a) => a,
4465        Err(e) => {
4466            task.attempts += 1;
4467            task.fail_startup_target(
4468                "startup-attachments",
4469                e.name.clone(),
4470                format!("{start_failed}{e:#}"),
4471                opts.max_attempts,
4472            );
4473            record(queue, task);
4474            return Vec::new();
4475        }
4476    };
4477    let startup_pause = stop.pause();
4478    let startup_interrupt = interrupt_pause.clone();
4479    let wait = crate::repo_lock::WaitPolicy::new(
4480        Duration::from_secs(config.graph.timeout_resource_wait),
4481        move || startup_pause.parked() || startup_interrupt.parked(),
4482    );
4483    // Startup includes review takeover and recovery. Do not embed its large
4484    // future in both the wait scope and the surrounding attempt stack frame.
4485    let started = wait.scope(Box::pin(async { match &starter {
4486        Starter::Review(_) if task.pr_recovery.is_some() => {
4487            let selected = task.pr_recovery.clone().expect("selected recovery");
4488            match selected.check_task(&task.id, &task.instruction) {
4489                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4490                    .await
4491                    .map(|mut r| {
4492                        r.state.attachments = attachments.clone();
4493                        r
4494                    }),
4495                Err(e) => Err(e),
4496            }
4497        }
4498        Starter::Review(branch) => {
4499            tracing::info!(
4500                "task {} reopens `{branch}` as a review-only pass",
4501                task.short()
4502            );
4503            // Every earlier attempt is superseded by the one being minted
4504            // now, so a branch one of them still holds may be taken over.
4505            let takeover = crate::handover::Takeover {
4506                earlier: task.earlier_attempts().to_vec(),
4507                home: crate::run::home(),
4508                choice: take_divergence_answer(branch, &config.merge.remote, task),
4509                task_instruction: Some(instruction_for(task)),
4510            };
4511            Runner::review_taking_over(
4512                &repo,
4513                branch,
4514                config,
4515                Some(takeover),
4516                crate::run::Origin::queue(&task.id),
4517            )
4518            .await
4519        }
4520        Starter::Resume(id) => {
4521            tracing::info!("resuming run {id} rather than competing again");
4522            Runner::resume(id).and_then(|mut r| {
4523                if retry_selected {
4524                    // The explicit queue release retries this same pinned
4525                    // implementation, preserving the attempt and worktrees.
4526                    for candidate in &mut r.state.candidates {
4527                        candidate.failed = None;
4528                        candidate.empty = false;
4529                        candidate.commits = 0;
4530                    }
4531                    r.state.status = RunStatus::Implementing;
4532                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4533                }
4534                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4535                    r.state.sources = task.sources.clone();
4536                }
4537                if r.state.prep_failure.is_some() {
4538                    let approval = task
4539                        .resumption
4540                        .as_ref()
4541                        .context("preparation retry requires an explicit task release")?;
4542                    r.retry_preparation(approval.at)?;
4543                }
4544                if let Some(instruction) =
4545                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4546                {
4547                    r.state.instruction = instruction;
4548                }
4549                r.state.attachments = attachments.clone();
4550                if task.replacement.is_some() {
4551                    r.state.config.merge.mode = MergeMode::Pr;
4552                    r.state.config.graph.land_approval = true;
4553                }
4554                // Replacements publish a new PR and ask again. Selected PR
4555                // recoveries keep their saved disposition; ordinary runs can
4556                // retain the task's merge override.
4557                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4558                    .overrides
4559                    .as_ref()
4560                    .and_then(|o| o.merge.as_deref())
4561                    .and_then(|m| merge_mode(m).ok())
4562                {
4563                    r.state.config.merge.mode = mode;
4564                }
4565                Ok(r)
4566            })
4567        }
4568        Starter::Start => {
4569            if let Some(branch) = &review_branch {
4570                tracing::warn!(
4571                    "conductor chose review for task {} but branch `{branch}` no longer \
4572                     exists; requeuing as a fresh competition instead",
4573                    task.short()
4574                );
4575            }
4576            let instruction = prepare_instruction(&starter, None, task)
4577                .unwrap_or_else(|| task.instruction.clone());
4578            Runner::start_naming(
4579                &repo,
4580                instruction,
4581                &task.title,
4582                config,
4583                crate::run::Origin::queue(&task.id),
4584            )
4585            .await
4586            .map(|mut r| {
4587                r.state.attachments = attachments.clone();
4588                r.state.sources = task.sources.clone();
4589                r
4590            })
4591        }
4592    }})).await;
4593    let mut runner = match started {
4594        Ok(r) => r,
4595        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4596            task.last_error = Some(e.to_string());
4597            if stop.parking() || interrupt_pause.parked() {
4598                let attempts = task.attempts;
4599                task.park(e.to_string());
4600                // Startup has not spent an attempt to refund.
4601                task.attempts = attempts;
4602            } else {
4603                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4604            }
4605            record(queue, task);
4606            return Vec::new();
4607        }
4608        // A branch an earlier attempt still holds and magi will not release
4609        // by itself is the operator's call, not a failed attempt: hold the
4610        // task with the reason, spend nothing, and say so on the bell.
4611        Err(e) if task.pr_recovery.is_some() => {
4612            task.startup_notice_cause("startup-public-head");
4613            task.attempts += 1;
4614            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
4615                task.link_run(&partial.run);
4616                task.record_pass(&partial.run, 0, task.attempts, None);
4617            }
4618            task.last_error = Some(format!("{start_failed}{e:#}"));
4619            task.hold_unrequested_retry(Some(format!(
4620                "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."
4621            )));
4622            record(queue, task);
4623            return Vec::new();
4624        }
4625        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4626            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4627                Some(r) => (p.handover_refused)(r),
4628                None => format!("{e:#}"),
4629            };
4630            task.startup_notice_cause("startup-handover");
4631            let reason = format!("{start_failed}{detail}");
4632            task.last_error = Some(reason.clone());
4633            // Consumed above by `take`; keep it so the released task retries
4634            // as a review of this same branch.
4635            let branch = match &starter {
4636                Starter::Review(branch) => Some(branch.clone()),
4637                _ => None,
4638            };
4639            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4640            // one page; the guidance rides in the reason, fixed per state so a
4641            // re-put never changes the wording and relights it.
4642            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4643            record(queue, task);
4644            tracing::warn!(
4645                "holding {} for a branch it cannot take over: {e:#}",
4646                task.short()
4647            );
4648            return Vec::new();
4649        }
4650        // A branch that differs between here and the remote in ways magi
4651        // cannot prove are the same change is a decision for the owner, not a
4652        // failed attempt: ask with both sides laid out, spend no attempt, and
4653        // let the answer requeue the task.
4654        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4655            let d = e
4656                .downcast_ref::<crate::reconcile::Diverged>()
4657                .expect("checked by the guard");
4658            let mut q = ask::Question::new(
4659                task.id.clone(),
4660                crate::reconcile::NODE.to_owned(),
4661                crate::reconcile::SEAT.to_owned(),
4662                d.summary(),
4663                d.detail(),
4664                d.choices(),
4665            );
4666            match Questions::open().put(&mut q) {
4667                Ok(()) => {
4668                    task.last_error = Some(format!("{e:#}"));
4669                    // Consumed above by `take`; the answer has to reach a review
4670                    // of this same branch, so keep pointing the task at it.
4671                    task.review_branch = Some(d.branch.clone());
4672                    task.review_instruction = Some(task.instruction.clone());
4673                    task.block(vec![q.id.clone()], Some(d.summary()));
4674                }
4675                Err(put) => {
4676                    tracing::warn!("could not file the divergence question: {put:#}");
4677                    task.attempts += 1;
4678                    task.fail_startup(
4679                        "startup-question-store",
4680                        format!("{start_failed}{e:#}"),
4681                        opts.max_attempts,
4682                    );
4683                }
4684            }
4685            record(queue, task);
4686            return Vec::new();
4687        }
4688        Err(e) => {
4689            // The answer was stale and nothing was applied: keep pointing at
4690            // the branch so the next attempt asks again against its new tips.
4691            // Nothing went wrong with the task, so no attempt is spent: a
4692            // budget one short of its limit must not hold it instead of
4693            // letting the question be asked again.
4694            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4695                && let Starter::Review(branch) = &starter
4696            {
4697                task.review_branch = Some(branch.clone());
4698                task.review_instruction = Some(task.instruction.clone());
4699                task.last_error = Some(format!("{start_failed}{e:#}"));
4700                task.status = crate::queue::TaskStatus::Failed;
4701                record(queue, task);
4702                return Vec::new();
4703            }
4704            task.attempts += 1;
4705            task.last_error = Some(format!("{start_failed}{e:#}"));
4706            task.startup_notice_cause("startup-source");
4707            task.hold_unrequested_retry(Some(format!(
4708                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4709            )));
4710            record(queue, task);
4711            return Vec::new();
4712        }
4713    };
4714    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4715        runner.state.recovery_config = Some(config_evidence);
4716    }
4717    if let Some(replacement) = &task.replacement {
4718        if matches!(starter, Starter::Start) {
4719            runner.state.instruction.push_str(&format!(
4720                "\n\n# Replacement review context\n{}",
4721                replacement.context
4722            ));
4723        }
4724        runner.state.replaces = Some(replacement.clone());
4725        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4726        if let Ok(mut old) = RunState::load(&replacement.run)
4727            && let Some(d) = &mut old.merge_decision
4728        {
4729            d.replacement_run = Some(runner.state.id.clone());
4730            old.event(
4731                "replacement",
4732                format!(
4733                    "replacement run {} owns the next attempt; old PR remains closed",
4734                    runner.state.id
4735                ),
4736            );
4737            if let Err(e) = old.save() {
4738                task.hold_manual(Some(format!(
4739                    "Could not link replacement history: {e}; no agents dispatched"
4740                )));
4741                record(queue, task);
4742                return Vec::new();
4743            }
4744        }
4745    }
4746    runner.state.task_instruction = Some(task.instruction.clone());
4747    // The follow-up depth is fixed now, while the task certainly exists:
4748    // deleting it later must not reset the cap (`crate::followup`).
4749    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4750    if runner.state.origin_chat.is_none() {
4751        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4752    }
4753    // A stop that means "park" reaches the graph through this handle.
4754    runner.on_pause(stop.pause());
4755    // `poll`'s interrupt scheduler reaches this one run - and no other -
4756    // through this handle. See `Pause`'s own doc for why these are never
4757    // the same one.
4758    runner.watch_interrupt(interrupt_pause);
4759
4760    // `start` has minted the run, so the task can now point at it. Persisting
4761    // `Running` before `execute` is what makes a crash mid-run legible.
4762    let run = runner.state.id.clone();
4763    task.start(run.clone());
4764    record(queue, task);
4765    lock(status).current.push(Current {
4766        worker: None,
4767        task: task.id.clone(),
4768        run,
4769    });
4770
4771    // `RunState::quota` is the run's whole history across every resume, so
4772    // only what this execution added may arm the cooldown or earn a refund.
4773    let quota_before = runner.state.quota.clone();
4774    runner.state.next_pass_task_entry = true;
4775    let result = runner.execute().await;
4776    finish_attempt(
4777        opts.max_attempts,
4778        queue,
4779        task,
4780        &runner.state,
4781        &quota_before,
4782        result,
4783    )
4784}
4785
4786/// Settle `task` after its run executed: the verdict, the diagnosis, the
4787/// supersession of earlier attempts and the save. Shared by the loop and by
4788/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4789/// Returns the quota losses this execution added to the run.
4790pub fn finish_attempt(
4791    max_attempts: usize,
4792    queue: &Queue,
4793    task: &mut Task,
4794    state: &RunState,
4795    quota_before: &[QuotaLoss],
4796    result: Result<()>,
4797) -> Vec<QuotaLoss> {
4798    let detail = match result {
4799        Ok(()) => describe(state),
4800        Err(e) => format!("{e:#}"),
4801    };
4802    let fresh = losses_this_attempt(quota_before, &state.quota);
4803    let verdict = Verdict {
4804        status: state.status,
4805        // A run that opened a pull request handed its work over, whatever the
4806        // gate then decided about merging it.
4807        left_pr: state.pr.is_some(),
4808        // Only a rate limit earns the task its attempt back - and only one
4809        // suffered now: a refund justified by a previous session's loss is
4810        // the same mistake as re-arming the cooldown from it. A stalled run
4811        // resumed without hitting quota again therefore spends its attempt,
4812        // like any other failure of the task's own.
4813        quota_hit: !fresh.is_empty(),
4814        // A run that parked was asked to stop; that is not a failure and must
4815        // not spend an attempt, or replacing the binary a few times would
4816        // exhaust a task's budget without an agent ever misbehaving.
4817        parked: state.parked,
4818        // A quota loss that left nothing viable is the same machine fact as a
4819        // `Stalled` quota loss; see `settle`'s doc table.
4820        no_viable_candidates: state.viable().is_empty(),
4821    };
4822    if let Some(replacement) = &state.replaces
4823        && let Some(pr) = &state.pr
4824        && let Ok(mut old) = RunState::load(&replacement.run)
4825        && let Some(d) = &mut old.merge_decision
4826    {
4827        d.replacement_pr = Some(pr.url.clone());
4828        let _ = old.save();
4829    }
4830    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4831    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4832        task.hold_unrequested_retry(Some(format!(
4833            "Candidate setup failed: {detail}. Correct the explicit sources with `magi task sources {}` (README, \"Use\": implementation imports), or select a complete implementation with `magi task recover-pr`, then explicitly release the task.",
4834            task.short()
4835        )));
4836    }
4837    if task.status == TaskStatus::Done {
4838        supersede_prior_runs(task, &crate::run::home());
4839    }
4840    record(queue, task);
4841    tracing::info!(
4842        "task {} is {} after run {} ({})",
4843        task.short(),
4844        task.status.as_str(),
4845        state.short(),
4846        label(state.status)
4847    );
4848    fresh
4849}
4850
4851/// A task a hand-started run leaves runnable (failed with attempts to spare,
4852/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4853/// later must not spend agent calls on it. `magi task release` retries.
4854pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4855    // Parked work (including legacy Failed records with a parked run) is a
4856    // checkpoint or owner handoff, not an unrequested retry.
4857    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4858        && !awaiting_resume_with(task, RunState::load)
4859        // A run parked on the owner's word about a withheld PR title/body
4860        // resumes via `land_resume_state`, including review-only tasks that
4861        // `awaiting_resume_with` does not consider.
4862        && withheld_text_wait(task).is_none()
4863        && !(task.fresh_start && task.replacement.is_some())
4864    {
4865        let why = task.last_error.clone().map_or_else(
4866            || "the run did not finish".to_owned(),
4867            |e| format!("the run did not finish: {e}"),
4868        );
4869        task.hold_unrequested_retry(Some(format!(
4870            "{why}. It was started by hand, so it is not retried \
4871             automatically; `magi task release` retries it."
4872        )));
4873        record(queue, task);
4874    }
4875}
4876
4877/// Whether an attempt at a task whose newest run is `run` would resume that
4878/// run rather than start a fresh competition. `magi run --resume` hands a run
4879/// to a live loop only when this holds.
4880#[must_use]
4881pub fn loop_would_resume(run: &str) -> bool {
4882    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4883}
4884
4885/// A loop in another process that is alive right now: a fresh heartbeat in
4886/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4887/// carries the pid it published (`None` inside when it published none - a
4888/// fresh heartbeat is still evidence of a live loop).
4889///
4890/// The one judgement of "is somebody else serving this queue", shared by the
4891/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4892/// deciding whether to hand a task to the loop. A claim file proves nothing
4893/// here: whether a claim succeeds says nothing about whether its owner lives.
4894#[must_use]
4895pub fn foreign_loop(
4896    reading: Option<&Reading>,
4897    now: Timestamp,
4898    own_pid: u32,
4899) -> Option<Option<u32>> {
4900    let reading = reading.filter(|r| r.running(now))?;
4901    match reading.pid {
4902        Some(pid) if pid == own_pid => None,
4903        pid => Some(pid),
4904    }
4905}
4906
4907fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4908    reading.worker_protocol != Some(1)
4909        && (foreign_loop(Some(reading), now, own_pid).is_some()
4910            || reading
4911                .pid
4912                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4913}
4914
4915/// Low-level claimed-task execution shared by the detached standalone worker
4916/// and focused lifecycle fixtures. The caller must retain the queue claim for
4917/// this entire call. CLI callers transfer ownership through
4918/// [`run_detached_claimed`] instead of executing inside their own runtime.
4919///
4920/// The one deliberate difference from the loop: a task the attempt leaves
4921/// runnable (failed with attempts to spare, or requeued) is **held** instead.
4922/// Nobody asked for a retry, and a daemon starting later must not spend agent
4923/// calls re-running a hand-started task behind the operator's back;
4924/// `magi task release` is the explicit retry.
4925pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4926    run_claimed_until(opts, queue, task, &Stop::new()).await;
4927}
4928
4929async fn run_claimed_until(
4930    opts: &Opts,
4931    queue: &Queue,
4932    task: &mut Task,
4933    stop: &Stop,
4934) -> Vec<QuotaLoss> {
4935    let status = Arc::new(Mutex::new(Status::new()));
4936    // An attempt embeds startup and graph futures. Keep it off the standalone
4937    // caller's stack, on both the initial execution and withheld-text resume.
4938    let mut quota = Box::pin(attempt(
4939        opts,
4940        queue,
4941        &status,
4942        stop,
4943        crate::graph::Pause::new(),
4944        task,
4945    ))
4946    .await;
4947    // A run parked on the owner's word about a withheld PR title/body has no
4948    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
4949    // here with the claim still held, and resume once the question is settled
4950    // (answered, or abandoned at its deadline -> the neutral text).
4951    // A rejected reply files one more question (the gate asks at most twice),
4952    // so after a resume the run may be waiting again: keep going, with a fresh
4953    // limit for the new question. `resumes` bounds it even if a resume parks
4954    // without asking anything new.
4955    let mut resumes = 0;
4956    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
4957        let Some(timeout) = withheld_text_wait(task) else {
4958            break;
4959        };
4960        eprintln!(
4961            "waiting for the owner's answer on a withheld pull request text \
4962             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4963        );
4964        // The deadline abandons the question itself; the extra margin only
4965        // covers an abandon that could not be saved.
4966        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4967        let ready = loop {
4968            match land_resume_state(task) {
4969                LandResume::StillWaiting
4970                    if !stop.parking() && std::time::Instant::now() < limit =>
4971                {
4972                    tokio::time::sleep(WITHHELD_POLL).await;
4973                }
4974                LandResume::Ready => break true,
4975                _ => break false,
4976            }
4977        };
4978        if !ready || stop.parking() {
4979            break;
4980        }
4981        resumes += 1;
4982        quota.extend(
4983            Box::pin(attempt(
4984                opts,
4985                queue,
4986                &status,
4987                stop,
4988                crate::graph::Pause::new(),
4989                task,
4990            ))
4991            .await,
4992        );
4993    }
4994    hold_if_runnable(queue, task);
4995    quota
4996}
4997
4998/// Resumes an in-process run makes for withheld-text questions: the gate asks
4999/// at most twice, plus one for a resume that asks nothing new.
5000const MAX_WITHHELD_RESUMES: u32 = 3;
5001
5002/// How often an in-process run rechecks its withheld-text question.
5003const WITHHELD_POLL: Duration = Duration::from_secs(15);
5004
5005/// The `answer_timeout` (seconds) of the task's last run when that run is
5006/// parked on an unresolved withheld-text question; `None` otherwise.
5007fn withheld_text_wait(task: &Task) -> Option<u64> {
5008    let id = task.runs.last()?;
5009    let s = RunState::load(id).ok()?;
5010    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5011        .then_some(s.config.graph.answer_timeout)
5012}
5013
5014/// The quota losses `after` holds that `before` did not: what one execution
5015/// suffered, as opposed to the run's history.
5016///
5017/// Compared by value rather than by length or position because
5018/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5019/// the vector can shrink and shift under a resume. A retried seat that hits
5020/// quota again is a `push` with a new `at`, so it shows up as new here.
5021/// `reclaim` deliberately keeps reading the whole history: after a crash there
5022/// is no attempt boundary to diff against.
5023fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5024    after
5025        .iter()
5026        .filter(|q| !before.contains(q))
5027        .cloned()
5028        .collect()
5029}
5030
5031/// When the loop-wide quota cooldown should end, given this attempt's losses;
5032/// `None` when there were none. Reset-hint parsing and the cap live here.
5033fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5034    if quota.is_empty() {
5035        return None;
5036    }
5037    let with_hint = quota.iter().find(|q| q.reset.is_some());
5038    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5039    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5040    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5041    Some(
5042        now.checked_add(jiff::SignedDuration::from_secs(secs))
5043            .unwrap_or(Timestamp::MAX),
5044    )
5045}
5046
5047/// An explicit task count must agree with a run before any resume.
5048fn implementers_match(task: &Task, state: &RunState) -> bool {
5049    task.replacement.as_ref().map_or_else(
5050        || {
5051            task.implementers()
5052                .is_none_or(|n| n == state.config.graph.implementers)
5053        },
5054        |replacement| {
5055            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5056                && state.config.graph.implementers == 1
5057        },
5058    )
5059}
5060
5061/// Never resume or take over candidate work built for a different seat count.
5062fn starter_with_implementers(
5063    task: &Task,
5064    previous: Option<&RunState>,
5065    proposed: Starter,
5066) -> Starter {
5067    if previous.is_some_and(|s| !implementers_match(task, s)) {
5068        task.review_of
5069            .as_ref()
5070            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5071    } else {
5072        proposed
5073    }
5074}
5075
5076/// Apply this task's explicit count to the new attempt, without changing defaults.
5077fn apply_task_implementers(config: &mut Config, task: &Task) {
5078    if let Some(n) = task.implementers() {
5079        config.graph.implementers = n;
5080    }
5081}
5082
5083/// [`prepare`] for one task: its own `--config` and command-line overrides
5084/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5085/// over the loop's, so handing a hand-started task to a daemon changes nothing
5086/// about what it does.
5087#[cfg(test)]
5088fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5089    let explicit = match &task.overrides {
5090        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5091        _ => opts.config.as_deref(),
5092    };
5093    let (mut config, _) = Config::discover(repo, explicit)?;
5094    apply_options(&mut config, opts, task)?;
5095    Ok(config)
5096}
5097
5098fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5099    if task
5100        .overrides
5101        .as_ref()
5102        .is_none_or(|o| o.inherit_daemon_options)
5103        && let Some(mode) = opts.merge.as_deref()
5104    {
5105        config.merge.mode = merge_mode(mode)?;
5106    }
5107    if let Some(o) = &task.overrides {
5108        o.apply(config);
5109    }
5110    Ok(())
5111}
5112
5113/// Load the config for a task's repository, with the merge override applied.
5114fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5115    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5116    if let Some(mode) = &opts.merge {
5117        config.merge.mode = merge_mode(mode)?;
5118    }
5119    Ok(config)
5120}
5121
5122/// Prune the shared build cache at a between-runs boundary. The detached cache
5123/// service checks authoritative task jobs first; dispatch waits for that finite
5124/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5125/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5126async fn maybe_prune_cache_between_runs(
5127    repo: &Path,
5128    opts: &Opts,
5129    home: &Path,
5130    stop: &Stop,
5131    last_checked: &mut Option<Timestamp>,
5132    now: Timestamp,
5133) {
5134    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5135        return;
5136    }
5137    *last_checked = Some(now);
5138    let cfg = match prepare(repo, opts) {
5139        Ok(cfg) => cfg,
5140        Err(e) => {
5141            tracing::warn!("cache check: no config: {e:#}");
5142            return;
5143        }
5144    };
5145    match clean::prune_cache_if_over_limit(&cfg, home) {
5146        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5147            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5148            pruned.files,
5149            pruned.freed
5150        ),
5151        Ok(_) => {}
5152        Err(e) => {
5153            tracing::warn!("housekeep: prune cache: {e:#}");
5154            notices::raise_in(
5155                home,
5156                Notice::warn(
5157                    "housekeep:cache",
5158                    format!(
5159                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5160                        e.to_string()
5161                            .lines()
5162                            .next()
5163                            .unwrap_or("unknown cleanup error")
5164                    ),
5165                ),
5166            );
5167        }
5168    }
5169}
5170
5171/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5172/// now, given when it last did (if ever). Pure, so the cadence is asserted
5173/// directly rather than by waiting out real minutes in a test.
5174fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5175    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5176}
5177
5178/// The disk janitor, with its housekeeping logged rather than fatal.
5179///
5180/// Called only at the loop's idle points, for the reason the caller documents:
5181/// a prune racing a live compile would delete files mid-build. The config is
5182/// re-read on every call because the repository that just ran may not be the
5183/// daemon's own default, and the cache directory is a repository fact.
5184///
5185/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5186/// and [`crate::run::default_worktree_root`] read here, for the same reason
5187/// [`drive`] takes its queue and status file rather than resolving them: a
5188/// test driving the loop must not reach through to the operator's real home
5189/// or worktree bay just because the janitor runs on every idle tick.
5190/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5191/// to get wrong silently - a test's `home` was already isolated, but nothing
5192/// exercised the parameter next to it, so a real worktree bay stayed wired in
5193/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5194/// it for real, every test in this file that drives the loop at all started
5195/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5196async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5197    let cfg = match prepare(repo, opts) {
5198        Ok(cfg) => cfg,
5199        Err(e) => {
5200            tracing::warn!("housekeep: no config: {e:#}");
5201            return;
5202        }
5203    };
5204    // A run's own worktree lives under `config.graph.worktree_root` when the
5205    // repository sets one - the same precedence `RunState::worktree_root`
5206    // uses - and `worktrees_root` only stands in for the *default* an
5207    // unconfigured repository resolves to (see this function's own
5208    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5209    // that always swept the default regardless of this override would never
5210    // see, and so never reclaim, a single worktree for a repository that
5211    // relocated them elsewhere.
5212    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5213    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5214    // Reported whenever there is anything to say, not only when `folded > 0`:
5215    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5216    // folded, on every single pass, for months - a report gated on `folded`
5217    // would have stayed silent through every one of them.
5218    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5219        let mut extra = Vec::new();
5220        if out.unreadable > 0 {
5221            extra.push(format!("{} unreadable", out.unreadable));
5222        }
5223        if out.orphaned_worktrees > 0 {
5224            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5225        }
5226        let detail = if extra.is_empty() {
5227            String::new()
5228        } else {
5229            format!(" ({})", extra.join(", "))
5230        };
5231        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5232    }
5233    if out.external_merges_recorded > 0 {
5234        tracing::info!(
5235            "housekeep: recorded {} run(s) as merged externally",
5236            out.external_merges_recorded
5237        );
5238    }
5239    if out.stale_pr_states_repaired > 0 {
5240        tracing::info!(
5241            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5242            out.stale_pr_states_repaired
5243        );
5244    }
5245    if out.cache_files > 0 {
5246        tracing::info!(
5247            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5248            out.cache_files,
5249            out.cache_freed
5250        );
5251    }
5252    if out.questions_abandoned > 0 {
5253        tracing::info!(
5254            "housekeep: abandoned {} question(s) left open by a finished run",
5255            out.questions_abandoned
5256        );
5257    }
5258}
5259
5260/// Run [`triage::run_once`] and log whatever it did, the same "only when
5261/// there is something to say" rule [`janitor`] follows for its own report.
5262///
5263/// Called at the same idle points as [`janitor`] - once per full poll
5264/// interval, never mid-attempt - for the same reason: it is not liveness
5265/// critical, and a task's own `hold_reason` string is the one thing this
5266/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5267/// tick for no benefit.
5268async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5269    let questions = Questions::at(home.join("questions"));
5270    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5271    if report.is_empty() {
5272        return;
5273    }
5274    if !report.quarantined.is_empty() {
5275        tracing::info!(
5276            "triage: held {} blocked task(s) whose blocked-on task or \
5277             question no longer exists: {}",
5278            report.quarantined.len(),
5279            report.quarantined.join(", ")
5280        );
5281    }
5282    if !report.resumed.is_empty() {
5283        tracing::info!(
5284            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5285            report.resumed.len(),
5286            report.resumed.join(", ")
5287        );
5288    }
5289    if !report.asked.is_empty() {
5290        tracing::info!(
5291            "triage: asked about {} held task(s): {}",
5292            report.asked.len(),
5293            report.asked.join(", ")
5294        );
5295    }
5296    if !report.answered.is_empty() {
5297        tracing::info!(
5298            "triage: applied {} operator answer(s): {}",
5299            report.answered.len(),
5300            report.answered.join(", ")
5301        );
5302    }
5303}
5304
5305/// The free-space gate: what stands between this task and a new run, if
5306/// anything. `Some(reason)` holds the task; `None` lets it start.
5307///
5308/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5309/// the operator opted out. A measurement failure is a gate, not a pass: both
5310/// sides of "cannot tell" are served by not starting.
5311pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5312    disk_gate_with(repo, config, crate::disk::free_bytes)
5313}
5314
5315/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5316/// test can assert the exact wiring `attempt` runs - config's threshold in,
5317/// task-holding reason out - without asking the real machine's disk anything.
5318fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5319    repo: &Path,
5320    config: &Config,
5321    free_bytes: F,
5322) -> Option<String> {
5323    let min = config.disk.min_free_bytes;
5324    if min == 0 {
5325        return None;
5326    }
5327    let mut paths = vec![repo.to_owned()];
5328    if let Some(cache) = config.cache_dir() {
5329        paths.push(cache);
5330    }
5331    if let Some(root) = &config.graph.worktree_root {
5332        paths.push(root.clone());
5333    }
5334    for path in paths {
5335        let probe = if path == repo {
5336            path.as_path()
5337        } else {
5338            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5339        };
5340        let reason = match free_bytes(probe) {
5341            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5342            Err(e) => Some(crate::disk::unmeasured_in(
5343                probe,
5344                &e,
5345                &config.graph.language,
5346            )),
5347        };
5348        if reason.is_some() {
5349            return reason;
5350        }
5351    }
5352    None
5353}
5354
5355/// How long to wait before offering another task when a run lost a seat to a
5356/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5357/// could read, or carried nothing at all. Long enough that a quota outage
5358/// cannot burn through a whole backlog in the few seconds each doomed attempt
5359/// takes to fail; short enough that a quota which clears early is not left
5360/// idle for the fallback's sake.
5361const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5362
5363/// Longest a parsed reset hint may push the wait out to. The hint comes from
5364/// the CLI's own words, not a contract, so a parsing slip that lands a day
5365/// away must not leave the loop asleep for a day.
5366const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5367
5368/// How long [`poll`] should wait before offering the next task, after a run
5369/// lost at least one seat to a rate limit.
5370///
5371/// Pure and separate from the loop so the policy can be exercised without a
5372/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5373/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5374/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5375/// far a parsed hint is trusted to push the wait out.
5376fn quota_wait(
5377    reset_at: Option<Timestamp>,
5378    now: Timestamp,
5379    fallback: Duration,
5380    cap: Duration,
5381) -> Duration {
5382    match reset_at {
5383        Some(at) if at > now => {
5384            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5385            Duration::from_secs(secs).min(cap)
5386        }
5387        _ => fallback,
5388    }
5389}
5390
5391/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5392///
5393/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5394/// explains why parsing it exactly "would be a bug factory" — so this only
5395/// recognises the shapes actually observed in the wild, and returns `None`
5396/// for anything else rather than guess at a format nobody has seen.
5397///
5398/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5399/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5400/// said it, not from whenever this loop happens to read it: anchoring on `now`
5401/// would push the reset later on every read and would read an already-elapsed
5402/// reset as still in the future. (A long hint is still clamped by
5403/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5404fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5405    parse_reset_hint_zoned(text, now)
5406        .or_else(|| parse_reset_hint_dated(text))
5407        .or_else(|| parse_reset_hint_relative(text, recorded))
5408}
5409
5410/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5411/// optional but at least one required, in that order. A bare number or any
5412/// unknown unit is refused.
5413fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5414    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5415    let mut rest = rest.trim();
5416    if rest.is_empty() {
5417        return None;
5418    }
5419    let mut total: i64 = 0;
5420    let mut matched = false;
5421    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5422        if let Some((digits, tail)) = rest.split_once(unit)
5423            && !digits.is_empty()
5424            && digits.bytes().all(|b| b.is_ascii_digit())
5425        {
5426            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5427            rest = tail;
5428            matched = true;
5429        }
5430    }
5431    if !rest.is_empty() || !matched {
5432        return None;
5433    }
5434    recorded
5435        .checked_add(jiff::SignedDuration::from_secs(total))
5436        .ok()
5437}
5438
5439/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5440/// case-insensitive) into a 24-hour hour and minute. Shared by every
5441/// reset-hint shape below.
5442fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5443    let clock = clock.trim().to_lowercase();
5444    let (digits, pm) = clock
5445        .strip_suffix("am")
5446        .map(|d| (d, false))
5447        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5448    let (h, m) = digits.trim().split_once(':')?;
5449    let mut hour: i8 = h.trim().parse().ok()?;
5450    let minute: i8 = m.trim().parse().ok()?;
5451    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5452        return None;
5453    }
5454    if pm && hour != 12 {
5455        hour += 12;
5456    } else if !pm && hour == 12 {
5457        hour = 0;
5458    }
5459    Some((hour, minute))
5460}
5461
5462/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5463/// and a zone, never a date. A clock reading already past today is read as
5464/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5465/// the window rolled over while nothing was watching.
5466fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5467    let open = text.find('(')?;
5468    let close = text.rfind(')')?;
5469    if close <= open {
5470        return None;
5471    }
5472    let zone = text[open + 1..close].trim();
5473    let (hour, minute) = parse_12h_clock(&text[..open])?;
5474    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5475    let candidate = now
5476        .to_zoned(tz)
5477        .with()
5478        .hour(hour)
5479        .minute(minute)
5480        .second(0)
5481        .millisecond(0)
5482        .microsecond(0)
5483        .nanosecond(0)
5484        .build()
5485        .ok()?;
5486    let mut at = candidate.timestamp();
5487    if at <= now {
5488        at += jiff::SignedDuration::from_hours(24);
5489    }
5490    Some(at)
5491}
5492
5493/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5494/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5495/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5496/// "already past today" correction to make: the year already disambiguates
5497/// it. Scanned as a five-word window so it can be pulled out of the middle
5498/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5499/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5500/// any other timestamp with no zone attached.
5501fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5502    let words: Vec<&str> = text.split_whitespace().collect();
5503    if words.len() < 5 {
5504        return None;
5505    }
5506    (0..=words.len() - 5)
5507        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5508}
5509
5510/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5511/// parenthesis right after the window is refused rather than ignored — it
5512/// reads as an explicit zone annotation on a shape that otherwise carries
5513/// none, and guessing UTC anyway would be exactly the silent misread this
5514/// module's parsing otherwise avoids.
5515fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5516    if trailing.is_some_and(|next| next.starts_with('(')) {
5517        return None;
5518    }
5519    let month = month_number(window[0])?;
5520    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5521    let day_digits = ["st", "nd", "rd", "th"]
5522        .iter()
5523        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5524    let day: i8 = day_digits.parse().ok()?;
5525    let year_token = window[2];
5526    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5527        return None;
5528    }
5529    let year: i16 = year_token.parse().ok()?;
5530    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5531    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5532    // reusing the same 12-hour clock reader the bracketed shape uses.
5533    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5534    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5535    let date = jiff::civil::Date::new(year, month, day).ok()?;
5536    let candidate = date
5537        .at(hour, minute, 0, 0)
5538        .to_zoned(jiff::tz::TimeZone::UTC)
5539        .ok()?;
5540    Some(candidate.timestamp())
5541}
5542
5543/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5544/// case-insensitively, into a 1-based month number.
5545fn month_number(name: &str) -> Option<i8> {
5546    const NAMES: [&str; 12] = [
5547        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5548    ];
5549    let lower = name.to_lowercase();
5550    NAMES
5551        .iter()
5552        .position(|n| *n == lower.as_str())
5553        .map(|i| i as i8 + 1)
5554}
5555
5556/// Test probe for the shared resume policy's review-budget exclusion.
5557#[cfg(test)]
5558fn exhausted_review_budget(state: &RunState) -> bool {
5559    // A run whose task-head publication failed has nothing left to review:
5560    // resuming it only retries the publication, so it is never "exhausted".
5561    !crate::handover::can_resume(state)
5562        && state.status == RunStatus::Blocked
5563        && !state.released()
5564        && state.retired_to.is_none()
5565}
5566
5567/// This task's *most recent* run, if resuming it would actually make
5568/// progress. `short` is only for the warning's own message.
5569///
5570/// Only ever `runs.last()` — never a search back through older history.
5571/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5572/// mint, oldest first, and every entry before the last one was already
5573/// superseded at the moment it was minted: the daemon only ever starts a new
5574/// run when the previous one was not worth resuming (unresumable, exhausted,
5575/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5576/// opens a fresh review-only run alongside an older, already-failed
5577/// competition. Searching further back would let an old run that merely
5578/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5579/// behind, say — get resumed instead of the fresh competition
5580/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5581/// nothing asked to revisit.
5582///
5583/// Two runs paid for the "prefer resuming over restarting" half of this
5584/// lesson, which is why this still checks `runs.last()` rather than always
5585/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5586/// task a moment later, duplicating two and a half hours of agent work. Then
5587/// b25f stalled on a judge that timed out and one that answered with no JSON
5588/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5589/// **one second** later, buying three fresh implementations to reach the
5590/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5591/// the second case: a stall is terminal, and its cheap recovery re-asks only
5592/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5593/// that is technically `resumable()` but provably cannot progress must not
5594/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5595/// no-op instead of the fresh competition it promises.
5596///
5597/// A load failure is warned about rather than silently read as "not
5598/// resumable": the alternative is exactly what let a schema mismatch on run
5599/// `eba2` fall through to a full re-competition with nobody told why.
5600/// `crate::conduct` is what actually offers a better answer than
5601/// `Runner::start` here (see `Recovery::Review`), once this task's next
5602/// failure shows it up as `held`/`failed` with the run state unreadable.
5603fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5604    unfinished_run_with(runs, short, RunState::load)
5605}
5606
5607/// [`unfinished_run`] with an injected state reader. Tests provide their
5608/// fixtures directly rather than touching the process-global run home.
5609pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5610where
5611    F: FnMut(&str) -> Result<RunState>,
5612{
5613    let mut id = runs.last()?.clone();
5614    let mut visited = std::collections::BTreeSet::new();
5615    let mut repo = None;
5616    loop {
5617        if !runs.contains(&id) || !visited.insert(id.clone()) {
5618            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5619            return None;
5620        }
5621        let state = match load(&id) {
5622            Ok(state) if state.id == id => state,
5623            Ok(_) => return None,
5624            Err(e) => {
5625                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5626                return None;
5627            }
5628        };
5629        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5630            return None;
5631        }
5632        repo = Some(state.repo.clone());
5633        if let Some(authority) = state.retired_to {
5634            id = authority;
5635            continue;
5636        }
5637        return (crate::handover::can_resume(&state)
5638            && state.liveness(false) != crate::run::Liveness::Live)
5639            .then_some(id);
5640    }
5641}
5642
5643/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5644/// that [`attempt`] will resume it on its own?
5645///
5646/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5647/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5648/// injected reader like its sibling. An unreadable run is not awaiting
5649/// anything: it keeps going to the conductor as before.
5650fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5651where
5652    F: FnOnce(&str) -> Result<RunState>,
5653{
5654    // `Failed` stays: a record an older build wrote for a parked run.
5655    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5656        || task.fresh_start
5657        || task.review_branch.is_some()
5658    {
5659        return false;
5660    }
5661    let Some(id) = task.runs.last() else {
5662        return false;
5663    };
5664    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5665}
5666
5667/// Which of the three ways [`attempt`] can mint or continue a run this task
5668/// should use.
5669#[derive(Debug, Clone, PartialEq, Eq)]
5670enum Starter {
5671    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5672    /// and that still exists.
5673    Review(String),
5674    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5675    Resume(String),
5676    /// `crate::graph::Runner::start`: a fresh competition.
5677    Start,
5678}
5679
5680/// A second bound independent of inputs and the resettable failure counter.
5681/// Count recovery records, not history entries: resuming appends the same id.
5682/// Unknown history is not evidence that a new set of worktrees is affordable.
5683fn retained_attempt_hold(
5684    task: &Task,
5685    starter: &Starter,
5686    limit: usize,
5687    mut load: impl FnMut(&str) -> Result<RunState>,
5688) -> Option<String> {
5689    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5690        return None;
5691    }
5692    let mut retained = 0;
5693    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5694        let state = match load(id) {
5695            Ok(state) if state.id == *id => state,
5696            _ => {
5697                return Some(format!(
5698                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5699                ));
5700            }
5701        };
5702        if state.retired_to.is_some() || state.released() {
5703            continue;
5704        }
5705        // Neither a completed status nor an empty candidate array proves that
5706        // all recovery sources (including unrecorded preparation) were retired.
5707        retained += 1;
5708    }
5709    (retained >= limit).then(|| format!(
5710        "[recovery-backlog] {retained} unretired attempts reach the limit of {limit}. Resume an existing recovery owner or inspect the lineage and retire proved-obsolete attempts before creating another run. Releases, refunds and changed upstream inputs do not reset this limit. No source or historical report was removed."
5711    ))
5712}
5713
5714/// A selected public implementation overrides every historical candidate and pin.
5715fn selected_starter(
5716    selected: &crate::pr_recovery::Selection,
5717    previous: Option<&RunState>,
5718    unfinished: Option<&str>,
5719) -> Starter {
5720    if let Some(id) = unfinished
5721        && previous.is_some_and(|r| {
5722            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5723        })
5724    {
5725        Starter::Resume(id.to_owned())
5726    } else {
5727        Starter::Review(selected.branch.clone())
5728    }
5729}
5730
5731/// The owner's answer to this branch's divergence question, consumed from the
5732/// task so a later, different divergence asks again. The runner applies it
5733/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5734fn take_divergence_answer(
5735    branch: &str,
5736    remote: &str,
5737    task: &mut Task,
5738) -> Option<crate::reconcile::Choice> {
5739    let summary = crate::reconcile::summary_for(branch, remote);
5740    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5741        (a.question == summary)
5742            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5743            .flatten()
5744            .map(|c| (i, c))
5745    })?;
5746    task.answers.remove(idx);
5747    Some(choice)
5748}
5749
5750/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5751/// this attempt should use. Pure, and separate from [`attempt`], so the
5752/// routing itself is assertable without spawning a real graph or a git
5753/// process: `attempt`'s own `crate::git::branch_exists` call has already
5754/// happened by the time this is called.
5755///
5756/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5757/// whose branch is gone falls all the way through to [`Starter::Start`], not
5758/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5759/// old (likely `Blocked`) run in the first place, and a branch that vanished
5760/// out from under that choice is not evidence resuming it would fare better.
5761fn choose_starter(
5762    review_branch: Option<&str>,
5763    branch_exists: bool,
5764    unfinished: Option<&str>,
5765) -> Starter {
5766    match review_branch {
5767        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5768        Some(_) => Starter::Start,
5769        None => match unfinished {
5770            Some(id) => Starter::Resume(id.to_owned()),
5771            None => Starter::Start,
5772        },
5773    }
5774}
5775
5776/// Reuse a compatible latest review owner instead of taking its checked-out
5777/// branch into a new run. Different branches and changed criteria still use
5778/// the ordinary review/takeover policy.
5779fn review_retry_starter(
5780    task: &Task,
5781    previous: Option<&RunState>,
5782    branch: Option<&str>,
5783    exists: bool,
5784    unfinished: Option<&str>,
5785) -> Starter {
5786    if let Some(run) = previous
5787        && unfinished == Some(run.id.as_str())
5788        && run.reviewed_commits.is_some()
5789        && branch.is_some_and(|branch| {
5790            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5791        })
5792        && may_resume_run(run, task)
5793    {
5794        return Starter::Resume(run.id.clone());
5795    }
5796    match (branch, unfinished, &task.review_of) {
5797        (None, None, Some(branch)) => Starter::Review(branch.clone()),
5798        _ => choose_starter(branch, exists, unfinished),
5799    }
5800}
5801
5802/// Consume a retained review only while its authored criteria still match.
5803fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5804    let branch = task.review_branch.take();
5805    let instruction = task.review_instruction.take();
5806    branch.filter(|branch| match &instruction {
5807        Some(authored) => *authored == task.instruction,
5808        // Legacy retained branches must agree with their prior run; only an
5809        // explicitly pinned review can proceed without recoverable provenance.
5810        None => previous.map_or_else(
5811            || task.review_of.as_ref() == Some(branch),
5812            |run| compatible_run_instruction(run, task),
5813        ),
5814    })
5815}
5816
5817/// A current explicit pin can select an otherwise incompatible run. Edits
5818/// and subsequent approvals invalidate pins selected for earlier criteria.
5819fn may_resume_run(run: &RunState, task: &Task) -> bool {
5820    task.resume_override
5821        .as_ref()
5822        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5823        || compatible_run_instruction(run, task)
5824}
5825
5826/// Review scaffolding is execution context, not evidence of an operator edit.
5827pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5828    if let Some(authored) = &run.task_instruction {
5829        return compatible_instruction(authored, task);
5830    }
5831    if compatible_instruction(&run.instruction, task) {
5832        return true;
5833    }
5834    // Recognize only the existing generated review shapes on legacy runs.
5835    // Ordinary authored text with a similar heading is left intact.
5836    if run.reviewed_commits.is_some() {
5837        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5838            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5839        }
5840        if let Some(branch) = &task.review_of {
5841            let canonical = format!(
5842                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5843            );
5844            let generated = format!(
5845                "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"
5846            );
5847            return task.instruction == canonical && run.instruction.starts_with(&generated);
5848        }
5849    }
5850    false
5851}
5852
5853/// Compare authored instructions, excluding answer blocks appended by the daemon.
5854pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5855    strip_answers_block(old, task) == task.instruction
5856}
5857
5858/// Which repository a task runs in. A task that names none — the normal case
5859/// for one filed from a phone — runs in the daemon's own default.
5860fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5861    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5862        return fallback.to_path_buf();
5863    }
5864    task.repo.clone()
5865}
5866
5867/// The header [`append_answers`] appends operator answers under. Shared with
5868/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5869/// rather than grown a new block on every resume.
5870const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5871
5872/// Render the first `count` answers in the block appended to an instruction.
5873fn answers_block(task: &Task, count: usize) -> String {
5874    let mut s = ANSWERS_HEADER.to_owned();
5875    for a in &task.answers[..count] {
5876        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5877    }
5878    s
5879}
5880
5881/// Render the approval independently of transient task state, so historical
5882/// suffixes remain recognizable after another explicit release.
5883fn resumption_block(r: &crate::queue::Resumption) -> String {
5884    format!(
5885        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5886         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5887        r.generation, r.at, r.instruction, r.answers_through,
5888    )
5889}
5890
5891/// Append audit answers and the latest explicit approval to the instruction.
5892fn append_answers(base: &str, task: &Task) -> String {
5893    let mut s = base.to_owned();
5894    if !task.answers.is_empty() {
5895        s.push_str(&answers_block(task, task.answers.len()));
5896    }
5897    if let Some(r) = &task.resumption {
5898        s.push_str(&resumption_block(r));
5899    }
5900    s
5901}
5902
5903/// Drop the prior answer block only when it is exactly the suffix this task
5904/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5905/// the task author is ordinary instruction text, not a block to remove.
5906fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5907    let mut instruction = instruction;
5908    for approval in task
5909        .resumption
5910        .iter()
5911        .chain(task.resumption_history.iter().rev())
5912    {
5913        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5914            instruction = base;
5915            break;
5916        }
5917    }
5918    for count in (1..=task.answers.len()).rev() {
5919        let block = answers_block(task, count);
5920        if let Some(base) = instruction.strip_suffix(&block) {
5921            return base;
5922        }
5923    }
5924    instruction
5925}
5926
5927/// The instruction handed to `Runner::start`: the task's own text, plus any
5928/// operator answers `crate::conduct` collected for it (see
5929/// [`Task::answers`]), so a decision the operator actually made reaches the
5930/// implementers rather than only clearing the block that was waiting on it.
5931///
5932/// Appended rather than merged into [`Task::instruction`] itself, so the
5933/// task's own record stays exactly what its author wrote.
5934fn instruction_for(task: &Task) -> String {
5935    append_answers(&task.instruction, task)
5936}
5937
5938/// The instruction a resumed run should carry on with: whatever it already
5939/// had, refreshed with the task's *current* operator answers.
5940///
5941/// A resumable run's own `RunState::instruction` predates any answer
5942/// `crate::conduct` collects after the run parks, so resuming it unchanged —
5943/// the behaviour before this function existed — silently drops the very
5944/// decision the operator made to unblock it. Re-stripping any block this
5945/// function appended on an earlier resume before re-appending the current
5946/// list (rather than blindly appending again) is what keeps a task resumed
5947/// three times over three answered questions from carrying the same answer
5948/// three times.
5949fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5950    append_answers(strip_answers_block(old_instruction, task), task)
5951}
5952
5953/// Preserve the producer's verified boundary and target, independent of prose.
5954fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5955    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5956    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5957    if let Some(cause) = task.hold_notice_cause.as_mut() {
5958        cause.target = failure.map(|f| f.target.clone());
5959    }
5960}
5961
5962#[derive(Debug, thiserror::Error)]
5963#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5964struct MissingAttachment {
5965    name: String,
5966    path: PathBuf,
5967}
5968
5969/// The task's attachments as absolute paths, each checked to still exist.
5970fn task_attachments(
5971    queue: &Queue,
5972    task: &Task,
5973) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5974    let paths = queue.attachment_paths(task);
5975    for (name, path) in task.attachments.iter().zip(&paths) {
5976        if !path.is_file() {
5977            return Err(MissingAttachment {
5978                name: name.clone(),
5979                path: path.clone(),
5980            });
5981        }
5982    }
5983    Ok(paths)
5984}
5985
5986/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
5987/// answers before handing it to `Runner` — the actual boundary between
5988/// [`choose_starter`]'s routing and the graph, factored out so it is
5989/// assertable without a real repository, git branch, or agent CLI.
5990///
5991/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
5992/// instruction from the reviewed branch's own commit log because there is no
5993/// task statement to speak of for hand-written work, and splicing operator
5994/// answers into that text would contradict the very message it sends
5995/// reviewers ("there is no task statement").
5996fn prepare_instruction(
5997    starter: &Starter,
5998    old_instruction: Option<&str>,
5999    task: &Task,
6000) -> Option<String> {
6001    match starter {
6002        Starter::Start => Some(instruction_for(task)),
6003        Starter::Resume(_) => Some(resumed_instruction(
6004            old_instruction.expect("a resumed run always has a prior instruction"),
6005            task,
6006        )),
6007        Starter::Review(_) => None,
6008    }
6009}
6010
6011/// Persist a transition. A queue write failure is logged rather than fatal: the
6012/// run already happened, and taking the daemon down would only add a lost
6013/// backlog to a full disk.
6014fn record(queue: &Queue, task: &mut Task) {
6015    if let Err(e) = queue.put(task) {
6016        tracing::error!("could not record task {}: {e:#}", task.short());
6017        let notice = Notice::error(
6018            "loop:record",
6019            format!(
6020                "Task {} state could not be saved: {}. Check the disk.",
6021                task.id,
6022                e.to_string().lines().next().unwrap_or("unknown save error")
6023            ),
6024        )
6025        .link(Link::Task {
6026            id: task.id.clone(),
6027        });
6028        // The queue lives at `<home>/queue`, so its parent is the home.
6029        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6030            Some(home) => notices::raise_in(home, notice),
6031            None => notices::raise(notice),
6032        }
6033    }
6034}
6035
6036/// Every runnable task, in the order the loop should try them.
6037///
6038/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6039/// tail exists so that a claim somebody else holds costs the loop the next
6040/// candidate rather than a whole poll interval of idleness.
6041fn runnable(queue: &Queue) -> Vec<Task> {
6042    let mut tasks: Vec<Task> = queue
6043        .list()
6044        .into_iter()
6045        .filter(|t| t.status.runnable())
6046        .collect();
6047    tasks.sort_unstable_by(crate::queue::dispatch_order);
6048    tasks
6049}
6050
6051/// Why a run ended where it did, in one line, for [`Task::last_error`].
6052///
6053/// A stalled run names the seats the quota took out: "out of quota" is not
6054/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6055/// agent to replace or which plan to top up.
6056///
6057/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6058/// purpose: unlike `label`'s other callers (an internal log line, an
6059/// already-a-bug fallback message), this string becomes `Task::last_error`
6060/// verbatim, which the phone renders in the same alarm-styled box an
6061/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6062/// `.err` styling. A bare `verified_noop` there would read exactly like the
6063/// failure this whole feature exists to tell apart from one.
6064fn describe(state: &RunState) -> String {
6065    let p = phrases(&state.config.graph.language);
6066    let mut detail = if state.status == RunStatus::Stalled {
6067        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6068        seats.sort_unstable();
6069        seats.dedup();
6070        if seats.is_empty() {
6071            p.quorum_lost.to_owned()
6072        } else {
6073            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6074        }
6075    } else {
6076        format!("{}{}", p.run_ended, state.status.display_label())
6077    };
6078    if let Some(cause) = state.verification_blocking_cause() {
6079        detail.push_str(&format!(" ({cause})"));
6080    } else if let Some(last) = state.events.last() {
6081        // The review loop's "never answered" stop is the one event worth
6082        // translating; it is recognised from structured state, not by
6083        // matching the English event text (which stays as recorded).
6084        let unanswered = state
6085            .reviews
6086            .last()
6087            .filter(|r| {
6088                state.status == RunStatus::Blocked
6089                    && last.node == "review"
6090                    && r.incomplete()
6091                    && r.blocking == 0
6092                    && r.round == state.config.graph.review_rounds
6093                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6094            })
6095            .map(|r| (r.expected - r.answered, r.round));
6096        match unanswered {
6097            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6098                detail.push_str(&format!(
6099                    " ({}: {})",
6100                    last.node,
6101                    (p.reviewers_never_answered)(missing, rounds)
6102                ));
6103            }
6104            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6105        }
6106    }
6107    detail.push_str(&format!(" [run {}]", state.id));
6108    detail
6109}
6110
6111/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6112///
6113/// The task file lives in the backlog indefinitely; a diagnostic is an
6114/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6115/// stay small regardless of how much a gate command or a candidate printed.
6116const DIAGNOSTIC_MAX: usize = 4_000;
6117
6118/// Tail kept from a single failing command's output inside a diagnostic.
6119/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6120/// pointer for a human deciding whether to go read the full artifact by hand,
6121/// not a replacement for reading it.
6122const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6123
6124/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6125/// `magi task show` says more than the one-line reason in [`describe`].
6126///
6127/// The one-liner answers "where did the run stop"; this answers "what would a
6128/// human have found opening `artifacts/` by hand" — the point of the whole
6129/// feature is the case that one-liner actively misleads on: a run held as "no
6130/// candidate produced a change" can mean the implementer actually finished
6131/// the task (opened a PR, merged it, tagged a release) and only left a clean
6132/// local worktree behind, which reads as "nothing happened" unless someone
6133/// goes and reads what the agent actually said. `None` when the run carries
6134/// none of the three shapes this recognises — an ordinary run held for
6135/// something not diagnosable from `RunState` alone still explains itself
6136/// through `Task::last_error`.
6137fn diagnostic(state: &RunState) -> Option<String> {
6138    let mut parts: Vec<String> = Vec::new();
6139
6140    // Gate failure: which check(s), and the tail of what each printed.
6141    for o in state.gate.iter().filter(|o| !o.ok()) {
6142        parts.push(format!(
6143            "gate `{}` failed ({}):\n{}",
6144            o.command,
6145            notices::exit_status(o.code),
6146            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6147        ));
6148    }
6149
6150    // The land loop gave up because the fixer declined while checks were
6151    // still red: the message already names them (see `land::run`).
6152    if let Some(last) = state
6153        .events
6154        .iter()
6155        .rev()
6156        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6157    {
6158        parts.push(last.message.clone());
6159    }
6160
6161    // No viable candidate: every implementer's own final word, sanitized the
6162    // same way a judge would have read it, so a run that actually finished
6163    // the job does not read as an unexplained failure. A verified no-op is
6164    // called out ahead of its own summary and apart from an ordinary
6165    // failure's `why` — this is the one candidate shape whose diagnostic a
6166    // human is expected to actually judge, not just skim.
6167    if state.viable().is_empty() {
6168        for c in &state.candidates {
6169            if let Some(evidence) = &c.verified_noop {
6170                parts.push(format!(
6171                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6172                    c.label
6173                ));
6174            } else if !c.summary.trim().is_empty() {
6175                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6176            } else if let Some(why) = &c.failed {
6177                parts.push(format!("candidate {}: {why}", c.label));
6178            }
6179        }
6180    }
6181
6182    if parts.is_empty() {
6183        return None;
6184    }
6185    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6186    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6187    // back slightly over. Leave it enough room to always land under the
6188    // limit.
6189    Some(crate::run::tail(
6190        &parts.join("\n\n"),
6191        DIAGNOSTIC_MAX.saturating_sub(100),
6192    ))
6193}
6194
6195/// Stable lower-case name for a run status, for an internal log line and the
6196/// "graph stopped without reaching a terminal status" bug message in
6197/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6198/// doc for why that one reads [`RunStatus::display_label`] instead. One
6199/// definition of a status's name, on the type that owns it: this table used
6200/// to live here as a second copy, and a status renamed in one place would
6201/// have gone on reading correctly in the other.
6202fn label(status: RunStatus) -> &'static str {
6203    status.as_str()
6204}
6205
6206/// Parse a merge mode override.
6207pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6208    match mode {
6209        "none" => Ok(MergeMode::None),
6210        "local" => Ok(MergeMode::Local),
6211        "pr" => Ok(MergeMode::Pr),
6212        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6213    }
6214}
6215
6216/// Take the status lock, recovering from a poisoned one.
6217///
6218/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6219/// data, and the worst a poisoned lock can hold is a stale timestamp.
6220fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6221    mutex
6222        .lock()
6223        .unwrap_or_else(std::sync::PoisonError::into_inner)
6224}
6225
6226#[cfg(test)]
6227mod tests {
6228    use super::*;
6229    use crate::queue::{Source, TaskStatus};
6230    use crate::run::{Candidate, CommandOutcome};
6231    use pretty_assertions::assert_eq;
6232
6233    fn task() -> Task {
6234        Task::new(
6235            "add retries".to_owned(),
6236            "add retries".to_owned(),
6237            PathBuf::from("/repo"),
6238            Source::Human,
6239        )
6240    }
6241
6242    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6243        let job = crate::worker::Job {
6244            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6245            sequence: 1,
6246            kind: "task".into(),
6247            key: format!("task:{}", request.task),
6248            payload: serde_json::to_value(request).unwrap(),
6249            generation: "a".repeat(64),
6250            version: None,
6251            status: crate::worker::Status::Starting,
6252            result: None,
6253            pid: None,
6254            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6255            finished_at: None,
6256        };
6257        let dir = home.join("workers/jobs").join(&job.id);
6258        std::fs::create_dir_all(&dir).unwrap();
6259        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6260        job
6261    }
6262
6263    #[test]
6264    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6265        let home = tempfile::tempdir().unwrap();
6266        let request = TaskWorker {
6267            opts: Opts::default(),
6268            queue: home.path().join("queue"),
6269            task: "startup".into(),
6270            lane: PermitKind::Ordinary,
6271            standalone: false,
6272        };
6273        let job = starting_task_reservation(home.path(), &request);
6274        let error = task_worker_spawn_error(
6275            home.path(),
6276            &request,
6277            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6278        )
6279        .expect_err("our own reservation must not turn a failed spawn into a resync");
6280        let active = crate::worker::active(home.path()).unwrap();
6281        assert_eq!(active.len(), 1);
6282        assert_eq!(active[0].id, job.id);
6283        assert_eq!(active[0].status, crate::worker::Status::Starting);
6284        assert!(
6285            crate::worker::control(home.path(), &job.key)
6286                .unwrap()
6287                .is_none()
6288        );
6289        let notices = notices::Notices::at(home.path().join("notifications")).list();
6290        assert_eq!(notices.len(), 1);
6291        assert_eq!(notices[0].key, "loop:worker-startup");
6292        assert!(!notices[0].message.contains("private-error-detail"));
6293        assert!(notices[0].message.contains(&request.task));
6294        assert!(
6295            notices[0]
6296                .message
6297                .contains("could not be started or acknowledged")
6298        );
6299        assert!(notices[0].message.contains("worker.log"));
6300        assert_eq!(
6301            notices[0].link,
6302            Some(Link::Task {
6303                id: request.task.clone()
6304            })
6305        );
6306        assert!(format!("{error:#}").contains("private-error-detail"));
6307    }
6308
6309    #[test]
6310    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6311        let home = tempfile::tempdir().unwrap();
6312        let mut request = TaskWorker {
6313            opts: Opts::default(),
6314            queue: home.path().join("queue"),
6315            task: "handoff".into(),
6316            lane: PermitKind::Ordinary,
6317            standalone: true,
6318        };
6319        let job = starting_task_reservation(home.path(), &request);
6320        request.standalone = false;
6321        task_worker_spawn_error(
6322            home.path(),
6323            &request,
6324            anyhow::anyhow!("operation key is already reserved for a different request"),
6325        )
6326        .expect("a different standalone request is the handoff race, not our startup failure");
6327        let active = crate::worker::active(home.path()).unwrap();
6328        assert_eq!(active.len(), 1);
6329        assert_eq!(active[0].id, job.id);
6330        assert_eq!(active[0].payload, job.payload);
6331        assert!(
6332            notices::Notices::at(home.path().join("notifications"))
6333                .list()
6334                .is_empty()
6335        );
6336    }
6337
6338    #[test]
6339    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6340        let home = tempfile::tempdir().unwrap();
6341        let queue = Queue::at(home.path().join("queue"));
6342        let mut task = task();
6343        task.runs = vec!["previous".into()];
6344        queue.put(&mut task).unwrap();
6345        let request = TaskWorker {
6346            opts: Opts::default(),
6347            queue: home.path().join("queue"),
6348            task: task.id.clone(),
6349            lane: PermitKind::Ordinary,
6350            standalone: false,
6351        };
6352        let job = starting_task_reservation(home.path(), &request);
6353        let claims = current_work(home.path(), Timestamp::now());
6354        assert_eq!(claims.len(), 1);
6355        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6356        assert_eq!(claims[0].run, "previous");
6357        assert!(other_claims_run(&claims, "previous", None));
6358        // Only after confirming the executing caller may admission ignore
6359        // this exact projection. Cleanup continues to observe it as live.
6360        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6361        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6362    }
6363
6364    #[test]
6365    fn admission_excludes_only_the_callers_exact_reservation() {
6366        let own = Current {
6367            worker: Some("own".into()),
6368            task: "same-task".into(),
6369            run: "previous".into(),
6370        };
6371        assert!(!other_claims_run(
6372            std::slice::from_ref(&own),
6373            "previous",
6374            Some("own")
6375        ));
6376        assert!(other_claims_run(
6377            std::slice::from_ref(&own),
6378            "previous",
6379            None
6380        ));
6381        for worker in [None, Some("other".into())] {
6382            let other = Current {
6383                worker,
6384                ..own.clone()
6385            };
6386            assert!(other_claims_run(
6387                &[own.clone(), other],
6388                "previous",
6389                Some("own")
6390            ));
6391        }
6392        let legacy: Current =
6393            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6394        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6395    }
6396
6397    #[test]
6398    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6399        let mut task = task();
6400        let mut run = run_state(RunStatus::Reviewing);
6401        run.task_instruction = Some(task.instruction.clone());
6402        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6403        let branch = "magi/test/B";
6404        run.candidates.push(crate::run::Candidate {
6405            branch: branch.into(),
6406            ..candidate('B', "preserved work", false, None)
6407        });
6408        task.runs = vec![run.id.clone()];
6409        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6410        assert_eq!(
6411            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6412            Starter::Resume(run.id.clone())
6413        );
6414        assert!(matches!(
6415            review_retry_starter(
6416                &task,
6417                Some(&run),
6418                Some("different"),
6419                true,
6420                unfinished.as_deref()
6421            ),
6422            Starter::Review(_)
6423        ));
6424        assert_eq!(
6425            review_retry_starter(
6426                &task,
6427                Some(&run),
6428                Some(branch),
6429                false,
6430                unfinished.as_deref()
6431            ),
6432            Starter::Start
6433        );
6434        task.instruction.push_str(" changed criteria");
6435        assert!(matches!(
6436            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6437            Starter::Review(_)
6438        ));
6439        assert!(matches!(
6440            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6441            Starter::Review(_)
6442        ));
6443    }
6444
6445    #[test]
6446    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6447        let dir = tempfile::tempdir().unwrap();
6448        let queue = Queue::at(dir.path().join("queue"));
6449        let mut task = task();
6450        task.status = TaskStatus::Running;
6451        task.attempts = 1;
6452        queue.put(&mut task).unwrap();
6453        let live = std::collections::BTreeSet::from([task.id.clone()]);
6454        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6455        drop(queue.claim(&task.id).unwrap());
6456        let saved = queue.get(&task.id).unwrap();
6457        assert_eq!(saved.status, TaskStatus::Running);
6458        assert_eq!(saved.attempts, 1);
6459        assert!(saved.last_error.is_none());
6460    }
6461
6462    #[test]
6463    fn standalone_workers_do_not_consume_scheduler_lanes() {
6464        let request = |task: &str, lane, standalone| TaskWorker {
6465            opts: Opts::default(),
6466            queue: PathBuf::from("/queue"),
6467            task: task.to_owned(),
6468            lane,
6469            standalone,
6470        };
6471        let mut jobs = vec![
6472            request("ordinary", PermitKind::Ordinary, false),
6473            request("standalone-urgent", PermitKind::Urgent, true),
6474            request("standalone-ordinary", PermitKind::Ordinary, true),
6475            request("decision", PermitKind::None, false),
6476        ];
6477        assert_eq!(available_slots(&jobs, 2), (1, 1));
6478        jobs.push(request("urgent", PermitKind::Urgent, false));
6479        assert_eq!(available_slots(&jobs, 2), (1, 0));
6480        assert_eq!(available_slots(&jobs, 0), (0, 0));
6481    }
6482
6483    #[test]
6484    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6485        let now = Timestamp::now();
6486        let mut reading = Reading {
6487            pid: Some(std::process::id()),
6488            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6489            ..Reading::default()
6490        };
6491        assert!(!reading.running(now));
6492        assert!(legacy_scheduler_running(&reading, now, 0));
6493        reading.worker_protocol = Some(1);
6494        assert!(!legacy_scheduler_running(&reading, now, 0));
6495    }
6496
6497    #[test]
6498    fn selected_public_head_overrides_historical_resume_and_pin() {
6499        let mut t = task();
6500        let mut old = run_state(RunStatus::Blocked);
6501        let selection = crate::pr_recovery::Selection {
6502            url: "url".into(),
6503            branch: format!("magi/task-{}", t.id),
6504            head: "a".repeat(40),
6505            source_head: None,
6506            source_run: None,
6507            source_proof: None,
6508            disposition: Some(crate::pr_recovery::Disposition::Review),
6509            instruction: t.instruction.clone(),
6510            approved_at: Timestamp::now(),
6511        };
6512        t.resume_override = Some(crate::queue::OperatorResume {
6513            pinned_run: Some(old.id.clone()),
6514            question_id: "choice".into(),
6515            at: Timestamp::now(),
6516            conductor_rehold: None,
6517            forced: false,
6518        });
6519        assert_eq!(
6520            selected_starter(&selection, Some(&old), Some(&old.id)),
6521            Starter::Review(selection.branch.clone())
6522        );
6523        old.pr_recovery = Some(selection.clone());
6524        assert_eq!(
6525            selected_starter(&selection, Some(&old), Some(&old.id)),
6526            Starter::Review(selection.branch.clone())
6527        );
6528        old.reviewed_commits = Some(vec!["implementation".into()]);
6529        assert_eq!(
6530            selected_starter(&selection, Some(&old), Some(&old.id)),
6531            Starter::Resume(old.id.clone())
6532        );
6533        let mut changed = selection.clone();
6534        changed.head = "b".repeat(40);
6535        assert_eq!(
6536            selected_starter(&changed, Some(&old), Some(&old.id)),
6537            Starter::Review(changed.branch)
6538        );
6539    }
6540
6541    #[test]
6542    fn candidate_transplant_failure_is_one_actionable_hold() {
6543        let dir = tempfile::tempdir().unwrap();
6544        let q = Queue::at(dir.path().join("queue"));
6545        let mut t = task();
6546        let mut state = run_state(RunStatus::Blocked);
6547        state.event("prep", "cannot apply referenced commit: conflict");
6548        state.prep_failure = Some("conflict".into());
6549        t.start(state.id.clone());
6550        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6551        assert_eq!(t.attempts, 1);
6552        assert_eq!(t.status, TaskStatus::Held);
6553        assert!(t.operator_held());
6554        assert!(!t.status.runnable());
6555        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6556        let first = t.chat_notice_key().unwrap();
6557        t.chat_notices.push(first.clone());
6558        t.release_operator("test", None);
6559        state.id = "another-unprepared-run".into();
6560        t.start(state.id.clone());
6561        finish_attempt(
6562            3,
6563            &q,
6564            &mut t,
6565            &state,
6566            &[],
6567            Err(anyhow::anyhow!("still conflicts")),
6568        );
6569        assert_eq!(
6570            t.chat_notice_key().as_ref(),
6571            Some(&first),
6572            "no work happened"
6573        );
6574        t.release_operator("test", None);
6575        state.prep_failure = None;
6576        state.status = RunStatus::Failed;
6577        state.begin_pass();
6578        t.start(state.id.clone());
6579        finish_attempt(
6580            1,
6581            &q,
6582            &mut t,
6583            &state,
6584            &[],
6585            Err(anyhow::anyhow!("new gate failure")),
6586        );
6587        let failure = t.chat_notice_key().unwrap();
6588        assert_ne!(failure, first, "approved recovery reached a real failure");
6589        t.release_operator("test", None);
6590        state.begin_pass();
6591        t.start(state.id.clone());
6592        finish_attempt(
6593            1,
6594            &q,
6595            &mut t,
6596            &state,
6597            &[],
6598            Err(anyhow::anyhow!("new failure on resume")),
6599        );
6600        assert_ne!(
6601            t.chat_notice_key().as_ref(),
6602            Some(&failure),
6603            "a new settled pass"
6604        );
6605    }
6606
6607    #[test]
6608    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6609        for source in ["cli", "web"] {
6610            let mut t = task();
6611            let mut run = run_state(RunStatus::Blocked);
6612            run.instruction = "Run A original criteria".into();
6613            run.task_instruction = Some(run.instruction.clone());
6614            t.start(run.id.clone());
6615            t.release_operator("choice", Some("resume-question"));
6616            t.resume_override = Some(crate::queue::OperatorResume {
6617                question_id: "resume-question".into(),
6618                at: Timestamp::now(),
6619                conductor_rehold: None,
6620                forced: true,
6621                pinned_run: Some(run.id.clone()),
6622            });
6623            t.hold_machine(Some("not enough free space to start a run".into()));
6624            let mut unchanged = t.clone();
6625            unchanged
6626                .edit("title changed".into(), unchanged.instruction.clone())
6627                .unwrap();
6628            unchanged.release_operator(source, None);
6629            assert_eq!(
6630                unchanged
6631                    .resume_override
6632                    .as_ref()
6633                    .unwrap()
6634                    .pinned_run
6635                    .as_deref(),
6636                Some(run.id.as_str())
6637            );
6638            assert!(!compatible_run_instruction(&run, &unchanged));
6639            assert!(may_resume_run(&run, &unchanged));
6640
6641            t.edit(
6642                "approved recovery".into(),
6643                "Reuse measured PR head B; fix Clippy; review".into(),
6644            )
6645            .unwrap();
6646            assert!(t.resume_override.is_none());
6647            t.release_operator(source, None);
6648            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6649            assert!(reloaded.resume_override.is_none());
6650            assert!(!may_resume_run(&run, &reloaded));
6651            let unfinished =
6652                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6653                    .filter(|_| may_resume_run(&run, &reloaded));
6654            assert_eq!(
6655                choose_starter(None, false, unfinished.as_deref()),
6656                Starter::Start
6657            );
6658            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6659            assert_eq!(
6660                reloaded.resumption_history[0].question_id.as_deref(),
6661                Some("resume-question")
6662            );
6663
6664            // A revision already persisted with the old approval/pin is also
6665            // invalidated when the new operator release is recorded.
6666            unchanged.instruction = "Reuse measured PR head B".into();
6667            unchanged.hold_machine(Some("disk hold".into()));
6668            unchanged.release_operator(source, None);
6669            assert!(unchanged.resume_override.is_none());
6670            assert!(!may_resume_run(&run, &unchanged));
6671        }
6672    }
6673
6674    #[test]
6675    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6676        let mut t = task();
6677        let mut run = run_state(RunStatus::Blocked);
6678        t.review_of = Some("approved-head".into());
6679        t.instruction =
6680            "Review the branch `approved-head` (review-only: no implementation, no judging)."
6681                .into();
6682        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();
6683        run.reviewed_commits = Some(vec!["Commit log".into()]);
6684        t.start(run.id.clone());
6685        t.hold_machine(Some("interrupted review".into()));
6686        t.release_operator("cli", None);
6687        assert!(
6688            compatible_run_instruction(&run, &t),
6689            "legacy explicit review remains resumable"
6690        );
6691        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6692            .filter(|_| compatible_run_instruction(&run, &t));
6693        assert_eq!(
6694            choose_starter(None, false, unfinished.as_deref()),
6695            Starter::Resume(run.id.clone())
6696        );
6697        run.task_instruction = Some(t.instruction.clone());
6698        assert!(compatible_run_instruction(&run, &t));
6699        let reloaded: RunState =
6700            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6701        assert!(compatible_run_instruction(&reloaded, &t));
6702        t.edit(
6703            "new approved head".into(),
6704            "Reuse measured PR head B".into(),
6705        )
6706        .unwrap();
6707        assert!(!compatible_run_instruction(&run, &t));
6708
6709        // Legacy recovery reviews retain the task criteria ahead of the log.
6710        t.review_of = None;
6711        t.instruction = "Fix Clippy on approved head".into();
6712        run.task_instruction = None;
6713        run.instruction = format!(
6714            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6715            t.instruction
6716        );
6717        assert!(compatible_run_instruction(&run, &t));
6718        t.instruction.push('\n');
6719        assert!(
6720            compatible_run_instruction(&run, &t),
6721            "legacy generated review trimmed the original criteria"
6722        );
6723        t.hold_for_handover(Some("approved-head".into()), "refused".into());
6724        let mut unchanged = t.clone();
6725        assert_eq!(
6726            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6727            Some("approved-head")
6728        );
6729        t.edit("new plan".into(), "Reuse measured PR head B".into())
6730            .unwrap();
6731        assert!(take_review_branch(&mut t, Some(&run)).is_none());
6732        assert!(!compatible_run_instruction(&run, &t));
6733        t.review_branch = Some("approved-head".into());
6734        t.review_instruction = None;
6735        assert!(
6736            take_review_branch(&mut t, Some(&run)).is_none(),
6737            "legacy retained candidate cannot replace a revised approved head"
6738        );
6739    }
6740
6741    #[test]
6742    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6743        crate::run::pin_test_home();
6744        let dir = tempfile::tempdir().unwrap();
6745        let queue = Queue::at(dir.path().join("queue"));
6746        for resume in [true, false] {
6747            let state = run_state(RunStatus::Blocked);
6748            let mut t = task();
6749            t.start(state.id.clone());
6750            let action = if resume {
6751                ask::ChoiceAction::Resume {
6752                    run: state.id.clone(),
6753                }
6754            } else {
6755                ask::ChoiceAction::Requeue
6756            };
6757            let mut q = action_question(&state.id, action);
6758            q.status = ask::QuestionStatus::Open;
6759            q.answer = None;
6760            q.answered_at = None;
6761            t.fail("run stopped with a question", 3);
6762            hold_if_runnable(&queue, &mut t);
6763            assert!(t.operator_decided_at.is_none());
6764            assert!(t.operator_held());
6765            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6766            let expected = if resume {
6767                ActionDecision::Resume(state.id.clone())
6768            } else {
6769                ActionDecision::Requeue
6770            };
6771            assert_eq!(
6772                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6773                expected
6774            );
6775            t.hold_manual(Some("later explicit hold".into()));
6776            assert_eq!(
6777                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6778                ActionDecision::Stale
6779            );
6780        }
6781    }
6782
6783    #[test]
6784    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6785        let mut t = task();
6786        t.answers.push(crate::queue::AnsweredQuestion {
6787            question: "Inspect the remote?".into(),
6788            answer: "Inspect then wait".into(),
6789        });
6790        let old = instruction_for(&t);
6791        assert!(compatible_instruction(&old, &t));
6792        t.instruction = "Reuse approved PR head and review".into();
6793        t.release_operator("cli", None);
6794        assert!(!compatible_instruction(&old, &t));
6795        let approved = instruction_for(&t);
6796        assert!(approved.contains("waiting premises are superseded"));
6797        assert!(compatible_instruction(&approved, &t));
6798        assert_eq!(resumed_instruction(&approved, &t), approved);
6799        t.release_operator("web", None);
6800        assert!(compatible_instruction(&approved, &t));
6801        assert_eq!(t.resumption_history.len(), 1);
6802        t.start("run".into());
6803        assert!(instruction_for(&t).contains("Explicit operator resumption"));
6804    }
6805
6806    /// A run that stopped on an infrastructure wait asked no agent anything:
6807    /// the task is held by the machine under a `[resource]` reason (resumable,
6808    /// re-checked by triage), and the attempt it started is given back.
6809    #[test]
6810    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6811        let mut state = RunState::new(
6812            PathBuf::from("/repo"),
6813            "main".into(),
6814            "base".into(),
6815            "task".into(),
6816            Config::default(),
6817        );
6818        state.status = RunStatus::Landing;
6819        state.parked = true;
6820        state.pr_pushed_head = Some("head".into());
6821        state.land_unrelated = Some(
6822            serde_json::from_value(serde_json::json!({
6823                "head": "head", "question": "ci-question",
6824                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6825            }))
6826            .unwrap(),
6827        );
6828        let mut t = task();
6829        t.start(state.id.clone());
6830        let verdict = Verdict {
6831            status: RunStatus::Landing,
6832            left_pr: true,
6833            quota_hit: false,
6834            parked: true,
6835            no_viable_candidates: false,
6836        };
6837        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6838        assert_eq!(t.attempts, 0);
6839        assert_eq!(t.status, TaskStatus::Held);
6840        assert!(!t.operator_held());
6841        assert!(
6842            t.hold_reason
6843                .as_deref()
6844                .unwrap()
6845                .starts_with("[ci-unrelated]")
6846        );
6847        // A second settlement must not refund an earlier task attempt.
6848        t.attempts = 1;
6849        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6850        assert_eq!(t.attempts, 1);
6851        assert_eq!(t.passes.len(), 1);
6852        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6853        state.pr_pushed_head = Some("new-head".into());
6854        state.parked = false;
6855        state.status = RunStatus::Blocked;
6856        let stale = Verdict {
6857            status: RunStatus::Blocked,
6858            parked: false,
6859            ..verdict
6860        };
6861        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6862        assert_eq!(t.attempts, 1);
6863        // A new execution pass can refund its own newly charged attempt.
6864        state.begin_pass();
6865        state.begin_pass();
6866        state.status = RunStatus::Landing;
6867        state.parked = true;
6868        state.pr_pushed_head = Some("head".into());
6869        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6870        assert_eq!(t.attempts, 0);
6871        assert_eq!(t.passes.len(), 2);
6872    }
6873
6874    #[test]
6875    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
6876        let mut state = RunState::new(
6877            PathBuf::from("/repo"),
6878            "main".to_owned(),
6879            "abc1234".to_owned(),
6880            "task".to_owned(),
6881            Config::default(),
6882        );
6883        state.status = RunStatus::Blocked;
6884        state.resource_block = Some(crate::run::ResourceBlock {
6885            cause: crate::run::ResourceBlockCause::Other,
6886            node: "graft".to_owned(),
6887            kind: "shared build cache".to_owned(),
6888            detail: "timed out".to_owned(),
6889            at: jiff::Timestamp::now(),
6890        });
6891        let mut t = task();
6892        t.start("20260902-000000-aaaa".to_owned());
6893        assert_eq!(t.attempts, 1);
6894        let verdict = Verdict {
6895            status: RunStatus::Blocked,
6896            left_pr: false,
6897            quota_hit: false,
6898            parked: false,
6899            no_viable_candidates: false,
6900        };
6901        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
6902        assert_eq!(t.status, TaskStatus::Held);
6903        assert_eq!(t.attempts, 0, "the attempt is refunded");
6904        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
6905        assert!(
6906            !t.operator_held(),
6907            "a machine hold, released without a human"
6908        );
6909
6910        let mut selected = task();
6911        selected.start("20260902-000000-cccc".into());
6912        selected.replacement = Some(crate::merge_decision::Replacement {
6913            question: "fixture".into(),
6914            run: "earlier".into(),
6915            pr: "https://example.invalid/pr/1".into(),
6916            agent: "selected".into(),
6917            context: "fixture".into(),
6918        });
6919        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
6920        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
6921        assert_eq!(selected.attempts, 0);
6922        assert!(
6923            !selected.operator_held(),
6924            "a selected agent also retains a machine resource hold"
6925        );
6926        assert!(
6927            selected
6928                .hold_reason
6929                .as_deref()
6930                .unwrap()
6931                .starts_with("[resource] ")
6932        );
6933
6934        // A park request outranks it: still the operator's doing.
6935        let mut p = task();
6936        p.start("20260902-000000-bbbb".to_owned());
6937        settle_and_diagnose(
6938            &mut p,
6939            Verdict {
6940                parked: true,
6941                ..verdict
6942            },
6943            "parked",
6944            2,
6945            &state,
6946        );
6947        assert_eq!(p.status, TaskStatus::Parked);
6948        assert_eq!(
6949            p.attempts, 0,
6950            "parking refunds once rather than also settling the resource hold"
6951        );
6952    }
6953
6954    #[test]
6955    fn record_failure_notice_links_the_task() {
6956        let dir = tempfile::tempdir().unwrap();
6957        // A regular file where the queue directory should be makes every
6958        // `put` fail, on every platform and whoever runs the test.
6959        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
6960        let queue = Queue::at(dir.path().join("queue"));
6961        let mut t = interrupt_task("rec-fail-1");
6962        record(&queue, &mut t);
6963
6964        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
6965        assert_eq!(found.len(), 1);
6966        assert_eq!(found[0].key, "loop:record");
6967        assert_eq!(
6968            found[0].link,
6969            Some(Link::Task {
6970                id: "rec-fail-1".to_owned()
6971            })
6972        );
6973    }
6974
6975    /// A runnable task marked to interrupt, with an id fixed for assertions
6976    /// rather than the random one [`Task::new`] mints.
6977    fn interrupt_task(id: &str) -> Task {
6978        let mut t = task();
6979        t.id = id.to_owned();
6980        t.interrupt = true;
6981        t
6982    }
6983
6984    /// An ordinary runnable task with an id fixed for assertions.
6985    fn task_with_id(id: &str) -> Task {
6986        let mut t = task();
6987        t.id = id.to_owned();
6988        t
6989    }
6990
6991    /// A runnable task marked `--urgent`, with an id fixed for assertions.
6992    fn urgent_task(id: &str) -> Task {
6993        let mut t = task();
6994        t.id = id.to_owned();
6995        t.urgent = true;
6996        t
6997    }
6998
6999    #[test]
7000    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7001        let dir = tempfile::tempdir().unwrap();
7002        let queue = Queue::at(dir.path().join("queue"));
7003        let mut parked = task_with_id("parked");
7004        parked.start("run".into());
7005        parked.park("upgrade");
7006        parked.record_pass_at(
7007            "run",
7008            0,
7009            Some(Timestamp::now()),
7010            1,
7011            Some(crate::run::ParkCause::Upgrade {
7012                from: "old".into(),
7013                to: None,
7014            }),
7015        );
7016        let mut fresh = task_with_id("fresh");
7017        fresh.priority = 100;
7018        let mut urgent_task = urgent_task("urgent");
7019        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7020            queue.put(t).unwrap();
7021        }
7022        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7023        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7024        let candidates = runnable(&queue);
7025        assert_eq!(candidates[0].id, parked.id);
7026        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7027        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7028        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7029        drop(first);
7030        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7031        let next = runnable(&queue)
7032            .into_iter()
7033            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7034            .unwrap();
7035        assert_eq!(next.task.id, fresh.id);
7036        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7037        drop(claimed_elsewhere);
7038        drop(next);
7039        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7040    }
7041
7042    #[test]
7043    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7044        let dir = tempfile::tempdir().unwrap();
7045        let queue = Queue::at(dir.path().join("queue"));
7046        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7047        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7048        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7049        let mut first = task();
7050        queue.put(&mut first).unwrap();
7051        let stale_plain = queue.get(&first.id).unwrap();
7052        first.set_urgent(true).unwrap();
7053        queue.put(&mut first).unwrap();
7054        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7055        let mut second = urgent_task("second");
7056        queue.put(&mut second).unwrap();
7057        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7058        drop(queue.claim(&second.id).unwrap());
7059        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7060        drop(dispatched);
7061        let stale_urgent = queue.get(&first.id).unwrap();
7062        first.set_urgent(false).unwrap();
7063        queue.put(&mut first).unwrap();
7064        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7065        assert_eq!(urgent.available_permits(), 1);
7066        drop(queue.claim(&first.id).unwrap());
7067        drop(occupied);
7068    }
7069
7070    #[test]
7071    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7072        let dir = tempfile::tempdir().unwrap();
7073        let queue = Queue::at(dir.path().join("queue"));
7074        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7075        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7076        let mut t = task();
7077        queue.put(&mut t).unwrap();
7078        for enabled in [true, false] {
7079            let stale = queue.get(&t.id).unwrap();
7080            t.set_urgent(enabled).unwrap();
7081            queue.put(&mut t).unwrap();
7082            assert_ne!(stale.urgent, enabled);
7083            let DispatchClaim {
7084                task: fresh,
7085                claim,
7086                permit,
7087            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7088            assert_eq!(fresh.urgent, enabled);
7089            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7090            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7091            assert!(queue.claim(&t.id).is_err());
7092            assert_eq!(fresh.attempts, stale.attempts);
7093            drop((claim, permit));
7094            assert_eq!(ordinary.available_permits(), 1);
7095            assert_eq!(urgent.available_permits(), 1);
7096        }
7097        t.set_urgent(true).unwrap();
7098        queue.put(&mut t).unwrap();
7099        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7100        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7101        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7102        drop(queue.claim(&t.id).unwrap());
7103        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7104        drop(occupied);
7105        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7106        drop(queue.claim(&t.id).unwrap());
7107        let held = queue.claim(&t.id).unwrap();
7108        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7109        drop(held);
7110        t.status = TaskStatus::Held;
7111        queue.put(&mut t).unwrap();
7112        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7113        drop(queue.claim(&t.id).unwrap());
7114        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7115        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7116        drop(queue.claim(&t.id).unwrap());
7117        assert_eq!(urgent.available_permits(), 1);
7118    }
7119
7120    /// The land-resume exemption wins outright, whether or not the candidate
7121    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7122    /// queue behind anything" guarantee cannot be weaker just because the
7123    /// same task was also filed with `--urgent`.
7124    #[test]
7125    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7126        assert_eq!(permit_kind(true, false), PermitKind::None);
7127        assert_eq!(permit_kind(true, true), PermitKind::None);
7128    }
7129
7130    /// The one property this whole feature exists for: `--urgent` draws from
7131    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7132    /// ordinary candidate draws from the ordinary pool exactly as before,
7133    /// untouched by the urgent slot's existence.
7134    #[test]
7135    fn permit_kind_separates_urgent_from_ordinary() {
7136        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7137        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7138    }
7139
7140    /// The exact wiring `attempt` runs before minting anything: a config's
7141    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7142    /// Free space is injected rather than asked of the real disk - the point
7143    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7144    /// is deterministic on every machine this test runs on, never dependent
7145    /// on how full the CI runner's own disk happens to be.
7146    #[test]
7147    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7148        let cfg = Config::default();
7149        let repo = Path::new("/any/repo/path");
7150
7151        let reason =
7152            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7153        assert!(reason.contains("1024"), "{reason}");
7154        assert!(
7155            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7156            "{reason}"
7157        );
7158
7159        assert_eq!(
7160            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7161            None,
7162            "exactly at the floor is open"
7163        );
7164        assert_eq!(
7165            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7166            None,
7167            "comfortably above the floor is open"
7168        );
7169    }
7170
7171    #[test]
7172    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7173        let mut cfg = Config::default();
7174        cfg.disk.min_free_bytes = 0;
7175        let repo = Path::new("/any/repo/path");
7176        assert_eq!(
7177            disk_gate_with(repo, &cfg, |_| Ok(0)),
7178            None,
7179            "a zero floor never measures at all"
7180        );
7181    }
7182
7183    #[test]
7184    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7185        let cfg = Config::default();
7186        let repo = Path::new("/any/repo/path");
7187        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7188            .expect("a measurement failure must close the gate, not open it");
7189        assert!(reason.contains("could not measure"), "{reason}");
7190    }
7191
7192    #[test]
7193    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7194        let ordinary = task();
7195        let next = advance_interrupt(
7196            Interrupt::Idle,
7197            std::slice::from_ref(&ordinary.id),
7198            std::slice::from_ref(&ordinary),
7199        );
7200        assert_eq!(next, Interrupt::Idle);
7201    }
7202
7203    #[test]
7204    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7205        // Nothing to interrupt - this is just an ordinary candidate, and the
7206        // loop's normal dispatch will pick it up like any other.
7207        let marked = interrupt_task("marked");
7208        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7209        assert_eq!(next, Interrupt::Idle);
7210    }
7211
7212    #[test]
7213    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7214        let marked = interrupt_task("marked");
7215        let next = advance_interrupt(
7216            Interrupt::Idle,
7217            &["running".to_owned()],
7218            std::slice::from_ref(&marked),
7219        );
7220        assert_eq!(
7221            next,
7222            Interrupt::Parking {
7223                parked: vec!["running".to_owned()],
7224                interrupt_task: "marked".to_owned(),
7225            }
7226        );
7227    }
7228
7229    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7230    /// one run can be in flight when a task becomes runnable and marked.
7231    /// Parking all of them would mean `Resuming` later has more than one id
7232    /// to release back to ordinary dispatch, which cannot be made safe
7233    /// against that same setting's own extra concurrency slots letting two
7234    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7235    /// The simplification the task's own constraints ask for: do not begin
7236    /// a sequence at all until the herd settles back to exactly one.
7237    #[test]
7238    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7239        let marked = interrupt_task("marked");
7240
7241        let two = advance_interrupt(
7242            Interrupt::Idle,
7243            &["a".to_owned(), "b".to_owned()],
7244            std::slice::from_ref(&marked),
7245        );
7246        assert_eq!(two, Interrupt::Idle);
7247
7248        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7249        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7250    }
7251
7252    #[test]
7253    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7254        let state = Interrupt::Parking {
7255            parked: vec!["running".to_owned()],
7256            interrupt_task: "marked".to_owned(),
7257        };
7258        // Still in flight: no change.
7259        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7260        assert_eq!(still_going, state);
7261
7262        // Left flight, but the interrupt task has not been dispatched yet on
7263        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7264        // as long as it is still runnable.
7265        let stopped_but_not_yet_dispatched =
7266            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7267        assert_eq!(stopped_but_not_yet_dispatched, state);
7268
7269        // Left flight, and the interrupt task is now in flight itself.
7270        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7271        assert_eq!(
7272            dispatched,
7273            Interrupt::Running {
7274                parked: vec!["running".to_owned()],
7275                interrupt_task: "marked".to_owned(),
7276            }
7277        );
7278    }
7279
7280    #[test]
7281    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7282        let state = Interrupt::Running {
7283            parked: vec!["running".to_owned()],
7284            interrupt_task: "marked".to_owned(),
7285        };
7286        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7287        assert_eq!(still_running, state);
7288
7289        // Whatever it ended as - merged, failed, held - is not this
7290        // function's concern: leaving flight is the only trigger, driven
7291        // straight off the same in-flight list `poll` already reaps. It does
7292        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7293        // why that would let an unrelated task start ahead of, or alongside,
7294        // the guaranteed resume.
7295        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7296        assert_eq!(
7297            ended,
7298            Interrupt::Resuming {
7299                parked: vec!["running".to_owned()]
7300            }
7301        );
7302    }
7303
7304    #[test]
7305    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7306        let state = Interrupt::Resuming {
7307            parked: vec!["running".to_owned()],
7308        };
7309        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7310        assert_eq!(still_waiting, state);
7311
7312        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7313        assert_eq!(dispatched, Interrupt::Idle);
7314    }
7315
7316    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7317    /// or otherwise moved on by an operator with no claim standing in the
7318    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7319    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7320    /// come. The parked run still gets its resume.
7321    #[test]
7322    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7323    {
7324        let state = Interrupt::Parking {
7325            parked: vec!["running".to_owned()],
7326            interrupt_task: "marked".to_owned(),
7327        };
7328        // `marked` has been held/blocked/deleted since the sequence began:
7329        // it no longer appears in `runnable` at all.
7330        let next = advance_interrupt(state, &[], &[]);
7331        assert_eq!(
7332            next,
7333            Interrupt::Resuming {
7334                parked: vec!["running".to_owned()]
7335            },
7336            "abandoning the interrupt must not abandon the resume it owes"
7337        );
7338    }
7339
7340    /// The same abandonment, one step later: `Resuming` itself must not wait
7341    /// forever for a parked task that has since become unrunnable.
7342    #[test]
7343    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7344        let state = Interrupt::Resuming {
7345            parked: vec!["running".to_owned()],
7346        };
7347        let next = advance_interrupt(state, &[], &[]);
7348        assert_eq!(
7349            next,
7350            Interrupt::Idle,
7351            "nothing is left to wait for; the loop must not stay wedged"
7352        );
7353    }
7354
7355    #[test]
7356    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7357        let marked = interrupt_task("marked");
7358        let next = advance_interrupt_tick(
7359            false,
7360            Interrupt::Idle,
7361            &["running".to_owned()],
7362            std::slice::from_ref(&marked),
7363        );
7364        assert_eq!(
7365            next,
7366            Interrupt::Idle,
7367            "an unmarked, unconfigured daemon must behave exactly as before"
7368        );
7369    }
7370
7371    #[test]
7372    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7373        let state = Interrupt::Parking {
7374            parked: vec!["running".to_owned()],
7375            interrupt_task: "marked".to_owned(),
7376        };
7377        let candidates = vec![interrupt_task("marked"), task()];
7378        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7379        assert!(
7380            allowed.is_empty(),
7381            "nothing may dispatch - not even the interrupt task itself - \
7382             until the parked run has actually stopped"
7383        );
7384    }
7385
7386    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7387    /// grow a special case for it: an urgent candidate that is not the
7388    /// interrupt task withholds exactly like an ordinary one for as long as
7389    /// the parked run it is racing has not actually left flight. A version
7390    /// of this feature once bypassed the gate for urgent candidates, on the
7391    /// theory that a genuinely separate concurrency lane could not collide
7392    /// with 75dd's own; it could, and did - the bypassed task dispatched
7393    /// alongside a run 75dd's own state machine had only *asked* to park,
7394    /// not yet confirmed gone, which is exactly the second run
7395    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7396    /// tick during Parking/Running/Resuming where letting an extra
7397    /// candidate through is safe, urgent or not - the parked run may still
7398    /// be genuinely mid-call.
7399    #[test]
7400    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7401        for state in [
7402            Interrupt::Parking {
7403                parked: vec!["running".to_owned()],
7404                interrupt_task: "marked".to_owned(),
7405            },
7406            Interrupt::Running {
7407                parked: vec!["running".to_owned()],
7408                interrupt_task: "marked".to_owned(),
7409            },
7410            Interrupt::Resuming {
7411                parked: vec!["running".to_owned()],
7412            },
7413        ] {
7414            let candidates = vec![
7415                interrupt_task("marked"),
7416                urgent_task("hot"),
7417                task_with_id("ordinary"),
7418            ];
7419            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7420            assert!(
7421                !allowed.iter().any(|t| t.id == "hot"),
7422                "an urgent candidate must wait out the same gate as anything \
7423                 else while the run it would run alongside has not actually \
7424                 left flight, for state {state:?}: {allowed:?}"
7425            );
7426        }
7427    }
7428
7429    /// The one case where marking a task `--urgent` and `interrupt` at once
7430    /// is not redundant: once the interrupt sequence's own guaranteed
7431    /// resume/dispatch actually admits the task, it is unaffected by also
7432    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7433    /// never on the urgent flag.
7434    #[test]
7435    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7436        let state = Interrupt::Resuming {
7437            parked: vec!["hot".to_owned()],
7438        };
7439        let candidates = vec![urgent_task("hot"), task()];
7440        let allowed = interrupt_gate(&state, &[], candidates);
7441        assert_eq!(
7442            allowed.iter().filter(|t| t.id == "hot").count(),
7443            1,
7444            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7445        );
7446    }
7447
7448    #[test]
7449    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7450        let state = Interrupt::Parking {
7451            parked: vec!["running".to_owned()],
7452            interrupt_task: "marked".to_owned(),
7453        };
7454        let other = task();
7455        let candidates = vec![interrupt_task("marked"), other.clone()];
7456        let allowed = interrupt_gate(&state, &[], candidates);
7457        assert_eq!(allowed.len(), 1);
7458        assert_eq!(allowed[0].id, "marked");
7459    }
7460
7461    #[test]
7462    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7463        let state = Interrupt::Running {
7464            parked: vec!["running".to_owned()],
7465            interrupt_task: "marked".to_owned(),
7466        };
7467        let candidates = vec![task(), task()];
7468        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7469        assert!(allowed.is_empty());
7470    }
7471
7472    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7473    /// sequence began (only reachable above the default
7474    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7475    /// never both in the same tick, which is what "exactly one resume, no
7476    /// simultaneous run" actually requires structurally rather than by
7477    /// coincidence of how many ordinary slots happen to be free.
7478    #[test]
7479    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7480        let state = Interrupt::Resuming {
7481            parked: vec!["a".to_owned(), "c".to_owned()],
7482        };
7483        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7484        let allowed = interrupt_gate(&state, &[], candidates);
7485        assert_eq!(
7486            allowed.len(),
7487            1,
7488            "at most one candidate may be offered while resuming: {allowed:?}"
7489        );
7490        assert_eq!(allowed[0].id, "a");
7491    }
7492
7493    #[test]
7494    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7495        let state = Interrupt::Resuming {
7496            parked: vec!["a".to_owned()],
7497        };
7498        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7499        assert!(allowed.is_empty());
7500    }
7501
7502    /// The invariant the completion criteria ask for by name: across a whole
7503    /// simulated sequence, there is never a tick where the gate would let
7504    /// through both the parked run's resume and the interrupt task, and
7505    /// exactly one candidate resumes the instant the interrupt task's run
7506    /// ends - never zero, never more than one.
7507    #[test]
7508    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7509        let running = task(); // id: whatever `Task::new` minted
7510        let marked = interrupt_task("marked");
7511
7512        let mut state = Interrupt::Idle;
7513        // Tick 1: `running` is in flight, `marked` becomes runnable.
7514        let in_flight = vec![running.id.clone()];
7515        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7516        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7517        assert!(gated.is_empty(), "still waiting on `running` to park");
7518
7519        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7520        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7521        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7522        assert_eq!(
7523            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7524            vec!["marked"],
7525            "only the interrupt task may be offered to the dispatcher now"
7526        );
7527
7528        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7529        state = advance_interrupt_tick(
7530            true,
7531            state,
7532            &["marked".to_owned()],
7533            std::slice::from_ref(&running),
7534        );
7535        let gated = interrupt_gate(
7536            &state,
7537            &["marked".to_owned()],
7538            vec![marked.clone(), running.clone()],
7539        );
7540        assert!(
7541            gated.is_empty(),
7542            "the parked run must not be offered back while the interrupt \
7543             task is still running"
7544        );
7545
7546        // Tick 4: `marked`'s run reached a terminal status and left flight.
7547        // A higher-priority ordinary task `other` is also runnable now - it
7548        // must not be let through instead of, or alongside, `running`.
7549        let other = task_with_id("other");
7550        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7551        assert_eq!(
7552            state,
7553            Interrupt::Resuming {
7554                parked: vec![running.id.clone()]
7555            }
7556        );
7557        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7558        assert_eq!(
7559            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7560            vec![running.id.as_str()],
7561            "exactly the parked run resumes - not the unrelated task, even \
7562             though it was offered first"
7563        );
7564
7565        // Tick 5: `running` is now in flight (dispatched from tick 4's
7566        // gate). Only now does the sequence end and ordinary dispatch fully
7567        // resume.
7568        state = advance_interrupt_tick(
7569            true,
7570            state,
7571            std::slice::from_ref(&running.id),
7572            std::slice::from_ref(&other),
7573        );
7574        assert_eq!(state, Interrupt::Idle);
7575        let gated = interrupt_gate(
7576            &state,
7577            std::slice::from_ref(&running.id),
7578            vec![other.clone()],
7579        );
7580        assert_eq!(
7581            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7582            vec![other.id.as_str()],
7583            "ordinary dispatch is unrestricted again"
7584        );
7585    }
7586
7587    #[test]
7588    fn every_run_status_settles_the_task_it_came_from() {
7589        // run status, resulting task status, attempts still standing after one
7590        let table = [
7591            (RunStatus::Merged, TaskStatus::Done, 1),
7592            (RunStatus::Ready, TaskStatus::Done, 1),
7593            (RunStatus::Stalled, TaskStatus::Failed, 0),
7594            (RunStatus::Blocked, TaskStatus::Failed, 1),
7595            (RunStatus::Failed, TaskStatus::Failed, 1),
7596            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7597            (RunStatus::Prep, TaskStatus::Failed, 1),
7598            (RunStatus::Implementing, TaskStatus::Failed, 1),
7599            (RunStatus::Judging, TaskStatus::Failed, 1),
7600            (RunStatus::Deliberating, TaskStatus::Failed, 1),
7601            (RunStatus::Voting, TaskStatus::Failed, 1),
7602            (RunStatus::Reviewing, TaskStatus::Failed, 1),
7603            (RunStatus::Gating, TaskStatus::Failed, 1),
7604        ];
7605        for (run, want, attempts) in table {
7606            let mut t = task();
7607            t.start("20260902-000000-aaaa".to_owned());
7608            settle(
7609                &mut t,
7610                Verdict {
7611                    status: run,
7612                    left_pr: false,
7613                    parked: false,
7614                    quota_hit: matches!(run, RunStatus::Stalled),
7615                    no_viable_candidates: false,
7616                },
7617                "why",
7618                2,
7619            );
7620            assert_eq!(t.status, want, "task status after {}", label(run));
7621            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7622        }
7623    }
7624
7625    #[test]
7626    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7627        let mut stalled = task();
7628        stalled.start("20260902-000000-aaaa".to_owned());
7629        settle(
7630            &mut stalled,
7631            Verdict {
7632                status: RunStatus::Stalled,
7633                left_pr: false,
7634                parked: false,
7635                quota_hit: true,
7636                no_viable_candidates: false,
7637            },
7638            "quota",
7639            1,
7640        );
7641        assert_eq!(stalled.attempts, 0);
7642        assert!(
7643            stalled.status.runnable(),
7644            "a machine problem must leave the task in line"
7645        );
7646
7647        let mut blocked = task();
7648        blocked.start("20260902-000000-aaaa".to_owned());
7649        settle(
7650            &mut blocked,
7651            Verdict {
7652                status: RunStatus::Blocked,
7653                left_pr: false,
7654                parked: false,
7655                quota_hit: false,
7656                no_viable_candidates: false,
7657            },
7658            "findings open",
7659            1,
7660        );
7661        assert_eq!(blocked.attempts, 1);
7662        assert_eq!(
7663            blocked.status,
7664            TaskStatus::Held,
7665            "the last attempt hands the task to a human"
7666        );
7667    }
7668
7669    #[test]
7670    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7671        // Attempts to spare: without the pull request this task would go
7672        // straight back in line and run the whole competition again.
7673        let mut delivered = task();
7674        delivered.start("20260903-080619-01c2".to_owned());
7675        settle(
7676            &mut delivered,
7677            Verdict {
7678                status: RunStatus::Blocked,
7679                left_pr: true,
7680                parked: false,
7681                quota_hit: false,
7682                no_viable_candidates: false,
7683            },
7684            "no check status",
7685            4,
7686        );
7687        assert_eq!(
7688            delivered.status,
7689            TaskStatus::Held,
7690            "a pull request waiting on CI or a person is not a retryable failure"
7691        );
7692        assert!(
7693            !delivered.status.runnable(),
7694            "the loop must not pick this task up again"
7695        );
7696        assert_eq!(
7697            delivered.last_error.as_deref(),
7698            Some("no check status"),
7699            "the operator needs to be told what the gate was waiting for"
7700        );
7701
7702        // The same status without a pull request is a plain failure, and with
7703        // attempts left it is retried.
7704        let mut empty_handed = task();
7705        empty_handed.start("20260903-080619-01c2".to_owned());
7706        settle(
7707            &mut empty_handed,
7708            Verdict {
7709                status: RunStatus::Blocked,
7710                left_pr: false,
7711                parked: false,
7712                quota_hit: false,
7713                no_viable_candidates: false,
7714            },
7715            "findings open",
7716            4,
7717        );
7718        assert_eq!(empty_handed.status, TaskStatus::Failed);
7719        assert!(empty_handed.status.runnable());
7720    }
7721
7722    #[test]
7723    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7724        // Every candidate agreed, with evidence, that nothing belonged in the
7725        // worktree. That is not a confirmed success to close automatically -
7726        // a human still has to check the claim - and it is not an ordinary
7727        // failure either, so this settles exactly like a pull request nobody
7728        // merged yet: `Held`, same as `Blocked` with a PR.
7729        let mut noop = task();
7730        noop.start("20260912-131304-391f".to_owned());
7731        settle(
7732            &mut noop,
7733            Verdict {
7734                status: RunStatus::VerifiedNoop,
7735                left_pr: false,
7736                parked: false,
7737                quota_hit: false,
7738                no_viable_candidates: true,
7739            },
7740            "candidate A: already fixed by b32cfc4, on main",
7741            4,
7742        );
7743        assert_eq!(
7744            noop.status,
7745            TaskStatus::Held,
7746            "an unverified claim is a request for a human, not a failure"
7747        );
7748        assert!(
7749            !noop.status.runnable(),
7750            "the loop must not requeue this on the same unverified claim"
7751        );
7752        // `Task::release` resets attempts to zero the moment a human looks at
7753        // the evidence and lets it run again, so it does not matter here
7754        // whether the one attempt already spent stays spent - what matters is
7755        // that nothing retries this task unattended in the meantime.
7756        assert_eq!(noop.attempts, 1);
7757    }
7758
7759    #[test]
7760    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7761        // Parking is the operator asking for the process back - to replace the
7762        // binary, most of all. The run's work is intact on disk, so this is
7763        // not a failed attempt, and charging for it would mean a few upgrades
7764        // could exhaust a budget meant for agents that misbehaved.
7765        let mut parked = task();
7766        parked.start("20260903-183634-2d98".to_owned());
7767        settle(
7768            &mut parked,
7769            Verdict {
7770                status: RunStatus::Implementing,
7771                left_pr: false,
7772                quota_hit: false,
7773                parked: true,
7774                no_viable_candidates: false,
7775            },
7776            "parked after `implementing`",
7777            2,
7778        );
7779        assert_eq!(parked.attempts, 0, "a park is refunded");
7780        assert!(
7781            parked.status.runnable(),
7782            "and the task stays in line so the next loop resumes its run"
7783        );
7784        assert_eq!(parked.status, TaskStatus::Parked);
7785        assert_eq!(
7786            parked.park_reason.as_deref(),
7787            Some("parked after `implementing`"),
7788            "the card says where it stopped"
7789        );
7790        assert_eq!(parked.last_error, None, "nothing failed");
7791
7792        // Without the park flag the same non-terminal status is what it always
7793        // was: `execute` returning mid-flight, which is a bug and spends an
7794        // attempt so a task cannot loop on it forever.
7795        let mut broken = task();
7796        broken.start("20260903-183634-2d98".to_owned());
7797        settle(
7798            &mut broken,
7799            Verdict {
7800                status: RunStatus::Implementing,
7801                left_pr: false,
7802                quota_hit: false,
7803                parked: false,
7804                no_viable_candidates: false,
7805            },
7806            "returned mid-flight",
7807            2,
7808        );
7809        assert_eq!(broken.attempts, 1);
7810    }
7811
7812    #[test]
7813    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7814        // Run e633: quorum lost because two judges answered with the wrong
7815        // JSON shape, `quota: []`. Refunding that takes the bound off the
7816        // retry loop, and each retry pays for a fresh hour-long implement
7817        // wave before it can fail the same way.
7818        let mut flaky = task();
7819        flaky.start("20260903-123023-e633".to_owned());
7820        settle(
7821            &mut flaky,
7822            Verdict {
7823                status: RunStatus::Stalled,
7824                left_pr: false,
7825                parked: false,
7826                quota_hit: false,
7827                no_viable_candidates: false,
7828            },
7829            "verdict rests on 1 of 3 judges",
7830            2,
7831        );
7832        assert_eq!(
7833            flaky.attempts, 1,
7834            "flakiness spends an attempt, so `max_attempts` still bounds it"
7835        );
7836        assert!(flaky.status.runnable(), "and it is still worth retrying");
7837
7838        // The same status, lost to a rate limit, is the machine's fault.
7839        let mut limited = task();
7840        limited.start("20260903-123023-e633".to_owned());
7841        settle(
7842            &mut limited,
7843            Verdict {
7844                status: RunStatus::Stalled,
7845                left_pr: false,
7846                parked: false,
7847                quota_hit: true,
7848                no_viable_candidates: false,
7849            },
7850            "judge-2, judge-3 out of quota",
7851            2,
7852        );
7853        assert_eq!(limited.attempts, 0, "a quota window is refunded");
7854        assert!(limited.status.runnable());
7855
7856        // And the bound really binds: a task that keeps stalling on flakiness
7857        // reaches a human instead of running the roster forever.
7858        let mut worn = task();
7859        for _ in 0..2 {
7860            worn.release();
7861        }
7862        worn.start("20260903-123023-e633".to_owned());
7863        worn.attempts = 2;
7864        settle(
7865            &mut worn,
7866            Verdict {
7867                status: RunStatus::Stalled,
7868                left_pr: false,
7869                parked: false,
7870                quota_hit: false,
7871                no_viable_candidates: false,
7872            },
7873            "no quorum again",
7874            2,
7875        );
7876        assert_eq!(worn.status, TaskStatus::Held);
7877        assert!(!worn.status.runnable());
7878    }
7879
7880    #[test]
7881    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
7882        // The implement wave loses every seat to the same rate limit and
7883        // `after_implement` bails with nothing viable, which surfaces as
7884        // `Failed` rather than `Stalled`. That is the same machine fact the
7885        // `Stalled`-quota row already refunds, and must be refunded the same
7886        // way, or a quota outage quietly holds every task it touches instead
7887        // of leaving them in line for the reset.
7888        let mut wiped_out = task();
7889        wiped_out.start("20260907-025000-a1b2".to_owned());
7890        settle(
7891            &mut wiped_out,
7892            Verdict {
7893                status: RunStatus::Failed,
7894                left_pr: false,
7895                parked: false,
7896                quota_hit: true,
7897                no_viable_candidates: true,
7898            },
7899            "no candidate produced a change; nothing to judge",
7900            2,
7901        );
7902        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
7903        assert!(
7904            wiped_out.status.runnable(),
7905            "a machine problem must leave the task in line"
7906        );
7907
7908        // This is the exemption that must stay narrow: a candidate that did
7909        // produce a change, and then failed for some other reason, still
7910        // spends the attempt even though a seat elsewhere hit its quota.
7911        // Otherwise every ordinary failure that happens to share a run with
7912        // an unrelated rate limit would be refunded for free.
7913        let mut partial_progress = task();
7914        partial_progress.start("20260907-025500-c3d4".to_owned());
7915        settle(
7916            &mut partial_progress,
7917            Verdict {
7918                status: RunStatus::Failed,
7919                left_pr: false,
7920                parked: false,
7921                quota_hit: true,
7922                no_viable_candidates: false,
7923            },
7924            "gate failed on the winning candidate",
7925            2,
7926        );
7927        assert_eq!(
7928            partial_progress.attempts, 1,
7929            "a candidate that actually produced a change spends the attempt \
7930             even though some other seat hit its quota"
7931        );
7932        assert!(partial_progress.status.runnable());
7933    }
7934
7935    #[test]
7936    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
7937        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
7938        // disk, and that construction must reach the same conclusion as the
7939        // one `attempt` builds from a live run, or a crash at exactly the
7940        // wrong moment gives a recovered task a different policy than one a
7941        // daemon finished settling itself.
7942        let mut t = task();
7943        t.start("20260907-025000-a1b2".to_owned());
7944        let mut state = run_state(RunStatus::Failed);
7945        state.quota.push(QuotaLoss {
7946            seat: "cand-a".to_owned(),
7947            node: "implement".to_owned(),
7948            at: Timestamp::now(),
7949            reset: None,
7950        });
7951        assert!(
7952            state.viable().is_empty(),
7953            "no candidate was added, so nothing is viable"
7954        );
7955        reclaim(&mut t, Some(state), 2, "en");
7956        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
7957        assert!(t.status.runnable());
7958    }
7959
7960    #[test]
7961    fn a_held_task_is_never_offered_to_the_loop() {
7962        let dir = tempfile::tempdir().unwrap();
7963        let queue = Queue::at(dir.path().to_path_buf());
7964        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
7965            let mut t = task();
7966            t.id = format!("2026090{n}-000000-000{n}");
7967            t.priority = priority;
7968            queue.put(&mut t).unwrap();
7969        }
7970        let mut held = task();
7971        held.id = "20260909-000000-9999".to_owned();
7972        held.priority = 99;
7973        held.hold_machine(None);
7974        queue.put(&mut held).unwrap();
7975
7976        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
7977        assert_eq!(order.len(), 3);
7978        assert!(!order.contains(&held.id));
7979        assert_eq!(
7980            order.first().cloned(),
7981            queue.next_runnable().map(|t| t.id),
7982            "the loop's first candidate is exactly what the queue offers"
7983        );
7984        assert_eq!(
7985            order,
7986            vec![
7987                "20260902-000000-0002".to_owned(),
7988                "20260903-000000-0003".to_owned(),
7989                "20260901-000000-0001".to_owned(),
7990            ],
7991            "priority first, then oldest, so nothing starves"
7992        );
7993    }
7994
7995    #[test]
7996    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
7997        let dir = tempfile::tempdir().unwrap();
7998        let queue = Queue::at(dir.path().to_path_buf());
7999        let mut old = task();
8000        old.id = "20260101-000000-old0".to_owned();
8001        queue.put(&mut old).unwrap();
8002        let mut fresh = task();
8003        fresh.id = "20260101-000000-new0".to_owned();
8004        queue.put(&mut fresh).unwrap();
8005
8006        // No parseable pid at all, so age is the only signal there is to
8007        // check - unlike a real `Queue::claim`, which always names a real,
8008        // and therefore alive, pid this test cannot fake as dead.
8009        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8010        std::thread::sleep(Duration::from_millis(60));
8011        let live = queue.claim(&fresh.id).unwrap();
8012
8013        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8014        assert_eq!(swept, vec![old.id.clone()]);
8015        assert!(
8016            queue.claim(&old.id).is_ok(),
8017            "an unparseable lock older than the threshold is swept"
8018        );
8019        assert!(
8020            queue.claim(&fresh.id).is_err(),
8021            "a live pid protects its lock regardless of age"
8022        );
8023        drop(live);
8024    }
8025
8026    #[test]
8027    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8028        // A live worker's claim remains authoritative even beyond the sweep's
8029        // age limit. Sweeping it would permit a second competing attempt.
8030        let dir = tempfile::tempdir().unwrap();
8031        let queue = Queue::at(dir.path().to_path_buf());
8032        let mut t = task();
8033        t.id = "20260101-000000-live".to_owned();
8034        queue.put(&mut t).unwrap();
8035
8036        let claim = queue.claim(&t.id).unwrap();
8037        std::thread::sleep(Duration::from_millis(60));
8038
8039        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8040        assert!(
8041            swept.is_empty(),
8042            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8043        );
8044        assert!(
8045            queue.claim(&t.id).is_err(),
8046            "the lock still protects its task"
8047        );
8048        drop(claim);
8049    }
8050
8051    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8052    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8053    fn injected_dead_pid() -> u32 {
8054        std::process::id().checked_add(1).unwrap_or(1)
8055    }
8056
8057    #[test]
8058    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8059        let dir = tempfile::tempdir().unwrap();
8060        let queue = Queue::at(dir.path().to_path_buf());
8061        let mut t = task();
8062        t.id = "20260101-000000-dead".to_owned();
8063        queue.put(&mut t).unwrap();
8064        let dead_pid = injected_dead_pid();
8065
8066        // Written directly rather than through `Queue::claim`, which would
8067        // stamp this test process's own very much alive pid and defeat the
8068        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8069        // like moments after it died, not six hours later.
8070        std::fs::write(
8071            dir.path().join(format!("{}.lock", t.id)),
8072            dead_pid.to_string(),
8073        )
8074        .unwrap();
8075
8076        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8077            pid != dead_pid
8078        });
8079        assert_eq!(
8080            swept,
8081            vec![t.id.clone()],
8082            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8083        );
8084        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8085    }
8086
8087    #[test]
8088    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8089        let dir = tempfile::tempdir().unwrap();
8090        let queue = Queue::at(dir.path().to_path_buf());
8091        let mut t = task();
8092        t.id = "20260101-000000-late".to_owned();
8093        queue.put(&mut t).unwrap();
8094        let dead_pid = injected_dead_pid();
8095
8096        // Tick one, standing in for the sweep `poll` already runs at
8097        // startup: nothing to find yet.
8098        assert!(
8099            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8100            "nothing has claimed the task yet"
8101        );
8102
8103        // A second daemon claims the task and dies before it ever writes
8104        // `running`, well after this loop's own startup sweep already ran.
8105        std::fs::write(
8106            dir.path().join(format!("{}.lock", t.id)),
8107            dead_pid.to_string(),
8108        )
8109        .unwrap();
8110
8111        // Tick two, standing in for a poll long into this daemon's uptime:
8112        // the same function, called again, notices what only just appeared -
8113        // proving the sweep is not a one-shot startup check.
8114        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8115            pid != dead_pid
8116        });
8117        assert_eq!(swept, vec![t.id.clone()]);
8118    }
8119
8120    #[test]
8121    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8122        // `reclaim_orphaned_running` looks up the task's last run, which
8123        // touches `run::home()`; the first call anywhere in this binary wins,
8124        // so this is a no-op if another test already pinned one, and either
8125        // way the run id below is never written under it.
8126        crate::run::pin_test_home();
8127        let dir = tempfile::tempdir().unwrap();
8128        let queue = Queue::at(dir.path().to_path_buf());
8129        let mut t = task();
8130        t.id = "20260101-000000-crsh".to_owned();
8131        t.status = TaskStatus::Running;
8132        t.attempts = 1;
8133        // No `run.json` behind this id: standing in for a run this test does
8134        // not need to make readable, since the point is the lock, not the
8135        // recovery table `reclaim` already has its own tests for.
8136        t.runs.push("20260904-000000-4043".to_owned());
8137        queue.put(&mut t).unwrap();
8138        let dead_pid = injected_dead_pid();
8139
8140        // The crashed daemon's own claim, naming a pid nothing on the
8141        // machine holds anymore.
8142        std::fs::write(
8143            dir.path().join(format!("{}.lock", t.id)),
8144            dead_pid.to_string(),
8145        )
8146        .unwrap();
8147
8148        // Before the lock is swept the task looks claimed, and
8149        // `reclaim_orphaned_running` must leave it alone - this is exactly
8150        // the bug: a `running` task stranded behind a dead daemon's lock,
8151        // invisible to the claim-as-proof check because the lock outlived
8152        // the process that wrote it.
8153        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8154        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8155
8156        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8157            pid != dead_pid
8158        });
8159        assert_eq!(swept, vec![t.id.clone()]);
8160
8161        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8162        assert_eq!(reclaimed, vec![t.id.clone()]);
8163        let after = queue.get(&t.id).unwrap();
8164        assert_eq!(
8165            after.status,
8166            TaskStatus::Held,
8167            "no run.json to recover from, so a human is asked"
8168        );
8169        assert_eq!(
8170            after.runs,
8171            vec!["20260904-000000-4043".to_owned()],
8172            "the crashed run's id is kept as evidence, not discarded"
8173        );
8174    }
8175
8176    #[test]
8177    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8178        let dir = tempfile::tempdir().unwrap();
8179        let queue = Queue::at(dir.path().to_path_buf());
8180        let mut t = task();
8181        t.id = "20260101-000000-unknown".to_owned();
8182        queue.put(&mut t).unwrap();
8183        let dead_pid = injected_dead_pid();
8184        std::fs::write(
8185            dir.path().join(format!("{}.lock", t.id)),
8186            dead_pid.to_string(),
8187        )
8188        .unwrap();
8189
8190        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8191        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8192        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8193    }
8194
8195    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8196        let mut s = run_state(status);
8197        s.config.graph.language = language.to_owned();
8198        s
8199    }
8200
8201    fn unstarted_verdict(status: RunStatus) -> Verdict {
8202        Verdict {
8203            status,
8204            left_pr: false,
8205            quota_hit: false,
8206            parked: false,
8207            no_viable_candidates: false,
8208        }
8209    }
8210
8211    #[test]
8212    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8213        let mut t = task();
8214        t.attempts = 1;
8215        settle_in(
8216            &mut t,
8217            unstarted_verdict(RunStatus::AlreadyInBase),
8218            "already in main",
8219            1,
8220            phrases("en"),
8221        );
8222        assert_eq!(t.status, TaskStatus::Done);
8223        assert_eq!(t.attempts, 0);
8224    }
8225
8226    #[test]
8227    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8228        let reason = |language: &str| {
8229            let mut t = task();
8230            settle_in(
8231                &mut t,
8232                unstarted_verdict(RunStatus::Judging),
8233                "boom",
8234                1,
8235                phrases(language),
8236            );
8237            t.last_error.or(t.hold_reason).unwrap_or_default()
8238        };
8239        assert!(
8240            reason("en").starts_with("the graph stopped at `"),
8241            "{}",
8242            reason("en")
8243        );
8244        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8245        assert!(reason("日本語").contains("boom"));
8246        assert_eq!(reason("fr"), reason("en"));
8247    }
8248
8249    #[test]
8250    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8251        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8252        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8253        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8254        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8255        assert!(ja.contains("[run "), "{ja}");
8256        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8257        assert!(ended.starts_with("run 終了: "), "{ended}");
8258        let mut de = run_state_in(RunStatus::Failed, "de");
8259        let mut en = run_state_in(RunStatus::Failed, "en");
8260        de.id = "same".to_owned();
8261        en.id = "same".to_owned();
8262        assert_eq!(describe(&de), describe(&en));
8263    }
8264
8265    #[test]
8266    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8267        use crate::handover::Refused;
8268        let cases = [
8269            Refused::Foreign {
8270                branch: "b".into(),
8271                path: "/w/x".into(),
8272                why: "made by hand".into(),
8273            },
8274            Refused::Unsafe {
8275                branch: "b".into(),
8276                path: "/w/x".into(),
8277                why: "its worktree has uncommitted changes (a.rs)".into(),
8278            },
8279            Refused::ReleaseFailed {
8280                branch: "b".into(),
8281                path: "/w/x".into(),
8282                run: "ab12".into(),
8283            },
8284        ];
8285        for r in &cases {
8286            let en = (phrases("en").handover_refused)(r);
8287            assert_eq!(en, r.to_string());
8288            let ja = (phrases("ja").handover_refused)(r);
8289            assert!(
8290                !ja.contains("is checked out") && !ja.contains("try again"),
8291                "{ja}"
8292            );
8293            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8294            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8295                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8296            }
8297        }
8298        assert!(phrases("en").handover_hint.contains("release the task"));
8299        assert!(phrases("ja").handover_hint.contains("解放"));
8300    }
8301
8302    #[test]
8303    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8304        let build = |lang: &str| {
8305            let mut s = run_state_in(RunStatus::Blocked, lang);
8306            s.id = "same".to_owned();
8307            s.config.graph.review_rounds = 3;
8308            let mut r = review_round(3);
8309            r.expected = 3;
8310            r.answered = 1;
8311            s.reviews.push(r);
8312            s.event(
8313                "review",
8314                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8315            );
8316            s
8317        };
8318        let en = describe(&build("en"));
8319        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8320        let ja = describe(&build("ja"));
8321        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8322        assert!(!ja.contains("never answered"), "{ja}");
8323        assert!(ja.contains("[run "), "{ja}");
8324
8325        // An incomplete panel whose verification failed is a different stop:
8326        // the real event must survive in ja too.
8327        let mut failed = build("ja");
8328        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8329            command: "cargo test".to_owned(),
8330            code: Some(1),
8331            output_tail: String::new(),
8332            duration_ms: 0,
8333            resource_blocked: false,
8334        });
8335        failed.event("review", "stopped; e2e failed: cargo test");
8336        let ja = describe(&failed);
8337        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8338        assert!(!ja.contains("席のレビュアー"), "{ja}");
8339    }
8340
8341    #[test]
8342    fn refusals_and_recovery_prose_follow_the_language() {
8343        let t = held_task_with("r1");
8344        let q = action_question(
8345            "r1",
8346            ask::ChoiceAction::Resume {
8347                run: "r1".to_owned(),
8348            },
8349        );
8350        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
8351            ActionDecision::Refuse(s) => s,
8352            other => panic!("{other:?}"),
8353        };
8354        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8355        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8356        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8357
8358        let mut held = task();
8359        reclaim(&mut held, None, 2, "ja");
8360        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8361        let mut held = task();
8362        reclaim(&mut held, None, 2, "xx");
8363        assert!(held.hold_reason.unwrap().contains("held for a human"));
8364    }
8365
8366    fn run_state(status: RunStatus) -> RunState {
8367        let mut state = RunState::new(
8368            PathBuf::from("/repo"),
8369            "main".to_owned(),
8370            "abc1234def".to_owned(),
8371            "add retries".to_owned(),
8372            Config::default(),
8373        );
8374        state.status = status;
8375        state
8376    }
8377
8378    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8379        Candidate {
8380            index: 0,
8381            label,
8382            agent: "claude".to_owned(),
8383            branch: format!("magi/x/{label}"),
8384            worktree: PathBuf::from("/repo"),
8385            summary: summary.to_owned(),
8386            stat: String::new(),
8387            files: 0,
8388            commits: usize::from(!empty),
8389            empty,
8390            failed: failed.map(str::to_owned),
8391            verified_noop: None,
8392            duration_ms: 0,
8393            folded: false,
8394        }
8395    }
8396
8397    #[test]
8398    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8399        let mut state = run_state(RunStatus::Blocked);
8400        state.gate = vec![
8401            CommandOutcome {
8402                command: "cargo make check".to_owned(),
8403                code: Some(0),
8404                output_tail: "ok".to_owned(),
8405                duration_ms: 0,
8406                resource_blocked: false,
8407            },
8408            CommandOutcome {
8409                command: "cargo test".to_owned(),
8410                code: Some(101),
8411                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8412                duration_ms: 0,
8413                resource_blocked: false,
8414            },
8415        ];
8416        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8417        assert!(d.contains("cargo test"), "{d}");
8418        assert!(
8419            !d.contains("cargo make check"),
8420            "a passing check is not a diagnostic: {d}"
8421        );
8422        assert!(d.contains("assertion failed"), "{d}");
8423    }
8424
8425    #[test]
8426    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8427        let mut state = run_state(RunStatus::Blocked);
8428        state.event(
8429            "land",
8430            "stopped: the fixer produced no commit while 2 check(s) were failing \
8431             (build, lint); stopping instead of looping on an unchanged tree",
8432        );
8433        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8434        assert!(d.contains("build"), "{d}");
8435        assert!(d.contains("lint"), "{d}");
8436        assert!(d.contains("fixer produced no commit"), "{d}");
8437    }
8438
8439    #[test]
8440    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8441        // `describe`'s output becomes `Task::last_error` verbatim, and the
8442        // phone renders that in the same alarm-styled box an ordinary
8443        // failure gets. A bare `verified_noop` there would read exactly like
8444        // the failure this status exists to be told apart from.
8445        let state = run_state(RunStatus::VerifiedNoop);
8446        let d = describe(&state);
8447        assert!(
8448            d.contains("agent-verified no-op"),
8449            "expected the display label, not the wire spelling: {d}"
8450        );
8451        assert!(!d.contains("verified_noop"), "{d}");
8452    }
8453
8454    #[test]
8455    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8456        let mut state = run_state(RunStatus::Failed);
8457        state.gate.push(crate::run::CommandOutcome {
8458            command: "cargo test".into(),
8459            code: Some(101),
8460            output_tail: format!(
8461                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8462                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8463            ),
8464            duration_ms: 1,
8465            resource_blocked: false,
8466        });
8467        let d = diagnostic(&state).unwrap();
8468        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8469        assert!(d.contains("assertion failed: widget missing"));
8470        assert!(d.contains("widget log"));
8471    }
8472
8473    #[test]
8474    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8475        // The whole point of the feature: a run held as "no candidate produced
8476        // a change" can mean the implementer actually finished the task and
8477        // only left a clean local tree behind - see AGENTS.md on this exact
8478        // failure mode. The diagnostic has to carry what the agent actually
8479        // said, not just the fact that nothing was there to judge.
8480        let mut state = run_state(RunStatus::Failed);
8481        state.candidates = vec![candidate(
8482            'A',
8483            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8484            true,
8485            None,
8486        )];
8487        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8488        assert!(d.contains("candidate A"), "{d}");
8489        assert!(d.contains("tagged v1.2.3"), "{d}");
8490    }
8491
8492    #[test]
8493    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8494        let mut state = run_state(RunStatus::Failed);
8495        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8496        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8497        assert!(d.contains("candidate A"), "{d}");
8498        assert!(d.contains("agent timed out"), "{d}");
8499    }
8500
8501    #[test]
8502    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8503        // A viable candidate existed, the gate never ran, and nothing land
8504        // said matches - `Task::last_error` is left to explain this one alone.
8505        let mut state = run_state(RunStatus::Failed);
8506        state.candidates = vec![candidate('A', "did the work", false, None)];
8507        assert!(diagnostic(&state).is_none());
8508    }
8509
8510    #[test]
8511    fn diagnostic_is_bounded_however_much_a_run_printed() {
8512        let mut state = run_state(RunStatus::Blocked);
8513        state.gate = vec![
8514            CommandOutcome {
8515                command: "cargo test".to_owned(),
8516                code: Some(101),
8517                output_tail: "x".repeat(50_000),
8518                duration_ms: 0,
8519                resource_blocked: false,
8520            },
8521            CommandOutcome {
8522                command: "cargo clippy".to_owned(),
8523                code: Some(1),
8524                output_tail: "y".repeat(50_000),
8525                duration_ms: 0,
8526                resource_blocked: false,
8527            },
8528        ];
8529        state.candidates = vec![
8530            candidate('A', &"z".repeat(50_000), true, None),
8531            candidate('B', &"w".repeat(50_000), true, None),
8532        ];
8533        let d = diagnostic(&state).expect("plenty here to diagnose");
8534        assert!(
8535            d.len() <= DIAGNOSTIC_MAX,
8536            "diagnostic grew to {} bytes, unbounded",
8537            d.len()
8538        );
8539    }
8540
8541    #[test]
8542    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8543        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8544            let mut t = task();
8545            let mut state = run_state(status);
8546            t.pr_recovery = Some(crate::pr_recovery::Selection {
8547                url: "url".into(),
8548                branch: format!("magi/task-{}", t.id),
8549                head: "a".repeat(40),
8550                source_head: None,
8551                source_run: None,
8552                source_proof: None,
8553                disposition: Some(crate::pr_recovery::Disposition::Land),
8554                instruction: t.instruction.clone(),
8555                approved_at: Timestamp::now(),
8556            });
8557            state.pr_recovery = t.pr_recovery.clone();
8558            t.start(state.id.clone());
8559            settle_and_diagnose(
8560                &mut t,
8561                Verdict {
8562                    status,
8563                    left_pr: false,
8564                    quota_hit: false,
8565                    parked: false,
8566                    no_viable_candidates: false,
8567                },
8568                "delivery stopped",
8569                5,
8570                &state,
8571            );
8572            assert_eq!(t.status, TaskStatus::Held);
8573            let reason = t.hold_reason.as_deref().unwrap();
8574            if status == RunStatus::Ready {
8575                assert!(reason.contains("Selected PR delivery is incomplete"));
8576                assert!(t.recovery_budget.is_none());
8577            } else {
8578                assert!(reason.contains("Selected recovery stopped"));
8579                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8580            }
8581            assert!(t.pr_recovery.is_some());
8582        }
8583    }
8584
8585    #[test]
8586    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8587        let mut state = run_state(RunStatus::Voting);
8588        state.base_sync = Some(crate::run::BaseSync {
8589            tip: "base-tip".into(),
8590            behind: 3,
8591            attempts: 4,
8592            conflict: Some("base stopped".into()),
8593            already_in: None,
8594        });
8595        state.record_base_sync_stop("candidate-head");
8596        let mut t = task();
8597        t.start(state.id.clone());
8598        let verdict = Verdict {
8599            status: RunStatus::Blocked,
8600            left_pr: false,
8601            quota_hit: false,
8602            parked: false,
8603            no_viable_candidates: false,
8604        };
8605        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8606        assert_eq!(
8607            t.status,
8608            TaskStatus::Held,
8609            "unspent task attempts cannot start another competition"
8610        );
8611        let at = t.held_at;
8612        let cause = t.hold_notice_cause.clone();
8613        state.begin_pass();
8614        t.release_operator("test-resume", None);
8615        t.start(state.id.clone());
8616        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8617        assert_eq!(t.status, TaskStatus::Held);
8618        assert_eq!(t.held_at, at);
8619        assert_eq!(t.hold_notice_cause, cause);
8620    }
8621
8622    #[test]
8623    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8624        let mut state = run_state(RunStatus::Blocked);
8625        state.gate = vec![CommandOutcome {
8626            command: "cargo test".to_owned(),
8627            code: Some(101),
8628            output_tail: "assertion failed".to_owned(),
8629            duration_ms: 0,
8630            resource_blocked: false,
8631        }];
8632        let verdict = Verdict {
8633            status: RunStatus::Blocked,
8634            left_pr: false,
8635            quota_hit: false,
8636            parked: false,
8637            no_viable_candidates: false,
8638        };
8639
8640        // Attempt one of two still has a retry coming: no diagnostic yet, the
8641        // task is going to run again and this run's evidence would go stale.
8642        let mut t = task();
8643        t.start("run-1".to_owned());
8644        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8645        assert_eq!(t.status, TaskStatus::Failed);
8646        assert!(t.diagnostic.is_none());
8647
8648        // Attempt two exhausts the budget: now it is held, and the
8649        // diagnostic is what `magi task show` has to say more than one line.
8650        t.start("run-2".to_owned());
8651        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8652        assert_eq!(t.status, TaskStatus::Held);
8653        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8654        assert!(d.contains("cargo test"), "{d}");
8655    }
8656
8657    #[test]
8658    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8659        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8660        // `magi ask` question settled Held with `hold_reason: null`, so the
8661        // notification said nothing actionable. `note_open_question` should
8662        // append the question id to whatever `handed_off` already wrote.
8663        crate::run::pin_test_home();
8664        let home = crate::run::home();
8665        let state = run_state(RunStatus::VerifiedNoop);
8666        let mut q = ask::Question::new(
8667            state.id.clone(),
8668            "implement".to_owned(),
8669            "impl-A".to_owned(),
8670            "is this really a no-op?".to_owned(),
8671            String::new(),
8672            Vec::new(),
8673        );
8674        Questions::at(home.join("questions")).put(&mut q).unwrap();
8675
8676        let verdict = Verdict {
8677            status: RunStatus::VerifiedNoop,
8678            left_pr: false,
8679            quota_hit: false,
8680            parked: false,
8681            no_viable_candidates: false,
8682        };
8683        let mut t = task();
8684        t.start(state.id.clone());
8685        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8686
8687        assert_eq!(t.status, TaskStatus::Held);
8688        let reason = t.hold_reason.expect("a held task must record why");
8689        assert!(
8690            reason.starts_with("run ended agent-verified no-op"),
8691            "the original settle reason must survive unchanged: {reason}"
8692        );
8693        assert!(
8694            reason.contains(q.short()),
8695            "the open question's id must be named so the notice is actionable: {reason}"
8696        );
8697    }
8698
8699    #[test]
8700    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8701        crate::run::pin_test_home();
8702        let state = run_state(RunStatus::VerifiedNoop);
8703
8704        let verdict = Verdict {
8705            status: RunStatus::VerifiedNoop,
8706            left_pr: false,
8707            quota_hit: false,
8708            parked: false,
8709            no_viable_candidates: false,
8710        };
8711        let mut t = task();
8712        t.start(state.id.clone());
8713        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8714
8715        assert_eq!(t.status, TaskStatus::Held);
8716        assert_eq!(
8717            t.hold_reason.as_deref(),
8718            Some("run ended agent-verified no-op"),
8719            "nothing to append when the question was already answered or never asked"
8720        );
8721    }
8722
8723    #[test]
8724    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8725        crate::run::pin_test_home();
8726        let mut first = run_state(RunStatus::Blocked);
8727        first.id = "20260101-000000-sup1".to_owned();
8728        first.save().unwrap();
8729        let mut second = run_state(RunStatus::Merged);
8730        second.id = "20260101-000000-sup2".to_owned();
8731        second.save().unwrap();
8732
8733        let mut t = task();
8734        t.runs = vec![first.id.clone(), second.id.clone()];
8735        t.status = TaskStatus::Done;
8736
8737        supersede_prior_runs(&t, &crate::run::home());
8738
8739        assert_eq!(
8740            RunState::load(&first.id).unwrap().status,
8741            RunStatus::Superseded,
8742            "the first attempt's Blocked no longer needs anyone's attention"
8743        );
8744        assert_eq!(
8745            RunState::load(&second.id).unwrap().status,
8746            RunStatus::Merged,
8747            "the run that actually succeeded is left exactly as it was"
8748        );
8749    }
8750
8751    #[test]
8752    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8753        // `is_working_on` alone only proves a *daemon* claim; a `magi run
8754        // --resume` invoked by hand outside the daemon never touches
8755        // `daemon.json` at all, so it would look identical to a genuinely
8756        // idle run without also consulting `RunState::liveness`, which reads
8757        // this run's own recorded `driver_pid` instead.
8758        crate::run::pin_test_home();
8759        let mut first = run_state(RunStatus::Blocked);
8760        first.id = "20260101-000000-sup9".to_owned();
8761        // This test process's own pid: guaranteed alive without needing a
8762        // real second process or daemon.
8763        first.driver_pid = Some(std::process::id());
8764        first.driver_started_at = Some(
8765            crate::proc::process_started_at(std::process::id())
8766                .expect("this test process's own start time must be queryable"),
8767        );
8768        first.save().unwrap();
8769        let mut second = run_state(RunStatus::Merged);
8770        second.id = "20260101-000000-supa".to_owned();
8771        second.save().unwrap();
8772
8773        let mut t = task();
8774        t.runs = vec![first.id.clone(), second.id.clone()];
8775        t.status = TaskStatus::Done;
8776
8777        supersede_prior_runs(&t, &crate::run::home());
8778
8779        assert_eq!(
8780            RunState::load(&first.id).unwrap().status,
8781            RunStatus::Blocked,
8782            "a live driver_pid means something is still actually working this run, \
8783             even though no daemon claims it - rewriting under it would just be \
8784             undone the next time that process saves"
8785        );
8786    }
8787
8788    #[test]
8789    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8790        // The first resweep must skip a still-live attempt exactly like
8791        // `supersede_prior_runs` itself does; a later resweep, once that
8792        // process is no longer actually driving it, is what closes the gap
8793        // `supersede_prior_runs` alone leaves - a task only ever reaches
8794        // `Done` once, so nothing else would ever look at this run again.
8795        let dir = tempfile::tempdir().unwrap();
8796        let home = dir.path().to_path_buf();
8797        let queue = Queue::at(dir.path().join("queue"));
8798
8799        let mut first = run_state(RunStatus::Blocked);
8800        first.id = "20260101-000000-supd".to_owned();
8801        first.driver_pid = Some(std::process::id());
8802        first.driver_started_at = Some(
8803            crate::proc::process_started_at(std::process::id())
8804                .expect("this test process's own start time must be queryable"),
8805        );
8806        first.save_under(&home).unwrap();
8807        let mut second = run_state(RunStatus::Merged);
8808        second.id = "20260101-000000-supe".to_owned();
8809        second.save_under(&home).unwrap();
8810
8811        let mut t = task();
8812        t.runs = vec![first.id.clone(), second.id.clone()];
8813        t.status = TaskStatus::Done;
8814        queue.put(&mut t).unwrap();
8815
8816        resweep_superseded_attempts(&queue, &home);
8817        assert_eq!(
8818            RunState::load_under(&first.id, &home).unwrap().status,
8819            RunStatus::Blocked,
8820            "still live on the first pass, so still untouched"
8821        );
8822
8823        // Stand in for the manual process no longer being the one driving
8824        // this run: same pid (this test process really is still alive), but
8825        // an identity marker that no longer matches it - see
8826        // `RunState::liveness`'s own doc for why a mismatched
8827        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
8828        let mut stale = RunState::load_under(&first.id, &home).unwrap();
8829        stale.driver_started_at = Some("1".to_owned());
8830        stale.save_under(&home).unwrap();
8831
8832        resweep_superseded_attempts(&queue, &home);
8833        assert_eq!(
8834            RunState::load_under(&first.id, &home).unwrap().status,
8835            RunStatus::Superseded,
8836            "the second pass catches up what the first one correctly skipped"
8837        );
8838    }
8839
8840    #[test]
8841    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8842        crate::run::pin_test_home();
8843        let mut first = run_state(RunStatus::Blocked);
8844        first.id = "20260101-000000-sup3".to_owned();
8845        first.save().unwrap();
8846        let mut second = run_state(RunStatus::Blocked);
8847        second.id = "20260101-000000-sup4".to_owned();
8848        second.save().unwrap();
8849
8850        let mut t = task();
8851        t.runs = vec![first.id.clone(), second.id.clone()];
8852        // Still retrying: nothing about this task's story is settled yet, so
8853        // neither Blocked run may be relabelled, even though a later attempt
8854        // already exists.
8855        t.status = TaskStatus::Failed;
8856
8857        supersede_prior_runs(&t, &crate::run::home());
8858
8859        assert_eq!(
8860            RunState::load(&first.id).unwrap().status,
8861            RunStatus::Blocked
8862        );
8863        assert_eq!(
8864            RunState::load(&second.id).unwrap().status,
8865            RunStatus::Blocked
8866        );
8867    }
8868
8869    #[test]
8870    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
8871        // `magi task done` (or the API's equivalent) can close a task with no
8872        // run of its own ever having succeeded - there is nothing here that
8873        // counts as "the attempt that finished it", so nothing is rewritten.
8874        crate::run::pin_test_home();
8875        let mut first = run_state(RunStatus::Blocked);
8876        first.id = "20260101-000000-sup5".to_owned();
8877        first.save().unwrap();
8878
8879        let mut t = task();
8880        t.runs = vec![first.id.clone()];
8881        t.status = TaskStatus::Done;
8882
8883        supersede_prior_runs(&t, &crate::run::home());
8884
8885        assert_eq!(
8886            RunState::load(&first.id).unwrap().status,
8887            RunStatus::Blocked,
8888            "a single-attempt task has no earlier run to supersede"
8889        );
8890    }
8891
8892    #[test]
8893    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
8894        // `magi task done` (or the web/conductor equivalents) can close a
8895        // task in any status, including one whose *last* recorded attempt is
8896        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
8897        // never watched, say. `runs.last()` being `Done`-adjacent is not
8898        // proof it actually succeeded, so nothing earlier may be relabelled
8899        // on its say-so alone.
8900        crate::run::pin_test_home();
8901        let mut first = run_state(RunStatus::Blocked);
8902        first.id = "20260101-000000-supb".to_owned();
8903        first.save().unwrap();
8904        let mut second = run_state(RunStatus::Failed);
8905        second.id = "20260101-000000-supc".to_owned();
8906        second.save().unwrap();
8907
8908        let mut t = task();
8909        t.runs = vec![first.id.clone(), second.id.clone()];
8910        t.status = TaskStatus::Done;
8911
8912        supersede_prior_runs(&t, &crate::run::home());
8913
8914        assert_eq!(
8915            RunState::load(&first.id).unwrap().status,
8916            RunStatus::Blocked,
8917            "the task's last attempt never landed, so there is nothing here \
8918             actually superseding it"
8919        );
8920    }
8921
8922    #[test]
8923    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
8924        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
8925        // to look" - `Failed` and `VerifiedNoop` are already their own
8926        // terminal answers and must not be relabelled into a third one.
8927        crate::run::pin_test_home();
8928        let mut failed = run_state(RunStatus::Failed);
8929        failed.id = "20260101-000000-sup6".to_owned();
8930        failed.save().unwrap();
8931        let mut noop = run_state(RunStatus::VerifiedNoop);
8932        noop.id = "20260101-000000-sup7".to_owned();
8933        noop.save().unwrap();
8934        let mut winner = run_state(RunStatus::Ready);
8935        winner.id = "20260101-000000-sup8".to_owned();
8936        winner.save().unwrap();
8937
8938        let mut t = task();
8939        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
8940        t.status = TaskStatus::Done;
8941
8942        supersede_prior_runs(&t, &crate::run::home());
8943
8944        assert_eq!(
8945            RunState::load(&failed.id).unwrap().status,
8946            RunStatus::Failed
8947        );
8948        assert_eq!(
8949            RunState::load(&noop.id).unwrap().status,
8950            RunStatus::VerifiedNoop
8951        );
8952    }
8953
8954    fn approval_question(run: &str) -> ask::Question {
8955        ask::Question::new(
8956            run.to_owned(),
8957            land::APPROVAL_NODE.to_owned(),
8958            "land".to_owned(),
8959            "merge?".to_owned(),
8960            String::new(),
8961            vec!["merge".to_owned(), "hold".to_owned()],
8962        )
8963    }
8964
8965    #[test]
8966    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
8967        crate::run::pin_test_home();
8968        let mut state = run_state(RunStatus::Landing);
8969        state.id = "20260101-000000-fre1".to_owned();
8970        state.parked = true;
8971        state.save().unwrap();
8972        ask::Questions::open()
8973            .put(&mut approval_question(&state.id))
8974            .unwrap();
8975
8976        let mut t = task();
8977        t.runs.push(state.id.clone());
8978        assert_eq!(
8979            land_resume_state(&t),
8980            LandResume::StillWaiting,
8981            "nobody has answered and the timeout has not passed"
8982        );
8983    }
8984
8985    #[test]
8986    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
8987        crate::run::pin_test_home();
8988        let mut state = run_state(RunStatus::Gating);
8989        state.id = "20260101-000000-gt01".to_owned();
8990        state.parked = true;
8991        state.config.graph.answer_timeout = 60;
8992        state.github_text = Some(crate::run::GithubTextAsk {
8993            rewrite: None,
8994            fingerprint: "f".into(),
8995            title: true,
8996            body: false,
8997            categories: vec!["title-language".into()],
8998            question: None,
8999            asks: 1,
9000            resolved: false,
9001            chosen_title: None,
9002            choice: None,
9003        });
9004        state.save().unwrap();
9005        let store = ask::Questions::open();
9006        let mut q = ask::Question::new(
9007            state.id.clone(),
9008            crate::github_text::ASK_NODE.to_owned(),
9009            crate::github_text::ASK_SEAT.to_owned(),
9010            "s".into(),
9011            String::new(),
9012            vec!["use fallback".into()],
9013        );
9014        store.put(&mut q).unwrap();
9015        let mut t = task();
9016        t.runs.push(state.id.clone());
9017        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9018        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9019        store.put(&mut q).unwrap();
9020        assert_eq!(land_resume_state(&t), LandResume::Ready);
9021        assert!(!store.get(&q.id).unwrap().status.open());
9022        // Once decided, a parked run is an ordinary candidate again.
9023        state.github_text.as_mut().unwrap().resolved = true;
9024        state.save().unwrap();
9025        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9026    }
9027
9028    #[test]
9029    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9030        // `ask::ask_and_wait`'s own deadline used to retire a question
9031        // nobody answered; land's approval bypasses that wait (see
9032        // `land::approval_gate`), so this is now the only place
9033        // `graph.answer_timeout` is enforced for a land approval at all.
9034        crate::run::pin_test_home();
9035        let mut state = run_state(RunStatus::Landing);
9036        state.id = "20260101-000000-exp1".to_owned();
9037        state.parked = true;
9038        state.config.graph.answer_timeout = 60;
9039        state.save().unwrap();
9040
9041        let store = ask::Questions::open();
9042        let mut q = approval_question(&state.id);
9043        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9044        store.put(&mut q).unwrap();
9045
9046        let mut t = task();
9047        t.runs.push(state.id.clone());
9048        assert_eq!(
9049            land_resume_state(&t),
9050            LandResume::Ready,
9051            "an expired question must not be waited on forever"
9052        );
9053
9054        let after = store.get(&q.id).unwrap();
9055        assert!(
9056            !after.status.open(),
9057            "the question is abandoned, not silently ignored"
9058        );
9059        assert!(
9060            after.resolution().is_none(),
9061            "an abandoned question is not read as a decision"
9062        );
9063    }
9064
9065    #[test]
9066    fn reclaim_settles_a_running_task_against_its_last_run() {
9067        let mut t = task();
9068        t.start("20260904-000000-4043".to_owned());
9069        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9070        assert_eq!(
9071            t.status,
9072            TaskStatus::Done,
9073            "a run that actually finished must not stay `running` forever"
9074        );
9075    }
9076
9077    #[test]
9078    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9079        let mut t = task();
9080        t.start("20260904-000000-4043".to_owned());
9081        t.last_error = Some("earlier trouble".to_owned());
9082        let mut state = run_state(RunStatus::Judging);
9083        state.parked = true;
9084        reclaim(&mut t, Some(state), 1, "en");
9085        assert_eq!(t.status, TaskStatus::Parked);
9086        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9087        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9088        assert!(t.park_reason.is_some());
9089        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9090        assert!(!t.fresh_start);
9091        assert!(t.status.runnable());
9092    }
9093
9094    #[test]
9095    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9096        let mut t = task();
9097        t.start("20260904-000000-4043".to_owned());
9098        t.last_error = Some("earlier trouble".to_owned());
9099        settle(
9100            &mut t,
9101            Verdict {
9102                status: RunStatus::Judging,
9103                left_pr: false,
9104                quota_hit: false,
9105                parked: true,
9106                no_viable_candidates: false,
9107            },
9108            "parked after `judging`",
9109            1,
9110        );
9111        assert_eq!(t.status, TaskStatus::Parked);
9112        assert_eq!(t.attempts, 0);
9113        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9114        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9115        assert_eq!(t.schema, crate::queue::SCHEMA);
9116        assert!(
9117            crate::notices::task_held(&t).is_none(),
9118            "a park is not news"
9119        );
9120        t.start("20260904-000000-4043".to_owned());
9121        assert_eq!(t.park_reason, None);
9122    }
9123
9124    #[test]
9125    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9126        // A blocked run with attempts left goes back to `Failed`, exactly as
9127        // it would from `attempt` itself - `reclaim` must not invent a second
9128        // policy for a task a daemon merely stopped without reporting.
9129        let mut t = task();
9130        t.start("20260904-000000-4043".to_owned());
9131        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9132        assert_eq!(t.status, TaskStatus::Failed);
9133        assert!(t.status.runnable());
9134    }
9135
9136    #[test]
9137    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9138        let mut t = task();
9139        t.start("20260904-000000-4043".to_owned());
9140        assert_eq!(t.attempts, 1);
9141        let mut run = run_state(RunStatus::Implementing);
9142        run.id = "20260904-000000-4043".to_owned();
9143        run.begin_pass();
9144        let cause = crate::run::ParkCause::Upgrade {
9145            from: "0.121.0".to_owned(),
9146            to: Some("0.121.1".to_owned()),
9147        };
9148        run.end_pass_parked(cause.clone());
9149        run.parked = true;
9150        let verdict = Verdict {
9151            status: run.status,
9152            left_pr: false,
9153            quota_hit: false,
9154            parked: true,
9155            no_viable_candidates: false,
9156        };
9157        // A crash after the checkpoint but before queue settlement must
9158        // recover exactly the same scheduling evidence and refund.
9159        let mut orphan = t.clone();
9160        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9161        assert_eq!(orphan.status, TaskStatus::Parked);
9162        assert_eq!(orphan.attempts, 0);
9163        assert_eq!(
9164            orphan.upgrade_resume_key(),
9165            Some((run.passes[0].started_at, orphan.id.as_str()))
9166        );
9167        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9168        assert_eq!(t.attempts, 0);
9169        assert_eq!(t.passes.len(), 1);
9170        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9171        assert_eq!(t.passes[0].parked, Some(cause));
9172        assert_eq!(t.passes[0].pass_index, 0);
9173        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9174        assert!(t.upgrade_resume_key().is_some());
9175
9176        // A resumed pass that then fails spends its attempt, and the earlier
9177        // pass's entry is untouched.
9178        t.start("20260904-000000-4043".to_owned());
9179        run.begin_pass();
9180        run.status = RunStatus::Failed;
9181        let verdict = Verdict {
9182            status: RunStatus::Failed,
9183            left_pr: false,
9184            quota_hit: false,
9185            parked: false,
9186            no_viable_candidates: false,
9187        };
9188        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9189        assert_eq!(t.passes.len(), 2);
9190        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9191        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9192        assert_eq!(t.passes[1].pass_index, 1);
9193        assert_eq!(t.attempts, 1);
9194    }
9195
9196    #[test]
9197    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9198        let mut t = task();
9199        t.start("20260904-000000-4043".to_owned());
9200        reclaim(&mut t, None, 2, "en");
9201        assert_eq!(t.status, TaskStatus::Held);
9202        assert!(
9203            t.last_error
9204                .as_deref()
9205                .is_some_and(|e| e.contains("running")),
9206            "the operator needs to know why this task was held"
9207        );
9208    }
9209
9210    #[test]
9211    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9212        let dir = tempfile::tempdir().unwrap();
9213        let queue = Queue::at(dir.path().to_path_buf());
9214
9215        // No run recorded, so this never has to touch `RunState::load`.
9216        let mut orphaned = task();
9217        orphaned.id = "20260904-000000-orph".to_owned();
9218        orphaned.status = TaskStatus::Running;
9219        orphaned.attempts = 1;
9220        queue.put(&mut orphaned).unwrap();
9221
9222        let mut alive = task();
9223        alive.id = "20260904-000000-live".to_owned();
9224        alive.status = TaskStatus::Running;
9225        alive.attempts = 1;
9226        queue.put(&mut alive).unwrap();
9227        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9228
9229        let mut queued = task();
9230        queued.id = "20260904-000000-wait".to_owned();
9231        queue.put(&mut queued).unwrap();
9232
9233        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9234        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9235
9236        assert_eq!(
9237            queue.get(&orphaned.id).unwrap().status,
9238            TaskStatus::Held,
9239            "nothing was driving it and there was no run to recover"
9240        );
9241        assert_eq!(
9242            queue.get(&alive.id).unwrap().status,
9243            TaskStatus::Running,
9244            "a live claim must protect the task it belongs to"
9245        );
9246        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9247    }
9248
9249    /// Read a run.json back from an explicit `home`, the same way
9250    /// `reclaim_abandoned_runs` itself does - never through the
9251    /// process-global `RunState::load`, which this test's own `home` (an
9252    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9253    /// use at all.
9254    fn read_run_under(home: &Path, id: &str) -> RunState {
9255        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9256        serde_json::from_str(&body).unwrap()
9257    }
9258
9259    #[test]
9260    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9261        let dir = tempfile::tempdir().unwrap();
9262        let home = dir.path().to_path_buf();
9263        let now = Timestamp::now();
9264        let overrun_seat = || crate::run::ActiveSeat {
9265            node: "implement".to_owned(),
9266            started_at: now - jiff::SignedDuration::new(21_000, 0),
9267            timeout_secs: 3_600,
9268            attempt: 0,
9269            task: None,
9270            command: None,
9271            index: None,
9272            total: None,
9273        };
9274
9275        let mut dead = run_state(RunStatus::Implementing);
9276        dead.id = "20260101-000000-dead".to_owned();
9277        dead.active.insert("impl-A".to_owned(), overrun_seat());
9278        // A `driver_pid` the injected query below confirms gone outright —
9279        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9280        dead.driver_pid = Some(4242);
9281        dead.save_under(&home).unwrap();
9282
9283        // Same shape, but a live daemon's heartbeat names it: must be left
9284        // exactly alone, however far past its own timeout the seat sits.
9285        let mut alive = run_state(RunStatus::Implementing);
9286        alive.id = "20260101-000000-aliv".to_owned();
9287        alive.active.insert("impl-A".to_owned(), overrun_seat());
9288        alive.save_under(&home).unwrap();
9289        let mut status = Status::new();
9290        status.current = vec![Current {
9291            worker: None,
9292            task: "20260101-000000-task".to_owned(),
9293            run: alive.id.clone(),
9294        }];
9295        write_status_to(&home.join("daemon.json"), &status).unwrap();
9296
9297        // The abandoned seat left an open question behind: nobody is left to
9298        // read an answer once the run is failed, and this must not wait for
9299        // some later daemon startup's own sweep to notice that.
9300        let questions = Questions::at(home.join("questions"));
9301        let mut q = ask::Question::new(
9302            dead.id.clone(),
9303            "implement".to_owned(),
9304            "impl-A".to_owned(),
9305            "Which storage backend?".to_owned(),
9306            String::new(),
9307            vec!["SQLite".to_owned(), "Redis".to_owned()],
9308        );
9309        questions.put(&mut q).unwrap();
9310
9311        let abandoned = reclaim_abandoned_runs_with(
9312            &home,
9313            now,
9314            |pid| if pid == 4242 { Some(false) } else { None },
9315            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9316        );
9317        assert_eq!(abandoned, vec![dead.id.clone()]);
9318
9319        let reloaded = read_run_under(&home, &dead.id);
9320        assert_eq!(reloaded.status, RunStatus::Failed);
9321        assert!(reloaded.active.is_empty());
9322        assert!(
9323            !questions.get(&q.id).unwrap().status.open(),
9324            "the failed run's own open question must be settled in the same pass"
9325        );
9326
9327        let still_alive = read_run_under(&home, &alive.id);
9328        assert_eq!(
9329            still_alive.status,
9330            RunStatus::Implementing,
9331            "a live daemon's claim protects it"
9332        );
9333        assert!(!still_alive.active.is_empty());
9334    }
9335
9336    /// The exact shape a review round flagged as broken: `magi serve` running
9337    /// in this same `home` scans *every* run on disk, including a manual
9338    /// `magi review` / `magi run` this daemon never started and that
9339    /// therefore claims no heartbeat of its own. Before this scan asked
9340    /// `liveness` rather than just `is_working_on`, a manual run whose active
9341    /// seat merely ran a little past its own timeout — the CLI finishing up,
9342    /// its result still being collected — got wiped and failed by a daemon
9343    /// that had nothing to do with it, out from under a process that was
9344    /// still very much running.
9345    #[test]
9346    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9347        let dir = tempfile::tempdir().unwrap();
9348        let home = dir.path().to_path_buf();
9349        let now = Timestamp::now();
9350
9351        let mut manual = run_state(RunStatus::Reviewing);
9352        manual.id = "20260101-000000-manl".to_owned();
9353        manual.active.insert(
9354            "review-1".to_owned(),
9355            crate::run::ActiveSeat {
9356                node: "review".to_owned(),
9357                started_at: now - jiff::SignedDuration::new(21_000, 0),
9358                timeout_secs: 3_600,
9359                attempt: 0,
9360                task: None,
9361                command: None,
9362                index: None,
9363                total: None,
9364            },
9365        );
9366        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9367        // but a real, still-running process: `liveness` must corroborate this
9368        // as `Live`, not read the missing daemon claim as death.
9369        manual.driver_pid = Some(4242);
9370        manual.driver_started_at = Some("1790000000".to_owned());
9371        manual.save_under(&home).unwrap();
9372
9373        let abandoned = reclaim_abandoned_runs_with(
9374            &home,
9375            now,
9376            |pid| if pid == 4242 { Some(true) } else { None },
9377            |pid| {
9378                if pid == 4242 {
9379                    Some("1790000000".to_owned())
9380                } else {
9381                    None
9382                }
9383            },
9384        );
9385        assert!(
9386            abandoned.is_empty(),
9387            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9388        );
9389
9390        let reloaded = read_run_under(&home, &manual.id);
9391        assert_eq!(reloaded.status, RunStatus::Reviewing);
9392        assert!(!reloaded.active.is_empty());
9393    }
9394
9395    #[test]
9396    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9397        let dir = tempfile::tempdir().unwrap();
9398        let queue = Queue::at(dir.path().to_path_buf());
9399        let mut only = task();
9400        queue.put(&mut only).unwrap();
9401
9402        let _elsewhere = queue.claim(&only.id).unwrap();
9403        let candidates = runnable(&queue);
9404        assert_eq!(candidates.len(), 1, "the task is still runnable");
9405        assert!(
9406            queue.claim(&candidates[0].id).is_err(),
9407            "the loop cannot take a claim somebody else holds"
9408        );
9409
9410        let after = queue.get(&only.id).unwrap();
9411        assert_eq!(after.status, TaskStatus::Queued);
9412        assert_eq!(
9413            after.attempts, 0,
9414            "losing the race is not an attempt at the task"
9415        );
9416        assert_eq!(after.last_error, None);
9417    }
9418
9419    #[test]
9420    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9421        let dir = tempfile::tempdir().unwrap();
9422        let path = dir.path().join("daemon.json");
9423
9424        let mut status = Status::new();
9425        status.idle = false;
9426        status.completed = 7;
9427        status.current = vec![Current {
9428            worker: None,
9429            task: "20260902-000000-t111".to_owned(),
9430            run: "20260902-000001-r111".to_owned(),
9431        }];
9432        write_status_to(&path, &status).unwrap();
9433        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9434        assert_eq!(first.schema, SCHEMA);
9435        assert_eq!(first.pid, std::process::id());
9436        assert!(!first.idle);
9437        assert_eq!(first.completed, 7);
9438        assert_eq!(first.current, status.current);
9439        assert!(
9440            !path.with_extension("json.tmp").exists(),
9441            "the temp file is renamed, not left behind"
9442        );
9443
9444        std::thread::sleep(Duration::from_millis(5));
9445        status.updated_at = Timestamp::now();
9446        status.polls = 3;
9447        write_status_to(&path, &status).unwrap();
9448        let second: Status =
9449            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9450        assert!(
9451            second.updated_at > first.updated_at,
9452            "a reader can only detect staleness if the heartbeat moves"
9453        );
9454        assert_eq!(
9455            second.started_at, first.started_at,
9456            "the start time is not a heartbeat"
9457        );
9458        assert_eq!(second.polls, 3);
9459    }
9460
9461    #[test]
9462    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9463        let dir = tempfile::tempdir().unwrap();
9464
9465        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9466
9467        let mut status = Status::new();
9468        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9469        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9470        let stale = read_status(dir.path()).unwrap();
9471        assert!(
9472            !stale.running(Timestamp::now()),
9473            "a minute without a heartbeat is a dead daemon, not a busy one"
9474        );
9475        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9476
9477        status.updated_at = Timestamp::now();
9478        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9479        let fresh = read_status(dir.path()).unwrap();
9480        assert!(fresh.running(Timestamp::now()));
9481    }
9482
9483    #[test]
9484    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9485        let dir = tempfile::tempdir().unwrap();
9486        let now = Timestamp::now();
9487        let mine = "20260903-080619-01c2";
9488
9489        assert!(
9490            !is_working_on(dir.path(), mine, now),
9491            "no status file means nobody is working on anything"
9492        );
9493
9494        let mut status = Status::new();
9495        status.current = vec![Current {
9496            worker: None,
9497            task: "20260903-080340-0167".to_owned(),
9498            run: mine.to_owned(),
9499        }];
9500        status.updated_at = now;
9501        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9502        assert!(is_working_on(dir.path(), mine, now));
9503        assert!(
9504            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9505            "a daemon busy with one run is not working on another"
9506        );
9507
9508        // A killed daemon stops writing heartbeats but leaves the file behind
9509        // naming the run it died in. That run must not be undeletable forever.
9510        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9511        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9512        assert!(
9513            !is_working_on(dir.path(), mine, now),
9514            "a stale heartbeat is a dead daemon, so its run is a leftover"
9515        );
9516    }
9517
9518    #[test]
9519    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9520        let dir = tempfile::tempdir().unwrap();
9521        let now = Timestamp::now();
9522
9523        assert!(
9524            !is_working_on_short(dir.path(), "01c2", now),
9525            "no status file means nobody is working on anything"
9526        );
9527
9528        let mut status = Status::new();
9529        status.current = vec![Current {
9530            worker: None,
9531            task: "20260903-080340-0167".to_owned(),
9532            run: "20260903-080619-01c2".to_owned(),
9533        }];
9534        status.updated_at = now;
9535        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9536        assert!(
9537            is_working_on_short(dir.path(), "01c2", now),
9538            "the run's short id is the last block of its full id"
9539        );
9540        assert!(
9541            !is_working_on_short(dir.path(), "3cbf", now),
9542            "a daemon busy with one worktree bay is not working on another"
9543        );
9544    }
9545
9546    #[test]
9547    fn a_newer_status_file_still_yields_a_reading() {
9548        let dir = tempfile::tempdir().unwrap();
9549        // A field this build has never heard of must not turn the reading into
9550        // nothing at all; that is the whole reason the reader is permissive.
9551        std::fs::write(
9552            dir.path().join("daemon.json"),
9553            serde_json::json!({
9554                "schema": 2,
9555                "updated_at": Timestamp::now().to_string(),
9556                "idle": true,
9557                "surprise": { "nested": [1, 2, 3] },
9558            })
9559            .to_string(),
9560        )
9561        .unwrap();
9562
9563        let reading = read_status(dir.path()).expect("a forward-compatible read");
9564        assert!(reading.running(Timestamp::now()));
9565        assert!(reading.idle);
9566        assert!(reading.current.is_empty());
9567    }
9568
9569    #[test]
9570    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9571        // A daemon started before `current` became a list keeps writing this
9572        // shape on every heartbeat until it is restarted. A rolling upgrade
9573        // - a newer `magi web` or `magi doctor` reading an older `magi
9574        // serve`'s heartbeat - must still see the run it is on, not "no
9575        // daemon" from a type mismatch failing the whole struct.
9576        let dir = tempfile::tempdir().unwrap();
9577        std::fs::write(
9578            dir.path().join("daemon.json"),
9579            serde_json::json!({
9580                "schema": 1,
9581                "pid": 4242,
9582                "updated_at": Timestamp::now().to_string(),
9583                "idle": false,
9584                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9585                "completed": 3,
9586                "polls": 9,
9587            })
9588            .to_string(),
9589        )
9590        .unwrap();
9591
9592        let reading = read_status(dir.path()).expect("an older shape must still parse");
9593        assert!(reading.running(Timestamp::now()));
9594        assert_eq!(
9595            reading.current,
9596            vec![Current {
9597                worker: None,
9598                task: "20260902-140501-aaaa".to_owned(),
9599                run: "20260902-140502-bbbb".to_owned(),
9600            }]
9601        );
9602    }
9603
9604    #[test]
9605    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9606        let dir = tempfile::tempdir().unwrap();
9607        std::fs::write(
9608            dir.path().join("daemon.json"),
9609            serde_json::json!({
9610                "schema": 1,
9611                "updated_at": Timestamp::now().to_string(),
9612                "idle": true,
9613                "current": null,
9614            })
9615            .to_string(),
9616        )
9617        .unwrap();
9618        let with_null = read_status(dir.path()).expect("null must still parse");
9619        assert!(with_null.current.is_empty());
9620
9621        std::fs::write(
9622            dir.path().join("daemon.json"),
9623            serde_json::json!({
9624                "schema": 1,
9625                "updated_at": Timestamp::now().to_string(),
9626                "idle": true,
9627            })
9628            .to_string(),
9629        )
9630        .unwrap();
9631        let absent = read_status(dir.path()).expect("a missing field must still parse");
9632        assert!(absent.current.is_empty());
9633    }
9634
9635    #[test]
9636    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9637        let fallback = Path::new("/default");
9638        let mut blank = task();
9639        blank.repo = PathBuf::new();
9640        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9641        let mut dot = task();
9642        dot.repo = PathBuf::from(".");
9643        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9644        assert_eq!(
9645            repo_for(&task(), fallback),
9646            PathBuf::from("/repo"),
9647            "a task that names a repository keeps it"
9648        );
9649    }
9650
9651    #[test]
9652    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9653        let dir = tempfile::tempdir().unwrap();
9654        let path = dir.path().join("explicit.toml");
9655        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9656        let opts = Opts {
9657            config: Some(path),
9658            merge: Some("none".into()),
9659            ..Default::default()
9660        };
9661        let mut t = task();
9662        t.set_implementers(
9663            2,
9664            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9665                .unwrap(),
9666        )
9667        .unwrap();
9668        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9669        assert_eq!(cfg.graph.implementers, 2);
9670        assert_eq!(cfg.graph.judges, 1);
9671        assert_eq!(cfg.merge.mode, MergeMode::None);
9672        t.set_implementers(1, &cfg).unwrap();
9673        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9674        apply_task_implementers(&mut cfg, &t);
9675        assert_eq!(cfg.graph.implementers, 1);
9676        assert_eq!(cfg.graph.judges, 1);
9677        assert_eq!(cfg.merge.mode, MergeMode::None);
9678    }
9679
9680    #[test]
9681    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9682        let dir = tempfile::tempdir().unwrap();
9683        let repo = dir.path().join("repo");
9684        std::fs::create_dir(&repo).unwrap();
9685        std::fs::write(
9686            repo.join("magi.toml"),
9687            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9688        )
9689        .unwrap();
9690        let daemon_config = dir.path().join("daemon.toml");
9691        std::fs::write(
9692            &daemon_config,
9693            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9694        )
9695        .unwrap();
9696        let opts = Opts {
9697            config: Some(daemon_config),
9698            merge: Some("pr".into()),
9699            ..Default::default()
9700        };
9701        let q = Queue::at(dir.path().join("queue"));
9702        let validation: Config =
9703            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9704                .unwrap();
9705        // No provenance field on legacy direct tasks: both shapes stay isolated.
9706        for record in ["{}", r#"{"candidates":2}"#] {
9707            let overrides = serde_json::from_str(record).unwrap();
9708            let filing = crate::direct::Filing {
9709                instruction: "work".into(),
9710                title: "direct".into(),
9711                repo: repo.clone(),
9712                source: crate::queue::Source::Human,
9713                solo: false,
9714                overrides,
9715                review_of: None,
9716                sources: Default::default(),
9717            };
9718            let filed =
9719                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9720            let crate::direct::Filed::Standalone {
9721                mut task,
9722                claim: _claim,
9723            } = filed
9724            else {
9725                panic!("local filing")
9726            };
9727            let before = prepare_for(&repo, &opts, &task).unwrap();
9728            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9729            assert_eq!(
9730                before.merge.mode,
9731                MergeMode::None,
9732                "daemon --merge must not leak"
9733            );
9734            for n in [2, 1, 2] {
9735                task.set_implementers(n, &validation).unwrap();
9736                q.put(&mut task).unwrap();
9737                task = q.get(&task.id).unwrap();
9738                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9739                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9740                apply_task_implementers(&mut cfg, &task);
9741                assert_eq!(cfg.graph.implementers, usize::from(n));
9742                assert_eq!(cfg.graph.judges, 2);
9743                assert_eq!(cfg.merge.mode, MergeMode::None);
9744            }
9745        }
9746    }
9747
9748    #[test]
9749    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9750        let cfg: Config =
9751            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9752                .unwrap();
9753        let mut t = task();
9754        t.review_of = Some("review-target".into());
9755        t.hold_manual(Some("retry".into()));
9756        let mut previous = RunState::new(
9757            PathBuf::from("/repo"),
9758            "main".into(),
9759            "abc1234".into(),
9760            "review".into(),
9761            cfg.clone(),
9762        );
9763        previous.config.graph.implementers = 2;
9764        for count in [1, 3] {
9765            t.set_implementers(count, &cfg).unwrap();
9766            t.release();
9767            assert_eq!(t.review_of.as_deref(), Some("review-target"));
9768            for proposed in [
9769                Starter::Resume(previous.id.clone()),
9770                Starter::Review("recovery-target".into()),
9771            ] {
9772                assert_eq!(
9773                    starter_with_implementers(&t, Some(&previous), proposed),
9774                    Starter::Review("review-target".into())
9775                );
9776            }
9777            let mut configured = cfg.clone();
9778            apply_task_implementers(&mut configured, &t);
9779            assert_eq!(configured.graph.implementers, usize::from(count));
9780            assert_eq!(previous.config.graph.implementers, 2);
9781        }
9782    }
9783
9784    #[test]
9785    fn task_implementers_dispatch_and_resume_agree() {
9786        let mut t = task();
9787        let cfg: crate::config::Config =
9788            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9789                .unwrap();
9790        let mut run = RunState::new(
9791            PathBuf::from("/repo"),
9792            "main".into(),
9793            "abc1234".into(),
9794            "work".into(),
9795            cfg.clone(),
9796        );
9797        run.config.graph.implementers = 2;
9798        for n in [2, 1, 3, 2] {
9799            t.set_implementers(n, &cfg).unwrap();
9800            let mut dispatched = cfg.clone();
9801            apply_task_implementers(&mut dispatched, &t);
9802            assert_eq!(dispatched.graph.implementers, usize::from(n));
9803            assert_eq!(implementers_match(&t, &run), n == 2);
9804            for proposed in [
9805                Starter::Resume(run.id.clone()),
9806                Starter::Review("old-branch".into()),
9807            ] {
9808                let expected = if n == 2 {
9809                    proposed.clone()
9810                } else {
9811                    Starter::Start
9812                };
9813                assert_eq!(
9814                    starter_with_implementers(&t, Some(&run), proposed),
9815                    expected
9816                );
9817            }
9818            assert_eq!(
9819                run.config.graph.implementers, 2,
9820                "history must not be rewritten"
9821            );
9822        }
9823        t.solo = false;
9824        t.overrides = None;
9825        assert!(implementers_match(&t, &run));
9826    }
9827
9828    #[test]
9829    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9830        // Three seats said out loud. What `solo` promises is one candidate
9831        // *whatever the config asks for*, so the contrast has to be a number
9832        // this test owns - it used to be `Config::default()`'s, which became
9833        // 1 when one implementation became the default and left the two
9834        // halves of this test asserting the same thing.
9835        let mut solo_cfg = Config::default();
9836        solo_cfg.graph.implementers = 3;
9837        let mut solo_task = task();
9838        solo_task.solo = true;
9839        apply_task_implementers(&mut solo_cfg, &solo_task);
9840        assert_eq!(solo_cfg.graph.implementers, 1);
9841
9842        let mut plain_cfg = Config::default();
9843        plain_cfg.graph.implementers = 3;
9844        let plain_task = task();
9845        assert!(!plain_task.solo);
9846        apply_task_implementers(&mut plain_cfg, &plain_task);
9847        assert_eq!(
9848            plain_cfg.graph.implementers, 3,
9849            "a task that did not ask to run alone keeps the config's candidates"
9850        );
9851    }
9852
9853    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9854        QuotaLoss {
9855            seat: seat.into(),
9856            node: "judge".into(),
9857            at: at.parse().unwrap(),
9858            reset: reset.map(str::to_string),
9859        }
9860    }
9861
9862    #[test]
9863    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
9864        let old: Vec<QuotaLoss> = (1..=4)
9865            .map(|i| {
9866                loss(
9867                    &format!("judge-{i}"),
9868                    "2026-09-23T05:23:00Z",
9869                    Some("2:40pm (Asia/Tokyo)"),
9870                )
9871            })
9872            .collect();
9873        let fresh = losses_this_attempt(&old, &old);
9874        assert!(fresh.is_empty());
9875        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
9876        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
9877    }
9878
9879    #[test]
9880    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
9881        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
9882        let now = Timestamp::now();
9883        let mut after = old.clone();
9884        after.push(loss("judge-2", &now.to_string(), None));
9885        let fresh = losses_this_attempt(&old, &after);
9886        assert_eq!(fresh, vec![after[1].clone()]);
9887        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
9888        assert_eq!(
9889            until,
9890            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
9891        );
9892    }
9893
9894    #[test]
9895    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
9896        // `recover_stall` removes judge-1's loss and the retry then hits quota
9897        // again: the vector is the same length, so an index diff sees nothing.
9898        let before = vec![
9899            loss("judge-1", "2026-09-23T05:23:00Z", None),
9900            loss("judge-2", "2026-09-23T05:24:00Z", None),
9901        ];
9902        let after = vec![
9903            loss("judge-2", "2026-09-23T05:24:00Z", None),
9904            loss("judge-1", "2026-09-24T01:00:00Z", None),
9905        ];
9906        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
9907    }
9908
9909    #[test]
9910    fn merge_overrides_are_parsed_or_refused() {
9911        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
9912        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
9913        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
9914        assert!(merge_mode("squash").is_err());
9915    }
9916
9917    #[test]
9918    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
9919        let now = Timestamp::now();
9920        let fallback = Duration::from_secs(300);
9921        let cap = Duration::from_secs(1800);
9922
9923        // No reset hint at all: the fallback.
9924        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
9925
9926        // A reset ten minutes out, well inside the cap: waited for exactly.
9927        let soon = now + jiff::SignedDuration::from_secs(600);
9928        assert_eq!(
9929            quota_wait(Some(soon), now, fallback, cap),
9930            Duration::from_secs(600)
9931        );
9932
9933        // A reset already in the past is not trusted: the fallback, not a
9934        // zero or negative wait that would spin the loop right back around.
9935        let past = now - jiff::SignedDuration::from_secs(60);
9936        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
9937
9938        // A reset further out than the cap is trusted for direction but not
9939        // for magnitude: a parsing slip must not sleep the loop for a day.
9940        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
9941        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
9942    }
9943
9944    #[test]
9945    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
9946        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9947
9948        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
9949        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
9950
9951        // Same clock reading, but it has already gone by today: read as
9952        // tomorrow's, since the CLI would not still be reporting a limit past
9953        // its own stated reset.
9954        let already_past =
9955            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
9956        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
9957
9958        assert!(
9959            parse_reset_hint("session limit reached", now, now).is_none(),
9960            "free text with no recognised shape is not guessed at"
9961        );
9962        assert!(
9963            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
9964            "an unresolvable zone name is not guessed at either"
9965        );
9966    }
9967
9968    #[test]
9969    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
9970        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9971
9972        let at = parse_reset_hint(
9973            "You've hit your usage limit. Visit \
9974             https://chatgpt.com/codex/settings/usage to purchase more \
9975             credits or try again at Sep 19th, 2026 5:10 PM.",
9976            now,
9977            now,
9978        )
9979        .expect("the codex reset wording is a recognised shape");
9980        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
9981
9982        // The month is explicit, so a date already earlier in the same
9983        // sentence-implied year than `now` is trusted as written rather than
9984        // rolled forward a year the way the bracketed shape rolls a
9985        // same-day clock reading to tomorrow.
9986        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
9987            .expect("an explicit year needs no rollover");
9988        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
9989
9990        assert!(
9991            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
9992            "a two-digit year is not the documented shape and is not guessed at"
9993        );
9994        assert!(
9995            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
9996            "a four-letter month name is not the documented three-letter abbreviation"
9997        );
9998        assert!(
9999            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10000            "an explicit zone on the dated shape is a format nobody has \
10001             documented, and is refused rather than guessed at as UTC"
10002        );
10003    }
10004
10005    #[test]
10006    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10007        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10008        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10009
10010        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10011        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10012
10013        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10014        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10015
10016        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10017            assert!(
10018                parse_reset_hint(bad, now, recorded).is_none(),
10019                "{bad:?} must not be guessed at"
10020            );
10021        }
10022    }
10023
10024    /// A loop whose queue lives in a temp tree and whose poll interval is far
10025    /// longer than the test's patience, so anything that waits out a poll
10026    /// instead of noticing the stop fails rather than merely being slow.
10027    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10028        let config = dir.join("magi.toml");
10029        std::fs::write(
10030            &config,
10031            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10032        )
10033        .unwrap();
10034        let opts = Opts {
10035            poll: Duration::from_secs(30),
10036            config: Some(config),
10037            // The explicit fixture config keeps startup cleanup from reading
10038            // machine configuration. This fictional repository likewise
10039            // keeps any best-effort git cleanup away from this checkout.
10040            repo: dir.join("repo"),
10041            ..Opts::default()
10042        };
10043        // The status file goes in a directory that does not exist yet, so its
10044        // creation is itself evidence the loop published one. `worktrees`
10045        // must be just as fictional: the janitor reclaims worktrees under it
10046        // for real, and a test that let it fall through to
10047        // `crate::run::default_worktree_root()` would have it reclaim
10048        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10049        // which is exactly what happened before this function took the
10050        // parameter at all.
10051        let home = dir.join("home");
10052        // These control-only fixtures do not launch native workers. Give the
10053        // independently tested maintenance services a fresh cadence receipt.
10054        let stamps = home.join("service-ticks");
10055        std::fs::create_dir_all(&stamps).unwrap();
10056        for service in ["waiter", "deputies", "release-watch"] {
10057            std::fs::write(
10058                stamps.join(service),
10059                Timestamp::now().as_second().to_string(),
10060            )
10061            .unwrap();
10062        }
10063        for operation in [
10064            "conductor",
10065            "maintenance",
10066            "housekeeping",
10067            "disk-pressure",
10068            "cache",
10069            "fetch",
10070        ] {
10071            std::fs::write(
10072                stamps.join(format!("daemon-{operation}")),
10073                serde_json::to_vec(&Timestamp::now()).unwrap(),
10074            )
10075            .unwrap();
10076        }
10077        let worktrees = dir.join("wt");
10078        (
10079            opts,
10080            Queue::at(dir.join("queue")),
10081            home.join("daemon.json"),
10082            home,
10083            worktrees,
10084        )
10085    }
10086
10087    #[test]
10088    fn a_stop_is_idempotent_and_once_set_stays_set() {
10089        let stop = Stop::new();
10090        assert!(!stop.stopped());
10091
10092        stop.stop();
10093        assert!(stop.stopped());
10094        stop.stop();
10095        assert!(stop.stopped(), "a second stop is not a toggle");
10096
10097        let shared = stop.clone();
10098        assert!(
10099            shared.stopped(),
10100            "a clone is the same stop; that is how the loop and its caller share one"
10101        );
10102    }
10103
10104    #[tokio::test]
10105    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10106        for operation in ["conductor", "maintenance", "housekeeping"] {
10107            let dir = tempfile::tempdir().unwrap();
10108            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10109            opts.once = true;
10110            opts.poll = Duration::from_millis(1);
10111            let mut task = task();
10112            task.runs.push("fixture-run".into());
10113            queue.put(&mut task).unwrap();
10114            let claim = queue.claim(&task.id).unwrap();
10115
10116            // Model a live service holding the task's claim across the
10117            // scheduler's dispatch scan. No real subprocess or timed race.
10118            let directory = home.join("workers/jobs/abcdef");
10119            std::fs::create_dir_all(&directory).unwrap();
10120            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10121            crate::pr_head::try_lock_file(&lease).unwrap();
10122            let mut job = crate::worker::Job {
10123                id: "abcdef".into(),
10124                sequence: 1,
10125                kind: "daemon-service".into(),
10126                key: format!("service:daemon-{operation}"),
10127                payload: serde_json::Value::Null,
10128                generation: "fixture".into(),
10129                version: None,
10130                status: crate::worker::Status::Running,
10131                result: None,
10132                pid: Some(std::process::id()),
10133                created_at: Timestamp::now().as_second() as u64,
10134                finished_at: None,
10135            };
10136            let record = directory.join("job.json");
10137            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10138
10139            let status = Arc::new(Mutex::new(Status::new()));
10140            let stop = Stop::new();
10141            let mut drain = Box::pin(poll(
10142                &opts,
10143                &queue,
10144                &status,
10145                &home,
10146                &worktrees,
10147                &stop,
10148                DispatchLimits {
10149                    max_concurrent: 1,
10150                    pause_for_interrupts: false,
10151                    recovery_cfg: None,
10152                },
10153            ));
10154            std::future::poll_fn(|cx| {
10155                use std::future::Future;
10156                assert!(
10157                    drain.as_mut().poll(cx).is_pending(),
10158                    "--once must wait for {operation} to release its queue claim"
10159                );
10160                std::task::Poll::Ready(())
10161            })
10162            .await;
10163            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10164
10165            // An answer arrives while the service still owns the claim. A
10166            // fresh scheduling pass must apply it before declaring idle.
10167            let questions = Questions::at(home.join("questions"));
10168            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10169            questions.put(&mut q).unwrap();
10170            drop(claim);
10171            // Model services that took longer than their cadence, without a
10172            // wall-clock sleep. The final scans must not respawn them even
10173            // though their receipts now permit another periodic invocation.
10174            let expired =
10175                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10176            for service in [operation, "housekeeping"] {
10177                std::fs::write(
10178                    home.join("service-ticks").join(format!("daemon-{service}")),
10179                    &expired,
10180                )
10181                .unwrap();
10182            }
10183            job.status = crate::worker::Status::Finished;
10184            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10185            drop(lease);
10186            tokio::time::timeout(Duration::from_secs(2), drain)
10187                .await
10188                .expect("the settled service must allow the drain to finish")
10189                .unwrap();
10190            let after = queue.get(&task.id).unwrap();
10191            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10192            assert!(after.action_applied(&q.id));
10193            for service in [operation, "housekeeping"] {
10194                assert_eq!(
10195                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10196                        .unwrap(),
10197                    expired,
10198                    "the final once rescan must not restart {service}"
10199                );
10200            }
10201        }
10202    }
10203
10204    #[test]
10205    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10206        let stop = Stop::new();
10207        stop.busy.store(1, Ordering::SeqCst);
10208        assert!(
10209            !stop.finishing(),
10210            "a busy loop nobody has asked to stop is just running"
10211        );
10212
10213        stop.stop();
10214        assert!(
10215            stop.finishing(),
10216            "a stop asked for mid-run has not landed until the run is settled"
10217        );
10218
10219        stop.busy.store(0, Ordering::SeqCst);
10220        assert!(
10221            !stop.finishing(),
10222            "once the run is settled the stop has landed and there is nothing to finish"
10223        );
10224    }
10225
10226    #[test]
10227    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10228        let stop = Stop::new();
10229        stop.busy.store(2, Ordering::SeqCst);
10230        stop.stop();
10231        assert!(stop.finishing(), "two runs still in flight");
10232
10233        stop.busy.store(1, Ordering::SeqCst);
10234        assert!(
10235            stop.finishing(),
10236            "one run finished, but a sibling is still working"
10237        );
10238
10239        stop.busy.store(0, Ordering::SeqCst);
10240        assert!(
10241            !stop.finishing(),
10242            "the last run out is what actually lands the stop"
10243        );
10244    }
10245
10246    #[tokio::test]
10247    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10248        let dir = tempfile::tempdir().unwrap();
10249        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10250        let stop = Stop::new();
10251        stop.stop();
10252
10253        let began = std::time::Instant::now();
10254        tokio::time::timeout(
10255            Duration::from_secs(2),
10256            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10257        )
10258        .await
10259        .expect("a stopped loop must return, not sit out its poll interval")
10260        .expect("the loop's own setup and teardown must not fail");
10261        assert!(
10262            began.elapsed() < opts.poll,
10263            "returned only after {:?}, which is a poll interval, not a stop",
10264            began.elapsed()
10265        );
10266    }
10267
10268    #[tokio::test]
10269    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10270        let dir = tempfile::tempdir().unwrap();
10271        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10272        let stop = Stop::new();
10273
10274        // Asked for after the loop is already parked on its empty queue, which
10275        // is the case an operator tapping stop on a phone actually hits.
10276        let asker = {
10277            let stop = stop.clone();
10278            tokio::spawn(async move {
10279                tokio::time::sleep(Duration::from_millis(20)).await;
10280                stop.stop();
10281            })
10282        };
10283
10284        let began = std::time::Instant::now();
10285        tokio::time::timeout(
10286            Duration::from_secs(2),
10287            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10288        )
10289        .await
10290        .expect("a stop asked for while idle must wake the wait")
10291        .expect("the loop's own setup and teardown must not fail");
10292        asker.await.unwrap();
10293        assert!(
10294            began.elapsed() < opts.poll,
10295            "returned only after {:?}, so the stop waited on the sleep",
10296            began.elapsed()
10297        );
10298    }
10299
10300    #[tokio::test]
10301    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10302        let dir = tempfile::tempdir().unwrap();
10303        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10304        let stop = Stop::new();
10305        stop.stop();
10306
10307        tokio::time::timeout(
10308            Duration::from_secs(2),
10309            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10310        )
10311        .await
10312        .expect("a stopped loop must return")
10313        .expect("the loop's own setup and teardown must not fail");
10314
10315        assert!(
10316            home.is_dir(),
10317            "the loop did publish a status file, so its removal is the teardown and not an absence"
10318        );
10319        assert!(
10320            !status_file.exists(),
10321            "a stopped loop clears its status file"
10322        );
10323        assert!(
10324            read_status(&home).is_none(),
10325            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10326        );
10327    }
10328
10329    #[tokio::test]
10330    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10331        let dir = tempfile::tempdir().unwrap();
10332        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10333
10334        let mut settled = RunState::new(
10335            dir.path().join("repo"),
10336            "main".to_owned(),
10337            "abc1234".to_owned(),
10338            "fixture".to_owned(),
10339            Config::default(),
10340        );
10341        settled.status = RunStatus::Ready;
10342        let run_dir = home.join("runs").join(&settled.id);
10343        std::fs::create_dir_all(&run_dir).unwrap();
10344        std::fs::write(
10345            run_dir.join("run.json"),
10346            serde_json::to_string_pretty(&settled).unwrap(),
10347        )
10348        .unwrap();
10349        let questions = Questions::at(home.join("questions"));
10350        let mut question = ask::Question::new(
10351            settled.id.clone(),
10352            "review".to_owned(),
10353            "reviewer-1".to_owned(),
10354            "Continue?".to_owned(),
10355            String::new(),
10356            Vec::new(),
10357        );
10358        questions.put(&mut question).unwrap();
10359
10360        run_service_worker(
10361            &home,
10362            serde_json::to_value(ServiceWorker {
10363                opts,
10364                queue: queue.root().to_path_buf(),
10365                worktrees_root: worktrees,
10366                operation: "housekeeping".to_owned(),
10367            })
10368            .unwrap(),
10369        )
10370        .await
10371        .unwrap();
10372
10373        assert_eq!(
10374            questions.get(&question.id).unwrap().status,
10375            ask::QuestionStatus::Abandoned,
10376            "the independent housekeeping worker settles ended-run questions"
10377        );
10378    }
10379
10380    #[test]
10381    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10382        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10383
10384        assert!(
10385            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10386            "never checked before: due at once"
10387        );
10388
10389        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10390        assert!(
10391            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10392            "well inside the interval: not due yet"
10393        );
10394
10395        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10396        assert!(
10397            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10398            "exactly at the edge: not yet due, same convention as `clean::due`"
10399        );
10400
10401        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10402        assert!(
10403            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10404            "past the interval: due again"
10405        );
10406    }
10407
10408    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10409    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10410    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10411    /// and the congestion test below both need, and must not drift apart.
10412    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10413        let config = dir.join("magi.toml");
10414        // A literal (single-quoted) TOML string, not a basic one: the cache
10415        // path is a Windows path full of backslashes, and a basic string
10416        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10417        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10418        // `{{ vars.cache }}` rendering documents.
10419        std::fs::write(
10420            &config,
10421            format!(
10422                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10423                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10424                cache_dir.display()
10425            ),
10426        )
10427        .unwrap();
10428        Opts {
10429            config: Some(config),
10430            repo: dir.join("repo"),
10431            ..Opts::default()
10432        }
10433    }
10434
10435    #[tokio::test]
10436    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10437        let dir = tempfile::tempdir().unwrap();
10438        let home = dir.path().join("home");
10439        let cache_dir = dir.path().join("cache");
10440        std::fs::create_dir_all(&cache_dir).unwrap();
10441        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10442        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10443
10444        // Nobody has asked this daemon to stop, which is the ordinary case;
10445        // the skip that a stop buys is asserted by its own test below.
10446        let running = Stop::new();
10447        let mut last_checked = None;
10448        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10449        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10450            .await;
10451        assert_eq!(
10452            crate::disk::dir_size(&cache_dir),
10453            0,
10454            "over the cap on the first check ever: pruned at once, no idle queue required"
10455        );
10456        assert_eq!(last_checked, Some(t0));
10457
10458        // A fresh oversized file lands, but the next check is not due yet.
10459        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10460        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10461        maybe_prune_cache_between_runs(
10462            &opts.repo,
10463            &opts,
10464            &home,
10465            &running,
10466            &mut last_checked,
10467            too_soon,
10468        )
10469        .await;
10470        assert_eq!(
10471            crate::disk::dir_size(&cache_dir),
10472            10,
10473            "too soon since the last check: left alone rather than rescanned every call"
10474        );
10475        assert_eq!(
10476            last_checked,
10477            Some(t0),
10478            "an idle check does not reset the clock"
10479        );
10480
10481        // Once the interval elapses, the same oversized cache is caught again.
10482        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10483        maybe_prune_cache_between_runs(
10484            &opts.repo,
10485            &opts,
10486            &home,
10487            &running,
10488            &mut last_checked,
10489            due_again,
10490        )
10491        .await;
10492        assert_eq!(
10493            crate::disk::dir_size(&cache_dir),
10494            0,
10495            "due again: pruned back under the cap"
10496        );
10497    }
10498
10499    /// A stop must not queue behind housekeeping. The prune below is a
10500    /// synchronous walk of the whole cache with no await point in it, so a
10501    /// loop that entered it could not get back to its own `stopped()` test
10502    /// until the walk finished - and because no run is in flight at this
10503    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10504    /// the stop had already landed. The idle branch has always made this same
10505    /// check before reaching `janitor`; the between-runs path makes it too.
10506    #[tokio::test]
10507    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10508        let dir = tempfile::tempdir().unwrap();
10509        let home = dir.path().join("home");
10510        let cache_dir = dir.path().join("cache");
10511        std::fs::create_dir_all(&cache_dir).unwrap();
10512        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10513        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10514
10515        let stop = Stop::new();
10516        stop.stop();
10517        assert!(
10518            !stop.finishing(),
10519            "no run is in flight at a between-runs boundary, so nothing else \
10520             would tell the operator this stop had not taken effect yet"
10521        );
10522
10523        let mut last_checked = None;
10524        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10525        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10526            .await;
10527        assert_eq!(
10528            crate::disk::dir_size(&cache_dir),
10529            10,
10530            "over its cap, and due for the first check ever, but a stop outranks \
10531             it: the cap is a standing policy the next start measures again"
10532        );
10533        assert_eq!(
10534            last_checked, None,
10535            "a check that never happened must not claim the interval"
10536        );
10537    }
10538
10539    /// A backlog must not starve cache pruning. The finite cache worker runs
10540    /// independently of queue drain and must not consume any task attempts.
10541    #[tokio::test]
10542    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10543        let dir = tempfile::tempdir().unwrap();
10544        let cache_dir = dir.path().join("cache");
10545        std::fs::create_dir_all(&cache_dir).unwrap();
10546        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10547
10548        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10549        opts.poll = Duration::from_millis(20);
10550        opts.max_attempts = 1_000;
10551
10552        let queue = Queue::at(dir.path().join("queue"));
10553        for i in 0..128 {
10554            let mut task = Task::new(
10555                format!("queued work {i}"),
10556                format!("queued work {i}"),
10557                opts.repo.clone(),
10558                Source::Human,
10559            );
10560            queue.put(&mut task).unwrap();
10561        }
10562
10563        let home = dir.path().join("home");
10564        let worktrees = dir.path().join("wt");
10565        run_service_worker(
10566            &home,
10567            serde_json::to_value(ServiceWorker {
10568                opts,
10569                queue: queue.root().to_path_buf(),
10570                worktrees_root: worktrees,
10571                operation: "cache".to_owned(),
10572            })
10573            .unwrap(),
10574        )
10575        .await
10576        .unwrap();
10577        let after = queue.list();
10578        assert_eq!(after.len(), 128);
10579        assert!(
10580            after
10581                .iter()
10582                .all(|task| task.status.runnable() && task.attempts == 0)
10583        );
10584
10585        assert_eq!(
10586            crate::disk::dir_size(&cache_dir),
10587            0,
10588            "an oversized cache must not be left to grow unboundedly just because the \
10589             queue kept the loop busy the whole time"
10590        );
10591    }
10592
10593    #[test]
10594    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10595        let dir = tempfile::tempdir().unwrap();
10596        let queue = Queue::at(dir.path().join("queue"));
10597        let questions = Questions::at(dir.path().join("questions"));
10598        let mut task = task();
10599        queue.put(&mut task).unwrap();
10600
10601        let mut task_question = ask::Question::new(
10602            task.id.clone(),
10603            crate::conduct::NODE.to_owned(),
10604            "conduct".to_owned(),
10605            "Which backend?".to_owned(),
10606            String::new(),
10607            Vec::new(),
10608        );
10609        questions.put(&mut task_question).unwrap();
10610        task.block(vec![task_question.id.clone()], None);
10611        queue.put(&mut task).unwrap();
10612
10613        let mut run_question = ask::Question::new(
10614            "20260101-000000-run1".to_owned(),
10615            "review".to_owned(),
10616            "reviewer-1".to_owned(),
10617            "Run question".to_owned(),
10618            String::new(),
10619            Vec::new(),
10620        );
10621        questions.put(&mut run_question).unwrap();
10622
10623        // A question from another node whose `run` happens to equal this
10624        // task's id — the same field, filled in for an unrelated reason. Only
10625        // `crate::conduct::NODE` questions use `run` as a task id; this one
10626        // must never be touched by this reconciliation, even after release.
10627        let mut coincidental = ask::Question::new(
10628            task.id.clone(),
10629            "review".to_owned(),
10630            "reviewer-1".to_owned(),
10631            "Unrelated review question".to_owned(),
10632            String::new(),
10633            Vec::new(),
10634        );
10635        questions.put(&mut coincidental).unwrap();
10636
10637        reconcile_task_questions(&queue, &questions);
10638        assert!(questions.get(&task_question.id).unwrap().status.open());
10639        assert!(questions.get(&run_question.id).unwrap().status.open());
10640        assert!(questions.get(&coincidental.id).unwrap().status.open());
10641
10642        task.release();
10643        queue.put(&mut task).unwrap();
10644        reconcile_task_questions(&queue, &questions);
10645        assert_eq!(
10646            questions.get(&task_question.id).unwrap().status,
10647            ask::QuestionStatus::Abandoned
10648        );
10649        assert!(
10650            questions.get(&run_question.id).unwrap().status.open(),
10651            "run questions remain the run janitor's responsibility"
10652        );
10653        assert!(
10654            questions.get(&coincidental.id).unwrap().status.open(),
10655            "a non-conductor question must not be abandoned just because its \
10656             run id coincides with a task id"
10657        );
10658    }
10659
10660    #[test]
10661    fn a_freshly_started_running_task_is_never_stalled() {
10662        let dir = tempfile::tempdir().unwrap();
10663        let mut t = task();
10664        t.start("run-1".to_owned());
10665        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10666        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10667        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10668    }
10669
10670    #[test]
10671    fn a_long_running_task_with_no_live_daemon_is_stalled() {
10672        let dir = tempfile::tempdir().unwrap();
10673        let mut t = task();
10674        t.start("run-1".to_owned());
10675        t.updated_at = Timestamp::now()
10676            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10677        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10678        assert_eq!(
10679            stalled_tasks(
10680                &Queue::at(dir.path().join("q")),
10681                dir.path(),
10682                Timestamp::now()
10683            )
10684            .len(),
10685            0,
10686            "the task was never written to this queue"
10687        );
10688    }
10689
10690    #[test]
10691    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10692        let dir = tempfile::tempdir().unwrap();
10693        let mut t = task();
10694        t.id = "20260903-080340-0167".to_owned();
10695        t.start("20260903-080619-01c2".to_owned());
10696        t.updated_at = Timestamp::now()
10697            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10698
10699        let mut status = Status::new();
10700        status.current = vec![Current {
10701            worker: None,
10702            task: t.id.clone(),
10703            run: "20260903-080619-01c2".to_owned(),
10704        }];
10705        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10706
10707        assert!(
10708            !is_stalled(&t, dir.path(), Timestamp::now()),
10709            "a live daemon's own heartbeat rules out stalled, however long the task has run"
10710        );
10711    }
10712
10713    /// Rewrite a task's `updated_at` on disk directly, bypassing
10714    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
10715    /// a fixture look like it has genuinely been `running` for a while.
10716    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10717        let path = queue.path_of(id);
10718        let body = std::fs::read_to_string(&path).unwrap();
10719        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10720        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10721        v["updated_at"] = serde_json::Value::String(old.to_string());
10722        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10723    }
10724
10725    #[test]
10726    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10727        // The realistic `poll()` ordering, not `is_stalled` in isolation:
10728        // `reclaim_orphaned_running` runs first, on every poll, and settles
10729        // any `running` task whose claim it can actually take. For most
10730        // crashes that is immediate - a dead pid is proof enough for
10731        // `sweep_stale_claims` to drop the lock the same tick, and the very
10732        // next claim attempt succeeds. But a lock whose pid cannot be parsed
10733        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
10734        // `sweep_stale_claims`'s own doc), so the lock - and the claim
10735        // failure behind it - can legitimately outlive many polls. This is
10736        // exactly the gap `stalled_tasks` exists to surface well before that
10737        // six-hour sweep would: reclaim leaves the task `running`, and it
10738        // must still reach the conductor as stalled.
10739        let dir = tempfile::tempdir().unwrap();
10740        let queue = Queue::at(dir.path().join("queue"));
10741        let home = dir.path().join("home");
10742
10743        let mut t = task();
10744        t.id = "20260101-000001-lock".to_owned();
10745        t.start("run-1".to_owned());
10746        queue.put(&mut t).unwrap();
10747        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10748        std::fs::write(
10749            dir.path().join("queue").join(format!("{}.lock", t.id)),
10750            "not a pid",
10751        )
10752        .unwrap();
10753
10754        let now = Timestamp::now();
10755        assert!(
10756            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10757            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10758             and reclaim must leave the task alone"
10759        );
10760        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10761
10762        let stalled = stalled_tasks(&queue, &home, now);
10763        assert_eq!(
10764            stalled.len(),
10765            1,
10766            "reclaim's inability to claim it yet must not hide it from the conductor"
10767        );
10768        assert_eq!(stalled[0].id, t.id);
10769    }
10770
10771    #[test]
10772    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10773        let dir = tempfile::tempdir().unwrap();
10774        crate::run::set_home(dir.path().join("run-home"));
10775        let queue = Queue::at(dir.path().join("queue"));
10776        let home = dir.path().join("home");
10777        let questions = Questions::at(dir.path().join("questions"));
10778
10779        let mut t = task();
10780        t.id = "20260101-000003-dead".to_owned();
10781        t.start("missing-run".to_owned());
10782        queue.put(&mut t).unwrap();
10783        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10784
10785        // This is the real poll ordering: retain the deterministic stalled
10786        // input before a claim proves the owner is gone and reclaims it.
10787        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10788        assert_eq!(
10789            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10790            [&t.id]
10791        );
10792        assert_eq!(
10793            reclaim_orphaned_running(&queue, 2, &Default::default()),
10794            [t.id.clone()]
10795        );
10796        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10797
10798        // Reclaim drops its guard before conductor decisions are applied, so
10799        // the decision for the captured stalled input has a real write path.
10800        crate::conduct::apply(
10801            &queue,
10802            &questions,
10803            &crate::conduct::Verdict {
10804                decisions: vec![crate::conduct::Decision {
10805                    id: t.id.clone(),
10806                    recovery: Some(crate::conduct::Recovery::Requeue),
10807                    ..crate::conduct::Decision::default()
10808                }],
10809            },
10810        )
10811        .unwrap();
10812        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10813    }
10814
10815    #[test]
10816    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10817        let dir = tempfile::tempdir().unwrap();
10818        let queue = Queue::at(dir.path().join("queue"));
10819        let home = dir.path().join("home");
10820
10821        let mut fresh = task();
10822        fresh.id = "20260101-000001-aaaa".to_owned();
10823        fresh.start("run-1".to_owned());
10824        queue.put(&mut fresh).unwrap();
10825
10826        let mut old = task();
10827        old.id = "20260101-000002-bbbb".to_owned();
10828        old.start("run-2".to_owned());
10829        queue.put(&mut old).unwrap();
10830        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10831
10832        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10833        assert_eq!(stalled.len(), 1);
10834        assert_eq!(stalled[0].id, old.id);
10835    }
10836
10837    #[test]
10838    fn queued_and_finished_task_views_partition_by_status() {
10839        let dir = tempfile::tempdir().unwrap();
10840        let queue = Queue::at(dir.path().join("queue"));
10841
10842        let mut queued = task();
10843        queued.id = "20260101-000001-aaaa".to_owned();
10844        queue.put(&mut queued).unwrap();
10845
10846        let mut failed = task();
10847        failed.id = "20260101-000002-bbbb".to_owned();
10848        failed.start("run-1".to_owned());
10849        failed.fail("gate red", 5);
10850        queue.put(&mut failed).unwrap();
10851
10852        let mut held = task();
10853        held.id = "20260101-000003-cccc".to_owned();
10854        held.hold_machine(None);
10855        queue.put(&mut held).unwrap();
10856
10857        let mut running = task();
10858        running.id = "20260101-000004-dddd".to_owned();
10859        running.start("run-2".to_owned());
10860        queue.put(&mut running).unwrap();
10861
10862        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
10863        assert_eq!(queued_ids, [queued.id.clone()]);
10864
10865        let mut finished_ids: Vec<String> =
10866            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
10867        finished_ids.sort_unstable();
10868        let mut want = vec![failed.id.clone(), held.id.clone()];
10869        want.sort_unstable();
10870        assert_eq!(finished_ids, want);
10871    }
10872
10873    #[test]
10874    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
10875        for short in [false, true] {
10876            let dir = tempfile::tempdir().unwrap();
10877            let queue = Queue::at(dir.path().join("queue"));
10878            let questions = ask::Questions::at(dir.path().join("questions"));
10879            let mut running = task();
10880            running.id = "20261013-192213-feb2".into();
10881            running.start("existing-run".into());
10882            queue.put(&mut running).unwrap();
10883            let mut middle = task();
10884            middle.id = "20261013-193611-ca5b".into();
10885            middle.block(
10886                vec![if short {
10887                    "feb2".into()
10888                } else {
10889                    running.id.clone()
10890                }],
10891                None,
10892            );
10893            queue.put(&mut middle).unwrap();
10894            let mut waiting = task();
10895            waiting.id = "20261013-202849-ee37".into();
10896            waiting.block(
10897                vec![if short {
10898                    "ca5b".into()
10899                } else {
10900                    middle.id.clone()
10901                }],
10902                Some("wait for implementation".into()),
10903            );
10904            queue.put(&mut waiting).unwrap();
10905            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
10906            let inv = crate::blockers::Inventory::load(&queue, &questions);
10907            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
10908            assert!(inv.stuck().is_empty());
10909            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10910            assert!(report.quarantined.is_empty());
10911            assert!(report.asked.is_empty());
10912            resolve_blockers(&queue, &questions);
10913            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10914            assert!(questions.list().is_empty());
10915            // Finishing the transitive prerequisite alone does not satisfy
10916            // the task's direct dependency.
10917            running.succeed();
10918            queue.put(&mut running).unwrap();
10919            resolve_blockers(&queue, &questions);
10920            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
10921            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10922            middle = queue.get(&middle.id).unwrap();
10923            middle.succeed();
10924            queue.put(&mut middle).unwrap();
10925            resolve_blockers(&queue, &questions);
10926            let after = queue.get(&waiting.id).unwrap();
10927            assert_eq!(after.status, TaskStatus::Queued);
10928            assert!(after.blocked_by.is_empty());
10929            assert_eq!(after.instruction, waiting.instruction);
10930        }
10931    }
10932
10933    #[test]
10934    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
10935        for future_schema in [false, true] {
10936            let name = "20261013-193611-ca5b";
10937            let mut future = task();
10938            future.id = name.into();
10939            future.schema = crate::queue::SCHEMA + 1;
10940            let contents = if future_schema {
10941                serde_json::to_string(&future).unwrap()
10942            } else {
10943                "corrupt".into()
10944            };
10945            let dir = tempfile::tempdir().unwrap();
10946            let queue = Queue::at(dir.path().join("queue"));
10947            let questions = ask::Questions::at(dir.path().join("questions"));
10948            let mut waiting = task();
10949            waiting.id = "20261013-202849-ee37".into();
10950            waiting.block(vec!["ca5b".into()], None);
10951            queue.put(&mut waiting).unwrap();
10952            std::fs::write(queue.path_of(name), contents).unwrap();
10953            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
10954            assert!(
10955                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
10956            );
10957            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10958            assert!(report.asked.is_empty());
10959            resolve_blockers(&queue, &questions);
10960            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10961            assert!(questions.list().is_empty());
10962        }
10963        let dir = tempfile::tempdir().unwrap();
10964        let queue = Queue::at(dir.path().join("queue"));
10965        let questions = ask::Questions::at(dir.path().join("questions"));
10966        let mut waiting = task();
10967        waiting.id = "20261013-202849-ee37".into();
10968        waiting.block(vec!["ca5b".into()], None);
10969        queue.put(&mut waiting).unwrap();
10970        let mut done = task();
10971        done.id = "20261013-193611-ca5b".into();
10972        done.succeed();
10973        queue.put(&mut done).unwrap();
10974        // An unreadable second match must not disappear from uniqueness
10975        // checks just because Queue::list skips it.
10976        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
10977        assert!(queue.get("ca5b").is_err());
10978        assert_eq!(
10979            crate::queue::dependency(&queue, &questions, "ca5b"),
10980            crate::queue::Dependency::Ambiguous
10981        );
10982        resolve_blockers(&queue, &questions);
10983        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10984        assert!(report.asked.is_empty());
10985        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10986        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
10987    }
10988
10989    #[test]
10990    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
10991        for held in [false, true] {
10992            for question in [false, true] {
10993                for reference in ["ca5b", "20261013-193611-ca5b"] {
10994                    let dir = tempfile::tempdir().unwrap();
10995                    let queue = Queue::at(dir.path().join("queue"));
10996                    let questions = ask::Questions::at(dir.path().join("questions"));
10997                    let mut prerequisite = task();
10998                    prerequisite.id = "20261013-193611-ca5b".into();
10999                    prerequisite.start("existing-run".into());
11000                    queue.put(&mut prerequisite).unwrap();
11001                    let mut waiting = task();
11002                    waiting.id = "20261013-202849-ee37".into();
11003                    if held {
11004                        waiting.hold_machine(Some("waiting for separate consent".into()));
11005                    }
11006                    queue.put(&mut waiting).unwrap();
11007                    let reason = "Deleting saved data requires separate owner consent";
11008                    crate::conduct::apply(
11009                        &queue,
11010                        &questions,
11011                        &crate::conduct::Verdict {
11012                            decisions: vec![crate::conduct::Decision {
11013                                id: waiting.id.clone(),
11014                                blocked_by: vec![reference.into()],
11015                                question: question.then(|| "May the saved data be deleted?".into()),
11016                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11017                                reason: Some(reason.into()),
11018                                ..crate::conduct::Decision::default()
11019                            }],
11020                        },
11021                    )
11022                    .unwrap();
11023                    let before = queue.get(&waiting.id).unwrap();
11024                    if question {
11025                        assert_eq!(before.status, TaskStatus::Blocked);
11026                        let q = questions.get(&before.blocked_by[0]).unwrap();
11027                        assert_eq!(q.summary, "May the saved data be deleted?");
11028                        assert!(q.status.open());
11029                    } else {
11030                        assert_eq!(before.status, TaskStatus::Held);
11031                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11032                        assert!(recorded_reason.starts_with(reason));
11033                        if held {
11034                            assert!(recorded_reason.contains("waiting for separate consent"));
11035                        }
11036                    }
11037                    prerequisite.succeed();
11038                    queue.put(&mut prerequisite).unwrap();
11039                    resolve_blockers(&queue, &questions);
11040                    let after = queue.get(&waiting.id).unwrap();
11041                    assert_eq!(after.status, before.status);
11042                    assert_eq!(after.blocked_by, before.blocked_by);
11043                    assert_eq!(after.hold_reason, before.hold_reason);
11044                    assert_eq!(after.instruction, waiting.instruction);
11045                    if question {
11046                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11047                    }
11048                    assert!(
11049                        queue.next_runnable().is_none(),
11050                        "dependency completion is not consent"
11051                    );
11052                }
11053            }
11054        }
11055    }
11056
11057    #[test]
11058    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11059        let dir = tempfile::tempdir().unwrap();
11060        let queue = Queue::at(dir.path().join("queue"));
11061        let questions = ask::Questions::at(dir.path().join("questions"));
11062
11063        let mut dep = task();
11064        dep.id = "20260101-000001-dep0".to_owned();
11065        dep.succeed();
11066        queue.put(&mut dep).unwrap();
11067
11068        let mut still_going = task();
11069        still_going.id = "20260101-000002-dep1".to_owned();
11070        queue.put(&mut still_going).unwrap();
11071
11072        let mut blocked = task();
11073        blocked.id = "20260101-000003-main".to_owned();
11074        blocked.block(
11075            vec![dep.id.clone(), still_going.id.clone()],
11076            Some("waits on both".to_owned()),
11077        );
11078        queue.put(&mut blocked).unwrap();
11079
11080        resolve_blockers(&queue, &questions);
11081
11082        let after = queue.get(&blocked.id).unwrap();
11083        assert_eq!(
11084            after.status,
11085            TaskStatus::Blocked,
11086            "one dependency is still outstanding"
11087        );
11088        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11089    }
11090
11091    #[test]
11092    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11093        let dir = tempfile::tempdir().unwrap();
11094        let queue = Queue::at(dir.path().join("queue"));
11095        let questions = ask::Questions::at(dir.path().join("questions"));
11096
11097        let mut q = crate::ask::Question::new(
11098            "20260101-000001-main".to_owned(),
11099            crate::conduct::NODE.to_owned(),
11100            "conduct".to_owned(),
11101            "Which backend?".to_owned(),
11102            String::new(),
11103            Vec::new(),
11104        );
11105        questions.put(&mut q).unwrap();
11106        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11107            .unwrap();
11108        questions.put(&mut q).unwrap();
11109
11110        let mut blocked = task();
11111        blocked.id = "20260101-000001-main".to_owned();
11112        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11113        queue.put(&mut blocked).unwrap();
11114
11115        resolve_blockers(&queue, &questions);
11116
11117        let after = queue.get(&blocked.id).unwrap();
11118        assert_eq!(
11119            after.status,
11120            TaskStatus::Queued,
11121            "the only blocker resolved"
11122        );
11123        assert_eq!(after.answers.len(), 1);
11124        assert_eq!(after.answers[0].question, "Which backend?");
11125        assert_eq!(after.answers[0].answer, "SQLite");
11126
11127        // And the run this task starts next is told about it.
11128        let instruction = instruction_for(&after);
11129        assert!(instruction.contains("Which backend?"));
11130        assert!(instruction.contains("SQLite"));
11131    }
11132
11133    #[test]
11134    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11135        let dir = tempfile::tempdir().unwrap();
11136        let queue = Queue::at(dir.path().join("queue"));
11137        let questions = ask::Questions::at(dir.path().join("questions"));
11138
11139        let mut q = crate::ask::Question::new(
11140            "20260101-000001-main".to_owned(),
11141            crate::conduct::NODE.to_owned(),
11142            "conduct".to_owned(),
11143            "Is the setup done?".to_owned(),
11144            String::new(),
11145            Vec::new(),
11146        );
11147        q.abandon("no answer within 60s of asking");
11148        questions.put(&mut q).unwrap();
11149
11150        let mut blocked = task();
11151        blocked.id = "20260101-000001-main".to_owned();
11152        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11153        queue.put(&mut blocked).unwrap();
11154
11155        resolve_blockers(&queue, &questions);
11156
11157        let after = queue.get(&blocked.id).unwrap();
11158        assert_eq!(
11159            after.status,
11160            TaskStatus::Held,
11161            "never left blocked on nothing"
11162        );
11163        assert!(!after.operator_held(), "a machine hold, for triage");
11164        assert!(
11165            after
11166                .hold_reason
11167                .as_deref()
11168                .unwrap_or_default()
11169                .contains("went unanswered")
11170        );
11171    }
11172
11173    #[test]
11174    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11175        // Reproduces the reported bug (task 3958): a task held out of
11176        // attempts, blocked on a `crate::conduct` follow-up question, must
11177        // come back `held` once that question is answered - never `queued`,
11178        // whatever the answer said - or it silently re-enters the
11179        // competition queue with its attempts already exhausted.
11180        let dir = tempfile::tempdir().unwrap();
11181        let queue = Queue::at(dir.path().join("queue"));
11182        let questions = ask::Questions::at(dir.path().join("questions"));
11183
11184        let mut q = crate::ask::Question::new(
11185            "20260101-000001-main".to_owned(),
11186            crate::conduct::NODE.to_owned(),
11187            "conduct".to_owned(),
11188            "How should this be handled?".to_owned(),
11189            String::new(),
11190            Vec::new(),
11191        );
11192        questions.put(&mut q).unwrap();
11193        q.answer(crate::ask::Answer::Text(
11194            "leave it held, a human will look at it later".to_owned(),
11195        ))
11196        .unwrap();
11197        questions.put(&mut q).unwrap();
11198
11199        let mut held = task();
11200        held.id = "20260101-000001-main".to_owned();
11201        held.hold_machine(Some("out of attempts".to_owned()));
11202        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11203        queue.put(&mut held).unwrap();
11204
11205        resolve_blockers(&queue, &questions);
11206
11207        let after = queue.get(&held.id).unwrap();
11208        assert_eq!(after.status, TaskStatus::Held);
11209        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11210        assert_eq!(
11211            after.answers[0].answer,
11212            "leave it held, a human will look at it later"
11213        );
11214    }
11215
11216    #[test]
11217    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11218        let dir = tempfile::tempdir().unwrap();
11219        let queue = Queue::at(dir.path().join("queue"));
11220        let questions = ask::Questions::at(dir.path().join("questions"));
11221        let mut dep = task();
11222        dep.id = "20260101-000001-gone".to_owned();
11223        queue.put(&mut dep).unwrap();
11224        let mut blocked = task();
11225        blocked.id = "20260101-000003-main".to_owned();
11226        blocked.block(vec![dep.id.clone()], None);
11227        queue.put(&mut blocked).unwrap();
11228
11229        // Claimed, so `remove` cannot rewrite it and the resolver must.
11230        let claim = queue.claim(&blocked.id).unwrap();
11231        queue.remove(&dep.id, false, &questions).unwrap();
11232        drop(claim);
11233        resolve_blockers(&queue, &questions);
11234
11235        let after = queue.get(&blocked.id).unwrap();
11236        assert_eq!(after.status, TaskStatus::Queued);
11237        assert!(after.blocked_by.is_empty());
11238    }
11239
11240    #[test]
11241    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11242        // Reproduces the reported bug: a task blocked on a task id that was
11243        // removed (`magi task rm`, or deleted by hand) can never see that id
11244        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11245        // would otherwise leave the task `blocked` forever with no way for an
11246        // operator to find out why.
11247        let dir = tempfile::tempdir().unwrap();
11248        let queue = Queue::at(dir.path().join("queue"));
11249        let questions = ask::Questions::at(dir.path().join("questions"));
11250
11251        let mut still_going = task();
11252        still_going.id = "20260101-000002-dep1".to_owned();
11253        queue.put(&mut still_going).unwrap();
11254
11255        let mut blocked = task();
11256        blocked.id = "20260101-000003-main".to_owned();
11257        blocked.block(
11258            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11259            Some("waits on both".to_owned()),
11260        );
11261        queue.put(&mut blocked).unwrap();
11262
11263        resolve_blockers(&queue, &questions);
11264
11265        let after = queue.get(&blocked.id).unwrap();
11266        assert_eq!(
11267            after.status,
11268            TaskStatus::Held,
11269            "a missing dependency must not leave the task blocked forever"
11270        );
11271        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11272        assert!(after.blocked_by.is_empty());
11273        let reason = after.hold_reason.as_deref().unwrap_or_default();
11274        assert!(
11275            reason.contains("20260101-000001-gone"),
11276            "the missing id must be named so an operator can tell what happened: {reason}"
11277        );
11278        assert!(
11279            reason.contains(&still_going.id),
11280            "the still-valid dependency must not silently vanish from the record: {reason}"
11281        );
11282    }
11283
11284    #[test]
11285    fn instruction_for_is_unchanged_without_any_answers() {
11286        let t = task();
11287        assert_eq!(instruction_for(&t), t.instruction);
11288    }
11289
11290    #[test]
11291    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11292        let dir = tempfile::tempdir().unwrap();
11293        let q = Queue::at(dir.path().join("queue"));
11294        let src = dir.path().join("shot.png");
11295        std::fs::write(&src, "x").unwrap();
11296        let mut t = task();
11297        q.attach(&mut t, &[src]).unwrap();
11298        let paths = task_attachments(&q, &t).unwrap();
11299        assert_eq!(paths.len(), 1);
11300        assert!(paths[0].is_absolute() && paths[0].is_file());
11301        std::fs::remove_file(&paths[0]).unwrap();
11302        let err = task_attachments(&q, &t).unwrap_err().to_string();
11303        assert!(err.contains("shot.png"), "{err}");
11304    }
11305
11306    #[tokio::test]
11307    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11308        let dir = tempfile::tempdir().unwrap();
11309        let queue_path = dir.path().join("queue");
11310        let queue = Queue::at(queue_path.clone());
11311        let mut t = task();
11312        t.source = Source::Agent {
11313            run: "originating-chat".into(),
11314            node: crate::queue::CHAT_NODE.into(),
11315        };
11316        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11317            stage: "config-fetch",
11318            target: "origin/main".into(),
11319        });
11320        record_config_failure(&mut t, &fetch);
11321        t.hold_machine(Some(format!("{fetch:#}")));
11322        let fetch_key = t.chat_notice_due().unwrap();
11323        t.chat_notices.push(fetch_key.clone());
11324        queue.put(&mut t).unwrap();
11325
11326        let queue = Queue::at(queue_path);
11327        let mut t = queue.get(&t.id).unwrap();
11328        let a = dir.path().join("a.toml");
11329        let b = dir.path().join("b.toml");
11330        for (path, text, new_cause) in [
11331            (&a, "[graph", true),
11332            (&a, "[verify", false),
11333            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11334            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11335        ] {
11336            t.release_operator("test", None);
11337            std::fs::write(path, text).unwrap();
11338            let error = Config::discover_fetched(dir.path(), Some(path))
11339                .await
11340                .unwrap_err();
11341            record_config_failure(&mut t, &error);
11342            t.hold_machine(Some(format!("{error:#}")));
11343            let due = t.chat_notice_due();
11344            assert_eq!(due.is_some(), new_cause, "{error:#}");
11345            if let Some(key) = due {
11346                assert_ne!(key, fetch_key);
11347                t.chat_notices.push(key);
11348            }
11349        }
11350        t.succeed();
11351        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11352    }
11353
11354    #[test]
11355    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11356        let dir = tempfile::tempdir().unwrap();
11357        let queue_path = dir.path().join("queue");
11358        let queue = Queue::at(queue_path.clone());
11359        let mut t = task();
11360        t.source = crate::queue::Source::Agent {
11361            run: "originating-chat".into(),
11362            node: crate::queue::CHAT_NODE.into(),
11363        };
11364        let a = dir.path().join("a.png");
11365        let b = dir.path().join("b.png");
11366        std::fs::write(&a, "a").unwrap();
11367        std::fs::write(&b, "b").unwrap();
11368        queue.attach(&mut t, &[a, b]).unwrap();
11369        let paths = task_attachments(&queue, &t).unwrap();
11370        for path in &paths {
11371            std::fs::remove_file(path).unwrap();
11372        }
11373        let missing = task_attachments(&queue, &t).unwrap_err();
11374        t.attempts += 1;
11375        let reason = missing.to_string();
11376        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11377        let first = t.chat_notice_due().expect("first attachment notice");
11378        t.chat_notices.push(first.clone());
11379        queue.put(&mut t).unwrap();
11380
11381        let queue = Queue::at(queue_path.clone());
11382        let mut t = queue.get(&t.id).unwrap();
11383        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11384        t.release_operator("test", None);
11385        t.attempts += 1;
11386        let missing = task_attachments(&queue, &t).unwrap_err();
11387        t.fail_startup_target(
11388            "startup-attachments",
11389            missing.name,
11390            "same missing attachment with regenerated wording",
11391            1,
11392        );
11393        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11394
11395        std::fs::write(&paths[0], "restored").unwrap();
11396        t.release_operator("test", None);
11397        t.attempts += 1;
11398        let missing = task_attachments(&queue, &t).unwrap_err();
11399        let reason = missing.to_string();
11400        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11401        let second = t
11402            .chat_notice_due()
11403            .expect("different attachment must notify");
11404        assert_ne!(first, second);
11405        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11406    }
11407
11408    #[test]
11409    fn resumed_instruction_is_unchanged_without_any_answers() {
11410        let t = task();
11411        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11412    }
11413
11414    #[test]
11415    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11416        let mut t = task();
11417        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11418        // The run's own instruction on disk predates the answer: it is the
11419        // plain original text `Runner::start` saved before the operator was
11420        // ever asked anything.
11421        let old = t.instruction.clone();
11422
11423        let refreshed = resumed_instruction(&old, &t);
11424        assert!(refreshed.starts_with(&old), "the original text is kept");
11425        assert!(refreshed.contains("Which backend?"));
11426        assert!(refreshed.contains("SQLite"));
11427    }
11428
11429    #[test]
11430    fn resumed_instruction_keeps_an_original_answers_heading() {
11431        let mut t = task();
11432        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11433        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11434
11435        let refreshed = resumed_instruction(&t.instruction, &t);
11436
11437        assert!(
11438            refreshed.starts_with(&t.instruction),
11439            "an answers heading in the original instruction is not the appended block"
11440        );
11441        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11442        assert!(refreshed.contains("Which backend?"));
11443        assert!(refreshed.contains("SQLite"));
11444
11445        let repeated = resumed_instruction(&refreshed, &t);
11446        assert_eq!(
11447            repeated, refreshed,
11448            "only the final appended block is refreshed"
11449        );
11450    }
11451
11452    #[test]
11453    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11454        let mut t = task();
11455        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11456
11457        // A first resume appends the block; a second resume of the same run,
11458        // with no new answer in between, must reproduce exactly the same
11459        // text rather than appending the block a second time.
11460        let once = resumed_instruction(&t.instruction, &t);
11461        let twice = resumed_instruction(&once, &t);
11462        assert_eq!(once, twice);
11463        assert_eq!(once.matches("Which backend?").count(), 1);
11464
11465        // A later answer replaces the block wholesale rather than growing it.
11466        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11467        let refreshed = resumed_instruction(&once, &t);
11468        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11469        assert!(refreshed.contains("Which backend?"));
11470        assert!(refreshed.contains("Which cache?"));
11471    }
11472
11473    #[test]
11474    fn prepare_instruction_covers_all_three_starters() {
11475        let mut t = task();
11476        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11477
11478        // Start: a fresh run gets the task text plus every answer so far —
11479        // exactly `instruction_for`.
11480        assert_eq!(
11481            prepare_instruction(&Starter::Start, None, &t),
11482            Some(instruction_for(&t))
11483        );
11484
11485        // Resume: the run's prior instruction is refreshed with the answer,
11486        // not discarded and not left stale.
11487        let old = t.instruction.clone();
11488        assert_eq!(
11489            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11490            Some(resumed_instruction(&old, &t))
11491        );
11492
11493        // Review: a review-only pass builds its own instruction from the
11494        // branch's history in `crate::graph`, with no task statement at all -
11495        // this boundary must leave it alone.
11496        assert_eq!(
11497            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11498            None
11499        );
11500    }
11501
11502    #[test]
11503    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11504        assert_eq!(
11505            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11506            Starter::Review("magi/eba2/A".to_owned())
11507        );
11508    }
11509
11510    #[test]
11511    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11512        assert_eq!(
11513            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11514            Starter::Start,
11515            "a vanished review branch must not fall back to resuming the old run either"
11516        );
11517    }
11518
11519    #[test]
11520    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11521        let mut t = task();
11522        t.start("old-run".to_owned());
11523        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11524        t.release();
11525        let branch = t.review_branch.take();
11526        assert_eq!(
11527            choose_starter(branch.as_deref(), true, Some("old-run")),
11528            Starter::Review("magi/eba2/A".to_owned()),
11529            "a review wins over resuming the old run"
11530        );
11531    }
11532
11533    #[test]
11534    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11535        assert_eq!(
11536            choose_starter(None, false, Some("some-run")),
11537            Starter::Resume("some-run".to_owned())
11538        );
11539        assert_eq!(choose_starter(None, false, None), Starter::Start);
11540    }
11541
11542    #[test]
11543    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11544        let mut released = task();
11545        released.start("stalled-run".to_owned());
11546        released.requeue();
11547        let unfinished = (!released.fresh_start)
11548            .then(|| Some("stalled-run".to_owned()))
11549            .flatten();
11550        assert_eq!(
11551            choose_starter(None, false, unfinished.as_deref()),
11552            Starter::Start,
11553            "release keeps run history but must not resume it"
11554        );
11555        assert_eq!(released.runs, ["stalled-run"]);
11556    }
11557
11558    fn stopped_public_run(status: RunStatus) -> RunState {
11559        let mut state = run_state(status);
11560        state.driver_exited = true;
11561        state.config.graph.land = true;
11562        state.config.graph.review_rounds = 1;
11563        state.reviews = vec![review_round(1)];
11564        state.merge = Some(crate::run::MergeOutcome {
11565            mode: MergeMode::Pr,
11566            ok: false,
11567            detail: "landing stopped".into(),
11568            empty: false,
11569        });
11570        state.pr = Some(crate::run::PrRecord {
11571            url: "https://example.test/pull/1".into(),
11572            number: 1,
11573            state: "open".into(),
11574            checks: "red".into(),
11575            round: 1,
11576            rounds: 1,
11577            red_at_merge: Vec::new(),
11578        });
11579        state
11580    }
11581
11582    #[test]
11583    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11584        for status in [RunStatus::Blocked, RunStatus::Gating] {
11585            let home = tempfile::tempdir().unwrap();
11586            let mut state = stopped_public_run(status);
11587            state.save_under(home.path()).unwrap();
11588            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11589            assert!(!exhausted_review_budget(&state));
11590            let mut task = held_task_with(&state.id);
11591            task.release();
11592            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11593            assert_eq!(
11594                choose_starter(None, false, unfinished.as_deref()),
11595                Starter::Resume(state.id.clone())
11596            );
11597            let question = action_question(&state.id, resume_action(&state.id));
11598            assert_eq!(
11599                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11600                ActionDecision::Resume(state.id.clone())
11601            );
11602            // The control-plane command uses this same preflight before pinning.
11603            assert_eq!(
11604                crate::resume::validate(home.path(), &state.id).unwrap().id,
11605                state.id
11606            );
11607            let queue = Queue::at(home.path().join("queue"));
11608            let mut controlled = Task::new(
11609                "resume land".into(),
11610                state.instruction.clone(),
11611                state.repo.clone(),
11612                Source::Agent {
11613                    run: "talk".into(),
11614                    node: crate::queue::CHAT_NODE.into(),
11615                },
11616            );
11617            controlled.runs.push(state.id.clone());
11618            controlled.hold_machine(Some("land stopped".into()));
11619            queue.put(&mut controlled).unwrap();
11620            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11621            assert_eq!(resumed.status, TaskStatus::Queued);
11622            assert_eq!(
11623                resumed.resume_override.unwrap().pinned_run,
11624                Some(state.id.clone())
11625            );
11626            assert_eq!(resumed.attempts, 0);
11627        }
11628    }
11629
11630    #[test]
11631    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11632        for review_rounds in [0, 1] {
11633            let home = tempfile::tempdir().unwrap();
11634            let mut state = run_state(RunStatus::Blocked);
11635            state.config.graph.review_rounds = review_rounds;
11636            if review_rounds > 0 {
11637                let mut review = review_round(1);
11638                review.clean = true;
11639                state.reviews = vec![review];
11640            }
11641            state.gate_ran = true;
11642            state.gate = vec![crate::run::CommandOutcome {
11643                command: "verify".into(),
11644                code: Some(1),
11645                output_tail: "gate failed after repair budget exhausted".into(),
11646                duration_ms: 0,
11647                resource_blocked: false,
11648            }];
11649            state.save_under(home.path()).unwrap();
11650            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11651            assert!(exhausted_review_budget(&state));
11652            let mut task = held_task_with(&state.id);
11653            task.release();
11654            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11655            let question = action_question(&state.id, resume_action(&state.id));
11656            assert_ne!(
11657                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11658                ActionDecision::Resume(state.id.clone())
11659            );
11660            let error = crate::resume::validate(home.path(), &state.id)
11661                .unwrap_err()
11662                .to_string();
11663            assert!(!error.contains("review budget exhausted"), "{error}");
11664            assert!(
11665                error.contains(if review_rounds == 0 {
11666                    "review is disabled"
11667                } else {
11668                    "gate already ran"
11669                }),
11670                "{error}"
11671            );
11672
11673            // An unexecuted gate still has work to do with or without reviews.
11674            state.gate_ran = false;
11675            state.gate.clear();
11676            assert!(!exhausted_review_budget(&state));
11677            assert_eq!(
11678                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11679                Some(state.id)
11680            );
11681        }
11682    }
11683
11684    #[test]
11685    fn resource_blocked_verification_resumes_the_same_run() {
11686        for (kind, stage) in [
11687            ("cache", "clean"),
11688            ("coordination", "clean"),
11689            ("cache", "review-e2e"),
11690            ("coordination", "no-reviews"),
11691            ("coordination", "handoff"),
11692        ] {
11693            let home = tempfile::tempdir().unwrap();
11694            let mut state = run_state(RunStatus::Blocked);
11695            state.config.graph.review_rounds = 1;
11696            let mut review = review_round(1);
11697            review.clean = true;
11698            state.reviews = vec![review];
11699            if stage == "review-e2e" {
11700                let review = &mut state.reviews[0];
11701                review.clean = false;
11702                review.blocking = 1;
11703                review.e2e = vec![crate::run::CommandOutcome {
11704                    command: "verify".into(),
11705                    code: None,
11706                    output_tail: "resource wait expired".into(),
11707                    duration_ms: 0,
11708                    resource_blocked: true,
11709                }];
11710            } else if stage == "no-reviews" {
11711                state.config.graph.review_rounds = 0;
11712                state.reviews.clear();
11713            } else if stage == "handoff" {
11714                // A completed final verification can hand off to the gate
11715                // even when the review still carries contested findings.
11716                let review = &mut state.reviews[0];
11717                review.clean = false;
11718                review.blocking = 1;
11719                review.e2e = vec![crate::run::CommandOutcome {
11720                    command: "verify".into(),
11721                    code: Some(0),
11722                    output_tail: String::new(),
11723                    duration_ms: 0,
11724                    resource_blocked: false,
11725                }];
11726            }
11727            state.gate_ran = false;
11728            state.resource_block = Some(crate::run::ResourceBlock {
11729                cause: crate::run::ResourceBlockCause::Other,
11730                node: if stage == "review-e2e" {
11731                    "review"
11732                } else {
11733                    "gate"
11734                }
11735                .into(),
11736                kind: kind.into(),
11737                detail: "resource wait expired".into(),
11738                at: jiff::Timestamp::now(),
11739            });
11740            state.save_under(home.path()).unwrap();
11741            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11742            assert!(!exhausted_review_budget(&state));
11743            let mut task = held_task_with(&state.id);
11744            task.release();
11745            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11746            assert_eq!(
11747                choose_starter(None, false, unfinished.as_deref()),
11748                Starter::Resume(state.id.clone())
11749            );
11750            let question = action_question(&state.id, resume_action(&state.id));
11751            assert_eq!(
11752                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11753                ActionDecision::Resume(state.id.clone())
11754            );
11755            assert_eq!(
11756                crate::resume::validate(home.path(), &state.id).unwrap().id,
11757                state.id
11758            );
11759            let queue = Queue::at(home.path().join("queue"));
11760            let mut controlled = Task::new(
11761                "resume verification".into(),
11762                state.instruction.clone(),
11763                state.repo.clone(),
11764                Source::Agent {
11765                    run: "talk".into(),
11766                    node: crate::queue::CHAT_NODE.into(),
11767                },
11768            );
11769            controlled.runs.push(state.id.clone());
11770            controlled.hold_machine(Some("verification resource unavailable".into()));
11771            queue.put(&mut controlled).unwrap();
11772            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11773            assert_eq!(resumed.status, TaskStatus::Queued);
11774            assert_eq!(
11775                resumed.resume_override.unwrap().pinned_run,
11776                Some(state.id.clone())
11777            );
11778            assert_eq!(resumed.attempts, 0);
11779
11780            // A genuinely unresolved final review still exhausts the budget.
11781            state.config.graph.review_rounds = 1;
11782            let mut unresolved = review_round(1);
11783            unresolved.blocking = 1;
11784            state.reviews = vec![unresolved];
11785            state.resource_block = None;
11786            state.save_under(home.path()).unwrap();
11787            assert!(exhausted_review_budget(&state));
11788            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11789        }
11790    }
11791
11792    #[tokio::test]
11793    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11794        if !crate::standalone_test(
11795            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11796        ) {
11797            return;
11798        }
11799        let home = tempfile::tempdir().unwrap();
11800        let mut owner = stopped_public_run(RunStatus::Blocked);
11801        owner.save_under(home.path()).unwrap();
11802        let history = vec![owner.id.clone()];
11803        let repo = owner.repo.clone();
11804        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11805        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11806        let initial =
11807            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11808        assert!(
11809            initial.is_pending(),
11810            "a busy record must not hold or resume the task"
11811        );
11812        owner.retired_to = Some("20260101-000001-bbbb".into());
11813        owner.save_under(home.path()).unwrap();
11814        drop(lock);
11815        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11816            .await
11817            .expect("ownership lock released")
11818            .expect("read settled owner");
11819        assert!(
11820            result.is_none(),
11821            "the retired owner must not be resumed from a stale read"
11822        );
11823    }
11824
11825    #[tokio::test]
11826    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11827        if !crate::standalone_test(
11828            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11829        ) {
11830            return;
11831        }
11832        let home = tempfile::tempdir().unwrap();
11833        let mut owner = stopped_public_run(RunStatus::Blocked);
11834        let repo = tempfile::tempdir().unwrap();
11835        crate::git::git(repo.path(), &["init"]).await.unwrap();
11836        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
11837        owner.id = "20260101-000000-aaaa".into();
11838        owner.save_under(home.path()).unwrap();
11839        let mut successor = run_state(RunStatus::Blocked);
11840        successor.id = "20260101-000001-bbbb".into();
11841        successor.save_under(home.path()).unwrap();
11842        let runs = vec![owner.id.clone(), successor.id.clone()];
11843        assert_eq!(
11844            public_resume_owner(home.path(), &runs, &owner.repo)
11845                .await
11846                .unwrap()
11847                .unwrap()
11848                .id,
11849            owner.id
11850        );
11851        let subdir = owner.repo.join("nested");
11852        std::fs::create_dir(&subdir).unwrap();
11853        assert_eq!(
11854            public_resume_owner(home.path(), &runs, &subdir)
11855                .await
11856                .unwrap()
11857                .unwrap()
11858                .id,
11859            owner.id
11860        );
11861        #[cfg(unix)]
11862        {
11863            let alias = home.path().join("repo-alias");
11864            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
11865            assert_eq!(
11866                public_resume_owner(home.path(), &runs, &alias.join("nested"))
11867                    .await
11868                    .unwrap()
11869                    .unwrap()
11870                    .id,
11871                owner.id
11872            );
11873        }
11874        let different = tempfile::tempdir().unwrap();
11875        crate::git::git(different.path(), &["init"]).await.unwrap();
11876        assert!(
11877            public_resume_owner(home.path(), &runs, different.path())
11878                .await
11879                .is_err()
11880        );
11881        std::fs::remove_file(
11882            home.path()
11883                .join("runs")
11884                .join(&successor.id)
11885                .join("run.json"),
11886        )
11887        .unwrap();
11888        assert!(
11889            public_resume_owner(home.path(), &runs, &owner.repo)
11890                .await
11891                .is_err()
11892        );
11893    }
11894
11895    #[test]
11896    fn an_ordinary_release_keeps_a_resumable_run_available() {
11897        let mut released = task();
11898        released.start("stalled-run".to_owned());
11899        released.release();
11900        let unfinished = (!released.fresh_start)
11901            .then(|| Some("stalled-run".to_owned()))
11902            .flatten();
11903        assert_eq!(
11904            choose_starter(None, false, unfinished.as_deref()),
11905            Starter::Resume("stalled-run".to_owned()),
11906            "manual release must preserve the normal resume path"
11907        );
11908    }
11909
11910    #[test]
11911    fn resume_refusals_explain_admission_without_changing_task_or_run() {
11912        crate::run::pin_test_home();
11913        use crate::handover::{ResumeRefusal, resume_refusal_under};
11914        let home = tempfile::tempdir().unwrap();
11915        let mut exhausted = run_state(RunStatus::Blocked);
11916        exhausted.driver_exited = true;
11917        exhausted.config.graph.review_rounds = 3;
11918        exhausted.reviews = (1..=3).map(review_round).collect();
11919        for refusal in [
11920            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
11921            ResumeRefusal::Status(RunStatus::Ready),
11922            ResumeRefusal::Released("20261022-000000-aaaa".into()),
11923            ResumeRefusal::Retired("retirement-successor".into()),
11924            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
11925        ] {
11926            let mut state = exhausted.clone();
11927            let expected = match refusal {
11928                ResumeRefusal::Status(_) => {
11929                    state.status = RunStatus::Ready;
11930                    "status `ready`"
11931                }
11932                ResumeRefusal::Released(ref target) => {
11933                    state.released_to = Some(target.clone());
11934                    "execution was released"
11935                }
11936                ResumeRefusal::Retired(ref target) => {
11937                    state.retired_to = Some(target.clone());
11938                    "execution was retired"
11939                }
11940                ResumeRefusal::OwnershipTransferred(ref target) => {
11941                    state.pr_taken_over_by = Some(target.clone());
11942                    "PR ownership was transferred"
11943                }
11944                _ => "review budget exhausted (3/3 rounds used)",
11945            };
11946            assert_eq!(
11947                resume_refusal_under(&state, Some(home.path())),
11948                Some(refusal.clone())
11949            );
11950            assert_eq!(
11951                refusal.successor(),
11952                state
11953                    .released_to
11954                    .as_deref()
11955                    .or(state.retired_to.as_deref())
11956                    .or(state.pr_taken_over_by.as_deref())
11957            );
11958            state.save_under(home.path()).unwrap();
11959            let queue = Queue::at(home.path().join("queue"));
11960            let mut task = Task::new(
11961                "retained implementation".into(),
11962                state.instruction.clone(),
11963                state.repo.clone(),
11964                Source::Agent {
11965                    run: "talk".into(),
11966                    node: crate::queue::CHAT_NODE.into(),
11967                },
11968            );
11969            task.runs.push(state.id.clone());
11970            task.hold_machine(Some("stopped".into()));
11971            queue.put(&mut task).unwrap();
11972            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
11973            let before_run = serde_json::to_value(&state).unwrap();
11974            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
11975                .unwrap_err()
11976                .to_string();
11977            assert!(error.contains(expected), "{error}");
11978            assert!(!error.contains("only a stalled or blocked"), "{error}");
11979            if matches!(refusal, ResumeRefusal::Status(_)) {
11980                assert!(
11981                    error.contains("is final; there is nothing left to resume"),
11982                    "{error}"
11983                );
11984            }
11985            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
11986                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
11987                assert!(error.contains("review-only successor with a new review budget"));
11988                assert!(error.contains("does not resume this run"));
11989            }
11990            for target in [
11991                &state.released_to,
11992                &state.retired_to,
11993                &state.pr_taken_over_by,
11994            ]
11995            .into_iter()
11996            .flatten()
11997            {
11998                let short = if state.retired_to.as_ref() == Some(target) {
11999                    target.as_str()
12000                } else {
12001                    crate::run::short_of(target)
12002                };
12003                assert!(
12004                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12005                    "{error}"
12006                );
12007                if short != target {
12008                    assert!(!error.contains(target), "full successor id leaked: {error}");
12009                }
12010            }
12011            assert_eq!(
12012                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12013                before_task
12014            );
12015            assert_eq!(
12016                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12017                    .unwrap(),
12018                before_run
12019            );
12020            let question = action_question(&state.id, resume_action(&state.id));
12021            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12022                let ActionDecision::Refuse(detail) =
12023                    decide_action(&task, &question, phrases, |_| Ok(state.clone()))
12024                else {
12025                    panic!("refusal expected");
12026                };
12027                assert!(detail.contains(expected), "{detail}");
12028            }
12029        }
12030        // Preserve predicate ordering, while keeping every recorded destination visible.
12031        exhausted.status = RunStatus::Ready;
12032        exhausted.released_to = Some("released".into());
12033        exhausted.retired_to = Some("retired".into());
12034        exhausted.pr_taken_over_by = Some("owner".into());
12035        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12036        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12037        let detail = reason.diagnostic(&exhausted);
12038        for target in ["released", "retired", "owner"] {
12039            assert!(detail.contains(&format!("magi show {target}")));
12040        }
12041    }
12042
12043    #[test]
12044    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12045        let home = tempfile::tempdir().unwrap();
12046        let mut state = run_state(RunStatus::Blocked);
12047        state.driver_exited = true;
12048        state.config.graph.review_rounds = 1;
12049        state.reviews = vec![review_round(1)];
12050        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12051        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12052            let mut saved = state.clone();
12053            match checkpoint {
12054                "publication" => saved.pr_publication_pending = true,
12055                "approval" => {
12056                    saved.land_approval = Some(crate::run::LandApproval {
12057                        question: "approval".into(),
12058                        head: "head".into(),
12059                    })
12060                }
12061                "armed" => saved.land_armed_head = Some("head".into()),
12062                "landing" => saved.status = RunStatus::Landing,
12063                _ => {
12064                    let mut question = ask::Question::new(
12065                        saved.id.clone(),
12066                        "review".into(),
12067                        "review-1".into(),
12068                        "continue?".into(),
12069                        String::new(),
12070                        vec!["continue".into()],
12071                    );
12072                    ask::Questions::at(home.path().join("questions"))
12073                        .put(&mut question)
12074                        .unwrap();
12075                }
12076            }
12077            saved.save_under(home.path()).unwrap();
12078            assert!(
12079                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12080                "{checkpoint}"
12081            );
12082            assert!(
12083                crate::resume::validate(home.path(), &saved.id).is_ok(),
12084                "{checkpoint}"
12085            );
12086        }
12087    }
12088
12089    #[test]
12090    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12091        let mut state = run_state(RunStatus::Blocked);
12092        state.config.graph.review_rounds = 3;
12093        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12094        assert!(exhausted_review_budget(&state));
12095
12096        // One round still unused: resuming can still ask a reviewer something.
12097        state.reviews.pop();
12098        assert!(!exhausted_review_budget(&state));
12099
12100        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12101        // count: only a `Blocked` run re-enters the review loop on resume.
12102        let mut stalled = run_state(RunStatus::Stalled);
12103        stalled.config.graph.review_rounds = 1;
12104        stalled.reviews = vec![review_round(1)];
12105        assert!(!exhausted_review_budget(&stalled));
12106    }
12107
12108    fn review_round(round: usize) -> crate::run::ReviewRound {
12109        crate::run::ReviewRound {
12110            round,
12111            head: "deadbeef".to_owned(),
12112            verified_head: None,
12113            verified_at: None,
12114            reviews: Vec::new(),
12115            e2e: Vec::new(),
12116            verify_retried: false,
12117            e2e_deferred: false,
12118            e2e_defer_reason: None,
12119            fix: None,
12120            blocking: 0,
12121            answered: 1,
12122            expected: 1,
12123            clean: false,
12124            progressed: true,
12125            vote_split: false,
12126            reconsideration: Vec::new(),
12127            verdict: None,
12128        }
12129    }
12130
12131    #[test]
12132    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12133        let mut run = RunState::new(
12134            PathBuf::from("/repo"),
12135            "main".to_owned(),
12136            "abc1234def".to_owned(),
12137            "add retries".to_owned(),
12138            Config::default(),
12139        );
12140        run.status = RunStatus::Judging;
12141        run.parked = true;
12142        let mut task = Task::new(
12143            "add retries".to_owned(),
12144            "add retries".to_owned(),
12145            PathBuf::from("/repo"),
12146            crate::queue::Source::Human,
12147        );
12148        task.status = TaskStatus::Failed;
12149        task.runs = vec![run.id.clone()];
12150        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12151        assert!(with(&task, &run), "parked after judging is the case");
12152        let mut parked_task = task.clone();
12153        parked_task.status = TaskStatus::Parked;
12154        assert!(with(&parked_task, &run), "the Parked status is the case");
12155
12156        let mut not_parked = run.clone();
12157        not_parked.parked = false;
12158        not_parked.status = RunStatus::Stalled;
12159        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12160
12161        let mut fresh = task.clone();
12162        fresh.fresh_start = true;
12163        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12164
12165        let mut review = task.clone();
12166        review.review_branch = Some("magi/x/A".to_owned());
12167        assert!(!with(&review, &run), "review is ranked before resume");
12168
12169        let mut held = task.clone();
12170        held.status = TaskStatus::Held;
12171        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12172
12173        let mut released = run.clone();
12174        released.released_to = Some("20260901-000000-new1".to_owned());
12175        assert!(!with(&task, &released), "nothing left to resume into");
12176
12177        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12178            "unreadable"
12179        )));
12180    }
12181
12182    #[test]
12183    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12184        let mut released = RunState::new(
12185            PathBuf::from("/repo"),
12186            "main".to_owned(),
12187            "abc1234def".to_owned(),
12188            "add retries".to_owned(),
12189            Config::default(),
12190        );
12191        released.status = RunStatus::Blocked;
12192        assert_eq!(
12193            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12194            Some(released.id.clone())
12195        );
12196        released.released_to = Some("20260901-000000-new1".to_owned());
12197        assert_eq!(
12198            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12199            None,
12200            "there is nothing left to resume it into"
12201        );
12202    }
12203
12204    #[test]
12205    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12206        // Mirrors the failure this exists to close: a task's last run ended
12207        // `Blocked` with the review budget spent, `crate::conduct` chose
12208        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12209        // evidence), and without this check `attempt` would go on treating
12210        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12211        // review loop iterates zero times over an already-spent budget, so
12212        // the resumed run settles right back to `Blocked` having asked nobody
12213        // anything, and `Requeue`'s promised fresh competition never happens.
12214        let mut exhausted = RunState::new(
12215            PathBuf::from("/repo"),
12216            "main".to_owned(),
12217            "abc1234def".to_owned(),
12218            "add retries".to_owned(),
12219            Config::default(),
12220        );
12221        exhausted.status = RunStatus::Blocked;
12222        exhausted.config.graph.review_rounds = 1;
12223        exhausted.reviews = vec![review_round(1)];
12224
12225        assert_eq!(
12226            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12227            None,
12228            "an exhausted `Blocked` run must not be offered as resumable"
12229        );
12230
12231        // A `Blocked` run with rounds still unused is genuinely worth
12232        // resuming, and must still be found.
12233        let mut has_budget_left = RunState::new(
12234            PathBuf::from("/repo"),
12235            "main".to_owned(),
12236            "abc1234def".to_owned(),
12237            "add retries".to_owned(),
12238            Config::default(),
12239        );
12240        has_budget_left.status = RunStatus::Blocked;
12241        has_budget_left.config.graph.review_rounds = 3;
12242        has_budget_left.reviews = vec![review_round(1)];
12243
12244        assert_eq!(
12245            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12246                Ok(has_budget_left.clone())
12247            }),
12248            Some(has_budget_left.id.clone())
12249        );
12250    }
12251
12252    #[test]
12253    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12254        let mut run = RunState::new(
12255            PathBuf::from("/repo"),
12256            "main".to_owned(),
12257            "abc1234def".to_owned(),
12258            "add retries".to_owned(),
12259            Config::default(),
12260        );
12261        run.status = RunStatus::Blocked;
12262        run.config.graph.review_rounds = 1;
12263        run.reviews = vec![review_round(1)];
12264        run.pr_publication_pending = true;
12265        assert_eq!(
12266            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12267            Some(run.id.clone()),
12268            "a spent review budget must not turn a failed publication into a re-competition"
12269        );
12270    }
12271
12272    #[test]
12273    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12274        let mut task = Task::new(
12275            "recover work".into(),
12276            "recover work".into(),
12277            PathBuf::from("/repo"),
12278            crate::queue::Source::Human,
12279        );
12280        let mut history = std::collections::BTreeMap::new();
12281        for index in 0..8 {
12282            let mut run = run_state(RunStatus::Blocked);
12283            run.id = format!("20260101-000000-{index:04}");
12284            run.base_commit = format!("upstream-{index}");
12285            // Seven empty newer attempts must not erase the old recovery owner.
12286            if index > 0 {
12287                run.candidates.clear();
12288            }
12289            task.runs.extend([run.id.clone(), run.id.clone()]);
12290            history.insert(run.id.clone(), run);
12291            task.requeue();
12292        }
12293        let check = |task: &Task, starter: &Starter, limit| {
12294            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12295        };
12296        assert!(
12297            check(&task, &Starter::Start, 8)
12298                .unwrap()
12299                .contains("8 unretired")
12300        );
12301        assert!(check(&task, &Starter::Start, 9).is_none());
12302        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12303        task.release_operator("owner", None);
12304        assert_eq!(task.attempts, 0);
12305        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12306        assert!(check(&restored, &Starter::Start, 8).is_some());
12307        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12308        assert!(check(&restored, &Starter::Start, 0).is_none());
12309    }
12310
12311    #[test]
12312    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12313        let mut task = Task::new(
12314            "recover work".into(),
12315            "recover work".into(),
12316            PathBuf::from("/repo"),
12317            crate::queue::Source::Human,
12318        );
12319        let mut run = run_state(RunStatus::Superseded);
12320        run.candidates.clear();
12321        task.runs.push(run.id.clone());
12322        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12323        run.retired_to = Some("authority".into());
12324        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12325        run.retired_to = None;
12326        run.released_to = Some("authority".into());
12327        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12328        assert!(
12329            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12330                .unwrap()
12331                .contains("Cannot verify")
12332        );
12333        // Resuming an existing owner needs no new inventory or worktree budget.
12334        assert!(
12335            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12336                panic!("resume must not load historical attempts")
12337            })
12338            .is_none()
12339        );
12340    }
12341
12342    #[test]
12343    fn retired_resume_requires_a_valid_same_repository_authority() {
12344        let mut source = run_state(RunStatus::Blocked);
12345        let mut empty = run_state(RunStatus::Blocked);
12346        empty.retired_to = Some(source.id.clone());
12347        let runs = vec![source.id.clone(), empty.id.clone()];
12348        let resolve = |source: &RunState, empty: &RunState| {
12349            unfinished_run_with(&runs, "fixture", |id| {
12350                if id == source.id {
12351                    Ok(source.clone())
12352                } else if id == empty.id {
12353                    Ok(empty.clone())
12354                } else {
12355                    bail!("unreadable authority")
12356                }
12357            })
12358        };
12359        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12360        assert_eq!(
12361            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12362            Starter::Resume(source.id.clone())
12363        );
12364        source.retired_to = Some(empty.id.clone());
12365        assert!(
12366            resolve(&source, &empty).is_none(),
12367            "cycles do not revive obsolete runs"
12368        );
12369        source.retired_to = None;
12370        source.repo = PathBuf::from("/another-repository");
12371        assert!(resolve(&source, &empty).is_none());
12372        source.repo = empty.repo.clone();
12373        source.released_to = Some("later".into());
12374        assert!(resolve(&source, &empty).is_none());
12375        empty.retired_to = Some("unlisted-run".into());
12376        assert!(resolve(&source, &empty).is_none());
12377    }
12378
12379    #[test]
12380    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12381        // A task whose history holds an *older* run that still looks
12382        // resumable (say, a competition `Runner::review` was started
12383        // alongside after that older run went `Stalled`) and a *newest* run
12384        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12385        // on this task must mean a fresh competition — falling back to the
12386        // stale, superseded `Stalled` run instead would resurrect history
12387        // nothing asked to revisit and silently defeat the requeue.
12388        let mut older_stalled = RunState::new(
12389            PathBuf::from("/repo"),
12390            "main".to_owned(),
12391            "abc1234def".to_owned(),
12392            "add retries".to_owned(),
12393            Config::default(),
12394        );
12395        older_stalled.status = RunStatus::Stalled;
12396
12397        let mut newest_exhausted = RunState::new(
12398            PathBuf::from("/repo"),
12399            "main".to_owned(),
12400            "abc1234def".to_owned(),
12401            "add retries".to_owned(),
12402            Config::default(),
12403        );
12404        newest_exhausted.status = RunStatus::Blocked;
12405        newest_exhausted.config.graph.review_rounds = 1;
12406        newest_exhausted.reviews = vec![review_round(1)];
12407
12408        assert_eq!(
12409            unfinished_run_with(
12410                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12411                "t",
12412                |_| Ok(newest_exhausted.clone())
12413            ),
12414            None,
12415            "the newest run is exhausted, so nothing here is worth resuming - \
12416             least of all the older, already-superseded run"
12417        );
12418    }
12419
12420    #[test]
12421    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12422        assert_eq!(
12423            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12424                Err(anyhow::anyhow!("fixture is absent"))
12425            }),
12426            None
12427        );
12428    }
12429
12430    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12431        let mut q = ask::Question::new(
12432            run.to_owned(),
12433            "implement".to_owned(),
12434            "impl-A".to_owned(),
12435            "continue?".to_owned(),
12436            String::new(),
12437            vec!["resume で続行する".to_owned(), "other".to_owned()],
12438        );
12439        q.actions.insert("resume で続行する".to_owned(), action);
12440        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12441            .unwrap();
12442        q
12443    }
12444
12445    fn held_task_with(run: &str) -> Task {
12446        let mut t = task();
12447        t.runs = vec![run.to_owned()];
12448        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12449        t
12450    }
12451
12452    fn resume_action(run: &str) -> ask::ChoiceAction {
12453        ask::ChoiceAction::Resume { run: run.into() }
12454    }
12455
12456    #[test]
12457    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12458        for parked in [false, true] {
12459            let mut t = task();
12460            t.start("A".into());
12461            t.start("B".into());
12462            assert_eq!(t.runs, vec!["A", "B"]);
12463            t.start("A".into());
12464            let mut resumed = run_state(RunStatus::Blocked);
12465            resumed.id = "A".into();
12466            resumed.parked = parked;
12467            resumed.driver_exited = true;
12468            t.hold_machine(Some("resumed run stopped".into()));
12469            let q = action_question("A", resume_action("A"));
12470            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12471            assert_eq!(
12472                decide_action(&t, &q, &PHRASES_EN, |id| {
12473                    assert_eq!(id, "A");
12474                    Ok(resumed.clone())
12475                }),
12476                ActionDecision::Resume("A".into())
12477            );
12478            assert_eq!(
12479                action_standing(&t, &action_question("B", resume_action("B"))),
12480                ActionStanding::Stale
12481            );
12482            t.release_operator("cli", None);
12483            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12484                assert_eq!(id, "A");
12485                Ok(resumed.clone())
12486            });
12487            assert_eq!(
12488                choose_starter(None, false, unfinished.as_deref()),
12489                Starter::Resume("A".into())
12490            );
12491            assert_eq!(t.runs, vec!["B", "A"]);
12492        }
12493    }
12494
12495    #[test]
12496    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12497        let mut state = crate::land::tests::repair_state(true, true);
12498        state.status = RunStatus::Landing;
12499        state.parked = true;
12500        state.driver_exited = true;
12501        let mut q = ask::Question::new(
12502            state.id.clone(),
12503            land::APPROVAL_NODE.into(),
12504            "land".into(),
12505            "Merge?".into(),
12506            String::new(),
12507            vec![land::APPROVE.into(), land::HOLD.into()],
12508        );
12509        q.id = state.id.clone();
12510        state.land_approval = Some(crate::run::LandApproval {
12511            question: q.id.clone(),
12512            head: "current-head".into(),
12513        });
12514        assert!(land::upgrade_repair_choice(&mut q, &state));
12515        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12516        let mut task = held_task_with(&state.id);
12517        task.status = TaskStatus::Parked;
12518        assert_eq!(
12519            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12520            ActionDecision::Resume(state.id.clone())
12521        );
12522        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12523        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12524        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12525        assert_eq!(
12526            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12527            ActionDecision::Resume(state.id.clone()),
12528            "a repair answer newer than the manual hold resumes the existing owner"
12529        );
12530        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12531        for answered_at in [q.answered_at, None] {
12532            let mut older = q.clone();
12533            older.answered_at = answered_at;
12534            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
12535                panic!("a later manual hold must prevent dispatch")
12536            });
12537            let ActionDecision::Refuse(reason) = refused else {
12538                panic!("expected an actionable refusal, got {refused:?}");
12539            };
12540            assert!(reason.contains("later operator decision"));
12541            assert!(reason.contains(&format!("magi task release {}", task.id)));
12542        }
12543        task.operator_decided_at = None;
12544        let mut superseded = state.clone();
12545        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12546        assert_eq!(
12547            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
12548            ActionDecision::Stale
12549        );
12550        for case in 1..4 {
12551            let mut changed = state.clone();
12552            match case {
12553                1 => changed.status = RunStatus::Blocked,
12554                2 => changed.released_to = Some("new-owner".into()),
12555                _ => changed.land_approval.as_mut().unwrap().head.clear(),
12556            }
12557            assert!(matches!(
12558                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
12559                ActionDecision::Refuse(_)
12560            ));
12561        }
12562        assert!(matches!(
12563            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
12564            ActionDecision::Refuse(_)
12565        ));
12566        task.runs.push("replacement".into());
12567        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12568        assert_eq!(
12569            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
12570                "old owner must not load"
12571            )),
12572            ActionDecision::Stale
12573        );
12574    }
12575
12576    #[test]
12577    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12578        let mut state = crate::land::tests::repair_state(true, true);
12579        state.status = RunStatus::Landing;
12580        state.parked = true;
12581        state.driver_exited = true;
12582        let mut q = ask::Question::new(
12583            state.id.clone(),
12584            land::APPROVAL_NODE.into(),
12585            "land".into(),
12586            "Merge?".into(),
12587            String::new(),
12588            vec![land::APPROVE.into(), land::HOLD.into()],
12589        );
12590        q.id = state.id.clone();
12591        state.land_approval = Some(crate::run::LandApproval {
12592            question: q.id.clone(),
12593            head: "current-head".into(),
12594        });
12595        state.save().unwrap();
12596        land::upgrade_repair_choice(&mut q, &state);
12597        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12598        Questions::open().put(&mut q).unwrap();
12599        let tmp = tempfile::tempdir().unwrap();
12600        let queue = Queue::at(tmp.path().join("queue"));
12601        let mut task = held_task_with(&state.id);
12602        task.status = TaskStatus::Parked;
12603        queue.put(&mut task).unwrap();
12604        let empty = Arc::new(tokio::sync::Semaphore::new(0));
12605        let free = Arc::new(tokio::sync::Semaphore::new(1));
12606        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12607        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12608        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12609        assert!(claim.permit.is_some());
12610        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12611        drop(claim);
12612        Questions::open()
12613            .update(&q.id, |q| {
12614                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12615                Ok(())
12616            })
12617            .unwrap();
12618        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12619        assert!(claim.permit.is_none());
12620        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12621    }
12622
12623    #[test]
12624    fn decide_action_resumes_only_the_latest_resumable_run() {
12625        let t = held_task_with("r1");
12626        let q = action_question("r1", resume_action("r1"));
12627        let load = |s: RunState| move |_: &str| Ok(s);
12628        assert_eq!(
12629            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
12630            ActionDecision::Resume("r1".into())
12631        );
12632        // Not the latest run of the task.
12633        let q_other = action_question("r1", resume_action("r0"));
12634        assert!(matches!(
12635            decide_action(
12636                &t,
12637                &q_other,
12638                &PHRASES_EN,
12639                load(run_state(RunStatus::Blocked))
12640            ),
12641            ActionDecision::Refuse(_)
12642        ));
12643        // A finished run cannot make progress.
12644        assert!(matches!(
12645            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
12646            ActionDecision::Refuse(_)
12647        ));
12648        // A released one either.
12649        let mut released = run_state(RunStatus::Blocked);
12650        released.released_to = Some("elsewhere".into());
12651        assert!(matches!(
12652            decide_action(&t, &q, &PHRASES_EN, load(released)),
12653            ActionDecision::Refuse(_)
12654        ));
12655        // Unreadable state is a refusal, never a fresh competition.
12656        assert!(matches!(
12657            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
12658            ActionDecision::Refuse(_)
12659        ));
12660    }
12661
12662    #[test]
12663    fn decide_action_ignores_a_question_about_an_earlier_run() {
12664        let mut t = held_task_with("r1");
12665        t.runs.push("r2".to_owned());
12666        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12667        assert_eq!(
12668            decide_action(
12669                &t,
12670                &action_question("r1", ask::ChoiceAction::Done),
12671                &PHRASES_EN,
12672                never
12673            ),
12674            ActionDecision::Stale
12675        );
12676    }
12677
12678    #[test]
12679    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
12680        let mut t = held_task_with("r1");
12681        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12682        assert_eq!(
12683            decide_action(
12684                &t,
12685                &action_question("r1", ask::ChoiceAction::Requeue),
12686                &PHRASES_EN,
12687                never
12688            ),
12689            ActionDecision::Requeue
12690        );
12691        let done_q = action_question("r1", ask::ChoiceAction::Done);
12692        assert_eq!(
12693            decide_action(&t, &done_q, &PHRASES_EN, never),
12694            ActionDecision::Done
12695        );
12696        t.mark_action_applied(&done_q.id);
12697        assert_eq!(
12698            decide_action(&t, &done_q, &PHRASES_EN, never),
12699            ActionDecision::Skip
12700        );
12701
12702        // A plain answer (no action for that label) does nothing.
12703        let mut plain = action_question("r1", ask::ChoiceAction::Done);
12704        plain.actions.clear();
12705        assert_eq!(
12706            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
12707            ActionDecision::Skip
12708        );
12709        // A running task is left alone.
12710        let mut running = held_task_with("r1");
12711        running.status = TaskStatus::Running;
12712        assert_eq!(
12713            decide_action(
12714                &running,
12715                &action_question("r1", ask::ChoiceAction::Done),
12716                &PHRASES_EN,
12717                never
12718            ),
12719            ActionDecision::Skip
12720        );
12721    }
12722
12723    #[test]
12724    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
12725        crate::run::pin_test_home();
12726        for legacy in [false, true] {
12727            let dir = tempfile::tempdir().unwrap();
12728            let queue = Queue::at(dir.path().join("queue"));
12729            let questions = Questions::at(dir.path().join("questions"));
12730            let run = "20260101-000000-hold";
12731            let mut task = held_task_with(run);
12732            task.status = TaskStatus::Parked;
12733            let mut q = ask::Question::new(
12734                run.into(),
12735                land::APPROVAL_NODE.into(),
12736                "land".into(),
12737                "Repair?".into(),
12738                String::new(),
12739                vec![land::REPAIR.into()],
12740            );
12741            q.actions.insert(land::REPAIR.into(), resume_action(run));
12742            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12743            // Deterministically order the answer before the actual manual hold.
12744            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12745            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
12746            questions.put(&mut q).unwrap();
12747            task.hold_manual(Some("Keep this PR paused".into()));
12748            if legacy {
12749                task.hold_source = None;
12750            }
12751            queue.put(&mut task).unwrap();
12752
12753            apply_task_choice_actions(&queue, &questions, dir.path());
12754            let after = queue.get(&task.id).unwrap();
12755            assert!(after.operator_held());
12756            assert_eq!(after.hold_source, task.hold_source);
12757            assert_eq!(after.operator_decided_at, task.operator_decided_at);
12758            assert_eq!(after.runs, task.runs);
12759            assert_eq!(after.instruction, task.instruction);
12760            assert!(after.resume_override.is_none());
12761            assert!(after.action_applied(&q.id));
12762            let reason = after.hold_reason.as_deref().unwrap();
12763            assert!(reason.starts_with("Keep this PR paused"));
12764            assert!(reason.contains("later operator decision"));
12765            assert!(reason.contains(&format!("magi task release {}", task.id)));
12766
12767            for recovery in [
12768                crate::conduct::Recovery::Review,
12769                crate::conduct::Recovery::Requeue,
12770            ] {
12771                crate::conduct::apply(
12772                    &queue,
12773                    &questions,
12774                    &crate::conduct::Verdict {
12775                        decisions: vec![crate::conduct::Decision {
12776                            id: task.id.clone(),
12777                            recovery: Some(recovery),
12778                            ..Default::default()
12779                        }],
12780                    },
12781                )
12782                .unwrap();
12783            }
12784            // Reconciliation is idempotent, and automatic recovery cannot
12785            // reopen this owner after it observes the rejected repair answer.
12786            apply_task_choice_actions(&queue, &questions, dir.path());
12787            let still_held = queue.get(&task.id).unwrap();
12788            assert!(still_held.operator_held());
12789            assert_eq!(still_held.hold_reason, after.hold_reason);
12790            assert_eq!(still_held.runs, task.runs);
12791            assert!(still_held.review_branch.is_none());
12792            assert!(!still_held.fresh_start);
12793            assert!(queue.next_runnable().is_none());
12794        }
12795    }
12796
12797    #[test]
12798    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
12799        for held in [false, true] {
12800            for retry in [false, true] {
12801                let dir = tempfile::tempdir().unwrap();
12802                let queue = Queue::at(dir.path().join("queue"));
12803                let questions = Questions::at(dir.path().join("questions"));
12804                let home = dir.path().join("home");
12805                let mut t = task();
12806                if held {
12807                    t.hold_machine(Some("driver state unknown".into()));
12808                }
12809                queue.put(&mut t).unwrap();
12810                let verdict = serde_json::from_value(serde_json::json!({
12811                    "decisions": [{
12812                        "id": t.id,
12813                        "question": "Driver state unknown; retry the checks or hold?",
12814                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
12815                        "actions": {
12816                            "daemon: recheck and retry": {"do": "requeue"},
12817                            "daemon: hold the task": {"do": "hold"}
12818                        }
12819                    }]
12820                }))
12821                .unwrap();
12822                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
12823                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12824                let mut q = questions.list().pop().unwrap();
12825                let choice = if retry {
12826                    "daemon: recheck and retry"
12827                } else {
12828                    "daemon: hold the task"
12829                };
12830                assert_eq!(q.actions.len(), 2);
12831                q.answer(ask::Answer::Choice(choice.into())).unwrap();
12832                questions.put(&mut q).unwrap();
12833
12834                // A Web answer does not remove the deputy's fresh lease.
12835                questions.beat(&q.id, ask::WaiterKind::Deputy);
12836                for _ in 0..2 {
12837                    resolve_blockers(&queue, &questions);
12838                    apply_task_choice_actions(&queue, &questions, &home);
12839                    let waiting = queue.get(&t.id).unwrap();
12840                    assert_eq!(waiting.status, TaskStatus::Blocked);
12841                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
12842                    assert!(waiting.answers.is_empty());
12843                    assert!(!waiting.action_applied(&q.id));
12844                    assert!(runnable(&queue).is_empty());
12845                    let free = Arc::new(tokio::sync::Semaphore::new(1));
12846                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
12847                }
12848                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12849
12850                // Releasing the blocker and applying the operation share one save.
12851                resolve_blockers(&queue, &questions);
12852                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12853                apply_task_choice_actions(&queue, &questions, &home);
12854                let after = queue.get(&t.id).unwrap();
12855                assert_eq!(
12856                    after.status,
12857                    if retry {
12858                        TaskStatus::Queued
12859                    } else {
12860                        TaskStatus::Held
12861                    }
12862                );
12863                assert!(after.action_applied(&q.id));
12864                assert_eq!(after.operator_held(), !retry);
12865                assert_eq!(after.answers.len(), 1);
12866
12867                // A later operator decision must not replay this answer.
12868                let mut changed = after;
12869                if retry {
12870                    changed.hold_manual(Some("later hold".into()));
12871                } else {
12872                    changed.release_operator("test", None);
12873                }
12874                let expected = changed.status;
12875                queue.put(&mut changed).unwrap();
12876                apply_task_choice_actions(&queue, &questions, &home);
12877                assert_eq!(queue.get(&t.id).unwrap().status, expected);
12878            }
12879        }
12880    }
12881
12882    #[test]
12883    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
12884        let dir = tempfile::tempdir().unwrap();
12885        let queue = Queue::at(dir.path().join("queue"));
12886        let questions = Questions::at(dir.path().join("questions"));
12887        let home = dir.path().join("home");
12888        let mut state = run_state(RunStatus::Blocked);
12889        state.id = "20260101-000000-act1".to_owned();
12890        state.save_under(&home).unwrap();
12891
12892        let mut t = held_task_with(&state.id);
12893        queue.put(&mut t).unwrap();
12894        let mut q = action_question(&state.id, resume_action(&state.id));
12895        questions.put(&mut q).unwrap();
12896
12897        apply_task_choice_actions(&queue, &questions, &home);
12898        let after = queue.get(&t.id).unwrap();
12899        assert_eq!(after.status, TaskStatus::Queued);
12900        assert!(!after.fresh_start);
12901        assert!(after.action_applied(&q.id));
12902        let pin = after.resume_override.clone().unwrap();
12903        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
12904        assert!(pin.forced);
12905
12906        // Held again later: the same answer does not release it a second time.
12907        let mut again = queue.get(&t.id).unwrap();
12908        again.hold_machine(Some("later".into()));
12909        queue.put(&mut again).unwrap();
12910        apply_task_choice_actions(&queue, &questions, &home);
12911        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12912    }
12913
12914    #[test]
12915    fn a_delivered_answer_is_still_acted_on_exactly_once() {
12916        let dir = tempfile::tempdir().unwrap();
12917        let queue = Queue::at(dir.path().join("queue"));
12918        let questions = Questions::at(dir.path().join("questions"));
12919        let home = dir.path().join("home");
12920        let mut state = run_state(RunStatus::Blocked);
12921        state.id = "20260101-000000-act2".to_owned();
12922        state.save_under(&home).unwrap();
12923
12924        let mut t = held_task_with(&state.id);
12925        queue.put(&mut t).unwrap();
12926        let mut q = action_question(&state.id, resume_action(&state.id));
12927        q.answer_delivered = true;
12928        questions.put(&mut q).unwrap();
12929
12930        // Delivered, and the agent then died: the task is still held, so the
12931        // chosen action applies.
12932        apply_task_choice_actions(&queue, &questions, &home);
12933        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12934        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
12935
12936        // Held again: the same answer does nothing a second time.
12937        let mut again = queue.get(&t.id).unwrap();
12938        again.hold_machine(Some("later".into()));
12939        queue.put(&mut again).unwrap();
12940        apply_task_choice_actions(&queue, &questions, &home);
12941        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12942    }
12943
12944    #[test]
12945    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
12946        let dir = tempfile::tempdir().unwrap();
12947        let queue = Queue::at(dir.path().join("queue"));
12948        let questions = Questions::at(dir.path().join("questions"));
12949        let home = dir.path().join("home");
12950        let mut state = run_state(RunStatus::Blocked);
12951        state.id = "20260101-000000-act3".to_owned();
12952        state.save_under(&home).unwrap();
12953        let mut t = held_task_with(&state.id);
12954        queue.put(&mut t).unwrap();
12955        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
12956        questions.put(&mut q).unwrap();
12957
12958        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
12959        apply_task_choice_actions(&queue, &questions, &home);
12960        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12961
12962        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12963        apply_task_choice_actions(&queue, &questions, &home);
12964        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12965    }
12966
12967    #[test]
12968    fn action_standing_tells_the_reasons_apart() {
12969        let mut t = held_task_with("r1");
12970        let q = action_question("r1", ask::ChoiceAction::Requeue);
12971        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12972        let mut plain = q.clone();
12973        plain.actions.clear();
12974        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
12975
12976        // Applied wins over everything, even a running task.
12977        t.mark_action_applied(&q.id);
12978        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
12979
12980        // A newer attempt running: the old question is Stale, not Busy.
12981        let mut t = held_task_with("r1");
12982        t.start("r2".to_owned());
12983        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
12984        // The same question about the latest run just waits.
12985        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
12986        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12987        t.status = TaskStatus::Blocked;
12988        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12989
12990        // A conductor question is keyed by the task, never stale.
12991        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
12992        c.node = crate::conduct::NODE.to_owned();
12993        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
12994        assert!(!ActionStanding::Busy.daemon_owns());
12995    }
12996
12997    #[test]
12998    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
12999        let dir = tempfile::tempdir().unwrap();
13000        let queue = Queue::at(dir.path().join("queue"));
13001        let questions = Questions::at(dir.path().join("questions"));
13002        let home = dir.path().join("home");
13003        let mut state = run_state(RunStatus::Blocked);
13004        state.id = "20260101-000000-act4".to_owned();
13005        state.save_under(&home).unwrap();
13006        let mut t = held_task_with(&state.id);
13007        t.status = TaskStatus::Running;
13008        queue.put(&mut t).unwrap();
13009        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13010        q.cwd = Some(dir.path().display().to_string());
13011        questions.put(&mut q).unwrap();
13012
13013        // While the task runs the daemon will not act, so the waiter still
13014        // delivers the word to the dead asker's seat ...
13015        let running = queue.get(&t.id).unwrap();
13016        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13017        assert!(matches!(
13018            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13019            crate::waiter::Action::Deliver(_)
13020        ));
13021        // ... and the daemon waits while the task runs, then applies once.
13022        apply_task_choice_actions(&queue, &questions, &home);
13023        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13024        let mut back = queue.get(&t.id).unwrap();
13025        back.hold_machine(Some("later".into()));
13026        queue.put(&mut back).unwrap();
13027        apply_task_choice_actions(&queue, &questions, &home);
13028        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13029        let mut again = queue.get(&t.id).unwrap();
13030        again.hold_machine(Some("again".into()));
13031        queue.put(&mut again).unwrap();
13032        apply_task_choice_actions(&queue, &questions, &home);
13033        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13034    }
13035}