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(last) = state.events.last() {
6079        // The review loop's "never answered" stop is the one event worth
6080        // translating; it is recognised from structured state, not by
6081        // matching the English event text (which stays as recorded).
6082        let unanswered = state
6083            .reviews
6084            .last()
6085            .filter(|r| {
6086                state.status == RunStatus::Blocked
6087                    && last.node == "review"
6088                    && r.incomplete()
6089                    && r.blocking == 0
6090                    && r.round == state.config.graph.review_rounds
6091                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6092            })
6093            .map(|r| (r.expected - r.answered, r.round));
6094        match unanswered {
6095            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6096                detail.push_str(&format!(
6097                    " ({}: {})",
6098                    last.node,
6099                    (p.reviewers_never_answered)(missing, rounds)
6100                ));
6101            }
6102            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6103        }
6104    }
6105    detail.push_str(&format!(" [run {}]", state.id));
6106    detail
6107}
6108
6109/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6110///
6111/// The task file lives in the backlog indefinitely; a diagnostic is an
6112/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6113/// stay small regardless of how much a gate command or a candidate printed.
6114const DIAGNOSTIC_MAX: usize = 4_000;
6115
6116/// Tail kept from a single failing command's output inside a diagnostic.
6117/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6118/// pointer for a human deciding whether to go read the full artifact by hand,
6119/// not a replacement for reading it.
6120const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6121
6122/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6123/// `magi task show` says more than the one-line reason in [`describe`].
6124///
6125/// The one-liner answers "where did the run stop"; this answers "what would a
6126/// human have found opening `artifacts/` by hand" — the point of the whole
6127/// feature is the case that one-liner actively misleads on: a run held as "no
6128/// candidate produced a change" can mean the implementer actually finished
6129/// the task (opened a PR, merged it, tagged a release) and only left a clean
6130/// local worktree behind, which reads as "nothing happened" unless someone
6131/// goes and reads what the agent actually said. `None` when the run carries
6132/// none of the three shapes this recognises — an ordinary run held for
6133/// something not diagnosable from `RunState` alone still explains itself
6134/// through `Task::last_error`.
6135fn diagnostic(state: &RunState) -> Option<String> {
6136    let mut parts: Vec<String> = Vec::new();
6137
6138    // Gate failure: which check(s), and the tail of what each printed.
6139    for o in state.gate.iter().filter(|o| !o.ok()) {
6140        parts.push(format!(
6141            "gate `{}` failed ({}):\n{}",
6142            o.command,
6143            notices::exit_status(o.code),
6144            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6145        ));
6146    }
6147
6148    // The land loop gave up because the fixer declined while checks were
6149    // still red: the message already names them (see `land::run`).
6150    if let Some(last) = state
6151        .events
6152        .iter()
6153        .rev()
6154        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6155    {
6156        parts.push(last.message.clone());
6157    }
6158
6159    // No viable candidate: every implementer's own final word, sanitized the
6160    // same way a judge would have read it, so a run that actually finished
6161    // the job does not read as an unexplained failure. A verified no-op is
6162    // called out ahead of its own summary and apart from an ordinary
6163    // failure's `why` — this is the one candidate shape whose diagnostic a
6164    // human is expected to actually judge, not just skim.
6165    if state.viable().is_empty() {
6166        for c in &state.candidates {
6167            if let Some(evidence) = &c.verified_noop {
6168                parts.push(format!(
6169                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6170                    c.label
6171                ));
6172            } else if !c.summary.trim().is_empty() {
6173                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6174            } else if let Some(why) = &c.failed {
6175                parts.push(format!("candidate {}: {why}", c.label));
6176            }
6177        }
6178    }
6179
6180    if parts.is_empty() {
6181        return None;
6182    }
6183    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6184    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6185    // back slightly over. Leave it enough room to always land under the
6186    // limit.
6187    Some(crate::run::tail(
6188        &parts.join("\n\n"),
6189        DIAGNOSTIC_MAX.saturating_sub(100),
6190    ))
6191}
6192
6193/// Stable lower-case name for a run status, for an internal log line and the
6194/// "graph stopped without reaching a terminal status" bug message in
6195/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6196/// doc for why that one reads [`RunStatus::display_label`] instead. One
6197/// definition of a status's name, on the type that owns it: this table used
6198/// to live here as a second copy, and a status renamed in one place would
6199/// have gone on reading correctly in the other.
6200fn label(status: RunStatus) -> &'static str {
6201    status.as_str()
6202}
6203
6204/// Parse a merge mode override.
6205pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6206    match mode {
6207        "none" => Ok(MergeMode::None),
6208        "local" => Ok(MergeMode::Local),
6209        "pr" => Ok(MergeMode::Pr),
6210        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6211    }
6212}
6213
6214/// Take the status lock, recovering from a poisoned one.
6215///
6216/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6217/// data, and the worst a poisoned lock can hold is a stale timestamp.
6218fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6219    mutex
6220        .lock()
6221        .unwrap_or_else(std::sync::PoisonError::into_inner)
6222}
6223
6224#[cfg(test)]
6225mod tests {
6226    use super::*;
6227    use crate::queue::{Source, TaskStatus};
6228    use crate::run::{Candidate, CommandOutcome};
6229    use pretty_assertions::assert_eq;
6230
6231    fn task() -> Task {
6232        Task::new(
6233            "add retries".to_owned(),
6234            "add retries".to_owned(),
6235            PathBuf::from("/repo"),
6236            Source::Human,
6237        )
6238    }
6239
6240    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6241        let job = crate::worker::Job {
6242            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6243            sequence: 1,
6244            kind: "task".into(),
6245            key: format!("task:{}", request.task),
6246            payload: serde_json::to_value(request).unwrap(),
6247            generation: "a".repeat(64),
6248            version: None,
6249            status: crate::worker::Status::Starting,
6250            result: None,
6251            pid: None,
6252            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6253            finished_at: None,
6254        };
6255        let dir = home.join("workers/jobs").join(&job.id);
6256        std::fs::create_dir_all(&dir).unwrap();
6257        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6258        job
6259    }
6260
6261    #[test]
6262    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6263        let home = tempfile::tempdir().unwrap();
6264        let request = TaskWorker {
6265            opts: Opts::default(),
6266            queue: home.path().join("queue"),
6267            task: "startup".into(),
6268            lane: PermitKind::Ordinary,
6269            standalone: false,
6270        };
6271        let job = starting_task_reservation(home.path(), &request);
6272        let error = task_worker_spawn_error(
6273            home.path(),
6274            &request,
6275            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6276        )
6277        .expect_err("our own reservation must not turn a failed spawn into a resync");
6278        let active = crate::worker::active(home.path()).unwrap();
6279        assert_eq!(active.len(), 1);
6280        assert_eq!(active[0].id, job.id);
6281        assert_eq!(active[0].status, crate::worker::Status::Starting);
6282        assert!(
6283            crate::worker::control(home.path(), &job.key)
6284                .unwrap()
6285                .is_none()
6286        );
6287        let notices = notices::Notices::at(home.path().join("notifications")).list();
6288        assert_eq!(notices.len(), 1);
6289        assert_eq!(notices[0].key, "loop:worker-startup");
6290        assert!(!notices[0].message.contains("private-error-detail"));
6291        assert!(notices[0].message.contains(&request.task));
6292        assert!(
6293            notices[0]
6294                .message
6295                .contains("could not be started or acknowledged")
6296        );
6297        assert!(notices[0].message.contains("worker.log"));
6298        assert_eq!(
6299            notices[0].link,
6300            Some(Link::Task {
6301                id: request.task.clone()
6302            })
6303        );
6304        assert!(format!("{error:#}").contains("private-error-detail"));
6305    }
6306
6307    #[test]
6308    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6309        let home = tempfile::tempdir().unwrap();
6310        let mut request = TaskWorker {
6311            opts: Opts::default(),
6312            queue: home.path().join("queue"),
6313            task: "handoff".into(),
6314            lane: PermitKind::Ordinary,
6315            standalone: true,
6316        };
6317        let job = starting_task_reservation(home.path(), &request);
6318        request.standalone = false;
6319        task_worker_spawn_error(
6320            home.path(),
6321            &request,
6322            anyhow::anyhow!("operation key is already reserved for a different request"),
6323        )
6324        .expect("a different standalone request is the handoff race, not our startup failure");
6325        let active = crate::worker::active(home.path()).unwrap();
6326        assert_eq!(active.len(), 1);
6327        assert_eq!(active[0].id, job.id);
6328        assert_eq!(active[0].payload, job.payload);
6329        assert!(
6330            notices::Notices::at(home.path().join("notifications"))
6331                .list()
6332                .is_empty()
6333        );
6334    }
6335
6336    #[test]
6337    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6338        let home = tempfile::tempdir().unwrap();
6339        let queue = Queue::at(home.path().join("queue"));
6340        let mut task = task();
6341        task.runs = vec!["previous".into()];
6342        queue.put(&mut task).unwrap();
6343        let request = TaskWorker {
6344            opts: Opts::default(),
6345            queue: home.path().join("queue"),
6346            task: task.id.clone(),
6347            lane: PermitKind::Ordinary,
6348            standalone: false,
6349        };
6350        let job = starting_task_reservation(home.path(), &request);
6351        let claims = current_work(home.path(), Timestamp::now());
6352        assert_eq!(claims.len(), 1);
6353        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6354        assert_eq!(claims[0].run, "previous");
6355        assert!(other_claims_run(&claims, "previous", None));
6356        // Only after confirming the executing caller may admission ignore
6357        // this exact projection. Cleanup continues to observe it as live.
6358        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6359        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6360    }
6361
6362    #[test]
6363    fn admission_excludes_only_the_callers_exact_reservation() {
6364        let own = Current {
6365            worker: Some("own".into()),
6366            task: "same-task".into(),
6367            run: "previous".into(),
6368        };
6369        assert!(!other_claims_run(
6370            std::slice::from_ref(&own),
6371            "previous",
6372            Some("own")
6373        ));
6374        assert!(other_claims_run(
6375            std::slice::from_ref(&own),
6376            "previous",
6377            None
6378        ));
6379        for worker in [None, Some("other".into())] {
6380            let other = Current {
6381                worker,
6382                ..own.clone()
6383            };
6384            assert!(other_claims_run(
6385                &[own.clone(), other],
6386                "previous",
6387                Some("own")
6388            ));
6389        }
6390        let legacy: Current =
6391            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6392        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6393    }
6394
6395    #[test]
6396    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6397        let mut task = task();
6398        let mut run = run_state(RunStatus::Reviewing);
6399        run.task_instruction = Some(task.instruction.clone());
6400        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6401        let branch = "magi/test/B";
6402        run.candidates.push(crate::run::Candidate {
6403            branch: branch.into(),
6404            ..candidate('B', "preserved work", false, None)
6405        });
6406        task.runs = vec![run.id.clone()];
6407        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6408        assert_eq!(
6409            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6410            Starter::Resume(run.id.clone())
6411        );
6412        assert!(matches!(
6413            review_retry_starter(
6414                &task,
6415                Some(&run),
6416                Some("different"),
6417                true,
6418                unfinished.as_deref()
6419            ),
6420            Starter::Review(_)
6421        ));
6422        assert_eq!(
6423            review_retry_starter(
6424                &task,
6425                Some(&run),
6426                Some(branch),
6427                false,
6428                unfinished.as_deref()
6429            ),
6430            Starter::Start
6431        );
6432        task.instruction.push_str(" changed criteria");
6433        assert!(matches!(
6434            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6435            Starter::Review(_)
6436        ));
6437        assert!(matches!(
6438            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6439            Starter::Review(_)
6440        ));
6441    }
6442
6443    #[test]
6444    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6445        let dir = tempfile::tempdir().unwrap();
6446        let queue = Queue::at(dir.path().join("queue"));
6447        let mut task = task();
6448        task.status = TaskStatus::Running;
6449        task.attempts = 1;
6450        queue.put(&mut task).unwrap();
6451        let live = std::collections::BTreeSet::from([task.id.clone()]);
6452        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6453        drop(queue.claim(&task.id).unwrap());
6454        let saved = queue.get(&task.id).unwrap();
6455        assert_eq!(saved.status, TaskStatus::Running);
6456        assert_eq!(saved.attempts, 1);
6457        assert!(saved.last_error.is_none());
6458    }
6459
6460    #[test]
6461    fn standalone_workers_do_not_consume_scheduler_lanes() {
6462        let request = |task: &str, lane, standalone| TaskWorker {
6463            opts: Opts::default(),
6464            queue: PathBuf::from("/queue"),
6465            task: task.to_owned(),
6466            lane,
6467            standalone,
6468        };
6469        let mut jobs = vec![
6470            request("ordinary", PermitKind::Ordinary, false),
6471            request("standalone-urgent", PermitKind::Urgent, true),
6472            request("standalone-ordinary", PermitKind::Ordinary, true),
6473            request("decision", PermitKind::None, false),
6474        ];
6475        assert_eq!(available_slots(&jobs, 2), (1, 1));
6476        jobs.push(request("urgent", PermitKind::Urgent, false));
6477        assert_eq!(available_slots(&jobs, 2), (1, 0));
6478        assert_eq!(available_slots(&jobs, 0), (0, 0));
6479    }
6480
6481    #[test]
6482    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6483        let now = Timestamp::now();
6484        let mut reading = Reading {
6485            pid: Some(std::process::id()),
6486            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6487            ..Reading::default()
6488        };
6489        assert!(!reading.running(now));
6490        assert!(legacy_scheduler_running(&reading, now, 0));
6491        reading.worker_protocol = Some(1);
6492        assert!(!legacy_scheduler_running(&reading, now, 0));
6493    }
6494
6495    #[test]
6496    fn selected_public_head_overrides_historical_resume_and_pin() {
6497        let mut t = task();
6498        let mut old = run_state(RunStatus::Blocked);
6499        let selection = crate::pr_recovery::Selection {
6500            url: "url".into(),
6501            branch: format!("magi/task-{}", t.id),
6502            head: "a".repeat(40),
6503            source_head: None,
6504            source_run: None,
6505            source_proof: None,
6506            disposition: Some(crate::pr_recovery::Disposition::Review),
6507            instruction: t.instruction.clone(),
6508            approved_at: Timestamp::now(),
6509        };
6510        t.resume_override = Some(crate::queue::OperatorResume {
6511            pinned_run: Some(old.id.clone()),
6512            question_id: "choice".into(),
6513            at: Timestamp::now(),
6514            conductor_rehold: None,
6515            forced: false,
6516        });
6517        assert_eq!(
6518            selected_starter(&selection, Some(&old), Some(&old.id)),
6519            Starter::Review(selection.branch.clone())
6520        );
6521        old.pr_recovery = Some(selection.clone());
6522        assert_eq!(
6523            selected_starter(&selection, Some(&old), Some(&old.id)),
6524            Starter::Review(selection.branch.clone())
6525        );
6526        old.reviewed_commits = Some(vec!["implementation".into()]);
6527        assert_eq!(
6528            selected_starter(&selection, Some(&old), Some(&old.id)),
6529            Starter::Resume(old.id.clone())
6530        );
6531        let mut changed = selection.clone();
6532        changed.head = "b".repeat(40);
6533        assert_eq!(
6534            selected_starter(&changed, Some(&old), Some(&old.id)),
6535            Starter::Review(changed.branch)
6536        );
6537    }
6538
6539    #[test]
6540    fn candidate_transplant_failure_is_one_actionable_hold() {
6541        let dir = tempfile::tempdir().unwrap();
6542        let q = Queue::at(dir.path().join("queue"));
6543        let mut t = task();
6544        let mut state = run_state(RunStatus::Blocked);
6545        state.event("prep", "cannot apply referenced commit: conflict");
6546        state.prep_failure = Some("conflict".into());
6547        t.start(state.id.clone());
6548        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6549        assert_eq!(t.attempts, 1);
6550        assert_eq!(t.status, TaskStatus::Held);
6551        assert!(t.operator_held());
6552        assert!(!t.status.runnable());
6553        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6554        let first = t.chat_notice_key().unwrap();
6555        t.chat_notices.push(first.clone());
6556        t.release_operator("test", None);
6557        state.id = "another-unprepared-run".into();
6558        t.start(state.id.clone());
6559        finish_attempt(
6560            3,
6561            &q,
6562            &mut t,
6563            &state,
6564            &[],
6565            Err(anyhow::anyhow!("still conflicts")),
6566        );
6567        assert_eq!(
6568            t.chat_notice_key().as_ref(),
6569            Some(&first),
6570            "no work happened"
6571        );
6572        t.release_operator("test", None);
6573        state.prep_failure = None;
6574        state.status = RunStatus::Failed;
6575        state.begin_pass();
6576        t.start(state.id.clone());
6577        finish_attempt(
6578            1,
6579            &q,
6580            &mut t,
6581            &state,
6582            &[],
6583            Err(anyhow::anyhow!("new gate failure")),
6584        );
6585        let failure = t.chat_notice_key().unwrap();
6586        assert_ne!(failure, first, "approved recovery reached a real failure");
6587        t.release_operator("test", None);
6588        state.begin_pass();
6589        t.start(state.id.clone());
6590        finish_attempt(
6591            1,
6592            &q,
6593            &mut t,
6594            &state,
6595            &[],
6596            Err(anyhow::anyhow!("new failure on resume")),
6597        );
6598        assert_ne!(
6599            t.chat_notice_key().as_ref(),
6600            Some(&failure),
6601            "a new settled pass"
6602        );
6603    }
6604
6605    #[test]
6606    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6607        for source in ["cli", "web"] {
6608            let mut t = task();
6609            let mut run = run_state(RunStatus::Blocked);
6610            run.instruction = "Run A original criteria".into();
6611            run.task_instruction = Some(run.instruction.clone());
6612            t.start(run.id.clone());
6613            t.release_operator("choice", Some("resume-question"));
6614            t.resume_override = Some(crate::queue::OperatorResume {
6615                question_id: "resume-question".into(),
6616                at: Timestamp::now(),
6617                conductor_rehold: None,
6618                forced: true,
6619                pinned_run: Some(run.id.clone()),
6620            });
6621            t.hold_machine(Some("not enough free space to start a run".into()));
6622            let mut unchanged = t.clone();
6623            unchanged
6624                .edit("title changed".into(), unchanged.instruction.clone())
6625                .unwrap();
6626            unchanged.release_operator(source, None);
6627            assert_eq!(
6628                unchanged
6629                    .resume_override
6630                    .as_ref()
6631                    .unwrap()
6632                    .pinned_run
6633                    .as_deref(),
6634                Some(run.id.as_str())
6635            );
6636            assert!(!compatible_run_instruction(&run, &unchanged));
6637            assert!(may_resume_run(&run, &unchanged));
6638
6639            t.edit(
6640                "approved recovery".into(),
6641                "Reuse measured PR head B; fix Clippy; review".into(),
6642            )
6643            .unwrap();
6644            assert!(t.resume_override.is_none());
6645            t.release_operator(source, None);
6646            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6647            assert!(reloaded.resume_override.is_none());
6648            assert!(!may_resume_run(&run, &reloaded));
6649            let unfinished =
6650                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6651                    .filter(|_| may_resume_run(&run, &reloaded));
6652            assert_eq!(
6653                choose_starter(None, false, unfinished.as_deref()),
6654                Starter::Start
6655            );
6656            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6657            assert_eq!(
6658                reloaded.resumption_history[0].question_id.as_deref(),
6659                Some("resume-question")
6660            );
6661
6662            // A revision already persisted with the old approval/pin is also
6663            // invalidated when the new operator release is recorded.
6664            unchanged.instruction = "Reuse measured PR head B".into();
6665            unchanged.hold_machine(Some("disk hold".into()));
6666            unchanged.release_operator(source, None);
6667            assert!(unchanged.resume_override.is_none());
6668            assert!(!may_resume_run(&run, &unchanged));
6669        }
6670    }
6671
6672    #[test]
6673    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6674        let mut t = task();
6675        let mut run = run_state(RunStatus::Blocked);
6676        t.review_of = Some("approved-head".into());
6677        t.instruction =
6678            "Review the branch `approved-head` (review-only: no implementation, no judging)."
6679                .into();
6680        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();
6681        run.reviewed_commits = Some(vec!["Commit log".into()]);
6682        t.start(run.id.clone());
6683        t.hold_machine(Some("interrupted review".into()));
6684        t.release_operator("cli", None);
6685        assert!(
6686            compatible_run_instruction(&run, &t),
6687            "legacy explicit review remains resumable"
6688        );
6689        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6690            .filter(|_| compatible_run_instruction(&run, &t));
6691        assert_eq!(
6692            choose_starter(None, false, unfinished.as_deref()),
6693            Starter::Resume(run.id.clone())
6694        );
6695        run.task_instruction = Some(t.instruction.clone());
6696        assert!(compatible_run_instruction(&run, &t));
6697        let reloaded: RunState =
6698            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6699        assert!(compatible_run_instruction(&reloaded, &t));
6700        t.edit(
6701            "new approved head".into(),
6702            "Reuse measured PR head B".into(),
6703        )
6704        .unwrap();
6705        assert!(!compatible_run_instruction(&run, &t));
6706
6707        // Legacy recovery reviews retain the task criteria ahead of the log.
6708        t.review_of = None;
6709        t.instruction = "Fix Clippy on approved head".into();
6710        run.task_instruction = None;
6711        run.instruction = format!(
6712            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6713            t.instruction
6714        );
6715        assert!(compatible_run_instruction(&run, &t));
6716        t.instruction.push('\n');
6717        assert!(
6718            compatible_run_instruction(&run, &t),
6719            "legacy generated review trimmed the original criteria"
6720        );
6721        t.hold_for_handover(Some("approved-head".into()), "refused".into());
6722        let mut unchanged = t.clone();
6723        assert_eq!(
6724            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6725            Some("approved-head")
6726        );
6727        t.edit("new plan".into(), "Reuse measured PR head B".into())
6728            .unwrap();
6729        assert!(take_review_branch(&mut t, Some(&run)).is_none());
6730        assert!(!compatible_run_instruction(&run, &t));
6731        t.review_branch = Some("approved-head".into());
6732        t.review_instruction = None;
6733        assert!(
6734            take_review_branch(&mut t, Some(&run)).is_none(),
6735            "legacy retained candidate cannot replace a revised approved head"
6736        );
6737    }
6738
6739    #[test]
6740    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6741        crate::run::pin_test_home();
6742        let dir = tempfile::tempdir().unwrap();
6743        let queue = Queue::at(dir.path().join("queue"));
6744        for resume in [true, false] {
6745            let state = run_state(RunStatus::Blocked);
6746            let mut t = task();
6747            t.start(state.id.clone());
6748            let action = if resume {
6749                ask::ChoiceAction::Resume {
6750                    run: state.id.clone(),
6751                }
6752            } else {
6753                ask::ChoiceAction::Requeue
6754            };
6755            let mut q = action_question(&state.id, action);
6756            q.status = ask::QuestionStatus::Open;
6757            q.answer = None;
6758            q.answered_at = None;
6759            t.fail("run stopped with a question", 3);
6760            hold_if_runnable(&queue, &mut t);
6761            assert!(t.operator_decided_at.is_none());
6762            assert!(t.operator_held());
6763            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6764            let expected = if resume {
6765                ActionDecision::Resume(state.id.clone())
6766            } else {
6767                ActionDecision::Requeue
6768            };
6769            assert_eq!(
6770                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6771                expected
6772            );
6773            t.hold_manual(Some("later explicit hold".into()));
6774            assert_eq!(
6775                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6776                ActionDecision::Stale
6777            );
6778        }
6779    }
6780
6781    #[test]
6782    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6783        let mut t = task();
6784        t.answers.push(crate::queue::AnsweredQuestion {
6785            question: "Inspect the remote?".into(),
6786            answer: "Inspect then wait".into(),
6787        });
6788        let old = instruction_for(&t);
6789        assert!(compatible_instruction(&old, &t));
6790        t.instruction = "Reuse approved PR head and review".into();
6791        t.release_operator("cli", None);
6792        assert!(!compatible_instruction(&old, &t));
6793        let approved = instruction_for(&t);
6794        assert!(approved.contains("waiting premises are superseded"));
6795        assert!(compatible_instruction(&approved, &t));
6796        assert_eq!(resumed_instruction(&approved, &t), approved);
6797        t.release_operator("web", None);
6798        assert!(compatible_instruction(&approved, &t));
6799        assert_eq!(t.resumption_history.len(), 1);
6800        t.start("run".into());
6801        assert!(instruction_for(&t).contains("Explicit operator resumption"));
6802    }
6803
6804    /// A run that stopped on an infrastructure wait asked no agent anything:
6805    /// the task is held by the machine under a `[resource]` reason (resumable,
6806    /// re-checked by triage), and the attempt it started is given back.
6807    #[test]
6808    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6809        let mut state = RunState::new(
6810            PathBuf::from("/repo"),
6811            "main".into(),
6812            "base".into(),
6813            "task".into(),
6814            Config::default(),
6815        );
6816        state.status = RunStatus::Landing;
6817        state.parked = true;
6818        state.pr_pushed_head = Some("head".into());
6819        state.land_unrelated = Some(
6820            serde_json::from_value(serde_json::json!({
6821                "head": "head", "question": "ci-question",
6822                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6823            }))
6824            .unwrap(),
6825        );
6826        let mut t = task();
6827        t.start(state.id.clone());
6828        let verdict = Verdict {
6829            status: RunStatus::Landing,
6830            left_pr: true,
6831            quota_hit: false,
6832            parked: true,
6833            no_viable_candidates: false,
6834        };
6835        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6836        assert_eq!(t.attempts, 0);
6837        assert_eq!(t.status, TaskStatus::Held);
6838        assert!(!t.operator_held());
6839        assert!(
6840            t.hold_reason
6841                .as_deref()
6842                .unwrap()
6843                .starts_with("[ci-unrelated]")
6844        );
6845        // A second settlement must not refund an earlier task attempt.
6846        t.attempts = 1;
6847        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6848        assert_eq!(t.attempts, 1);
6849        assert_eq!(t.passes.len(), 1);
6850        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6851        state.pr_pushed_head = Some("new-head".into());
6852        state.parked = false;
6853        state.status = RunStatus::Blocked;
6854        let stale = Verdict {
6855            status: RunStatus::Blocked,
6856            parked: false,
6857            ..verdict
6858        };
6859        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6860        assert_eq!(t.attempts, 1);
6861        // A new execution pass can refund its own newly charged attempt.
6862        state.begin_pass();
6863        state.begin_pass();
6864        state.status = RunStatus::Landing;
6865        state.parked = true;
6866        state.pr_pushed_head = Some("head".into());
6867        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6868        assert_eq!(t.attempts, 0);
6869        assert_eq!(t.passes.len(), 2);
6870    }
6871
6872    #[test]
6873    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
6874        let mut state = RunState::new(
6875            PathBuf::from("/repo"),
6876            "main".to_owned(),
6877            "abc1234".to_owned(),
6878            "task".to_owned(),
6879            Config::default(),
6880        );
6881        state.status = RunStatus::Blocked;
6882        state.resource_block = Some(crate::run::ResourceBlock {
6883            cause: crate::run::ResourceBlockCause::Other,
6884            node: "graft".to_owned(),
6885            kind: "shared build cache".to_owned(),
6886            detail: "timed out".to_owned(),
6887            at: jiff::Timestamp::now(),
6888        });
6889        let mut t = task();
6890        t.start("20260902-000000-aaaa".to_owned());
6891        assert_eq!(t.attempts, 1);
6892        let verdict = Verdict {
6893            status: RunStatus::Blocked,
6894            left_pr: false,
6895            quota_hit: false,
6896            parked: false,
6897            no_viable_candidates: false,
6898        };
6899        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
6900        assert_eq!(t.status, TaskStatus::Held);
6901        assert_eq!(t.attempts, 0, "the attempt is refunded");
6902        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
6903        assert!(
6904            !t.operator_held(),
6905            "a machine hold, released without a human"
6906        );
6907
6908        let mut selected = task();
6909        selected.start("20260902-000000-cccc".into());
6910        selected.replacement = Some(crate::merge_decision::Replacement {
6911            question: "fixture".into(),
6912            run: "earlier".into(),
6913            pr: "https://example.invalid/pr/1".into(),
6914            agent: "selected".into(),
6915            context: "fixture".into(),
6916        });
6917        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
6918        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
6919        assert_eq!(selected.attempts, 0);
6920        assert!(
6921            !selected.operator_held(),
6922            "a selected agent also retains a machine resource hold"
6923        );
6924        assert!(
6925            selected
6926                .hold_reason
6927                .as_deref()
6928                .unwrap()
6929                .starts_with("[resource] ")
6930        );
6931
6932        // A park request outranks it: still the operator's doing.
6933        let mut p = task();
6934        p.start("20260902-000000-bbbb".to_owned());
6935        settle_and_diagnose(
6936            &mut p,
6937            Verdict {
6938                parked: true,
6939                ..verdict
6940            },
6941            "parked",
6942            2,
6943            &state,
6944        );
6945        assert_eq!(p.status, TaskStatus::Parked);
6946        assert_eq!(
6947            p.attempts, 0,
6948            "parking refunds once rather than also settling the resource hold"
6949        );
6950    }
6951
6952    #[test]
6953    fn record_failure_notice_links_the_task() {
6954        let dir = tempfile::tempdir().unwrap();
6955        // A regular file where the queue directory should be makes every
6956        // `put` fail, on every platform and whoever runs the test.
6957        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
6958        let queue = Queue::at(dir.path().join("queue"));
6959        let mut t = interrupt_task("rec-fail-1");
6960        record(&queue, &mut t);
6961
6962        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
6963        assert_eq!(found.len(), 1);
6964        assert_eq!(found[0].key, "loop:record");
6965        assert_eq!(
6966            found[0].link,
6967            Some(Link::Task {
6968                id: "rec-fail-1".to_owned()
6969            })
6970        );
6971    }
6972
6973    /// A runnable task marked to interrupt, with an id fixed for assertions
6974    /// rather than the random one [`Task::new`] mints.
6975    fn interrupt_task(id: &str) -> Task {
6976        let mut t = task();
6977        t.id = id.to_owned();
6978        t.interrupt = true;
6979        t
6980    }
6981
6982    /// An ordinary runnable task with an id fixed for assertions.
6983    fn task_with_id(id: &str) -> Task {
6984        let mut t = task();
6985        t.id = id.to_owned();
6986        t
6987    }
6988
6989    /// A runnable task marked `--urgent`, with an id fixed for assertions.
6990    fn urgent_task(id: &str) -> Task {
6991        let mut t = task();
6992        t.id = id.to_owned();
6993        t.urgent = true;
6994        t
6995    }
6996
6997    #[test]
6998    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
6999        let dir = tempfile::tempdir().unwrap();
7000        let queue = Queue::at(dir.path().join("queue"));
7001        let mut parked = task_with_id("parked");
7002        parked.start("run".into());
7003        parked.park("upgrade");
7004        parked.record_pass_at(
7005            "run",
7006            0,
7007            Some(Timestamp::now()),
7008            1,
7009            Some(crate::run::ParkCause::Upgrade {
7010                from: "old".into(),
7011                to: None,
7012            }),
7013        );
7014        let mut fresh = task_with_id("fresh");
7015        fresh.priority = 100;
7016        let mut urgent_task = urgent_task("urgent");
7017        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7018            queue.put(t).unwrap();
7019        }
7020        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7021        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7022        let candidates = runnable(&queue);
7023        assert_eq!(candidates[0].id, parked.id);
7024        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7025        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7026        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7027        drop(first);
7028        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7029        let next = runnable(&queue)
7030            .into_iter()
7031            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7032            .unwrap();
7033        assert_eq!(next.task.id, fresh.id);
7034        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7035        drop(claimed_elsewhere);
7036        drop(next);
7037        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7038    }
7039
7040    #[test]
7041    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7042        let dir = tempfile::tempdir().unwrap();
7043        let queue = Queue::at(dir.path().join("queue"));
7044        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7045        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7046        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7047        let mut first = task();
7048        queue.put(&mut first).unwrap();
7049        let stale_plain = queue.get(&first.id).unwrap();
7050        first.set_urgent(true).unwrap();
7051        queue.put(&mut first).unwrap();
7052        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7053        let mut second = urgent_task("second");
7054        queue.put(&mut second).unwrap();
7055        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7056        drop(queue.claim(&second.id).unwrap());
7057        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7058        drop(dispatched);
7059        let stale_urgent = queue.get(&first.id).unwrap();
7060        first.set_urgent(false).unwrap();
7061        queue.put(&mut first).unwrap();
7062        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7063        assert_eq!(urgent.available_permits(), 1);
7064        drop(queue.claim(&first.id).unwrap());
7065        drop(occupied);
7066    }
7067
7068    #[test]
7069    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7070        let dir = tempfile::tempdir().unwrap();
7071        let queue = Queue::at(dir.path().join("queue"));
7072        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7073        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7074        let mut t = task();
7075        queue.put(&mut t).unwrap();
7076        for enabled in [true, false] {
7077            let stale = queue.get(&t.id).unwrap();
7078            t.set_urgent(enabled).unwrap();
7079            queue.put(&mut t).unwrap();
7080            assert_ne!(stale.urgent, enabled);
7081            let DispatchClaim {
7082                task: fresh,
7083                claim,
7084                permit,
7085            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7086            assert_eq!(fresh.urgent, enabled);
7087            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7088            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7089            assert!(queue.claim(&t.id).is_err());
7090            assert_eq!(fresh.attempts, stale.attempts);
7091            drop((claim, permit));
7092            assert_eq!(ordinary.available_permits(), 1);
7093            assert_eq!(urgent.available_permits(), 1);
7094        }
7095        t.set_urgent(true).unwrap();
7096        queue.put(&mut t).unwrap();
7097        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7098        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7099        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7100        drop(queue.claim(&t.id).unwrap());
7101        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7102        drop(occupied);
7103        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7104        drop(queue.claim(&t.id).unwrap());
7105        let held = queue.claim(&t.id).unwrap();
7106        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7107        drop(held);
7108        t.status = TaskStatus::Held;
7109        queue.put(&mut t).unwrap();
7110        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7111        drop(queue.claim(&t.id).unwrap());
7112        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7113        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7114        drop(queue.claim(&t.id).unwrap());
7115        assert_eq!(urgent.available_permits(), 1);
7116    }
7117
7118    /// The land-resume exemption wins outright, whether or not the candidate
7119    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7120    /// queue behind anything" guarantee cannot be weaker just because the
7121    /// same task was also filed with `--urgent`.
7122    #[test]
7123    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7124        assert_eq!(permit_kind(true, false), PermitKind::None);
7125        assert_eq!(permit_kind(true, true), PermitKind::None);
7126    }
7127
7128    /// The one property this whole feature exists for: `--urgent` draws from
7129    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7130    /// ordinary candidate draws from the ordinary pool exactly as before,
7131    /// untouched by the urgent slot's existence.
7132    #[test]
7133    fn permit_kind_separates_urgent_from_ordinary() {
7134        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7135        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7136    }
7137
7138    /// The exact wiring `attempt` runs before minting anything: a config's
7139    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7140    /// Free space is injected rather than asked of the real disk - the point
7141    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7142    /// is deterministic on every machine this test runs on, never dependent
7143    /// on how full the CI runner's own disk happens to be.
7144    #[test]
7145    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7146        let cfg = Config::default();
7147        let repo = Path::new("/any/repo/path");
7148
7149        let reason =
7150            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7151        assert!(reason.contains("1024"), "{reason}");
7152        assert!(
7153            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7154            "{reason}"
7155        );
7156
7157        assert_eq!(
7158            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7159            None,
7160            "exactly at the floor is open"
7161        );
7162        assert_eq!(
7163            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7164            None,
7165            "comfortably above the floor is open"
7166        );
7167    }
7168
7169    #[test]
7170    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7171        let mut cfg = Config::default();
7172        cfg.disk.min_free_bytes = 0;
7173        let repo = Path::new("/any/repo/path");
7174        assert_eq!(
7175            disk_gate_with(repo, &cfg, |_| Ok(0)),
7176            None,
7177            "a zero floor never measures at all"
7178        );
7179    }
7180
7181    #[test]
7182    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7183        let cfg = Config::default();
7184        let repo = Path::new("/any/repo/path");
7185        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7186            .expect("a measurement failure must close the gate, not open it");
7187        assert!(reason.contains("could not measure"), "{reason}");
7188    }
7189
7190    #[test]
7191    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7192        let ordinary = task();
7193        let next = advance_interrupt(
7194            Interrupt::Idle,
7195            std::slice::from_ref(&ordinary.id),
7196            std::slice::from_ref(&ordinary),
7197        );
7198        assert_eq!(next, Interrupt::Idle);
7199    }
7200
7201    #[test]
7202    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7203        // Nothing to interrupt - this is just an ordinary candidate, and the
7204        // loop's normal dispatch will pick it up like any other.
7205        let marked = interrupt_task("marked");
7206        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7207        assert_eq!(next, Interrupt::Idle);
7208    }
7209
7210    #[test]
7211    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7212        let marked = interrupt_task("marked");
7213        let next = advance_interrupt(
7214            Interrupt::Idle,
7215            &["running".to_owned()],
7216            std::slice::from_ref(&marked),
7217        );
7218        assert_eq!(
7219            next,
7220            Interrupt::Parking {
7221                parked: vec!["running".to_owned()],
7222                interrupt_task: "marked".to_owned(),
7223            }
7224        );
7225    }
7226
7227    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7228    /// one run can be in flight when a task becomes runnable and marked.
7229    /// Parking all of them would mean `Resuming` later has more than one id
7230    /// to release back to ordinary dispatch, which cannot be made safe
7231    /// against that same setting's own extra concurrency slots letting two
7232    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7233    /// The simplification the task's own constraints ask for: do not begin
7234    /// a sequence at all until the herd settles back to exactly one.
7235    #[test]
7236    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7237        let marked = interrupt_task("marked");
7238
7239        let two = advance_interrupt(
7240            Interrupt::Idle,
7241            &["a".to_owned(), "b".to_owned()],
7242            std::slice::from_ref(&marked),
7243        );
7244        assert_eq!(two, Interrupt::Idle);
7245
7246        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7247        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7248    }
7249
7250    #[test]
7251    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7252        let state = Interrupt::Parking {
7253            parked: vec!["running".to_owned()],
7254            interrupt_task: "marked".to_owned(),
7255        };
7256        // Still in flight: no change.
7257        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7258        assert_eq!(still_going, state);
7259
7260        // Left flight, but the interrupt task has not been dispatched yet on
7261        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7262        // as long as it is still runnable.
7263        let stopped_but_not_yet_dispatched =
7264            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7265        assert_eq!(stopped_but_not_yet_dispatched, state);
7266
7267        // Left flight, and the interrupt task is now in flight itself.
7268        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7269        assert_eq!(
7270            dispatched,
7271            Interrupt::Running {
7272                parked: vec!["running".to_owned()],
7273                interrupt_task: "marked".to_owned(),
7274            }
7275        );
7276    }
7277
7278    #[test]
7279    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7280        let state = Interrupt::Running {
7281            parked: vec!["running".to_owned()],
7282            interrupt_task: "marked".to_owned(),
7283        };
7284        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7285        assert_eq!(still_running, state);
7286
7287        // Whatever it ended as - merged, failed, held - is not this
7288        // function's concern: leaving flight is the only trigger, driven
7289        // straight off the same in-flight list `poll` already reaps. It does
7290        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7291        // why that would let an unrelated task start ahead of, or alongside,
7292        // the guaranteed resume.
7293        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7294        assert_eq!(
7295            ended,
7296            Interrupt::Resuming {
7297                parked: vec!["running".to_owned()]
7298            }
7299        );
7300    }
7301
7302    #[test]
7303    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7304        let state = Interrupt::Resuming {
7305            parked: vec!["running".to_owned()],
7306        };
7307        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7308        assert_eq!(still_waiting, state);
7309
7310        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7311        assert_eq!(dispatched, Interrupt::Idle);
7312    }
7313
7314    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7315    /// or otherwise moved on by an operator with no claim standing in the
7316    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7317    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7318    /// come. The parked run still gets its resume.
7319    #[test]
7320    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7321    {
7322        let state = Interrupt::Parking {
7323            parked: vec!["running".to_owned()],
7324            interrupt_task: "marked".to_owned(),
7325        };
7326        // `marked` has been held/blocked/deleted since the sequence began:
7327        // it no longer appears in `runnable` at all.
7328        let next = advance_interrupt(state, &[], &[]);
7329        assert_eq!(
7330            next,
7331            Interrupt::Resuming {
7332                parked: vec!["running".to_owned()]
7333            },
7334            "abandoning the interrupt must not abandon the resume it owes"
7335        );
7336    }
7337
7338    /// The same abandonment, one step later: `Resuming` itself must not wait
7339    /// forever for a parked task that has since become unrunnable.
7340    #[test]
7341    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7342        let state = Interrupt::Resuming {
7343            parked: vec!["running".to_owned()],
7344        };
7345        let next = advance_interrupt(state, &[], &[]);
7346        assert_eq!(
7347            next,
7348            Interrupt::Idle,
7349            "nothing is left to wait for; the loop must not stay wedged"
7350        );
7351    }
7352
7353    #[test]
7354    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7355        let marked = interrupt_task("marked");
7356        let next = advance_interrupt_tick(
7357            false,
7358            Interrupt::Idle,
7359            &["running".to_owned()],
7360            std::slice::from_ref(&marked),
7361        );
7362        assert_eq!(
7363            next,
7364            Interrupt::Idle,
7365            "an unmarked, unconfigured daemon must behave exactly as before"
7366        );
7367    }
7368
7369    #[test]
7370    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7371        let state = Interrupt::Parking {
7372            parked: vec!["running".to_owned()],
7373            interrupt_task: "marked".to_owned(),
7374        };
7375        let candidates = vec![interrupt_task("marked"), task()];
7376        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7377        assert!(
7378            allowed.is_empty(),
7379            "nothing may dispatch - not even the interrupt task itself - \
7380             until the parked run has actually stopped"
7381        );
7382    }
7383
7384    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7385    /// grow a special case for it: an urgent candidate that is not the
7386    /// interrupt task withholds exactly like an ordinary one for as long as
7387    /// the parked run it is racing has not actually left flight. A version
7388    /// of this feature once bypassed the gate for urgent candidates, on the
7389    /// theory that a genuinely separate concurrency lane could not collide
7390    /// with 75dd's own; it could, and did - the bypassed task dispatched
7391    /// alongside a run 75dd's own state machine had only *asked* to park,
7392    /// not yet confirmed gone, which is exactly the second run
7393    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7394    /// tick during Parking/Running/Resuming where letting an extra
7395    /// candidate through is safe, urgent or not - the parked run may still
7396    /// be genuinely mid-call.
7397    #[test]
7398    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7399        for state in [
7400            Interrupt::Parking {
7401                parked: vec!["running".to_owned()],
7402                interrupt_task: "marked".to_owned(),
7403            },
7404            Interrupt::Running {
7405                parked: vec!["running".to_owned()],
7406                interrupt_task: "marked".to_owned(),
7407            },
7408            Interrupt::Resuming {
7409                parked: vec!["running".to_owned()],
7410            },
7411        ] {
7412            let candidates = vec![
7413                interrupt_task("marked"),
7414                urgent_task("hot"),
7415                task_with_id("ordinary"),
7416            ];
7417            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7418            assert!(
7419                !allowed.iter().any(|t| t.id == "hot"),
7420                "an urgent candidate must wait out the same gate as anything \
7421                 else while the run it would run alongside has not actually \
7422                 left flight, for state {state:?}: {allowed:?}"
7423            );
7424        }
7425    }
7426
7427    /// The one case where marking a task `--urgent` and `interrupt` at once
7428    /// is not redundant: once the interrupt sequence's own guaranteed
7429    /// resume/dispatch actually admits the task, it is unaffected by also
7430    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7431    /// never on the urgent flag.
7432    #[test]
7433    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7434        let state = Interrupt::Resuming {
7435            parked: vec!["hot".to_owned()],
7436        };
7437        let candidates = vec![urgent_task("hot"), task()];
7438        let allowed = interrupt_gate(&state, &[], candidates);
7439        assert_eq!(
7440            allowed.iter().filter(|t| t.id == "hot").count(),
7441            1,
7442            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7443        );
7444    }
7445
7446    #[test]
7447    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7448        let state = Interrupt::Parking {
7449            parked: vec!["running".to_owned()],
7450            interrupt_task: "marked".to_owned(),
7451        };
7452        let other = task();
7453        let candidates = vec![interrupt_task("marked"), other.clone()];
7454        let allowed = interrupt_gate(&state, &[], candidates);
7455        assert_eq!(allowed.len(), 1);
7456        assert_eq!(allowed[0].id, "marked");
7457    }
7458
7459    #[test]
7460    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7461        let state = Interrupt::Running {
7462            parked: vec!["running".to_owned()],
7463            interrupt_task: "marked".to_owned(),
7464        };
7465        let candidates = vec![task(), task()];
7466        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7467        assert!(allowed.is_empty());
7468    }
7469
7470    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7471    /// sequence began (only reachable above the default
7472    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7473    /// never both in the same tick, which is what "exactly one resume, no
7474    /// simultaneous run" actually requires structurally rather than by
7475    /// coincidence of how many ordinary slots happen to be free.
7476    #[test]
7477    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7478        let state = Interrupt::Resuming {
7479            parked: vec!["a".to_owned(), "c".to_owned()],
7480        };
7481        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7482        let allowed = interrupt_gate(&state, &[], candidates);
7483        assert_eq!(
7484            allowed.len(),
7485            1,
7486            "at most one candidate may be offered while resuming: {allowed:?}"
7487        );
7488        assert_eq!(allowed[0].id, "a");
7489    }
7490
7491    #[test]
7492    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7493        let state = Interrupt::Resuming {
7494            parked: vec!["a".to_owned()],
7495        };
7496        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7497        assert!(allowed.is_empty());
7498    }
7499
7500    /// The invariant the completion criteria ask for by name: across a whole
7501    /// simulated sequence, there is never a tick where the gate would let
7502    /// through both the parked run's resume and the interrupt task, and
7503    /// exactly one candidate resumes the instant the interrupt task's run
7504    /// ends - never zero, never more than one.
7505    #[test]
7506    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7507        let running = task(); // id: whatever `Task::new` minted
7508        let marked = interrupt_task("marked");
7509
7510        let mut state = Interrupt::Idle;
7511        // Tick 1: `running` is in flight, `marked` becomes runnable.
7512        let in_flight = vec![running.id.clone()];
7513        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7514        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7515        assert!(gated.is_empty(), "still waiting on `running` to park");
7516
7517        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7518        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7519        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7520        assert_eq!(
7521            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7522            vec!["marked"],
7523            "only the interrupt task may be offered to the dispatcher now"
7524        );
7525
7526        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7527        state = advance_interrupt_tick(
7528            true,
7529            state,
7530            &["marked".to_owned()],
7531            std::slice::from_ref(&running),
7532        );
7533        let gated = interrupt_gate(
7534            &state,
7535            &["marked".to_owned()],
7536            vec![marked.clone(), running.clone()],
7537        );
7538        assert!(
7539            gated.is_empty(),
7540            "the parked run must not be offered back while the interrupt \
7541             task is still running"
7542        );
7543
7544        // Tick 4: `marked`'s run reached a terminal status and left flight.
7545        // A higher-priority ordinary task `other` is also runnable now - it
7546        // must not be let through instead of, or alongside, `running`.
7547        let other = task_with_id("other");
7548        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7549        assert_eq!(
7550            state,
7551            Interrupt::Resuming {
7552                parked: vec![running.id.clone()]
7553            }
7554        );
7555        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7556        assert_eq!(
7557            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7558            vec![running.id.as_str()],
7559            "exactly the parked run resumes - not the unrelated task, even \
7560             though it was offered first"
7561        );
7562
7563        // Tick 5: `running` is now in flight (dispatched from tick 4's
7564        // gate). Only now does the sequence end and ordinary dispatch fully
7565        // resume.
7566        state = advance_interrupt_tick(
7567            true,
7568            state,
7569            std::slice::from_ref(&running.id),
7570            std::slice::from_ref(&other),
7571        );
7572        assert_eq!(state, Interrupt::Idle);
7573        let gated = interrupt_gate(
7574            &state,
7575            std::slice::from_ref(&running.id),
7576            vec![other.clone()],
7577        );
7578        assert_eq!(
7579            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7580            vec![other.id.as_str()],
7581            "ordinary dispatch is unrestricted again"
7582        );
7583    }
7584
7585    #[test]
7586    fn every_run_status_settles_the_task_it_came_from() {
7587        // run status, resulting task status, attempts still standing after one
7588        let table = [
7589            (RunStatus::Merged, TaskStatus::Done, 1),
7590            (RunStatus::Ready, TaskStatus::Done, 1),
7591            (RunStatus::Stalled, TaskStatus::Failed, 0),
7592            (RunStatus::Blocked, TaskStatus::Failed, 1),
7593            (RunStatus::Failed, TaskStatus::Failed, 1),
7594            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7595            (RunStatus::Prep, TaskStatus::Failed, 1),
7596            (RunStatus::Implementing, TaskStatus::Failed, 1),
7597            (RunStatus::Judging, TaskStatus::Failed, 1),
7598            (RunStatus::Deliberating, TaskStatus::Failed, 1),
7599            (RunStatus::Voting, TaskStatus::Failed, 1),
7600            (RunStatus::Reviewing, TaskStatus::Failed, 1),
7601            (RunStatus::Gating, TaskStatus::Failed, 1),
7602        ];
7603        for (run, want, attempts) in table {
7604            let mut t = task();
7605            t.start("20260902-000000-aaaa".to_owned());
7606            settle(
7607                &mut t,
7608                Verdict {
7609                    status: run,
7610                    left_pr: false,
7611                    parked: false,
7612                    quota_hit: matches!(run, RunStatus::Stalled),
7613                    no_viable_candidates: false,
7614                },
7615                "why",
7616                2,
7617            );
7618            assert_eq!(t.status, want, "task status after {}", label(run));
7619            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7620        }
7621    }
7622
7623    #[test]
7624    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7625        let mut stalled = task();
7626        stalled.start("20260902-000000-aaaa".to_owned());
7627        settle(
7628            &mut stalled,
7629            Verdict {
7630                status: RunStatus::Stalled,
7631                left_pr: false,
7632                parked: false,
7633                quota_hit: true,
7634                no_viable_candidates: false,
7635            },
7636            "quota",
7637            1,
7638        );
7639        assert_eq!(stalled.attempts, 0);
7640        assert!(
7641            stalled.status.runnable(),
7642            "a machine problem must leave the task in line"
7643        );
7644
7645        let mut blocked = task();
7646        blocked.start("20260902-000000-aaaa".to_owned());
7647        settle(
7648            &mut blocked,
7649            Verdict {
7650                status: RunStatus::Blocked,
7651                left_pr: false,
7652                parked: false,
7653                quota_hit: false,
7654                no_viable_candidates: false,
7655            },
7656            "findings open",
7657            1,
7658        );
7659        assert_eq!(blocked.attempts, 1);
7660        assert_eq!(
7661            blocked.status,
7662            TaskStatus::Held,
7663            "the last attempt hands the task to a human"
7664        );
7665    }
7666
7667    #[test]
7668    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7669        // Attempts to spare: without the pull request this task would go
7670        // straight back in line and run the whole competition again.
7671        let mut delivered = task();
7672        delivered.start("20260903-080619-01c2".to_owned());
7673        settle(
7674            &mut delivered,
7675            Verdict {
7676                status: RunStatus::Blocked,
7677                left_pr: true,
7678                parked: false,
7679                quota_hit: false,
7680                no_viable_candidates: false,
7681            },
7682            "no check status",
7683            4,
7684        );
7685        assert_eq!(
7686            delivered.status,
7687            TaskStatus::Held,
7688            "a pull request waiting on CI or a person is not a retryable failure"
7689        );
7690        assert!(
7691            !delivered.status.runnable(),
7692            "the loop must not pick this task up again"
7693        );
7694        assert_eq!(
7695            delivered.last_error.as_deref(),
7696            Some("no check status"),
7697            "the operator needs to be told what the gate was waiting for"
7698        );
7699
7700        // The same status without a pull request is a plain failure, and with
7701        // attempts left it is retried.
7702        let mut empty_handed = task();
7703        empty_handed.start("20260903-080619-01c2".to_owned());
7704        settle(
7705            &mut empty_handed,
7706            Verdict {
7707                status: RunStatus::Blocked,
7708                left_pr: false,
7709                parked: false,
7710                quota_hit: false,
7711                no_viable_candidates: false,
7712            },
7713            "findings open",
7714            4,
7715        );
7716        assert_eq!(empty_handed.status, TaskStatus::Failed);
7717        assert!(empty_handed.status.runnable());
7718    }
7719
7720    #[test]
7721    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7722        // Every candidate agreed, with evidence, that nothing belonged in the
7723        // worktree. That is not a confirmed success to close automatically -
7724        // a human still has to check the claim - and it is not an ordinary
7725        // failure either, so this settles exactly like a pull request nobody
7726        // merged yet: `Held`, same as `Blocked` with a PR.
7727        let mut noop = task();
7728        noop.start("20260912-131304-391f".to_owned());
7729        settle(
7730            &mut noop,
7731            Verdict {
7732                status: RunStatus::VerifiedNoop,
7733                left_pr: false,
7734                parked: false,
7735                quota_hit: false,
7736                no_viable_candidates: true,
7737            },
7738            "candidate A: already fixed by b32cfc4, on main",
7739            4,
7740        );
7741        assert_eq!(
7742            noop.status,
7743            TaskStatus::Held,
7744            "an unverified claim is a request for a human, not a failure"
7745        );
7746        assert!(
7747            !noop.status.runnable(),
7748            "the loop must not requeue this on the same unverified claim"
7749        );
7750        // `Task::release` resets attempts to zero the moment a human looks at
7751        // the evidence and lets it run again, so it does not matter here
7752        // whether the one attempt already spent stays spent - what matters is
7753        // that nothing retries this task unattended in the meantime.
7754        assert_eq!(noop.attempts, 1);
7755    }
7756
7757    #[test]
7758    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7759        // Parking is the operator asking for the process back - to replace the
7760        // binary, most of all. The run's work is intact on disk, so this is
7761        // not a failed attempt, and charging for it would mean a few upgrades
7762        // could exhaust a budget meant for agents that misbehaved.
7763        let mut parked = task();
7764        parked.start("20260903-183634-2d98".to_owned());
7765        settle(
7766            &mut parked,
7767            Verdict {
7768                status: RunStatus::Implementing,
7769                left_pr: false,
7770                quota_hit: false,
7771                parked: true,
7772                no_viable_candidates: false,
7773            },
7774            "parked after `implementing`",
7775            2,
7776        );
7777        assert_eq!(parked.attempts, 0, "a park is refunded");
7778        assert!(
7779            parked.status.runnable(),
7780            "and the task stays in line so the next loop resumes its run"
7781        );
7782        assert_eq!(parked.status, TaskStatus::Parked);
7783        assert_eq!(
7784            parked.park_reason.as_deref(),
7785            Some("parked after `implementing`"),
7786            "the card says where it stopped"
7787        );
7788        assert_eq!(parked.last_error, None, "nothing failed");
7789
7790        // Without the park flag the same non-terminal status is what it always
7791        // was: `execute` returning mid-flight, which is a bug and spends an
7792        // attempt so a task cannot loop on it forever.
7793        let mut broken = task();
7794        broken.start("20260903-183634-2d98".to_owned());
7795        settle(
7796            &mut broken,
7797            Verdict {
7798                status: RunStatus::Implementing,
7799                left_pr: false,
7800                quota_hit: false,
7801                parked: false,
7802                no_viable_candidates: false,
7803            },
7804            "returned mid-flight",
7805            2,
7806        );
7807        assert_eq!(broken.attempts, 1);
7808    }
7809
7810    #[test]
7811    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7812        // Run e633: quorum lost because two judges answered with the wrong
7813        // JSON shape, `quota: []`. Refunding that takes the bound off the
7814        // retry loop, and each retry pays for a fresh hour-long implement
7815        // wave before it can fail the same way.
7816        let mut flaky = task();
7817        flaky.start("20260903-123023-e633".to_owned());
7818        settle(
7819            &mut flaky,
7820            Verdict {
7821                status: RunStatus::Stalled,
7822                left_pr: false,
7823                parked: false,
7824                quota_hit: false,
7825                no_viable_candidates: false,
7826            },
7827            "verdict rests on 1 of 3 judges",
7828            2,
7829        );
7830        assert_eq!(
7831            flaky.attempts, 1,
7832            "flakiness spends an attempt, so `max_attempts` still bounds it"
7833        );
7834        assert!(flaky.status.runnable(), "and it is still worth retrying");
7835
7836        // The same status, lost to a rate limit, is the machine's fault.
7837        let mut limited = task();
7838        limited.start("20260903-123023-e633".to_owned());
7839        settle(
7840            &mut limited,
7841            Verdict {
7842                status: RunStatus::Stalled,
7843                left_pr: false,
7844                parked: false,
7845                quota_hit: true,
7846                no_viable_candidates: false,
7847            },
7848            "judge-2, judge-3 out of quota",
7849            2,
7850        );
7851        assert_eq!(limited.attempts, 0, "a quota window is refunded");
7852        assert!(limited.status.runnable());
7853
7854        // And the bound really binds: a task that keeps stalling on flakiness
7855        // reaches a human instead of running the roster forever.
7856        let mut worn = task();
7857        for _ in 0..2 {
7858            worn.release();
7859        }
7860        worn.start("20260903-123023-e633".to_owned());
7861        worn.attempts = 2;
7862        settle(
7863            &mut worn,
7864            Verdict {
7865                status: RunStatus::Stalled,
7866                left_pr: false,
7867                parked: false,
7868                quota_hit: false,
7869                no_viable_candidates: false,
7870            },
7871            "no quorum again",
7872            2,
7873        );
7874        assert_eq!(worn.status, TaskStatus::Held);
7875        assert!(!worn.status.runnable());
7876    }
7877
7878    #[test]
7879    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
7880        // The implement wave loses every seat to the same rate limit and
7881        // `after_implement` bails with nothing viable, which surfaces as
7882        // `Failed` rather than `Stalled`. That is the same machine fact the
7883        // `Stalled`-quota row already refunds, and must be refunded the same
7884        // way, or a quota outage quietly holds every task it touches instead
7885        // of leaving them in line for the reset.
7886        let mut wiped_out = task();
7887        wiped_out.start("20260907-025000-a1b2".to_owned());
7888        settle(
7889            &mut wiped_out,
7890            Verdict {
7891                status: RunStatus::Failed,
7892                left_pr: false,
7893                parked: false,
7894                quota_hit: true,
7895                no_viable_candidates: true,
7896            },
7897            "no candidate produced a change; nothing to judge",
7898            2,
7899        );
7900        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
7901        assert!(
7902            wiped_out.status.runnable(),
7903            "a machine problem must leave the task in line"
7904        );
7905
7906        // This is the exemption that must stay narrow: a candidate that did
7907        // produce a change, and then failed for some other reason, still
7908        // spends the attempt even though a seat elsewhere hit its quota.
7909        // Otherwise every ordinary failure that happens to share a run with
7910        // an unrelated rate limit would be refunded for free.
7911        let mut partial_progress = task();
7912        partial_progress.start("20260907-025500-c3d4".to_owned());
7913        settle(
7914            &mut partial_progress,
7915            Verdict {
7916                status: RunStatus::Failed,
7917                left_pr: false,
7918                parked: false,
7919                quota_hit: true,
7920                no_viable_candidates: false,
7921            },
7922            "gate failed on the winning candidate",
7923            2,
7924        );
7925        assert_eq!(
7926            partial_progress.attempts, 1,
7927            "a candidate that actually produced a change spends the attempt \
7928             even though some other seat hit its quota"
7929        );
7930        assert!(partial_progress.status.runnable());
7931    }
7932
7933    #[test]
7934    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
7935        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
7936        // disk, and that construction must reach the same conclusion as the
7937        // one `attempt` builds from a live run, or a crash at exactly the
7938        // wrong moment gives a recovered task a different policy than one a
7939        // daemon finished settling itself.
7940        let mut t = task();
7941        t.start("20260907-025000-a1b2".to_owned());
7942        let mut state = run_state(RunStatus::Failed);
7943        state.quota.push(QuotaLoss {
7944            seat: "cand-a".to_owned(),
7945            node: "implement".to_owned(),
7946            at: Timestamp::now(),
7947            reset: None,
7948        });
7949        assert!(
7950            state.viable().is_empty(),
7951            "no candidate was added, so nothing is viable"
7952        );
7953        reclaim(&mut t, Some(state), 2, "en");
7954        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
7955        assert!(t.status.runnable());
7956    }
7957
7958    #[test]
7959    fn a_held_task_is_never_offered_to_the_loop() {
7960        let dir = tempfile::tempdir().unwrap();
7961        let queue = Queue::at(dir.path().to_path_buf());
7962        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
7963            let mut t = task();
7964            t.id = format!("2026090{n}-000000-000{n}");
7965            t.priority = priority;
7966            queue.put(&mut t).unwrap();
7967        }
7968        let mut held = task();
7969        held.id = "20260909-000000-9999".to_owned();
7970        held.priority = 99;
7971        held.hold_machine(None);
7972        queue.put(&mut held).unwrap();
7973
7974        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
7975        assert_eq!(order.len(), 3);
7976        assert!(!order.contains(&held.id));
7977        assert_eq!(
7978            order.first().cloned(),
7979            queue.next_runnable().map(|t| t.id),
7980            "the loop's first candidate is exactly what the queue offers"
7981        );
7982        assert_eq!(
7983            order,
7984            vec![
7985                "20260902-000000-0002".to_owned(),
7986                "20260903-000000-0003".to_owned(),
7987                "20260901-000000-0001".to_owned(),
7988            ],
7989            "priority first, then oldest, so nothing starves"
7990        );
7991    }
7992
7993    #[test]
7994    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
7995        let dir = tempfile::tempdir().unwrap();
7996        let queue = Queue::at(dir.path().to_path_buf());
7997        let mut old = task();
7998        old.id = "20260101-000000-old0".to_owned();
7999        queue.put(&mut old).unwrap();
8000        let mut fresh = task();
8001        fresh.id = "20260101-000000-new0".to_owned();
8002        queue.put(&mut fresh).unwrap();
8003
8004        // No parseable pid at all, so age is the only signal there is to
8005        // check - unlike a real `Queue::claim`, which always names a real,
8006        // and therefore alive, pid this test cannot fake as dead.
8007        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8008        std::thread::sleep(Duration::from_millis(60));
8009        let live = queue.claim(&fresh.id).unwrap();
8010
8011        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8012        assert_eq!(swept, vec![old.id.clone()]);
8013        assert!(
8014            queue.claim(&old.id).is_ok(),
8015            "an unparseable lock older than the threshold is swept"
8016        );
8017        assert!(
8018            queue.claim(&fresh.id).is_err(),
8019            "a live pid protects its lock regardless of age"
8020        );
8021        drop(live);
8022    }
8023
8024    #[test]
8025    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8026        // A live worker's claim remains authoritative even beyond the sweep's
8027        // age limit. Sweeping it would permit a second competing attempt.
8028        let dir = tempfile::tempdir().unwrap();
8029        let queue = Queue::at(dir.path().to_path_buf());
8030        let mut t = task();
8031        t.id = "20260101-000000-live".to_owned();
8032        queue.put(&mut t).unwrap();
8033
8034        let claim = queue.claim(&t.id).unwrap();
8035        std::thread::sleep(Duration::from_millis(60));
8036
8037        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8038        assert!(
8039            swept.is_empty(),
8040            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8041        );
8042        assert!(
8043            queue.claim(&t.id).is_err(),
8044            "the lock still protects its task"
8045        );
8046        drop(claim);
8047    }
8048
8049    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8050    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8051    fn injected_dead_pid() -> u32 {
8052        std::process::id().checked_add(1).unwrap_or(1)
8053    }
8054
8055    #[test]
8056    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8057        let dir = tempfile::tempdir().unwrap();
8058        let queue = Queue::at(dir.path().to_path_buf());
8059        let mut t = task();
8060        t.id = "20260101-000000-dead".to_owned();
8061        queue.put(&mut t).unwrap();
8062        let dead_pid = injected_dead_pid();
8063
8064        // Written directly rather than through `Queue::claim`, which would
8065        // stamp this test process's own very much alive pid and defeat the
8066        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8067        // like moments after it died, not six hours later.
8068        std::fs::write(
8069            dir.path().join(format!("{}.lock", t.id)),
8070            dead_pid.to_string(),
8071        )
8072        .unwrap();
8073
8074        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8075            pid != dead_pid
8076        });
8077        assert_eq!(
8078            swept,
8079            vec![t.id.clone()],
8080            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8081        );
8082        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8083    }
8084
8085    #[test]
8086    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8087        let dir = tempfile::tempdir().unwrap();
8088        let queue = Queue::at(dir.path().to_path_buf());
8089        let mut t = task();
8090        t.id = "20260101-000000-late".to_owned();
8091        queue.put(&mut t).unwrap();
8092        let dead_pid = injected_dead_pid();
8093
8094        // Tick one, standing in for the sweep `poll` already runs at
8095        // startup: nothing to find yet.
8096        assert!(
8097            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8098            "nothing has claimed the task yet"
8099        );
8100
8101        // A second daemon claims the task and dies before it ever writes
8102        // `running`, well after this loop's own startup sweep already ran.
8103        std::fs::write(
8104            dir.path().join(format!("{}.lock", t.id)),
8105            dead_pid.to_string(),
8106        )
8107        .unwrap();
8108
8109        // Tick two, standing in for a poll long into this daemon's uptime:
8110        // the same function, called again, notices what only just appeared -
8111        // proving the sweep is not a one-shot startup check.
8112        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8113            pid != dead_pid
8114        });
8115        assert_eq!(swept, vec![t.id.clone()]);
8116    }
8117
8118    #[test]
8119    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8120        // `reclaim_orphaned_running` looks up the task's last run, which
8121        // touches `run::home()`; the first call anywhere in this binary wins,
8122        // so this is a no-op if another test already pinned one, and either
8123        // way the run id below is never written under it.
8124        crate::run::pin_test_home();
8125        let dir = tempfile::tempdir().unwrap();
8126        let queue = Queue::at(dir.path().to_path_buf());
8127        let mut t = task();
8128        t.id = "20260101-000000-crsh".to_owned();
8129        t.status = TaskStatus::Running;
8130        t.attempts = 1;
8131        // No `run.json` behind this id: standing in for a run this test does
8132        // not need to make readable, since the point is the lock, not the
8133        // recovery table `reclaim` already has its own tests for.
8134        t.runs.push("20260904-000000-4043".to_owned());
8135        queue.put(&mut t).unwrap();
8136        let dead_pid = injected_dead_pid();
8137
8138        // The crashed daemon's own claim, naming a pid nothing on the
8139        // machine holds anymore.
8140        std::fs::write(
8141            dir.path().join(format!("{}.lock", t.id)),
8142            dead_pid.to_string(),
8143        )
8144        .unwrap();
8145
8146        // Before the lock is swept the task looks claimed, and
8147        // `reclaim_orphaned_running` must leave it alone - this is exactly
8148        // the bug: a `running` task stranded behind a dead daemon's lock,
8149        // invisible to the claim-as-proof check because the lock outlived
8150        // the process that wrote it.
8151        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8152        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8153
8154        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8155            pid != dead_pid
8156        });
8157        assert_eq!(swept, vec![t.id.clone()]);
8158
8159        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8160        assert_eq!(reclaimed, vec![t.id.clone()]);
8161        let after = queue.get(&t.id).unwrap();
8162        assert_eq!(
8163            after.status,
8164            TaskStatus::Held,
8165            "no run.json to recover from, so a human is asked"
8166        );
8167        assert_eq!(
8168            after.runs,
8169            vec!["20260904-000000-4043".to_owned()],
8170            "the crashed run's id is kept as evidence, not discarded"
8171        );
8172    }
8173
8174    #[test]
8175    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8176        let dir = tempfile::tempdir().unwrap();
8177        let queue = Queue::at(dir.path().to_path_buf());
8178        let mut t = task();
8179        t.id = "20260101-000000-unknown".to_owned();
8180        queue.put(&mut t).unwrap();
8181        let dead_pid = injected_dead_pid();
8182        std::fs::write(
8183            dir.path().join(format!("{}.lock", t.id)),
8184            dead_pid.to_string(),
8185        )
8186        .unwrap();
8187
8188        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8189        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8190        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8191    }
8192
8193    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8194        let mut s = run_state(status);
8195        s.config.graph.language = language.to_owned();
8196        s
8197    }
8198
8199    fn unstarted_verdict(status: RunStatus) -> Verdict {
8200        Verdict {
8201            status,
8202            left_pr: false,
8203            quota_hit: false,
8204            parked: false,
8205            no_viable_candidates: false,
8206        }
8207    }
8208
8209    #[test]
8210    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8211        let mut t = task();
8212        t.attempts = 1;
8213        settle_in(
8214            &mut t,
8215            unstarted_verdict(RunStatus::AlreadyInBase),
8216            "already in main",
8217            1,
8218            phrases("en"),
8219        );
8220        assert_eq!(t.status, TaskStatus::Done);
8221        assert_eq!(t.attempts, 0);
8222    }
8223
8224    #[test]
8225    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8226        let reason = |language: &str| {
8227            let mut t = task();
8228            settle_in(
8229                &mut t,
8230                unstarted_verdict(RunStatus::Judging),
8231                "boom",
8232                1,
8233                phrases(language),
8234            );
8235            t.last_error.or(t.hold_reason).unwrap_or_default()
8236        };
8237        assert!(
8238            reason("en").starts_with("the graph stopped at `"),
8239            "{}",
8240            reason("en")
8241        );
8242        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8243        assert!(reason("日本語").contains("boom"));
8244        assert_eq!(reason("fr"), reason("en"));
8245    }
8246
8247    #[test]
8248    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8249        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8250        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8251        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8252        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8253        assert!(ja.contains("[run "), "{ja}");
8254        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8255        assert!(ended.starts_with("run 終了: "), "{ended}");
8256        let mut de = run_state_in(RunStatus::Failed, "de");
8257        let mut en = run_state_in(RunStatus::Failed, "en");
8258        de.id = "same".to_owned();
8259        en.id = "same".to_owned();
8260        assert_eq!(describe(&de), describe(&en));
8261    }
8262
8263    #[test]
8264    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8265        use crate::handover::Refused;
8266        let cases = [
8267            Refused::Foreign {
8268                branch: "b".into(),
8269                path: "/w/x".into(),
8270                why: "made by hand".into(),
8271            },
8272            Refused::Unsafe {
8273                branch: "b".into(),
8274                path: "/w/x".into(),
8275                why: "its worktree has uncommitted changes (a.rs)".into(),
8276            },
8277            Refused::ReleaseFailed {
8278                branch: "b".into(),
8279                path: "/w/x".into(),
8280                run: "ab12".into(),
8281            },
8282        ];
8283        for r in &cases {
8284            let en = (phrases("en").handover_refused)(r);
8285            assert_eq!(en, r.to_string());
8286            let ja = (phrases("ja").handover_refused)(r);
8287            assert!(
8288                !ja.contains("is checked out") && !ja.contains("try again"),
8289                "{ja}"
8290            );
8291            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8292            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8293                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8294            }
8295        }
8296        assert!(phrases("en").handover_hint.contains("release the task"));
8297        assert!(phrases("ja").handover_hint.contains("解放"));
8298    }
8299
8300    #[test]
8301    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8302        let build = |lang: &str| {
8303            let mut s = run_state_in(RunStatus::Blocked, lang);
8304            s.id = "same".to_owned();
8305            s.config.graph.review_rounds = 3;
8306            let mut r = review_round(3);
8307            r.expected = 3;
8308            r.answered = 1;
8309            s.reviews.push(r);
8310            s.event(
8311                "review",
8312                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8313            );
8314            s
8315        };
8316        let en = describe(&build("en"));
8317        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8318        let ja = describe(&build("ja"));
8319        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8320        assert!(!ja.contains("never answered"), "{ja}");
8321        assert!(ja.contains("[run "), "{ja}");
8322
8323        // An incomplete panel whose verification failed is a different stop:
8324        // the real event must survive in ja too.
8325        let mut failed = build("ja");
8326        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8327            command: "cargo test".to_owned(),
8328            code: Some(1),
8329            output_tail: String::new(),
8330            duration_ms: 0,
8331            resource_blocked: false,
8332        });
8333        failed.event("review", "stopped; e2e failed: cargo test");
8334        let ja = describe(&failed);
8335        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8336        assert!(!ja.contains("席のレビュアー"), "{ja}");
8337    }
8338
8339    #[test]
8340    fn refusals_and_recovery_prose_follow_the_language() {
8341        let t = held_task_with("r1");
8342        let q = action_question(
8343            "r1",
8344            ask::ChoiceAction::Resume {
8345                run: "r1".to_owned(),
8346            },
8347        );
8348        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
8349            ActionDecision::Refuse(s) => s,
8350            other => panic!("{other:?}"),
8351        };
8352        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8353        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8354        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8355
8356        let mut held = task();
8357        reclaim(&mut held, None, 2, "ja");
8358        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8359        let mut held = task();
8360        reclaim(&mut held, None, 2, "xx");
8361        assert!(held.hold_reason.unwrap().contains("held for a human"));
8362    }
8363
8364    fn run_state(status: RunStatus) -> RunState {
8365        let mut state = RunState::new(
8366            PathBuf::from("/repo"),
8367            "main".to_owned(),
8368            "abc1234def".to_owned(),
8369            "add retries".to_owned(),
8370            Config::default(),
8371        );
8372        state.status = status;
8373        state
8374    }
8375
8376    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8377        Candidate {
8378            index: 0,
8379            label,
8380            agent: "claude".to_owned(),
8381            branch: format!("magi/x/{label}"),
8382            worktree: PathBuf::from("/repo"),
8383            summary: summary.to_owned(),
8384            stat: String::new(),
8385            files: 0,
8386            commits: usize::from(!empty),
8387            empty,
8388            failed: failed.map(str::to_owned),
8389            verified_noop: None,
8390            duration_ms: 0,
8391            folded: false,
8392        }
8393    }
8394
8395    #[test]
8396    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8397        let mut state = run_state(RunStatus::Blocked);
8398        state.gate = vec![
8399            CommandOutcome {
8400                command: "cargo make check".to_owned(),
8401                code: Some(0),
8402                output_tail: "ok".to_owned(),
8403                duration_ms: 0,
8404                resource_blocked: false,
8405            },
8406            CommandOutcome {
8407                command: "cargo test".to_owned(),
8408                code: Some(101),
8409                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8410                duration_ms: 0,
8411                resource_blocked: false,
8412            },
8413        ];
8414        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8415        assert!(d.contains("cargo test"), "{d}");
8416        assert!(
8417            !d.contains("cargo make check"),
8418            "a passing check is not a diagnostic: {d}"
8419        );
8420        assert!(d.contains("assertion failed"), "{d}");
8421    }
8422
8423    #[test]
8424    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8425        let mut state = run_state(RunStatus::Blocked);
8426        state.event(
8427            "land",
8428            "stopped: the fixer produced no commit while 2 check(s) were failing \
8429             (build, lint); stopping instead of looping on an unchanged tree",
8430        );
8431        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8432        assert!(d.contains("build"), "{d}");
8433        assert!(d.contains("lint"), "{d}");
8434        assert!(d.contains("fixer produced no commit"), "{d}");
8435    }
8436
8437    #[test]
8438    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8439        // `describe`'s output becomes `Task::last_error` verbatim, and the
8440        // phone renders that in the same alarm-styled box an ordinary
8441        // failure gets. A bare `verified_noop` there would read exactly like
8442        // the failure this status exists to be told apart from.
8443        let state = run_state(RunStatus::VerifiedNoop);
8444        let d = describe(&state);
8445        assert!(
8446            d.contains("agent-verified no-op"),
8447            "expected the display label, not the wire spelling: {d}"
8448        );
8449        assert!(!d.contains("verified_noop"), "{d}");
8450    }
8451
8452    #[test]
8453    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8454        // The whole point of the feature: a run held as "no candidate produced
8455        // a change" can mean the implementer actually finished the task and
8456        // only left a clean local tree behind - see AGENTS.md on this exact
8457        // failure mode. The diagnostic has to carry what the agent actually
8458        // said, not just the fact that nothing was there to judge.
8459        let mut state = run_state(RunStatus::Failed);
8460        state.candidates = vec![candidate(
8461            'A',
8462            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8463            true,
8464            None,
8465        )];
8466        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8467        assert!(d.contains("candidate A"), "{d}");
8468        assert!(d.contains("tagged v1.2.3"), "{d}");
8469    }
8470
8471    #[test]
8472    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8473        let mut state = run_state(RunStatus::Failed);
8474        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8475        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8476        assert!(d.contains("candidate A"), "{d}");
8477        assert!(d.contains("agent timed out"), "{d}");
8478    }
8479
8480    #[test]
8481    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8482        // A viable candidate existed, the gate never ran, and nothing land
8483        // said matches - `Task::last_error` is left to explain this one alone.
8484        let mut state = run_state(RunStatus::Failed);
8485        state.candidates = vec![candidate('A', "did the work", false, None)];
8486        assert!(diagnostic(&state).is_none());
8487    }
8488
8489    #[test]
8490    fn diagnostic_is_bounded_however_much_a_run_printed() {
8491        let mut state = run_state(RunStatus::Blocked);
8492        state.gate = vec![
8493            CommandOutcome {
8494                command: "cargo test".to_owned(),
8495                code: Some(101),
8496                output_tail: "x".repeat(50_000),
8497                duration_ms: 0,
8498                resource_blocked: false,
8499            },
8500            CommandOutcome {
8501                command: "cargo clippy".to_owned(),
8502                code: Some(1),
8503                output_tail: "y".repeat(50_000),
8504                duration_ms: 0,
8505                resource_blocked: false,
8506            },
8507        ];
8508        state.candidates = vec![
8509            candidate('A', &"z".repeat(50_000), true, None),
8510            candidate('B', &"w".repeat(50_000), true, None),
8511        ];
8512        let d = diagnostic(&state).expect("plenty here to diagnose");
8513        assert!(
8514            d.len() <= DIAGNOSTIC_MAX,
8515            "diagnostic grew to {} bytes, unbounded",
8516            d.len()
8517        );
8518    }
8519
8520    #[test]
8521    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8522        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8523            let mut t = task();
8524            let mut state = run_state(status);
8525            t.pr_recovery = Some(crate::pr_recovery::Selection {
8526                url: "url".into(),
8527                branch: format!("magi/task-{}", t.id),
8528                head: "a".repeat(40),
8529                source_head: None,
8530                source_run: None,
8531                source_proof: None,
8532                disposition: Some(crate::pr_recovery::Disposition::Land),
8533                instruction: t.instruction.clone(),
8534                approved_at: Timestamp::now(),
8535            });
8536            state.pr_recovery = t.pr_recovery.clone();
8537            t.start(state.id.clone());
8538            settle_and_diagnose(
8539                &mut t,
8540                Verdict {
8541                    status,
8542                    left_pr: false,
8543                    quota_hit: false,
8544                    parked: false,
8545                    no_viable_candidates: false,
8546                },
8547                "delivery stopped",
8548                5,
8549                &state,
8550            );
8551            assert_eq!(t.status, TaskStatus::Held);
8552            let reason = t.hold_reason.as_deref().unwrap();
8553            if status == RunStatus::Ready {
8554                assert!(reason.contains("Selected PR delivery is incomplete"));
8555                assert!(t.recovery_budget.is_none());
8556            } else {
8557                assert!(reason.contains("Selected recovery stopped"));
8558                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8559            }
8560            assert!(t.pr_recovery.is_some());
8561        }
8562    }
8563
8564    #[test]
8565    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8566        let mut state = run_state(RunStatus::Voting);
8567        state.base_sync = Some(crate::run::BaseSync {
8568            tip: "base-tip".into(),
8569            behind: 3,
8570            attempts: 4,
8571            conflict: Some("base stopped".into()),
8572            already_in: None,
8573        });
8574        state.record_base_sync_stop("candidate-head");
8575        let mut t = task();
8576        t.start(state.id.clone());
8577        let verdict = Verdict {
8578            status: RunStatus::Blocked,
8579            left_pr: false,
8580            quota_hit: false,
8581            parked: false,
8582            no_viable_candidates: false,
8583        };
8584        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8585        assert_eq!(
8586            t.status,
8587            TaskStatus::Held,
8588            "unspent task attempts cannot start another competition"
8589        );
8590        let at = t.held_at;
8591        let cause = t.hold_notice_cause.clone();
8592        state.begin_pass();
8593        t.release_operator("test-resume", None);
8594        t.start(state.id.clone());
8595        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8596        assert_eq!(t.status, TaskStatus::Held);
8597        assert_eq!(t.held_at, at);
8598        assert_eq!(t.hold_notice_cause, cause);
8599    }
8600
8601    #[test]
8602    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8603        let mut state = run_state(RunStatus::Blocked);
8604        state.gate = vec![CommandOutcome {
8605            command: "cargo test".to_owned(),
8606            code: Some(101),
8607            output_tail: "assertion failed".to_owned(),
8608            duration_ms: 0,
8609            resource_blocked: false,
8610        }];
8611        let verdict = Verdict {
8612            status: RunStatus::Blocked,
8613            left_pr: false,
8614            quota_hit: false,
8615            parked: false,
8616            no_viable_candidates: false,
8617        };
8618
8619        // Attempt one of two still has a retry coming: no diagnostic yet, the
8620        // task is going to run again and this run's evidence would go stale.
8621        let mut t = task();
8622        t.start("run-1".to_owned());
8623        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8624        assert_eq!(t.status, TaskStatus::Failed);
8625        assert!(t.diagnostic.is_none());
8626
8627        // Attempt two exhausts the budget: now it is held, and the
8628        // diagnostic is what `magi task show` has to say more than one line.
8629        t.start("run-2".to_owned());
8630        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8631        assert_eq!(t.status, TaskStatus::Held);
8632        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8633        assert!(d.contains("cargo test"), "{d}");
8634    }
8635
8636    #[test]
8637    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8638        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8639        // `magi ask` question settled Held with `hold_reason: null`, so the
8640        // notification said nothing actionable. `note_open_question` should
8641        // append the question id to whatever `handed_off` already wrote.
8642        crate::run::pin_test_home();
8643        let home = crate::run::home();
8644        let state = run_state(RunStatus::VerifiedNoop);
8645        let mut q = ask::Question::new(
8646            state.id.clone(),
8647            "implement".to_owned(),
8648            "impl-A".to_owned(),
8649            "is this really a no-op?".to_owned(),
8650            String::new(),
8651            Vec::new(),
8652        );
8653        Questions::at(home.join("questions")).put(&mut q).unwrap();
8654
8655        let verdict = Verdict {
8656            status: RunStatus::VerifiedNoop,
8657            left_pr: false,
8658            quota_hit: false,
8659            parked: false,
8660            no_viable_candidates: false,
8661        };
8662        let mut t = task();
8663        t.start(state.id.clone());
8664        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8665
8666        assert_eq!(t.status, TaskStatus::Held);
8667        let reason = t.hold_reason.expect("a held task must record why");
8668        assert!(
8669            reason.starts_with("run ended agent-verified no-op"),
8670            "the original settle reason must survive unchanged: {reason}"
8671        );
8672        assert!(
8673            reason.contains(q.short()),
8674            "the open question's id must be named so the notice is actionable: {reason}"
8675        );
8676    }
8677
8678    #[test]
8679    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8680        crate::run::pin_test_home();
8681        let state = run_state(RunStatus::VerifiedNoop);
8682
8683        let verdict = Verdict {
8684            status: RunStatus::VerifiedNoop,
8685            left_pr: false,
8686            quota_hit: false,
8687            parked: false,
8688            no_viable_candidates: false,
8689        };
8690        let mut t = task();
8691        t.start(state.id.clone());
8692        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8693
8694        assert_eq!(t.status, TaskStatus::Held);
8695        assert_eq!(
8696            t.hold_reason.as_deref(),
8697            Some("run ended agent-verified no-op"),
8698            "nothing to append when the question was already answered or never asked"
8699        );
8700    }
8701
8702    #[test]
8703    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8704        crate::run::pin_test_home();
8705        let mut first = run_state(RunStatus::Blocked);
8706        first.id = "20260101-000000-sup1".to_owned();
8707        first.save().unwrap();
8708        let mut second = run_state(RunStatus::Merged);
8709        second.id = "20260101-000000-sup2".to_owned();
8710        second.save().unwrap();
8711
8712        let mut t = task();
8713        t.runs = vec![first.id.clone(), second.id.clone()];
8714        t.status = TaskStatus::Done;
8715
8716        supersede_prior_runs(&t, &crate::run::home());
8717
8718        assert_eq!(
8719            RunState::load(&first.id).unwrap().status,
8720            RunStatus::Superseded,
8721            "the first attempt's Blocked no longer needs anyone's attention"
8722        );
8723        assert_eq!(
8724            RunState::load(&second.id).unwrap().status,
8725            RunStatus::Merged,
8726            "the run that actually succeeded is left exactly as it was"
8727        );
8728    }
8729
8730    #[test]
8731    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8732        // `is_working_on` alone only proves a *daemon* claim; a `magi run
8733        // --resume` invoked by hand outside the daemon never touches
8734        // `daemon.json` at all, so it would look identical to a genuinely
8735        // idle run without also consulting `RunState::liveness`, which reads
8736        // this run's own recorded `driver_pid` instead.
8737        crate::run::pin_test_home();
8738        let mut first = run_state(RunStatus::Blocked);
8739        first.id = "20260101-000000-sup9".to_owned();
8740        // This test process's own pid: guaranteed alive without needing a
8741        // real second process or daemon.
8742        first.driver_pid = Some(std::process::id());
8743        first.driver_started_at = Some(
8744            crate::proc::process_started_at(std::process::id())
8745                .expect("this test process's own start time must be queryable"),
8746        );
8747        first.save().unwrap();
8748        let mut second = run_state(RunStatus::Merged);
8749        second.id = "20260101-000000-supa".to_owned();
8750        second.save().unwrap();
8751
8752        let mut t = task();
8753        t.runs = vec![first.id.clone(), second.id.clone()];
8754        t.status = TaskStatus::Done;
8755
8756        supersede_prior_runs(&t, &crate::run::home());
8757
8758        assert_eq!(
8759            RunState::load(&first.id).unwrap().status,
8760            RunStatus::Blocked,
8761            "a live driver_pid means something is still actually working this run, \
8762             even though no daemon claims it - rewriting under it would just be \
8763             undone the next time that process saves"
8764        );
8765    }
8766
8767    #[test]
8768    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8769        // The first resweep must skip a still-live attempt exactly like
8770        // `supersede_prior_runs` itself does; a later resweep, once that
8771        // process is no longer actually driving it, is what closes the gap
8772        // `supersede_prior_runs` alone leaves - a task only ever reaches
8773        // `Done` once, so nothing else would ever look at this run again.
8774        let dir = tempfile::tempdir().unwrap();
8775        let home = dir.path().to_path_buf();
8776        let queue = Queue::at(dir.path().join("queue"));
8777
8778        let mut first = run_state(RunStatus::Blocked);
8779        first.id = "20260101-000000-supd".to_owned();
8780        first.driver_pid = Some(std::process::id());
8781        first.driver_started_at = Some(
8782            crate::proc::process_started_at(std::process::id())
8783                .expect("this test process's own start time must be queryable"),
8784        );
8785        first.save_under(&home).unwrap();
8786        let mut second = run_state(RunStatus::Merged);
8787        second.id = "20260101-000000-supe".to_owned();
8788        second.save_under(&home).unwrap();
8789
8790        let mut t = task();
8791        t.runs = vec![first.id.clone(), second.id.clone()];
8792        t.status = TaskStatus::Done;
8793        queue.put(&mut t).unwrap();
8794
8795        resweep_superseded_attempts(&queue, &home);
8796        assert_eq!(
8797            RunState::load_under(&first.id, &home).unwrap().status,
8798            RunStatus::Blocked,
8799            "still live on the first pass, so still untouched"
8800        );
8801
8802        // Stand in for the manual process no longer being the one driving
8803        // this run: same pid (this test process really is still alive), but
8804        // an identity marker that no longer matches it - see
8805        // `RunState::liveness`'s own doc for why a mismatched
8806        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
8807        let mut stale = RunState::load_under(&first.id, &home).unwrap();
8808        stale.driver_started_at = Some("1".to_owned());
8809        stale.save_under(&home).unwrap();
8810
8811        resweep_superseded_attempts(&queue, &home);
8812        assert_eq!(
8813            RunState::load_under(&first.id, &home).unwrap().status,
8814            RunStatus::Superseded,
8815            "the second pass catches up what the first one correctly skipped"
8816        );
8817    }
8818
8819    #[test]
8820    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8821        crate::run::pin_test_home();
8822        let mut first = run_state(RunStatus::Blocked);
8823        first.id = "20260101-000000-sup3".to_owned();
8824        first.save().unwrap();
8825        let mut second = run_state(RunStatus::Blocked);
8826        second.id = "20260101-000000-sup4".to_owned();
8827        second.save().unwrap();
8828
8829        let mut t = task();
8830        t.runs = vec![first.id.clone(), second.id.clone()];
8831        // Still retrying: nothing about this task's story is settled yet, so
8832        // neither Blocked run may be relabelled, even though a later attempt
8833        // already exists.
8834        t.status = TaskStatus::Failed;
8835
8836        supersede_prior_runs(&t, &crate::run::home());
8837
8838        assert_eq!(
8839            RunState::load(&first.id).unwrap().status,
8840            RunStatus::Blocked
8841        );
8842        assert_eq!(
8843            RunState::load(&second.id).unwrap().status,
8844            RunStatus::Blocked
8845        );
8846    }
8847
8848    #[test]
8849    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
8850        // `magi task done` (or the API's equivalent) can close a task with no
8851        // run of its own ever having succeeded - there is nothing here that
8852        // counts as "the attempt that finished it", so nothing is rewritten.
8853        crate::run::pin_test_home();
8854        let mut first = run_state(RunStatus::Blocked);
8855        first.id = "20260101-000000-sup5".to_owned();
8856        first.save().unwrap();
8857
8858        let mut t = task();
8859        t.runs = vec![first.id.clone()];
8860        t.status = TaskStatus::Done;
8861
8862        supersede_prior_runs(&t, &crate::run::home());
8863
8864        assert_eq!(
8865            RunState::load(&first.id).unwrap().status,
8866            RunStatus::Blocked,
8867            "a single-attempt task has no earlier run to supersede"
8868        );
8869    }
8870
8871    #[test]
8872    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
8873        // `magi task done` (or the web/conductor equivalents) can close a
8874        // task in any status, including one whose *last* recorded attempt is
8875        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
8876        // never watched, say. `runs.last()` being `Done`-adjacent is not
8877        // proof it actually succeeded, so nothing earlier may be relabelled
8878        // on its say-so alone.
8879        crate::run::pin_test_home();
8880        let mut first = run_state(RunStatus::Blocked);
8881        first.id = "20260101-000000-supb".to_owned();
8882        first.save().unwrap();
8883        let mut second = run_state(RunStatus::Failed);
8884        second.id = "20260101-000000-supc".to_owned();
8885        second.save().unwrap();
8886
8887        let mut t = task();
8888        t.runs = vec![first.id.clone(), second.id.clone()];
8889        t.status = TaskStatus::Done;
8890
8891        supersede_prior_runs(&t, &crate::run::home());
8892
8893        assert_eq!(
8894            RunState::load(&first.id).unwrap().status,
8895            RunStatus::Blocked,
8896            "the task's last attempt never landed, so there is nothing here \
8897             actually superseding it"
8898        );
8899    }
8900
8901    #[test]
8902    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
8903        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
8904        // to look" - `Failed` and `VerifiedNoop` are already their own
8905        // terminal answers and must not be relabelled into a third one.
8906        crate::run::pin_test_home();
8907        let mut failed = run_state(RunStatus::Failed);
8908        failed.id = "20260101-000000-sup6".to_owned();
8909        failed.save().unwrap();
8910        let mut noop = run_state(RunStatus::VerifiedNoop);
8911        noop.id = "20260101-000000-sup7".to_owned();
8912        noop.save().unwrap();
8913        let mut winner = run_state(RunStatus::Ready);
8914        winner.id = "20260101-000000-sup8".to_owned();
8915        winner.save().unwrap();
8916
8917        let mut t = task();
8918        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
8919        t.status = TaskStatus::Done;
8920
8921        supersede_prior_runs(&t, &crate::run::home());
8922
8923        assert_eq!(
8924            RunState::load(&failed.id).unwrap().status,
8925            RunStatus::Failed
8926        );
8927        assert_eq!(
8928            RunState::load(&noop.id).unwrap().status,
8929            RunStatus::VerifiedNoop
8930        );
8931    }
8932
8933    fn approval_question(run: &str) -> ask::Question {
8934        ask::Question::new(
8935            run.to_owned(),
8936            land::APPROVAL_NODE.to_owned(),
8937            "land".to_owned(),
8938            "merge?".to_owned(),
8939            String::new(),
8940            vec!["merge".to_owned(), "hold".to_owned()],
8941        )
8942    }
8943
8944    #[test]
8945    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
8946        crate::run::pin_test_home();
8947        let mut state = run_state(RunStatus::Landing);
8948        state.id = "20260101-000000-fre1".to_owned();
8949        state.parked = true;
8950        state.save().unwrap();
8951        ask::Questions::open()
8952            .put(&mut approval_question(&state.id))
8953            .unwrap();
8954
8955        let mut t = task();
8956        t.runs.push(state.id.clone());
8957        assert_eq!(
8958            land_resume_state(&t),
8959            LandResume::StillWaiting,
8960            "nobody has answered and the timeout has not passed"
8961        );
8962    }
8963
8964    #[test]
8965    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
8966        crate::run::pin_test_home();
8967        let mut state = run_state(RunStatus::Gating);
8968        state.id = "20260101-000000-gt01".to_owned();
8969        state.parked = true;
8970        state.config.graph.answer_timeout = 60;
8971        state.github_text = Some(crate::run::GithubTextAsk {
8972            rewrite: None,
8973            fingerprint: "f".into(),
8974            title: true,
8975            body: false,
8976            categories: vec!["title-language".into()],
8977            question: None,
8978            asks: 1,
8979            resolved: false,
8980            chosen_title: None,
8981            choice: None,
8982        });
8983        state.save().unwrap();
8984        let store = ask::Questions::open();
8985        let mut q = ask::Question::new(
8986            state.id.clone(),
8987            crate::github_text::ASK_NODE.to_owned(),
8988            crate::github_text::ASK_SEAT.to_owned(),
8989            "s".into(),
8990            String::new(),
8991            vec!["use fallback".into()],
8992        );
8993        store.put(&mut q).unwrap();
8994        let mut t = task();
8995        t.runs.push(state.id.clone());
8996        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
8997        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
8998        store.put(&mut q).unwrap();
8999        assert_eq!(land_resume_state(&t), LandResume::Ready);
9000        assert!(!store.get(&q.id).unwrap().status.open());
9001        // Once decided, a parked run is an ordinary candidate again.
9002        state.github_text.as_mut().unwrap().resolved = true;
9003        state.save().unwrap();
9004        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9005    }
9006
9007    #[test]
9008    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9009        // `ask::ask_and_wait`'s own deadline used to retire a question
9010        // nobody answered; land's approval bypasses that wait (see
9011        // `land::approval_gate`), so this is now the only place
9012        // `graph.answer_timeout` is enforced for a land approval at all.
9013        crate::run::pin_test_home();
9014        let mut state = run_state(RunStatus::Landing);
9015        state.id = "20260101-000000-exp1".to_owned();
9016        state.parked = true;
9017        state.config.graph.answer_timeout = 60;
9018        state.save().unwrap();
9019
9020        let store = ask::Questions::open();
9021        let mut q = approval_question(&state.id);
9022        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9023        store.put(&mut q).unwrap();
9024
9025        let mut t = task();
9026        t.runs.push(state.id.clone());
9027        assert_eq!(
9028            land_resume_state(&t),
9029            LandResume::Ready,
9030            "an expired question must not be waited on forever"
9031        );
9032
9033        let after = store.get(&q.id).unwrap();
9034        assert!(
9035            !after.status.open(),
9036            "the question is abandoned, not silently ignored"
9037        );
9038        assert!(
9039            after.resolution().is_none(),
9040            "an abandoned question is not read as a decision"
9041        );
9042    }
9043
9044    #[test]
9045    fn reclaim_settles_a_running_task_against_its_last_run() {
9046        let mut t = task();
9047        t.start("20260904-000000-4043".to_owned());
9048        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9049        assert_eq!(
9050            t.status,
9051            TaskStatus::Done,
9052            "a run that actually finished must not stay `running` forever"
9053        );
9054    }
9055
9056    #[test]
9057    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9058        let mut t = task();
9059        t.start("20260904-000000-4043".to_owned());
9060        t.last_error = Some("earlier trouble".to_owned());
9061        let mut state = run_state(RunStatus::Judging);
9062        state.parked = true;
9063        reclaim(&mut t, Some(state), 1, "en");
9064        assert_eq!(t.status, TaskStatus::Parked);
9065        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9066        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9067        assert!(t.park_reason.is_some());
9068        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9069        assert!(!t.fresh_start);
9070        assert!(t.status.runnable());
9071    }
9072
9073    #[test]
9074    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9075        let mut t = task();
9076        t.start("20260904-000000-4043".to_owned());
9077        t.last_error = Some("earlier trouble".to_owned());
9078        settle(
9079            &mut t,
9080            Verdict {
9081                status: RunStatus::Judging,
9082                left_pr: false,
9083                quota_hit: false,
9084                parked: true,
9085                no_viable_candidates: false,
9086            },
9087            "parked after `judging`",
9088            1,
9089        );
9090        assert_eq!(t.status, TaskStatus::Parked);
9091        assert_eq!(t.attempts, 0);
9092        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9093        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9094        assert_eq!(t.schema, crate::queue::SCHEMA);
9095        assert!(
9096            crate::notices::task_held(&t).is_none(),
9097            "a park is not news"
9098        );
9099        t.start("20260904-000000-4043".to_owned());
9100        assert_eq!(t.park_reason, None);
9101    }
9102
9103    #[test]
9104    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9105        // A blocked run with attempts left goes back to `Failed`, exactly as
9106        // it would from `attempt` itself - `reclaim` must not invent a second
9107        // policy for a task a daemon merely stopped without reporting.
9108        let mut t = task();
9109        t.start("20260904-000000-4043".to_owned());
9110        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9111        assert_eq!(t.status, TaskStatus::Failed);
9112        assert!(t.status.runnable());
9113    }
9114
9115    #[test]
9116    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9117        let mut t = task();
9118        t.start("20260904-000000-4043".to_owned());
9119        assert_eq!(t.attempts, 1);
9120        let mut run = run_state(RunStatus::Implementing);
9121        run.id = "20260904-000000-4043".to_owned();
9122        run.begin_pass();
9123        let cause = crate::run::ParkCause::Upgrade {
9124            from: "0.121.0".to_owned(),
9125            to: Some("0.121.1".to_owned()),
9126        };
9127        run.end_pass_parked(cause.clone());
9128        run.parked = true;
9129        let verdict = Verdict {
9130            status: run.status,
9131            left_pr: false,
9132            quota_hit: false,
9133            parked: true,
9134            no_viable_candidates: false,
9135        };
9136        // A crash after the checkpoint but before queue settlement must
9137        // recover exactly the same scheduling evidence and refund.
9138        let mut orphan = t.clone();
9139        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9140        assert_eq!(orphan.status, TaskStatus::Parked);
9141        assert_eq!(orphan.attempts, 0);
9142        assert_eq!(
9143            orphan.upgrade_resume_key(),
9144            Some((run.passes[0].started_at, orphan.id.as_str()))
9145        );
9146        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9147        assert_eq!(t.attempts, 0);
9148        assert_eq!(t.passes.len(), 1);
9149        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9150        assert_eq!(t.passes[0].parked, Some(cause));
9151        assert_eq!(t.passes[0].pass_index, 0);
9152        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9153        assert!(t.upgrade_resume_key().is_some());
9154
9155        // A resumed pass that then fails spends its attempt, and the earlier
9156        // pass's entry is untouched.
9157        t.start("20260904-000000-4043".to_owned());
9158        run.begin_pass();
9159        run.status = RunStatus::Failed;
9160        let verdict = Verdict {
9161            status: RunStatus::Failed,
9162            left_pr: false,
9163            quota_hit: false,
9164            parked: false,
9165            no_viable_candidates: false,
9166        };
9167        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9168        assert_eq!(t.passes.len(), 2);
9169        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9170        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9171        assert_eq!(t.passes[1].pass_index, 1);
9172        assert_eq!(t.attempts, 1);
9173    }
9174
9175    #[test]
9176    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9177        let mut t = task();
9178        t.start("20260904-000000-4043".to_owned());
9179        reclaim(&mut t, None, 2, "en");
9180        assert_eq!(t.status, TaskStatus::Held);
9181        assert!(
9182            t.last_error
9183                .as_deref()
9184                .is_some_and(|e| e.contains("running")),
9185            "the operator needs to know why this task was held"
9186        );
9187    }
9188
9189    #[test]
9190    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9191        let dir = tempfile::tempdir().unwrap();
9192        let queue = Queue::at(dir.path().to_path_buf());
9193
9194        // No run recorded, so this never has to touch `RunState::load`.
9195        let mut orphaned = task();
9196        orphaned.id = "20260904-000000-orph".to_owned();
9197        orphaned.status = TaskStatus::Running;
9198        orphaned.attempts = 1;
9199        queue.put(&mut orphaned).unwrap();
9200
9201        let mut alive = task();
9202        alive.id = "20260904-000000-live".to_owned();
9203        alive.status = TaskStatus::Running;
9204        alive.attempts = 1;
9205        queue.put(&mut alive).unwrap();
9206        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9207
9208        let mut queued = task();
9209        queued.id = "20260904-000000-wait".to_owned();
9210        queue.put(&mut queued).unwrap();
9211
9212        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9213        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9214
9215        assert_eq!(
9216            queue.get(&orphaned.id).unwrap().status,
9217            TaskStatus::Held,
9218            "nothing was driving it and there was no run to recover"
9219        );
9220        assert_eq!(
9221            queue.get(&alive.id).unwrap().status,
9222            TaskStatus::Running,
9223            "a live claim must protect the task it belongs to"
9224        );
9225        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9226    }
9227
9228    /// Read a run.json back from an explicit `home`, the same way
9229    /// `reclaim_abandoned_runs` itself does - never through the
9230    /// process-global `RunState::load`, which this test's own `home` (an
9231    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9232    /// use at all.
9233    fn read_run_under(home: &Path, id: &str) -> RunState {
9234        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9235        serde_json::from_str(&body).unwrap()
9236    }
9237
9238    #[test]
9239    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9240        let dir = tempfile::tempdir().unwrap();
9241        let home = dir.path().to_path_buf();
9242        let now = Timestamp::now();
9243        let overrun_seat = || crate::run::ActiveSeat {
9244            node: "implement".to_owned(),
9245            started_at: now - jiff::SignedDuration::new(21_000, 0),
9246            timeout_secs: 3_600,
9247            attempt: 0,
9248            task: None,
9249            command: None,
9250            index: None,
9251            total: None,
9252        };
9253
9254        let mut dead = run_state(RunStatus::Implementing);
9255        dead.id = "20260101-000000-dead".to_owned();
9256        dead.active.insert("impl-A".to_owned(), overrun_seat());
9257        // A `driver_pid` the injected query below confirms gone outright —
9258        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9259        dead.driver_pid = Some(4242);
9260        dead.save_under(&home).unwrap();
9261
9262        // Same shape, but a live daemon's heartbeat names it: must be left
9263        // exactly alone, however far past its own timeout the seat sits.
9264        let mut alive = run_state(RunStatus::Implementing);
9265        alive.id = "20260101-000000-aliv".to_owned();
9266        alive.active.insert("impl-A".to_owned(), overrun_seat());
9267        alive.save_under(&home).unwrap();
9268        let mut status = Status::new();
9269        status.current = vec![Current {
9270            worker: None,
9271            task: "20260101-000000-task".to_owned(),
9272            run: alive.id.clone(),
9273        }];
9274        write_status_to(&home.join("daemon.json"), &status).unwrap();
9275
9276        // The abandoned seat left an open question behind: nobody is left to
9277        // read an answer once the run is failed, and this must not wait for
9278        // some later daemon startup's own sweep to notice that.
9279        let questions = Questions::at(home.join("questions"));
9280        let mut q = ask::Question::new(
9281            dead.id.clone(),
9282            "implement".to_owned(),
9283            "impl-A".to_owned(),
9284            "Which storage backend?".to_owned(),
9285            String::new(),
9286            vec!["SQLite".to_owned(), "Redis".to_owned()],
9287        );
9288        questions.put(&mut q).unwrap();
9289
9290        let abandoned = reclaim_abandoned_runs_with(
9291            &home,
9292            now,
9293            |pid| if pid == 4242 { Some(false) } else { None },
9294            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9295        );
9296        assert_eq!(abandoned, vec![dead.id.clone()]);
9297
9298        let reloaded = read_run_under(&home, &dead.id);
9299        assert_eq!(reloaded.status, RunStatus::Failed);
9300        assert!(reloaded.active.is_empty());
9301        assert!(
9302            !questions.get(&q.id).unwrap().status.open(),
9303            "the failed run's own open question must be settled in the same pass"
9304        );
9305
9306        let still_alive = read_run_under(&home, &alive.id);
9307        assert_eq!(
9308            still_alive.status,
9309            RunStatus::Implementing,
9310            "a live daemon's claim protects it"
9311        );
9312        assert!(!still_alive.active.is_empty());
9313    }
9314
9315    /// The exact shape a review round flagged as broken: `magi serve` running
9316    /// in this same `home` scans *every* run on disk, including a manual
9317    /// `magi review` / `magi run` this daemon never started and that
9318    /// therefore claims no heartbeat of its own. Before this scan asked
9319    /// `liveness` rather than just `is_working_on`, a manual run whose active
9320    /// seat merely ran a little past its own timeout — the CLI finishing up,
9321    /// its result still being collected — got wiped and failed by a daemon
9322    /// that had nothing to do with it, out from under a process that was
9323    /// still very much running.
9324    #[test]
9325    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9326        let dir = tempfile::tempdir().unwrap();
9327        let home = dir.path().to_path_buf();
9328        let now = Timestamp::now();
9329
9330        let mut manual = run_state(RunStatus::Reviewing);
9331        manual.id = "20260101-000000-manl".to_owned();
9332        manual.active.insert(
9333            "review-1".to_owned(),
9334            crate::run::ActiveSeat {
9335                node: "review".to_owned(),
9336                started_at: now - jiff::SignedDuration::new(21_000, 0),
9337                timeout_secs: 3_600,
9338                attempt: 0,
9339                task: None,
9340                command: None,
9341                index: None,
9342                total: None,
9343            },
9344        );
9345        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9346        // but a real, still-running process: `liveness` must corroborate this
9347        // as `Live`, not read the missing daemon claim as death.
9348        manual.driver_pid = Some(4242);
9349        manual.driver_started_at = Some("1790000000".to_owned());
9350        manual.save_under(&home).unwrap();
9351
9352        let abandoned = reclaim_abandoned_runs_with(
9353            &home,
9354            now,
9355            |pid| if pid == 4242 { Some(true) } else { None },
9356            |pid| {
9357                if pid == 4242 {
9358                    Some("1790000000".to_owned())
9359                } else {
9360                    None
9361                }
9362            },
9363        );
9364        assert!(
9365            abandoned.is_empty(),
9366            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9367        );
9368
9369        let reloaded = read_run_under(&home, &manual.id);
9370        assert_eq!(reloaded.status, RunStatus::Reviewing);
9371        assert!(!reloaded.active.is_empty());
9372    }
9373
9374    #[test]
9375    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9376        let dir = tempfile::tempdir().unwrap();
9377        let queue = Queue::at(dir.path().to_path_buf());
9378        let mut only = task();
9379        queue.put(&mut only).unwrap();
9380
9381        let _elsewhere = queue.claim(&only.id).unwrap();
9382        let candidates = runnable(&queue);
9383        assert_eq!(candidates.len(), 1, "the task is still runnable");
9384        assert!(
9385            queue.claim(&candidates[0].id).is_err(),
9386            "the loop cannot take a claim somebody else holds"
9387        );
9388
9389        let after = queue.get(&only.id).unwrap();
9390        assert_eq!(after.status, TaskStatus::Queued);
9391        assert_eq!(
9392            after.attempts, 0,
9393            "losing the race is not an attempt at the task"
9394        );
9395        assert_eq!(after.last_error, None);
9396    }
9397
9398    #[test]
9399    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9400        let dir = tempfile::tempdir().unwrap();
9401        let path = dir.path().join("daemon.json");
9402
9403        let mut status = Status::new();
9404        status.idle = false;
9405        status.completed = 7;
9406        status.current = vec![Current {
9407            worker: None,
9408            task: "20260902-000000-t111".to_owned(),
9409            run: "20260902-000001-r111".to_owned(),
9410        }];
9411        write_status_to(&path, &status).unwrap();
9412        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9413        assert_eq!(first.schema, SCHEMA);
9414        assert_eq!(first.pid, std::process::id());
9415        assert!(!first.idle);
9416        assert_eq!(first.completed, 7);
9417        assert_eq!(first.current, status.current);
9418        assert!(
9419            !path.with_extension("json.tmp").exists(),
9420            "the temp file is renamed, not left behind"
9421        );
9422
9423        std::thread::sleep(Duration::from_millis(5));
9424        status.updated_at = Timestamp::now();
9425        status.polls = 3;
9426        write_status_to(&path, &status).unwrap();
9427        let second: Status =
9428            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9429        assert!(
9430            second.updated_at > first.updated_at,
9431            "a reader can only detect staleness if the heartbeat moves"
9432        );
9433        assert_eq!(
9434            second.started_at, first.started_at,
9435            "the start time is not a heartbeat"
9436        );
9437        assert_eq!(second.polls, 3);
9438    }
9439
9440    #[test]
9441    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9442        let dir = tempfile::tempdir().unwrap();
9443
9444        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9445
9446        let mut status = Status::new();
9447        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9448        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9449        let stale = read_status(dir.path()).unwrap();
9450        assert!(
9451            !stale.running(Timestamp::now()),
9452            "a minute without a heartbeat is a dead daemon, not a busy one"
9453        );
9454        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9455
9456        status.updated_at = Timestamp::now();
9457        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9458        let fresh = read_status(dir.path()).unwrap();
9459        assert!(fresh.running(Timestamp::now()));
9460    }
9461
9462    #[test]
9463    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9464        let dir = tempfile::tempdir().unwrap();
9465        let now = Timestamp::now();
9466        let mine = "20260903-080619-01c2";
9467
9468        assert!(
9469            !is_working_on(dir.path(), mine, now),
9470            "no status file means nobody is working on anything"
9471        );
9472
9473        let mut status = Status::new();
9474        status.current = vec![Current {
9475            worker: None,
9476            task: "20260903-080340-0167".to_owned(),
9477            run: mine.to_owned(),
9478        }];
9479        status.updated_at = now;
9480        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9481        assert!(is_working_on(dir.path(), mine, now));
9482        assert!(
9483            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9484            "a daemon busy with one run is not working on another"
9485        );
9486
9487        // A killed daemon stops writing heartbeats but leaves the file behind
9488        // naming the run it died in. That run must not be undeletable forever.
9489        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9490        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9491        assert!(
9492            !is_working_on(dir.path(), mine, now),
9493            "a stale heartbeat is a dead daemon, so its run is a leftover"
9494        );
9495    }
9496
9497    #[test]
9498    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9499        let dir = tempfile::tempdir().unwrap();
9500        let now = Timestamp::now();
9501
9502        assert!(
9503            !is_working_on_short(dir.path(), "01c2", now),
9504            "no status file means nobody is working on anything"
9505        );
9506
9507        let mut status = Status::new();
9508        status.current = vec![Current {
9509            worker: None,
9510            task: "20260903-080340-0167".to_owned(),
9511            run: "20260903-080619-01c2".to_owned(),
9512        }];
9513        status.updated_at = now;
9514        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9515        assert!(
9516            is_working_on_short(dir.path(), "01c2", now),
9517            "the run's short id is the last block of its full id"
9518        );
9519        assert!(
9520            !is_working_on_short(dir.path(), "3cbf", now),
9521            "a daemon busy with one worktree bay is not working on another"
9522        );
9523    }
9524
9525    #[test]
9526    fn a_newer_status_file_still_yields_a_reading() {
9527        let dir = tempfile::tempdir().unwrap();
9528        // A field this build has never heard of must not turn the reading into
9529        // nothing at all; that is the whole reason the reader is permissive.
9530        std::fs::write(
9531            dir.path().join("daemon.json"),
9532            serde_json::json!({
9533                "schema": 2,
9534                "updated_at": Timestamp::now().to_string(),
9535                "idle": true,
9536                "surprise": { "nested": [1, 2, 3] },
9537            })
9538            .to_string(),
9539        )
9540        .unwrap();
9541
9542        let reading = read_status(dir.path()).expect("a forward-compatible read");
9543        assert!(reading.running(Timestamp::now()));
9544        assert!(reading.idle);
9545        assert!(reading.current.is_empty());
9546    }
9547
9548    #[test]
9549    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9550        // A daemon started before `current` became a list keeps writing this
9551        // shape on every heartbeat until it is restarted. A rolling upgrade
9552        // - a newer `magi web` or `magi doctor` reading an older `magi
9553        // serve`'s heartbeat - must still see the run it is on, not "no
9554        // daemon" from a type mismatch failing the whole struct.
9555        let dir = tempfile::tempdir().unwrap();
9556        std::fs::write(
9557            dir.path().join("daemon.json"),
9558            serde_json::json!({
9559                "schema": 1,
9560                "pid": 4242,
9561                "updated_at": Timestamp::now().to_string(),
9562                "idle": false,
9563                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9564                "completed": 3,
9565                "polls": 9,
9566            })
9567            .to_string(),
9568        )
9569        .unwrap();
9570
9571        let reading = read_status(dir.path()).expect("an older shape must still parse");
9572        assert!(reading.running(Timestamp::now()));
9573        assert_eq!(
9574            reading.current,
9575            vec![Current {
9576                worker: None,
9577                task: "20260902-140501-aaaa".to_owned(),
9578                run: "20260902-140502-bbbb".to_owned(),
9579            }]
9580        );
9581    }
9582
9583    #[test]
9584    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9585        let dir = tempfile::tempdir().unwrap();
9586        std::fs::write(
9587            dir.path().join("daemon.json"),
9588            serde_json::json!({
9589                "schema": 1,
9590                "updated_at": Timestamp::now().to_string(),
9591                "idle": true,
9592                "current": null,
9593            })
9594            .to_string(),
9595        )
9596        .unwrap();
9597        let with_null = read_status(dir.path()).expect("null must still parse");
9598        assert!(with_null.current.is_empty());
9599
9600        std::fs::write(
9601            dir.path().join("daemon.json"),
9602            serde_json::json!({
9603                "schema": 1,
9604                "updated_at": Timestamp::now().to_string(),
9605                "idle": true,
9606            })
9607            .to_string(),
9608        )
9609        .unwrap();
9610        let absent = read_status(dir.path()).expect("a missing field must still parse");
9611        assert!(absent.current.is_empty());
9612    }
9613
9614    #[test]
9615    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9616        let fallback = Path::new("/default");
9617        let mut blank = task();
9618        blank.repo = PathBuf::new();
9619        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9620        let mut dot = task();
9621        dot.repo = PathBuf::from(".");
9622        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9623        assert_eq!(
9624            repo_for(&task(), fallback),
9625            PathBuf::from("/repo"),
9626            "a task that names a repository keeps it"
9627        );
9628    }
9629
9630    #[test]
9631    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9632        let dir = tempfile::tempdir().unwrap();
9633        let path = dir.path().join("explicit.toml");
9634        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9635        let opts = Opts {
9636            config: Some(path),
9637            merge: Some("none".into()),
9638            ..Default::default()
9639        };
9640        let mut t = task();
9641        t.set_implementers(
9642            2,
9643            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9644                .unwrap(),
9645        )
9646        .unwrap();
9647        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9648        assert_eq!(cfg.graph.implementers, 2);
9649        assert_eq!(cfg.graph.judges, 1);
9650        assert_eq!(cfg.merge.mode, MergeMode::None);
9651        t.set_implementers(1, &cfg).unwrap();
9652        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9653        apply_task_implementers(&mut cfg, &t);
9654        assert_eq!(cfg.graph.implementers, 1);
9655        assert_eq!(cfg.graph.judges, 1);
9656        assert_eq!(cfg.merge.mode, MergeMode::None);
9657    }
9658
9659    #[test]
9660    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9661        let dir = tempfile::tempdir().unwrap();
9662        let repo = dir.path().join("repo");
9663        std::fs::create_dir(&repo).unwrap();
9664        std::fs::write(
9665            repo.join("magi.toml"),
9666            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9667        )
9668        .unwrap();
9669        let daemon_config = dir.path().join("daemon.toml");
9670        std::fs::write(
9671            &daemon_config,
9672            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9673        )
9674        .unwrap();
9675        let opts = Opts {
9676            config: Some(daemon_config),
9677            merge: Some("pr".into()),
9678            ..Default::default()
9679        };
9680        let q = Queue::at(dir.path().join("queue"));
9681        let validation: Config =
9682            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9683                .unwrap();
9684        // No provenance field on legacy direct tasks: both shapes stay isolated.
9685        for record in ["{}", r#"{"candidates":2}"#] {
9686            let overrides = serde_json::from_str(record).unwrap();
9687            let filing = crate::direct::Filing {
9688                instruction: "work".into(),
9689                title: "direct".into(),
9690                repo: repo.clone(),
9691                source: crate::queue::Source::Human,
9692                solo: false,
9693                overrides,
9694                review_of: None,
9695                sources: Default::default(),
9696            };
9697            let filed =
9698                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9699            let crate::direct::Filed::Standalone {
9700                mut task,
9701                claim: _claim,
9702            } = filed
9703            else {
9704                panic!("local filing")
9705            };
9706            let before = prepare_for(&repo, &opts, &task).unwrap();
9707            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9708            assert_eq!(
9709                before.merge.mode,
9710                MergeMode::None,
9711                "daemon --merge must not leak"
9712            );
9713            for n in [2, 1, 2] {
9714                task.set_implementers(n, &validation).unwrap();
9715                q.put(&mut task).unwrap();
9716                task = q.get(&task.id).unwrap();
9717                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9718                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9719                apply_task_implementers(&mut cfg, &task);
9720                assert_eq!(cfg.graph.implementers, usize::from(n));
9721                assert_eq!(cfg.graph.judges, 2);
9722                assert_eq!(cfg.merge.mode, MergeMode::None);
9723            }
9724        }
9725    }
9726
9727    #[test]
9728    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9729        let cfg: Config =
9730            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9731                .unwrap();
9732        let mut t = task();
9733        t.review_of = Some("review-target".into());
9734        t.hold_manual(Some("retry".into()));
9735        let mut previous = RunState::new(
9736            PathBuf::from("/repo"),
9737            "main".into(),
9738            "abc1234".into(),
9739            "review".into(),
9740            cfg.clone(),
9741        );
9742        previous.config.graph.implementers = 2;
9743        for count in [1, 3] {
9744            t.set_implementers(count, &cfg).unwrap();
9745            t.release();
9746            assert_eq!(t.review_of.as_deref(), Some("review-target"));
9747            for proposed in [
9748                Starter::Resume(previous.id.clone()),
9749                Starter::Review("recovery-target".into()),
9750            ] {
9751                assert_eq!(
9752                    starter_with_implementers(&t, Some(&previous), proposed),
9753                    Starter::Review("review-target".into())
9754                );
9755            }
9756            let mut configured = cfg.clone();
9757            apply_task_implementers(&mut configured, &t);
9758            assert_eq!(configured.graph.implementers, usize::from(count));
9759            assert_eq!(previous.config.graph.implementers, 2);
9760        }
9761    }
9762
9763    #[test]
9764    fn task_implementers_dispatch_and_resume_agree() {
9765        let mut t = task();
9766        let cfg: crate::config::Config =
9767            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9768                .unwrap();
9769        let mut run = RunState::new(
9770            PathBuf::from("/repo"),
9771            "main".into(),
9772            "abc1234".into(),
9773            "work".into(),
9774            cfg.clone(),
9775        );
9776        run.config.graph.implementers = 2;
9777        for n in [2, 1, 3, 2] {
9778            t.set_implementers(n, &cfg).unwrap();
9779            let mut dispatched = cfg.clone();
9780            apply_task_implementers(&mut dispatched, &t);
9781            assert_eq!(dispatched.graph.implementers, usize::from(n));
9782            assert_eq!(implementers_match(&t, &run), n == 2);
9783            for proposed in [
9784                Starter::Resume(run.id.clone()),
9785                Starter::Review("old-branch".into()),
9786            ] {
9787                let expected = if n == 2 {
9788                    proposed.clone()
9789                } else {
9790                    Starter::Start
9791                };
9792                assert_eq!(
9793                    starter_with_implementers(&t, Some(&run), proposed),
9794                    expected
9795                );
9796            }
9797            assert_eq!(
9798                run.config.graph.implementers, 2,
9799                "history must not be rewritten"
9800            );
9801        }
9802        t.solo = false;
9803        t.overrides = None;
9804        assert!(implementers_match(&t, &run));
9805    }
9806
9807    #[test]
9808    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9809        // Three seats said out loud. What `solo` promises is one candidate
9810        // *whatever the config asks for*, so the contrast has to be a number
9811        // this test owns - it used to be `Config::default()`'s, which became
9812        // 1 when one implementation became the default and left the two
9813        // halves of this test asserting the same thing.
9814        let mut solo_cfg = Config::default();
9815        solo_cfg.graph.implementers = 3;
9816        let mut solo_task = task();
9817        solo_task.solo = true;
9818        apply_task_implementers(&mut solo_cfg, &solo_task);
9819        assert_eq!(solo_cfg.graph.implementers, 1);
9820
9821        let mut plain_cfg = Config::default();
9822        plain_cfg.graph.implementers = 3;
9823        let plain_task = task();
9824        assert!(!plain_task.solo);
9825        apply_task_implementers(&mut plain_cfg, &plain_task);
9826        assert_eq!(
9827            plain_cfg.graph.implementers, 3,
9828            "a task that did not ask to run alone keeps the config's candidates"
9829        );
9830    }
9831
9832    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9833        QuotaLoss {
9834            seat: seat.into(),
9835            node: "judge".into(),
9836            at: at.parse().unwrap(),
9837            reset: reset.map(str::to_string),
9838        }
9839    }
9840
9841    #[test]
9842    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
9843        let old: Vec<QuotaLoss> = (1..=4)
9844            .map(|i| {
9845                loss(
9846                    &format!("judge-{i}"),
9847                    "2026-09-23T05:23:00Z",
9848                    Some("2:40pm (Asia/Tokyo)"),
9849                )
9850            })
9851            .collect();
9852        let fresh = losses_this_attempt(&old, &old);
9853        assert!(fresh.is_empty());
9854        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
9855        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
9856    }
9857
9858    #[test]
9859    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
9860        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
9861        let now = Timestamp::now();
9862        let mut after = old.clone();
9863        after.push(loss("judge-2", &now.to_string(), None));
9864        let fresh = losses_this_attempt(&old, &after);
9865        assert_eq!(fresh, vec![after[1].clone()]);
9866        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
9867        assert_eq!(
9868            until,
9869            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
9870        );
9871    }
9872
9873    #[test]
9874    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
9875        // `recover_stall` removes judge-1's loss and the retry then hits quota
9876        // again: the vector is the same length, so an index diff sees nothing.
9877        let before = vec![
9878            loss("judge-1", "2026-09-23T05:23:00Z", None),
9879            loss("judge-2", "2026-09-23T05:24:00Z", None),
9880        ];
9881        let after = vec![
9882            loss("judge-2", "2026-09-23T05:24:00Z", None),
9883            loss("judge-1", "2026-09-24T01:00:00Z", None),
9884        ];
9885        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
9886    }
9887
9888    #[test]
9889    fn merge_overrides_are_parsed_or_refused() {
9890        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
9891        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
9892        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
9893        assert!(merge_mode("squash").is_err());
9894    }
9895
9896    #[test]
9897    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
9898        let now = Timestamp::now();
9899        let fallback = Duration::from_secs(300);
9900        let cap = Duration::from_secs(1800);
9901
9902        // No reset hint at all: the fallback.
9903        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
9904
9905        // A reset ten minutes out, well inside the cap: waited for exactly.
9906        let soon = now + jiff::SignedDuration::from_secs(600);
9907        assert_eq!(
9908            quota_wait(Some(soon), now, fallback, cap),
9909            Duration::from_secs(600)
9910        );
9911
9912        // A reset already in the past is not trusted: the fallback, not a
9913        // zero or negative wait that would spin the loop right back around.
9914        let past = now - jiff::SignedDuration::from_secs(60);
9915        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
9916
9917        // A reset further out than the cap is trusted for direction but not
9918        // for magnitude: a parsing slip must not sleep the loop for a day.
9919        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
9920        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
9921    }
9922
9923    #[test]
9924    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
9925        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9926
9927        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
9928        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
9929
9930        // Same clock reading, but it has already gone by today: read as
9931        // tomorrow's, since the CLI would not still be reporting a limit past
9932        // its own stated reset.
9933        let already_past =
9934            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
9935        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
9936
9937        assert!(
9938            parse_reset_hint("session limit reached", now, now).is_none(),
9939            "free text with no recognised shape is not guessed at"
9940        );
9941        assert!(
9942            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
9943            "an unresolvable zone name is not guessed at either"
9944        );
9945    }
9946
9947    #[test]
9948    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
9949        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9950
9951        let at = parse_reset_hint(
9952            "You've hit your usage limit. Visit \
9953             https://chatgpt.com/codex/settings/usage to purchase more \
9954             credits or try again at Sep 19th, 2026 5:10 PM.",
9955            now,
9956            now,
9957        )
9958        .expect("the codex reset wording is a recognised shape");
9959        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
9960
9961        // The month is explicit, so a date already earlier in the same
9962        // sentence-implied year than `now` is trusted as written rather than
9963        // rolled forward a year the way the bracketed shape rolls a
9964        // same-day clock reading to tomorrow.
9965        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
9966            .expect("an explicit year needs no rollover");
9967        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
9968
9969        assert!(
9970            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
9971            "a two-digit year is not the documented shape and is not guessed at"
9972        );
9973        assert!(
9974            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
9975            "a four-letter month name is not the documented three-letter abbreviation"
9976        );
9977        assert!(
9978            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
9979            "an explicit zone on the dated shape is a format nobody has \
9980             documented, and is refused rather than guessed at as UTC"
9981        );
9982    }
9983
9984    #[test]
9985    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
9986        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
9987        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
9988
9989        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
9990        assert_eq!(at.as_second() - recorded.as_second(), 3769);
9991
9992        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
9993        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
9994
9995        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
9996            assert!(
9997                parse_reset_hint(bad, now, recorded).is_none(),
9998                "{bad:?} must not be guessed at"
9999            );
10000        }
10001    }
10002
10003    /// A loop whose queue lives in a temp tree and whose poll interval is far
10004    /// longer than the test's patience, so anything that waits out a poll
10005    /// instead of noticing the stop fails rather than merely being slow.
10006    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10007        let config = dir.join("magi.toml");
10008        std::fs::write(
10009            &config,
10010            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10011        )
10012        .unwrap();
10013        let opts = Opts {
10014            poll: Duration::from_secs(30),
10015            config: Some(config),
10016            // The explicit fixture config keeps startup cleanup from reading
10017            // machine configuration. This fictional repository likewise
10018            // keeps any best-effort git cleanup away from this checkout.
10019            repo: dir.join("repo"),
10020            ..Opts::default()
10021        };
10022        // The status file goes in a directory that does not exist yet, so its
10023        // creation is itself evidence the loop published one. `worktrees`
10024        // must be just as fictional: the janitor reclaims worktrees under it
10025        // for real, and a test that let it fall through to
10026        // `crate::run::default_worktree_root()` would have it reclaim
10027        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10028        // which is exactly what happened before this function took the
10029        // parameter at all.
10030        let home = dir.join("home");
10031        // These control-only fixtures do not launch native workers. Give the
10032        // independently tested maintenance services a fresh cadence receipt.
10033        let stamps = home.join("service-ticks");
10034        std::fs::create_dir_all(&stamps).unwrap();
10035        for service in ["waiter", "deputies", "release-watch"] {
10036            std::fs::write(
10037                stamps.join(service),
10038                Timestamp::now().as_second().to_string(),
10039            )
10040            .unwrap();
10041        }
10042        for operation in [
10043            "conductor",
10044            "maintenance",
10045            "housekeeping",
10046            "disk-pressure",
10047            "cache",
10048            "fetch",
10049        ] {
10050            std::fs::write(
10051                stamps.join(format!("daemon-{operation}")),
10052                serde_json::to_vec(&Timestamp::now()).unwrap(),
10053            )
10054            .unwrap();
10055        }
10056        let worktrees = dir.join("wt");
10057        (
10058            opts,
10059            Queue::at(dir.join("queue")),
10060            home.join("daemon.json"),
10061            home,
10062            worktrees,
10063        )
10064    }
10065
10066    #[test]
10067    fn a_stop_is_idempotent_and_once_set_stays_set() {
10068        let stop = Stop::new();
10069        assert!(!stop.stopped());
10070
10071        stop.stop();
10072        assert!(stop.stopped());
10073        stop.stop();
10074        assert!(stop.stopped(), "a second stop is not a toggle");
10075
10076        let shared = stop.clone();
10077        assert!(
10078            shared.stopped(),
10079            "a clone is the same stop; that is how the loop and its caller share one"
10080        );
10081    }
10082
10083    #[tokio::test]
10084    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10085        for operation in ["conductor", "maintenance", "housekeeping"] {
10086            let dir = tempfile::tempdir().unwrap();
10087            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10088            opts.once = true;
10089            opts.poll = Duration::from_millis(1);
10090            let mut task = task();
10091            task.runs.push("fixture-run".into());
10092            queue.put(&mut task).unwrap();
10093            let claim = queue.claim(&task.id).unwrap();
10094
10095            // Model a live service holding the task's claim across the
10096            // scheduler's dispatch scan. No real subprocess or timed race.
10097            let directory = home.join("workers/jobs/abcdef");
10098            std::fs::create_dir_all(&directory).unwrap();
10099            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10100            crate::pr_head::try_lock_file(&lease).unwrap();
10101            let mut job = crate::worker::Job {
10102                id: "abcdef".into(),
10103                sequence: 1,
10104                kind: "daemon-service".into(),
10105                key: format!("service:daemon-{operation}"),
10106                payload: serde_json::Value::Null,
10107                generation: "fixture".into(),
10108                version: None,
10109                status: crate::worker::Status::Running,
10110                result: None,
10111                pid: Some(std::process::id()),
10112                created_at: Timestamp::now().as_second() as u64,
10113                finished_at: None,
10114            };
10115            let record = directory.join("job.json");
10116            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10117
10118            let status = Arc::new(Mutex::new(Status::new()));
10119            let stop = Stop::new();
10120            let mut drain = Box::pin(poll(
10121                &opts,
10122                &queue,
10123                &status,
10124                &home,
10125                &worktrees,
10126                &stop,
10127                DispatchLimits {
10128                    max_concurrent: 1,
10129                    pause_for_interrupts: false,
10130                    recovery_cfg: None,
10131                },
10132            ));
10133            std::future::poll_fn(|cx| {
10134                use std::future::Future;
10135                assert!(
10136                    drain.as_mut().poll(cx).is_pending(),
10137                    "--once must wait for {operation} to release its queue claim"
10138                );
10139                std::task::Poll::Ready(())
10140            })
10141            .await;
10142            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10143
10144            // An answer arrives while the service still owns the claim. A
10145            // fresh scheduling pass must apply it before declaring idle.
10146            let questions = Questions::at(home.join("questions"));
10147            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10148            questions.put(&mut q).unwrap();
10149            drop(claim);
10150            // Model services that took longer than their cadence, without a
10151            // wall-clock sleep. The final scans must not respawn them even
10152            // though their receipts now permit another periodic invocation.
10153            let expired =
10154                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10155            for service in [operation, "housekeeping"] {
10156                std::fs::write(
10157                    home.join("service-ticks").join(format!("daemon-{service}")),
10158                    &expired,
10159                )
10160                .unwrap();
10161            }
10162            job.status = crate::worker::Status::Finished;
10163            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10164            drop(lease);
10165            tokio::time::timeout(Duration::from_secs(2), drain)
10166                .await
10167                .expect("the settled service must allow the drain to finish")
10168                .unwrap();
10169            let after = queue.get(&task.id).unwrap();
10170            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10171            assert!(after.action_applied(&q.id));
10172            for service in [operation, "housekeeping"] {
10173                assert_eq!(
10174                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10175                        .unwrap(),
10176                    expired,
10177                    "the final once rescan must not restart {service}"
10178                );
10179            }
10180        }
10181    }
10182
10183    #[test]
10184    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10185        let stop = Stop::new();
10186        stop.busy.store(1, Ordering::SeqCst);
10187        assert!(
10188            !stop.finishing(),
10189            "a busy loop nobody has asked to stop is just running"
10190        );
10191
10192        stop.stop();
10193        assert!(
10194            stop.finishing(),
10195            "a stop asked for mid-run has not landed until the run is settled"
10196        );
10197
10198        stop.busy.store(0, Ordering::SeqCst);
10199        assert!(
10200            !stop.finishing(),
10201            "once the run is settled the stop has landed and there is nothing to finish"
10202        );
10203    }
10204
10205    #[test]
10206    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10207        let stop = Stop::new();
10208        stop.busy.store(2, Ordering::SeqCst);
10209        stop.stop();
10210        assert!(stop.finishing(), "two runs still in flight");
10211
10212        stop.busy.store(1, Ordering::SeqCst);
10213        assert!(
10214            stop.finishing(),
10215            "one run finished, but a sibling is still working"
10216        );
10217
10218        stop.busy.store(0, Ordering::SeqCst);
10219        assert!(
10220            !stop.finishing(),
10221            "the last run out is what actually lands the stop"
10222        );
10223    }
10224
10225    #[tokio::test]
10226    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10227        let dir = tempfile::tempdir().unwrap();
10228        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10229        let stop = Stop::new();
10230        stop.stop();
10231
10232        let began = std::time::Instant::now();
10233        tokio::time::timeout(
10234            Duration::from_secs(2),
10235            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10236        )
10237        .await
10238        .expect("a stopped loop must return, not sit out its poll interval")
10239        .expect("the loop's own setup and teardown must not fail");
10240        assert!(
10241            began.elapsed() < opts.poll,
10242            "returned only after {:?}, which is a poll interval, not a stop",
10243            began.elapsed()
10244        );
10245    }
10246
10247    #[tokio::test]
10248    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10249        let dir = tempfile::tempdir().unwrap();
10250        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10251        let stop = Stop::new();
10252
10253        // Asked for after the loop is already parked on its empty queue, which
10254        // is the case an operator tapping stop on a phone actually hits.
10255        let asker = {
10256            let stop = stop.clone();
10257            tokio::spawn(async move {
10258                tokio::time::sleep(Duration::from_millis(20)).await;
10259                stop.stop();
10260            })
10261        };
10262
10263        let began = std::time::Instant::now();
10264        tokio::time::timeout(
10265            Duration::from_secs(2),
10266            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10267        )
10268        .await
10269        .expect("a stop asked for while idle must wake the wait")
10270        .expect("the loop's own setup and teardown must not fail");
10271        asker.await.unwrap();
10272        assert!(
10273            began.elapsed() < opts.poll,
10274            "returned only after {:?}, so the stop waited on the sleep",
10275            began.elapsed()
10276        );
10277    }
10278
10279    #[tokio::test]
10280    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10281        let dir = tempfile::tempdir().unwrap();
10282        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10283        let stop = Stop::new();
10284        stop.stop();
10285
10286        tokio::time::timeout(
10287            Duration::from_secs(2),
10288            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10289        )
10290        .await
10291        .expect("a stopped loop must return")
10292        .expect("the loop's own setup and teardown must not fail");
10293
10294        assert!(
10295            home.is_dir(),
10296            "the loop did publish a status file, so its removal is the teardown and not an absence"
10297        );
10298        assert!(
10299            !status_file.exists(),
10300            "a stopped loop clears its status file"
10301        );
10302        assert!(
10303            read_status(&home).is_none(),
10304            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10305        );
10306    }
10307
10308    #[tokio::test]
10309    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10310        let dir = tempfile::tempdir().unwrap();
10311        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10312
10313        let mut settled = RunState::new(
10314            dir.path().join("repo"),
10315            "main".to_owned(),
10316            "abc1234".to_owned(),
10317            "fixture".to_owned(),
10318            Config::default(),
10319        );
10320        settled.status = RunStatus::Ready;
10321        let run_dir = home.join("runs").join(&settled.id);
10322        std::fs::create_dir_all(&run_dir).unwrap();
10323        std::fs::write(
10324            run_dir.join("run.json"),
10325            serde_json::to_string_pretty(&settled).unwrap(),
10326        )
10327        .unwrap();
10328        let questions = Questions::at(home.join("questions"));
10329        let mut question = ask::Question::new(
10330            settled.id.clone(),
10331            "review".to_owned(),
10332            "reviewer-1".to_owned(),
10333            "Continue?".to_owned(),
10334            String::new(),
10335            Vec::new(),
10336        );
10337        questions.put(&mut question).unwrap();
10338
10339        run_service_worker(
10340            &home,
10341            serde_json::to_value(ServiceWorker {
10342                opts,
10343                queue: queue.root().to_path_buf(),
10344                worktrees_root: worktrees,
10345                operation: "housekeeping".to_owned(),
10346            })
10347            .unwrap(),
10348        )
10349        .await
10350        .unwrap();
10351
10352        assert_eq!(
10353            questions.get(&question.id).unwrap().status,
10354            ask::QuestionStatus::Abandoned,
10355            "the independent housekeeping worker settles ended-run questions"
10356        );
10357    }
10358
10359    #[test]
10360    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10361        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10362
10363        assert!(
10364            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10365            "never checked before: due at once"
10366        );
10367
10368        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10369        assert!(
10370            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10371            "well inside the interval: not due yet"
10372        );
10373
10374        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10375        assert!(
10376            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10377            "exactly at the edge: not yet due, same convention as `clean::due`"
10378        );
10379
10380        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10381        assert!(
10382            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10383            "past the interval: due again"
10384        );
10385    }
10386
10387    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10388    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10389    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10390    /// and the congestion test below both need, and must not drift apart.
10391    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10392        let config = dir.join("magi.toml");
10393        // A literal (single-quoted) TOML string, not a basic one: the cache
10394        // path is a Windows path full of backslashes, and a basic string
10395        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10396        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10397        // `{{ vars.cache }}` rendering documents.
10398        std::fs::write(
10399            &config,
10400            format!(
10401                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10402                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10403                cache_dir.display()
10404            ),
10405        )
10406        .unwrap();
10407        Opts {
10408            config: Some(config),
10409            repo: dir.join("repo"),
10410            ..Opts::default()
10411        }
10412    }
10413
10414    #[tokio::test]
10415    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10416        let dir = tempfile::tempdir().unwrap();
10417        let home = dir.path().join("home");
10418        let cache_dir = dir.path().join("cache");
10419        std::fs::create_dir_all(&cache_dir).unwrap();
10420        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10421        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10422
10423        // Nobody has asked this daemon to stop, which is the ordinary case;
10424        // the skip that a stop buys is asserted by its own test below.
10425        let running = Stop::new();
10426        let mut last_checked = None;
10427        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10428        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10429            .await;
10430        assert_eq!(
10431            crate::disk::dir_size(&cache_dir),
10432            0,
10433            "over the cap on the first check ever: pruned at once, no idle queue required"
10434        );
10435        assert_eq!(last_checked, Some(t0));
10436
10437        // A fresh oversized file lands, but the next check is not due yet.
10438        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10439        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10440        maybe_prune_cache_between_runs(
10441            &opts.repo,
10442            &opts,
10443            &home,
10444            &running,
10445            &mut last_checked,
10446            too_soon,
10447        )
10448        .await;
10449        assert_eq!(
10450            crate::disk::dir_size(&cache_dir),
10451            10,
10452            "too soon since the last check: left alone rather than rescanned every call"
10453        );
10454        assert_eq!(
10455            last_checked,
10456            Some(t0),
10457            "an idle check does not reset the clock"
10458        );
10459
10460        // Once the interval elapses, the same oversized cache is caught again.
10461        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10462        maybe_prune_cache_between_runs(
10463            &opts.repo,
10464            &opts,
10465            &home,
10466            &running,
10467            &mut last_checked,
10468            due_again,
10469        )
10470        .await;
10471        assert_eq!(
10472            crate::disk::dir_size(&cache_dir),
10473            0,
10474            "due again: pruned back under the cap"
10475        );
10476    }
10477
10478    /// A stop must not queue behind housekeeping. The prune below is a
10479    /// synchronous walk of the whole cache with no await point in it, so a
10480    /// loop that entered it could not get back to its own `stopped()` test
10481    /// until the walk finished - and because no run is in flight at this
10482    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10483    /// the stop had already landed. The idle branch has always made this same
10484    /// check before reaching `janitor`; the between-runs path makes it too.
10485    #[tokio::test]
10486    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10487        let dir = tempfile::tempdir().unwrap();
10488        let home = dir.path().join("home");
10489        let cache_dir = dir.path().join("cache");
10490        std::fs::create_dir_all(&cache_dir).unwrap();
10491        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10492        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10493
10494        let stop = Stop::new();
10495        stop.stop();
10496        assert!(
10497            !stop.finishing(),
10498            "no run is in flight at a between-runs boundary, so nothing else \
10499             would tell the operator this stop had not taken effect yet"
10500        );
10501
10502        let mut last_checked = None;
10503        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10504        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10505            .await;
10506        assert_eq!(
10507            crate::disk::dir_size(&cache_dir),
10508            10,
10509            "over its cap, and due for the first check ever, but a stop outranks \
10510             it: the cap is a standing policy the next start measures again"
10511        );
10512        assert_eq!(
10513            last_checked, None,
10514            "a check that never happened must not claim the interval"
10515        );
10516    }
10517
10518    /// A backlog must not starve cache pruning. The finite cache worker runs
10519    /// independently of queue drain and must not consume any task attempts.
10520    #[tokio::test]
10521    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10522        let dir = tempfile::tempdir().unwrap();
10523        let cache_dir = dir.path().join("cache");
10524        std::fs::create_dir_all(&cache_dir).unwrap();
10525        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10526
10527        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10528        opts.poll = Duration::from_millis(20);
10529        opts.max_attempts = 1_000;
10530
10531        let queue = Queue::at(dir.path().join("queue"));
10532        for i in 0..128 {
10533            let mut task = Task::new(
10534                format!("queued work {i}"),
10535                format!("queued work {i}"),
10536                opts.repo.clone(),
10537                Source::Human,
10538            );
10539            queue.put(&mut task).unwrap();
10540        }
10541
10542        let home = dir.path().join("home");
10543        let worktrees = dir.path().join("wt");
10544        run_service_worker(
10545            &home,
10546            serde_json::to_value(ServiceWorker {
10547                opts,
10548                queue: queue.root().to_path_buf(),
10549                worktrees_root: worktrees,
10550                operation: "cache".to_owned(),
10551            })
10552            .unwrap(),
10553        )
10554        .await
10555        .unwrap();
10556        let after = queue.list();
10557        assert_eq!(after.len(), 128);
10558        assert!(
10559            after
10560                .iter()
10561                .all(|task| task.status.runnable() && task.attempts == 0)
10562        );
10563
10564        assert_eq!(
10565            crate::disk::dir_size(&cache_dir),
10566            0,
10567            "an oversized cache must not be left to grow unboundedly just because the \
10568             queue kept the loop busy the whole time"
10569        );
10570    }
10571
10572    #[test]
10573    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10574        let dir = tempfile::tempdir().unwrap();
10575        let queue = Queue::at(dir.path().join("queue"));
10576        let questions = Questions::at(dir.path().join("questions"));
10577        let mut task = task();
10578        queue.put(&mut task).unwrap();
10579
10580        let mut task_question = ask::Question::new(
10581            task.id.clone(),
10582            crate::conduct::NODE.to_owned(),
10583            "conduct".to_owned(),
10584            "Which backend?".to_owned(),
10585            String::new(),
10586            Vec::new(),
10587        );
10588        questions.put(&mut task_question).unwrap();
10589        task.block(vec![task_question.id.clone()], None);
10590        queue.put(&mut task).unwrap();
10591
10592        let mut run_question = ask::Question::new(
10593            "20260101-000000-run1".to_owned(),
10594            "review".to_owned(),
10595            "reviewer-1".to_owned(),
10596            "Run question".to_owned(),
10597            String::new(),
10598            Vec::new(),
10599        );
10600        questions.put(&mut run_question).unwrap();
10601
10602        // A question from another node whose `run` happens to equal this
10603        // task's id — the same field, filled in for an unrelated reason. Only
10604        // `crate::conduct::NODE` questions use `run` as a task id; this one
10605        // must never be touched by this reconciliation, even after release.
10606        let mut coincidental = ask::Question::new(
10607            task.id.clone(),
10608            "review".to_owned(),
10609            "reviewer-1".to_owned(),
10610            "Unrelated review question".to_owned(),
10611            String::new(),
10612            Vec::new(),
10613        );
10614        questions.put(&mut coincidental).unwrap();
10615
10616        reconcile_task_questions(&queue, &questions);
10617        assert!(questions.get(&task_question.id).unwrap().status.open());
10618        assert!(questions.get(&run_question.id).unwrap().status.open());
10619        assert!(questions.get(&coincidental.id).unwrap().status.open());
10620
10621        task.release();
10622        queue.put(&mut task).unwrap();
10623        reconcile_task_questions(&queue, &questions);
10624        assert_eq!(
10625            questions.get(&task_question.id).unwrap().status,
10626            ask::QuestionStatus::Abandoned
10627        );
10628        assert!(
10629            questions.get(&run_question.id).unwrap().status.open(),
10630            "run questions remain the run janitor's responsibility"
10631        );
10632        assert!(
10633            questions.get(&coincidental.id).unwrap().status.open(),
10634            "a non-conductor question must not be abandoned just because its \
10635             run id coincides with a task id"
10636        );
10637    }
10638
10639    #[test]
10640    fn a_freshly_started_running_task_is_never_stalled() {
10641        let dir = tempfile::tempdir().unwrap();
10642        let mut t = task();
10643        t.start("run-1".to_owned());
10644        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10645        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10646        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10647    }
10648
10649    #[test]
10650    fn a_long_running_task_with_no_live_daemon_is_stalled() {
10651        let dir = tempfile::tempdir().unwrap();
10652        let mut t = task();
10653        t.start("run-1".to_owned());
10654        t.updated_at = Timestamp::now()
10655            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10656        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10657        assert_eq!(
10658            stalled_tasks(
10659                &Queue::at(dir.path().join("q")),
10660                dir.path(),
10661                Timestamp::now()
10662            )
10663            .len(),
10664            0,
10665            "the task was never written to this queue"
10666        );
10667    }
10668
10669    #[test]
10670    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10671        let dir = tempfile::tempdir().unwrap();
10672        let mut t = task();
10673        t.id = "20260903-080340-0167".to_owned();
10674        t.start("20260903-080619-01c2".to_owned());
10675        t.updated_at = Timestamp::now()
10676            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10677
10678        let mut status = Status::new();
10679        status.current = vec![Current {
10680            worker: None,
10681            task: t.id.clone(),
10682            run: "20260903-080619-01c2".to_owned(),
10683        }];
10684        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10685
10686        assert!(
10687            !is_stalled(&t, dir.path(), Timestamp::now()),
10688            "a live daemon's own heartbeat rules out stalled, however long the task has run"
10689        );
10690    }
10691
10692    /// Rewrite a task's `updated_at` on disk directly, bypassing
10693    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
10694    /// a fixture look like it has genuinely been `running` for a while.
10695    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10696        let path = queue.path_of(id);
10697        let body = std::fs::read_to_string(&path).unwrap();
10698        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10699        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10700        v["updated_at"] = serde_json::Value::String(old.to_string());
10701        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10702    }
10703
10704    #[test]
10705    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10706        // The realistic `poll()` ordering, not `is_stalled` in isolation:
10707        // `reclaim_orphaned_running` runs first, on every poll, and settles
10708        // any `running` task whose claim it can actually take. For most
10709        // crashes that is immediate - a dead pid is proof enough for
10710        // `sweep_stale_claims` to drop the lock the same tick, and the very
10711        // next claim attempt succeeds. But a lock whose pid cannot be parsed
10712        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
10713        // `sweep_stale_claims`'s own doc), so the lock - and the claim
10714        // failure behind it - can legitimately outlive many polls. This is
10715        // exactly the gap `stalled_tasks` exists to surface well before that
10716        // six-hour sweep would: reclaim leaves the task `running`, and it
10717        // must still reach the conductor as stalled.
10718        let dir = tempfile::tempdir().unwrap();
10719        let queue = Queue::at(dir.path().join("queue"));
10720        let home = dir.path().join("home");
10721
10722        let mut t = task();
10723        t.id = "20260101-000001-lock".to_owned();
10724        t.start("run-1".to_owned());
10725        queue.put(&mut t).unwrap();
10726        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10727        std::fs::write(
10728            dir.path().join("queue").join(format!("{}.lock", t.id)),
10729            "not a pid",
10730        )
10731        .unwrap();
10732
10733        let now = Timestamp::now();
10734        assert!(
10735            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10736            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10737             and reclaim must leave the task alone"
10738        );
10739        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10740
10741        let stalled = stalled_tasks(&queue, &home, now);
10742        assert_eq!(
10743            stalled.len(),
10744            1,
10745            "reclaim's inability to claim it yet must not hide it from the conductor"
10746        );
10747        assert_eq!(stalled[0].id, t.id);
10748    }
10749
10750    #[test]
10751    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10752        let dir = tempfile::tempdir().unwrap();
10753        crate::run::set_home(dir.path().join("run-home"));
10754        let queue = Queue::at(dir.path().join("queue"));
10755        let home = dir.path().join("home");
10756        let questions = Questions::at(dir.path().join("questions"));
10757
10758        let mut t = task();
10759        t.id = "20260101-000003-dead".to_owned();
10760        t.start("missing-run".to_owned());
10761        queue.put(&mut t).unwrap();
10762        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10763
10764        // This is the real poll ordering: retain the deterministic stalled
10765        // input before a claim proves the owner is gone and reclaims it.
10766        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10767        assert_eq!(
10768            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10769            [&t.id]
10770        );
10771        assert_eq!(
10772            reclaim_orphaned_running(&queue, 2, &Default::default()),
10773            [t.id.clone()]
10774        );
10775        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10776
10777        // Reclaim drops its guard before conductor decisions are applied, so
10778        // the decision for the captured stalled input has a real write path.
10779        crate::conduct::apply(
10780            &queue,
10781            &questions,
10782            &crate::conduct::Verdict {
10783                decisions: vec![crate::conduct::Decision {
10784                    id: t.id.clone(),
10785                    recovery: Some(crate::conduct::Recovery::Requeue),
10786                    ..crate::conduct::Decision::default()
10787                }],
10788            },
10789        )
10790        .unwrap();
10791        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10792    }
10793
10794    #[test]
10795    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10796        let dir = tempfile::tempdir().unwrap();
10797        let queue = Queue::at(dir.path().join("queue"));
10798        let home = dir.path().join("home");
10799
10800        let mut fresh = task();
10801        fresh.id = "20260101-000001-aaaa".to_owned();
10802        fresh.start("run-1".to_owned());
10803        queue.put(&mut fresh).unwrap();
10804
10805        let mut old = task();
10806        old.id = "20260101-000002-bbbb".to_owned();
10807        old.start("run-2".to_owned());
10808        queue.put(&mut old).unwrap();
10809        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10810
10811        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10812        assert_eq!(stalled.len(), 1);
10813        assert_eq!(stalled[0].id, old.id);
10814    }
10815
10816    #[test]
10817    fn queued_and_finished_task_views_partition_by_status() {
10818        let dir = tempfile::tempdir().unwrap();
10819        let queue = Queue::at(dir.path().join("queue"));
10820
10821        let mut queued = task();
10822        queued.id = "20260101-000001-aaaa".to_owned();
10823        queue.put(&mut queued).unwrap();
10824
10825        let mut failed = task();
10826        failed.id = "20260101-000002-bbbb".to_owned();
10827        failed.start("run-1".to_owned());
10828        failed.fail("gate red", 5);
10829        queue.put(&mut failed).unwrap();
10830
10831        let mut held = task();
10832        held.id = "20260101-000003-cccc".to_owned();
10833        held.hold_machine(None);
10834        queue.put(&mut held).unwrap();
10835
10836        let mut running = task();
10837        running.id = "20260101-000004-dddd".to_owned();
10838        running.start("run-2".to_owned());
10839        queue.put(&mut running).unwrap();
10840
10841        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
10842        assert_eq!(queued_ids, [queued.id.clone()]);
10843
10844        let mut finished_ids: Vec<String> =
10845            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
10846        finished_ids.sort_unstable();
10847        let mut want = vec![failed.id.clone(), held.id.clone()];
10848        want.sort_unstable();
10849        assert_eq!(finished_ids, want);
10850    }
10851
10852    #[test]
10853    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
10854        for short in [false, true] {
10855            let dir = tempfile::tempdir().unwrap();
10856            let queue = Queue::at(dir.path().join("queue"));
10857            let questions = ask::Questions::at(dir.path().join("questions"));
10858            let mut running = task();
10859            running.id = "20261013-192213-feb2".into();
10860            running.start("existing-run".into());
10861            queue.put(&mut running).unwrap();
10862            let mut middle = task();
10863            middle.id = "20261013-193611-ca5b".into();
10864            middle.block(
10865                vec![if short {
10866                    "feb2".into()
10867                } else {
10868                    running.id.clone()
10869                }],
10870                None,
10871            );
10872            queue.put(&mut middle).unwrap();
10873            let mut waiting = task();
10874            waiting.id = "20261013-202849-ee37".into();
10875            waiting.block(
10876                vec![if short {
10877                    "ca5b".into()
10878                } else {
10879                    middle.id.clone()
10880                }],
10881                Some("wait for implementation".into()),
10882            );
10883            queue.put(&mut waiting).unwrap();
10884            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
10885            let inv = crate::blockers::Inventory::load(&queue, &questions);
10886            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
10887            assert!(inv.stuck().is_empty());
10888            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10889            assert!(report.quarantined.is_empty());
10890            assert!(report.asked.is_empty());
10891            resolve_blockers(&queue, &questions);
10892            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10893            assert!(questions.list().is_empty());
10894            // Finishing the transitive prerequisite alone does not satisfy
10895            // the task's direct dependency.
10896            running.succeed();
10897            queue.put(&mut running).unwrap();
10898            resolve_blockers(&queue, &questions);
10899            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
10900            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10901            middle = queue.get(&middle.id).unwrap();
10902            middle.succeed();
10903            queue.put(&mut middle).unwrap();
10904            resolve_blockers(&queue, &questions);
10905            let after = queue.get(&waiting.id).unwrap();
10906            assert_eq!(after.status, TaskStatus::Queued);
10907            assert!(after.blocked_by.is_empty());
10908            assert_eq!(after.instruction, waiting.instruction);
10909        }
10910    }
10911
10912    #[test]
10913    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
10914        for future_schema in [false, true] {
10915            let name = "20261013-193611-ca5b";
10916            let mut future = task();
10917            future.id = name.into();
10918            future.schema = crate::queue::SCHEMA + 1;
10919            let contents = if future_schema {
10920                serde_json::to_string(&future).unwrap()
10921            } else {
10922                "corrupt".into()
10923            };
10924            let dir = tempfile::tempdir().unwrap();
10925            let queue = Queue::at(dir.path().join("queue"));
10926            let questions = ask::Questions::at(dir.path().join("questions"));
10927            let mut waiting = task();
10928            waiting.id = "20261013-202849-ee37".into();
10929            waiting.block(vec!["ca5b".into()], None);
10930            queue.put(&mut waiting).unwrap();
10931            std::fs::write(queue.path_of(name), contents).unwrap();
10932            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
10933            assert!(
10934                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
10935            );
10936            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10937            assert!(report.asked.is_empty());
10938            resolve_blockers(&queue, &questions);
10939            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10940            assert!(questions.list().is_empty());
10941        }
10942        let dir = tempfile::tempdir().unwrap();
10943        let queue = Queue::at(dir.path().join("queue"));
10944        let questions = ask::Questions::at(dir.path().join("questions"));
10945        let mut waiting = task();
10946        waiting.id = "20261013-202849-ee37".into();
10947        waiting.block(vec!["ca5b".into()], None);
10948        queue.put(&mut waiting).unwrap();
10949        let mut done = task();
10950        done.id = "20261013-193611-ca5b".into();
10951        done.succeed();
10952        queue.put(&mut done).unwrap();
10953        // An unreadable second match must not disappear from uniqueness
10954        // checks just because Queue::list skips it.
10955        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
10956        assert!(queue.get("ca5b").is_err());
10957        assert_eq!(
10958            crate::queue::dependency(&queue, &questions, "ca5b"),
10959            crate::queue::Dependency::Ambiguous
10960        );
10961        resolve_blockers(&queue, &questions);
10962        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10963        assert!(report.asked.is_empty());
10964        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10965        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
10966    }
10967
10968    #[test]
10969    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
10970        for held in [false, true] {
10971            for question in [false, true] {
10972                for reference in ["ca5b", "20261013-193611-ca5b"] {
10973                    let dir = tempfile::tempdir().unwrap();
10974                    let queue = Queue::at(dir.path().join("queue"));
10975                    let questions = ask::Questions::at(dir.path().join("questions"));
10976                    let mut prerequisite = task();
10977                    prerequisite.id = "20261013-193611-ca5b".into();
10978                    prerequisite.start("existing-run".into());
10979                    queue.put(&mut prerequisite).unwrap();
10980                    let mut waiting = task();
10981                    waiting.id = "20261013-202849-ee37".into();
10982                    if held {
10983                        waiting.hold_machine(Some("waiting for separate consent".into()));
10984                    }
10985                    queue.put(&mut waiting).unwrap();
10986                    let reason = "Deleting saved data requires separate owner consent";
10987                    crate::conduct::apply(
10988                        &queue,
10989                        &questions,
10990                        &crate::conduct::Verdict {
10991                            decisions: vec![crate::conduct::Decision {
10992                                id: waiting.id.clone(),
10993                                blocked_by: vec![reference.into()],
10994                                question: question.then(|| "May the saved data be deleted?".into()),
10995                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
10996                                reason: Some(reason.into()),
10997                                ..crate::conduct::Decision::default()
10998                            }],
10999                        },
11000                    )
11001                    .unwrap();
11002                    let before = queue.get(&waiting.id).unwrap();
11003                    if question {
11004                        assert_eq!(before.status, TaskStatus::Blocked);
11005                        let q = questions.get(&before.blocked_by[0]).unwrap();
11006                        assert_eq!(q.summary, "May the saved data be deleted?");
11007                        assert!(q.status.open());
11008                    } else {
11009                        assert_eq!(before.status, TaskStatus::Held);
11010                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11011                        assert!(recorded_reason.starts_with(reason));
11012                        if held {
11013                            assert!(recorded_reason.contains("waiting for separate consent"));
11014                        }
11015                    }
11016                    prerequisite.succeed();
11017                    queue.put(&mut prerequisite).unwrap();
11018                    resolve_blockers(&queue, &questions);
11019                    let after = queue.get(&waiting.id).unwrap();
11020                    assert_eq!(after.status, before.status);
11021                    assert_eq!(after.blocked_by, before.blocked_by);
11022                    assert_eq!(after.hold_reason, before.hold_reason);
11023                    assert_eq!(after.instruction, waiting.instruction);
11024                    if question {
11025                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11026                    }
11027                    assert!(
11028                        queue.next_runnable().is_none(),
11029                        "dependency completion is not consent"
11030                    );
11031                }
11032            }
11033        }
11034    }
11035
11036    #[test]
11037    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11038        let dir = tempfile::tempdir().unwrap();
11039        let queue = Queue::at(dir.path().join("queue"));
11040        let questions = ask::Questions::at(dir.path().join("questions"));
11041
11042        let mut dep = task();
11043        dep.id = "20260101-000001-dep0".to_owned();
11044        dep.succeed();
11045        queue.put(&mut dep).unwrap();
11046
11047        let mut still_going = task();
11048        still_going.id = "20260101-000002-dep1".to_owned();
11049        queue.put(&mut still_going).unwrap();
11050
11051        let mut blocked = task();
11052        blocked.id = "20260101-000003-main".to_owned();
11053        blocked.block(
11054            vec![dep.id.clone(), still_going.id.clone()],
11055            Some("waits on both".to_owned()),
11056        );
11057        queue.put(&mut blocked).unwrap();
11058
11059        resolve_blockers(&queue, &questions);
11060
11061        let after = queue.get(&blocked.id).unwrap();
11062        assert_eq!(
11063            after.status,
11064            TaskStatus::Blocked,
11065            "one dependency is still outstanding"
11066        );
11067        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11068    }
11069
11070    #[test]
11071    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11072        let dir = tempfile::tempdir().unwrap();
11073        let queue = Queue::at(dir.path().join("queue"));
11074        let questions = ask::Questions::at(dir.path().join("questions"));
11075
11076        let mut q = crate::ask::Question::new(
11077            "20260101-000001-main".to_owned(),
11078            crate::conduct::NODE.to_owned(),
11079            "conduct".to_owned(),
11080            "Which backend?".to_owned(),
11081            String::new(),
11082            Vec::new(),
11083        );
11084        questions.put(&mut q).unwrap();
11085        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11086            .unwrap();
11087        questions.put(&mut q).unwrap();
11088
11089        let mut blocked = task();
11090        blocked.id = "20260101-000001-main".to_owned();
11091        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11092        queue.put(&mut blocked).unwrap();
11093
11094        resolve_blockers(&queue, &questions);
11095
11096        let after = queue.get(&blocked.id).unwrap();
11097        assert_eq!(
11098            after.status,
11099            TaskStatus::Queued,
11100            "the only blocker resolved"
11101        );
11102        assert_eq!(after.answers.len(), 1);
11103        assert_eq!(after.answers[0].question, "Which backend?");
11104        assert_eq!(after.answers[0].answer, "SQLite");
11105
11106        // And the run this task starts next is told about it.
11107        let instruction = instruction_for(&after);
11108        assert!(instruction.contains("Which backend?"));
11109        assert!(instruction.contains("SQLite"));
11110    }
11111
11112    #[test]
11113    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11114        let dir = tempfile::tempdir().unwrap();
11115        let queue = Queue::at(dir.path().join("queue"));
11116        let questions = ask::Questions::at(dir.path().join("questions"));
11117
11118        let mut q = crate::ask::Question::new(
11119            "20260101-000001-main".to_owned(),
11120            crate::conduct::NODE.to_owned(),
11121            "conduct".to_owned(),
11122            "Is the setup done?".to_owned(),
11123            String::new(),
11124            Vec::new(),
11125        );
11126        q.abandon("no answer within 60s of asking");
11127        questions.put(&mut q).unwrap();
11128
11129        let mut blocked = task();
11130        blocked.id = "20260101-000001-main".to_owned();
11131        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11132        queue.put(&mut blocked).unwrap();
11133
11134        resolve_blockers(&queue, &questions);
11135
11136        let after = queue.get(&blocked.id).unwrap();
11137        assert_eq!(
11138            after.status,
11139            TaskStatus::Held,
11140            "never left blocked on nothing"
11141        );
11142        assert!(!after.operator_held(), "a machine hold, for triage");
11143        assert!(
11144            after
11145                .hold_reason
11146                .as_deref()
11147                .unwrap_or_default()
11148                .contains("went unanswered")
11149        );
11150    }
11151
11152    #[test]
11153    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11154        // Reproduces the reported bug (task 3958): a task held out of
11155        // attempts, blocked on a `crate::conduct` follow-up question, must
11156        // come back `held` once that question is answered - never `queued`,
11157        // whatever the answer said - or it silently re-enters the
11158        // competition queue with its attempts already exhausted.
11159        let dir = tempfile::tempdir().unwrap();
11160        let queue = Queue::at(dir.path().join("queue"));
11161        let questions = ask::Questions::at(dir.path().join("questions"));
11162
11163        let mut q = crate::ask::Question::new(
11164            "20260101-000001-main".to_owned(),
11165            crate::conduct::NODE.to_owned(),
11166            "conduct".to_owned(),
11167            "How should this be handled?".to_owned(),
11168            String::new(),
11169            Vec::new(),
11170        );
11171        questions.put(&mut q).unwrap();
11172        q.answer(crate::ask::Answer::Text(
11173            "leave it held, a human will look at it later".to_owned(),
11174        ))
11175        .unwrap();
11176        questions.put(&mut q).unwrap();
11177
11178        let mut held = task();
11179        held.id = "20260101-000001-main".to_owned();
11180        held.hold_machine(Some("out of attempts".to_owned()));
11181        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11182        queue.put(&mut held).unwrap();
11183
11184        resolve_blockers(&queue, &questions);
11185
11186        let after = queue.get(&held.id).unwrap();
11187        assert_eq!(after.status, TaskStatus::Held);
11188        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11189        assert_eq!(
11190            after.answers[0].answer,
11191            "leave it held, a human will look at it later"
11192        );
11193    }
11194
11195    #[test]
11196    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11197        let dir = tempfile::tempdir().unwrap();
11198        let queue = Queue::at(dir.path().join("queue"));
11199        let questions = ask::Questions::at(dir.path().join("questions"));
11200        let mut dep = task();
11201        dep.id = "20260101-000001-gone".to_owned();
11202        queue.put(&mut dep).unwrap();
11203        let mut blocked = task();
11204        blocked.id = "20260101-000003-main".to_owned();
11205        blocked.block(vec![dep.id.clone()], None);
11206        queue.put(&mut blocked).unwrap();
11207
11208        // Claimed, so `remove` cannot rewrite it and the resolver must.
11209        let claim = queue.claim(&blocked.id).unwrap();
11210        queue.remove(&dep.id, false, &questions).unwrap();
11211        drop(claim);
11212        resolve_blockers(&queue, &questions);
11213
11214        let after = queue.get(&blocked.id).unwrap();
11215        assert_eq!(after.status, TaskStatus::Queued);
11216        assert!(after.blocked_by.is_empty());
11217    }
11218
11219    #[test]
11220    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11221        // Reproduces the reported bug: a task blocked on a task id that was
11222        // removed (`magi task rm`, or deleted by hand) can never see that id
11223        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11224        // would otherwise leave the task `blocked` forever with no way for an
11225        // operator to find out why.
11226        let dir = tempfile::tempdir().unwrap();
11227        let queue = Queue::at(dir.path().join("queue"));
11228        let questions = ask::Questions::at(dir.path().join("questions"));
11229
11230        let mut still_going = task();
11231        still_going.id = "20260101-000002-dep1".to_owned();
11232        queue.put(&mut still_going).unwrap();
11233
11234        let mut blocked = task();
11235        blocked.id = "20260101-000003-main".to_owned();
11236        blocked.block(
11237            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11238            Some("waits on both".to_owned()),
11239        );
11240        queue.put(&mut blocked).unwrap();
11241
11242        resolve_blockers(&queue, &questions);
11243
11244        let after = queue.get(&blocked.id).unwrap();
11245        assert_eq!(
11246            after.status,
11247            TaskStatus::Held,
11248            "a missing dependency must not leave the task blocked forever"
11249        );
11250        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11251        assert!(after.blocked_by.is_empty());
11252        let reason = after.hold_reason.as_deref().unwrap_or_default();
11253        assert!(
11254            reason.contains("20260101-000001-gone"),
11255            "the missing id must be named so an operator can tell what happened: {reason}"
11256        );
11257        assert!(
11258            reason.contains(&still_going.id),
11259            "the still-valid dependency must not silently vanish from the record: {reason}"
11260        );
11261    }
11262
11263    #[test]
11264    fn instruction_for_is_unchanged_without_any_answers() {
11265        let t = task();
11266        assert_eq!(instruction_for(&t), t.instruction);
11267    }
11268
11269    #[test]
11270    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11271        let dir = tempfile::tempdir().unwrap();
11272        let q = Queue::at(dir.path().join("queue"));
11273        let src = dir.path().join("shot.png");
11274        std::fs::write(&src, "x").unwrap();
11275        let mut t = task();
11276        q.attach(&mut t, &[src]).unwrap();
11277        let paths = task_attachments(&q, &t).unwrap();
11278        assert_eq!(paths.len(), 1);
11279        assert!(paths[0].is_absolute() && paths[0].is_file());
11280        std::fs::remove_file(&paths[0]).unwrap();
11281        let err = task_attachments(&q, &t).unwrap_err().to_string();
11282        assert!(err.contains("shot.png"), "{err}");
11283    }
11284
11285    #[tokio::test]
11286    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11287        let dir = tempfile::tempdir().unwrap();
11288        let queue_path = dir.path().join("queue");
11289        let queue = Queue::at(queue_path.clone());
11290        let mut t = task();
11291        t.source = Source::Agent {
11292            run: "originating-chat".into(),
11293            node: crate::queue::CHAT_NODE.into(),
11294        };
11295        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11296            stage: "config-fetch",
11297            target: "origin/main".into(),
11298        });
11299        record_config_failure(&mut t, &fetch);
11300        t.hold_machine(Some(format!("{fetch:#}")));
11301        let fetch_key = t.chat_notice_due().unwrap();
11302        t.chat_notices.push(fetch_key.clone());
11303        queue.put(&mut t).unwrap();
11304
11305        let queue = Queue::at(queue_path);
11306        let mut t = queue.get(&t.id).unwrap();
11307        let a = dir.path().join("a.toml");
11308        let b = dir.path().join("b.toml");
11309        for (path, text, new_cause) in [
11310            (&a, "[graph", true),
11311            (&a, "[verify", false),
11312            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11313            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11314        ] {
11315            t.release_operator("test", None);
11316            std::fs::write(path, text).unwrap();
11317            let error = Config::discover_fetched(dir.path(), Some(path))
11318                .await
11319                .unwrap_err();
11320            record_config_failure(&mut t, &error);
11321            t.hold_machine(Some(format!("{error:#}")));
11322            let due = t.chat_notice_due();
11323            assert_eq!(due.is_some(), new_cause, "{error:#}");
11324            if let Some(key) = due {
11325                assert_ne!(key, fetch_key);
11326                t.chat_notices.push(key);
11327            }
11328        }
11329        t.succeed();
11330        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11331    }
11332
11333    #[test]
11334    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11335        let dir = tempfile::tempdir().unwrap();
11336        let queue_path = dir.path().join("queue");
11337        let queue = Queue::at(queue_path.clone());
11338        let mut t = task();
11339        t.source = crate::queue::Source::Agent {
11340            run: "originating-chat".into(),
11341            node: crate::queue::CHAT_NODE.into(),
11342        };
11343        let a = dir.path().join("a.png");
11344        let b = dir.path().join("b.png");
11345        std::fs::write(&a, "a").unwrap();
11346        std::fs::write(&b, "b").unwrap();
11347        queue.attach(&mut t, &[a, b]).unwrap();
11348        let paths = task_attachments(&queue, &t).unwrap();
11349        for path in &paths {
11350            std::fs::remove_file(path).unwrap();
11351        }
11352        let missing = task_attachments(&queue, &t).unwrap_err();
11353        t.attempts += 1;
11354        let reason = missing.to_string();
11355        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11356        let first = t.chat_notice_due().expect("first attachment notice");
11357        t.chat_notices.push(first.clone());
11358        queue.put(&mut t).unwrap();
11359
11360        let queue = Queue::at(queue_path.clone());
11361        let mut t = queue.get(&t.id).unwrap();
11362        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11363        t.release_operator("test", None);
11364        t.attempts += 1;
11365        let missing = task_attachments(&queue, &t).unwrap_err();
11366        t.fail_startup_target(
11367            "startup-attachments",
11368            missing.name,
11369            "same missing attachment with regenerated wording",
11370            1,
11371        );
11372        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11373
11374        std::fs::write(&paths[0], "restored").unwrap();
11375        t.release_operator("test", None);
11376        t.attempts += 1;
11377        let missing = task_attachments(&queue, &t).unwrap_err();
11378        let reason = missing.to_string();
11379        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11380        let second = t
11381            .chat_notice_due()
11382            .expect("different attachment must notify");
11383        assert_ne!(first, second);
11384        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11385    }
11386
11387    #[test]
11388    fn resumed_instruction_is_unchanged_without_any_answers() {
11389        let t = task();
11390        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11391    }
11392
11393    #[test]
11394    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11395        let mut t = task();
11396        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11397        // The run's own instruction on disk predates the answer: it is the
11398        // plain original text `Runner::start` saved before the operator was
11399        // ever asked anything.
11400        let old = t.instruction.clone();
11401
11402        let refreshed = resumed_instruction(&old, &t);
11403        assert!(refreshed.starts_with(&old), "the original text is kept");
11404        assert!(refreshed.contains("Which backend?"));
11405        assert!(refreshed.contains("SQLite"));
11406    }
11407
11408    #[test]
11409    fn resumed_instruction_keeps_an_original_answers_heading() {
11410        let mut t = task();
11411        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11412        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11413
11414        let refreshed = resumed_instruction(&t.instruction, &t);
11415
11416        assert!(
11417            refreshed.starts_with(&t.instruction),
11418            "an answers heading in the original instruction is not the appended block"
11419        );
11420        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11421        assert!(refreshed.contains("Which backend?"));
11422        assert!(refreshed.contains("SQLite"));
11423
11424        let repeated = resumed_instruction(&refreshed, &t);
11425        assert_eq!(
11426            repeated, refreshed,
11427            "only the final appended block is refreshed"
11428        );
11429    }
11430
11431    #[test]
11432    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11433        let mut t = task();
11434        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11435
11436        // A first resume appends the block; a second resume of the same run,
11437        // with no new answer in between, must reproduce exactly the same
11438        // text rather than appending the block a second time.
11439        let once = resumed_instruction(&t.instruction, &t);
11440        let twice = resumed_instruction(&once, &t);
11441        assert_eq!(once, twice);
11442        assert_eq!(once.matches("Which backend?").count(), 1);
11443
11444        // A later answer replaces the block wholesale rather than growing it.
11445        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11446        let refreshed = resumed_instruction(&once, &t);
11447        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11448        assert!(refreshed.contains("Which backend?"));
11449        assert!(refreshed.contains("Which cache?"));
11450    }
11451
11452    #[test]
11453    fn prepare_instruction_covers_all_three_starters() {
11454        let mut t = task();
11455        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11456
11457        // Start: a fresh run gets the task text plus every answer so far —
11458        // exactly `instruction_for`.
11459        assert_eq!(
11460            prepare_instruction(&Starter::Start, None, &t),
11461            Some(instruction_for(&t))
11462        );
11463
11464        // Resume: the run's prior instruction is refreshed with the answer,
11465        // not discarded and not left stale.
11466        let old = t.instruction.clone();
11467        assert_eq!(
11468            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11469            Some(resumed_instruction(&old, &t))
11470        );
11471
11472        // Review: a review-only pass builds its own instruction from the
11473        // branch's history in `crate::graph`, with no task statement at all -
11474        // this boundary must leave it alone.
11475        assert_eq!(
11476            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11477            None
11478        );
11479    }
11480
11481    #[test]
11482    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11483        assert_eq!(
11484            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11485            Starter::Review("magi/eba2/A".to_owned())
11486        );
11487    }
11488
11489    #[test]
11490    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11491        assert_eq!(
11492            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11493            Starter::Start,
11494            "a vanished review branch must not fall back to resuming the old run either"
11495        );
11496    }
11497
11498    #[test]
11499    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11500        let mut t = task();
11501        t.start("old-run".to_owned());
11502        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11503        t.release();
11504        let branch = t.review_branch.take();
11505        assert_eq!(
11506            choose_starter(branch.as_deref(), true, Some("old-run")),
11507            Starter::Review("magi/eba2/A".to_owned()),
11508            "a review wins over resuming the old run"
11509        );
11510    }
11511
11512    #[test]
11513    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11514        assert_eq!(
11515            choose_starter(None, false, Some("some-run")),
11516            Starter::Resume("some-run".to_owned())
11517        );
11518        assert_eq!(choose_starter(None, false, None), Starter::Start);
11519    }
11520
11521    #[test]
11522    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11523        let mut released = task();
11524        released.start("stalled-run".to_owned());
11525        released.requeue();
11526        let unfinished = (!released.fresh_start)
11527            .then(|| Some("stalled-run".to_owned()))
11528            .flatten();
11529        assert_eq!(
11530            choose_starter(None, false, unfinished.as_deref()),
11531            Starter::Start,
11532            "release keeps run history but must not resume it"
11533        );
11534        assert_eq!(released.runs, ["stalled-run"]);
11535    }
11536
11537    fn stopped_public_run(status: RunStatus) -> RunState {
11538        let mut state = run_state(status);
11539        state.driver_exited = true;
11540        state.config.graph.land = true;
11541        state.config.graph.review_rounds = 1;
11542        state.reviews = vec![review_round(1)];
11543        state.merge = Some(crate::run::MergeOutcome {
11544            mode: MergeMode::Pr,
11545            ok: false,
11546            detail: "landing stopped".into(),
11547            empty: false,
11548        });
11549        state.pr = Some(crate::run::PrRecord {
11550            url: "https://example.test/pull/1".into(),
11551            number: 1,
11552            state: "open".into(),
11553            checks: "red".into(),
11554            round: 1,
11555            rounds: 1,
11556            red_at_merge: Vec::new(),
11557        });
11558        state
11559    }
11560
11561    #[test]
11562    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11563        for status in [RunStatus::Blocked, RunStatus::Gating] {
11564            let home = tempfile::tempdir().unwrap();
11565            let mut state = stopped_public_run(status);
11566            state.save_under(home.path()).unwrap();
11567            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11568            assert!(!exhausted_review_budget(&state));
11569            let mut task = held_task_with(&state.id);
11570            task.release();
11571            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11572            assert_eq!(
11573                choose_starter(None, false, unfinished.as_deref()),
11574                Starter::Resume(state.id.clone())
11575            );
11576            let question = action_question(&state.id, resume_action(&state.id));
11577            assert_eq!(
11578                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11579                ActionDecision::Resume(state.id.clone())
11580            );
11581            // The control-plane command uses this same preflight before pinning.
11582            assert_eq!(
11583                crate::resume::validate(home.path(), &state.id).unwrap().id,
11584                state.id
11585            );
11586            let queue = Queue::at(home.path().join("queue"));
11587            let mut controlled = Task::new(
11588                "resume land".into(),
11589                state.instruction.clone(),
11590                state.repo.clone(),
11591                Source::Agent {
11592                    run: "talk".into(),
11593                    node: crate::queue::CHAT_NODE.into(),
11594                },
11595            );
11596            controlled.runs.push(state.id.clone());
11597            controlled.hold_machine(Some("land stopped".into()));
11598            queue.put(&mut controlled).unwrap();
11599            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11600            assert_eq!(resumed.status, TaskStatus::Queued);
11601            assert_eq!(
11602                resumed.resume_override.unwrap().pinned_run,
11603                Some(state.id.clone())
11604            );
11605            assert_eq!(resumed.attempts, 0);
11606        }
11607    }
11608
11609    #[test]
11610    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11611        for review_rounds in [0, 1] {
11612            let home = tempfile::tempdir().unwrap();
11613            let mut state = run_state(RunStatus::Blocked);
11614            state.config.graph.review_rounds = review_rounds;
11615            if review_rounds > 0 {
11616                let mut review = review_round(1);
11617                review.clean = true;
11618                state.reviews = vec![review];
11619            }
11620            state.gate_ran = true;
11621            state.gate = vec![crate::run::CommandOutcome {
11622                command: "verify".into(),
11623                code: Some(1),
11624                output_tail: "gate failed after repair budget exhausted".into(),
11625                duration_ms: 0,
11626                resource_blocked: false,
11627            }];
11628            state.save_under(home.path()).unwrap();
11629            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11630            assert!(exhausted_review_budget(&state));
11631            let mut task = held_task_with(&state.id);
11632            task.release();
11633            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11634            let question = action_question(&state.id, resume_action(&state.id));
11635            assert_ne!(
11636                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11637                ActionDecision::Resume(state.id.clone())
11638            );
11639            let error = crate::resume::validate(home.path(), &state.id)
11640                .unwrap_err()
11641                .to_string();
11642            assert!(!error.contains("review budget exhausted"), "{error}");
11643            assert!(
11644                error.contains(if review_rounds == 0 {
11645                    "review is disabled"
11646                } else {
11647                    "gate already ran"
11648                }),
11649                "{error}"
11650            );
11651
11652            // An unexecuted gate still has work to do with or without reviews.
11653            state.gate_ran = false;
11654            state.gate.clear();
11655            assert!(!exhausted_review_budget(&state));
11656            assert_eq!(
11657                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11658                Some(state.id)
11659            );
11660        }
11661    }
11662
11663    #[test]
11664    fn resource_blocked_verification_resumes_the_same_run() {
11665        for (kind, stage) in [
11666            ("cache", "clean"),
11667            ("coordination", "clean"),
11668            ("cache", "review-e2e"),
11669            ("coordination", "no-reviews"),
11670            ("coordination", "handoff"),
11671        ] {
11672            let home = tempfile::tempdir().unwrap();
11673            let mut state = run_state(RunStatus::Blocked);
11674            state.config.graph.review_rounds = 1;
11675            let mut review = review_round(1);
11676            review.clean = true;
11677            state.reviews = vec![review];
11678            if stage == "review-e2e" {
11679                let review = &mut state.reviews[0];
11680                review.clean = false;
11681                review.blocking = 1;
11682                review.e2e = vec![crate::run::CommandOutcome {
11683                    command: "verify".into(),
11684                    code: None,
11685                    output_tail: "resource wait expired".into(),
11686                    duration_ms: 0,
11687                    resource_blocked: true,
11688                }];
11689            } else if stage == "no-reviews" {
11690                state.config.graph.review_rounds = 0;
11691                state.reviews.clear();
11692            } else if stage == "handoff" {
11693                // A completed final verification can hand off to the gate
11694                // even when the review still carries contested findings.
11695                let review = &mut state.reviews[0];
11696                review.clean = false;
11697                review.blocking = 1;
11698                review.e2e = vec![crate::run::CommandOutcome {
11699                    command: "verify".into(),
11700                    code: Some(0),
11701                    output_tail: String::new(),
11702                    duration_ms: 0,
11703                    resource_blocked: false,
11704                }];
11705            }
11706            state.gate_ran = false;
11707            state.resource_block = Some(crate::run::ResourceBlock {
11708                cause: crate::run::ResourceBlockCause::Other,
11709                node: if stage == "review-e2e" {
11710                    "review"
11711                } else {
11712                    "gate"
11713                }
11714                .into(),
11715                kind: kind.into(),
11716                detail: "resource wait expired".into(),
11717                at: jiff::Timestamp::now(),
11718            });
11719            state.save_under(home.path()).unwrap();
11720            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11721            assert!(!exhausted_review_budget(&state));
11722            let mut task = held_task_with(&state.id);
11723            task.release();
11724            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11725            assert_eq!(
11726                choose_starter(None, false, unfinished.as_deref()),
11727                Starter::Resume(state.id.clone())
11728            );
11729            let question = action_question(&state.id, resume_action(&state.id));
11730            assert_eq!(
11731                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11732                ActionDecision::Resume(state.id.clone())
11733            );
11734            assert_eq!(
11735                crate::resume::validate(home.path(), &state.id).unwrap().id,
11736                state.id
11737            );
11738            let queue = Queue::at(home.path().join("queue"));
11739            let mut controlled = Task::new(
11740                "resume verification".into(),
11741                state.instruction.clone(),
11742                state.repo.clone(),
11743                Source::Agent {
11744                    run: "talk".into(),
11745                    node: crate::queue::CHAT_NODE.into(),
11746                },
11747            );
11748            controlled.runs.push(state.id.clone());
11749            controlled.hold_machine(Some("verification resource unavailable".into()));
11750            queue.put(&mut controlled).unwrap();
11751            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11752            assert_eq!(resumed.status, TaskStatus::Queued);
11753            assert_eq!(
11754                resumed.resume_override.unwrap().pinned_run,
11755                Some(state.id.clone())
11756            );
11757            assert_eq!(resumed.attempts, 0);
11758
11759            // A genuinely unresolved final review still exhausts the budget.
11760            state.config.graph.review_rounds = 1;
11761            let mut unresolved = review_round(1);
11762            unresolved.blocking = 1;
11763            state.reviews = vec![unresolved];
11764            state.resource_block = None;
11765            state.save_under(home.path()).unwrap();
11766            assert!(exhausted_review_budget(&state));
11767            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11768        }
11769    }
11770
11771    #[tokio::test]
11772    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11773        if !crate::standalone_test(
11774            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11775        ) {
11776            return;
11777        }
11778        let home = tempfile::tempdir().unwrap();
11779        let mut owner = stopped_public_run(RunStatus::Blocked);
11780        owner.save_under(home.path()).unwrap();
11781        let history = vec![owner.id.clone()];
11782        let repo = owner.repo.clone();
11783        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11784        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11785        let initial =
11786            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11787        assert!(
11788            initial.is_pending(),
11789            "a busy record must not hold or resume the task"
11790        );
11791        owner.retired_to = Some("20260101-000001-bbbb".into());
11792        owner.save_under(home.path()).unwrap();
11793        drop(lock);
11794        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11795            .await
11796            .expect("ownership lock released")
11797            .expect("read settled owner");
11798        assert!(
11799            result.is_none(),
11800            "the retired owner must not be resumed from a stale read"
11801        );
11802    }
11803
11804    #[tokio::test]
11805    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11806        if !crate::standalone_test(
11807            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11808        ) {
11809            return;
11810        }
11811        let home = tempfile::tempdir().unwrap();
11812        let mut owner = stopped_public_run(RunStatus::Blocked);
11813        let repo = tempfile::tempdir().unwrap();
11814        crate::git::git(repo.path(), &["init"]).await.unwrap();
11815        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
11816        owner.id = "20260101-000000-aaaa".into();
11817        owner.save_under(home.path()).unwrap();
11818        let mut successor = run_state(RunStatus::Blocked);
11819        successor.id = "20260101-000001-bbbb".into();
11820        successor.save_under(home.path()).unwrap();
11821        let runs = vec![owner.id.clone(), successor.id.clone()];
11822        assert_eq!(
11823            public_resume_owner(home.path(), &runs, &owner.repo)
11824                .await
11825                .unwrap()
11826                .unwrap()
11827                .id,
11828            owner.id
11829        );
11830        let subdir = owner.repo.join("nested");
11831        std::fs::create_dir(&subdir).unwrap();
11832        assert_eq!(
11833            public_resume_owner(home.path(), &runs, &subdir)
11834                .await
11835                .unwrap()
11836                .unwrap()
11837                .id,
11838            owner.id
11839        );
11840        #[cfg(unix)]
11841        {
11842            let alias = home.path().join("repo-alias");
11843            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
11844            assert_eq!(
11845                public_resume_owner(home.path(), &runs, &alias.join("nested"))
11846                    .await
11847                    .unwrap()
11848                    .unwrap()
11849                    .id,
11850                owner.id
11851            );
11852        }
11853        let different = tempfile::tempdir().unwrap();
11854        crate::git::git(different.path(), &["init"]).await.unwrap();
11855        assert!(
11856            public_resume_owner(home.path(), &runs, different.path())
11857                .await
11858                .is_err()
11859        );
11860        std::fs::remove_file(
11861            home.path()
11862                .join("runs")
11863                .join(&successor.id)
11864                .join("run.json"),
11865        )
11866        .unwrap();
11867        assert!(
11868            public_resume_owner(home.path(), &runs, &owner.repo)
11869                .await
11870                .is_err()
11871        );
11872    }
11873
11874    #[test]
11875    fn an_ordinary_release_keeps_a_resumable_run_available() {
11876        let mut released = task();
11877        released.start("stalled-run".to_owned());
11878        released.release();
11879        let unfinished = (!released.fresh_start)
11880            .then(|| Some("stalled-run".to_owned()))
11881            .flatten();
11882        assert_eq!(
11883            choose_starter(None, false, unfinished.as_deref()),
11884            Starter::Resume("stalled-run".to_owned()),
11885            "manual release must preserve the normal resume path"
11886        );
11887    }
11888
11889    #[test]
11890    fn resume_refusals_explain_admission_without_changing_task_or_run() {
11891        crate::run::pin_test_home();
11892        use crate::handover::{ResumeRefusal, resume_refusal_under};
11893        let home = tempfile::tempdir().unwrap();
11894        let mut exhausted = run_state(RunStatus::Blocked);
11895        exhausted.driver_exited = true;
11896        exhausted.config.graph.review_rounds = 3;
11897        exhausted.reviews = (1..=3).map(review_round).collect();
11898        for refusal in [
11899            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
11900            ResumeRefusal::Status(RunStatus::Ready),
11901            ResumeRefusal::Released("20261022-000000-aaaa".into()),
11902            ResumeRefusal::Retired("retirement-successor".into()),
11903            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
11904        ] {
11905            let mut state = exhausted.clone();
11906            let expected = match refusal {
11907                ResumeRefusal::Status(_) => {
11908                    state.status = RunStatus::Ready;
11909                    "status `ready`"
11910                }
11911                ResumeRefusal::Released(ref target) => {
11912                    state.released_to = Some(target.clone());
11913                    "execution was released"
11914                }
11915                ResumeRefusal::Retired(ref target) => {
11916                    state.retired_to = Some(target.clone());
11917                    "execution was retired"
11918                }
11919                ResumeRefusal::OwnershipTransferred(ref target) => {
11920                    state.pr_taken_over_by = Some(target.clone());
11921                    "PR ownership was transferred"
11922                }
11923                _ => "review budget exhausted (3/3 rounds used)",
11924            };
11925            assert_eq!(
11926                resume_refusal_under(&state, Some(home.path())),
11927                Some(refusal.clone())
11928            );
11929            assert_eq!(
11930                refusal.successor(),
11931                state
11932                    .released_to
11933                    .as_deref()
11934                    .or(state.retired_to.as_deref())
11935                    .or(state.pr_taken_over_by.as_deref())
11936            );
11937            state.save_under(home.path()).unwrap();
11938            let queue = Queue::at(home.path().join("queue"));
11939            let mut task = Task::new(
11940                "retained implementation".into(),
11941                state.instruction.clone(),
11942                state.repo.clone(),
11943                Source::Agent {
11944                    run: "talk".into(),
11945                    node: crate::queue::CHAT_NODE.into(),
11946                },
11947            );
11948            task.runs.push(state.id.clone());
11949            task.hold_machine(Some("stopped".into()));
11950            queue.put(&mut task).unwrap();
11951            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
11952            let before_run = serde_json::to_value(&state).unwrap();
11953            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
11954                .unwrap_err()
11955                .to_string();
11956            assert!(error.contains(expected), "{error}");
11957            assert!(!error.contains("only a stalled or blocked"), "{error}");
11958            if matches!(refusal, ResumeRefusal::Status(_)) {
11959                assert!(
11960                    error.contains("is final; there is nothing left to resume"),
11961                    "{error}"
11962                );
11963            }
11964            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
11965                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
11966                assert!(error.contains("review-only successor with a new review budget"));
11967                assert!(error.contains("does not resume this run"));
11968            }
11969            for target in [
11970                &state.released_to,
11971                &state.retired_to,
11972                &state.pr_taken_over_by,
11973            ]
11974            .into_iter()
11975            .flatten()
11976            {
11977                let short = if state.retired_to.as_ref() == Some(target) {
11978                    target.as_str()
11979                } else {
11980                    crate::run::short_of(target)
11981                };
11982                assert!(
11983                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
11984                    "{error}"
11985                );
11986                if short != target {
11987                    assert!(!error.contains(target), "full successor id leaked: {error}");
11988                }
11989            }
11990            assert_eq!(
11991                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
11992                before_task
11993            );
11994            assert_eq!(
11995                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
11996                    .unwrap(),
11997                before_run
11998            );
11999            let question = action_question(&state.id, resume_action(&state.id));
12000            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12001                let ActionDecision::Refuse(detail) =
12002                    decide_action(&task, &question, phrases, |_| Ok(state.clone()))
12003                else {
12004                    panic!("refusal expected");
12005                };
12006                assert!(detail.contains(expected), "{detail}");
12007            }
12008        }
12009        // Preserve predicate ordering, while keeping every recorded destination visible.
12010        exhausted.status = RunStatus::Ready;
12011        exhausted.released_to = Some("released".into());
12012        exhausted.retired_to = Some("retired".into());
12013        exhausted.pr_taken_over_by = Some("owner".into());
12014        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12015        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12016        let detail = reason.diagnostic(&exhausted);
12017        for target in ["released", "retired", "owner"] {
12018            assert!(detail.contains(&format!("magi show {target}")));
12019        }
12020    }
12021
12022    #[test]
12023    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12024        let home = tempfile::tempdir().unwrap();
12025        let mut state = run_state(RunStatus::Blocked);
12026        state.driver_exited = true;
12027        state.config.graph.review_rounds = 1;
12028        state.reviews = vec![review_round(1)];
12029        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12030        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12031            let mut saved = state.clone();
12032            match checkpoint {
12033                "publication" => saved.pr_publication_pending = true,
12034                "approval" => {
12035                    saved.land_approval = Some(crate::run::LandApproval {
12036                        question: "approval".into(),
12037                        head: "head".into(),
12038                    })
12039                }
12040                "armed" => saved.land_armed_head = Some("head".into()),
12041                "landing" => saved.status = RunStatus::Landing,
12042                _ => {
12043                    let mut question = ask::Question::new(
12044                        saved.id.clone(),
12045                        "review".into(),
12046                        "review-1".into(),
12047                        "continue?".into(),
12048                        String::new(),
12049                        vec!["continue".into()],
12050                    );
12051                    ask::Questions::at(home.path().join("questions"))
12052                        .put(&mut question)
12053                        .unwrap();
12054                }
12055            }
12056            saved.save_under(home.path()).unwrap();
12057            assert!(
12058                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12059                "{checkpoint}"
12060            );
12061            assert!(
12062                crate::resume::validate(home.path(), &saved.id).is_ok(),
12063                "{checkpoint}"
12064            );
12065        }
12066    }
12067
12068    #[test]
12069    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12070        let mut state = run_state(RunStatus::Blocked);
12071        state.config.graph.review_rounds = 3;
12072        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12073        assert!(exhausted_review_budget(&state));
12074
12075        // One round still unused: resuming can still ask a reviewer something.
12076        state.reviews.pop();
12077        assert!(!exhausted_review_budget(&state));
12078
12079        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12080        // count: only a `Blocked` run re-enters the review loop on resume.
12081        let mut stalled = run_state(RunStatus::Stalled);
12082        stalled.config.graph.review_rounds = 1;
12083        stalled.reviews = vec![review_round(1)];
12084        assert!(!exhausted_review_budget(&stalled));
12085    }
12086
12087    fn review_round(round: usize) -> crate::run::ReviewRound {
12088        crate::run::ReviewRound {
12089            round,
12090            head: "deadbeef".to_owned(),
12091            verified_head: None,
12092            verified_at: None,
12093            reviews: Vec::new(),
12094            e2e: Vec::new(),
12095            verify_retried: false,
12096            e2e_deferred: false,
12097            e2e_defer_reason: None,
12098            fix: None,
12099            blocking: 0,
12100            answered: 1,
12101            expected: 1,
12102            clean: false,
12103            progressed: true,
12104            vote_split: false,
12105            reconsideration: Vec::new(),
12106            verdict: None,
12107        }
12108    }
12109
12110    #[test]
12111    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12112        let mut run = RunState::new(
12113            PathBuf::from("/repo"),
12114            "main".to_owned(),
12115            "abc1234def".to_owned(),
12116            "add retries".to_owned(),
12117            Config::default(),
12118        );
12119        run.status = RunStatus::Judging;
12120        run.parked = true;
12121        let mut task = Task::new(
12122            "add retries".to_owned(),
12123            "add retries".to_owned(),
12124            PathBuf::from("/repo"),
12125            crate::queue::Source::Human,
12126        );
12127        task.status = TaskStatus::Failed;
12128        task.runs = vec![run.id.clone()];
12129        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12130        assert!(with(&task, &run), "parked after judging is the case");
12131        let mut parked_task = task.clone();
12132        parked_task.status = TaskStatus::Parked;
12133        assert!(with(&parked_task, &run), "the Parked status is the case");
12134
12135        let mut not_parked = run.clone();
12136        not_parked.parked = false;
12137        not_parked.status = RunStatus::Stalled;
12138        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12139
12140        let mut fresh = task.clone();
12141        fresh.fresh_start = true;
12142        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12143
12144        let mut review = task.clone();
12145        review.review_branch = Some("magi/x/A".to_owned());
12146        assert!(!with(&review, &run), "review is ranked before resume");
12147
12148        let mut held = task.clone();
12149        held.status = TaskStatus::Held;
12150        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12151
12152        let mut released = run.clone();
12153        released.released_to = Some("20260901-000000-new1".to_owned());
12154        assert!(!with(&task, &released), "nothing left to resume into");
12155
12156        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12157            "unreadable"
12158        )));
12159    }
12160
12161    #[test]
12162    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12163        let mut released = RunState::new(
12164            PathBuf::from("/repo"),
12165            "main".to_owned(),
12166            "abc1234def".to_owned(),
12167            "add retries".to_owned(),
12168            Config::default(),
12169        );
12170        released.status = RunStatus::Blocked;
12171        assert_eq!(
12172            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12173            Some(released.id.clone())
12174        );
12175        released.released_to = Some("20260901-000000-new1".to_owned());
12176        assert_eq!(
12177            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12178            None,
12179            "there is nothing left to resume it into"
12180        );
12181    }
12182
12183    #[test]
12184    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12185        // Mirrors the failure this exists to close: a task's last run ended
12186        // `Blocked` with the review budget spent, `crate::conduct` chose
12187        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12188        // evidence), and without this check `attempt` would go on treating
12189        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12190        // review loop iterates zero times over an already-spent budget, so
12191        // the resumed run settles right back to `Blocked` having asked nobody
12192        // anything, and `Requeue`'s promised fresh competition never happens.
12193        let mut exhausted = RunState::new(
12194            PathBuf::from("/repo"),
12195            "main".to_owned(),
12196            "abc1234def".to_owned(),
12197            "add retries".to_owned(),
12198            Config::default(),
12199        );
12200        exhausted.status = RunStatus::Blocked;
12201        exhausted.config.graph.review_rounds = 1;
12202        exhausted.reviews = vec![review_round(1)];
12203
12204        assert_eq!(
12205            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12206            None,
12207            "an exhausted `Blocked` run must not be offered as resumable"
12208        );
12209
12210        // A `Blocked` run with rounds still unused is genuinely worth
12211        // resuming, and must still be found.
12212        let mut has_budget_left = RunState::new(
12213            PathBuf::from("/repo"),
12214            "main".to_owned(),
12215            "abc1234def".to_owned(),
12216            "add retries".to_owned(),
12217            Config::default(),
12218        );
12219        has_budget_left.status = RunStatus::Blocked;
12220        has_budget_left.config.graph.review_rounds = 3;
12221        has_budget_left.reviews = vec![review_round(1)];
12222
12223        assert_eq!(
12224            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12225                Ok(has_budget_left.clone())
12226            }),
12227            Some(has_budget_left.id.clone())
12228        );
12229    }
12230
12231    #[test]
12232    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12233        let mut run = RunState::new(
12234            PathBuf::from("/repo"),
12235            "main".to_owned(),
12236            "abc1234def".to_owned(),
12237            "add retries".to_owned(),
12238            Config::default(),
12239        );
12240        run.status = RunStatus::Blocked;
12241        run.config.graph.review_rounds = 1;
12242        run.reviews = vec![review_round(1)];
12243        run.pr_publication_pending = true;
12244        assert_eq!(
12245            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12246            Some(run.id.clone()),
12247            "a spent review budget must not turn a failed publication into a re-competition"
12248        );
12249    }
12250
12251    #[test]
12252    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12253        let mut task = Task::new(
12254            "recover work".into(),
12255            "recover work".into(),
12256            PathBuf::from("/repo"),
12257            crate::queue::Source::Human,
12258        );
12259        let mut history = std::collections::BTreeMap::new();
12260        for index in 0..8 {
12261            let mut run = run_state(RunStatus::Blocked);
12262            run.id = format!("20260101-000000-{index:04}");
12263            run.base_commit = format!("upstream-{index}");
12264            // Seven empty newer attempts must not erase the old recovery owner.
12265            if index > 0 {
12266                run.candidates.clear();
12267            }
12268            task.runs.extend([run.id.clone(), run.id.clone()]);
12269            history.insert(run.id.clone(), run);
12270            task.requeue();
12271        }
12272        let check = |task: &Task, starter: &Starter, limit| {
12273            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12274        };
12275        assert!(
12276            check(&task, &Starter::Start, 8)
12277                .unwrap()
12278                .contains("8 unretired")
12279        );
12280        assert!(check(&task, &Starter::Start, 9).is_none());
12281        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12282        task.release_operator("owner", None);
12283        assert_eq!(task.attempts, 0);
12284        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12285        assert!(check(&restored, &Starter::Start, 8).is_some());
12286        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12287        assert!(check(&restored, &Starter::Start, 0).is_none());
12288    }
12289
12290    #[test]
12291    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12292        let mut task = Task::new(
12293            "recover work".into(),
12294            "recover work".into(),
12295            PathBuf::from("/repo"),
12296            crate::queue::Source::Human,
12297        );
12298        let mut run = run_state(RunStatus::Superseded);
12299        run.candidates.clear();
12300        task.runs.push(run.id.clone());
12301        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12302        run.retired_to = Some("authority".into());
12303        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12304        run.retired_to = None;
12305        run.released_to = Some("authority".into());
12306        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12307        assert!(
12308            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12309                .unwrap()
12310                .contains("Cannot verify")
12311        );
12312        // Resuming an existing owner needs no new inventory or worktree budget.
12313        assert!(
12314            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12315                panic!("resume must not load historical attempts")
12316            })
12317            .is_none()
12318        );
12319    }
12320
12321    #[test]
12322    fn retired_resume_requires_a_valid_same_repository_authority() {
12323        let mut source = run_state(RunStatus::Blocked);
12324        let mut empty = run_state(RunStatus::Blocked);
12325        empty.retired_to = Some(source.id.clone());
12326        let runs = vec![source.id.clone(), empty.id.clone()];
12327        let resolve = |source: &RunState, empty: &RunState| {
12328            unfinished_run_with(&runs, "fixture", |id| {
12329                if id == source.id {
12330                    Ok(source.clone())
12331                } else if id == empty.id {
12332                    Ok(empty.clone())
12333                } else {
12334                    bail!("unreadable authority")
12335                }
12336            })
12337        };
12338        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12339        assert_eq!(
12340            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12341            Starter::Resume(source.id.clone())
12342        );
12343        source.retired_to = Some(empty.id.clone());
12344        assert!(
12345            resolve(&source, &empty).is_none(),
12346            "cycles do not revive obsolete runs"
12347        );
12348        source.retired_to = None;
12349        source.repo = PathBuf::from("/another-repository");
12350        assert!(resolve(&source, &empty).is_none());
12351        source.repo = empty.repo.clone();
12352        source.released_to = Some("later".into());
12353        assert!(resolve(&source, &empty).is_none());
12354        empty.retired_to = Some("unlisted-run".into());
12355        assert!(resolve(&source, &empty).is_none());
12356    }
12357
12358    #[test]
12359    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12360        // A task whose history holds an *older* run that still looks
12361        // resumable (say, a competition `Runner::review` was started
12362        // alongside after that older run went `Stalled`) and a *newest* run
12363        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12364        // on this task must mean a fresh competition — falling back to the
12365        // stale, superseded `Stalled` run instead would resurrect history
12366        // nothing asked to revisit and silently defeat the requeue.
12367        let mut older_stalled = RunState::new(
12368            PathBuf::from("/repo"),
12369            "main".to_owned(),
12370            "abc1234def".to_owned(),
12371            "add retries".to_owned(),
12372            Config::default(),
12373        );
12374        older_stalled.status = RunStatus::Stalled;
12375
12376        let mut newest_exhausted = RunState::new(
12377            PathBuf::from("/repo"),
12378            "main".to_owned(),
12379            "abc1234def".to_owned(),
12380            "add retries".to_owned(),
12381            Config::default(),
12382        );
12383        newest_exhausted.status = RunStatus::Blocked;
12384        newest_exhausted.config.graph.review_rounds = 1;
12385        newest_exhausted.reviews = vec![review_round(1)];
12386
12387        assert_eq!(
12388            unfinished_run_with(
12389                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12390                "t",
12391                |_| Ok(newest_exhausted.clone())
12392            ),
12393            None,
12394            "the newest run is exhausted, so nothing here is worth resuming - \
12395             least of all the older, already-superseded run"
12396        );
12397    }
12398
12399    #[test]
12400    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12401        assert_eq!(
12402            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12403                Err(anyhow::anyhow!("fixture is absent"))
12404            }),
12405            None
12406        );
12407    }
12408
12409    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12410        let mut q = ask::Question::new(
12411            run.to_owned(),
12412            "implement".to_owned(),
12413            "impl-A".to_owned(),
12414            "continue?".to_owned(),
12415            String::new(),
12416            vec!["resume で続行する".to_owned(), "other".to_owned()],
12417        );
12418        q.actions.insert("resume で続行する".to_owned(), action);
12419        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12420            .unwrap();
12421        q
12422    }
12423
12424    fn held_task_with(run: &str) -> Task {
12425        let mut t = task();
12426        t.runs = vec![run.to_owned()];
12427        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12428        t
12429    }
12430
12431    fn resume_action(run: &str) -> ask::ChoiceAction {
12432        ask::ChoiceAction::Resume { run: run.into() }
12433    }
12434
12435    #[test]
12436    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12437        for parked in [false, true] {
12438            let mut t = task();
12439            t.start("A".into());
12440            t.start("B".into());
12441            assert_eq!(t.runs, vec!["A", "B"]);
12442            t.start("A".into());
12443            let mut resumed = run_state(RunStatus::Blocked);
12444            resumed.id = "A".into();
12445            resumed.parked = parked;
12446            resumed.driver_exited = true;
12447            t.hold_machine(Some("resumed run stopped".into()));
12448            let q = action_question("A", resume_action("A"));
12449            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12450            assert_eq!(
12451                decide_action(&t, &q, &PHRASES_EN, |id| {
12452                    assert_eq!(id, "A");
12453                    Ok(resumed.clone())
12454                }),
12455                ActionDecision::Resume("A".into())
12456            );
12457            assert_eq!(
12458                action_standing(&t, &action_question("B", resume_action("B"))),
12459                ActionStanding::Stale
12460            );
12461            t.release_operator("cli", None);
12462            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12463                assert_eq!(id, "A");
12464                Ok(resumed.clone())
12465            });
12466            assert_eq!(
12467                choose_starter(None, false, unfinished.as_deref()),
12468                Starter::Resume("A".into())
12469            );
12470            assert_eq!(t.runs, vec!["B", "A"]);
12471        }
12472    }
12473
12474    #[test]
12475    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12476        let mut state = crate::land::tests::repair_state(true, true);
12477        state.status = RunStatus::Landing;
12478        state.parked = true;
12479        state.driver_exited = true;
12480        let mut q = ask::Question::new(
12481            state.id.clone(),
12482            land::APPROVAL_NODE.into(),
12483            "land".into(),
12484            "Merge?".into(),
12485            String::new(),
12486            vec![land::APPROVE.into(), land::HOLD.into()],
12487        );
12488        q.id = state.id.clone();
12489        state.land_approval = Some(crate::run::LandApproval {
12490            question: q.id.clone(),
12491            head: "current-head".into(),
12492        });
12493        assert!(land::upgrade_repair_choice(&mut q, &state));
12494        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12495        let mut task = held_task_with(&state.id);
12496        task.status = TaskStatus::Parked;
12497        assert_eq!(
12498            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12499            ActionDecision::Resume(state.id.clone())
12500        );
12501        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12502        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12503        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12504        assert_eq!(
12505            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12506            ActionDecision::Resume(state.id.clone()),
12507            "a repair answer newer than the manual hold resumes the existing owner"
12508        );
12509        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12510        for answered_at in [q.answered_at, None] {
12511            let mut older = q.clone();
12512            older.answered_at = answered_at;
12513            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
12514                panic!("a later manual hold must prevent dispatch")
12515            });
12516            let ActionDecision::Refuse(reason) = refused else {
12517                panic!("expected an actionable refusal, got {refused:?}");
12518            };
12519            assert!(reason.contains("later operator decision"));
12520            assert!(reason.contains(&format!("magi task release {}", task.id)));
12521        }
12522        task.operator_decided_at = None;
12523        let mut superseded = state.clone();
12524        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12525        assert_eq!(
12526            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
12527            ActionDecision::Stale
12528        );
12529        for case in 1..4 {
12530            let mut changed = state.clone();
12531            match case {
12532                1 => changed.status = RunStatus::Blocked,
12533                2 => changed.released_to = Some("new-owner".into()),
12534                _ => changed.land_approval.as_mut().unwrap().head.clear(),
12535            }
12536            assert!(matches!(
12537                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
12538                ActionDecision::Refuse(_)
12539            ));
12540        }
12541        assert!(matches!(
12542            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
12543            ActionDecision::Refuse(_)
12544        ));
12545        task.runs.push("replacement".into());
12546        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12547        assert_eq!(
12548            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
12549                "old owner must not load"
12550            )),
12551            ActionDecision::Stale
12552        );
12553    }
12554
12555    #[test]
12556    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12557        let mut state = crate::land::tests::repair_state(true, true);
12558        state.status = RunStatus::Landing;
12559        state.parked = true;
12560        state.driver_exited = true;
12561        let mut q = ask::Question::new(
12562            state.id.clone(),
12563            land::APPROVAL_NODE.into(),
12564            "land".into(),
12565            "Merge?".into(),
12566            String::new(),
12567            vec![land::APPROVE.into(), land::HOLD.into()],
12568        );
12569        q.id = state.id.clone();
12570        state.land_approval = Some(crate::run::LandApproval {
12571            question: q.id.clone(),
12572            head: "current-head".into(),
12573        });
12574        state.save().unwrap();
12575        land::upgrade_repair_choice(&mut q, &state);
12576        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12577        Questions::open().put(&mut q).unwrap();
12578        let tmp = tempfile::tempdir().unwrap();
12579        let queue = Queue::at(tmp.path().join("queue"));
12580        let mut task = held_task_with(&state.id);
12581        task.status = TaskStatus::Parked;
12582        queue.put(&mut task).unwrap();
12583        let empty = Arc::new(tokio::sync::Semaphore::new(0));
12584        let free = Arc::new(tokio::sync::Semaphore::new(1));
12585        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12586        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12587        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12588        assert!(claim.permit.is_some());
12589        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12590        drop(claim);
12591        Questions::open()
12592            .update(&q.id, |q| {
12593                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12594                Ok(())
12595            })
12596            .unwrap();
12597        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12598        assert!(claim.permit.is_none());
12599        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12600    }
12601
12602    #[test]
12603    fn decide_action_resumes_only_the_latest_resumable_run() {
12604        let t = held_task_with("r1");
12605        let q = action_question("r1", resume_action("r1"));
12606        let load = |s: RunState| move |_: &str| Ok(s);
12607        assert_eq!(
12608            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
12609            ActionDecision::Resume("r1".into())
12610        );
12611        // Not the latest run of the task.
12612        let q_other = action_question("r1", resume_action("r0"));
12613        assert!(matches!(
12614            decide_action(
12615                &t,
12616                &q_other,
12617                &PHRASES_EN,
12618                load(run_state(RunStatus::Blocked))
12619            ),
12620            ActionDecision::Refuse(_)
12621        ));
12622        // A finished run cannot make progress.
12623        assert!(matches!(
12624            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
12625            ActionDecision::Refuse(_)
12626        ));
12627        // A released one either.
12628        let mut released = run_state(RunStatus::Blocked);
12629        released.released_to = Some("elsewhere".into());
12630        assert!(matches!(
12631            decide_action(&t, &q, &PHRASES_EN, load(released)),
12632            ActionDecision::Refuse(_)
12633        ));
12634        // Unreadable state is a refusal, never a fresh competition.
12635        assert!(matches!(
12636            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
12637            ActionDecision::Refuse(_)
12638        ));
12639    }
12640
12641    #[test]
12642    fn decide_action_ignores_a_question_about_an_earlier_run() {
12643        let mut t = held_task_with("r1");
12644        t.runs.push("r2".to_owned());
12645        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12646        assert_eq!(
12647            decide_action(
12648                &t,
12649                &action_question("r1", ask::ChoiceAction::Done),
12650                &PHRASES_EN,
12651                never
12652            ),
12653            ActionDecision::Stale
12654        );
12655    }
12656
12657    #[test]
12658    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
12659        let mut t = held_task_with("r1");
12660        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12661        assert_eq!(
12662            decide_action(
12663                &t,
12664                &action_question("r1", ask::ChoiceAction::Requeue),
12665                &PHRASES_EN,
12666                never
12667            ),
12668            ActionDecision::Requeue
12669        );
12670        let done_q = action_question("r1", ask::ChoiceAction::Done);
12671        assert_eq!(
12672            decide_action(&t, &done_q, &PHRASES_EN, never),
12673            ActionDecision::Done
12674        );
12675        t.mark_action_applied(&done_q.id);
12676        assert_eq!(
12677            decide_action(&t, &done_q, &PHRASES_EN, never),
12678            ActionDecision::Skip
12679        );
12680
12681        // A plain answer (no action for that label) does nothing.
12682        let mut plain = action_question("r1", ask::ChoiceAction::Done);
12683        plain.actions.clear();
12684        assert_eq!(
12685            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
12686            ActionDecision::Skip
12687        );
12688        // A running task is left alone.
12689        let mut running = held_task_with("r1");
12690        running.status = TaskStatus::Running;
12691        assert_eq!(
12692            decide_action(
12693                &running,
12694                &action_question("r1", ask::ChoiceAction::Done),
12695                &PHRASES_EN,
12696                never
12697            ),
12698            ActionDecision::Skip
12699        );
12700    }
12701
12702    #[test]
12703    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
12704        crate::run::pin_test_home();
12705        for legacy in [false, true] {
12706            let dir = tempfile::tempdir().unwrap();
12707            let queue = Queue::at(dir.path().join("queue"));
12708            let questions = Questions::at(dir.path().join("questions"));
12709            let run = "20260101-000000-hold";
12710            let mut task = held_task_with(run);
12711            task.status = TaskStatus::Parked;
12712            let mut q = ask::Question::new(
12713                run.into(),
12714                land::APPROVAL_NODE.into(),
12715                "land".into(),
12716                "Repair?".into(),
12717                String::new(),
12718                vec![land::REPAIR.into()],
12719            );
12720            q.actions.insert(land::REPAIR.into(), resume_action(run));
12721            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12722            // Deterministically order the answer before the actual manual hold.
12723            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12724            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
12725            questions.put(&mut q).unwrap();
12726            task.hold_manual(Some("Keep this PR paused".into()));
12727            if legacy {
12728                task.hold_source = None;
12729            }
12730            queue.put(&mut task).unwrap();
12731
12732            apply_task_choice_actions(&queue, &questions, dir.path());
12733            let after = queue.get(&task.id).unwrap();
12734            assert!(after.operator_held());
12735            assert_eq!(after.hold_source, task.hold_source);
12736            assert_eq!(after.operator_decided_at, task.operator_decided_at);
12737            assert_eq!(after.runs, task.runs);
12738            assert_eq!(after.instruction, task.instruction);
12739            assert!(after.resume_override.is_none());
12740            assert!(after.action_applied(&q.id));
12741            let reason = after.hold_reason.as_deref().unwrap();
12742            assert!(reason.starts_with("Keep this PR paused"));
12743            assert!(reason.contains("later operator decision"));
12744            assert!(reason.contains(&format!("magi task release {}", task.id)));
12745
12746            for recovery in [
12747                crate::conduct::Recovery::Review,
12748                crate::conduct::Recovery::Requeue,
12749            ] {
12750                crate::conduct::apply(
12751                    &queue,
12752                    &questions,
12753                    &crate::conduct::Verdict {
12754                        decisions: vec![crate::conduct::Decision {
12755                            id: task.id.clone(),
12756                            recovery: Some(recovery),
12757                            ..Default::default()
12758                        }],
12759                    },
12760                )
12761                .unwrap();
12762            }
12763            // Reconciliation is idempotent, and automatic recovery cannot
12764            // reopen this owner after it observes the rejected repair answer.
12765            apply_task_choice_actions(&queue, &questions, dir.path());
12766            let still_held = queue.get(&task.id).unwrap();
12767            assert!(still_held.operator_held());
12768            assert_eq!(still_held.hold_reason, after.hold_reason);
12769            assert_eq!(still_held.runs, task.runs);
12770            assert!(still_held.review_branch.is_none());
12771            assert!(!still_held.fresh_start);
12772            assert!(queue.next_runnable().is_none());
12773        }
12774    }
12775
12776    #[test]
12777    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
12778        for held in [false, true] {
12779            for retry in [false, true] {
12780                let dir = tempfile::tempdir().unwrap();
12781                let queue = Queue::at(dir.path().join("queue"));
12782                let questions = Questions::at(dir.path().join("questions"));
12783                let home = dir.path().join("home");
12784                let mut t = task();
12785                if held {
12786                    t.hold_machine(Some("driver state unknown".into()));
12787                }
12788                queue.put(&mut t).unwrap();
12789                let verdict = serde_json::from_value(serde_json::json!({
12790                    "decisions": [{
12791                        "id": t.id,
12792                        "question": "Driver state unknown; retry the checks or hold?",
12793                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
12794                        "actions": {
12795                            "daemon: recheck and retry": {"do": "requeue"},
12796                            "daemon: hold the task": {"do": "hold"}
12797                        }
12798                    }]
12799                }))
12800                .unwrap();
12801                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
12802                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12803                let mut q = questions.list().pop().unwrap();
12804                let choice = if retry {
12805                    "daemon: recheck and retry"
12806                } else {
12807                    "daemon: hold the task"
12808                };
12809                assert_eq!(q.actions.len(), 2);
12810                q.answer(ask::Answer::Choice(choice.into())).unwrap();
12811                questions.put(&mut q).unwrap();
12812
12813                // A Web answer does not remove the deputy's fresh lease.
12814                questions.beat(&q.id, ask::WaiterKind::Deputy);
12815                for _ in 0..2 {
12816                    resolve_blockers(&queue, &questions);
12817                    apply_task_choice_actions(&queue, &questions, &home);
12818                    let waiting = queue.get(&t.id).unwrap();
12819                    assert_eq!(waiting.status, TaskStatus::Blocked);
12820                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
12821                    assert!(waiting.answers.is_empty());
12822                    assert!(!waiting.action_applied(&q.id));
12823                    assert!(runnable(&queue).is_empty());
12824                    let free = Arc::new(tokio::sync::Semaphore::new(1));
12825                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
12826                }
12827                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12828
12829                // Releasing the blocker and applying the operation share one save.
12830                resolve_blockers(&queue, &questions);
12831                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12832                apply_task_choice_actions(&queue, &questions, &home);
12833                let after = queue.get(&t.id).unwrap();
12834                assert_eq!(
12835                    after.status,
12836                    if retry {
12837                        TaskStatus::Queued
12838                    } else {
12839                        TaskStatus::Held
12840                    }
12841                );
12842                assert!(after.action_applied(&q.id));
12843                assert_eq!(after.operator_held(), !retry);
12844                assert_eq!(after.answers.len(), 1);
12845
12846                // A later operator decision must not replay this answer.
12847                let mut changed = after;
12848                if retry {
12849                    changed.hold_manual(Some("later hold".into()));
12850                } else {
12851                    changed.release_operator("test", None);
12852                }
12853                let expected = changed.status;
12854                queue.put(&mut changed).unwrap();
12855                apply_task_choice_actions(&queue, &questions, &home);
12856                assert_eq!(queue.get(&t.id).unwrap().status, expected);
12857            }
12858        }
12859    }
12860
12861    #[test]
12862    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
12863        let dir = tempfile::tempdir().unwrap();
12864        let queue = Queue::at(dir.path().join("queue"));
12865        let questions = Questions::at(dir.path().join("questions"));
12866        let home = dir.path().join("home");
12867        let mut state = run_state(RunStatus::Blocked);
12868        state.id = "20260101-000000-act1".to_owned();
12869        state.save_under(&home).unwrap();
12870
12871        let mut t = held_task_with(&state.id);
12872        queue.put(&mut t).unwrap();
12873        let mut q = action_question(&state.id, resume_action(&state.id));
12874        questions.put(&mut q).unwrap();
12875
12876        apply_task_choice_actions(&queue, &questions, &home);
12877        let after = queue.get(&t.id).unwrap();
12878        assert_eq!(after.status, TaskStatus::Queued);
12879        assert!(!after.fresh_start);
12880        assert!(after.action_applied(&q.id));
12881        let pin = after.resume_override.clone().unwrap();
12882        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
12883        assert!(pin.forced);
12884
12885        // Held again later: the same answer does not release it a second time.
12886        let mut again = queue.get(&t.id).unwrap();
12887        again.hold_machine(Some("later".into()));
12888        queue.put(&mut again).unwrap();
12889        apply_task_choice_actions(&queue, &questions, &home);
12890        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12891    }
12892
12893    #[test]
12894    fn a_delivered_answer_is_still_acted_on_exactly_once() {
12895        let dir = tempfile::tempdir().unwrap();
12896        let queue = Queue::at(dir.path().join("queue"));
12897        let questions = Questions::at(dir.path().join("questions"));
12898        let home = dir.path().join("home");
12899        let mut state = run_state(RunStatus::Blocked);
12900        state.id = "20260101-000000-act2".to_owned();
12901        state.save_under(&home).unwrap();
12902
12903        let mut t = held_task_with(&state.id);
12904        queue.put(&mut t).unwrap();
12905        let mut q = action_question(&state.id, resume_action(&state.id));
12906        q.answer_delivered = true;
12907        questions.put(&mut q).unwrap();
12908
12909        // Delivered, and the agent then died: the task is still held, so the
12910        // chosen action applies.
12911        apply_task_choice_actions(&queue, &questions, &home);
12912        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12913        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
12914
12915        // Held again: the same answer does nothing a second time.
12916        let mut again = queue.get(&t.id).unwrap();
12917        again.hold_machine(Some("later".into()));
12918        queue.put(&mut again).unwrap();
12919        apply_task_choice_actions(&queue, &questions, &home);
12920        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12921    }
12922
12923    #[test]
12924    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
12925        let dir = tempfile::tempdir().unwrap();
12926        let queue = Queue::at(dir.path().join("queue"));
12927        let questions = Questions::at(dir.path().join("questions"));
12928        let home = dir.path().join("home");
12929        let mut state = run_state(RunStatus::Blocked);
12930        state.id = "20260101-000000-act3".to_owned();
12931        state.save_under(&home).unwrap();
12932        let mut t = held_task_with(&state.id);
12933        queue.put(&mut t).unwrap();
12934        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
12935        questions.put(&mut q).unwrap();
12936
12937        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
12938        apply_task_choice_actions(&queue, &questions, &home);
12939        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12940
12941        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12942        apply_task_choice_actions(&queue, &questions, &home);
12943        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12944    }
12945
12946    #[test]
12947    fn action_standing_tells_the_reasons_apart() {
12948        let mut t = held_task_with("r1");
12949        let q = action_question("r1", ask::ChoiceAction::Requeue);
12950        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12951        let mut plain = q.clone();
12952        plain.actions.clear();
12953        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
12954
12955        // Applied wins over everything, even a running task.
12956        t.mark_action_applied(&q.id);
12957        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
12958
12959        // A newer attempt running: the old question is Stale, not Busy.
12960        let mut t = held_task_with("r1");
12961        t.start("r2".to_owned());
12962        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
12963        // The same question about the latest run just waits.
12964        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
12965        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12966        t.status = TaskStatus::Blocked;
12967        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12968
12969        // A conductor question is keyed by the task, never stale.
12970        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
12971        c.node = crate::conduct::NODE.to_owned();
12972        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
12973        assert!(!ActionStanding::Busy.daemon_owns());
12974    }
12975
12976    #[test]
12977    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
12978        let dir = tempfile::tempdir().unwrap();
12979        let queue = Queue::at(dir.path().join("queue"));
12980        let questions = Questions::at(dir.path().join("questions"));
12981        let home = dir.path().join("home");
12982        let mut state = run_state(RunStatus::Blocked);
12983        state.id = "20260101-000000-act4".to_owned();
12984        state.save_under(&home).unwrap();
12985        let mut t = held_task_with(&state.id);
12986        t.status = TaskStatus::Running;
12987        queue.put(&mut t).unwrap();
12988        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
12989        q.cwd = Some(dir.path().display().to_string());
12990        questions.put(&mut q).unwrap();
12991
12992        // While the task runs the daemon will not act, so the waiter still
12993        // delivers the word to the dead asker's seat ...
12994        let running = queue.get(&t.id).unwrap();
12995        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
12996        assert!(matches!(
12997            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
12998            crate::waiter::Action::Deliver(_)
12999        ));
13000        // ... and the daemon waits while the task runs, then applies once.
13001        apply_task_choice_actions(&queue, &questions, &home);
13002        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13003        let mut back = queue.get(&t.id).unwrap();
13004        back.hold_machine(Some("later".into()));
13005        queue.put(&mut back).unwrap();
13006        apply_task_choice_actions(&queue, &questions, &home);
13007        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13008        let mut again = queue.get(&t.id).unwrap();
13009        again.hold_machine(Some("again".into()));
13010        queue.put(&mut again).unwrap();
13011        apply_task_choice_actions(&queue, &questions, &home);
13012        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13013    }
13014}