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::summarize_verify(&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_keeps_gate_panic_before_large_backtrace() {
8454        let mut state = run_state(RunStatus::Failed);
8455        state.gate.push(crate::run::CommandOutcome {
8456            command: "cargo test".into(),
8457            code: Some(101),
8458            output_tail: format!(
8459                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8460                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8461            ),
8462            duration_ms: 1,
8463            resource_blocked: false,
8464        });
8465        let d = diagnostic(&state).unwrap();
8466        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8467        assert!(d.contains("assertion failed: widget missing"));
8468        assert!(d.contains("widget log"));
8469    }
8470
8471    #[test]
8472    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8473        // The whole point of the feature: a run held as "no candidate produced
8474        // a change" can mean the implementer actually finished the task and
8475        // only left a clean local tree behind - see AGENTS.md on this exact
8476        // failure mode. The diagnostic has to carry what the agent actually
8477        // said, not just the fact that nothing was there to judge.
8478        let mut state = run_state(RunStatus::Failed);
8479        state.candidates = vec![candidate(
8480            'A',
8481            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8482            true,
8483            None,
8484        )];
8485        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8486        assert!(d.contains("candidate A"), "{d}");
8487        assert!(d.contains("tagged v1.2.3"), "{d}");
8488    }
8489
8490    #[test]
8491    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8492        let mut state = run_state(RunStatus::Failed);
8493        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8494        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8495        assert!(d.contains("candidate A"), "{d}");
8496        assert!(d.contains("agent timed out"), "{d}");
8497    }
8498
8499    #[test]
8500    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8501        // A viable candidate existed, the gate never ran, and nothing land
8502        // said matches - `Task::last_error` is left to explain this one alone.
8503        let mut state = run_state(RunStatus::Failed);
8504        state.candidates = vec![candidate('A', "did the work", false, None)];
8505        assert!(diagnostic(&state).is_none());
8506    }
8507
8508    #[test]
8509    fn diagnostic_is_bounded_however_much_a_run_printed() {
8510        let mut state = run_state(RunStatus::Blocked);
8511        state.gate = vec![
8512            CommandOutcome {
8513                command: "cargo test".to_owned(),
8514                code: Some(101),
8515                output_tail: "x".repeat(50_000),
8516                duration_ms: 0,
8517                resource_blocked: false,
8518            },
8519            CommandOutcome {
8520                command: "cargo clippy".to_owned(),
8521                code: Some(1),
8522                output_tail: "y".repeat(50_000),
8523                duration_ms: 0,
8524                resource_blocked: false,
8525            },
8526        ];
8527        state.candidates = vec![
8528            candidate('A', &"z".repeat(50_000), true, None),
8529            candidate('B', &"w".repeat(50_000), true, None),
8530        ];
8531        let d = diagnostic(&state).expect("plenty here to diagnose");
8532        assert!(
8533            d.len() <= DIAGNOSTIC_MAX,
8534            "diagnostic grew to {} bytes, unbounded",
8535            d.len()
8536        );
8537    }
8538
8539    #[test]
8540    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8541        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8542            let mut t = task();
8543            let mut state = run_state(status);
8544            t.pr_recovery = Some(crate::pr_recovery::Selection {
8545                url: "url".into(),
8546                branch: format!("magi/task-{}", t.id),
8547                head: "a".repeat(40),
8548                source_head: None,
8549                source_run: None,
8550                source_proof: None,
8551                disposition: Some(crate::pr_recovery::Disposition::Land),
8552                instruction: t.instruction.clone(),
8553                approved_at: Timestamp::now(),
8554            });
8555            state.pr_recovery = t.pr_recovery.clone();
8556            t.start(state.id.clone());
8557            settle_and_diagnose(
8558                &mut t,
8559                Verdict {
8560                    status,
8561                    left_pr: false,
8562                    quota_hit: false,
8563                    parked: false,
8564                    no_viable_candidates: false,
8565                },
8566                "delivery stopped",
8567                5,
8568                &state,
8569            );
8570            assert_eq!(t.status, TaskStatus::Held);
8571            let reason = t.hold_reason.as_deref().unwrap();
8572            if status == RunStatus::Ready {
8573                assert!(reason.contains("Selected PR delivery is incomplete"));
8574                assert!(t.recovery_budget.is_none());
8575            } else {
8576                assert!(reason.contains("Selected recovery stopped"));
8577                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8578            }
8579            assert!(t.pr_recovery.is_some());
8580        }
8581    }
8582
8583    #[test]
8584    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8585        let mut state = run_state(RunStatus::Voting);
8586        state.base_sync = Some(crate::run::BaseSync {
8587            tip: "base-tip".into(),
8588            behind: 3,
8589            attempts: 4,
8590            conflict: Some("base stopped".into()),
8591            already_in: None,
8592        });
8593        state.record_base_sync_stop("candidate-head");
8594        let mut t = task();
8595        t.start(state.id.clone());
8596        let verdict = Verdict {
8597            status: RunStatus::Blocked,
8598            left_pr: false,
8599            quota_hit: false,
8600            parked: false,
8601            no_viable_candidates: false,
8602        };
8603        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8604        assert_eq!(
8605            t.status,
8606            TaskStatus::Held,
8607            "unspent task attempts cannot start another competition"
8608        );
8609        let at = t.held_at;
8610        let cause = t.hold_notice_cause.clone();
8611        state.begin_pass();
8612        t.release_operator("test-resume", None);
8613        t.start(state.id.clone());
8614        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8615        assert_eq!(t.status, TaskStatus::Held);
8616        assert_eq!(t.held_at, at);
8617        assert_eq!(t.hold_notice_cause, cause);
8618    }
8619
8620    #[test]
8621    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8622        let mut state = run_state(RunStatus::Blocked);
8623        state.gate = vec![CommandOutcome {
8624            command: "cargo test".to_owned(),
8625            code: Some(101),
8626            output_tail: "assertion failed".to_owned(),
8627            duration_ms: 0,
8628            resource_blocked: false,
8629        }];
8630        let verdict = Verdict {
8631            status: RunStatus::Blocked,
8632            left_pr: false,
8633            quota_hit: false,
8634            parked: false,
8635            no_viable_candidates: false,
8636        };
8637
8638        // Attempt one of two still has a retry coming: no diagnostic yet, the
8639        // task is going to run again and this run's evidence would go stale.
8640        let mut t = task();
8641        t.start("run-1".to_owned());
8642        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8643        assert_eq!(t.status, TaskStatus::Failed);
8644        assert!(t.diagnostic.is_none());
8645
8646        // Attempt two exhausts the budget: now it is held, and the
8647        // diagnostic is what `magi task show` has to say more than one line.
8648        t.start("run-2".to_owned());
8649        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8650        assert_eq!(t.status, TaskStatus::Held);
8651        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8652        assert!(d.contains("cargo test"), "{d}");
8653    }
8654
8655    #[test]
8656    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8657        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8658        // `magi ask` question settled Held with `hold_reason: null`, so the
8659        // notification said nothing actionable. `note_open_question` should
8660        // append the question id to whatever `handed_off` already wrote.
8661        crate::run::pin_test_home();
8662        let home = crate::run::home();
8663        let state = run_state(RunStatus::VerifiedNoop);
8664        let mut q = ask::Question::new(
8665            state.id.clone(),
8666            "implement".to_owned(),
8667            "impl-A".to_owned(),
8668            "is this really a no-op?".to_owned(),
8669            String::new(),
8670            Vec::new(),
8671        );
8672        Questions::at(home.join("questions")).put(&mut q).unwrap();
8673
8674        let verdict = Verdict {
8675            status: RunStatus::VerifiedNoop,
8676            left_pr: false,
8677            quota_hit: false,
8678            parked: false,
8679            no_viable_candidates: false,
8680        };
8681        let mut t = task();
8682        t.start(state.id.clone());
8683        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8684
8685        assert_eq!(t.status, TaskStatus::Held);
8686        let reason = t.hold_reason.expect("a held task must record why");
8687        assert!(
8688            reason.starts_with("run ended agent-verified no-op"),
8689            "the original settle reason must survive unchanged: {reason}"
8690        );
8691        assert!(
8692            reason.contains(q.short()),
8693            "the open question's id must be named so the notice is actionable: {reason}"
8694        );
8695    }
8696
8697    #[test]
8698    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8699        crate::run::pin_test_home();
8700        let state = run_state(RunStatus::VerifiedNoop);
8701
8702        let verdict = Verdict {
8703            status: RunStatus::VerifiedNoop,
8704            left_pr: false,
8705            quota_hit: false,
8706            parked: false,
8707            no_viable_candidates: false,
8708        };
8709        let mut t = task();
8710        t.start(state.id.clone());
8711        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8712
8713        assert_eq!(t.status, TaskStatus::Held);
8714        assert_eq!(
8715            t.hold_reason.as_deref(),
8716            Some("run ended agent-verified no-op"),
8717            "nothing to append when the question was already answered or never asked"
8718        );
8719    }
8720
8721    #[test]
8722    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8723        crate::run::pin_test_home();
8724        let mut first = run_state(RunStatus::Blocked);
8725        first.id = "20260101-000000-sup1".to_owned();
8726        first.save().unwrap();
8727        let mut second = run_state(RunStatus::Merged);
8728        second.id = "20260101-000000-sup2".to_owned();
8729        second.save().unwrap();
8730
8731        let mut t = task();
8732        t.runs = vec![first.id.clone(), second.id.clone()];
8733        t.status = TaskStatus::Done;
8734
8735        supersede_prior_runs(&t, &crate::run::home());
8736
8737        assert_eq!(
8738            RunState::load(&first.id).unwrap().status,
8739            RunStatus::Superseded,
8740            "the first attempt's Blocked no longer needs anyone's attention"
8741        );
8742        assert_eq!(
8743            RunState::load(&second.id).unwrap().status,
8744            RunStatus::Merged,
8745            "the run that actually succeeded is left exactly as it was"
8746        );
8747    }
8748
8749    #[test]
8750    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8751        // `is_working_on` alone only proves a *daemon* claim; a `magi run
8752        // --resume` invoked by hand outside the daemon never touches
8753        // `daemon.json` at all, so it would look identical to a genuinely
8754        // idle run without also consulting `RunState::liveness`, which reads
8755        // this run's own recorded `driver_pid` instead.
8756        crate::run::pin_test_home();
8757        let mut first = run_state(RunStatus::Blocked);
8758        first.id = "20260101-000000-sup9".to_owned();
8759        // This test process's own pid: guaranteed alive without needing a
8760        // real second process or daemon.
8761        first.driver_pid = Some(std::process::id());
8762        first.driver_started_at = Some(
8763            crate::proc::process_started_at(std::process::id())
8764                .expect("this test process's own start time must be queryable"),
8765        );
8766        first.save().unwrap();
8767        let mut second = run_state(RunStatus::Merged);
8768        second.id = "20260101-000000-supa".to_owned();
8769        second.save().unwrap();
8770
8771        let mut t = task();
8772        t.runs = vec![first.id.clone(), second.id.clone()];
8773        t.status = TaskStatus::Done;
8774
8775        supersede_prior_runs(&t, &crate::run::home());
8776
8777        assert_eq!(
8778            RunState::load(&first.id).unwrap().status,
8779            RunStatus::Blocked,
8780            "a live driver_pid means something is still actually working this run, \
8781             even though no daemon claims it - rewriting under it would just be \
8782             undone the next time that process saves"
8783        );
8784    }
8785
8786    #[test]
8787    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8788        // The first resweep must skip a still-live attempt exactly like
8789        // `supersede_prior_runs` itself does; a later resweep, once that
8790        // process is no longer actually driving it, is what closes the gap
8791        // `supersede_prior_runs` alone leaves - a task only ever reaches
8792        // `Done` once, so nothing else would ever look at this run again.
8793        let dir = tempfile::tempdir().unwrap();
8794        let home = dir.path().to_path_buf();
8795        let queue = Queue::at(dir.path().join("queue"));
8796
8797        let mut first = run_state(RunStatus::Blocked);
8798        first.id = "20260101-000000-supd".to_owned();
8799        first.driver_pid = Some(std::process::id());
8800        first.driver_started_at = Some(
8801            crate::proc::process_started_at(std::process::id())
8802                .expect("this test process's own start time must be queryable"),
8803        );
8804        first.save_under(&home).unwrap();
8805        let mut second = run_state(RunStatus::Merged);
8806        second.id = "20260101-000000-supe".to_owned();
8807        second.save_under(&home).unwrap();
8808
8809        let mut t = task();
8810        t.runs = vec![first.id.clone(), second.id.clone()];
8811        t.status = TaskStatus::Done;
8812        queue.put(&mut t).unwrap();
8813
8814        resweep_superseded_attempts(&queue, &home);
8815        assert_eq!(
8816            RunState::load_under(&first.id, &home).unwrap().status,
8817            RunStatus::Blocked,
8818            "still live on the first pass, so still untouched"
8819        );
8820
8821        // Stand in for the manual process no longer being the one driving
8822        // this run: same pid (this test process really is still alive), but
8823        // an identity marker that no longer matches it - see
8824        // `RunState::liveness`'s own doc for why a mismatched
8825        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
8826        let mut stale = RunState::load_under(&first.id, &home).unwrap();
8827        stale.driver_started_at = Some("1".to_owned());
8828        stale.save_under(&home).unwrap();
8829
8830        resweep_superseded_attempts(&queue, &home);
8831        assert_eq!(
8832            RunState::load_under(&first.id, &home).unwrap().status,
8833            RunStatus::Superseded,
8834            "the second pass catches up what the first one correctly skipped"
8835        );
8836    }
8837
8838    #[test]
8839    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8840        crate::run::pin_test_home();
8841        let mut first = run_state(RunStatus::Blocked);
8842        first.id = "20260101-000000-sup3".to_owned();
8843        first.save().unwrap();
8844        let mut second = run_state(RunStatus::Blocked);
8845        second.id = "20260101-000000-sup4".to_owned();
8846        second.save().unwrap();
8847
8848        let mut t = task();
8849        t.runs = vec![first.id.clone(), second.id.clone()];
8850        // Still retrying: nothing about this task's story is settled yet, so
8851        // neither Blocked run may be relabelled, even though a later attempt
8852        // already exists.
8853        t.status = TaskStatus::Failed;
8854
8855        supersede_prior_runs(&t, &crate::run::home());
8856
8857        assert_eq!(
8858            RunState::load(&first.id).unwrap().status,
8859            RunStatus::Blocked
8860        );
8861        assert_eq!(
8862            RunState::load(&second.id).unwrap().status,
8863            RunStatus::Blocked
8864        );
8865    }
8866
8867    #[test]
8868    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
8869        // `magi task done` (or the API's equivalent) can close a task with no
8870        // run of its own ever having succeeded - there is nothing here that
8871        // counts as "the attempt that finished it", so nothing is rewritten.
8872        crate::run::pin_test_home();
8873        let mut first = run_state(RunStatus::Blocked);
8874        first.id = "20260101-000000-sup5".to_owned();
8875        first.save().unwrap();
8876
8877        let mut t = task();
8878        t.runs = vec![first.id.clone()];
8879        t.status = TaskStatus::Done;
8880
8881        supersede_prior_runs(&t, &crate::run::home());
8882
8883        assert_eq!(
8884            RunState::load(&first.id).unwrap().status,
8885            RunStatus::Blocked,
8886            "a single-attempt task has no earlier run to supersede"
8887        );
8888    }
8889
8890    #[test]
8891    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
8892        // `magi task done` (or the web/conductor equivalents) can close a
8893        // task in any status, including one whose *last* recorded attempt is
8894        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
8895        // never watched, say. `runs.last()` being `Done`-adjacent is not
8896        // proof it actually succeeded, so nothing earlier may be relabelled
8897        // on its say-so alone.
8898        crate::run::pin_test_home();
8899        let mut first = run_state(RunStatus::Blocked);
8900        first.id = "20260101-000000-supb".to_owned();
8901        first.save().unwrap();
8902        let mut second = run_state(RunStatus::Failed);
8903        second.id = "20260101-000000-supc".to_owned();
8904        second.save().unwrap();
8905
8906        let mut t = task();
8907        t.runs = vec![first.id.clone(), second.id.clone()];
8908        t.status = TaskStatus::Done;
8909
8910        supersede_prior_runs(&t, &crate::run::home());
8911
8912        assert_eq!(
8913            RunState::load(&first.id).unwrap().status,
8914            RunStatus::Blocked,
8915            "the task's last attempt never landed, so there is nothing here \
8916             actually superseding it"
8917        );
8918    }
8919
8920    #[test]
8921    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
8922        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
8923        // to look" - `Failed` and `VerifiedNoop` are already their own
8924        // terminal answers and must not be relabelled into a third one.
8925        crate::run::pin_test_home();
8926        let mut failed = run_state(RunStatus::Failed);
8927        failed.id = "20260101-000000-sup6".to_owned();
8928        failed.save().unwrap();
8929        let mut noop = run_state(RunStatus::VerifiedNoop);
8930        noop.id = "20260101-000000-sup7".to_owned();
8931        noop.save().unwrap();
8932        let mut winner = run_state(RunStatus::Ready);
8933        winner.id = "20260101-000000-sup8".to_owned();
8934        winner.save().unwrap();
8935
8936        let mut t = task();
8937        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
8938        t.status = TaskStatus::Done;
8939
8940        supersede_prior_runs(&t, &crate::run::home());
8941
8942        assert_eq!(
8943            RunState::load(&failed.id).unwrap().status,
8944            RunStatus::Failed
8945        );
8946        assert_eq!(
8947            RunState::load(&noop.id).unwrap().status,
8948            RunStatus::VerifiedNoop
8949        );
8950    }
8951
8952    fn approval_question(run: &str) -> ask::Question {
8953        ask::Question::new(
8954            run.to_owned(),
8955            land::APPROVAL_NODE.to_owned(),
8956            "land".to_owned(),
8957            "merge?".to_owned(),
8958            String::new(),
8959            vec!["merge".to_owned(), "hold".to_owned()],
8960        )
8961    }
8962
8963    #[test]
8964    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
8965        crate::run::pin_test_home();
8966        let mut state = run_state(RunStatus::Landing);
8967        state.id = "20260101-000000-fre1".to_owned();
8968        state.parked = true;
8969        state.save().unwrap();
8970        ask::Questions::open()
8971            .put(&mut approval_question(&state.id))
8972            .unwrap();
8973
8974        let mut t = task();
8975        t.runs.push(state.id.clone());
8976        assert_eq!(
8977            land_resume_state(&t),
8978            LandResume::StillWaiting,
8979            "nobody has answered and the timeout has not passed"
8980        );
8981    }
8982
8983    #[test]
8984    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
8985        crate::run::pin_test_home();
8986        let mut state = run_state(RunStatus::Gating);
8987        state.id = "20260101-000000-gt01".to_owned();
8988        state.parked = true;
8989        state.config.graph.answer_timeout = 60;
8990        state.github_text = Some(crate::run::GithubTextAsk {
8991            rewrite: None,
8992            fingerprint: "f".into(),
8993            title: true,
8994            body: false,
8995            categories: vec!["title-language".into()],
8996            question: None,
8997            asks: 1,
8998            resolved: false,
8999            chosen_title: None,
9000            choice: None,
9001        });
9002        state.save().unwrap();
9003        let store = ask::Questions::open();
9004        let mut q = ask::Question::new(
9005            state.id.clone(),
9006            crate::github_text::ASK_NODE.to_owned(),
9007            crate::github_text::ASK_SEAT.to_owned(),
9008            "s".into(),
9009            String::new(),
9010            vec!["use fallback".into()],
9011        );
9012        store.put(&mut q).unwrap();
9013        let mut t = task();
9014        t.runs.push(state.id.clone());
9015        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9016        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9017        store.put(&mut q).unwrap();
9018        assert_eq!(land_resume_state(&t), LandResume::Ready);
9019        assert!(!store.get(&q.id).unwrap().status.open());
9020        // Once decided, a parked run is an ordinary candidate again.
9021        state.github_text.as_mut().unwrap().resolved = true;
9022        state.save().unwrap();
9023        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9024    }
9025
9026    #[test]
9027    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9028        // `ask::ask_and_wait`'s own deadline used to retire a question
9029        // nobody answered; land's approval bypasses that wait (see
9030        // `land::approval_gate`), so this is now the only place
9031        // `graph.answer_timeout` is enforced for a land approval at all.
9032        crate::run::pin_test_home();
9033        let mut state = run_state(RunStatus::Landing);
9034        state.id = "20260101-000000-exp1".to_owned();
9035        state.parked = true;
9036        state.config.graph.answer_timeout = 60;
9037        state.save().unwrap();
9038
9039        let store = ask::Questions::open();
9040        let mut q = approval_question(&state.id);
9041        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9042        store.put(&mut q).unwrap();
9043
9044        let mut t = task();
9045        t.runs.push(state.id.clone());
9046        assert_eq!(
9047            land_resume_state(&t),
9048            LandResume::Ready,
9049            "an expired question must not be waited on forever"
9050        );
9051
9052        let after = store.get(&q.id).unwrap();
9053        assert!(
9054            !after.status.open(),
9055            "the question is abandoned, not silently ignored"
9056        );
9057        assert!(
9058            after.resolution().is_none(),
9059            "an abandoned question is not read as a decision"
9060        );
9061    }
9062
9063    #[test]
9064    fn reclaim_settles_a_running_task_against_its_last_run() {
9065        let mut t = task();
9066        t.start("20260904-000000-4043".to_owned());
9067        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9068        assert_eq!(
9069            t.status,
9070            TaskStatus::Done,
9071            "a run that actually finished must not stay `running` forever"
9072        );
9073    }
9074
9075    #[test]
9076    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9077        let mut t = task();
9078        t.start("20260904-000000-4043".to_owned());
9079        t.last_error = Some("earlier trouble".to_owned());
9080        let mut state = run_state(RunStatus::Judging);
9081        state.parked = true;
9082        reclaim(&mut t, Some(state), 1, "en");
9083        assert_eq!(t.status, TaskStatus::Parked);
9084        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9085        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9086        assert!(t.park_reason.is_some());
9087        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9088        assert!(!t.fresh_start);
9089        assert!(t.status.runnable());
9090    }
9091
9092    #[test]
9093    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9094        let mut t = task();
9095        t.start("20260904-000000-4043".to_owned());
9096        t.last_error = Some("earlier trouble".to_owned());
9097        settle(
9098            &mut t,
9099            Verdict {
9100                status: RunStatus::Judging,
9101                left_pr: false,
9102                quota_hit: false,
9103                parked: true,
9104                no_viable_candidates: false,
9105            },
9106            "parked after `judging`",
9107            1,
9108        );
9109        assert_eq!(t.status, TaskStatus::Parked);
9110        assert_eq!(t.attempts, 0);
9111        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9112        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9113        assert_eq!(t.schema, crate::queue::SCHEMA);
9114        assert!(
9115            crate::notices::task_held(&t).is_none(),
9116            "a park is not news"
9117        );
9118        t.start("20260904-000000-4043".to_owned());
9119        assert_eq!(t.park_reason, None);
9120    }
9121
9122    #[test]
9123    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9124        // A blocked run with attempts left goes back to `Failed`, exactly as
9125        // it would from `attempt` itself - `reclaim` must not invent a second
9126        // policy for a task a daemon merely stopped without reporting.
9127        let mut t = task();
9128        t.start("20260904-000000-4043".to_owned());
9129        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9130        assert_eq!(t.status, TaskStatus::Failed);
9131        assert!(t.status.runnable());
9132    }
9133
9134    #[test]
9135    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9136        let mut t = task();
9137        t.start("20260904-000000-4043".to_owned());
9138        assert_eq!(t.attempts, 1);
9139        let mut run = run_state(RunStatus::Implementing);
9140        run.id = "20260904-000000-4043".to_owned();
9141        run.begin_pass();
9142        let cause = crate::run::ParkCause::Upgrade {
9143            from: "0.121.0".to_owned(),
9144            to: Some("0.121.1".to_owned()),
9145        };
9146        run.end_pass_parked(cause.clone());
9147        run.parked = true;
9148        let verdict = Verdict {
9149            status: run.status,
9150            left_pr: false,
9151            quota_hit: false,
9152            parked: true,
9153            no_viable_candidates: false,
9154        };
9155        // A crash after the checkpoint but before queue settlement must
9156        // recover exactly the same scheduling evidence and refund.
9157        let mut orphan = t.clone();
9158        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9159        assert_eq!(orphan.status, TaskStatus::Parked);
9160        assert_eq!(orphan.attempts, 0);
9161        assert_eq!(
9162            orphan.upgrade_resume_key(),
9163            Some((run.passes[0].started_at, orphan.id.as_str()))
9164        );
9165        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9166        assert_eq!(t.attempts, 0);
9167        assert_eq!(t.passes.len(), 1);
9168        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9169        assert_eq!(t.passes[0].parked, Some(cause));
9170        assert_eq!(t.passes[0].pass_index, 0);
9171        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9172        assert!(t.upgrade_resume_key().is_some());
9173
9174        // A resumed pass that then fails spends its attempt, and the earlier
9175        // pass's entry is untouched.
9176        t.start("20260904-000000-4043".to_owned());
9177        run.begin_pass();
9178        run.status = RunStatus::Failed;
9179        let verdict = Verdict {
9180            status: RunStatus::Failed,
9181            left_pr: false,
9182            quota_hit: false,
9183            parked: false,
9184            no_viable_candidates: false,
9185        };
9186        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9187        assert_eq!(t.passes.len(), 2);
9188        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9189        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9190        assert_eq!(t.passes[1].pass_index, 1);
9191        assert_eq!(t.attempts, 1);
9192    }
9193
9194    #[test]
9195    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9196        let mut t = task();
9197        t.start("20260904-000000-4043".to_owned());
9198        reclaim(&mut t, None, 2, "en");
9199        assert_eq!(t.status, TaskStatus::Held);
9200        assert!(
9201            t.last_error
9202                .as_deref()
9203                .is_some_and(|e| e.contains("running")),
9204            "the operator needs to know why this task was held"
9205        );
9206    }
9207
9208    #[test]
9209    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9210        let dir = tempfile::tempdir().unwrap();
9211        let queue = Queue::at(dir.path().to_path_buf());
9212
9213        // No run recorded, so this never has to touch `RunState::load`.
9214        let mut orphaned = task();
9215        orphaned.id = "20260904-000000-orph".to_owned();
9216        orphaned.status = TaskStatus::Running;
9217        orphaned.attempts = 1;
9218        queue.put(&mut orphaned).unwrap();
9219
9220        let mut alive = task();
9221        alive.id = "20260904-000000-live".to_owned();
9222        alive.status = TaskStatus::Running;
9223        alive.attempts = 1;
9224        queue.put(&mut alive).unwrap();
9225        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9226
9227        let mut queued = task();
9228        queued.id = "20260904-000000-wait".to_owned();
9229        queue.put(&mut queued).unwrap();
9230
9231        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9232        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9233
9234        assert_eq!(
9235            queue.get(&orphaned.id).unwrap().status,
9236            TaskStatus::Held,
9237            "nothing was driving it and there was no run to recover"
9238        );
9239        assert_eq!(
9240            queue.get(&alive.id).unwrap().status,
9241            TaskStatus::Running,
9242            "a live claim must protect the task it belongs to"
9243        );
9244        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9245    }
9246
9247    /// Read a run.json back from an explicit `home`, the same way
9248    /// `reclaim_abandoned_runs` itself does - never through the
9249    /// process-global `RunState::load`, which this test's own `home` (an
9250    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9251    /// use at all.
9252    fn read_run_under(home: &Path, id: &str) -> RunState {
9253        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9254        serde_json::from_str(&body).unwrap()
9255    }
9256
9257    #[test]
9258    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9259        let dir = tempfile::tempdir().unwrap();
9260        let home = dir.path().to_path_buf();
9261        let now = Timestamp::now();
9262        let overrun_seat = || crate::run::ActiveSeat {
9263            node: "implement".to_owned(),
9264            started_at: now - jiff::SignedDuration::new(21_000, 0),
9265            timeout_secs: 3_600,
9266            attempt: 0,
9267            task: None,
9268            command: None,
9269            index: None,
9270            total: None,
9271        };
9272
9273        let mut dead = run_state(RunStatus::Implementing);
9274        dead.id = "20260101-000000-dead".to_owned();
9275        dead.active.insert("impl-A".to_owned(), overrun_seat());
9276        // A `driver_pid` the injected query below confirms gone outright —
9277        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9278        dead.driver_pid = Some(4242);
9279        dead.save_under(&home).unwrap();
9280
9281        // Same shape, but a live daemon's heartbeat names it: must be left
9282        // exactly alone, however far past its own timeout the seat sits.
9283        let mut alive = run_state(RunStatus::Implementing);
9284        alive.id = "20260101-000000-aliv".to_owned();
9285        alive.active.insert("impl-A".to_owned(), overrun_seat());
9286        alive.save_under(&home).unwrap();
9287        let mut status = Status::new();
9288        status.current = vec![Current {
9289            worker: None,
9290            task: "20260101-000000-task".to_owned(),
9291            run: alive.id.clone(),
9292        }];
9293        write_status_to(&home.join("daemon.json"), &status).unwrap();
9294
9295        // The abandoned seat left an open question behind: nobody is left to
9296        // read an answer once the run is failed, and this must not wait for
9297        // some later daemon startup's own sweep to notice that.
9298        let questions = Questions::at(home.join("questions"));
9299        let mut q = ask::Question::new(
9300            dead.id.clone(),
9301            "implement".to_owned(),
9302            "impl-A".to_owned(),
9303            "Which storage backend?".to_owned(),
9304            String::new(),
9305            vec!["SQLite".to_owned(), "Redis".to_owned()],
9306        );
9307        questions.put(&mut q).unwrap();
9308
9309        let abandoned = reclaim_abandoned_runs_with(
9310            &home,
9311            now,
9312            |pid| if pid == 4242 { Some(false) } else { None },
9313            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9314        );
9315        assert_eq!(abandoned, vec![dead.id.clone()]);
9316
9317        let reloaded = read_run_under(&home, &dead.id);
9318        assert_eq!(reloaded.status, RunStatus::Failed);
9319        assert!(reloaded.active.is_empty());
9320        assert!(
9321            !questions.get(&q.id).unwrap().status.open(),
9322            "the failed run's own open question must be settled in the same pass"
9323        );
9324
9325        let still_alive = read_run_under(&home, &alive.id);
9326        assert_eq!(
9327            still_alive.status,
9328            RunStatus::Implementing,
9329            "a live daemon's claim protects it"
9330        );
9331        assert!(!still_alive.active.is_empty());
9332    }
9333
9334    /// The exact shape a review round flagged as broken: `magi serve` running
9335    /// in this same `home` scans *every* run on disk, including a manual
9336    /// `magi review` / `magi run` this daemon never started and that
9337    /// therefore claims no heartbeat of its own. Before this scan asked
9338    /// `liveness` rather than just `is_working_on`, a manual run whose active
9339    /// seat merely ran a little past its own timeout — the CLI finishing up,
9340    /// its result still being collected — got wiped and failed by a daemon
9341    /// that had nothing to do with it, out from under a process that was
9342    /// still very much running.
9343    #[test]
9344    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9345        let dir = tempfile::tempdir().unwrap();
9346        let home = dir.path().to_path_buf();
9347        let now = Timestamp::now();
9348
9349        let mut manual = run_state(RunStatus::Reviewing);
9350        manual.id = "20260101-000000-manl".to_owned();
9351        manual.active.insert(
9352            "review-1".to_owned(),
9353            crate::run::ActiveSeat {
9354                node: "review".to_owned(),
9355                started_at: now - jiff::SignedDuration::new(21_000, 0),
9356                timeout_secs: 3_600,
9357                attempt: 0,
9358                task: None,
9359                command: None,
9360                index: None,
9361                total: None,
9362            },
9363        );
9364        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9365        // but a real, still-running process: `liveness` must corroborate this
9366        // as `Live`, not read the missing daemon claim as death.
9367        manual.driver_pid = Some(4242);
9368        manual.driver_started_at = Some("1790000000".to_owned());
9369        manual.save_under(&home).unwrap();
9370
9371        let abandoned = reclaim_abandoned_runs_with(
9372            &home,
9373            now,
9374            |pid| if pid == 4242 { Some(true) } else { None },
9375            |pid| {
9376                if pid == 4242 {
9377                    Some("1790000000".to_owned())
9378                } else {
9379                    None
9380                }
9381            },
9382        );
9383        assert!(
9384            abandoned.is_empty(),
9385            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9386        );
9387
9388        let reloaded = read_run_under(&home, &manual.id);
9389        assert_eq!(reloaded.status, RunStatus::Reviewing);
9390        assert!(!reloaded.active.is_empty());
9391    }
9392
9393    #[test]
9394    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9395        let dir = tempfile::tempdir().unwrap();
9396        let queue = Queue::at(dir.path().to_path_buf());
9397        let mut only = task();
9398        queue.put(&mut only).unwrap();
9399
9400        let _elsewhere = queue.claim(&only.id).unwrap();
9401        let candidates = runnable(&queue);
9402        assert_eq!(candidates.len(), 1, "the task is still runnable");
9403        assert!(
9404            queue.claim(&candidates[0].id).is_err(),
9405            "the loop cannot take a claim somebody else holds"
9406        );
9407
9408        let after = queue.get(&only.id).unwrap();
9409        assert_eq!(after.status, TaskStatus::Queued);
9410        assert_eq!(
9411            after.attempts, 0,
9412            "losing the race is not an attempt at the task"
9413        );
9414        assert_eq!(after.last_error, None);
9415    }
9416
9417    #[test]
9418    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9419        let dir = tempfile::tempdir().unwrap();
9420        let path = dir.path().join("daemon.json");
9421
9422        let mut status = Status::new();
9423        status.idle = false;
9424        status.completed = 7;
9425        status.current = vec![Current {
9426            worker: None,
9427            task: "20260902-000000-t111".to_owned(),
9428            run: "20260902-000001-r111".to_owned(),
9429        }];
9430        write_status_to(&path, &status).unwrap();
9431        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9432        assert_eq!(first.schema, SCHEMA);
9433        assert_eq!(first.pid, std::process::id());
9434        assert!(!first.idle);
9435        assert_eq!(first.completed, 7);
9436        assert_eq!(first.current, status.current);
9437        assert!(
9438            !path.with_extension("json.tmp").exists(),
9439            "the temp file is renamed, not left behind"
9440        );
9441
9442        std::thread::sleep(Duration::from_millis(5));
9443        status.updated_at = Timestamp::now();
9444        status.polls = 3;
9445        write_status_to(&path, &status).unwrap();
9446        let second: Status =
9447            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9448        assert!(
9449            second.updated_at > first.updated_at,
9450            "a reader can only detect staleness if the heartbeat moves"
9451        );
9452        assert_eq!(
9453            second.started_at, first.started_at,
9454            "the start time is not a heartbeat"
9455        );
9456        assert_eq!(second.polls, 3);
9457    }
9458
9459    #[test]
9460    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9461        let dir = tempfile::tempdir().unwrap();
9462
9463        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9464
9465        let mut status = Status::new();
9466        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9467        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9468        let stale = read_status(dir.path()).unwrap();
9469        assert!(
9470            !stale.running(Timestamp::now()),
9471            "a minute without a heartbeat is a dead daemon, not a busy one"
9472        );
9473        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9474
9475        status.updated_at = Timestamp::now();
9476        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9477        let fresh = read_status(dir.path()).unwrap();
9478        assert!(fresh.running(Timestamp::now()));
9479    }
9480
9481    #[test]
9482    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9483        let dir = tempfile::tempdir().unwrap();
9484        let now = Timestamp::now();
9485        let mine = "20260903-080619-01c2";
9486
9487        assert!(
9488            !is_working_on(dir.path(), mine, now),
9489            "no status file means nobody is working on anything"
9490        );
9491
9492        let mut status = Status::new();
9493        status.current = vec![Current {
9494            worker: None,
9495            task: "20260903-080340-0167".to_owned(),
9496            run: mine.to_owned(),
9497        }];
9498        status.updated_at = now;
9499        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9500        assert!(is_working_on(dir.path(), mine, now));
9501        assert!(
9502            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9503            "a daemon busy with one run is not working on another"
9504        );
9505
9506        // A killed daemon stops writing heartbeats but leaves the file behind
9507        // naming the run it died in. That run must not be undeletable forever.
9508        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9509        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9510        assert!(
9511            !is_working_on(dir.path(), mine, now),
9512            "a stale heartbeat is a dead daemon, so its run is a leftover"
9513        );
9514    }
9515
9516    #[test]
9517    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9518        let dir = tempfile::tempdir().unwrap();
9519        let now = Timestamp::now();
9520
9521        assert!(
9522            !is_working_on_short(dir.path(), "01c2", now),
9523            "no status file means nobody is working on anything"
9524        );
9525
9526        let mut status = Status::new();
9527        status.current = vec![Current {
9528            worker: None,
9529            task: "20260903-080340-0167".to_owned(),
9530            run: "20260903-080619-01c2".to_owned(),
9531        }];
9532        status.updated_at = now;
9533        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9534        assert!(
9535            is_working_on_short(dir.path(), "01c2", now),
9536            "the run's short id is the last block of its full id"
9537        );
9538        assert!(
9539            !is_working_on_short(dir.path(), "3cbf", now),
9540            "a daemon busy with one worktree bay is not working on another"
9541        );
9542    }
9543
9544    #[test]
9545    fn a_newer_status_file_still_yields_a_reading() {
9546        let dir = tempfile::tempdir().unwrap();
9547        // A field this build has never heard of must not turn the reading into
9548        // nothing at all; that is the whole reason the reader is permissive.
9549        std::fs::write(
9550            dir.path().join("daemon.json"),
9551            serde_json::json!({
9552                "schema": 2,
9553                "updated_at": Timestamp::now().to_string(),
9554                "idle": true,
9555                "surprise": { "nested": [1, 2, 3] },
9556            })
9557            .to_string(),
9558        )
9559        .unwrap();
9560
9561        let reading = read_status(dir.path()).expect("a forward-compatible read");
9562        assert!(reading.running(Timestamp::now()));
9563        assert!(reading.idle);
9564        assert!(reading.current.is_empty());
9565    }
9566
9567    #[test]
9568    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9569        // A daemon started before `current` became a list keeps writing this
9570        // shape on every heartbeat until it is restarted. A rolling upgrade
9571        // - a newer `magi web` or `magi doctor` reading an older `magi
9572        // serve`'s heartbeat - must still see the run it is on, not "no
9573        // daemon" from a type mismatch failing the whole struct.
9574        let dir = tempfile::tempdir().unwrap();
9575        std::fs::write(
9576            dir.path().join("daemon.json"),
9577            serde_json::json!({
9578                "schema": 1,
9579                "pid": 4242,
9580                "updated_at": Timestamp::now().to_string(),
9581                "idle": false,
9582                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9583                "completed": 3,
9584                "polls": 9,
9585            })
9586            .to_string(),
9587        )
9588        .unwrap();
9589
9590        let reading = read_status(dir.path()).expect("an older shape must still parse");
9591        assert!(reading.running(Timestamp::now()));
9592        assert_eq!(
9593            reading.current,
9594            vec![Current {
9595                worker: None,
9596                task: "20260902-140501-aaaa".to_owned(),
9597                run: "20260902-140502-bbbb".to_owned(),
9598            }]
9599        );
9600    }
9601
9602    #[test]
9603    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9604        let dir = tempfile::tempdir().unwrap();
9605        std::fs::write(
9606            dir.path().join("daemon.json"),
9607            serde_json::json!({
9608                "schema": 1,
9609                "updated_at": Timestamp::now().to_string(),
9610                "idle": true,
9611                "current": null,
9612            })
9613            .to_string(),
9614        )
9615        .unwrap();
9616        let with_null = read_status(dir.path()).expect("null must still parse");
9617        assert!(with_null.current.is_empty());
9618
9619        std::fs::write(
9620            dir.path().join("daemon.json"),
9621            serde_json::json!({
9622                "schema": 1,
9623                "updated_at": Timestamp::now().to_string(),
9624                "idle": true,
9625            })
9626            .to_string(),
9627        )
9628        .unwrap();
9629        let absent = read_status(dir.path()).expect("a missing field must still parse");
9630        assert!(absent.current.is_empty());
9631    }
9632
9633    #[test]
9634    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9635        let fallback = Path::new("/default");
9636        let mut blank = task();
9637        blank.repo = PathBuf::new();
9638        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9639        let mut dot = task();
9640        dot.repo = PathBuf::from(".");
9641        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9642        assert_eq!(
9643            repo_for(&task(), fallback),
9644            PathBuf::from("/repo"),
9645            "a task that names a repository keeps it"
9646        );
9647    }
9648
9649    #[test]
9650    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9651        let dir = tempfile::tempdir().unwrap();
9652        let path = dir.path().join("explicit.toml");
9653        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9654        let opts = Opts {
9655            config: Some(path),
9656            merge: Some("none".into()),
9657            ..Default::default()
9658        };
9659        let mut t = task();
9660        t.set_implementers(
9661            2,
9662            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9663                .unwrap(),
9664        )
9665        .unwrap();
9666        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9667        assert_eq!(cfg.graph.implementers, 2);
9668        assert_eq!(cfg.graph.judges, 1);
9669        assert_eq!(cfg.merge.mode, MergeMode::None);
9670        t.set_implementers(1, &cfg).unwrap();
9671        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9672        apply_task_implementers(&mut cfg, &t);
9673        assert_eq!(cfg.graph.implementers, 1);
9674        assert_eq!(cfg.graph.judges, 1);
9675        assert_eq!(cfg.merge.mode, MergeMode::None);
9676    }
9677
9678    #[test]
9679    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9680        let dir = tempfile::tempdir().unwrap();
9681        let repo = dir.path().join("repo");
9682        std::fs::create_dir(&repo).unwrap();
9683        std::fs::write(
9684            repo.join("magi.toml"),
9685            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9686        )
9687        .unwrap();
9688        let daemon_config = dir.path().join("daemon.toml");
9689        std::fs::write(
9690            &daemon_config,
9691            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9692        )
9693        .unwrap();
9694        let opts = Opts {
9695            config: Some(daemon_config),
9696            merge: Some("pr".into()),
9697            ..Default::default()
9698        };
9699        let q = Queue::at(dir.path().join("queue"));
9700        let validation: Config =
9701            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9702                .unwrap();
9703        // No provenance field on legacy direct tasks: both shapes stay isolated.
9704        for record in ["{}", r#"{"candidates":2}"#] {
9705            let overrides = serde_json::from_str(record).unwrap();
9706            let filing = crate::direct::Filing {
9707                instruction: "work".into(),
9708                title: "direct".into(),
9709                repo: repo.clone(),
9710                source: crate::queue::Source::Human,
9711                solo: false,
9712                overrides,
9713                review_of: None,
9714                sources: Default::default(),
9715            };
9716            let filed =
9717                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9718            let crate::direct::Filed::Standalone {
9719                mut task,
9720                claim: _claim,
9721            } = filed
9722            else {
9723                panic!("local filing")
9724            };
9725            let before = prepare_for(&repo, &opts, &task).unwrap();
9726            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9727            assert_eq!(
9728                before.merge.mode,
9729                MergeMode::None,
9730                "daemon --merge must not leak"
9731            );
9732            for n in [2, 1, 2] {
9733                task.set_implementers(n, &validation).unwrap();
9734                q.put(&mut task).unwrap();
9735                task = q.get(&task.id).unwrap();
9736                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9737                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9738                apply_task_implementers(&mut cfg, &task);
9739                assert_eq!(cfg.graph.implementers, usize::from(n));
9740                assert_eq!(cfg.graph.judges, 2);
9741                assert_eq!(cfg.merge.mode, MergeMode::None);
9742            }
9743        }
9744    }
9745
9746    #[test]
9747    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9748        let cfg: Config =
9749            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9750                .unwrap();
9751        let mut t = task();
9752        t.review_of = Some("review-target".into());
9753        t.hold_manual(Some("retry".into()));
9754        let mut previous = RunState::new(
9755            PathBuf::from("/repo"),
9756            "main".into(),
9757            "abc1234".into(),
9758            "review".into(),
9759            cfg.clone(),
9760        );
9761        previous.config.graph.implementers = 2;
9762        for count in [1, 3] {
9763            t.set_implementers(count, &cfg).unwrap();
9764            t.release();
9765            assert_eq!(t.review_of.as_deref(), Some("review-target"));
9766            for proposed in [
9767                Starter::Resume(previous.id.clone()),
9768                Starter::Review("recovery-target".into()),
9769            ] {
9770                assert_eq!(
9771                    starter_with_implementers(&t, Some(&previous), proposed),
9772                    Starter::Review("review-target".into())
9773                );
9774            }
9775            let mut configured = cfg.clone();
9776            apply_task_implementers(&mut configured, &t);
9777            assert_eq!(configured.graph.implementers, usize::from(count));
9778            assert_eq!(previous.config.graph.implementers, 2);
9779        }
9780    }
9781
9782    #[test]
9783    fn task_implementers_dispatch_and_resume_agree() {
9784        let mut t = task();
9785        let cfg: crate::config::Config =
9786            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9787                .unwrap();
9788        let mut run = RunState::new(
9789            PathBuf::from("/repo"),
9790            "main".into(),
9791            "abc1234".into(),
9792            "work".into(),
9793            cfg.clone(),
9794        );
9795        run.config.graph.implementers = 2;
9796        for n in [2, 1, 3, 2] {
9797            t.set_implementers(n, &cfg).unwrap();
9798            let mut dispatched = cfg.clone();
9799            apply_task_implementers(&mut dispatched, &t);
9800            assert_eq!(dispatched.graph.implementers, usize::from(n));
9801            assert_eq!(implementers_match(&t, &run), n == 2);
9802            for proposed in [
9803                Starter::Resume(run.id.clone()),
9804                Starter::Review("old-branch".into()),
9805            ] {
9806                let expected = if n == 2 {
9807                    proposed.clone()
9808                } else {
9809                    Starter::Start
9810                };
9811                assert_eq!(
9812                    starter_with_implementers(&t, Some(&run), proposed),
9813                    expected
9814                );
9815            }
9816            assert_eq!(
9817                run.config.graph.implementers, 2,
9818                "history must not be rewritten"
9819            );
9820        }
9821        t.solo = false;
9822        t.overrides = None;
9823        assert!(implementers_match(&t, &run));
9824    }
9825
9826    #[test]
9827    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9828        // Three seats said out loud. What `solo` promises is one candidate
9829        // *whatever the config asks for*, so the contrast has to be a number
9830        // this test owns - it used to be `Config::default()`'s, which became
9831        // 1 when one implementation became the default and left the two
9832        // halves of this test asserting the same thing.
9833        let mut solo_cfg = Config::default();
9834        solo_cfg.graph.implementers = 3;
9835        let mut solo_task = task();
9836        solo_task.solo = true;
9837        apply_task_implementers(&mut solo_cfg, &solo_task);
9838        assert_eq!(solo_cfg.graph.implementers, 1);
9839
9840        let mut plain_cfg = Config::default();
9841        plain_cfg.graph.implementers = 3;
9842        let plain_task = task();
9843        assert!(!plain_task.solo);
9844        apply_task_implementers(&mut plain_cfg, &plain_task);
9845        assert_eq!(
9846            plain_cfg.graph.implementers, 3,
9847            "a task that did not ask to run alone keeps the config's candidates"
9848        );
9849    }
9850
9851    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9852        QuotaLoss {
9853            seat: seat.into(),
9854            node: "judge".into(),
9855            at: at.parse().unwrap(),
9856            reset: reset.map(str::to_string),
9857        }
9858    }
9859
9860    #[test]
9861    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
9862        let old: Vec<QuotaLoss> = (1..=4)
9863            .map(|i| {
9864                loss(
9865                    &format!("judge-{i}"),
9866                    "2026-09-23T05:23:00Z",
9867                    Some("2:40pm (Asia/Tokyo)"),
9868                )
9869            })
9870            .collect();
9871        let fresh = losses_this_attempt(&old, &old);
9872        assert!(fresh.is_empty());
9873        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
9874        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
9875    }
9876
9877    #[test]
9878    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
9879        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
9880        let now = Timestamp::now();
9881        let mut after = old.clone();
9882        after.push(loss("judge-2", &now.to_string(), None));
9883        let fresh = losses_this_attempt(&old, &after);
9884        assert_eq!(fresh, vec![after[1].clone()]);
9885        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
9886        assert_eq!(
9887            until,
9888            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
9889        );
9890    }
9891
9892    #[test]
9893    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
9894        // `recover_stall` removes judge-1's loss and the retry then hits quota
9895        // again: the vector is the same length, so an index diff sees nothing.
9896        let before = vec![
9897            loss("judge-1", "2026-09-23T05:23:00Z", None),
9898            loss("judge-2", "2026-09-23T05:24:00Z", None),
9899        ];
9900        let after = vec![
9901            loss("judge-2", "2026-09-23T05:24:00Z", None),
9902            loss("judge-1", "2026-09-24T01:00:00Z", None),
9903        ];
9904        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
9905    }
9906
9907    #[test]
9908    fn merge_overrides_are_parsed_or_refused() {
9909        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
9910        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
9911        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
9912        assert!(merge_mode("squash").is_err());
9913    }
9914
9915    #[test]
9916    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
9917        let now = Timestamp::now();
9918        let fallback = Duration::from_secs(300);
9919        let cap = Duration::from_secs(1800);
9920
9921        // No reset hint at all: the fallback.
9922        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
9923
9924        // A reset ten minutes out, well inside the cap: waited for exactly.
9925        let soon = now + jiff::SignedDuration::from_secs(600);
9926        assert_eq!(
9927            quota_wait(Some(soon), now, fallback, cap),
9928            Duration::from_secs(600)
9929        );
9930
9931        // A reset already in the past is not trusted: the fallback, not a
9932        // zero or negative wait that would spin the loop right back around.
9933        let past = now - jiff::SignedDuration::from_secs(60);
9934        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
9935
9936        // A reset further out than the cap is trusted for direction but not
9937        // for magnitude: a parsing slip must not sleep the loop for a day.
9938        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
9939        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
9940    }
9941
9942    #[test]
9943    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
9944        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9945
9946        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
9947        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
9948
9949        // Same clock reading, but it has already gone by today: read as
9950        // tomorrow's, since the CLI would not still be reporting a limit past
9951        // its own stated reset.
9952        let already_past =
9953            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
9954        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
9955
9956        assert!(
9957            parse_reset_hint("session limit reached", now, now).is_none(),
9958            "free text with no recognised shape is not guessed at"
9959        );
9960        assert!(
9961            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
9962            "an unresolvable zone name is not guessed at either"
9963        );
9964    }
9965
9966    #[test]
9967    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
9968        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9969
9970        let at = parse_reset_hint(
9971            "You've hit your usage limit. Visit \
9972             https://chatgpt.com/codex/settings/usage to purchase more \
9973             credits or try again at Sep 19th, 2026 5:10 PM.",
9974            now,
9975            now,
9976        )
9977        .expect("the codex reset wording is a recognised shape");
9978        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
9979
9980        // The month is explicit, so a date already earlier in the same
9981        // sentence-implied year than `now` is trusted as written rather than
9982        // rolled forward a year the way the bracketed shape rolls a
9983        // same-day clock reading to tomorrow.
9984        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
9985            .expect("an explicit year needs no rollover");
9986        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
9987
9988        assert!(
9989            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
9990            "a two-digit year is not the documented shape and is not guessed at"
9991        );
9992        assert!(
9993            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
9994            "a four-letter month name is not the documented three-letter abbreviation"
9995        );
9996        assert!(
9997            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
9998            "an explicit zone on the dated shape is a format nobody has \
9999             documented, and is refused rather than guessed at as UTC"
10000        );
10001    }
10002
10003    #[test]
10004    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10005        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10006        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10007
10008        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10009        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10010
10011        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10012        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10013
10014        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10015            assert!(
10016                parse_reset_hint(bad, now, recorded).is_none(),
10017                "{bad:?} must not be guessed at"
10018            );
10019        }
10020    }
10021
10022    /// A loop whose queue lives in a temp tree and whose poll interval is far
10023    /// longer than the test's patience, so anything that waits out a poll
10024    /// instead of noticing the stop fails rather than merely being slow.
10025    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10026        let config = dir.join("magi.toml");
10027        std::fs::write(
10028            &config,
10029            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10030        )
10031        .unwrap();
10032        let opts = Opts {
10033            poll: Duration::from_secs(30),
10034            config: Some(config),
10035            // The explicit fixture config keeps startup cleanup from reading
10036            // machine configuration. This fictional repository likewise
10037            // keeps any best-effort git cleanup away from this checkout.
10038            repo: dir.join("repo"),
10039            ..Opts::default()
10040        };
10041        // The status file goes in a directory that does not exist yet, so its
10042        // creation is itself evidence the loop published one. `worktrees`
10043        // must be just as fictional: the janitor reclaims worktrees under it
10044        // for real, and a test that let it fall through to
10045        // `crate::run::default_worktree_root()` would have it reclaim
10046        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10047        // which is exactly what happened before this function took the
10048        // parameter at all.
10049        let home = dir.join("home");
10050        // These control-only fixtures do not launch native workers. Give the
10051        // independently tested maintenance services a fresh cadence receipt.
10052        let stamps = home.join("service-ticks");
10053        std::fs::create_dir_all(&stamps).unwrap();
10054        for service in ["waiter", "deputies", "release-watch"] {
10055            std::fs::write(
10056                stamps.join(service),
10057                Timestamp::now().as_second().to_string(),
10058            )
10059            .unwrap();
10060        }
10061        for operation in [
10062            "conductor",
10063            "maintenance",
10064            "housekeeping",
10065            "disk-pressure",
10066            "cache",
10067            "fetch",
10068        ] {
10069            std::fs::write(
10070                stamps.join(format!("daemon-{operation}")),
10071                serde_json::to_vec(&Timestamp::now()).unwrap(),
10072            )
10073            .unwrap();
10074        }
10075        let worktrees = dir.join("wt");
10076        (
10077            opts,
10078            Queue::at(dir.join("queue")),
10079            home.join("daemon.json"),
10080            home,
10081            worktrees,
10082        )
10083    }
10084
10085    #[test]
10086    fn a_stop_is_idempotent_and_once_set_stays_set() {
10087        let stop = Stop::new();
10088        assert!(!stop.stopped());
10089
10090        stop.stop();
10091        assert!(stop.stopped());
10092        stop.stop();
10093        assert!(stop.stopped(), "a second stop is not a toggle");
10094
10095        let shared = stop.clone();
10096        assert!(
10097            shared.stopped(),
10098            "a clone is the same stop; that is how the loop and its caller share one"
10099        );
10100    }
10101
10102    #[tokio::test]
10103    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10104        for operation in ["conductor", "maintenance", "housekeeping"] {
10105            let dir = tempfile::tempdir().unwrap();
10106            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10107            opts.once = true;
10108            opts.poll = Duration::from_millis(1);
10109            let mut task = task();
10110            task.runs.push("fixture-run".into());
10111            queue.put(&mut task).unwrap();
10112            let claim = queue.claim(&task.id).unwrap();
10113
10114            // Model a live service holding the task's claim across the
10115            // scheduler's dispatch scan. No real subprocess or timed race.
10116            let directory = home.join("workers/jobs/abcdef");
10117            std::fs::create_dir_all(&directory).unwrap();
10118            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10119            crate::pr_head::try_lock_file(&lease).unwrap();
10120            let mut job = crate::worker::Job {
10121                id: "abcdef".into(),
10122                sequence: 1,
10123                kind: "daemon-service".into(),
10124                key: format!("service:daemon-{operation}"),
10125                payload: serde_json::Value::Null,
10126                generation: "fixture".into(),
10127                version: None,
10128                status: crate::worker::Status::Running,
10129                result: None,
10130                pid: Some(std::process::id()),
10131                created_at: Timestamp::now().as_second() as u64,
10132                finished_at: None,
10133            };
10134            let record = directory.join("job.json");
10135            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10136
10137            let status = Arc::new(Mutex::new(Status::new()));
10138            let stop = Stop::new();
10139            let mut drain = Box::pin(poll(
10140                &opts,
10141                &queue,
10142                &status,
10143                &home,
10144                &worktrees,
10145                &stop,
10146                DispatchLimits {
10147                    max_concurrent: 1,
10148                    pause_for_interrupts: false,
10149                    recovery_cfg: None,
10150                },
10151            ));
10152            std::future::poll_fn(|cx| {
10153                use std::future::Future;
10154                assert!(
10155                    drain.as_mut().poll(cx).is_pending(),
10156                    "--once must wait for {operation} to release its queue claim"
10157                );
10158                std::task::Poll::Ready(())
10159            })
10160            .await;
10161            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10162
10163            // An answer arrives while the service still owns the claim. A
10164            // fresh scheduling pass must apply it before declaring idle.
10165            let questions = Questions::at(home.join("questions"));
10166            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10167            questions.put(&mut q).unwrap();
10168            drop(claim);
10169            // Model services that took longer than their cadence, without a
10170            // wall-clock sleep. The final scans must not respawn them even
10171            // though their receipts now permit another periodic invocation.
10172            let expired =
10173                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10174            for service in [operation, "housekeeping"] {
10175                std::fs::write(
10176                    home.join("service-ticks").join(format!("daemon-{service}")),
10177                    &expired,
10178                )
10179                .unwrap();
10180            }
10181            job.status = crate::worker::Status::Finished;
10182            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10183            drop(lease);
10184            tokio::time::timeout(Duration::from_secs(2), drain)
10185                .await
10186                .expect("the settled service must allow the drain to finish")
10187                .unwrap();
10188            let after = queue.get(&task.id).unwrap();
10189            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10190            assert!(after.action_applied(&q.id));
10191            for service in [operation, "housekeeping"] {
10192                assert_eq!(
10193                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10194                        .unwrap(),
10195                    expired,
10196                    "the final once rescan must not restart {service}"
10197                );
10198            }
10199        }
10200    }
10201
10202    #[test]
10203    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10204        let stop = Stop::new();
10205        stop.busy.store(1, Ordering::SeqCst);
10206        assert!(
10207            !stop.finishing(),
10208            "a busy loop nobody has asked to stop is just running"
10209        );
10210
10211        stop.stop();
10212        assert!(
10213            stop.finishing(),
10214            "a stop asked for mid-run has not landed until the run is settled"
10215        );
10216
10217        stop.busy.store(0, Ordering::SeqCst);
10218        assert!(
10219            !stop.finishing(),
10220            "once the run is settled the stop has landed and there is nothing to finish"
10221        );
10222    }
10223
10224    #[test]
10225    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10226        let stop = Stop::new();
10227        stop.busy.store(2, Ordering::SeqCst);
10228        stop.stop();
10229        assert!(stop.finishing(), "two runs still in flight");
10230
10231        stop.busy.store(1, Ordering::SeqCst);
10232        assert!(
10233            stop.finishing(),
10234            "one run finished, but a sibling is still working"
10235        );
10236
10237        stop.busy.store(0, Ordering::SeqCst);
10238        assert!(
10239            !stop.finishing(),
10240            "the last run out is what actually lands the stop"
10241        );
10242    }
10243
10244    #[tokio::test]
10245    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10246        let dir = tempfile::tempdir().unwrap();
10247        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10248        let stop = Stop::new();
10249        stop.stop();
10250
10251        let began = std::time::Instant::now();
10252        tokio::time::timeout(
10253            Duration::from_secs(2),
10254            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10255        )
10256        .await
10257        .expect("a stopped loop must return, not sit out its poll interval")
10258        .expect("the loop's own setup and teardown must not fail");
10259        assert!(
10260            began.elapsed() < opts.poll,
10261            "returned only after {:?}, which is a poll interval, not a stop",
10262            began.elapsed()
10263        );
10264    }
10265
10266    #[tokio::test]
10267    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10268        let dir = tempfile::tempdir().unwrap();
10269        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10270        let stop = Stop::new();
10271
10272        // Asked for after the loop is already parked on its empty queue, which
10273        // is the case an operator tapping stop on a phone actually hits.
10274        let asker = {
10275            let stop = stop.clone();
10276            tokio::spawn(async move {
10277                tokio::time::sleep(Duration::from_millis(20)).await;
10278                stop.stop();
10279            })
10280        };
10281
10282        let began = std::time::Instant::now();
10283        tokio::time::timeout(
10284            Duration::from_secs(2),
10285            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10286        )
10287        .await
10288        .expect("a stop asked for while idle must wake the wait")
10289        .expect("the loop's own setup and teardown must not fail");
10290        asker.await.unwrap();
10291        assert!(
10292            began.elapsed() < opts.poll,
10293            "returned only after {:?}, so the stop waited on the sleep",
10294            began.elapsed()
10295        );
10296    }
10297
10298    #[tokio::test]
10299    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10300        let dir = tempfile::tempdir().unwrap();
10301        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10302        let stop = Stop::new();
10303        stop.stop();
10304
10305        tokio::time::timeout(
10306            Duration::from_secs(2),
10307            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10308        )
10309        .await
10310        .expect("a stopped loop must return")
10311        .expect("the loop's own setup and teardown must not fail");
10312
10313        assert!(
10314            home.is_dir(),
10315            "the loop did publish a status file, so its removal is the teardown and not an absence"
10316        );
10317        assert!(
10318            !status_file.exists(),
10319            "a stopped loop clears its status file"
10320        );
10321        assert!(
10322            read_status(&home).is_none(),
10323            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10324        );
10325    }
10326
10327    #[tokio::test]
10328    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10329        let dir = tempfile::tempdir().unwrap();
10330        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10331
10332        let mut settled = RunState::new(
10333            dir.path().join("repo"),
10334            "main".to_owned(),
10335            "abc1234".to_owned(),
10336            "fixture".to_owned(),
10337            Config::default(),
10338        );
10339        settled.status = RunStatus::Ready;
10340        let run_dir = home.join("runs").join(&settled.id);
10341        std::fs::create_dir_all(&run_dir).unwrap();
10342        std::fs::write(
10343            run_dir.join("run.json"),
10344            serde_json::to_string_pretty(&settled).unwrap(),
10345        )
10346        .unwrap();
10347        let questions = Questions::at(home.join("questions"));
10348        let mut question = ask::Question::new(
10349            settled.id.clone(),
10350            "review".to_owned(),
10351            "reviewer-1".to_owned(),
10352            "Continue?".to_owned(),
10353            String::new(),
10354            Vec::new(),
10355        );
10356        questions.put(&mut question).unwrap();
10357
10358        run_service_worker(
10359            &home,
10360            serde_json::to_value(ServiceWorker {
10361                opts,
10362                queue: queue.root().to_path_buf(),
10363                worktrees_root: worktrees,
10364                operation: "housekeeping".to_owned(),
10365            })
10366            .unwrap(),
10367        )
10368        .await
10369        .unwrap();
10370
10371        assert_eq!(
10372            questions.get(&question.id).unwrap().status,
10373            ask::QuestionStatus::Abandoned,
10374            "the independent housekeeping worker settles ended-run questions"
10375        );
10376    }
10377
10378    #[test]
10379    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10380        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10381
10382        assert!(
10383            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10384            "never checked before: due at once"
10385        );
10386
10387        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10388        assert!(
10389            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10390            "well inside the interval: not due yet"
10391        );
10392
10393        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10394        assert!(
10395            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10396            "exactly at the edge: not yet due, same convention as `clean::due`"
10397        );
10398
10399        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10400        assert!(
10401            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10402            "past the interval: due again"
10403        );
10404    }
10405
10406    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10407    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10408    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10409    /// and the congestion test below both need, and must not drift apart.
10410    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10411        let config = dir.join("magi.toml");
10412        // A literal (single-quoted) TOML string, not a basic one: the cache
10413        // path is a Windows path full of backslashes, and a basic string
10414        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10415        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10416        // `{{ vars.cache }}` rendering documents.
10417        std::fs::write(
10418            &config,
10419            format!(
10420                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10421                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10422                cache_dir.display()
10423            ),
10424        )
10425        .unwrap();
10426        Opts {
10427            config: Some(config),
10428            repo: dir.join("repo"),
10429            ..Opts::default()
10430        }
10431    }
10432
10433    #[tokio::test]
10434    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10435        let dir = tempfile::tempdir().unwrap();
10436        let home = dir.path().join("home");
10437        let cache_dir = dir.path().join("cache");
10438        std::fs::create_dir_all(&cache_dir).unwrap();
10439        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10440        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10441
10442        // Nobody has asked this daemon to stop, which is the ordinary case;
10443        // the skip that a stop buys is asserted by its own test below.
10444        let running = Stop::new();
10445        let mut last_checked = None;
10446        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10447        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10448            .await;
10449        assert_eq!(
10450            crate::disk::dir_size(&cache_dir),
10451            0,
10452            "over the cap on the first check ever: pruned at once, no idle queue required"
10453        );
10454        assert_eq!(last_checked, Some(t0));
10455
10456        // A fresh oversized file lands, but the next check is not due yet.
10457        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10458        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10459        maybe_prune_cache_between_runs(
10460            &opts.repo,
10461            &opts,
10462            &home,
10463            &running,
10464            &mut last_checked,
10465            too_soon,
10466        )
10467        .await;
10468        assert_eq!(
10469            crate::disk::dir_size(&cache_dir),
10470            10,
10471            "too soon since the last check: left alone rather than rescanned every call"
10472        );
10473        assert_eq!(
10474            last_checked,
10475            Some(t0),
10476            "an idle check does not reset the clock"
10477        );
10478
10479        // Once the interval elapses, the same oversized cache is caught again.
10480        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10481        maybe_prune_cache_between_runs(
10482            &opts.repo,
10483            &opts,
10484            &home,
10485            &running,
10486            &mut last_checked,
10487            due_again,
10488        )
10489        .await;
10490        assert_eq!(
10491            crate::disk::dir_size(&cache_dir),
10492            0,
10493            "due again: pruned back under the cap"
10494        );
10495    }
10496
10497    /// A stop must not queue behind housekeeping. The prune below is a
10498    /// synchronous walk of the whole cache with no await point in it, so a
10499    /// loop that entered it could not get back to its own `stopped()` test
10500    /// until the walk finished - and because no run is in flight at this
10501    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10502    /// the stop had already landed. The idle branch has always made this same
10503    /// check before reaching `janitor`; the between-runs path makes it too.
10504    #[tokio::test]
10505    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10506        let dir = tempfile::tempdir().unwrap();
10507        let home = dir.path().join("home");
10508        let cache_dir = dir.path().join("cache");
10509        std::fs::create_dir_all(&cache_dir).unwrap();
10510        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10511        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10512
10513        let stop = Stop::new();
10514        stop.stop();
10515        assert!(
10516            !stop.finishing(),
10517            "no run is in flight at a between-runs boundary, so nothing else \
10518             would tell the operator this stop had not taken effect yet"
10519        );
10520
10521        let mut last_checked = None;
10522        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10523        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10524            .await;
10525        assert_eq!(
10526            crate::disk::dir_size(&cache_dir),
10527            10,
10528            "over its cap, and due for the first check ever, but a stop outranks \
10529             it: the cap is a standing policy the next start measures again"
10530        );
10531        assert_eq!(
10532            last_checked, None,
10533            "a check that never happened must not claim the interval"
10534        );
10535    }
10536
10537    /// A backlog must not starve cache pruning. The finite cache worker runs
10538    /// independently of queue drain and must not consume any task attempts.
10539    #[tokio::test]
10540    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10541        let dir = tempfile::tempdir().unwrap();
10542        let cache_dir = dir.path().join("cache");
10543        std::fs::create_dir_all(&cache_dir).unwrap();
10544        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10545
10546        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10547        opts.poll = Duration::from_millis(20);
10548        opts.max_attempts = 1_000;
10549
10550        let queue = Queue::at(dir.path().join("queue"));
10551        for i in 0..128 {
10552            let mut task = Task::new(
10553                format!("queued work {i}"),
10554                format!("queued work {i}"),
10555                opts.repo.clone(),
10556                Source::Human,
10557            );
10558            queue.put(&mut task).unwrap();
10559        }
10560
10561        let home = dir.path().join("home");
10562        let worktrees = dir.path().join("wt");
10563        run_service_worker(
10564            &home,
10565            serde_json::to_value(ServiceWorker {
10566                opts,
10567                queue: queue.root().to_path_buf(),
10568                worktrees_root: worktrees,
10569                operation: "cache".to_owned(),
10570            })
10571            .unwrap(),
10572        )
10573        .await
10574        .unwrap();
10575        let after = queue.list();
10576        assert_eq!(after.len(), 128);
10577        assert!(
10578            after
10579                .iter()
10580                .all(|task| task.status.runnable() && task.attempts == 0)
10581        );
10582
10583        assert_eq!(
10584            crate::disk::dir_size(&cache_dir),
10585            0,
10586            "an oversized cache must not be left to grow unboundedly just because the \
10587             queue kept the loop busy the whole time"
10588        );
10589    }
10590
10591    #[test]
10592    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10593        let dir = tempfile::tempdir().unwrap();
10594        let queue = Queue::at(dir.path().join("queue"));
10595        let questions = Questions::at(dir.path().join("questions"));
10596        let mut task = task();
10597        queue.put(&mut task).unwrap();
10598
10599        let mut task_question = ask::Question::new(
10600            task.id.clone(),
10601            crate::conduct::NODE.to_owned(),
10602            "conduct".to_owned(),
10603            "Which backend?".to_owned(),
10604            String::new(),
10605            Vec::new(),
10606        );
10607        questions.put(&mut task_question).unwrap();
10608        task.block(vec![task_question.id.clone()], None);
10609        queue.put(&mut task).unwrap();
10610
10611        let mut run_question = ask::Question::new(
10612            "20260101-000000-run1".to_owned(),
10613            "review".to_owned(),
10614            "reviewer-1".to_owned(),
10615            "Run question".to_owned(),
10616            String::new(),
10617            Vec::new(),
10618        );
10619        questions.put(&mut run_question).unwrap();
10620
10621        // A question from another node whose `run` happens to equal this
10622        // task's id — the same field, filled in for an unrelated reason. Only
10623        // `crate::conduct::NODE` questions use `run` as a task id; this one
10624        // must never be touched by this reconciliation, even after release.
10625        let mut coincidental = ask::Question::new(
10626            task.id.clone(),
10627            "review".to_owned(),
10628            "reviewer-1".to_owned(),
10629            "Unrelated review question".to_owned(),
10630            String::new(),
10631            Vec::new(),
10632        );
10633        questions.put(&mut coincidental).unwrap();
10634
10635        reconcile_task_questions(&queue, &questions);
10636        assert!(questions.get(&task_question.id).unwrap().status.open());
10637        assert!(questions.get(&run_question.id).unwrap().status.open());
10638        assert!(questions.get(&coincidental.id).unwrap().status.open());
10639
10640        task.release();
10641        queue.put(&mut task).unwrap();
10642        reconcile_task_questions(&queue, &questions);
10643        assert_eq!(
10644            questions.get(&task_question.id).unwrap().status,
10645            ask::QuestionStatus::Abandoned
10646        );
10647        assert!(
10648            questions.get(&run_question.id).unwrap().status.open(),
10649            "run questions remain the run janitor's responsibility"
10650        );
10651        assert!(
10652            questions.get(&coincidental.id).unwrap().status.open(),
10653            "a non-conductor question must not be abandoned just because its \
10654             run id coincides with a task id"
10655        );
10656    }
10657
10658    #[test]
10659    fn a_freshly_started_running_task_is_never_stalled() {
10660        let dir = tempfile::tempdir().unwrap();
10661        let mut t = task();
10662        t.start("run-1".to_owned());
10663        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10664        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10665        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10666    }
10667
10668    #[test]
10669    fn a_long_running_task_with_no_live_daemon_is_stalled() {
10670        let dir = tempfile::tempdir().unwrap();
10671        let mut t = task();
10672        t.start("run-1".to_owned());
10673        t.updated_at = Timestamp::now()
10674            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10675        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10676        assert_eq!(
10677            stalled_tasks(
10678                &Queue::at(dir.path().join("q")),
10679                dir.path(),
10680                Timestamp::now()
10681            )
10682            .len(),
10683            0,
10684            "the task was never written to this queue"
10685        );
10686    }
10687
10688    #[test]
10689    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10690        let dir = tempfile::tempdir().unwrap();
10691        let mut t = task();
10692        t.id = "20260903-080340-0167".to_owned();
10693        t.start("20260903-080619-01c2".to_owned());
10694        t.updated_at = Timestamp::now()
10695            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10696
10697        let mut status = Status::new();
10698        status.current = vec![Current {
10699            worker: None,
10700            task: t.id.clone(),
10701            run: "20260903-080619-01c2".to_owned(),
10702        }];
10703        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10704
10705        assert!(
10706            !is_stalled(&t, dir.path(), Timestamp::now()),
10707            "a live daemon's own heartbeat rules out stalled, however long the task has run"
10708        );
10709    }
10710
10711    /// Rewrite a task's `updated_at` on disk directly, bypassing
10712    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
10713    /// a fixture look like it has genuinely been `running` for a while.
10714    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10715        let path = queue.path_of(id);
10716        let body = std::fs::read_to_string(&path).unwrap();
10717        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10718        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10719        v["updated_at"] = serde_json::Value::String(old.to_string());
10720        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10721    }
10722
10723    #[test]
10724    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10725        // The realistic `poll()` ordering, not `is_stalled` in isolation:
10726        // `reclaim_orphaned_running` runs first, on every poll, and settles
10727        // any `running` task whose claim it can actually take. For most
10728        // crashes that is immediate - a dead pid is proof enough for
10729        // `sweep_stale_claims` to drop the lock the same tick, and the very
10730        // next claim attempt succeeds. But a lock whose pid cannot be parsed
10731        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
10732        // `sweep_stale_claims`'s own doc), so the lock - and the claim
10733        // failure behind it - can legitimately outlive many polls. This is
10734        // exactly the gap `stalled_tasks` exists to surface well before that
10735        // six-hour sweep would: reclaim leaves the task `running`, and it
10736        // must still reach the conductor as stalled.
10737        let dir = tempfile::tempdir().unwrap();
10738        let queue = Queue::at(dir.path().join("queue"));
10739        let home = dir.path().join("home");
10740
10741        let mut t = task();
10742        t.id = "20260101-000001-lock".to_owned();
10743        t.start("run-1".to_owned());
10744        queue.put(&mut t).unwrap();
10745        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10746        std::fs::write(
10747            dir.path().join("queue").join(format!("{}.lock", t.id)),
10748            "not a pid",
10749        )
10750        .unwrap();
10751
10752        let now = Timestamp::now();
10753        assert!(
10754            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10755            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10756             and reclaim must leave the task alone"
10757        );
10758        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10759
10760        let stalled = stalled_tasks(&queue, &home, now);
10761        assert_eq!(
10762            stalled.len(),
10763            1,
10764            "reclaim's inability to claim it yet must not hide it from the conductor"
10765        );
10766        assert_eq!(stalled[0].id, t.id);
10767    }
10768
10769    #[test]
10770    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10771        let dir = tempfile::tempdir().unwrap();
10772        crate::run::set_home(dir.path().join("run-home"));
10773        let queue = Queue::at(dir.path().join("queue"));
10774        let home = dir.path().join("home");
10775        let questions = Questions::at(dir.path().join("questions"));
10776
10777        let mut t = task();
10778        t.id = "20260101-000003-dead".to_owned();
10779        t.start("missing-run".to_owned());
10780        queue.put(&mut t).unwrap();
10781        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10782
10783        // This is the real poll ordering: retain the deterministic stalled
10784        // input before a claim proves the owner is gone and reclaims it.
10785        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10786        assert_eq!(
10787            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10788            [&t.id]
10789        );
10790        assert_eq!(
10791            reclaim_orphaned_running(&queue, 2, &Default::default()),
10792            [t.id.clone()]
10793        );
10794        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10795
10796        // Reclaim drops its guard before conductor decisions are applied, so
10797        // the decision for the captured stalled input has a real write path.
10798        crate::conduct::apply(
10799            &queue,
10800            &questions,
10801            &crate::conduct::Verdict {
10802                decisions: vec![crate::conduct::Decision {
10803                    id: t.id.clone(),
10804                    recovery: Some(crate::conduct::Recovery::Requeue),
10805                    ..crate::conduct::Decision::default()
10806                }],
10807            },
10808        )
10809        .unwrap();
10810        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10811    }
10812
10813    #[test]
10814    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10815        let dir = tempfile::tempdir().unwrap();
10816        let queue = Queue::at(dir.path().join("queue"));
10817        let home = dir.path().join("home");
10818
10819        let mut fresh = task();
10820        fresh.id = "20260101-000001-aaaa".to_owned();
10821        fresh.start("run-1".to_owned());
10822        queue.put(&mut fresh).unwrap();
10823
10824        let mut old = task();
10825        old.id = "20260101-000002-bbbb".to_owned();
10826        old.start("run-2".to_owned());
10827        queue.put(&mut old).unwrap();
10828        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10829
10830        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10831        assert_eq!(stalled.len(), 1);
10832        assert_eq!(stalled[0].id, old.id);
10833    }
10834
10835    #[test]
10836    fn queued_and_finished_task_views_partition_by_status() {
10837        let dir = tempfile::tempdir().unwrap();
10838        let queue = Queue::at(dir.path().join("queue"));
10839
10840        let mut queued = task();
10841        queued.id = "20260101-000001-aaaa".to_owned();
10842        queue.put(&mut queued).unwrap();
10843
10844        let mut failed = task();
10845        failed.id = "20260101-000002-bbbb".to_owned();
10846        failed.start("run-1".to_owned());
10847        failed.fail("gate red", 5);
10848        queue.put(&mut failed).unwrap();
10849
10850        let mut held = task();
10851        held.id = "20260101-000003-cccc".to_owned();
10852        held.hold_machine(None);
10853        queue.put(&mut held).unwrap();
10854
10855        let mut running = task();
10856        running.id = "20260101-000004-dddd".to_owned();
10857        running.start("run-2".to_owned());
10858        queue.put(&mut running).unwrap();
10859
10860        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
10861        assert_eq!(queued_ids, [queued.id.clone()]);
10862
10863        let mut finished_ids: Vec<String> =
10864            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
10865        finished_ids.sort_unstable();
10866        let mut want = vec![failed.id.clone(), held.id.clone()];
10867        want.sort_unstable();
10868        assert_eq!(finished_ids, want);
10869    }
10870
10871    #[test]
10872    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
10873        for short in [false, true] {
10874            let dir = tempfile::tempdir().unwrap();
10875            let queue = Queue::at(dir.path().join("queue"));
10876            let questions = ask::Questions::at(dir.path().join("questions"));
10877            let mut running = task();
10878            running.id = "20261013-192213-feb2".into();
10879            running.start("existing-run".into());
10880            queue.put(&mut running).unwrap();
10881            let mut middle = task();
10882            middle.id = "20261013-193611-ca5b".into();
10883            middle.block(
10884                vec![if short {
10885                    "feb2".into()
10886                } else {
10887                    running.id.clone()
10888                }],
10889                None,
10890            );
10891            queue.put(&mut middle).unwrap();
10892            let mut waiting = task();
10893            waiting.id = "20261013-202849-ee37".into();
10894            waiting.block(
10895                vec![if short {
10896                    "ca5b".into()
10897                } else {
10898                    middle.id.clone()
10899                }],
10900                Some("wait for implementation".into()),
10901            );
10902            queue.put(&mut waiting).unwrap();
10903            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
10904            let inv = crate::blockers::Inventory::load(&queue, &questions);
10905            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
10906            assert!(inv.stuck().is_empty());
10907            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10908            assert!(report.quarantined.is_empty());
10909            assert!(report.asked.is_empty());
10910            resolve_blockers(&queue, &questions);
10911            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10912            assert!(questions.list().is_empty());
10913            // Finishing the transitive prerequisite alone does not satisfy
10914            // the task's direct dependency.
10915            running.succeed();
10916            queue.put(&mut running).unwrap();
10917            resolve_blockers(&queue, &questions);
10918            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
10919            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10920            middle = queue.get(&middle.id).unwrap();
10921            middle.succeed();
10922            queue.put(&mut middle).unwrap();
10923            resolve_blockers(&queue, &questions);
10924            let after = queue.get(&waiting.id).unwrap();
10925            assert_eq!(after.status, TaskStatus::Queued);
10926            assert!(after.blocked_by.is_empty());
10927            assert_eq!(after.instruction, waiting.instruction);
10928        }
10929    }
10930
10931    #[test]
10932    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
10933        for future_schema in [false, true] {
10934            let name = "20261013-193611-ca5b";
10935            let mut future = task();
10936            future.id = name.into();
10937            future.schema = crate::queue::SCHEMA + 1;
10938            let contents = if future_schema {
10939                serde_json::to_string(&future).unwrap()
10940            } else {
10941                "corrupt".into()
10942            };
10943            let dir = tempfile::tempdir().unwrap();
10944            let queue = Queue::at(dir.path().join("queue"));
10945            let questions = ask::Questions::at(dir.path().join("questions"));
10946            let mut waiting = task();
10947            waiting.id = "20261013-202849-ee37".into();
10948            waiting.block(vec!["ca5b".into()], None);
10949            queue.put(&mut waiting).unwrap();
10950            std::fs::write(queue.path_of(name), contents).unwrap();
10951            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
10952            assert!(
10953                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
10954            );
10955            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10956            assert!(report.asked.is_empty());
10957            resolve_blockers(&queue, &questions);
10958            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10959            assert!(questions.list().is_empty());
10960        }
10961        let dir = tempfile::tempdir().unwrap();
10962        let queue = Queue::at(dir.path().join("queue"));
10963        let questions = ask::Questions::at(dir.path().join("questions"));
10964        let mut waiting = task();
10965        waiting.id = "20261013-202849-ee37".into();
10966        waiting.block(vec!["ca5b".into()], None);
10967        queue.put(&mut waiting).unwrap();
10968        let mut done = task();
10969        done.id = "20261013-193611-ca5b".into();
10970        done.succeed();
10971        queue.put(&mut done).unwrap();
10972        // An unreadable second match must not disappear from uniqueness
10973        // checks just because Queue::list skips it.
10974        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
10975        assert!(queue.get("ca5b").is_err());
10976        assert_eq!(
10977            crate::queue::dependency(&queue, &questions, "ca5b"),
10978            crate::queue::Dependency::Ambiguous
10979        );
10980        resolve_blockers(&queue, &questions);
10981        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10982        assert!(report.asked.is_empty());
10983        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10984        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
10985    }
10986
10987    #[test]
10988    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
10989        for held in [false, true] {
10990            for question in [false, true] {
10991                for reference in ["ca5b", "20261013-193611-ca5b"] {
10992                    let dir = tempfile::tempdir().unwrap();
10993                    let queue = Queue::at(dir.path().join("queue"));
10994                    let questions = ask::Questions::at(dir.path().join("questions"));
10995                    let mut prerequisite = task();
10996                    prerequisite.id = "20261013-193611-ca5b".into();
10997                    prerequisite.start("existing-run".into());
10998                    queue.put(&mut prerequisite).unwrap();
10999                    let mut waiting = task();
11000                    waiting.id = "20261013-202849-ee37".into();
11001                    if held {
11002                        waiting.hold_machine(Some("waiting for separate consent".into()));
11003                    }
11004                    queue.put(&mut waiting).unwrap();
11005                    let reason = "Deleting saved data requires separate owner consent";
11006                    crate::conduct::apply(
11007                        &queue,
11008                        &questions,
11009                        &crate::conduct::Verdict {
11010                            decisions: vec![crate::conduct::Decision {
11011                                id: waiting.id.clone(),
11012                                blocked_by: vec![reference.into()],
11013                                question: question.then(|| "May the saved data be deleted?".into()),
11014                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11015                                reason: Some(reason.into()),
11016                                ..crate::conduct::Decision::default()
11017                            }],
11018                        },
11019                    )
11020                    .unwrap();
11021                    let before = queue.get(&waiting.id).unwrap();
11022                    if question {
11023                        assert_eq!(before.status, TaskStatus::Blocked);
11024                        let q = questions.get(&before.blocked_by[0]).unwrap();
11025                        assert_eq!(q.summary, "May the saved data be deleted?");
11026                        assert!(q.status.open());
11027                    } else {
11028                        assert_eq!(before.status, TaskStatus::Held);
11029                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11030                        assert!(recorded_reason.starts_with(reason));
11031                        if held {
11032                            assert!(recorded_reason.contains("waiting for separate consent"));
11033                        }
11034                    }
11035                    prerequisite.succeed();
11036                    queue.put(&mut prerequisite).unwrap();
11037                    resolve_blockers(&queue, &questions);
11038                    let after = queue.get(&waiting.id).unwrap();
11039                    assert_eq!(after.status, before.status);
11040                    assert_eq!(after.blocked_by, before.blocked_by);
11041                    assert_eq!(after.hold_reason, before.hold_reason);
11042                    assert_eq!(after.instruction, waiting.instruction);
11043                    if question {
11044                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11045                    }
11046                    assert!(
11047                        queue.next_runnable().is_none(),
11048                        "dependency completion is not consent"
11049                    );
11050                }
11051            }
11052        }
11053    }
11054
11055    #[test]
11056    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11057        let dir = tempfile::tempdir().unwrap();
11058        let queue = Queue::at(dir.path().join("queue"));
11059        let questions = ask::Questions::at(dir.path().join("questions"));
11060
11061        let mut dep = task();
11062        dep.id = "20260101-000001-dep0".to_owned();
11063        dep.succeed();
11064        queue.put(&mut dep).unwrap();
11065
11066        let mut still_going = task();
11067        still_going.id = "20260101-000002-dep1".to_owned();
11068        queue.put(&mut still_going).unwrap();
11069
11070        let mut blocked = task();
11071        blocked.id = "20260101-000003-main".to_owned();
11072        blocked.block(
11073            vec![dep.id.clone(), still_going.id.clone()],
11074            Some("waits on both".to_owned()),
11075        );
11076        queue.put(&mut blocked).unwrap();
11077
11078        resolve_blockers(&queue, &questions);
11079
11080        let after = queue.get(&blocked.id).unwrap();
11081        assert_eq!(
11082            after.status,
11083            TaskStatus::Blocked,
11084            "one dependency is still outstanding"
11085        );
11086        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11087    }
11088
11089    #[test]
11090    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11091        let dir = tempfile::tempdir().unwrap();
11092        let queue = Queue::at(dir.path().join("queue"));
11093        let questions = ask::Questions::at(dir.path().join("questions"));
11094
11095        let mut q = crate::ask::Question::new(
11096            "20260101-000001-main".to_owned(),
11097            crate::conduct::NODE.to_owned(),
11098            "conduct".to_owned(),
11099            "Which backend?".to_owned(),
11100            String::new(),
11101            Vec::new(),
11102        );
11103        questions.put(&mut q).unwrap();
11104        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11105            .unwrap();
11106        questions.put(&mut q).unwrap();
11107
11108        let mut blocked = task();
11109        blocked.id = "20260101-000001-main".to_owned();
11110        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11111        queue.put(&mut blocked).unwrap();
11112
11113        resolve_blockers(&queue, &questions);
11114
11115        let after = queue.get(&blocked.id).unwrap();
11116        assert_eq!(
11117            after.status,
11118            TaskStatus::Queued,
11119            "the only blocker resolved"
11120        );
11121        assert_eq!(after.answers.len(), 1);
11122        assert_eq!(after.answers[0].question, "Which backend?");
11123        assert_eq!(after.answers[0].answer, "SQLite");
11124
11125        // And the run this task starts next is told about it.
11126        let instruction = instruction_for(&after);
11127        assert!(instruction.contains("Which backend?"));
11128        assert!(instruction.contains("SQLite"));
11129    }
11130
11131    #[test]
11132    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11133        let dir = tempfile::tempdir().unwrap();
11134        let queue = Queue::at(dir.path().join("queue"));
11135        let questions = ask::Questions::at(dir.path().join("questions"));
11136
11137        let mut q = crate::ask::Question::new(
11138            "20260101-000001-main".to_owned(),
11139            crate::conduct::NODE.to_owned(),
11140            "conduct".to_owned(),
11141            "Is the setup done?".to_owned(),
11142            String::new(),
11143            Vec::new(),
11144        );
11145        q.abandon("no answer within 60s of asking");
11146        questions.put(&mut q).unwrap();
11147
11148        let mut blocked = task();
11149        blocked.id = "20260101-000001-main".to_owned();
11150        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11151        queue.put(&mut blocked).unwrap();
11152
11153        resolve_blockers(&queue, &questions);
11154
11155        let after = queue.get(&blocked.id).unwrap();
11156        assert_eq!(
11157            after.status,
11158            TaskStatus::Held,
11159            "never left blocked on nothing"
11160        );
11161        assert!(!after.operator_held(), "a machine hold, for triage");
11162        assert!(
11163            after
11164                .hold_reason
11165                .as_deref()
11166                .unwrap_or_default()
11167                .contains("went unanswered")
11168        );
11169    }
11170
11171    #[test]
11172    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11173        // Reproduces the reported bug (task 3958): a task held out of
11174        // attempts, blocked on a `crate::conduct` follow-up question, must
11175        // come back `held` once that question is answered - never `queued`,
11176        // whatever the answer said - or it silently re-enters the
11177        // competition queue with its attempts already exhausted.
11178        let dir = tempfile::tempdir().unwrap();
11179        let queue = Queue::at(dir.path().join("queue"));
11180        let questions = ask::Questions::at(dir.path().join("questions"));
11181
11182        let mut q = crate::ask::Question::new(
11183            "20260101-000001-main".to_owned(),
11184            crate::conduct::NODE.to_owned(),
11185            "conduct".to_owned(),
11186            "How should this be handled?".to_owned(),
11187            String::new(),
11188            Vec::new(),
11189        );
11190        questions.put(&mut q).unwrap();
11191        q.answer(crate::ask::Answer::Text(
11192            "leave it held, a human will look at it later".to_owned(),
11193        ))
11194        .unwrap();
11195        questions.put(&mut q).unwrap();
11196
11197        let mut held = task();
11198        held.id = "20260101-000001-main".to_owned();
11199        held.hold_machine(Some("out of attempts".to_owned()));
11200        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11201        queue.put(&mut held).unwrap();
11202
11203        resolve_blockers(&queue, &questions);
11204
11205        let after = queue.get(&held.id).unwrap();
11206        assert_eq!(after.status, TaskStatus::Held);
11207        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11208        assert_eq!(
11209            after.answers[0].answer,
11210            "leave it held, a human will look at it later"
11211        );
11212    }
11213
11214    #[test]
11215    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11216        let dir = tempfile::tempdir().unwrap();
11217        let queue = Queue::at(dir.path().join("queue"));
11218        let questions = ask::Questions::at(dir.path().join("questions"));
11219        let mut dep = task();
11220        dep.id = "20260101-000001-gone".to_owned();
11221        queue.put(&mut dep).unwrap();
11222        let mut blocked = task();
11223        blocked.id = "20260101-000003-main".to_owned();
11224        blocked.block(vec![dep.id.clone()], None);
11225        queue.put(&mut blocked).unwrap();
11226
11227        // Claimed, so `remove` cannot rewrite it and the resolver must.
11228        let claim = queue.claim(&blocked.id).unwrap();
11229        queue.remove(&dep.id, false, &questions).unwrap();
11230        drop(claim);
11231        resolve_blockers(&queue, &questions);
11232
11233        let after = queue.get(&blocked.id).unwrap();
11234        assert_eq!(after.status, TaskStatus::Queued);
11235        assert!(after.blocked_by.is_empty());
11236    }
11237
11238    #[test]
11239    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11240        // Reproduces the reported bug: a task blocked on a task id that was
11241        // removed (`magi task rm`, or deleted by hand) can never see that id
11242        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11243        // would otherwise leave the task `blocked` forever with no way for an
11244        // operator to find out why.
11245        let dir = tempfile::tempdir().unwrap();
11246        let queue = Queue::at(dir.path().join("queue"));
11247        let questions = ask::Questions::at(dir.path().join("questions"));
11248
11249        let mut still_going = task();
11250        still_going.id = "20260101-000002-dep1".to_owned();
11251        queue.put(&mut still_going).unwrap();
11252
11253        let mut blocked = task();
11254        blocked.id = "20260101-000003-main".to_owned();
11255        blocked.block(
11256            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11257            Some("waits on both".to_owned()),
11258        );
11259        queue.put(&mut blocked).unwrap();
11260
11261        resolve_blockers(&queue, &questions);
11262
11263        let after = queue.get(&blocked.id).unwrap();
11264        assert_eq!(
11265            after.status,
11266            TaskStatus::Held,
11267            "a missing dependency must not leave the task blocked forever"
11268        );
11269        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11270        assert!(after.blocked_by.is_empty());
11271        let reason = after.hold_reason.as_deref().unwrap_or_default();
11272        assert!(
11273            reason.contains("20260101-000001-gone"),
11274            "the missing id must be named so an operator can tell what happened: {reason}"
11275        );
11276        assert!(
11277            reason.contains(&still_going.id),
11278            "the still-valid dependency must not silently vanish from the record: {reason}"
11279        );
11280    }
11281
11282    #[test]
11283    fn instruction_for_is_unchanged_without_any_answers() {
11284        let t = task();
11285        assert_eq!(instruction_for(&t), t.instruction);
11286    }
11287
11288    #[test]
11289    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11290        let dir = tempfile::tempdir().unwrap();
11291        let q = Queue::at(dir.path().join("queue"));
11292        let src = dir.path().join("shot.png");
11293        std::fs::write(&src, "x").unwrap();
11294        let mut t = task();
11295        q.attach(&mut t, &[src]).unwrap();
11296        let paths = task_attachments(&q, &t).unwrap();
11297        assert_eq!(paths.len(), 1);
11298        assert!(paths[0].is_absolute() && paths[0].is_file());
11299        std::fs::remove_file(&paths[0]).unwrap();
11300        let err = task_attachments(&q, &t).unwrap_err().to_string();
11301        assert!(err.contains("shot.png"), "{err}");
11302    }
11303
11304    #[tokio::test]
11305    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11306        let dir = tempfile::tempdir().unwrap();
11307        let queue_path = dir.path().join("queue");
11308        let queue = Queue::at(queue_path.clone());
11309        let mut t = task();
11310        t.source = Source::Agent {
11311            run: "originating-chat".into(),
11312            node: crate::queue::CHAT_NODE.into(),
11313        };
11314        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11315            stage: "config-fetch",
11316            target: "origin/main".into(),
11317        });
11318        record_config_failure(&mut t, &fetch);
11319        t.hold_machine(Some(format!("{fetch:#}")));
11320        let fetch_key = t.chat_notice_due().unwrap();
11321        t.chat_notices.push(fetch_key.clone());
11322        queue.put(&mut t).unwrap();
11323
11324        let queue = Queue::at(queue_path);
11325        let mut t = queue.get(&t.id).unwrap();
11326        let a = dir.path().join("a.toml");
11327        let b = dir.path().join("b.toml");
11328        for (path, text, new_cause) in [
11329            (&a, "[graph", true),
11330            (&a, "[verify", false),
11331            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11332            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11333        ] {
11334            t.release_operator("test", None);
11335            std::fs::write(path, text).unwrap();
11336            let error = Config::discover_fetched(dir.path(), Some(path))
11337                .await
11338                .unwrap_err();
11339            record_config_failure(&mut t, &error);
11340            t.hold_machine(Some(format!("{error:#}")));
11341            let due = t.chat_notice_due();
11342            assert_eq!(due.is_some(), new_cause, "{error:#}");
11343            if let Some(key) = due {
11344                assert_ne!(key, fetch_key);
11345                t.chat_notices.push(key);
11346            }
11347        }
11348        t.succeed();
11349        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11350    }
11351
11352    #[test]
11353    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11354        let dir = tempfile::tempdir().unwrap();
11355        let queue_path = dir.path().join("queue");
11356        let queue = Queue::at(queue_path.clone());
11357        let mut t = task();
11358        t.source = crate::queue::Source::Agent {
11359            run: "originating-chat".into(),
11360            node: crate::queue::CHAT_NODE.into(),
11361        };
11362        let a = dir.path().join("a.png");
11363        let b = dir.path().join("b.png");
11364        std::fs::write(&a, "a").unwrap();
11365        std::fs::write(&b, "b").unwrap();
11366        queue.attach(&mut t, &[a, b]).unwrap();
11367        let paths = task_attachments(&queue, &t).unwrap();
11368        for path in &paths {
11369            std::fs::remove_file(path).unwrap();
11370        }
11371        let missing = task_attachments(&queue, &t).unwrap_err();
11372        t.attempts += 1;
11373        let reason = missing.to_string();
11374        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11375        let first = t.chat_notice_due().expect("first attachment notice");
11376        t.chat_notices.push(first.clone());
11377        queue.put(&mut t).unwrap();
11378
11379        let queue = Queue::at(queue_path.clone());
11380        let mut t = queue.get(&t.id).unwrap();
11381        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11382        t.release_operator("test", None);
11383        t.attempts += 1;
11384        let missing = task_attachments(&queue, &t).unwrap_err();
11385        t.fail_startup_target(
11386            "startup-attachments",
11387            missing.name,
11388            "same missing attachment with regenerated wording",
11389            1,
11390        );
11391        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11392
11393        std::fs::write(&paths[0], "restored").unwrap();
11394        t.release_operator("test", None);
11395        t.attempts += 1;
11396        let missing = task_attachments(&queue, &t).unwrap_err();
11397        let reason = missing.to_string();
11398        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11399        let second = t
11400            .chat_notice_due()
11401            .expect("different attachment must notify");
11402        assert_ne!(first, second);
11403        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11404    }
11405
11406    #[test]
11407    fn resumed_instruction_is_unchanged_without_any_answers() {
11408        let t = task();
11409        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11410    }
11411
11412    #[test]
11413    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11414        let mut t = task();
11415        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11416        // The run's own instruction on disk predates the answer: it is the
11417        // plain original text `Runner::start` saved before the operator was
11418        // ever asked anything.
11419        let old = t.instruction.clone();
11420
11421        let refreshed = resumed_instruction(&old, &t);
11422        assert!(refreshed.starts_with(&old), "the original text is kept");
11423        assert!(refreshed.contains("Which backend?"));
11424        assert!(refreshed.contains("SQLite"));
11425    }
11426
11427    #[test]
11428    fn resumed_instruction_keeps_an_original_answers_heading() {
11429        let mut t = task();
11430        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11431        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11432
11433        let refreshed = resumed_instruction(&t.instruction, &t);
11434
11435        assert!(
11436            refreshed.starts_with(&t.instruction),
11437            "an answers heading in the original instruction is not the appended block"
11438        );
11439        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11440        assert!(refreshed.contains("Which backend?"));
11441        assert!(refreshed.contains("SQLite"));
11442
11443        let repeated = resumed_instruction(&refreshed, &t);
11444        assert_eq!(
11445            repeated, refreshed,
11446            "only the final appended block is refreshed"
11447        );
11448    }
11449
11450    #[test]
11451    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11452        let mut t = task();
11453        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11454
11455        // A first resume appends the block; a second resume of the same run,
11456        // with no new answer in between, must reproduce exactly the same
11457        // text rather than appending the block a second time.
11458        let once = resumed_instruction(&t.instruction, &t);
11459        let twice = resumed_instruction(&once, &t);
11460        assert_eq!(once, twice);
11461        assert_eq!(once.matches("Which backend?").count(), 1);
11462
11463        // A later answer replaces the block wholesale rather than growing it.
11464        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11465        let refreshed = resumed_instruction(&once, &t);
11466        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11467        assert!(refreshed.contains("Which backend?"));
11468        assert!(refreshed.contains("Which cache?"));
11469    }
11470
11471    #[test]
11472    fn prepare_instruction_covers_all_three_starters() {
11473        let mut t = task();
11474        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11475
11476        // Start: a fresh run gets the task text plus every answer so far —
11477        // exactly `instruction_for`.
11478        assert_eq!(
11479            prepare_instruction(&Starter::Start, None, &t),
11480            Some(instruction_for(&t))
11481        );
11482
11483        // Resume: the run's prior instruction is refreshed with the answer,
11484        // not discarded and not left stale.
11485        let old = t.instruction.clone();
11486        assert_eq!(
11487            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11488            Some(resumed_instruction(&old, &t))
11489        );
11490
11491        // Review: a review-only pass builds its own instruction from the
11492        // branch's history in `crate::graph`, with no task statement at all -
11493        // this boundary must leave it alone.
11494        assert_eq!(
11495            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11496            None
11497        );
11498    }
11499
11500    #[test]
11501    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11502        assert_eq!(
11503            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11504            Starter::Review("magi/eba2/A".to_owned())
11505        );
11506    }
11507
11508    #[test]
11509    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11510        assert_eq!(
11511            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11512            Starter::Start,
11513            "a vanished review branch must not fall back to resuming the old run either"
11514        );
11515    }
11516
11517    #[test]
11518    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11519        let mut t = task();
11520        t.start("old-run".to_owned());
11521        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11522        t.release();
11523        let branch = t.review_branch.take();
11524        assert_eq!(
11525            choose_starter(branch.as_deref(), true, Some("old-run")),
11526            Starter::Review("magi/eba2/A".to_owned()),
11527            "a review wins over resuming the old run"
11528        );
11529    }
11530
11531    #[test]
11532    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11533        assert_eq!(
11534            choose_starter(None, false, Some("some-run")),
11535            Starter::Resume("some-run".to_owned())
11536        );
11537        assert_eq!(choose_starter(None, false, None), Starter::Start);
11538    }
11539
11540    #[test]
11541    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11542        let mut released = task();
11543        released.start("stalled-run".to_owned());
11544        released.requeue();
11545        let unfinished = (!released.fresh_start)
11546            .then(|| Some("stalled-run".to_owned()))
11547            .flatten();
11548        assert_eq!(
11549            choose_starter(None, false, unfinished.as_deref()),
11550            Starter::Start,
11551            "release keeps run history but must not resume it"
11552        );
11553        assert_eq!(released.runs, ["stalled-run"]);
11554    }
11555
11556    fn stopped_public_run(status: RunStatus) -> RunState {
11557        let mut state = run_state(status);
11558        state.driver_exited = true;
11559        state.config.graph.land = true;
11560        state.config.graph.review_rounds = 1;
11561        state.reviews = vec![review_round(1)];
11562        state.merge = Some(crate::run::MergeOutcome {
11563            mode: MergeMode::Pr,
11564            ok: false,
11565            detail: "landing stopped".into(),
11566            empty: false,
11567        });
11568        state.pr = Some(crate::run::PrRecord {
11569            url: "https://example.test/pull/1".into(),
11570            number: 1,
11571            state: "open".into(),
11572            checks: "red".into(),
11573            round: 1,
11574            rounds: 1,
11575            red_at_merge: Vec::new(),
11576        });
11577        state
11578    }
11579
11580    #[test]
11581    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11582        for status in [RunStatus::Blocked, RunStatus::Gating] {
11583            let home = tempfile::tempdir().unwrap();
11584            let mut state = stopped_public_run(status);
11585            state.save_under(home.path()).unwrap();
11586            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11587            assert!(!exhausted_review_budget(&state));
11588            let mut task = held_task_with(&state.id);
11589            task.release();
11590            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11591            assert_eq!(
11592                choose_starter(None, false, unfinished.as_deref()),
11593                Starter::Resume(state.id.clone())
11594            );
11595            let question = action_question(&state.id, resume_action(&state.id));
11596            assert_eq!(
11597                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11598                ActionDecision::Resume(state.id.clone())
11599            );
11600            // The control-plane command uses this same preflight before pinning.
11601            assert_eq!(
11602                crate::resume::validate(home.path(), &state.id).unwrap().id,
11603                state.id
11604            );
11605            let queue = Queue::at(home.path().join("queue"));
11606            let mut controlled = Task::new(
11607                "resume land".into(),
11608                state.instruction.clone(),
11609                state.repo.clone(),
11610                Source::Agent {
11611                    run: "talk".into(),
11612                    node: crate::queue::CHAT_NODE.into(),
11613                },
11614            );
11615            controlled.runs.push(state.id.clone());
11616            controlled.hold_machine(Some("land stopped".into()));
11617            queue.put(&mut controlled).unwrap();
11618            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11619            assert_eq!(resumed.status, TaskStatus::Queued);
11620            assert_eq!(
11621                resumed.resume_override.unwrap().pinned_run,
11622                Some(state.id.clone())
11623            );
11624            assert_eq!(resumed.attempts, 0);
11625        }
11626    }
11627
11628    #[test]
11629    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11630        for review_rounds in [0, 1] {
11631            let home = tempfile::tempdir().unwrap();
11632            let mut state = run_state(RunStatus::Blocked);
11633            state.config.graph.review_rounds = review_rounds;
11634            if review_rounds > 0 {
11635                let mut review = review_round(1);
11636                review.clean = true;
11637                state.reviews = vec![review];
11638            }
11639            state.gate_ran = true;
11640            state.gate = vec![crate::run::CommandOutcome {
11641                command: "verify".into(),
11642                code: Some(1),
11643                output_tail: "gate failed after repair budget exhausted".into(),
11644                duration_ms: 0,
11645                resource_blocked: false,
11646            }];
11647            state.save_under(home.path()).unwrap();
11648            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11649            assert!(exhausted_review_budget(&state));
11650            let mut task = held_task_with(&state.id);
11651            task.release();
11652            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11653            let question = action_question(&state.id, resume_action(&state.id));
11654            assert_ne!(
11655                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11656                ActionDecision::Resume(state.id.clone())
11657            );
11658            let error = crate::resume::validate(home.path(), &state.id)
11659                .unwrap_err()
11660                .to_string();
11661            assert!(!error.contains("review budget exhausted"), "{error}");
11662            assert!(
11663                error.contains(if review_rounds == 0 {
11664                    "review is disabled"
11665                } else {
11666                    "gate already ran"
11667                }),
11668                "{error}"
11669            );
11670
11671            // An unexecuted gate still has work to do with or without reviews.
11672            state.gate_ran = false;
11673            state.gate.clear();
11674            assert!(!exhausted_review_budget(&state));
11675            assert_eq!(
11676                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11677                Some(state.id)
11678            );
11679        }
11680    }
11681
11682    #[test]
11683    fn resource_blocked_verification_resumes_the_same_run() {
11684        for (kind, stage) in [
11685            ("cache", "clean"),
11686            ("coordination", "clean"),
11687            ("cache", "review-e2e"),
11688            ("coordination", "no-reviews"),
11689            ("coordination", "handoff"),
11690        ] {
11691            let home = tempfile::tempdir().unwrap();
11692            let mut state = run_state(RunStatus::Blocked);
11693            state.config.graph.review_rounds = 1;
11694            let mut review = review_round(1);
11695            review.clean = true;
11696            state.reviews = vec![review];
11697            if stage == "review-e2e" {
11698                let review = &mut state.reviews[0];
11699                review.clean = false;
11700                review.blocking = 1;
11701                review.e2e = vec![crate::run::CommandOutcome {
11702                    command: "verify".into(),
11703                    code: None,
11704                    output_tail: "resource wait expired".into(),
11705                    duration_ms: 0,
11706                    resource_blocked: true,
11707                }];
11708            } else if stage == "no-reviews" {
11709                state.config.graph.review_rounds = 0;
11710                state.reviews.clear();
11711            } else if stage == "handoff" {
11712                // A completed final verification can hand off to the gate
11713                // even when the review still carries contested findings.
11714                let review = &mut state.reviews[0];
11715                review.clean = false;
11716                review.blocking = 1;
11717                review.e2e = vec![crate::run::CommandOutcome {
11718                    command: "verify".into(),
11719                    code: Some(0),
11720                    output_tail: String::new(),
11721                    duration_ms: 0,
11722                    resource_blocked: false,
11723                }];
11724            }
11725            state.gate_ran = false;
11726            state.resource_block = Some(crate::run::ResourceBlock {
11727                cause: crate::run::ResourceBlockCause::Other,
11728                node: if stage == "review-e2e" {
11729                    "review"
11730                } else {
11731                    "gate"
11732                }
11733                .into(),
11734                kind: kind.into(),
11735                detail: "resource wait expired".into(),
11736                at: jiff::Timestamp::now(),
11737            });
11738            state.save_under(home.path()).unwrap();
11739            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11740            assert!(!exhausted_review_budget(&state));
11741            let mut task = held_task_with(&state.id);
11742            task.release();
11743            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11744            assert_eq!(
11745                choose_starter(None, false, unfinished.as_deref()),
11746                Starter::Resume(state.id.clone())
11747            );
11748            let question = action_question(&state.id, resume_action(&state.id));
11749            assert_eq!(
11750                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11751                ActionDecision::Resume(state.id.clone())
11752            );
11753            assert_eq!(
11754                crate::resume::validate(home.path(), &state.id).unwrap().id,
11755                state.id
11756            );
11757            let queue = Queue::at(home.path().join("queue"));
11758            let mut controlled = Task::new(
11759                "resume verification".into(),
11760                state.instruction.clone(),
11761                state.repo.clone(),
11762                Source::Agent {
11763                    run: "talk".into(),
11764                    node: crate::queue::CHAT_NODE.into(),
11765                },
11766            );
11767            controlled.runs.push(state.id.clone());
11768            controlled.hold_machine(Some("verification resource unavailable".into()));
11769            queue.put(&mut controlled).unwrap();
11770            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11771            assert_eq!(resumed.status, TaskStatus::Queued);
11772            assert_eq!(
11773                resumed.resume_override.unwrap().pinned_run,
11774                Some(state.id.clone())
11775            );
11776            assert_eq!(resumed.attempts, 0);
11777
11778            // A genuinely unresolved final review still exhausts the budget.
11779            state.config.graph.review_rounds = 1;
11780            let mut unresolved = review_round(1);
11781            unresolved.blocking = 1;
11782            state.reviews = vec![unresolved];
11783            state.resource_block = None;
11784            state.save_under(home.path()).unwrap();
11785            assert!(exhausted_review_budget(&state));
11786            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11787        }
11788    }
11789
11790    #[tokio::test]
11791    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11792        if !crate::standalone_test(
11793            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11794        ) {
11795            return;
11796        }
11797        let home = tempfile::tempdir().unwrap();
11798        let mut owner = stopped_public_run(RunStatus::Blocked);
11799        owner.save_under(home.path()).unwrap();
11800        let history = vec![owner.id.clone()];
11801        let repo = owner.repo.clone();
11802        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11803        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11804        let initial =
11805            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11806        assert!(
11807            initial.is_pending(),
11808            "a busy record must not hold or resume the task"
11809        );
11810        owner.retired_to = Some("20260101-000001-bbbb".into());
11811        owner.save_under(home.path()).unwrap();
11812        drop(lock);
11813        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11814            .await
11815            .expect("ownership lock released")
11816            .expect("read settled owner");
11817        assert!(
11818            result.is_none(),
11819            "the retired owner must not be resumed from a stale read"
11820        );
11821    }
11822
11823    #[tokio::test]
11824    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11825        if !crate::standalone_test(
11826            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11827        ) {
11828            return;
11829        }
11830        let home = tempfile::tempdir().unwrap();
11831        let mut owner = stopped_public_run(RunStatus::Blocked);
11832        let repo = tempfile::tempdir().unwrap();
11833        crate::git::git(repo.path(), &["init"]).await.unwrap();
11834        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
11835        owner.id = "20260101-000000-aaaa".into();
11836        owner.save_under(home.path()).unwrap();
11837        let mut successor = run_state(RunStatus::Blocked);
11838        successor.id = "20260101-000001-bbbb".into();
11839        successor.save_under(home.path()).unwrap();
11840        let runs = vec![owner.id.clone(), successor.id.clone()];
11841        assert_eq!(
11842            public_resume_owner(home.path(), &runs, &owner.repo)
11843                .await
11844                .unwrap()
11845                .unwrap()
11846                .id,
11847            owner.id
11848        );
11849        let subdir = owner.repo.join("nested");
11850        std::fs::create_dir(&subdir).unwrap();
11851        assert_eq!(
11852            public_resume_owner(home.path(), &runs, &subdir)
11853                .await
11854                .unwrap()
11855                .unwrap()
11856                .id,
11857            owner.id
11858        );
11859        #[cfg(unix)]
11860        {
11861            let alias = home.path().join("repo-alias");
11862            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
11863            assert_eq!(
11864                public_resume_owner(home.path(), &runs, &alias.join("nested"))
11865                    .await
11866                    .unwrap()
11867                    .unwrap()
11868                    .id,
11869                owner.id
11870            );
11871        }
11872        let different = tempfile::tempdir().unwrap();
11873        crate::git::git(different.path(), &["init"]).await.unwrap();
11874        assert!(
11875            public_resume_owner(home.path(), &runs, different.path())
11876                .await
11877                .is_err()
11878        );
11879        std::fs::remove_file(
11880            home.path()
11881                .join("runs")
11882                .join(&successor.id)
11883                .join("run.json"),
11884        )
11885        .unwrap();
11886        assert!(
11887            public_resume_owner(home.path(), &runs, &owner.repo)
11888                .await
11889                .is_err()
11890        );
11891    }
11892
11893    #[test]
11894    fn an_ordinary_release_keeps_a_resumable_run_available() {
11895        let mut released = task();
11896        released.start("stalled-run".to_owned());
11897        released.release();
11898        let unfinished = (!released.fresh_start)
11899            .then(|| Some("stalled-run".to_owned()))
11900            .flatten();
11901        assert_eq!(
11902            choose_starter(None, false, unfinished.as_deref()),
11903            Starter::Resume("stalled-run".to_owned()),
11904            "manual release must preserve the normal resume path"
11905        );
11906    }
11907
11908    #[test]
11909    fn resume_refusals_explain_admission_without_changing_task_or_run() {
11910        crate::run::pin_test_home();
11911        use crate::handover::{ResumeRefusal, resume_refusal_under};
11912        let home = tempfile::tempdir().unwrap();
11913        let mut exhausted = run_state(RunStatus::Blocked);
11914        exhausted.driver_exited = true;
11915        exhausted.config.graph.review_rounds = 3;
11916        exhausted.reviews = (1..=3).map(review_round).collect();
11917        for refusal in [
11918            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
11919            ResumeRefusal::Status(RunStatus::Ready),
11920            ResumeRefusal::Released("20261022-000000-aaaa".into()),
11921            ResumeRefusal::Retired("retirement-successor".into()),
11922            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
11923        ] {
11924            let mut state = exhausted.clone();
11925            let expected = match refusal {
11926                ResumeRefusal::Status(_) => {
11927                    state.status = RunStatus::Ready;
11928                    "status `ready`"
11929                }
11930                ResumeRefusal::Released(ref target) => {
11931                    state.released_to = Some(target.clone());
11932                    "execution was released"
11933                }
11934                ResumeRefusal::Retired(ref target) => {
11935                    state.retired_to = Some(target.clone());
11936                    "execution was retired"
11937                }
11938                ResumeRefusal::OwnershipTransferred(ref target) => {
11939                    state.pr_taken_over_by = Some(target.clone());
11940                    "PR ownership was transferred"
11941                }
11942                _ => "review budget exhausted (3/3 rounds used)",
11943            };
11944            assert_eq!(
11945                resume_refusal_under(&state, Some(home.path())),
11946                Some(refusal.clone())
11947            );
11948            assert_eq!(
11949                refusal.successor(),
11950                state
11951                    .released_to
11952                    .as_deref()
11953                    .or(state.retired_to.as_deref())
11954                    .or(state.pr_taken_over_by.as_deref())
11955            );
11956            state.save_under(home.path()).unwrap();
11957            let queue = Queue::at(home.path().join("queue"));
11958            let mut task = Task::new(
11959                "retained implementation".into(),
11960                state.instruction.clone(),
11961                state.repo.clone(),
11962                Source::Agent {
11963                    run: "talk".into(),
11964                    node: crate::queue::CHAT_NODE.into(),
11965                },
11966            );
11967            task.runs.push(state.id.clone());
11968            task.hold_machine(Some("stopped".into()));
11969            queue.put(&mut task).unwrap();
11970            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
11971            let before_run = serde_json::to_value(&state).unwrap();
11972            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
11973                .unwrap_err()
11974                .to_string();
11975            assert!(error.contains(expected), "{error}");
11976            assert!(!error.contains("only a stalled or blocked"), "{error}");
11977            if matches!(refusal, ResumeRefusal::Status(_)) {
11978                assert!(
11979                    error.contains("is final; there is nothing left to resume"),
11980                    "{error}"
11981                );
11982            }
11983            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
11984                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
11985                assert!(error.contains("review-only successor with a new review budget"));
11986                assert!(error.contains("does not resume this run"));
11987            }
11988            for target in [
11989                &state.released_to,
11990                &state.retired_to,
11991                &state.pr_taken_over_by,
11992            ]
11993            .into_iter()
11994            .flatten()
11995            {
11996                let short = if state.retired_to.as_ref() == Some(target) {
11997                    target.as_str()
11998                } else {
11999                    crate::run::short_of(target)
12000                };
12001                assert!(
12002                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12003                    "{error}"
12004                );
12005                if short != target {
12006                    assert!(!error.contains(target), "full successor id leaked: {error}");
12007                }
12008            }
12009            assert_eq!(
12010                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12011                before_task
12012            );
12013            assert_eq!(
12014                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12015                    .unwrap(),
12016                before_run
12017            );
12018            let question = action_question(&state.id, resume_action(&state.id));
12019            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12020                let ActionDecision::Refuse(detail) =
12021                    decide_action(&task, &question, phrases, |_| Ok(state.clone()))
12022                else {
12023                    panic!("refusal expected");
12024                };
12025                assert!(detail.contains(expected), "{detail}");
12026            }
12027        }
12028        // Preserve predicate ordering, while keeping every recorded destination visible.
12029        exhausted.status = RunStatus::Ready;
12030        exhausted.released_to = Some("released".into());
12031        exhausted.retired_to = Some("retired".into());
12032        exhausted.pr_taken_over_by = Some("owner".into());
12033        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12034        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12035        let detail = reason.diagnostic(&exhausted);
12036        for target in ["released", "retired", "owner"] {
12037            assert!(detail.contains(&format!("magi show {target}")));
12038        }
12039    }
12040
12041    #[test]
12042    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12043        let home = tempfile::tempdir().unwrap();
12044        let mut state = run_state(RunStatus::Blocked);
12045        state.driver_exited = true;
12046        state.config.graph.review_rounds = 1;
12047        state.reviews = vec![review_round(1)];
12048        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12049        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12050            let mut saved = state.clone();
12051            match checkpoint {
12052                "publication" => saved.pr_publication_pending = true,
12053                "approval" => {
12054                    saved.land_approval = Some(crate::run::LandApproval {
12055                        question: "approval".into(),
12056                        head: "head".into(),
12057                    })
12058                }
12059                "armed" => saved.land_armed_head = Some("head".into()),
12060                "landing" => saved.status = RunStatus::Landing,
12061                _ => {
12062                    let mut question = ask::Question::new(
12063                        saved.id.clone(),
12064                        "review".into(),
12065                        "review-1".into(),
12066                        "continue?".into(),
12067                        String::new(),
12068                        vec!["continue".into()],
12069                    );
12070                    ask::Questions::at(home.path().join("questions"))
12071                        .put(&mut question)
12072                        .unwrap();
12073                }
12074            }
12075            saved.save_under(home.path()).unwrap();
12076            assert!(
12077                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12078                "{checkpoint}"
12079            );
12080            assert!(
12081                crate::resume::validate(home.path(), &saved.id).is_ok(),
12082                "{checkpoint}"
12083            );
12084        }
12085    }
12086
12087    #[test]
12088    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12089        let mut state = run_state(RunStatus::Blocked);
12090        state.config.graph.review_rounds = 3;
12091        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12092        assert!(exhausted_review_budget(&state));
12093
12094        // One round still unused: resuming can still ask a reviewer something.
12095        state.reviews.pop();
12096        assert!(!exhausted_review_budget(&state));
12097
12098        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12099        // count: only a `Blocked` run re-enters the review loop on resume.
12100        let mut stalled = run_state(RunStatus::Stalled);
12101        stalled.config.graph.review_rounds = 1;
12102        stalled.reviews = vec![review_round(1)];
12103        assert!(!exhausted_review_budget(&stalled));
12104    }
12105
12106    fn review_round(round: usize) -> crate::run::ReviewRound {
12107        crate::run::ReviewRound {
12108            round,
12109            head: "deadbeef".to_owned(),
12110            verified_head: None,
12111            verified_at: None,
12112            reviews: Vec::new(),
12113            e2e: Vec::new(),
12114            verify_retried: false,
12115            e2e_deferred: false,
12116            e2e_defer_reason: None,
12117            fix: None,
12118            blocking: 0,
12119            answered: 1,
12120            expected: 1,
12121            clean: false,
12122            progressed: true,
12123            vote_split: false,
12124            reconsideration: Vec::new(),
12125            verdict: None,
12126        }
12127    }
12128
12129    #[test]
12130    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12131        let mut run = RunState::new(
12132            PathBuf::from("/repo"),
12133            "main".to_owned(),
12134            "abc1234def".to_owned(),
12135            "add retries".to_owned(),
12136            Config::default(),
12137        );
12138        run.status = RunStatus::Judging;
12139        run.parked = true;
12140        let mut task = Task::new(
12141            "add retries".to_owned(),
12142            "add retries".to_owned(),
12143            PathBuf::from("/repo"),
12144            crate::queue::Source::Human,
12145        );
12146        task.status = TaskStatus::Failed;
12147        task.runs = vec![run.id.clone()];
12148        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12149        assert!(with(&task, &run), "parked after judging is the case");
12150        let mut parked_task = task.clone();
12151        parked_task.status = TaskStatus::Parked;
12152        assert!(with(&parked_task, &run), "the Parked status is the case");
12153
12154        let mut not_parked = run.clone();
12155        not_parked.parked = false;
12156        not_parked.status = RunStatus::Stalled;
12157        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12158
12159        let mut fresh = task.clone();
12160        fresh.fresh_start = true;
12161        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12162
12163        let mut review = task.clone();
12164        review.review_branch = Some("magi/x/A".to_owned());
12165        assert!(!with(&review, &run), "review is ranked before resume");
12166
12167        let mut held = task.clone();
12168        held.status = TaskStatus::Held;
12169        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12170
12171        let mut released = run.clone();
12172        released.released_to = Some("20260901-000000-new1".to_owned());
12173        assert!(!with(&task, &released), "nothing left to resume into");
12174
12175        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12176            "unreadable"
12177        )));
12178    }
12179
12180    #[test]
12181    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12182        let mut released = RunState::new(
12183            PathBuf::from("/repo"),
12184            "main".to_owned(),
12185            "abc1234def".to_owned(),
12186            "add retries".to_owned(),
12187            Config::default(),
12188        );
12189        released.status = RunStatus::Blocked;
12190        assert_eq!(
12191            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12192            Some(released.id.clone())
12193        );
12194        released.released_to = Some("20260901-000000-new1".to_owned());
12195        assert_eq!(
12196            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12197            None,
12198            "there is nothing left to resume it into"
12199        );
12200    }
12201
12202    #[test]
12203    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12204        // Mirrors the failure this exists to close: a task's last run ended
12205        // `Blocked` with the review budget spent, `crate::conduct` chose
12206        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12207        // evidence), and without this check `attempt` would go on treating
12208        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12209        // review loop iterates zero times over an already-spent budget, so
12210        // the resumed run settles right back to `Blocked` having asked nobody
12211        // anything, and `Requeue`'s promised fresh competition never happens.
12212        let mut exhausted = RunState::new(
12213            PathBuf::from("/repo"),
12214            "main".to_owned(),
12215            "abc1234def".to_owned(),
12216            "add retries".to_owned(),
12217            Config::default(),
12218        );
12219        exhausted.status = RunStatus::Blocked;
12220        exhausted.config.graph.review_rounds = 1;
12221        exhausted.reviews = vec![review_round(1)];
12222
12223        assert_eq!(
12224            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12225            None,
12226            "an exhausted `Blocked` run must not be offered as resumable"
12227        );
12228
12229        // A `Blocked` run with rounds still unused is genuinely worth
12230        // resuming, and must still be found.
12231        let mut has_budget_left = RunState::new(
12232            PathBuf::from("/repo"),
12233            "main".to_owned(),
12234            "abc1234def".to_owned(),
12235            "add retries".to_owned(),
12236            Config::default(),
12237        );
12238        has_budget_left.status = RunStatus::Blocked;
12239        has_budget_left.config.graph.review_rounds = 3;
12240        has_budget_left.reviews = vec![review_round(1)];
12241
12242        assert_eq!(
12243            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12244                Ok(has_budget_left.clone())
12245            }),
12246            Some(has_budget_left.id.clone())
12247        );
12248    }
12249
12250    #[test]
12251    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12252        let mut run = RunState::new(
12253            PathBuf::from("/repo"),
12254            "main".to_owned(),
12255            "abc1234def".to_owned(),
12256            "add retries".to_owned(),
12257            Config::default(),
12258        );
12259        run.status = RunStatus::Blocked;
12260        run.config.graph.review_rounds = 1;
12261        run.reviews = vec![review_round(1)];
12262        run.pr_publication_pending = true;
12263        assert_eq!(
12264            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12265            Some(run.id.clone()),
12266            "a spent review budget must not turn a failed publication into a re-competition"
12267        );
12268    }
12269
12270    #[test]
12271    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12272        let mut task = Task::new(
12273            "recover work".into(),
12274            "recover work".into(),
12275            PathBuf::from("/repo"),
12276            crate::queue::Source::Human,
12277        );
12278        let mut history = std::collections::BTreeMap::new();
12279        for index in 0..8 {
12280            let mut run = run_state(RunStatus::Blocked);
12281            run.id = format!("20260101-000000-{index:04}");
12282            run.base_commit = format!("upstream-{index}");
12283            // Seven empty newer attempts must not erase the old recovery owner.
12284            if index > 0 {
12285                run.candidates.clear();
12286            }
12287            task.runs.extend([run.id.clone(), run.id.clone()]);
12288            history.insert(run.id.clone(), run);
12289            task.requeue();
12290        }
12291        let check = |task: &Task, starter: &Starter, limit| {
12292            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12293        };
12294        assert!(
12295            check(&task, &Starter::Start, 8)
12296                .unwrap()
12297                .contains("8 unretired")
12298        );
12299        assert!(check(&task, &Starter::Start, 9).is_none());
12300        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12301        task.release_operator("owner", None);
12302        assert_eq!(task.attempts, 0);
12303        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12304        assert!(check(&restored, &Starter::Start, 8).is_some());
12305        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12306        assert!(check(&restored, &Starter::Start, 0).is_none());
12307    }
12308
12309    #[test]
12310    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12311        let mut task = Task::new(
12312            "recover work".into(),
12313            "recover work".into(),
12314            PathBuf::from("/repo"),
12315            crate::queue::Source::Human,
12316        );
12317        let mut run = run_state(RunStatus::Superseded);
12318        run.candidates.clear();
12319        task.runs.push(run.id.clone());
12320        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12321        run.retired_to = Some("authority".into());
12322        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12323        run.retired_to = None;
12324        run.released_to = Some("authority".into());
12325        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12326        assert!(
12327            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12328                .unwrap()
12329                .contains("Cannot verify")
12330        );
12331        // Resuming an existing owner needs no new inventory or worktree budget.
12332        assert!(
12333            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12334                panic!("resume must not load historical attempts")
12335            })
12336            .is_none()
12337        );
12338    }
12339
12340    #[test]
12341    fn retired_resume_requires_a_valid_same_repository_authority() {
12342        let mut source = run_state(RunStatus::Blocked);
12343        let mut empty = run_state(RunStatus::Blocked);
12344        empty.retired_to = Some(source.id.clone());
12345        let runs = vec![source.id.clone(), empty.id.clone()];
12346        let resolve = |source: &RunState, empty: &RunState| {
12347            unfinished_run_with(&runs, "fixture", |id| {
12348                if id == source.id {
12349                    Ok(source.clone())
12350                } else if id == empty.id {
12351                    Ok(empty.clone())
12352                } else {
12353                    bail!("unreadable authority")
12354                }
12355            })
12356        };
12357        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12358        assert_eq!(
12359            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12360            Starter::Resume(source.id.clone())
12361        );
12362        source.retired_to = Some(empty.id.clone());
12363        assert!(
12364            resolve(&source, &empty).is_none(),
12365            "cycles do not revive obsolete runs"
12366        );
12367        source.retired_to = None;
12368        source.repo = PathBuf::from("/another-repository");
12369        assert!(resolve(&source, &empty).is_none());
12370        source.repo = empty.repo.clone();
12371        source.released_to = Some("later".into());
12372        assert!(resolve(&source, &empty).is_none());
12373        empty.retired_to = Some("unlisted-run".into());
12374        assert!(resolve(&source, &empty).is_none());
12375    }
12376
12377    #[test]
12378    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12379        // A task whose history holds an *older* run that still looks
12380        // resumable (say, a competition `Runner::review` was started
12381        // alongside after that older run went `Stalled`) and a *newest* run
12382        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12383        // on this task must mean a fresh competition — falling back to the
12384        // stale, superseded `Stalled` run instead would resurrect history
12385        // nothing asked to revisit and silently defeat the requeue.
12386        let mut older_stalled = RunState::new(
12387            PathBuf::from("/repo"),
12388            "main".to_owned(),
12389            "abc1234def".to_owned(),
12390            "add retries".to_owned(),
12391            Config::default(),
12392        );
12393        older_stalled.status = RunStatus::Stalled;
12394
12395        let mut newest_exhausted = RunState::new(
12396            PathBuf::from("/repo"),
12397            "main".to_owned(),
12398            "abc1234def".to_owned(),
12399            "add retries".to_owned(),
12400            Config::default(),
12401        );
12402        newest_exhausted.status = RunStatus::Blocked;
12403        newest_exhausted.config.graph.review_rounds = 1;
12404        newest_exhausted.reviews = vec![review_round(1)];
12405
12406        assert_eq!(
12407            unfinished_run_with(
12408                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12409                "t",
12410                |_| Ok(newest_exhausted.clone())
12411            ),
12412            None,
12413            "the newest run is exhausted, so nothing here is worth resuming - \
12414             least of all the older, already-superseded run"
12415        );
12416    }
12417
12418    #[test]
12419    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12420        assert_eq!(
12421            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12422                Err(anyhow::anyhow!("fixture is absent"))
12423            }),
12424            None
12425        );
12426    }
12427
12428    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12429        let mut q = ask::Question::new(
12430            run.to_owned(),
12431            "implement".to_owned(),
12432            "impl-A".to_owned(),
12433            "continue?".to_owned(),
12434            String::new(),
12435            vec!["resume で続行する".to_owned(), "other".to_owned()],
12436        );
12437        q.actions.insert("resume で続行する".to_owned(), action);
12438        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12439            .unwrap();
12440        q
12441    }
12442
12443    fn held_task_with(run: &str) -> Task {
12444        let mut t = task();
12445        t.runs = vec![run.to_owned()];
12446        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12447        t
12448    }
12449
12450    fn resume_action(run: &str) -> ask::ChoiceAction {
12451        ask::ChoiceAction::Resume { run: run.into() }
12452    }
12453
12454    #[test]
12455    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12456        for parked in [false, true] {
12457            let mut t = task();
12458            t.start("A".into());
12459            t.start("B".into());
12460            assert_eq!(t.runs, vec!["A", "B"]);
12461            t.start("A".into());
12462            let mut resumed = run_state(RunStatus::Blocked);
12463            resumed.id = "A".into();
12464            resumed.parked = parked;
12465            resumed.driver_exited = true;
12466            t.hold_machine(Some("resumed run stopped".into()));
12467            let q = action_question("A", resume_action("A"));
12468            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12469            assert_eq!(
12470                decide_action(&t, &q, &PHRASES_EN, |id| {
12471                    assert_eq!(id, "A");
12472                    Ok(resumed.clone())
12473                }),
12474                ActionDecision::Resume("A".into())
12475            );
12476            assert_eq!(
12477                action_standing(&t, &action_question("B", resume_action("B"))),
12478                ActionStanding::Stale
12479            );
12480            t.release_operator("cli", None);
12481            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12482                assert_eq!(id, "A");
12483                Ok(resumed.clone())
12484            });
12485            assert_eq!(
12486                choose_starter(None, false, unfinished.as_deref()),
12487                Starter::Resume("A".into())
12488            );
12489            assert_eq!(t.runs, vec!["B", "A"]);
12490        }
12491    }
12492
12493    #[test]
12494    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12495        let mut state = crate::land::tests::repair_state(true, true);
12496        state.status = RunStatus::Landing;
12497        state.parked = true;
12498        state.driver_exited = true;
12499        let mut q = ask::Question::new(
12500            state.id.clone(),
12501            land::APPROVAL_NODE.into(),
12502            "land".into(),
12503            "Merge?".into(),
12504            String::new(),
12505            vec![land::APPROVE.into(), land::HOLD.into()],
12506        );
12507        q.id = state.id.clone();
12508        state.land_approval = Some(crate::run::LandApproval {
12509            question: q.id.clone(),
12510            head: "current-head".into(),
12511        });
12512        assert!(land::upgrade_repair_choice(&mut q, &state));
12513        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12514        let mut task = held_task_with(&state.id);
12515        task.status = TaskStatus::Parked;
12516        assert_eq!(
12517            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12518            ActionDecision::Resume(state.id.clone())
12519        );
12520        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12521        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12522        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12523        assert_eq!(
12524            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12525            ActionDecision::Resume(state.id.clone()),
12526            "a repair answer newer than the manual hold resumes the existing owner"
12527        );
12528        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12529        for answered_at in [q.answered_at, None] {
12530            let mut older = q.clone();
12531            older.answered_at = answered_at;
12532            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
12533                panic!("a later manual hold must prevent dispatch")
12534            });
12535            let ActionDecision::Refuse(reason) = refused else {
12536                panic!("expected an actionable refusal, got {refused:?}");
12537            };
12538            assert!(reason.contains("later operator decision"));
12539            assert!(reason.contains(&format!("magi task release {}", task.id)));
12540        }
12541        task.operator_decided_at = None;
12542        let mut superseded = state.clone();
12543        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12544        assert_eq!(
12545            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
12546            ActionDecision::Stale
12547        );
12548        for case in 1..4 {
12549            let mut changed = state.clone();
12550            match case {
12551                1 => changed.status = RunStatus::Blocked,
12552                2 => changed.released_to = Some("new-owner".into()),
12553                _ => changed.land_approval.as_mut().unwrap().head.clear(),
12554            }
12555            assert!(matches!(
12556                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
12557                ActionDecision::Refuse(_)
12558            ));
12559        }
12560        assert!(matches!(
12561            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
12562            ActionDecision::Refuse(_)
12563        ));
12564        task.runs.push("replacement".into());
12565        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12566        assert_eq!(
12567            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
12568                "old owner must not load"
12569            )),
12570            ActionDecision::Stale
12571        );
12572    }
12573
12574    #[test]
12575    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12576        let mut state = crate::land::tests::repair_state(true, true);
12577        state.status = RunStatus::Landing;
12578        state.parked = true;
12579        state.driver_exited = true;
12580        let mut q = ask::Question::new(
12581            state.id.clone(),
12582            land::APPROVAL_NODE.into(),
12583            "land".into(),
12584            "Merge?".into(),
12585            String::new(),
12586            vec![land::APPROVE.into(), land::HOLD.into()],
12587        );
12588        q.id = state.id.clone();
12589        state.land_approval = Some(crate::run::LandApproval {
12590            question: q.id.clone(),
12591            head: "current-head".into(),
12592        });
12593        state.save().unwrap();
12594        land::upgrade_repair_choice(&mut q, &state);
12595        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12596        Questions::open().put(&mut q).unwrap();
12597        let tmp = tempfile::tempdir().unwrap();
12598        let queue = Queue::at(tmp.path().join("queue"));
12599        let mut task = held_task_with(&state.id);
12600        task.status = TaskStatus::Parked;
12601        queue.put(&mut task).unwrap();
12602        let empty = Arc::new(tokio::sync::Semaphore::new(0));
12603        let free = Arc::new(tokio::sync::Semaphore::new(1));
12604        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12605        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12606        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12607        assert!(claim.permit.is_some());
12608        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12609        drop(claim);
12610        Questions::open()
12611            .update(&q.id, |q| {
12612                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12613                Ok(())
12614            })
12615            .unwrap();
12616        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12617        assert!(claim.permit.is_none());
12618        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12619    }
12620
12621    #[test]
12622    fn decide_action_resumes_only_the_latest_resumable_run() {
12623        let t = held_task_with("r1");
12624        let q = action_question("r1", resume_action("r1"));
12625        let load = |s: RunState| move |_: &str| Ok(s);
12626        assert_eq!(
12627            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
12628            ActionDecision::Resume("r1".into())
12629        );
12630        // Not the latest run of the task.
12631        let q_other = action_question("r1", resume_action("r0"));
12632        assert!(matches!(
12633            decide_action(
12634                &t,
12635                &q_other,
12636                &PHRASES_EN,
12637                load(run_state(RunStatus::Blocked))
12638            ),
12639            ActionDecision::Refuse(_)
12640        ));
12641        // A finished run cannot make progress.
12642        assert!(matches!(
12643            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
12644            ActionDecision::Refuse(_)
12645        ));
12646        // A released one either.
12647        let mut released = run_state(RunStatus::Blocked);
12648        released.released_to = Some("elsewhere".into());
12649        assert!(matches!(
12650            decide_action(&t, &q, &PHRASES_EN, load(released)),
12651            ActionDecision::Refuse(_)
12652        ));
12653        // Unreadable state is a refusal, never a fresh competition.
12654        assert!(matches!(
12655            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
12656            ActionDecision::Refuse(_)
12657        ));
12658    }
12659
12660    #[test]
12661    fn decide_action_ignores_a_question_about_an_earlier_run() {
12662        let mut t = held_task_with("r1");
12663        t.runs.push("r2".to_owned());
12664        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12665        assert_eq!(
12666            decide_action(
12667                &t,
12668                &action_question("r1", ask::ChoiceAction::Done),
12669                &PHRASES_EN,
12670                never
12671            ),
12672            ActionDecision::Stale
12673        );
12674    }
12675
12676    #[test]
12677    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
12678        let mut t = held_task_with("r1");
12679        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12680        assert_eq!(
12681            decide_action(
12682                &t,
12683                &action_question("r1", ask::ChoiceAction::Requeue),
12684                &PHRASES_EN,
12685                never
12686            ),
12687            ActionDecision::Requeue
12688        );
12689        let done_q = action_question("r1", ask::ChoiceAction::Done);
12690        assert_eq!(
12691            decide_action(&t, &done_q, &PHRASES_EN, never),
12692            ActionDecision::Done
12693        );
12694        t.mark_action_applied(&done_q.id);
12695        assert_eq!(
12696            decide_action(&t, &done_q, &PHRASES_EN, never),
12697            ActionDecision::Skip
12698        );
12699
12700        // A plain answer (no action for that label) does nothing.
12701        let mut plain = action_question("r1", ask::ChoiceAction::Done);
12702        plain.actions.clear();
12703        assert_eq!(
12704            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
12705            ActionDecision::Skip
12706        );
12707        // A running task is left alone.
12708        let mut running = held_task_with("r1");
12709        running.status = TaskStatus::Running;
12710        assert_eq!(
12711            decide_action(
12712                &running,
12713                &action_question("r1", ask::ChoiceAction::Done),
12714                &PHRASES_EN,
12715                never
12716            ),
12717            ActionDecision::Skip
12718        );
12719    }
12720
12721    #[test]
12722    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
12723        crate::run::pin_test_home();
12724        for legacy in [false, true] {
12725            let dir = tempfile::tempdir().unwrap();
12726            let queue = Queue::at(dir.path().join("queue"));
12727            let questions = Questions::at(dir.path().join("questions"));
12728            let run = "20260101-000000-hold";
12729            let mut task = held_task_with(run);
12730            task.status = TaskStatus::Parked;
12731            let mut q = ask::Question::new(
12732                run.into(),
12733                land::APPROVAL_NODE.into(),
12734                "land".into(),
12735                "Repair?".into(),
12736                String::new(),
12737                vec![land::REPAIR.into()],
12738            );
12739            q.actions.insert(land::REPAIR.into(), resume_action(run));
12740            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12741            // Deterministically order the answer before the actual manual hold.
12742            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12743            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
12744            questions.put(&mut q).unwrap();
12745            task.hold_manual(Some("Keep this PR paused".into()));
12746            if legacy {
12747                task.hold_source = None;
12748            }
12749            queue.put(&mut task).unwrap();
12750
12751            apply_task_choice_actions(&queue, &questions, dir.path());
12752            let after = queue.get(&task.id).unwrap();
12753            assert!(after.operator_held());
12754            assert_eq!(after.hold_source, task.hold_source);
12755            assert_eq!(after.operator_decided_at, task.operator_decided_at);
12756            assert_eq!(after.runs, task.runs);
12757            assert_eq!(after.instruction, task.instruction);
12758            assert!(after.resume_override.is_none());
12759            assert!(after.action_applied(&q.id));
12760            let reason = after.hold_reason.as_deref().unwrap();
12761            assert!(reason.starts_with("Keep this PR paused"));
12762            assert!(reason.contains("later operator decision"));
12763            assert!(reason.contains(&format!("magi task release {}", task.id)));
12764
12765            for recovery in [
12766                crate::conduct::Recovery::Review,
12767                crate::conduct::Recovery::Requeue,
12768            ] {
12769                crate::conduct::apply(
12770                    &queue,
12771                    &questions,
12772                    &crate::conduct::Verdict {
12773                        decisions: vec![crate::conduct::Decision {
12774                            id: task.id.clone(),
12775                            recovery: Some(recovery),
12776                            ..Default::default()
12777                        }],
12778                    },
12779                )
12780                .unwrap();
12781            }
12782            // Reconciliation is idempotent, and automatic recovery cannot
12783            // reopen this owner after it observes the rejected repair answer.
12784            apply_task_choice_actions(&queue, &questions, dir.path());
12785            let still_held = queue.get(&task.id).unwrap();
12786            assert!(still_held.operator_held());
12787            assert_eq!(still_held.hold_reason, after.hold_reason);
12788            assert_eq!(still_held.runs, task.runs);
12789            assert!(still_held.review_branch.is_none());
12790            assert!(!still_held.fresh_start);
12791            assert!(queue.next_runnable().is_none());
12792        }
12793    }
12794
12795    #[test]
12796    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
12797        for held in [false, true] {
12798            for retry in [false, true] {
12799                let dir = tempfile::tempdir().unwrap();
12800                let queue = Queue::at(dir.path().join("queue"));
12801                let questions = Questions::at(dir.path().join("questions"));
12802                let home = dir.path().join("home");
12803                let mut t = task();
12804                if held {
12805                    t.hold_machine(Some("driver state unknown".into()));
12806                }
12807                queue.put(&mut t).unwrap();
12808                let verdict = serde_json::from_value(serde_json::json!({
12809                    "decisions": [{
12810                        "id": t.id,
12811                        "question": "Driver state unknown; retry the checks or hold?",
12812                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
12813                        "actions": {
12814                            "daemon: recheck and retry": {"do": "requeue"},
12815                            "daemon: hold the task": {"do": "hold"}
12816                        }
12817                    }]
12818                }))
12819                .unwrap();
12820                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
12821                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12822                let mut q = questions.list().pop().unwrap();
12823                let choice = if retry {
12824                    "daemon: recheck and retry"
12825                } else {
12826                    "daemon: hold the task"
12827                };
12828                assert_eq!(q.actions.len(), 2);
12829                q.answer(ask::Answer::Choice(choice.into())).unwrap();
12830                questions.put(&mut q).unwrap();
12831
12832                // A Web answer does not remove the deputy's fresh lease.
12833                questions.beat(&q.id, ask::WaiterKind::Deputy);
12834                for _ in 0..2 {
12835                    resolve_blockers(&queue, &questions);
12836                    apply_task_choice_actions(&queue, &questions, &home);
12837                    let waiting = queue.get(&t.id).unwrap();
12838                    assert_eq!(waiting.status, TaskStatus::Blocked);
12839                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
12840                    assert!(waiting.answers.is_empty());
12841                    assert!(!waiting.action_applied(&q.id));
12842                    assert!(runnable(&queue).is_empty());
12843                    let free = Arc::new(tokio::sync::Semaphore::new(1));
12844                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
12845                }
12846                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12847
12848                // Releasing the blocker and applying the operation share one save.
12849                resolve_blockers(&queue, &questions);
12850                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12851                apply_task_choice_actions(&queue, &questions, &home);
12852                let after = queue.get(&t.id).unwrap();
12853                assert_eq!(
12854                    after.status,
12855                    if retry {
12856                        TaskStatus::Queued
12857                    } else {
12858                        TaskStatus::Held
12859                    }
12860                );
12861                assert!(after.action_applied(&q.id));
12862                assert_eq!(after.operator_held(), !retry);
12863                assert_eq!(after.answers.len(), 1);
12864
12865                // A later operator decision must not replay this answer.
12866                let mut changed = after;
12867                if retry {
12868                    changed.hold_manual(Some("later hold".into()));
12869                } else {
12870                    changed.release_operator("test", None);
12871                }
12872                let expected = changed.status;
12873                queue.put(&mut changed).unwrap();
12874                apply_task_choice_actions(&queue, &questions, &home);
12875                assert_eq!(queue.get(&t.id).unwrap().status, expected);
12876            }
12877        }
12878    }
12879
12880    #[test]
12881    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
12882        let dir = tempfile::tempdir().unwrap();
12883        let queue = Queue::at(dir.path().join("queue"));
12884        let questions = Questions::at(dir.path().join("questions"));
12885        let home = dir.path().join("home");
12886        let mut state = run_state(RunStatus::Blocked);
12887        state.id = "20260101-000000-act1".to_owned();
12888        state.save_under(&home).unwrap();
12889
12890        let mut t = held_task_with(&state.id);
12891        queue.put(&mut t).unwrap();
12892        let mut q = action_question(&state.id, resume_action(&state.id));
12893        questions.put(&mut q).unwrap();
12894
12895        apply_task_choice_actions(&queue, &questions, &home);
12896        let after = queue.get(&t.id).unwrap();
12897        assert_eq!(after.status, TaskStatus::Queued);
12898        assert!(!after.fresh_start);
12899        assert!(after.action_applied(&q.id));
12900        let pin = after.resume_override.clone().unwrap();
12901        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
12902        assert!(pin.forced);
12903
12904        // Held again later: the same answer does not release it a second time.
12905        let mut again = queue.get(&t.id).unwrap();
12906        again.hold_machine(Some("later".into()));
12907        queue.put(&mut again).unwrap();
12908        apply_task_choice_actions(&queue, &questions, &home);
12909        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12910    }
12911
12912    #[test]
12913    fn a_delivered_answer_is_still_acted_on_exactly_once() {
12914        let dir = tempfile::tempdir().unwrap();
12915        let queue = Queue::at(dir.path().join("queue"));
12916        let questions = Questions::at(dir.path().join("questions"));
12917        let home = dir.path().join("home");
12918        let mut state = run_state(RunStatus::Blocked);
12919        state.id = "20260101-000000-act2".to_owned();
12920        state.save_under(&home).unwrap();
12921
12922        let mut t = held_task_with(&state.id);
12923        queue.put(&mut t).unwrap();
12924        let mut q = action_question(&state.id, resume_action(&state.id));
12925        q.answer_delivered = true;
12926        questions.put(&mut q).unwrap();
12927
12928        // Delivered, and the agent then died: the task is still held, so the
12929        // chosen action applies.
12930        apply_task_choice_actions(&queue, &questions, &home);
12931        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12932        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
12933
12934        // Held again: the same answer does nothing a second time.
12935        let mut again = queue.get(&t.id).unwrap();
12936        again.hold_machine(Some("later".into()));
12937        queue.put(&mut again).unwrap();
12938        apply_task_choice_actions(&queue, &questions, &home);
12939        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12940    }
12941
12942    #[test]
12943    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
12944        let dir = tempfile::tempdir().unwrap();
12945        let queue = Queue::at(dir.path().join("queue"));
12946        let questions = Questions::at(dir.path().join("questions"));
12947        let home = dir.path().join("home");
12948        let mut state = run_state(RunStatus::Blocked);
12949        state.id = "20260101-000000-act3".to_owned();
12950        state.save_under(&home).unwrap();
12951        let mut t = held_task_with(&state.id);
12952        queue.put(&mut t).unwrap();
12953        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
12954        questions.put(&mut q).unwrap();
12955
12956        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
12957        apply_task_choice_actions(&queue, &questions, &home);
12958        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12959
12960        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12961        apply_task_choice_actions(&queue, &questions, &home);
12962        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12963    }
12964
12965    #[test]
12966    fn action_standing_tells_the_reasons_apart() {
12967        let mut t = held_task_with("r1");
12968        let q = action_question("r1", ask::ChoiceAction::Requeue);
12969        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12970        let mut plain = q.clone();
12971        plain.actions.clear();
12972        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
12973
12974        // Applied wins over everything, even a running task.
12975        t.mark_action_applied(&q.id);
12976        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
12977
12978        // A newer attempt running: the old question is Stale, not Busy.
12979        let mut t = held_task_with("r1");
12980        t.start("r2".to_owned());
12981        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
12982        // The same question about the latest run just waits.
12983        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
12984        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12985        t.status = TaskStatus::Blocked;
12986        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12987
12988        // A conductor question is keyed by the task, never stale.
12989        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
12990        c.node = crate::conduct::NODE.to_owned();
12991        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
12992        assert!(!ActionStanding::Busy.daemon_owns());
12993    }
12994
12995    #[test]
12996    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
12997        let dir = tempfile::tempdir().unwrap();
12998        let queue = Queue::at(dir.path().join("queue"));
12999        let questions = Questions::at(dir.path().join("questions"));
13000        let home = dir.path().join("home");
13001        let mut state = run_state(RunStatus::Blocked);
13002        state.id = "20260101-000000-act4".to_owned();
13003        state.save_under(&home).unwrap();
13004        let mut t = held_task_with(&state.id);
13005        t.status = TaskStatus::Running;
13006        queue.put(&mut t).unwrap();
13007        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13008        q.cwd = Some(dir.path().display().to_string());
13009        questions.put(&mut q).unwrap();
13010
13011        // While the task runs the daemon will not act, so the waiter still
13012        // delivers the word to the dead asker's seat ...
13013        let running = queue.get(&t.id).unwrap();
13014        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13015        assert!(matches!(
13016            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13017            crate::waiter::Action::Deliver(_)
13018        ));
13019        // ... and the daemon waits while the task runs, then applies once.
13020        apply_task_choice_actions(&queue, &questions, &home);
13021        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13022        let mut back = queue.get(&t.id).unwrap();
13023        back.hold_machine(Some("later".into()));
13024        queue.put(&mut back).unwrap();
13025        apply_task_choice_actions(&queue, &questions, &home);
13026        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13027        let mut again = queue.get(&t.id).unwrap();
13028        again.hold_machine(Some("again".into()));
13029        queue.put(&mut again).unwrap();
13030        apply_task_choice_actions(&queue, &questions, &home);
13031        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13032    }
13033}