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.execution_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.clone(),
519                        run: task.execution_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 task.stale_question(q) {
887        ActionStanding::Stale
888    } else if q.chosen_action().is_none() {
889        ActionStanding::NoAction
890    } else if task.action_applied(&q.id) {
891        ActionStanding::Applied
892    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
893        ActionStanding::Stale
894    } else if matches!(
895        task.status,
896        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
897    ) {
898        ActionStanding::Busy
899    } else {
900        ActionStanding::Pending
901    }
902}
903
904/// What [`decide_action`] concluded about one answered question.
905#[derive(Debug, Clone, PartialEq, Eq)]
906enum ActionDecision {
907    /// Nothing to do now (no action, already applied, or the task is busy).
908    Skip,
909    /// Continue the named run instead of competing again.
910    Resume(String),
911    /// Requeue as a fresh competition.
912    Requeue,
913    /// Hold the task by explicit operator choice.
914    Hold,
915    /// Close the task as done.
916    Done,
917    /// The question is about an earlier attempt than the task's latest; it
918    /// is recorded as handled and changes nothing.
919    Stale,
920    /// The action cannot be carried out; hold the task and say why. Never
921    /// falls back to something else, because the operator chose this one.
922    Refuse(String),
923}
924
925/// Decide what the choice answered on `q` means for `task`. `load` reads a
926/// run's state, as with [`unfinished_run_with`]. `home` must name that same
927/// store for driver leases and question checkpoints.
928///
929/// `Resume` only fires on the task's *latest* run, and only while that run
930/// could actually make progress ([`RunStatus::resumable`], not released, review
931/// budget left); an answer naming anything else is refused rather than
932/// reinterpreted as a fresh competition.
933fn decide_action<F>(
934    home: &Path,
935    task: &Task,
936    q: &ask::Question,
937    p: &Phrases,
938    load: F,
939) -> ActionDecision
940where
941    F: FnOnce(&str) -> Result<RunState>,
942{
943    if task.stale_question(q) {
944        return ActionDecision::Stale;
945    }
946    let Some(action) = q.chosen_action() else {
947        return ActionDecision::Skip;
948    };
949    if task.action_applied(&q.id)
950        || matches!(
951            task.status,
952            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
953        )
954    {
955        return ActionDecision::Skip;
956    }
957    // A question about an earlier attempt must not act on a newer one. A
958    // conductor question is keyed by the task id, not a run, so it is exempt.
959    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
960        return ActionDecision::Stale;
961    }
962    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
963    let stopping = q.node == land::APPROVAL_NODE
964        && q.resolution()
965            .as_deref()
966            .is_some_and(crate::merge_decision::stops);
967    // An answer is the owner's decision as of when it was given: a manual hold
968    // placed before it (even after the question was asked) was seen and
969    // overruled by it, while a hold or release after it supersedes it.
970    let decision_at = q.answered_at.unwrap_or(q.asked_at);
971    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
972        return if repair || stopping {
973            ActionDecision::Refuse(format!(
974                "{} 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 {}`",
975                if repair { "repair" } else { "stop" },
976                q.id,
977                q.run,
978                task.id
979            ))
980        } else {
981            ActionDecision::Stale
982        };
983    }
984    match action {
985        a if a.maintenance() => ActionDecision::Skip,
986        ask::ChoiceAction::ResumeRun { .. }
987        | ask::ChoiceAction::ReleaseTask { .. }
988        | ask::ChoiceAction::RerunChecks { .. }
989        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
990        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
991        ask::ChoiceAction::Hold => ActionDecision::Hold,
992        ask::ChoiceAction::Done => ActionDecision::Done,
993        ask::ChoiceAction::Resume { run } => {
994            if task.execution_runs().last() != Some(run) {
995                return ActionDecision::Refuse((p.resume_not_latest)(
996                    q.short(),
997                    ask::short_id(run),
998                ));
999            }
1000            match load(run) {
1001                Ok(s) if stopping => {
1002                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1003                        || !s
1004                            .land_approval
1005                            .as_ref()
1006                            .is_some_and(|binding| binding.question == q.id)
1007                    {
1008                        ActionDecision::Stale
1009                    } else if s.liveness_under(home, false) == Liveness::Live {
1010                        ActionDecision::Skip
1011                    } else if s.status == RunStatus::Landing
1012                        && !s.released()
1013                        && s.retired_to.is_none()
1014                    {
1015                        ActionDecision::Resume(run.clone())
1016                    } else {
1017                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1018                    }
1019                }
1020                Ok(s)
1021                    if q.node == land::APPROVAL_NODE
1022                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1023                {
1024                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1025                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1026                    {
1027                        // A live/manual driver already consumed or superseded
1028                        // this answer. Do not hold its fresh approval wait.
1029                        ActionDecision::Stale
1030                    } else if s.liveness_under(home, false) == Liveness::Live {
1031                        ActionDecision::Skip
1032                    } else if s.status != RunStatus::Landing
1033                        || s.released()
1034                        || s.reviews.is_empty()
1035                        || !implementers_match(task, &s)
1036                        || !s
1037                            .land_approval
1038                            .as_ref()
1039                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1040                    {
1041                        ActionDecision::Refuse(format!(
1042                            "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",
1043                            q.id, run, run
1044                        ))
1045                    } else {
1046                        ActionDecision::Resume(run.clone())
1047                    }
1048                }
1049                Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1050                    ActionDecision::Refuse("run already has a live driver".into())
1051                }
1052                Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1053                    None => ActionDecision::Resume(run.clone()),
1054                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1055                        q.short(),
1056                        ask::short_id(run),
1057                        &reason.diagnostic(&s),
1058                    )),
1059                },
1060                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1061                    q.short(),
1062                    ask::short_id(run),
1063                    &format!("{e:#}"),
1064                )),
1065            }
1066        }
1067    }
1068}
1069
1070/// The fixed prose the daemon writes into [`Task::last_error`] and
1071/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1072/// `triage::Wording` and `land::Words`: only English and Japanese are
1073/// translated, anything else falls back to English.
1074///
1075/// Rendered when the reason is *generated*, so a reason keeps the language it
1076/// was written in if the setting changes later. The notification frame
1077/// (`Task <id> is held:`) is not here and stays English.
1078///
1079/// Deliberately **not** translated, because other code reads them back by
1080/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1081/// and `gate red`. IDs, node names, paths and external error text are embedded
1082/// as they are.
1083struct Phrases {
1084    /// `{}` = status label, then the detail.
1085    graph_stopped: fn(&str, &str) -> String,
1086    quorum_lost: &'static str,
1087    /// Followed by the seats' names.
1088    quota_took_out: &'static str,
1089    /// Followed by the status label.
1090    run_ended: &'static str,
1091    /// Followed by the question's short id.
1092    waiting_for_answer: &'static str,
1093    recovered_running: &'static str,
1094    no_run_to_recover: &'static str,
1095    could_not_start: &'static str,
1096    resume_not_latest: fn(&str, &str) -> String,
1097    resume_cannot_progress: fn(&str, &str, &str) -> String,
1098    resume_unreadable: fn(&str, &str, &str) -> String,
1099    /// A takeover refusal: the operator-facing text. English is the error's own
1100    /// `Display`; a translation keeps the machine detail apart in parentheses.
1101    handover_refused: fn(&crate::handover::Refused) -> String,
1102    /// Appended to a refused handover's hold reason (leading space included).
1103    handover_hint: &'static str,
1104    /// (seats that never answered, review rounds) for the review loop's
1105    /// "refusing to call it clean" stop.
1106    reviewers_never_answered: fn(usize, usize) -> String,
1107}
1108
1109const PHRASES_EN: Phrases = Phrases {
1110    graph_stopped: |status, detail| {
1111        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1112    },
1113    quorum_lost: "the judging panel lost its quorum",
1114    quota_took_out: "; quota took out ",
1115    run_ended: "run ended ",
1116    waiting_for_answer: " - waiting for operator answer to question ",
1117    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1118    no_run_to_recover: "task was `running` with no live daemon and no readable \
1119                        run to recover; held for a human to check what happened",
1120    could_not_start: "could not start the run: ",
1121    resume_not_latest: |q, run| {
1122        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1123    },
1124    resume_cannot_progress: |q, run, reason| {
1125        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1126    },
1127    resume_unreadable: |q, run, e| {
1128        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1129    },
1130    handover_refused: |r| r.to_string(),
1131    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1132    reviewers_never_answered: |missing, rounds| {
1133        format!(
1134            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1135             refusing to call it clean"
1136        )
1137    },
1138};
1139
1140const PHRASES_JA: Phrases = Phrases {
1141    graph_stopped: |status, detail| {
1142        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1143    },
1144    quorum_lost: "審査パネルが定足数を失いました",
1145    quota_took_out: "。クォータで脱落: ",
1146    run_ended: "run 終了: ",
1147    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1148    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1149    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1150                        何が起きたか人が確認するため保留にしました",
1151    could_not_start: "run を開始できませんでした: ",
1152    resume_not_latest: |q, run| {
1153        format!(
1154            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1155        )
1156    },
1157    resume_cannot_progress: |q, run, reason| {
1158        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1159    },
1160    resume_unreadable: |q, run, e| {
1161        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1162    },
1163    handover_refused: |r| {
1164        use crate::handover::Refused;
1165        match r {
1166            Refused::Foreign { branch, path, why } => format!(
1167                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1168                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1169                 から、やり直してください(詳細: {why})"
1170            ),
1171            Refused::Unsafe { branch, path, why } => format!(
1172                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1173                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1174                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1175            ),
1176            Refused::ReleaseFailed { branch, path, run } => format!(
1177                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1178                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1179                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1180            ),
1181        }
1182    },
1183    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1184    reviewers_never_answered: |missing, rounds| {
1185        format!(
1186            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1187             クリーンとは認めません"
1188        )
1189    },
1190};
1191
1192fn phrases(language: &str) -> &'static Phrases {
1193    if crate::lang::is_japanese(language) {
1194        &PHRASES_JA
1195    } else {
1196        &PHRASES_EN
1197    }
1198}
1199
1200/// The language of the repository a task belongs to, read best-effort for the
1201/// paths that have no run (and so no config of their own) to ask. An unreadable
1202/// config is English, not an error: a hold reason must still get written.
1203fn language_of(task: &Task, fallback: &Path) -> String {
1204    crate::lang::of_repo(&repo_for(task, fallback))
1205}
1206
1207/// The task an answered question speaks for: the one whose runs include the
1208/// question's run, or - for a conductor question, filed under the task's own
1209/// id - the task with that id.
1210pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1211    if q.node == crate::conduct::NODE {
1212        return tasks.iter().find(|t| t.id == q.run);
1213    }
1214    tasks.iter().find(|t| t.runs.contains(&q.run))
1215}
1216
1217/// Legacy conductor prose never becomes a maintenance command by inference.
1218/// Replace unsupported open labels under the question lock before dispatch.
1219fn repair_choice_offers(questions: &Questions) {
1220    for q in questions.list().into_iter().filter(|q| {
1221        q.status.open()
1222            && q.node == crate::conduct::NODE
1223            && q.choices
1224                .iter()
1225                .any(|c| crate::choice_effect::describe(q, c).is_none())
1226    }) {
1227        let _ = questions.update(&q.id, |current| {
1228            if current.status.open() {
1229                crate::choice_effect::executable_conductor(current);
1230                if let Some(deputy) = &mut current.deputy {
1231                    deputy.brief = crate::deputy::brief(
1232                        &current.run,
1233                        &current.detail,
1234                        &current.choices,
1235                        &current.actions,
1236                    );
1237                }
1238            }
1239            Ok(())
1240        });
1241    }
1242}
1243
1244/// Apply answered typed choices. Only the daemon calls this in production;
1245/// deputies settle the question and never execute its actions.
1246pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1247    apply_maintenance_choices(queue, questions, home).await;
1248    apply_task_choice_actions(queue, questions, home);
1249}
1250
1251/// Apply bounded maintenance effects independently of question ownership: a
1252/// release watcher need not have a queue task, and a predecessor is another run.
1253async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1254    for q in questions.list() {
1255        // Read again under the same fence used by explicit settlement.
1256        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1257            continue;
1258        };
1259        let Ok(q) = questions.get(&q.id) else {
1260            continue;
1261        };
1262        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1263            continue;
1264        };
1265        // Receipt paths use question IDs, whose format is independent of run
1266        // IDs. Apply the question store's filename safety rule to both eras.
1267        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1268            continue;
1269        }
1270        if queue.list().iter().any(|task| {
1271            (task.id == q.run
1272                || task.runs.contains(&q.run)
1273                || q.routed_task.as_deref() == Some(&task.id))
1274                && task.stale_question(&q)
1275        }) {
1276            continue;
1277        }
1278        let dir = home.join("choice-actions");
1279        if std::fs::create_dir_all(&dir).is_err() {
1280            continue;
1281        }
1282        let Ok(lock) = std::fs::OpenOptions::new()
1283            .create(true)
1284            .truncate(false)
1285            .write(true)
1286            .open(dir.join(format!("{}.lock", q.id)))
1287        else {
1288            continue;
1289        };
1290        if crate::pr_head::try_lock_file(&lock).is_err() {
1291            continue;
1292        }
1293        let fresh = !home
1294            .join("choice-actions")
1295            .join(format!("{}.json", q.id))
1296            .exists();
1297        let result = async {
1298            let receipt = dir.join(format!("{}.json", q.id));
1299            if receipt.exists() {
1300                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1301                anyhow::ensure!(
1302                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1303                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1304                );
1305                return Ok::<_, anyhow::Error>(());
1306            }
1307            // Never retry an uncertain external effect. The receipt is written
1308            // before calling gh, exactly like release_watch's rerun record.
1309            let record = |status: &str| -> anyhow::Result<()> {
1310                let tmp = receipt.with_extension("tmp");
1311                std::fs::write(
1312                    &tmp,
1313                    serde_json::to_vec(&serde_json::json!({
1314                        "action": action, "status": status,
1315                    }))?,
1316                )?;
1317                std::fs::rename(tmp, &receipt)?;
1318                Ok(())
1319            };
1320            let applied = async {
1321                match action {
1322                    ask::ChoiceAction::ResumeRun { run } => {
1323                        crate::resume::validate(home, run)?;
1324                        record("started")?;
1325                        let decided = q.answered_at.unwrap_or(q.asked_at);
1326                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1327                            crate::resume::validate_unqueued(home, run)?;
1328                            crate::resume::start(home, run.clone()).await?;
1329                        }
1330                    }
1331                    ask::ChoiceAction::ReleaseTask {
1332                        task,
1333                        held_at,
1334                        reason,
1335                    } => {
1336                        anyhow::ensure!(
1337                            queue.resolve_id(task)? == *task,
1338                            "task action requires an exact task ID"
1339                        );
1340                        let _claim = queue.claim(task)?;
1341                        let mut task = queue.get(task)?;
1342                        if task.action_applied(&q.id) {
1343                            return Ok(());
1344                        }
1345                        // Filing this conductor question temporarily wraps the
1346                        // original hold in a Blocked state. Restore only that
1347                        // exact blocker on the local copy before checking the
1348                        // hold binding; unrelated waits never authorize release.
1349                        if q.node == crate::conduct::NODE
1350                            && q.run == task.id
1351                            && task.status == TaskStatus::Blocked
1352                            && task.blocked_from == Some(TaskStatus::Held)
1353                            && task.blocked_by.as_slice() == [q.id.as_str()]
1354                        {
1355                            task.unblock(&q.id);
1356                        }
1357                        anyhow::ensure!(
1358                            task.status == TaskStatus::Held
1359                                && task.held_at == Some(*held_at)
1360                                && task.hold_reason.as_deref() == reason.as_deref()
1361                                && task
1362                                    .operator_decided_at
1363                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1364                            "task no longer has the hold this question names"
1365                        );
1366                        task.release_operator("choice", Some(&q.id));
1367                        task.mark_action_applied(&q.id);
1368                        queue.put(&mut task)?;
1369                    }
1370                    ask::ChoiceAction::AbandonRun { run } => {
1371                        record("started")?;
1372                        crate::driver::abandon_proven_dead(home, run)?;
1373                    }
1374                    ask::ChoiceAction::RerunChecks {
1375                        repo,
1376                        pr,
1377                        head,
1378                        runs,
1379                    } => {
1380                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1381                            .await?;
1382                    }
1383                    _ => unreachable!(),
1384                }
1385                Ok::<_, anyhow::Error>(())
1386            }
1387            .await;
1388            match applied {
1389                Ok(()) => record("applied"),
1390                Err(e) => {
1391                    record(&format!("refused or failed: {e:#}"))?;
1392                    Err(e)
1393                }
1394            }
1395        }
1396        .await;
1397        // Retire the originating blocker as well as the target operation.
1398        // A foreign resume leaves its issuer held instead of competing beside
1399        // the execution just started. Other successful maintenance lets the
1400        // original task retry its normal, guarded path.
1401        if home
1402            .join("choice-actions")
1403            .join(format!("{}.json", q.id))
1404            .exists()
1405            && let Some(listed) = task_of_question(&queue.list(), &q)
1406            && !listed.action_applied(&q.id)
1407            && let Ok(_claim) = queue.claim(&listed.id)
1408            && let Ok(mut origin) = queue.get(&listed.id)
1409        {
1410            if !origin.operator_held()
1411                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1412                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1413            {
1414                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1415                    origin.hold_machine(Some(format!(
1416                        "Maintenance choice {} settled; inspect its target before releasing this task",
1417                        q.id
1418                    )));
1419                } else {
1420                    origin.unblock(&q.id);
1421                }
1422            }
1423            origin.mark_action_applied(&q.id);
1424            let _ = queue.put(&mut origin);
1425        }
1426        if let Err(e) = result
1427            && fresh
1428        {
1429            notices::raise_in(
1430                home,
1431                Notice::warn(
1432                    &format!("action:{}", q.id),
1433                    format!("Choice action {} was not completed: {e:#}", q.id),
1434                )
1435                .link(if q.run_names_task() {
1436                    Link::Task { id: q.run.clone() }
1437                } else {
1438                    Link::Run { id: q.run.clone() }
1439                }),
1440            );
1441        }
1442    }
1443}
1444
1445/// Rerun the named failed workflow runs of a pull request, each at most once
1446/// per `request` (a question id, or a chat operation identity). The head,
1447/// lifecycle and failed state are re-read from the forge first; `started` is
1448/// called once those checks pass and before the first external call, and the
1449/// ledger entry is written before every `gh` call, so an uncertain result is
1450/// never repeated automatically.
1451pub(crate) async fn rerun_checks_once(
1452    home: &Path,
1453    request: &str,
1454    repo: &Path,
1455    pr: &str,
1456    head: &str,
1457    runs: &[String],
1458    started: impl FnOnce() -> anyhow::Result<()>,
1459) -> anyhow::Result<()> {
1460    use crate::release_watch::{GhForge, ReleaseForge};
1461    anyhow::ensure!(
1462        !runs.is_empty()
1463            && runs.len() <= 20
1464            && runs
1465                .iter()
1466                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1467            && !pr.starts_with('-'),
1468        "invalid rerun targets"
1469    );
1470    let snap = GhForge.snapshot(repo, pr).await?;
1471    anyhow::ensure!(
1472        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1473        "pull request head or lifecycle changed"
1474    );
1475    anyhow::ensure!(
1476        runs.iter().all(|r| snap
1477            .checks
1478            .iter()
1479            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1480        "named workflow is no longer failed on this pull request"
1481    );
1482    started()?;
1483    let dir = home.join("choice-actions");
1484    std::fs::create_dir_all(&dir)?;
1485    let rerun_lock = std::fs::OpenOptions::new()
1486        .create(true)
1487        .truncate(false)
1488        .write(true)
1489        .open(dir.join("reruns.lock"))?;
1490    crate::pr_head::try_lock_file(&rerun_lock)?;
1491    let ledger = dir.join("reruns.json");
1492    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1493        serde_json::from_slice(&std::fs::read(&ledger)?)?
1494    } else {
1495        Default::default()
1496    };
1497    for run in runs {
1498        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1499        if !recorded.insert(key) {
1500            continue;
1501        }
1502        let tmp = ledger.with_extension("tmp");
1503        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1504        std::fs::rename(tmp, &ledger)?;
1505        GhForge.rerun(repo, run).await?;
1506    }
1507    Ok(())
1508}
1509
1510/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1511///
1512/// Runs on every poll before the conductor looks at the queue. The task is
1513/// re-read under its claim, so a task somebody completed or held by hand in
1514/// the meantime is judged on what it is now. `Resume` releases the task and
1515/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1516/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1517/// ordinary `unfinished_run` logic resumes that same run.
1518pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1519    let tasks = queue.list();
1520    for q in questions.list() {
1521        // Read again under the same fence used by explicit settlement.
1522        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1523            continue;
1524        };
1525        let Ok(q) = questions.get(&q.id) else {
1526            continue;
1527        };
1528        // Dismissal is committed by the question writer, never a resume.
1529        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1530            continue;
1531        }
1532        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1533            continue;
1534        }
1535        let Some(listed) = task_of_question(&tasks, &q) else {
1536            if q.node == land::APPROVAL_NODE
1537                && q.resolution().as_deref().is_some_and(|choice| {
1538                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1539                })
1540            {
1541                notices::raise_in(
1542                    home,
1543                    Notice::warn(
1544                        &format!("repair-owner:{}", q.id),
1545                        format!(
1546                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1547                            q.run, q.run
1548                        ),
1549                    ).link(Link::Run { id: q.run.clone() }),
1550                );
1551            }
1552            continue;
1553        };
1554        if listed.action_applied(&q.id) {
1555            continue;
1556        }
1557        let Ok(_claim) = queue.claim(&listed.id) else {
1558            continue;
1559        };
1560        let Ok(mut task) = queue.get(&listed.id) else {
1561            continue;
1562        };
1563        // Work only on this local copy until the action can be committed.
1564        // In particular, a fresh lease below leaves the persisted task blocked.
1565        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1566            let blockers: Vec<_> = task
1567                .blocked_by
1568                .iter()
1569                .filter(|id| {
1570                    crate::queue::dependency(queue, questions, id)
1571                        == crate::queue::Dependency::Question(q.id.clone())
1572                })
1573                .cloned()
1574                .collect();
1575            if !blockers.is_empty() {
1576                for id in blockers {
1577                    task.unblock(&id);
1578                }
1579                let answer = match &q.answer {
1580                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1581                    None => String::new(),
1582                };
1583                task.record_answer(q.summary.clone(), answer);
1584            }
1585        }
1586        let language = language_of(&task, Path::new("."));
1587        let decision = decide_action(home, &task, &q, phrases(&language), |id| {
1588            RunState::load_under(id, home)
1589        });
1590        let ran = matches!(
1591            decision,
1592            ActionDecision::Resume(_)
1593                | ActionDecision::Requeue
1594                | ActionDecision::Hold
1595                | ActionDecision::Done
1596        );
1597        if ran && asker_may_still_read(questions, &q, home) {
1598            // The asking process or its seat can still take the word; act
1599            // once it has gone quiet. Bound on the remaining window: the
1600            // check is not atomic with the write below, so an asker that
1601            // takes the word in between (at most one poll, never more than
1602            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1603            // and `Task::actions_applied` under the claim keeps the action to
1604            // one application. The waiter does not deliver an answer that
1605            // carries an action (`waiter::decide_owned`), so it cannot race.
1606            continue;
1607        }
1608        let done = matches!(decision, ActionDecision::Done);
1609        // Resume owes an execution pass; only these task-local effects finish
1610        // in this write. Stale/refused actions never acquire an effect receipt.
1611        let completed = matches!(
1612            decision,
1613            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1614        );
1615        match decision {
1616            ActionDecision::Skip => continue,
1617            ActionDecision::Resume(run) => {
1618                task.release_operator("choice", Some(&q.id));
1619                task.resume_override = Some(crate::queue::OperatorResume {
1620                    question_id: q.id.clone(),
1621                    at: Timestamp::now(),
1622                    conductor_rehold: None,
1623                    forced: true,
1624                    pinned_run: Some(run),
1625                });
1626            }
1627            ActionDecision::Stale => {}
1628            ActionDecision::Requeue => {
1629                task.release_operator("choice-requeue", Some(&q.id));
1630                task.requeue();
1631            }
1632            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1633            ActionDecision::Done => task.succeed(),
1634            ActionDecision::Refuse(why) => {
1635                let _ =
1636                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1637                if task.operator_held() {
1638                    // A rejected answer does not release the operator's hold
1639                    // or reclassify it as recoverable by the conductor.
1640                    task.hold_reason = Some(match task.hold_reason.take() {
1641                        Some(reason) => format!("{reason}\n\n{why}"),
1642                        None => why,
1643                    });
1644                } else {
1645                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1646                    task.hold_machine(Some(why));
1647                }
1648                notices::raise(
1649                    Notice::warn(
1650                        &format!("action:{}", q.id),
1651                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1652                    )
1653                    .link(Link::Task {
1654                        id: task.id.clone(),
1655                    }),
1656                );
1657            }
1658        }
1659        task.mark_action_applied(&q.id);
1660        if completed {
1661            task.decision_effects.insert(
1662                q.id.clone(),
1663                format!("decision: {}", q.resolution().expect("answered action")),
1664            );
1665        }
1666        // The applied id travels with the transition, so a failed save loses
1667        // neither and the answer is acted on at the next poll.
1668        record(queue, &mut task);
1669        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1670            supersede_prior_runs(&task, home);
1671        }
1672        // Delivery is only a note of who has read the answer; the task's own
1673        // mark above is the authority. Best effort.
1674        let _ = questions.update(&q.id, |r| {
1675            r.answer_delivered = true;
1676            Ok(())
1677        });
1678    }
1679}
1680
1681/// Whether something may still read the answer to `q`: a fresh lease, or the
1682/// asking seat still listed as active in its run (its CLI can outlive the
1683/// `magi ask` that was killed).
1684fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1685    let now = Timestamp::now();
1686    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1687        return true;
1688    }
1689    q.node != crate::conduct::NODE
1690        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1691            s.seats_active()
1692                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1693        })
1694}
1695
1696/// Retire an unanswered conductor question after its task no longer refers to
1697/// it. Conductor questions use the task id in `Question::run`, so run-based
1698/// cleanup cannot observe a manual release or completion.
1699///
1700/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1701/// own question also carries a `run`, and a run id that happens to collide
1702/// with some task's id is not this loop's business — only a conductor
1703/// question actually uses the task id that way. One `Questions::list()` scan
1704/// is taken up front and matched against the in-memory task set, rather than
1705/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1706fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1707    let tasks = queue.list();
1708    let by_id: std::collections::BTreeMap<&str, &Task> =
1709        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1710    let referenced: Vec<&str> = tasks
1711        .iter()
1712        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1713        .collect();
1714
1715    for mut question in questions.list() {
1716        if !question.status.open() || question.node != crate::conduct::NODE {
1717            continue;
1718        }
1719        // Keep questions a task still names, including when the reference
1720        // moved to a dependent task.
1721        // Preserve even ambiguous references: retiring a possibly referenced
1722        // question is unsafe until the operator disambiguates it.
1723        if referenced
1724            .iter()
1725            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1726        {
1727            continue;
1728        }
1729        let Some(task) = by_id.get(question.run.as_str()) else {
1730            continue;
1731        };
1732        question.abandon(format!(
1733            "task {} no longer waits for this answer",
1734            task.short()
1735        ));
1736        if let Err(e) = questions.put(&mut question) {
1737            tracing::warn!(
1738                "could not retire question {} for task {}: {e:#}",
1739                question.short(),
1740                task.short()
1741            );
1742        }
1743    }
1744}
1745
1746/// What a finished run tells the queue about the task it came from.
1747///
1748/// A struct rather than a fourth and fifth boolean argument: the two flags
1749/// answer different questions about the same run, and a call site passing
1750/// `(…, true, false)` is one transposition away from refunding attempts
1751/// forever.
1752#[derive(Debug, Clone, Copy)]
1753pub struct Verdict {
1754    /// Where the graph stopped.
1755    pub status: RunStatus,
1756    /// The run opened a pull request.
1757    pub left_pr: bool,
1758    /// At least one seat was lost to a rate limit.
1759    pub quota_hit: bool,
1760    /// The run parked at a node boundary because it was asked to.
1761    pub parked: bool,
1762    /// The run never produced a single candidate a judge could look at.
1763    ///
1764    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1765    /// still have another candidate worth judging, in which case the loss was
1766    /// not the reason nothing came of the run. This is `true` only when the
1767    /// implement wave ended with nothing viable at all.
1768    pub no_viable_candidates: bool,
1769}
1770
1771/// Record a finished run against the task it came from.
1772///
1773/// Kept pure and separate from the loop because this mapping *is* the retry
1774/// policy, and a policy that can only be exercised by spawning a graph is a
1775/// policy nobody checks. The table:
1776///
1777/// | run status                           | task becomes        | attempt spent |
1778/// |---------------------------------------|---------------------|---------------|
1779/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1780/// | `Merged`, `Ready`                      | `Done`               | yes          |
1781/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1782/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1783/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1784/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1785/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1786/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1787/// | `Blocked` with a PR                    | `Held`               | yes          |
1788/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1789/// | `VerifiedNoop`                          | `Held`               | yes          |
1790/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1791///
1792/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1793/// deliberately: every candidate agreeing there is nothing to write is not a
1794/// machine fact about a rate limit, it is an unverified claim about the
1795/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1796/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1797/// claim could be wrong (a misread instruction, a stale check), and closing
1798/// the task automatically on an implementer's say-so would be the exact
1799/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1800/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1801/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1802/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1803/// claim regardless of whether the one already-spent attempt is refunded, and
1804/// [`Task::release`] resets the count to zero anyway the moment a human looks
1805/// at the evidence and lets it run again.
1806///
1807/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1808/// twice, together. A quorum lost to rate limits is a property of the machine
1809/// and not of the task, so the attempt is refunded and a reset quota picks
1810/// the work up where it stopped — and that is just as true when every
1811/// implement seat lost the same race and `after_implement` bails with nothing
1812/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1813/// machine fact. The `no_viable_candidates` guard is what keeps that row
1814/// narrow: a `Failed` run that produced a real candidate which then lost for
1815/// some other reason still spends the attempt, exactly like the quorum lost
1816/// to judges that answered with the wrong shape is ordinary flakiness, and
1817/// refunding *that* takes the bound off the retry loop entirely: run e633
1818/// stalled with `quota: []` after two judges wrote unusable JSON, was
1819/// refunded, and the next attempt paid for a fresh hour-long implement wave
1820/// before it could fail the same way. `max_attempts` exists precisely so
1821/// that cannot repeat forever.
1822///
1823/// A non-terminal status means `execute` returned while the graph was still
1824/// mid-flight, which is a bug rather than a verdict; it is treated as a
1825/// failure so that a task cannot loop on it either.
1826///
1827/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1828/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1829pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1830    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1831}
1832
1833/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1834fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1835    // A parked run is the operator's own doing, and its work is intact on
1836    // disk. The task goes back in line with its attempt refunded so the next
1837    // loop resumes the same run - which `one_task` prefers over competing
1838    // again - and so that swapping the binary a few times cannot exhaust a
1839    // budget meant for agents that actually misbehaved.
1840    if verdict.parked {
1841        task.park(detail);
1842        return;
1843    }
1844    match verdict.status {
1845        RunStatus::Merged | RunStatus::Ready
1846            if task.pr_recovery.as_ref().is_some_and(|s| {
1847                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1848            }) =>
1849        {
1850            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()));
1851        }
1852        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1853        RunStatus::AlreadyInBase => task.already_landed(detail),
1854        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1855        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1856            task.stall(detail)
1857        }
1858        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1859        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1860        RunStatus::Blocked => task.fail(detail, max_attempts),
1861        RunStatus::VerifiedNoop => task.handed_off(detail),
1862        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1863    }
1864}
1865
1866/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1867/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1868/// itself has actually finished *and* its own last attempt is provably why:
1869/// this loads that run and requires `Merged`/`Ready` before touching
1870/// anything earlier in `runs`, since `Task::succeed` can also be called
1871/// directly on a task whose last attempt never landed at all.
1872///
1873/// Called right after whatever call set `task.status` to
1874/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1875/// `reclaim`'s, but also every other place a task can be closed by hand
1876/// without the loop ever settling it itself: `magi task done`
1877/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1878/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1879/// GitHub merge, say, exactly the workflow this repository's own
1880/// "Landing a run's winner by hand" documents — is just as much "this task's
1881/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1882/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1883/// forever, which is the exact backlog this status exists to clear. `pub`
1884/// for those two out-of-module callers; everything else about this stays
1885/// internal bookkeeping.
1886///
1887/// A run something is still actually driving is left alone: a
1888/// task cannot be `Done` while one of its *own* attempts is still in flight,
1889/// so a live one at this point can only be an unrelated process — a manual
1890/// `--resume` of this old, now-moot run — and rewriting under it would just
1891/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1892/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1893/// pair `run_report`/`run_detail` use for the same question elsewhere:
1894/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1895/// --resume` invoked by hand outside it, which `liveness` also checks via
1896/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1897/// (already terminal in some other way, or itself mid-run) is left untouched
1898/// too.
1899///
1900/// Best-effort, like the rest of this module's bookkeeping: a load or save
1901/// failure here is a `tracing::warn`, not a failed settle, and the next time
1902/// this same task's completion is recorded — or a daemon restart replays
1903/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1904/// separate reconciliation pass; if that gap ever matters in practice, one
1905/// can be added then.
1906///
1907/// `home` is a parameter, not the process-global [`crate::run::home`], for
1908/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1909/// calls this with `ui.home`, which is `crate::run::home()` in a real
1910/// process but a fixture's own directory under test — falling through to
1911/// the global there would read and write through whichever home some other
1912/// test in the same binary happened to pin into that `OnceLock` first, not
1913/// the run this call actually means.
1914pub fn supersede_prior_runs(task: &Task, home: &Path) {
1915    let now = Timestamp::now();
1916    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1917    // right behind a `Merged`/`Ready` verdict) from one set directly by
1918    // `magi task done`/its web equivalent/the conductor on a task whose last
1919    // recorded attempt never actually landed - that requires reading the
1920    // run itself, which is exactly what this does before trusting anything
1921    // in `runs` is safe to relabel.
1922    let last_run_succeeded = task
1923        .runs
1924        .last()
1925        .and_then(|id| RunState::load_under(id, home).ok())
1926        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1927    for id in task.superseded_attempts(last_run_succeeded) {
1928        let mut state = match RunState::load_under(id, home) {
1929            Ok(s) => s,
1930            Err(e) => {
1931                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1932                continue;
1933            }
1934        };
1935        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1936            continue;
1937        }
1938        let daemon_claims = is_working_on(home, id, now);
1939        if state.liveness(daemon_claims) == Liveness::Live {
1940            continue;
1941        }
1942        state.status = RunStatus::Superseded;
1943        if let Err(e) = state.save_under(home) {
1944            tracing::warn!("could not mark run {id} superseded: {e:#}");
1945        }
1946    }
1947}
1948
1949/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1950/// finish the moment it was called, because one of its earlier attempts was
1951/// still live then - a `magi run --resume` invoked by hand on an old run,
1952/// most likely.
1953///
1954/// That skip is correct at the time (rewriting under a run something is
1955/// still actively saving would just be undone), but a task only ever
1956/// reaches `Done` once, so without this nothing would ever look at it
1957/// again: if that manual process later ends anywhere other than
1958/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1959/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1960/// backlog this status exists to clear. Called on the same idle-only
1961/// cadence as [`janitor`], next to it rather than folded into it: this
1962/// walks `queue` and `janitor` never otherwise needs one.
1963///
1964/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1965/// more than one attempt, every pass: each call is a handful of local file
1966/// reads bounded by that task's own attempt count, the same order of cost
1967/// [`clean::fold_due`] already pays scanning every run on disk on the same
1968/// cadence, and a task already fully resolved costs one failed liveness
1969/// check turned no-op the moment its lingering attempt is no longer live.
1970fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1971    for task in queue.list() {
1972        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1973            continue;
1974        }
1975        supersede_prior_runs(&task, home);
1976    }
1977}
1978
1979/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1980/// task ends up held.
1981///
1982/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1983/// dead daemon never got back to) share this, so the two cannot drift into
1984/// disagreeing about which held tasks get a diagnostic.
1985fn settle_and_diagnose(
1986    task: &mut Task,
1987    verdict: Verdict,
1988    detail: &str,
1989    max_attempts: usize,
1990    state: &RunState,
1991) {
1992    let p = phrases(&state.config.graph.language);
1993    // Shared by normal completion and crash recovery, under the task claim.
1994    // No new attempt can own the task until the old driver has exited.
1995    if let Some(d) = &state.merge_decision {
1996        use crate::merge_decision as md;
1997        if task
1998            .execution_runs()
1999            .last()
2000            .is_some_and(|id| id != &state.id)
2001        {
2002            return;
2003        }
2004        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2005            task.succeed();
2006        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2007            if state.liveness(false) != Liveness::Dead {
2008                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2009                return;
2010            }
2011            let replacement = md::Replacement {
2012                question: d.question.clone(),
2013                run: state.id.clone(),
2014                pr: d.target.pr.clone(),
2015                agent: agent.to_owned(),
2016                context: format!(
2017                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2018                    d.target.pr,
2019                    state.id,
2020                    serde_json::to_string(&state.reviews).unwrap_or_default()
2021                ),
2022            };
2023            task.requeue();
2024            task.pr_recovery = None;
2025            task.review_of = None;
2026            task.replacement = Some(replacement);
2027        } else {
2028            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2029                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2030            } 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())) }));
2031        }
2032        task.mark_action_applied(&d.question);
2033        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2034            task.decision_effects
2035                .insert(d.question.clone(), format!("decision: {}", d.choice));
2036        }
2037        if let Some(pass) = state.passes.last() {
2038            task.record_pass_at(
2039                &state.id,
2040                pass.index,
2041                Some(pass.started_at),
2042                task.attempts,
2043                None,
2044            );
2045        }
2046        return;
2047    }
2048    if let Some(replacement) = &task.replacement
2049        && !state.parked
2050        && state.resource_block.is_none()
2051        && (state.viable().is_empty()
2052            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2053    {
2054        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)));
2055        return;
2056    }
2057    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2058        let mut agents: Vec<_> = state
2059            .quota
2060            .iter()
2061            .filter(|q| {
2062                q.cause == crate::agent::QuotaCause::Authentication
2063                    && state
2064                        .passes
2065                        .last()
2066                        .is_none_or(|pass| q.at >= pass.started_at)
2067            })
2068            .map(|q| q.agent.as_str())
2069            .collect();
2070        agents.sort_unstable();
2071        agents.dedup();
2072        if !agents.is_empty() {
2073            task.stall(detail);
2074            task.notice_cause("agent-authentication", None, None);
2075            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2076            return;
2077        }
2078    }
2079    let attempts_before = task.attempts;
2080    // A run that stopped because a shared resource stayed busy was never a
2081    // failure of the task or of an agent. Earlier nodes may have run; only
2082    // the blocked operation lacks a result. The attempt is
2083    // refunded and the task is held by the machine, under a reason `triage`
2084    // can re-check, so the same run resumes with the same agents once the
2085    // resource is free. A park request still wins (it is the operator's).
2086    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2087        task.notice_cause(
2088            &format!("resource:{}:{}", block.kind, block.node),
2089            None,
2090            None,
2091        );
2092        task.last_error = Some(detail.to_owned());
2093        task.diagnostic = None;
2094        task.attempts = task.attempts.saturating_sub(1);
2095        if block.kind == "agent authentication" {
2096            task.hold_machine(Some(format!(
2097                "[authentication] {}; no attempt was spent",
2098                block.detail
2099            )));
2100        } else if block.kind == "agent usage limit" {
2101            // Usage limits keep the existing cooldown-and-resume policy.
2102            if let Some(agent) = &state.config.graph.selected_implementer {
2103                task.hold_machine(Some(format!("[agent usage limit] Selected implementer `{agent}` is unavailable. No other implementer was dispatched; resume after usage is available. No attempt was spent.")));
2104            } else {
2105                task.status = TaskStatus::Failed;
2106                task.last_error = Some(block.detail.clone());
2107            }
2108        } else if block.kind == "disk pressure" {
2109            task.hold_machine(Some(format!(
2110                "{}{}",
2111                crate::disk::RUNNING_PRESSURE,
2112                block.detail
2113            )));
2114        } else {
2115            task.hold_machine(Some(format!(
2116                "{}{}; no attempt was spent; resume to retry the affected operation",
2117                crate::cache::RESOURCE_HOLD,
2118                block.description()
2119            )));
2120        }
2121        if let Some(pass) = state.passes.last() {
2122            task.record_pass_at(
2123                &state.id,
2124                pass.index,
2125                Some(pass.started_at),
2126                attempts_before,
2127                None,
2128            );
2129        }
2130        return;
2131    }
2132    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2133        state.parked
2134            && state.status == RunStatus::Landing
2135            && state
2136                .pr_pushed_head
2137                .as_ref()
2138                .is_none_or(|h| h == &hold.head)
2139            && task.execution_runs().last() == Some(&state.id)
2140    }) {
2141        // Settlement and crash recovery share this idempotency key. A later
2142        // explicit resume is a new pass and may refund its own attempt once.
2143        let pass = state.passes.last().map_or(0, |p| p.index);
2144        if !task
2145            .passes
2146            .iter()
2147            .any(|p| p.run == state.id && p.pass_index == pass)
2148        {
2149            task.attempts = task.attempts.saturating_sub(1);
2150        }
2151        task.hold_machine(Some(format!(
2152            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2153            hold.question
2154        )));
2155        task.last_error = Some(detail.to_owned());
2156        task.diagnostic = None;
2157        task.record_pass_at(
2158            &state.id,
2159            pass,
2160            state.passes.last().map(|p| p.started_at),
2161            attempts_before,
2162            Some(crate::run::ParkCause::Question),
2163        );
2164        return;
2165    }
2166    let unresolved = task.hold_notice_cause.clone();
2167    if state.base_sync_blocked() {
2168        // No automatic retry may turn a retained sync stop into a new competition.
2169        task.hold_machine(Some(detail.to_owned()));
2170        task.last_error = Some(detail.to_owned());
2171    } else if !verdict.parked
2172        && task
2173            .pr_recovery
2174            .as_ref()
2175            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2176        && matches!(
2177            verdict.status,
2178            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2179        )
2180    {
2181        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2182            task.succeed();
2183        } else {
2184            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()));
2185        }
2186    } else if !verdict.parked
2187        && task.pr_recovery.is_some()
2188        && matches!(
2189            verdict.status,
2190            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2191        )
2192        && !verdict.quota_hit
2193    {
2194        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.")));
2195    } else {
2196        settle_in(task, verdict, detail, max_attempts, p);
2197    }
2198    if !verdict.parked
2199        && !verdict.quota_hit
2200        && matches!(
2201            verdict.status,
2202            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2203        )
2204    {
2205        task.recovery_failed(state);
2206    }
2207    if state.prep_failure.is_some() {
2208        // Minting a run whose candidates could not be prepared is not work
2209        // on a newly approved attempt. Keep the unresolved outcome anchor.
2210        task.hold_notice_cause = unresolved;
2211        task.startup_notice_cause("startup-candidates");
2212    }
2213    // Written here, where the refund (or not) is decided, so the history is a
2214    // fact and not a later guess from the run's status.
2215    if let Some(pass) = state.passes.last() {
2216        let parked = match &pass.end {
2217            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2218            _ => None,
2219        };
2220        task.record_pass_at(
2221            &state.id,
2222            pass.index,
2223            Some(pass.started_at),
2224            attempts_before,
2225            parked,
2226        );
2227    }
2228    if task.status == TaskStatus::Held {
2229        if state.base_sync_blocked() {
2230            task.base_sync_notice(state);
2231        } else if state.prep_failure.is_none() {
2232            task.notice_cause(
2233                label(verdict.status),
2234                Some(&state.id),
2235                state.passes.last().map(|p| p.index),
2236            );
2237        }
2238        task.diagnostic = diagnostic(state);
2239        note_open_question(task, &state.id, p);
2240    }
2241}
2242
2243/// If `task` is held with a `magi ask` question still open on `run`, name the
2244/// question in [`Task::hold_reason`] rather than leaving the hold reading
2245/// only [`describe`]'s run summary.
2246///
2247/// This is the shape task 20260928-191407-05fd left underspecified: an
2248/// implementer settled a verified no-op and filed a question for the
2249/// operator, and the hold that followed said nothing about the question
2250/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2251/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2252/// marker) and must keep seeing it unchanged.
2253///
2254/// Best-effort: an unreadable question store must not stop a run from
2255/// settling, so this is a no-op rather than a propagated error when
2256/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2257fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2258    let Some(home) = crate::run::try_home() else {
2259        return;
2260    };
2261    let open = Questions::at(home.join("questions")).open_for(run);
2262    let Some(q) = open.first() else {
2263        return;
2264    };
2265    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2266    decisions.sort_unstable();
2267    task.notice_cause(
2268        &format!("questions:{}", decisions.join(",")),
2269        Some(run),
2270        None,
2271    );
2272    let base = task.hold_reason.clone().unwrap_or_default();
2273    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2274}
2275
2276/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2277/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2278/// by some other means entirely, like a manual `magi run` resume that
2279/// finishes the graph outside the queue's bookkeeping.
2280///
2281/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2282/// `settle` is separate from `attempt`: a task recovered this way must land
2283/// exactly where a live daemon would have put it — the same policy table,
2284/// not a second one that quietly drifts from it — and that is only checkable
2285/// without spawning a real run.
2286fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2287    match last_run {
2288        Some(state) => {
2289            let verdict = Verdict {
2290                status: state.status,
2291                left_pr: state.pr.is_some(),
2292                quota_hit: state.quota.iter().any(|loss| {
2293                    state
2294                        .passes
2295                        .last()
2296                        .is_none_or(|pass| loss.at >= pass.started_at)
2297                }),
2298                parked: state.parked,
2299                no_viable_candidates: state.viable().is_empty(),
2300            };
2301            let detail = format!(
2302                "{}{}",
2303                phrases(&state.config.graph.language).recovered_running,
2304                describe(&state)
2305            );
2306            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2307        }
2308        None => {
2309            // No run, so no config of its own: `language` is the task's
2310            // repository's setting, read by the caller.
2311            let why = phrases(language).no_run_to_recover;
2312            task.last_error = Some(why.to_owned());
2313            // The phone shows `hold_reason`, so a task held by the machine
2314            // says why there too and not only in `last_error`.
2315            task.notice_cause("missing-run", None, None);
2316            task.hold_machine(Some(why.to_owned()));
2317        }
2318    }
2319}
2320
2321/// Find every task left at `running` that no live process is actually
2322/// driving, and settle each one against whatever its last run became.
2323///
2324/// # Why a claim is proof, not a guess
2325///
2326/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2327/// `running`, and the guard is held for the task's whole time in that status:
2328/// `attempt` does not return, and the loop does not move past the scope
2329/// holding the claim, until the run has settled. So a `running` task whose
2330/// lock is gone cannot have a live owner — this process or any other —
2331/// without needing a staleness threshold or a pid check the way
2332/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2333/// task that never got as far as `running` at all. Taking the claim here is
2334/// the whole test: it either fails, because something really does hold it
2335/// and the task is left alone, or it succeeds, which is the proof — and it is
2336/// kept for the rest of the decision so nothing else can start a competing
2337/// run while this one is being written.
2338///
2339/// Called on every poll, not only at startup, for the reason
2340/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2341/// keep noticing this, not only on the one morning it happened to restart.
2342fn reclaim_orphaned_running(
2343    queue: &Queue,
2344    max_attempts: usize,
2345    live_workers: &std::collections::BTreeSet<String>,
2346) -> Vec<String> {
2347    let mut reclaimed = Vec::new();
2348    for listed in queue.list() {
2349        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2350            continue;
2351        }
2352        let Ok(_claim) = queue.claim(&listed.id) else {
2353            continue;
2354        };
2355        // Re-read under the claim: a release or an edit landed by a human
2356        // between the listing above and the claim just taken must not be
2357        // clobbered by a decision based on the stale copy.
2358        let Ok(mut task) = queue.get(&listed.id) else {
2359            continue;
2360        };
2361        if task.status != TaskStatus::Running {
2362            continue;
2363        }
2364        let last_run = task
2365            .execution_runs()
2366            .last()
2367            .and_then(|id| RunState::load(id).ok());
2368        // `execute` normally abandons a run's own open questions the moment
2369        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2370        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2371        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2372        // with the question still `open`, because the process died before
2373        // reaching that call. `reclaim` itself stays pure on purpose (see its
2374        // own doc), so the same cleanup runs here instead, against the run
2375        // this reclaim is already reading. `settle_run` costs nothing when
2376        // `execute` already got there first.
2377        if let Some(state) = &last_run
2378            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2379        {
2380            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2381        }
2382        let language = if last_run.is_none() {
2383            language_of(&task, Path::new("."))
2384        } else {
2385            String::new()
2386        };
2387        reclaim(&mut task, last_run, max_attempts, &language);
2388        if task.status == TaskStatus::Done {
2389            supersede_prior_runs(&task, &crate::run::home());
2390        }
2391        record(queue, &mut task);
2392        reclaimed.push(task.id.clone());
2393    }
2394    reclaimed
2395}
2396
2397/// Find every run whose `run.json` is provably dead — every seat it still
2398/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2399/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2400/// not merely "no daemon claims it" — and fail it, clearing the leftover
2401/// active seats so the run stops reading as `implementing` (or whichever
2402/// node) forever.
2403///
2404/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2405/// `running`, using whatever `run.json` already says — but nothing in that
2406/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2407/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2408/// never got back to sits exactly where it was left: `active` full of seats
2409/// nobody will ever answer for, `status` stuck on whatever node was in
2410/// flight. `magi show` already tells an operator this in prose (`no live
2411/// daemon claims this run right now`); this is what makes that fact durable
2412/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2413/// stay stuck once nothing is driving it.
2414///
2415/// Runs on every poll, not only at startup, for the reason
2416/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2417/// daemon up for days must keep noticing a run some other, now-dead, daemon
2418/// left behind just as readily as one it trips over on the way up.
2419///
2420/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2421/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2422/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2423/// `runs` directory instead: `home` here is a parameter precisely so a test
2424/// can point it away from the operator's real history (see [`drive`]'s own
2425/// doc), and a scan that fell through to the global home anyway would walk
2426/// whichever directory some *other* process or test pinned into that
2427/// `OnceLock` first — mutating runs this call was never handed.
2428fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2429    reclaim_abandoned_runs_with(
2430        home,
2431        now,
2432        crate::proc::pid_status,
2433        crate::proc::process_started_at,
2434    )
2435}
2436
2437/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2438/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2439/// for the identical reason: this sweep's real damage (wiping a run's active
2440/// seats and failing it) has to be provable against an injected answer in a
2441/// test, not just the real process table.
2442fn reclaim_abandoned_runs_with<F, G>(
2443    home: &Path,
2444    now: Timestamp,
2445    query: F,
2446    identity: G,
2447) -> Vec<String>
2448where
2449    F: Fn(u32) -> Option<bool>,
2450    G: Fn(u32) -> Option<String>,
2451{
2452    let mut abandoned = Vec::new();
2453    for entry in std::fs::read_dir(home.join("runs"))
2454        .into_iter()
2455        .flatten()
2456        .flatten()
2457    {
2458        let id = entry.file_name().to_string_lossy().into_owned();
2459        if !crate::run::is_run_id(&id) {
2460            continue;
2461        }
2462        // Serialize the proof and save with claims and takeover: a new
2463        // execution must not be overwritten after the liveness observation.
2464        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2465            continue;
2466        };
2467        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2468        // that module's docs for why a run this cannot parse is left alone
2469        // rather than guessed at. A different schema number is not that: this
2470        // touches only `status` and `active`, never a field whose meaning a
2471        // schema bump changed, so an old record's values serve this exactly
2472        // as well as a current one's (see `clean::read_state`'s own doc for
2473        // the same reasoning applied to folding).
2474        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2475            continue;
2476        };
2477        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2478            continue;
2479        };
2480        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2481            continue;
2482        }
2483        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2484        // it", which is also the normal, healthy shape of a manual `magi
2485        // run` / `magi review` sharing this same home — this scan walks
2486        // every run on disk, not only ones this daemon itself started. Such
2487        // a run's active seats can legitimately sit past their own timeout
2488        // for a little while (the CLI finishing up, its result still being
2489        // collected) without the process driving it having died. `liveness`
2490        // is what actually tells the two apart, by corroborating
2491        // `driver_pid` against the process it names — see its own doc. Only
2492        // its strongest, provable answer licenses wiping this run's active
2493        // seats and failing it out from under whatever is still running it.
2494        let daemon_claims = is_working_on(home, &id, now);
2495        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2496            != crate::run::Liveness::Dead
2497        {
2498            continue;
2499        }
2500        state.abandon("daemon");
2501        if let Err(e) = state.save_under(home) {
2502            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2503            continue;
2504        }
2505        // This run never passes through `Runner::execute` again, so its end
2506        // is announced here.
2507        if let Some(notice) = notices::run_ended(&state) {
2508            notices::raise_in(home, notice);
2509        }
2510        // The seat that asked is gone for good now, exactly like any other
2511        // door `graph::Runner::settle_questions` closes the moment `status`
2512        // lands somewhere non-resumable - see that method's own doc. Nothing
2513        // else reaches this one before the next `janitor()` startup pass
2514        // (`clean::abandon_settled_questions`), and a daemon that stays up
2515        // for days must not leave an open question badging the operator
2516        // until it happens to restart.
2517        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2518            tracing::warn!("abandon questions for {id}: {e:#}");
2519        }
2520        abandoned.push(id);
2521    }
2522    abandoned
2523}
2524
2525#[derive(Debug, Clone, Serialize, Deserialize)]
2526struct TaskWorker {
2527    opts: Opts,
2528    queue: PathBuf,
2529    task: String,
2530    #[serde(default)]
2531    lane: PermitKind,
2532    #[serde(default)]
2533    standalone: bool,
2534}
2535
2536fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2537    Ok(crate::worker::active(home)?
2538        .into_iter()
2539        .filter(|job| job.kind == "task")
2540        .collect())
2541}
2542
2543fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2544    task_jobs(home)?
2545        .into_iter()
2546        .filter_map(
2547            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2548                Ok(request) if !request.standalone => Some(Ok(job)),
2549                Ok(_) => None,
2550                Err(error) => Some(Err(error.into())),
2551            },
2552        )
2553        .collect()
2554}
2555
2556/// Whether an independent scheduler can be controlled without its web parent.
2557#[must_use]
2558pub fn managed(home: &Path) -> bool {
2559    match crate::worker::active(home) {
2560        Err(error) => {
2561            tracing::error!("cannot determine scheduler ownership: {error:#}");
2562            true
2563        }
2564        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2565        Ok(_) => {
2566            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2567                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2568        }
2569    }
2570}
2571
2572/// Start a detached, singleton scheduler using this executable generation.
2573pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2574    anyhow::ensure!(
2575        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2576        "the scheduler is stopping; wait for retirement before starting it again"
2577    );
2578    crate::worker::spawn(
2579        home,
2580        "scheduler",
2581        "scheduler",
2582        serde_json::to_value(opts.absolute()?)?,
2583    )
2584    .await
2585}
2586
2587fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2588    home.join("worker-parks").join(format!("{}.json", job.id))
2589}
2590
2591fn request_task_park(
2592    home: &Path,
2593    job: &crate::worker::Job,
2594    cause: crate::run::ParkCause,
2595) -> Result<()> {
2596    let path = park_request_path(home, job);
2597    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2598    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2599    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2600}
2601
2602/// Stop dispatch immediately; only an explicit park reaches existing workers.
2603pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2604    if control == crate::worker::Control::Park {
2605        for job in owned_task_jobs(home)? {
2606            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2607        }
2608    }
2609    crate::worker::request(home, "scheduler", control)
2610}
2611
2612/// Replace the scheduler, leaving all active task and conversation jobs alone.
2613pub async fn restart_detached(home: &Path) -> Result<()> {
2614    let active = crate::worker::active(home)?;
2615    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2616    if prior.is_none() && !managed(home) {
2617        return Ok(());
2618    }
2619    let opts: Opts = match prior {
2620        Some(job) => serde_json::from_value(job.payload)?,
2621        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2622    };
2623    request_control(home, crate::worker::Control::Stop)?;
2624    loop {
2625        let reserved = crate::worker::active(home)?
2626            .iter()
2627            .any(|job| job.kind == "scheduler");
2628        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2629            break;
2630        }
2631        tokio::time::sleep(Duration::from_millis(100)).await;
2632    }
2633    spawn_detached(home, &opts).await?;
2634    Ok(())
2635}
2636
2637/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2638pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2639    let opts: Opts = serde_json::from_value(payload)?;
2640    let _ = home;
2641    serve_until(opts, Stop::new()).await
2642}
2643
2644/// Execute and settle one task with the queue claim owned by this process.
2645pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2646    let request: TaskWorker = serde_json::from_value(payload)?;
2647    let queue = Queue::at(request.queue);
2648    let key = format!("task:{}", request.task);
2649    let job = task_jobs(home)?
2650        .into_iter()
2651        .find(|job| job.key == key)
2652        .context("task worker reservation is missing")?;
2653    let park_path = park_request_path(home, &job);
2654    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2655    // our durable reservation. Never execute before that ownership hand-off.
2656    let _claim = loop {
2657        match queue.claim(&request.task) {
2658            Ok(claim) => break claim,
2659            // Only contention (the claim file exists) is worth waiting out; an
2660            // I/O failure must end this worker instead of pinning its lane.
2661            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2662                return Err(e.context("claim the task for its worker"));
2663            }
2664            Err(_) => {
2665                sweep_stale_claims(&queue, STALE_CLAIM);
2666                tokio::time::sleep(Duration::from_millis(50)).await;
2667            }
2668        }
2669    };
2670    let mut task = queue.get(&request.task)?;
2671    if !task.status.runnable()
2672        || (!request.standalone
2673            && request.lane
2674                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2675    {
2676        return Ok(());
2677    }
2678    let stop = Stop::new();
2679    let watcher = {
2680        let home = home.to_path_buf();
2681        let stop = stop.clone();
2682        let park_path = park_path.clone();
2683        tokio::spawn(async move {
2684            loop {
2685                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2686                    let cause = std::fs::read(&park_path)
2687                        .ok()
2688                        .and_then(|body| serde_json::from_slice(&body).ok())
2689                        .unwrap_or(crate::run::ParkCause::Operator);
2690                    stop.park(cause);
2691                    return;
2692                }
2693                tokio::time::sleep(Duration::from_millis(200)).await;
2694            }
2695        })
2696    };
2697    let quota = if request.standalone {
2698        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2699    } else {
2700        let status = Arc::new(Mutex::new(Status::new()));
2701        Box::pin(attempt(
2702            &request.opts,
2703            &queue,
2704            &status,
2705            &stop,
2706            crate::graph::Pause::new(),
2707            &mut task,
2708        ))
2709        .await
2710    };
2711    watcher.abort();
2712    let _ = std::fs::remove_file(park_path);
2713    persist_cooldown(home, &quota).await?;
2714    Ok(())
2715}
2716
2717/// Launch the standalone task worker with a claim-to-reservation handoff.
2718/// Returns only after the worker owns a durable execution reservation.
2719pub async fn spawn_claimed(
2720    home: &Path,
2721    opts: &Opts,
2722    queue: &Queue,
2723    task: &Task,
2724    claim: crate::queue::Claim,
2725) -> Result<crate::worker::Job> {
2726    let request = TaskWorker {
2727        opts: opts.absolute()?,
2728        queue: std::path::absolute(queue.root())?,
2729        task: task.id.clone(),
2730        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2731        standalone: true,
2732    };
2733    let job = crate::worker::spawn(
2734        home,
2735        "task",
2736        &format!("task:{}", task.id),
2737        serde_json::to_value(request)?,
2738    )
2739    .await?;
2740    drop(claim);
2741    Ok(job)
2742}
2743
2744/// Transfer a standalone caller's claim only after the detached worker is live,
2745/// then follow that worker to its final (non-automatically-retrying) outcome.
2746pub async fn run_detached_claimed(
2747    opts: &Opts,
2748    queue: &Queue,
2749    task: &mut Task,
2750    claim: crate::queue::Claim,
2751) -> Result<()> {
2752    let home = crate::run::home();
2753    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2754    loop {
2755        // Reconcile execution leases even without a scheduler. A dead worker
2756        // must become a reported failure, never an infinite persisted wait.
2757        crate::worker::active(&home)?;
2758        let current = crate::worker::get(&home, &job.id)?;
2759        if matches!(
2760            current.status,
2761            crate::worker::Status::Finished | crate::worker::Status::Failed
2762        ) {
2763            *task = queue.get(&task.id)?;
2764            anyhow::ensure!(
2765                current.status != crate::worker::Status::Failed,
2766                "task worker failed: {}",
2767                current.result.as_deref().unwrap_or("unknown failure")
2768            );
2769            return Ok(());
2770        }
2771        tokio::time::sleep(Duration::from_millis(200)).await;
2772    }
2773}
2774
2775async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2776    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2777        let _lease = loop {
2778            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2779                break lease;
2780            }
2781            tokio::time::sleep(Duration::from_millis(10)).await;
2782        };
2783        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2784            let path = home.join("task-quota-cooldown.json");
2785            let temporary = path.with_extension("json.tmp");
2786            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2787            std::fs::rename(temporary, path)?;
2788        }
2789    }
2790    Ok(())
2791}
2792
2793fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2794    match std::fs::read(home.join("task-quota-cooldown.json")) {
2795        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2796        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2797        Err(error) => Err(error.into()),
2798    }
2799}
2800
2801/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2802///
2803/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2804/// sets, so there is one loop body rather than two that drift apart the first
2805/// time the retry policy changes on only one of them.
2806pub async fn serve(opts: Opts) -> Result<()> {
2807    tracing::info!(
2808        "automatic update and restart requires magi web; standalone serve does not restart"
2809    );
2810    serve_until(opts, Stop::new()).await
2811}
2812
2813/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2814///
2815/// A stop retires dispatch promptly, including while a worker launch is being
2816/// acknowledged. Already reserved workers own their attempts independently and
2817/// finish with their started executable. Explicit park additionally forwards
2818/// durable park requests; neither scheduler retirement nor update does so.
2819///
2820/// While the queue is empty the stop is honoured within one wakeup rather than
2821/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2822/// caller that taps stop does not sit through the remainder of a sleep.
2823pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2824    let opts = opts.absolute()?;
2825    let home = crate::run::home();
2826    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2827        .context("another scheduler already owns this home")?;
2828    if let Some(reading) = read_status(&home)
2829        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2830    {
2831        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2832    }
2833    if !crate::worker::active(&home)?
2834        .iter()
2835        .any(|job| job.kind == "scheduler")
2836    {
2837        crate::worker::clear_control(&home, "scheduler")?;
2838    }
2839    std::fs::write(
2840        home.join("scheduler-options.json"),
2841        serde_json::to_vec(&opts)?,
2842    )?;
2843    let control = {
2844        let home = home.clone();
2845        let stop = stop.clone();
2846        tokio::spawn(async move {
2847            loop {
2848                match crate::worker::control(&home, "scheduler").ok().flatten() {
2849                    Some(crate::worker::Control::Park) => {
2850                        let _ = request_control(&home, crate::worker::Control::Park);
2851                        stop.park(crate::run::ParkCause::Operator);
2852                        break;
2853                    }
2854                    Some(crate::worker::Control::Stop) => {
2855                        stop.stop();
2856                        break;
2857                    }
2858                    None => {}
2859                }
2860                tokio::time::sleep(Duration::from_millis(100)).await;
2861            }
2862        })
2863    };
2864    let signal = {
2865        let stop = stop.clone();
2866        tokio::spawn(async move {
2867            if tokio::signal::ctrl_c().await.is_ok() {
2868                stop.stop();
2869                tracing::info!("scheduler shutdown requested; independent workers continue");
2870            }
2871        })
2872    };
2873
2874    let worktrees_root = opts
2875        .worktrees_root
2876        .clone()
2877        .unwrap_or_else(crate::run::default_worktree_root);
2878    let outcome = drive(
2879        &opts,
2880        &Queue::open(),
2881        &status_path(),
2882        &crate::run::home(),
2883        &worktrees_root,
2884        &stop,
2885    )
2886    .await;
2887
2888    signal.abort();
2889    control.abort();
2890    outcome
2891}
2892
2893/// The loop proper: setup, poll, teardown, with the queue and the status file
2894/// supplied rather than discovered.
2895///
2896/// All three of `home`, `worktrees_root` and the queue/status paths are
2897/// parameters rather than resolved here, for the same reason:
2898/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2899/// so a unit test that pinned it would fight every other test in the binary,
2900/// and a loop that resolved its own worktree bay could only be exercised
2901/// against the operator's real `~/wt/<repo>` - publishing over a live
2902/// daemon's status file, claiming tasks out of a live backlog, and, since
2903/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2904/// whatever the operator actually has on disk.
2905async fn drive(
2906    opts: &Opts,
2907    queue: &Queue,
2908    status_file: &Path,
2909    home: &Path,
2910    worktrees_root: &Path,
2911    stop: &Stop,
2912) -> Result<()> {
2913    // The status file is a *snapshot*, not a stream of events: a reader only
2914    // ever wants the latest values, and every tick rewrites the whole file
2915    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2916    // while an mpsc channel would force the loop to re-send unchanged fields on
2917    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2918    // for no gain. The lock is only ever held across a field assignment, never
2919    // across an await.
2920    let recovery_cfg = prepare(&opts.repo, opts).ok();
2921    let daemon_cfg = recovery_cfg
2922        .as_ref()
2923        .map(|c| c.daemon.clone())
2924        .unwrap_or_default();
2925    let reconciled = crate::driver::reconcile(home);
2926    if !reconciled.is_empty() {
2927        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2928    }
2929    let mut initial_status = Status::new();
2930    let owned = owned_task_jobs(home)?;
2931    initial_status.current = current_work(home, Timestamp::now())
2932        .into_iter()
2933        .filter(|current| {
2934            owned
2935                .iter()
2936                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2937        })
2938        .collect();
2939    initial_status.idle = initial_status.current.is_empty();
2940    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2941        recovery_cfg.as_ref(),
2942        daemon_cfg.max_deputies,
2943    ));
2944    let status = Arc::new(Mutex::new(initial_status));
2945    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2946    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2947
2948    // Read once at startup, not per task: how many runs this loop drives at
2949    // once is a property of the machine running it, not of whichever
2950    // repository a given task happens to name - see
2951    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2952    // fact in the same sense the agent roster is.
2953    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2954
2955    tracing::info!(
2956        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2957        queue.root().display(),
2958        opts.poll.as_secs(),
2959        opts.max_attempts,
2960        concurrency,
2961        if daemon_cfg.pause_for_interrupts {
2962            ", interrupts enabled"
2963        } else {
2964            ""
2965        }
2966    );
2967
2968    let outcome = tokio::select! {
2969        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2970            max_concurrent: concurrency,
2971            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2972            recovery_cfg,
2973        }) => outcome,
2974        () = async {
2975            while !stop.stopped() {
2976                tokio::time::sleep(Duration::from_millis(25)).await;
2977            }
2978        } => {
2979            if stop.parking() {
2980                request_control(home, crate::worker::Control::Park)?;
2981            }
2982            Ok(())
2983        }
2984    };
2985
2986    stop.busy.store(0, Ordering::SeqCst);
2987    beat.abort();
2988    clear_status_at(status_file);
2989    outcome
2990}
2991
2992/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2993/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2994pub(crate) fn release_watch_settings_from_config(
2995    home: &Path,
2996    repo: &Path,
2997    cfg: &Config,
2998) -> (Vec<PathBuf>, u64) {
2999    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3000        .into_iter()
3001        .map(|r| r.path)
3002        .collect();
3003    // Repositories the daemon has worked in, wherever they live: a task may
3004    // name one outside `[repos] roots`, and its release PR must be watched too.
3005    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3006        .list()
3007        .into_iter()
3008        .map(|t| t.repo)
3009        .collect();
3010    let runs = home.join("runs");
3011    for id in crate::run::list_ids_in(&runs) {
3012        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3013            .ok()
3014            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3015            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3016        known.extend(repo);
3017    }
3018    for k in known {
3019        let k = k.canonicalize().unwrap_or(k);
3020        if k.join(".git").exists() && !paths.contains(&k) {
3021            paths.push(k);
3022        }
3023    }
3024    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3025    if !paths.contains(&own) {
3026        paths.push(own);
3027    }
3028    (paths, cfg.daemon.release_stall_minutes)
3029}
3030
3031/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3032const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3033
3034/// Refresh the status file on a fixed tick.
3035///
3036/// Separate from the loop because a run takes tens of minutes: a status file
3037/// written only between tasks would look stale for the whole of every run, and
3038/// a reader would report the daemon dead exactly while it was busiest.
3039async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3040    loop {
3041        tokio::time::sleep(HEARTBEAT).await;
3042        let snapshot = {
3043            let mut guard = lock(&status);
3044            guard.updated_at = Timestamp::now();
3045            guard.clone()
3046        };
3047        if let Err(e) = write_status_to(&path, &snapshot) {
3048            // A failed heartbeat must not take the daemon down: the loop is the
3049            // product, the status file is only the window onto it.
3050            tracing::warn!("could not refresh the daemon status file: {e:#}");
3051        }
3052    }
3053}
3054
3055/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3056/// if so, whether that wait is over.
3057#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3058enum LandResume {
3059    /// The task's last run is not parked on a land approval; schedule it
3060    /// like any other candidate.
3061    NotLanding,
3062    /// Parked in `land`, waiting on a question nobody has answered yet.
3063    /// Left alone: attempting it now would only re-observe the same pull
3064    /// request and park again, spending a `gh` call on a decision that has
3065    /// not changed since the last time this was checked.
3066    StillWaiting,
3067    /// Parked in `land`, and the question is settled - answered or
3068    /// abandoned. Resuming this is the one kind of candidate that must not
3069    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3070    Ready,
3071}
3072
3073/// Classify a runnable candidate by whether it is parked on a land-merge
3074/// approval. Read-only - no claim taken, nothing written - so it is cheap
3075/// enough to call on every candidate, every poll.
3076fn land_resume_state(task: &Task) -> LandResume {
3077    let Some(run_id) = task.execution_runs().last() else {
3078        return LandResume::NotLanding;
3079    };
3080    let Ok(state) = RunState::load(run_id) else {
3081        return LandResume::NotLanding;
3082    };
3083    if !state.parked {
3084        return LandResume::NotLanding;
3085    }
3086    if state.status == RunStatus::Landing
3087        && state.land_approval.as_ref().is_some_and(|binding| {
3088            ask::Questions::open()
3089                .get(&binding.question)
3090                .is_ok_and(|q| {
3091                    q.run == state.id
3092                        && q.resolution()
3093                            .as_deref()
3094                            .is_some_and(crate::merge_decision::stops)
3095                })
3096        })
3097    {
3098        return LandResume::Ready;
3099    }
3100    if !implementers_match(task, &state) {
3101        return LandResume::NotLanding;
3102    }
3103    // Parked in `land` on the merge approval, or at `merge` on the owner's
3104    // word about a title/body the posting gate withheld. Told apart by the
3105    // run's own record, not by a status both can share.
3106    let node = if state.status == RunStatus::Landing {
3107        land::APPROVAL_NODE
3108    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3109        crate::github_text::ASK_NODE
3110    } else {
3111        return LandResume::NotLanding;
3112    };
3113    let store = ask::Questions::open();
3114    let waiting = store
3115        .list()
3116        .into_iter()
3117        .filter(|q| &q.run == run_id && q.node == node)
3118        .max_by(|a, b| a.id.cmp(&b.id));
3119    let Some(mut q) = waiting else {
3120        return LandResume::Ready;
3121    };
3122    if !q.status.open() {
3123        // Repair spends agent resources and must obey concurrency and quota
3124        // waits; only a merge/hold decision may use the decision-only lane.
3125        if q.resolution().as_deref() == Some(land::REPAIR) {
3126            return if state.liveness(false) == Liveness::Live {
3127                LandResume::StillWaiting
3128            } else {
3129                LandResume::NotLanding
3130            };
3131        }
3132        return LandResume::Ready;
3133    }
3134    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3135    // nobody ever answered; land's approval bypasses that wait entirely (see
3136    // `land::approval_gate`), so the same deadline has to be enforced here
3137    // instead, or `graph.answer_timeout` silently stops meaning anything for
3138    // a land approval and a run can sit `StillWaiting` forever with nobody
3139    // told to look at it.
3140    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3141    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3142    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3143        q.abandon(format!(
3144            "no answer within {}s of asking",
3145            timeout.as_secs().max(1)
3146        ));
3147        // If this can't be persisted, do not treat the wait as settled on a
3148        // guess: fall through and try again next poll.
3149        if store.put(&mut q).is_ok() {
3150            return LandResume::Ready;
3151        }
3152    }
3153    LandResume::StillWaiting
3154}
3155
3156/// How often the loop rechecks for new work while something it already
3157/// started is still running, rather than sleeping out the whole
3158/// [`Opts::poll`] interval.
3159///
3160/// Short on purpose: this is what lets a land-merge approval that comes back
3161/// while another task is mid-competition be noticed and resumed within a
3162/// fraction of a second, not within the next multi-second poll.
3163const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3164
3165/// How often [`poll`] rechecks the shared build cache against its cap at a
3166/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3167/// waiting for the queue to run dry.
3168///
3169/// A queue that never empties means the `janitor` call at the bottom of this
3170/// loop's fully-idle branch can go unreached for as long as the backlog
3171/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3172/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3173/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3174/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3175/// backlog of short tasks does not pay for that walk on every poll.
3176const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3177
3178/// State of [`poll`]'s own interrupt-scheduling sequence - see
3179/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3180/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3181/// both kept free of `Task`'s non-identity fields on purpose: every decision
3182/// here turns only on task ids and which ones are in flight, so the "never
3183/// more than one run at once" and "exactly one resume" invariants can be
3184/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3185/// queue - which is exactly the coverage this feature's first two attempts
3186/// were missing.
3187///
3188/// Persisted after every transition, so scheduler replacement preserves the
3189/// interrupt's exclusive turn and the interrupted task's priority resume.
3190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3191enum Interrupt {
3192    /// No interrupt sequence in progress. Ordinary dispatch applies.
3193    Idle,
3194    /// `interrupt_task` is runnable and exactly one other run is in flight;
3195    /// `parked` names that one task's id. Dispatch is withheld from
3196    /// everyone, including `interrupt_task` itself, until it has left
3197    /// flight - only then is `interrupt_task` let through.
3198    ///
3199    /// `parked` is a `Vec` rather than a bare id for symmetry with
3200    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3201    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3202    /// when exactly one run is in flight, so it is guaranteed to hold
3203    /// exactly one entry in practice - see that branch's own doc for why
3204    /// more than one is deliberately never attempted.
3205    Parking {
3206        parked: Vec<String>,
3207        interrupt_task: String,
3208    },
3209    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3210    /// withheld from everyone until it leaves flight - merged, failed, held,
3211    /// it makes no difference - at which point the sequence moves to
3212    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3213    /// going straight to `Idle` would hand `parked` back to ordinary
3214    /// priority-order dispatch, where a higher-priority task filed in the
3215    /// meantime could start ahead of it.
3216    Running {
3217        parked: Vec<String>,
3218        interrupt_task: String,
3219    },
3220    /// `interrupt_task` left flight; `parked` still names the one run this
3221    /// sequence owes a resume. Dispatch is withheld from everyone except
3222    /// that task - see [`interrupt_gate`] - so the resume this feature
3223    /// promises is never raced by, or run alongside, an unrelated candidate.
3224    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3225    /// own doc on abandonment - the moment it is no longer runnable at all.
3226    Resuming { parked: Vec<String> },
3227}
3228
3229/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3230/// and `runnable` are read-only snapshots of this tick's reality, and the
3231/// only side effect the caller still owes the world is asking whichever
3232/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3233/// site.
3234///
3235/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3236/// accepted rather than a narrower type because that is what [`poll`] already
3237/// has on hand from [`runnable`], and building a second, smaller list on
3238/// every tick just to satisfy this signature would cost more than it proves.
3239///
3240/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3241/// back to a task they are waiting on no longer being [`runnable`] - held,
3242/// blocked, deleted, or finished by some other means entirely, all of which
3243/// an operator can do to a task sitting in the queue with no claim on it at
3244/// all, at any moment, interrupt sequence or not. Without this check the
3245/// sequence would wait forever for a dispatch that can never come, and
3246/// `interrupt_gate` would withhold every other task in the queue right along
3247/// with it - a single `magi task hold` on the wrong id turning into a
3248/// daemon that never dispatches anything again.
3249fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3250    match state {
3251        Interrupt::Idle => {
3252            // Not just "something to interrupt": exactly one thing. More
3253            // than one run in flight only happens above the default
3254            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3255            // one resume, never run alongside anything else" only because
3256            // it is only ever seeded with exactly one id - see
3257            // `Interrupt::Resuming`'s own doc on why releasing more than one
3258            // parked id back to ordinary dispatch cannot be made safe
3259            // against that same setting's own extra concurrency slots.
3260            // Waiting here for the herd to settle to one is the
3261            // simplification this feature's own constraints ask for rather
3262            // than a second concurrency model to reconcile with the first.
3263            if in_flight.len() != 1 {
3264                return Interrupt::Idle;
3265            }
3266            match runnable.iter().find(|t| t.interrupt) {
3267                Some(t) => Interrupt::Parking {
3268                    parked: in_flight.to_vec(),
3269                    interrupt_task: t.id.clone(),
3270                },
3271                None => Interrupt::Idle,
3272            }
3273        }
3274        Interrupt::Parking {
3275            parked,
3276            interrupt_task,
3277        } => {
3278            if in_flight.iter().any(|id| parked.contains(id)) {
3279                // Still waiting for what was in flight to actually stop.
3280                Interrupt::Parking {
3281                    parked,
3282                    interrupt_task,
3283                }
3284            } else if in_flight.contains(&interrupt_task) {
3285                Interrupt::Running {
3286                    parked,
3287                    interrupt_task,
3288                }
3289            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3290                // The parked run(s) are gone, but the interrupt task has not
3291                // been dispatched yet on this tick - `interrupt_gate` is
3292                // what lets it through next.
3293                Interrupt::Parking {
3294                    parked,
3295                    interrupt_task,
3296                }
3297            } else {
3298                // The interrupt task itself is no longer runnable - see this
3299                // function's own doc on abandonment. The parked run(s) still
3300                // get their guaranteed resume; there is simply no interrupt
3301                // to run ahead of them any longer.
3302                Interrupt::Resuming { parked }
3303            }
3304        }
3305        Interrupt::Running {
3306            parked,
3307            interrupt_task,
3308        } => {
3309            if in_flight.contains(&interrupt_task) {
3310                Interrupt::Running {
3311                    parked,
3312                    interrupt_task,
3313                }
3314            } else {
3315                // The interrupt task's own run reached a terminal status,
3316                // whichever one - this is the *only* trigger that moves the
3317                // sequence on, driven straight off the same in-flight
3318                // bookkeeping `poll` already reaps every tick, not a second,
3319                // independent poll of anything.
3320                Interrupt::Resuming { parked }
3321            }
3322        }
3323        Interrupt::Resuming { parked } => {
3324            if in_flight.iter().any(|id| parked.contains(id)) {
3325                // One of the parked runs has been dispatched - the resume
3326                // this sequence owed is fulfilled. Whatever else is left in
3327                // `parked` (ordinarily nothing, at the default concurrency
3328                // of one) rejoins ordinary priority-order dispatch, same as
3329                // any other runnable task.
3330                Interrupt::Idle
3331            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3332                Interrupt::Resuming { parked }
3333            } else {
3334                // Abandonment (see this function's own doc): nothing left in
3335                // `parked` is even runnable any longer.
3336                Interrupt::Idle
3337            }
3338        }
3339    }
3340}
3341
3342/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3343/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3344/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3345/// indistinguishable from any other runnable task - exactly the "off does
3346/// nothing" this feature promises.
3347fn advance_interrupt_tick(
3348    enabled: bool,
3349    state: Interrupt,
3350    in_flight: &[String],
3351    runnable: &[Task],
3352) -> Interrupt {
3353    if !enabled {
3354        return Interrupt::Idle;
3355    }
3356    advance_interrupt(state, in_flight, runnable)
3357}
3358
3359/// Which of this tick's runnable candidates the interrupt sequence actually
3360/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3361/// each half is assertable on its own: this is the half that keeps a
3362/// competition and an interrupt from ever running at the same moment.
3363fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3364    match state {
3365        Interrupt::Idle => candidates,
3366        Interrupt::Parking {
3367            parked,
3368            interrupt_task,
3369        } => {
3370            if in_flight.iter().any(|id| parked.contains(id)) {
3371                Vec::new()
3372            } else {
3373                candidates
3374                    .into_iter()
3375                    .filter(|t| &t.id == interrupt_task)
3376                    .collect()
3377            }
3378        }
3379        Interrupt::Running { .. } => Vec::new(),
3380        // At most one: even if `parked` names more than one id (more than
3381        // one run was in flight when the sequence began, only possible
3382        // above the default `max_concurrent_runs = 1`), only the first match
3383        // is offered. Capping this to a single candidate - not merely to
3384        // `parked`'s own ids - is what makes "exactly one resume, never two
3385        // dispatched together" true regardless of how many ordinary slots
3386        // happen to be free this tick.
3387        Interrupt::Resuming { parked } => candidates
3388            .into_iter()
3389            .find(|t| parked.contains(&t.id))
3390            .into_iter()
3391            .collect(),
3392    }
3393}
3394
3395/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3396/// bundled into one parameter so `poll`'s own signature stays readable -
3397/// see [`drive`]'s call site for where these are actually read.
3398struct DispatchLimits {
3399    /// How many *ordinary* candidates run at once. See
3400    /// [`crate::config::Daemon::max_concurrent_runs`].
3401    max_concurrent: usize,
3402    /// See [`crate::config::Daemon::pause_for_interrupts`].
3403    pause_for_interrupts: bool,
3404    recovery_cfg: Option<Config>,
3405}
3406
3407/// Which semaphore, if any, dispatching a candidate should draw its permit
3408/// from.
3409///
3410/// Pure and separate from [`poll`]'s loop body for the same reason
3411/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3412/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3413/// exactly the policy this feature adds, and a policy only exercisable by
3414/// running the whole loop is a policy nobody checks.
3415#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3416enum PermitKind {
3417    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3418    /// Checked first - a task can be both a land resume and marked
3419    /// [`Task::urgent`], and the resume's own "must not queue behind
3420    /// anything" guarantee takes precedence.
3421    None,
3422    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3423    /// (never in addition to trying) the ordinary pool. This is what lets
3424    /// an urgent task dispatch while every ordinary slot is already checked
3425    /// out, and what stops a second urgent task from opening a third run: it
3426    /// waits on this same one-slot semaphore rather than falling through to
3427    /// the ordinary one.
3428    Urgent,
3429    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3430    /// above.
3431    #[default]
3432    Ordinary,
3433}
3434
3435/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3436/// own boolean, already computed by the caller from [`land_resume_state`].
3437fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3438    if priority {
3439        PermitKind::None
3440    } else if urgent {
3441        PermitKind::Urgent
3442    } else {
3443        PermitKind::Ordinary
3444    }
3445}
3446
3447fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3448    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3449        (0usize, 0usize),
3450        |(ordinary, urgent), request| match request.lane {
3451            PermitKind::Ordinary => (ordinary + 1, urgent),
3452            PermitKind::Urgent => (ordinary, urgent + 1),
3453            PermitKind::None => (ordinary, urgent),
3454        },
3455    );
3456    (
3457        limit.saturating_sub(ordinary),
3458        1usize.saturating_sub(urgent),
3459    )
3460}
3461
3462struct DispatchClaim {
3463    task: Task,
3464    claim: crate::queue::Claim,
3465    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3466}
3467
3468/// Claim and re-read before choosing a lane: a queue listing may predate an
3469/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3470fn claim_dispatch(
3471    queue: &Queue,
3472    candidate: &Task,
3473    cooling_down: bool,
3474    ordinary: &Arc<tokio::sync::Semaphore>,
3475    urgent: &Arc<tokio::sync::Semaphore>,
3476) -> Option<DispatchClaim> {
3477    let Ok(claim) = queue.claim(&candidate.id) else {
3478        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3479        return None;
3480    };
3481    let task = match queue.get(&candidate.id) {
3482        Ok(t) if t.status.runnable() => t,
3483        Ok(_) => return None,
3484        Err(e) => {
3485            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3486            return None;
3487        }
3488    };
3489    let resume = land_resume_state(&task);
3490    if resume == LandResume::StillWaiting {
3491        return None;
3492    }
3493    let priority = resume == LandResume::Ready;
3494    if !priority && cooling_down {
3495        return None;
3496    }
3497    // Never borrow an ordinary slot when the single urgent slot is busy.
3498    // Keep scanning other candidates when either pool has no free slot.
3499    let permit = match permit_kind(priority, task.urgent) {
3500        PermitKind::None => None,
3501        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3502        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3503    };
3504    // Persist the dispatch order under the claim, before config discovery or
3505    // coordination waits can reorder concurrent starts.
3506    let stamp = Timestamp::now();
3507    let mut task = task;
3508    task.dispatched_at = Some(stamp);
3509    if let Err(e) = queue.modify(&task.id, |t| {
3510        t.dispatched_at = Some(stamp);
3511        true
3512    }) {
3513        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3514    }
3515    Some(DispatchClaim {
3516        task,
3517        claim,
3518        permit,
3519    })
3520}
3521
3522/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3523/// teardown and cannot skip the teardown on an early return.
3524///
3525/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3526/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3527/// land approval that has since been answered is dispatched outside that
3528/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3529/// the whole point of parking there is that it must not queue behind
3530/// whatever else the loop happens to be running, even at the default of one.
3531/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3532/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3533/// these exemptions is still subject to the interrupt gate below, urgent
3534/// included: a land-resume or urgent candidate is exactly as much "something
3535/// else running" as an ordinary one from the interrupt sequence's point of
3536/// view, and letting either slip through while a run is being parked, or
3537/// while the interrupt task itself has the floor, is precisely the second
3538/// run 75dd's own "at most one run, ever, at once" guarantee must never
3539/// allow - see [`Interrupt`]'s own doc.
3540#[derive(Serialize, Deserialize)]
3541struct ServiceWorker {
3542    opts: Opts,
3543    queue: PathBuf,
3544    worktrees_root: PathBuf,
3545    operation: String,
3546}
3547
3548fn load_conductor(home: &Path) -> Result<Conductor> {
3549    match std::fs::read(home.join("conductor-state.json")) {
3550        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3551        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3552        Err(error) => Err(error.into()),
3553    }
3554}
3555
3556fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3557    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3558        .into_iter()
3559        .map(|c| c.task)
3560        .collect();
3561    let stalled = stalled_tasks(queue, home, Timestamp::now());
3562    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3563    let finished = finished_tasks(queue)
3564        .into_iter()
3565        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3566        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3567        .collect();
3568    let queued = queued_tasks(queue)
3569        .into_iter()
3570        .filter(|t| !live.contains(&t.id))
3571        .collect();
3572    (queued, stalled, finished)
3573}
3574
3575async fn start_service(
3576    home: &Path,
3577    opts: &Opts,
3578    queue: &Queue,
3579    worktrees_root: &Path,
3580    operation: &str,
3581    cfg: Option<&Config>,
3582    busy: bool,
3583) -> Result<()> {
3584    // Fetch policy is live configuration, unlike question recovery capacity.
3585    // Reload before both cadence and eligibility, including disabled -> enabled.
3586    let fetch_cfg = if operation == "fetch" {
3587        match prepare(&opts.repo, opts) {
3588            Ok(cfg) => Some(cfg),
3589            Err(error) => {
3590                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3591                return Ok(());
3592            }
3593        }
3594    } else {
3595        None
3596    };
3597    let cfg = fetch_cfg.as_ref().or(cfg);
3598    let ticks = home.join("service-ticks");
3599    std::fs::create_dir_all(&ticks)?;
3600    let receipt = ticks.join(format!("daemon-{operation}"));
3601    let last = std::fs::read(&receipt)
3602        .ok()
3603        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3604    let interval = match operation {
3605        "disk-pressure" => 30,
3606        "cache" => CACHE_CHECK_INTERVAL_SECS,
3607        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3608        _ => opts.poll.as_secs().max(1),
3609    };
3610    let now = Timestamp::now();
3611    if !cache_check_due(last, now, interval) {
3612        return Ok(());
3613    }
3614    let key = format!("service:daemon-{operation}");
3615    if crate::worker::active(home)?
3616        .iter()
3617        .any(|job| job.key == key)
3618    {
3619        return Ok(());
3620    }
3621    let eligible = match operation {
3622        "conductor" => {
3623            let (queued, stalled, finished) = conductor_work(queue, home);
3624            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3625                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3626        }
3627        "maintenance" => Questions::at(home.join("questions"))
3628            .list()
3629            .iter()
3630            .any(|q| {
3631                q.chosen_action().is_some_and(|action| action.maintenance())
3632                    && !home
3633                        .join("choice-actions")
3634                        .join(format!("{}.json", q.id))
3635                        .exists()
3636            }),
3637        "housekeeping" => !busy && runnable(queue).is_empty(),
3638        "cache" => {
3639            !busy
3640                && !runnable(queue).is_empty()
3641                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3642        }
3643        "disk-pressure" => busy,
3644        "fetch" => {
3645            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3646        }
3647        _ => false,
3648    };
3649    if !eligible {
3650        return Ok(());
3651    }
3652    let request = ServiceWorker {
3653        opts: opts.absolute()?,
3654        queue: std::path::absolute(queue.root())?,
3655        worktrees_root: std::path::absolute(worktrees_root)?,
3656        operation: operation.to_owned(),
3657    };
3658    if let Err(error) =
3659        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3660    {
3661        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3662    }
3663    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3664    Ok(())
3665}
3666
3667/// Finite maintenance jobs survive scheduler replacement without duplicating
3668/// agent calls or cancelling an operation between its effect and receipt.
3669pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3670    let request: ServiceWorker = serde_json::from_value(payload)?;
3671    let opts = &request.opts;
3672    let queue = Queue::at(request.queue);
3673    let questions = Questions::at(home.join("questions"));
3674    match request.operation.as_str() {
3675        "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3676        "conductor" => {
3677            let path = home.join("conductor-state.json");
3678            let mut conductor = load_conductor(home)?;
3679            let (queued, stalled, finished) = conductor_work(&queue, home);
3680            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3681                && conductor.worth_a_look(&queue, &stalled, &finished)
3682            {
3683                let cfg = prepare(&opts.repo, opts)?;
3684                conductor
3685                    .maybe_run(
3686                        &cfg,
3687                        &opts.repo,
3688                        &queue,
3689                        &questions,
3690                        home,
3691                        &queued,
3692                        &stalled,
3693                        &finished,
3694                        opts.max_attempts,
3695                    )
3696                    .await;
3697                let temporary = path.with_extension("json.tmp");
3698                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3699                std::fs::rename(temporary, path)?;
3700            }
3701        }
3702        "fetch" => {
3703            let cfg = prepare(&opts.repo, opts)?;
3704            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3705                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3706                tracing::debug!("fetch origins: {outcome:?}");
3707            }
3708        }
3709        "cache" => {
3710            if task_jobs(home)?.is_empty() {
3711                let mut checked = None;
3712                maybe_prune_cache_between_runs(
3713                    &opts.repo,
3714                    opts,
3715                    home,
3716                    &Stop::new(),
3717                    &mut checked,
3718                    Timestamp::now(),
3719                )
3720                .await;
3721            }
3722        }
3723        "disk-pressure" => {
3724            if let Ok(cfg) = prepare(&opts.repo, opts) {
3725                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3726                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3727                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3728                }
3729                for current in current_work(home, Timestamp::now()) {
3730                    if let Ok(state) = RunState::load_under(&current.run, home)
3731                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3732                    {
3733                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3734                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3735                        }) {
3736                            request_task_park(
3737                                home,
3738                                &job,
3739                                crate::run::ParkCause::Interrupt {
3740                                    reason: reason.clone(),
3741                                },
3742                            )?;
3743                        }
3744                        notices::raise_in(
3745                            home,
3746                            Notice::warn(
3747                                "disk:pressure",
3748                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3749                            ),
3750                        );
3751                    }
3752                }
3753            }
3754        }
3755        "housekeeping" => {
3756            if task_jobs(home)?.is_empty() {
3757                if let Ok(cfg) = prepare(&opts.repo, opts) {
3758                    crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3759                }
3760                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3761                resweep_superseded_attempts(&queue, home);
3762                triage_held(&queue, home, opts).await;
3763            }
3764        }
3765        operation => bail!("unknown daemon service {operation}"),
3766    }
3767    Ok(())
3768}
3769
3770/// Only a different request under the same key is a dispatch handoff race.
3771/// Our own unacknowledged reservation is a startup failure, not competing work:
3772/// stop dispatch without fencing it, so an already detached child may still run.
3773fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3774    let key = format!("task:{}", request.task);
3775    let payload = serde_json::to_value(request)?;
3776    if crate::worker::active(home)?
3777        .iter()
3778        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3779    {
3780        tracing::warn!(
3781            "task {} acquired a competing worker reservation: {error:#}",
3782            crate::run::short_of(&request.task)
3783        );
3784        return Ok(());
3785    }
3786    tracing::error!("task worker startup stopped dispatch: {error:#}");
3787    notices::raise_in(
3788        home,
3789        Notice::error(
3790            "loop:worker-startup",
3791            // Startup diagnostics may contain private child-process details;
3792            // keep them in the local error/log rather than the chat or notifier.
3793            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),
3794        ).link(Link::Task { id: request.task.clone() }),
3795    );
3796    Err(error).with_context(|| {
3797        format!(
3798            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3799            crate::run::short_of(&request.task)
3800        )
3801    })
3802}
3803
3804async fn poll(
3805    opts: &Opts,
3806    queue: &Queue,
3807    status: &Arc<Mutex<Status>>,
3808    home: &Path,
3809    worktrees_root: &Path,
3810    stop: &Stop,
3811    limits: DispatchLimits,
3812) -> Result<()> {
3813    let mut attempted = Vec::new();
3814    let mut settling_once_services = false;
3815    let interrupt_path = home.join("scheduler-interrupt.json");
3816    let mut interrupt = match std::fs::read(&interrupt_path) {
3817        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3818        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3819        Err(error) => return Err(error.into()),
3820    };
3821    let mut previous = std::collections::BTreeSet::<String>::new();
3822    while !stop.stopped() {
3823        let jobs: Vec<_> = crate::worker::active(home)?
3824            .into_iter()
3825            .filter(|job| job.kind == "task")
3826            .collect();
3827        let requests: Vec<_> = jobs
3828            .iter()
3829            .map(|job| {
3830                serde_json::from_value::<TaskWorker>(job.payload.clone())
3831                    .with_context(|| format!("read live task worker {}", job.id))
3832            })
3833            .collect::<Result<_>>()?;
3834        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3835        let owned: std::collections::BTreeSet<_> = requests
3836            .iter()
3837            .filter(|r| !r.standalone)
3838            .map(|r| r.task.clone())
3839            .collect();
3840        let current: Vec<_> = requests
3841            .iter()
3842            .zip(&jobs)
3843            .filter(|(request, _)| !request.standalone)
3844            .map(|(request, job)| Current {
3845                worker: Some(job.id.clone()),
3846                task: request.task.clone(),
3847                run: queue
3848                    .get(&request.task)
3849                    .ok()
3850                    .and_then(|task| task.execution_runs().last().cloned())
3851                    .unwrap_or_default(),
3852            })
3853            .collect();
3854        {
3855            let mut snapshot = lock(status);
3856            snapshot.polls += 1;
3857            snapshot.completed += previous.difference(&owned).count();
3858            snapshot.current = current;
3859            snapshot.idle = owned.is_empty();
3860        }
3861        previous = owned.clone();
3862        stop.busy.store(owned.len(), Ordering::SeqCst);
3863
3864        // Slots are reconstructed from durable reservations and OS-held worker
3865        // leases, not this scheduler's lifetime or mutable task urgency.
3866        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3867        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3868        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3869        let mut permits = Vec::new();
3870        sweep_stale_claims(queue, STALE_CLAIM);
3871        reclaim_orphaned_running(queue, opts.max_attempts, &live);
3872        reclaim_abandoned_runs(home, Timestamp::now());
3873        let questions = Questions::at(home.join("questions"));
3874
3875        // Deterministic: no model, run before the conductor sees anything so
3876        // its input reflects the queue's current, already-resolved state.
3877        crate::task_chat::sweep(
3878            queue,
3879            &crate::talk::Talks::at(home.join("talks")),
3880            &questions,
3881            home,
3882        );
3883        if let Err(error) = crate::task_inquiry::Outbox::at(home)
3884            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
3885        {
3886            tracing::warn!("task inquiry delivery remains pending: {error:#}");
3887        }
3888        repair_choice_offers(&questions);
3889        resolve_blockers(queue, &questions);
3890        apply_task_choice_actions(queue, &questions, home);
3891        triage::apply_answers(queue, &questions);
3892        reconcile_task_questions(queue, &questions);
3893        let talks = crate::talk::Talks::at(home.join("talks"));
3894        crate::chat_notify::sweep(queue, &talks, home);
3895        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3896        crate::chat_watch::sweep(home, &talks);
3897        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
3898            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
3899        }
3900        let mut turns = tokio::task::JoinSet::new();
3901        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3902        // start_turns dispatches detached turns; no paid work lives in this set.
3903        while turns.join_next().await.is_some() {}
3904
3905        crate::consult::start_services(
3906            home,
3907            &opts.repo,
3908            limits.recovery_cfg.as_ref(),
3909            opts.config.as_deref(),
3910        )
3911        .await?;
3912        for operation in [
3913            "conductor",
3914            "maintenance",
3915            "housekeeping",
3916            "disk-pressure",
3917            "cache",
3918            "fetch",
3919        ] {
3920            // Once an idle --once drain starts settling services, subsequent
3921            // scans only consume their effects. An expired cadence receipt
3922            // must not start another service and keep the drain alive.
3923            if settling_once_services {
3924                break;
3925            }
3926            start_service(
3927                home,
3928                opts,
3929                queue,
3930                worktrees_root,
3931                operation,
3932                limits.recovery_cfg.as_ref(),
3933                !live.is_empty(),
3934            )
3935            .await?;
3936        }
3937        let latest = crate::worker::active(home)?;
3938        if latest.iter().any(|job| job.key == "service:daemon-cache")
3939            || latest
3940                .iter()
3941                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3942        {
3943            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3944            continue;
3945        }
3946        let candidates: Vec<Task> = runnable(queue)
3947            .into_iter()
3948            .filter(|task| !live.contains(&task.id))
3949            .filter(|task| !opts.once || !attempted.contains(&task.id))
3950            .collect();
3951        let in_flight: Vec<_> = owned.iter().cloned().collect();
3952        let prior_interrupt = std::mem::discriminant(&interrupt);
3953        interrupt = advance_interrupt_tick(
3954            limits.pause_for_interrupts,
3955            interrupt,
3956            &in_flight,
3957            &candidates,
3958        );
3959        // Same-variant transitions preserve their identities. Only an actual
3960        // transition needs a durable write, atomically before sending controls.
3961        if prior_interrupt != std::mem::discriminant(&interrupt) {
3962            let temporary = interrupt_path.with_extension("json.tmp");
3963            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3964            std::fs::rename(temporary, &interrupt_path)?;
3965        }
3966        if let Interrupt::Parking {
3967            parked,
3968            interrupt_task,
3969        } = &interrupt
3970        {
3971            for job in jobs.iter().filter(|job| {
3972                parked
3973                    .iter()
3974                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3975            }) {
3976                if crate::worker::control(home, &job.key)?.is_none() {
3977                    request_task_park(
3978                        home,
3979                        job,
3980                        crate::run::ParkCause::Interrupt {
3981                            reason: format!(
3982                                "task {} asked to run first",
3983                                crate::run::short_of(interrupt_task)
3984                            ),
3985                        },
3986                    )?;
3987                }
3988            }
3989        }
3990        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3991        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3992        let mut started = false;
3993        let mut resync = false;
3994        for candidate in candidates {
3995            if stop.stopped() {
3996                break;
3997            }
3998            let Some(DispatchClaim {
3999                task,
4000                claim,
4001                permit,
4002            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
4003            else {
4004                continue;
4005            };
4006            if crate::worker::active(home)?
4007                .iter()
4008                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4009            {
4010                drop(claim);
4011                resync = true;
4012                break;
4013            }
4014            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4015            let request = TaskWorker {
4016                opts: opts.absolute()?,
4017                queue: std::path::absolute(queue.root())?,
4018                task: task.id.clone(),
4019                lane,
4020                standalone: false,
4021            };
4022            // Keep the claim until spawn acknowledges the worker's durable
4023            // reservation. The worker then claims and re-reads before attempt.
4024            if let Err(error) = crate::worker::spawn(
4025                home,
4026                "task",
4027                &format!("task:{}", task.id),
4028                serde_json::to_value(&request)?,
4029            )
4030            .await
4031            {
4032                task_worker_spawn_error(home, &request, error)?;
4033                drop(claim);
4034                resync = true;
4035                break;
4036            }
4037            drop(claim);
4038            permits.extend(permit);
4039            attempted.push(task.id);
4040            started = true;
4041        }
4042        if started || resync {
4043            continue;
4044        }
4045        if owned.is_empty() && opts.once {
4046            settling_once_services = true;
4047            // These finite services can own queue claims or publish answers.
4048            // A skipped claim is not an idle queue until they have finished;
4049            // scan again afterwards so their changes are actually scheduled.
4050            if crate::worker::active(home)?.iter().any(|job| {
4051                job.kind == "daemon-service"
4052                    && matches!(
4053                        job.key.as_str(),
4054                        "service:daemon-housekeeping"
4055                            | "service:daemon-conductor"
4056                            | "service:daemon-maintenance"
4057                    )
4058            }) {
4059                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4060                continue;
4061            }
4062            break;
4063        }
4064        stop.idle(if live.is_empty() {
4065            opts.poll
4066        } else {
4067            RECHECK_WHILE_BUSY.min(opts.poll)
4068        })
4069        .await;
4070    }
4071    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4072    // every queue claim and Runner driver lease through outcome settlement.
4073    stop.busy.store(0, Ordering::SeqCst);
4074    Ok(())
4075}
4076
4077/// A maintenance pass may briefly own the same record while a worker starts.
4078/// Wait without blocking the executor or charging an agent attempt, then read
4079/// ownership again under the acquired lock. Other I/O failures still fail closed.
4080async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4081    let busy = |error: &anyhow::Error| {
4082        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4083            error.kind() == std::io::ErrorKind::WouldBlock
4084                || cfg!(windows) && error.raw_os_error() == Some(33)
4085        })
4086    };
4087    match crate::pr_head::owner_lock(home, id) {
4088        Ok(lock) => return Ok(lock),
4089        Err(error) if busy(&error) => {}
4090        Err(error) => return Err(error),
4091    }
4092    let wait = RunState::load_under(id, home)?
4093        .config
4094        .graph
4095        .timeout_resource_wait;
4096    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4097}
4098
4099/// Historical successors do not revoke a still-resumable public owner. Scan
4100/// under the same lock as publication/driver claims, and fail closed on unknown
4101/// history before spending another attempt.
4102async fn public_resume_owner(
4103    home: &Path,
4104    runs: &[String],
4105    repo: &Path,
4106) -> Result<Option<RunState>> {
4107    let mut owner = None;
4108    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4109        let _lock = resume_owner_lock(home, id).await?;
4110        let state = RunState::load_under(id, home)?;
4111        if state.released()
4112            || state.retired_to.is_some()
4113            || state.pr_taken_over_by.is_some()
4114            || !crate::handover::landing_checkpoint(&state)
4115        {
4116            continue;
4117        }
4118        anyhow::ensure!(
4119            crate::git::toplevel(&state.repo).await?.canonicalize()?
4120                == crate::git::toplevel(repo).await?.canonicalize()?,
4121            "public owner repository differs; inspect run lineage"
4122        );
4123        anyhow::ensure!(
4124            owner.is_none(),
4125            "multiple retained public owners; inspect run lineage"
4126        );
4127        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4128            anyhow::bail!(reason.diagnostic(&state));
4129        }
4130        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4131        anyhow::ensure!(
4132            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4133            "public owner's driver is live or unknown; wait before retrying"
4134        );
4135        owner = Some(state);
4136    }
4137    Ok(owner)
4138}
4139
4140/// Run one claimed task to a terminal status and record the outcome.
4141///
4142/// Every transition is flushed to the queue as it happens, so the state on disk
4143/// is what actually occurred rather than what this process still intends to
4144/// write.
4145async fn attempt(
4146    opts: &Opts,
4147    queue: &Queue,
4148    status: &Arc<Mutex<Status>>,
4149    stop: &Stop,
4150    interrupt_pause: crate::graph::Pause,
4151    task: &mut Task,
4152) -> Vec<QuotaLoss> {
4153    let repo = repo_for(task, &opts.repo);
4154    tracing::info!(
4155        "task {} — {} (repo {})",
4156        task.short(),
4157        task.title,
4158        repo.display()
4159    );
4160
4161    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4162        Ok(owner) => owner,
4163        Err(e) => {
4164            task.hold_machine(Some(format!(
4165                "Cannot verify existing public owner: {e:#}; no attempt started."
4166            )));
4167            record(queue, task);
4168            return Vec::new();
4169        }
4170    };
4171    let resume_runs = public_owner
4172        .as_ref()
4173        .map(|s| vec![s.id.clone()])
4174        .unwrap_or_else(|| task.execution_runs().to_vec());
4175
4176    // A stop spends no agent resources and uses the saved landing owner.
4177    // Current roster edits, missing attachments or a failed config fetch must
4178    // never turn it into a new implementation, or prevent a PR from closing.
4179    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4180        && previous
4181            .merge_decision
4182            .as_ref()
4183            .is_some_and(|decision| !decision.closed)
4184        && previous.status != RunStatus::Landing
4185        && !crate::merge_decision::resumable_hold(&previous)
4186    {
4187        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)));
4188        record(queue, task);
4189        return Vec::new();
4190    }
4191    let stop_owner = resume_runs
4192        .last()
4193        .and_then(|id| RunState::load(id).ok())
4194        .filter(|state| {
4195            crate::merge_decision::resumable_hold(state)
4196                || state.status == RunStatus::Landing
4197                    && state.land_approval.as_ref().is_some_and(|binding| {
4198                        Questions::open().get(&binding.question).is_ok_and(|q| {
4199                            q.run == state.id
4200                                && q.resolution()
4201                                    .as_deref()
4202                                    .is_some_and(crate::merge_decision::stops)
4203                        })
4204                    })
4205        });
4206    if let Some(owner) = stop_owner {
4207        let mut runner = match Runner::resume(&owner.id) {
4208            Ok(runner) => runner,
4209            Err(e) => {
4210                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4211                record(queue, task);
4212                return Vec::new();
4213            }
4214        };
4215        runner.on_pause(stop.pause());
4216        runner.watch_interrupt(interrupt_pause);
4217        let quota_before = runner.state.quota.clone();
4218        let before_start = task.clone();
4219        task.start(owner.id.clone());
4220        if let Err(error) = queue.put(task) {
4221            *task = before_start;
4222            let error = runner.fail_startup("task-start", error);
4223            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4224                task.record_startup_failure(failure.clone());
4225            }
4226            task.hold_manual(Some(format!(
4227                "Could not persist task start; no agents dispatched: {error:#}"
4228            )));
4229            record(queue, task);
4230            return Vec::new();
4231        }
4232        lock(status).current.push(Current {
4233            worker: None,
4234            task: task.id.clone(),
4235            run: owner.id,
4236        });
4237        runner.state.carry_dispatched_resumes(task);
4238        runner.state.next_pass_task_entry = true;
4239        let result = runner.execute().await;
4240        return finish_attempt(
4241            opts.max_attempts,
4242            queue,
4243            task,
4244            &runner.state,
4245            &quota_before,
4246            result,
4247        );
4248    }
4249
4250    if let Some(owner) = &public_owner
4251        && (task.fresh_start || !may_resume_run(owner, task))
4252    {
4253        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)));
4254        record(queue, task);
4255        return Vec::new();
4256    }
4257
4258    if let Some(state) = task
4259        .execution_runs()
4260        .last()
4261        .and_then(|id| RunState::load(id).ok())
4262        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4263    {
4264        task.hold_machine(Some(reason));
4265        record(queue, task);
4266        return Vec::new();
4267    }
4268
4269    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4270        && !task.fresh_start
4271        && task.pr_recovery.is_none()
4272    {
4273        // Authorization still takes the owner lock and execution lease and
4274        // rechecks liveness, retained HEAD and ownership before saving.
4275        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4276            true
4277        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4278            let home = queue.root().parent().expect("queue has a home");
4279            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4280                Ok(()) => true,
4281                Err(error) => {
4282                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4283                    false
4284                }
4285            }
4286        } else {
4287            false
4288        };
4289        if !authorized {
4290            task.hold_machine(Some(format!("Base synchronization remains stopped. {} A release without a new owner approval grants no additional synchronization budget and starts no replacement competition.", held.base_sync_next_action())));
4291            // Retain the existing stop identity when an old release reached the queue.
4292            task.base_sync_notice(&held);
4293            task.resume_override = None;
4294            record(queue, task);
4295            return Vec::new();
4296        }
4297    }
4298    let unfinished = (!task.fresh_start)
4299        .then(|| unfinished_run(&resume_runs, task.short()))
4300        .flatten()
4301        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4302    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4303    if !task.fresh_start
4304        && task.pr_recovery.is_none()
4305        && task.review_branch.is_none()
4306        && task.resume_override.is_none()
4307        && previous
4308            .as_ref()
4309            .is_some_and(|run| run.retired_to.is_some())
4310        && unfinished.is_none()
4311    {
4312        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()));
4313        record(queue, task);
4314        return Vec::new();
4315    }
4316
4317    let saved_recovery = previous.as_ref().filter(|run| {
4318        task.replacement.is_none()
4319            && task.pr_recovery.as_ref().is_some_and(|selected| {
4320                selected
4321                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4322                    .is_ok()
4323                    && selected_starter(selected, Some(run), unfinished.as_deref())
4324                        == Starter::Resume(run.id.clone())
4325            })
4326    });
4327
4328    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4329    // failure here is the network's or the operator's, not the task's: hold
4330    // without spending an attempt, never fall back to a possibly stale copy.
4331    let explicit = match &task.overrides {
4332        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4333        Some(_) => opts.config.as_deref(),
4334        None => opts.config.as_deref(),
4335    };
4336    let (mut config, layers) = if let Some(run) = saved_recovery {
4337        // A matching resume owns its resolved configuration and evidence;
4338        // current layers and inherited overrides only configure new work.
4339        let mut saved = run.clone();
4340        if let Err(e) = saved.configure_recovery_resume() {
4341            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4342            record(queue, task);
4343            return Vec::new();
4344        }
4345        (saved.config, Vec::new())
4346    } else {
4347        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4348            Ok(loaded) => loaded,
4349            Err(e) => {
4350                let reason = format!("[config] {e:#}");
4351                record_config_failure(task, &e);
4352                task.last_error = Some(reason.clone());
4353                task.hold_machine(Some(reason));
4354                record(queue, task);
4355                return Vec::new();
4356            }
4357        };
4358        if let Err(e) = apply_options(&mut config, opts, task) {
4359            task.hold_manual(Some(format!(
4360                "[config] {e:#}; correct the merge override before releasing the task"
4361            )));
4362            record(queue, task);
4363            return Vec::new();
4364        }
4365        if let Some(selected) = &task.pr_recovery
4366            && let Err(e) = selected.configure(&mut config)
4367        {
4368            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4369            record(queue, task);
4370            return Vec::new();
4371        }
4372        (config, layers)
4373    };
4374    let config_evidence = crate::pr_recovery::ConfigEvidence {
4375        layers,
4376        overrides: task.overrides.clone(),
4377        daemon_merge: task
4378            .overrides
4379            .as_ref()
4380            .is_none_or(|o| o.inherit_daemon_options)
4381            .then(|| opts.merge.clone())
4382            .flatten(),
4383    };
4384    apply_task_implementers(&mut config, task);
4385    if let Some(replacement) = &task.replacement {
4386        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4387            old.liveness(false) == Liveness::Dead
4388                && old.merge_decision.as_ref().is_some_and(|d| {
4389                    d.closed
4390                        && d.question == replacement.question
4391                        && d.replacement_run.as_ref().is_none_or(|run| {
4392                            task.execution_runs().last() == Some(run)
4393                                && RunState::load(run).is_ok_and(|current| {
4394                                    current.replaces.as_ref().is_some_and(|pin| {
4395                                        pin.question == replacement.question
4396                                            && pin.agent == replacement.agent
4397                                    })
4398                                })
4399                        })
4400                })
4401        });
4402        if !safe {
4403            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()));
4404            record(queue, task);
4405            return Vec::new();
4406        }
4407        match config.agent(&replacement.agent) {
4408            Ok(agent) if crate::agent::installed(agent) => {}
4409            _ => {
4410                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)));
4411                record(queue, task);
4412                return Vec::new();
4413            }
4414        }
4415        config.graph.implementers = 1;
4416        config.graph.land_approval = true;
4417        config.merge.mode = MergeMode::Pr;
4418        config.graph.selected_implementer = Some(replacement.agent.clone());
4419    }
4420    let p = phrases(&config.graph.language);
4421    let start_failed = p.could_not_start;
4422    // Resolve once for both admission and settlement. The inputs are the
4423    // task's explicit sources (never prose), plus an explicit review source's
4424    // current head; review-only runs may rebase later, and neither fact can
4425    // refund a failed automatic generation.
4426    if let Ok(base) =
4427        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4428            .await
4429        && let Ok(head) =
4430            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4431    {
4432        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4433        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4434            let source = crate::git::rev_parse(&repo, branch)
4435                .await
4436                .unwrap_or_default();
4437            inputs.push_str(&format!(";review:{branch}:{source}"));
4438        }
4439        if let Some(reason) = task
4440            .recovery_exhausted(
4441                &head,
4442                &inputs,
4443                task.attempt_limit
4444                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4445            )
4446            .filter(|_| {
4447                !task.repair_grants.last().is_some_and(|receipt| {
4448                    RunState::load(&receipt.request.run)
4449                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4450                })
4451            })
4452        {
4453            task.hold_unrequested_retry(Some(reason));
4454            record(queue, task);
4455            return Vec::new();
4456        }
4457        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4458    }
4459
4460    // The free-space gate, checked *before* anything is minted: a task that
4461    // waits out a full disk costs nothing yet, and must not spend an attempt
4462    // or start a run the machine cannot finish. Held tasks stay in the list
4463    // for the human to see, and `magi task release` re-queues them when space
4464    // comes back - the same recovery as any other hold. A volume whose free
4465    // space cannot be measured closes the gate too: starting a run blind on a
4466    // disk that may be full is how the machine ends up with 6.7 GB free.
4467    if let Some(reason) = disk_gate(&repo, &config) {
4468        task.notice_cause("disk-space", None, None);
4469        task.last_error = Some(reason.clone());
4470        task.hold_machine(Some(reason.clone()));
4471        record(queue, task);
4472        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4473        // Stable wording - the free-space figures live in the task's hold
4474        // reason, and changing numbers would relight the bell every poll.
4475        notices::raise(
4476            Notice::warn(
4477                &format!("disk:{}", repo.display()),
4478                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4479            )
4480            .link(Link::Task {
4481                id: task.id.clone(),
4482            }),
4483        );
4484        return Vec::new();
4485    }
4486
4487    // A resumable run of this task is carried on, never re-competed. The
4488    // candidates are built and paid for, and a fresh competition races a
4489    // second implementation against them.
4490    //
4491    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4492    // started 3cbf on the same task a moment later, duplicating two and a
4493    // half hours of agent work. Then b25f stalled on a judge that timed out
4494    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4495    // was to blame for - and 4043 started **one second** later, buying three
4496    // fresh implementations to reach the same panel. `RunStatus::resumable`
4497    // rather than `!done()` is what catches the second case: a stall is
4498    // terminal, and its cheap recovery re-asks only the absent seats.
4499    //
4500    // A load failure is warned about rather than silently read as "not
4501    // resumable": the alternative is exactly what let a schema mismatch on
4502    // run `eba2` fall through to a full re-competition with nobody told why.
4503    // `crate::conduct` is what actually offers a better answer than
4504    // `Runner::start` here (see `Recovery::Review`), once this task's next
4505    // failure shows it up as `held`/`failed` with the run state unreadable.
4506    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4507    // branch survived, and this reopens exactly that branch as a
4508    // review-only pass rather than resuming or competing again. Consumed
4509    // (cleared) here whichever way this goes, so it never outlives this one
4510    // attempt - see `queue::Task::review_branch`.
4511    let review_branch = if previous
4512        .as_ref()
4513        .is_some_and(|state| crate::repair_budget::pending(task, state))
4514    {
4515        None
4516    } else {
4517        take_review_branch(task, previous.as_ref())
4518    };
4519    let branch_exists = match &review_branch {
4520        Some(branch) => crate::git::branch_exists(&repo, branch)
4521            .await
4522            .unwrap_or(false),
4523        None => false,
4524    };
4525    // An explicit `magi review <branch>` is reviewed whatever happens to the
4526    // branch unless an explicit implementer change requires fresh work. An
4527    // unfinished run of the same task still wins, so a retry resumes.
4528    let proposed = review_retry_starter(
4529        task,
4530        previous.as_ref(),
4531        review_branch.as_deref(),
4532        branch_exists,
4533        unfinished.as_deref(),
4534    );
4535    let retry_selected = task.replacement.is_some()
4536        && task.resumption.is_some()
4537        && !task.fresh_start
4538        && previous.as_ref().is_some_and(|run| {
4539            run.replaces.is_some()
4540                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4541                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4542        });
4543    let stop_pin = task
4544        .resume_override
4545        .as_ref()
4546        .filter(|pin| {
4547            Questions::open().get(&pin.question_id).is_ok_and(|q| {
4548                q.node == land::APPROVAL_NODE
4549                    && q.resolution()
4550                        .as_deref()
4551                        .is_some_and(crate::merge_decision::stops)
4552            })
4553        })
4554        .and_then(|pin| pin.pinned_run.clone());
4555    let granted_run = task.repair_grants.last().and_then(|receipt| {
4556        let state = RunState::load(&receipt.request.run).ok()?;
4557        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4558    });
4559    let starter = if let Some(run) = granted_run {
4560        Starter::Resume(run)
4561    } else if let Some(owner) = &public_owner {
4562        Starter::Resume(owner.id.clone())
4563    } else if let Some(run) = stop_pin {
4564        // Stop actions resume their exact owner even after seat-count edits;
4565        // they must never fall through to implementation or a takeover.
4566        Starter::Resume(run)
4567    } else if retry_selected {
4568        Starter::Resume(previous.as_ref().unwrap().id.clone())
4569    } else if let Some(selected) = &task.pr_recovery {
4570        if selected
4571            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4572            .is_ok()
4573        {
4574            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4575        } else {
4576            Starter::Review(selected.branch.clone())
4577        }
4578    } else {
4579        starter_with_implementers(task, previous.as_ref(), proposed)
4580    };
4581    // An explicit resume pin must never degrade into a new competition or
4582    // takeover, including when its run stops being eligible after the answer.
4583    if let Some(pin) = &task.resume_override
4584        && let Some(run) = &pin.pinned_run
4585        && starter != Starter::Resume(run.clone())
4586    {
4587        let run = run.clone();
4588        task.notice_cause("resume-owner", Some(&run), None);
4589        task.hold_machine(Some(format!(
4590            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4591            task.id
4592        )));
4593        record(queue, task);
4594        return Vec::new();
4595    }
4596    if task.replacement.is_some()
4597        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4598        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4599    {
4600        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()));
4601        record(queue, task);
4602        return Vec::new();
4603    }
4604    if let Some(reason) = retained_attempt_hold(
4605        task,
4606        &starter,
4607        config.disk.retained_attempt_limit,
4608        RunState::load,
4609    ) {
4610        // The review choice was consumed above. Preserve it across this hold
4611        // so a later release cannot silently become a fresh implementation.
4612        if let Starter::Review(branch) = &starter {
4613            task.review_branch = Some(branch.clone());
4614        }
4615        task.hold_unrequested_retry(Some(reason));
4616        record(queue, task);
4617        return Vec::new();
4618    }
4619    // Absolute paths of the files the task was filed with, re-read from the
4620    // task now so a file attached while it was held reaches a resumed run
4621    // too. A stored name whose file has gone is an error before any agent is
4622    // paid for, never a silent omission the implementer cannot notice.
4623    let attachments = match task_attachments(queue, task) {
4624        Ok(a) => a,
4625        Err(e) => {
4626            task.attempts += 1;
4627            task.fail_startup_target(
4628                "startup-attachments",
4629                e.name.clone(),
4630                format!("{start_failed}{e:#}"),
4631                opts.max_attempts,
4632            );
4633            record(queue, task);
4634            return Vec::new();
4635        }
4636    };
4637    let startup_pause = stop.pause();
4638    let startup_interrupt = interrupt_pause.clone();
4639    let wait = crate::repo_lock::WaitPolicy::new(
4640        Duration::from_secs(config.graph.timeout_resource_wait),
4641        move || startup_pause.parked() || startup_interrupt.parked(),
4642    );
4643    // Startup includes review takeover and recovery. Do not embed its large
4644    // future in both the wait scope and the surrounding attempt stack frame.
4645    let started = wait.scope(Box::pin(async { match &starter {
4646        Starter::Review(_) if task.pr_recovery.is_some() => {
4647            let selected = task.pr_recovery.clone().expect("selected recovery");
4648            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
4649                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4650                    .await
4651                    .map(|mut r| {
4652                        r.state.attachments = attachments.clone();
4653                        r
4654                    }),
4655                Err(e) => Err(e),
4656            }
4657        }
4658        Starter::Review(branch) => {
4659            tracing::info!(
4660                "task {} reopens `{branch}` as a review-only pass",
4661                task.short()
4662            );
4663            // Every earlier attempt is superseded by the one being minted
4664            // now, so a branch one of them still holds may be taken over.
4665            let takeover = crate::handover::Takeover {
4666                earlier: task.earlier_attempts().to_vec(),
4667                home: crate::run::home(),
4668                choice: take_divergence_answer(branch, &config.merge.remote, task),
4669                task_instruction: Some(instruction_for(task)),
4670            };
4671            Runner::review_taking_over(
4672                &repo,
4673                branch,
4674                config,
4675                Some(takeover),
4676                crate::run::Origin::queue(&task.id),
4677            )
4678            .await
4679        }
4680        Starter::Resume(id) => {
4681            tracing::info!("resuming run {id} rather than competing again");
4682            Runner::resume(id).and_then(|mut r| {
4683                if retry_selected {
4684                    // The explicit queue release retries this same pinned
4685                    // implementation, preserving the attempt and worktrees.
4686                    for candidate in &mut r.state.candidates {
4687                        candidate.failed = None;
4688                        candidate.empty = false;
4689                        candidate.commits = 0;
4690                    }
4691                    r.state.status = RunStatus::Implementing;
4692                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4693                }
4694                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4695                    r.state.sources = task.sources.clone();
4696                }
4697                if r.state.prep_failure.is_some() {
4698                    let approval = task
4699                        .resumption
4700                        .as_ref()
4701                        .context("preparation retry requires an explicit task release")?;
4702                    r.retry_preparation(approval.at)?;
4703                }
4704                if let Some(instruction) =
4705                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4706                {
4707                    r.state.instruction = instruction;
4708                }
4709                r.state.attachments = attachments.clone();
4710                if task.replacement.is_some() {
4711                    r.state.config.merge.mode = MergeMode::Pr;
4712                    r.state.config.graph.land_approval = true;
4713                }
4714                // Replacements publish a new PR and ask again. Selected PR
4715                // recoveries keep their saved disposition; ordinary runs can
4716                // retain the task's merge override.
4717                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4718                    .overrides
4719                    .as_ref()
4720                    .and_then(|o| o.merge.as_deref())
4721                    .and_then(|m| merge_mode(m).ok())
4722                {
4723                    r.state.config.merge.mode = mode;
4724                }
4725                Ok(r)
4726            })
4727        }
4728        Starter::Start => {
4729            if let Some(branch) = &review_branch {
4730                tracing::warn!(
4731                    "conductor chose review for task {} but branch `{branch}` no longer \
4732                     exists; requeuing as a fresh competition instead",
4733                    task.short()
4734                );
4735            }
4736            let instruction = prepare_instruction(&starter, None, task)
4737                .unwrap_or_else(|| task.instruction.clone());
4738            Runner::start_naming(
4739                &repo,
4740                instruction,
4741                &task.title,
4742                config,
4743                crate::run::Origin::queue(&task.id),
4744            )
4745            .await
4746            .map(|mut r| {
4747                r.state.attachments = attachments.clone();
4748                r.state.sources = task.sources.clone();
4749                r
4750            })
4751        }
4752    }})).await;
4753    if let Err(error) = &started
4754        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
4755    {
4756        task.record_startup_failure(failure.clone());
4757    }
4758    let mut runner = match started {
4759        Ok(r) => r,
4760        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4761            task.last_error = Some(e.to_string());
4762            if stop.parking() || interrupt_pause.parked() {
4763                let attempts = task.attempts;
4764                task.park(e.to_string());
4765                // Startup has not spent an attempt to refund.
4766                task.attempts = attempts;
4767            } else {
4768                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4769            }
4770            record(queue, task);
4771            return Vec::new();
4772        }
4773        // A branch an earlier attempt still holds and magi will not release
4774        // by itself is the operator's call, not a failed attempt: hold the
4775        // task with the reason, spend nothing, and say so on the bell.
4776        Err(e) if task.pr_recovery.is_some() => {
4777            task.startup_notice_cause("startup-public-head");
4778            task.attempts += 1;
4779            task.last_error = Some(format!("{start_failed}{e:#}"));
4780            task.hold_unrequested_retry(Some(format!(
4781                "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."
4782            )));
4783            record(queue, task);
4784            return Vec::new();
4785        }
4786        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4787            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4788                Some(r) => (p.handover_refused)(r),
4789                None => format!("{e:#}"),
4790            };
4791            task.startup_notice_cause("startup-handover");
4792            let reason = format!("{start_failed}{detail}");
4793            task.last_error = Some(reason.clone());
4794            // Consumed above by `take`; keep it so the released task retries
4795            // as a review of this same branch.
4796            let branch = match &starter {
4797                Starter::Review(branch) => Some(branch.clone()),
4798                _ => None,
4799            };
4800            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4801            // one page; the guidance rides in the reason, fixed per state so a
4802            // re-put never changes the wording and relights it.
4803            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4804            record(queue, task);
4805            tracing::warn!(
4806                "holding {} for a branch it cannot take over: {e:#}",
4807                task.short()
4808            );
4809            return Vec::new();
4810        }
4811        // A branch that differs between here and the remote in ways magi
4812        // cannot prove are the same change is a decision for the owner, not a
4813        // failed attempt: ask with both sides laid out, spend no attempt, and
4814        // let the answer requeue the task.
4815        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4816            let d = e
4817                .downcast_ref::<crate::reconcile::Diverged>()
4818                .expect("checked by the guard");
4819            let mut q = ask::Question::new(
4820                task.id.clone(),
4821                crate::reconcile::NODE.to_owned(),
4822                crate::reconcile::SEAT.to_owned(),
4823                d.summary(),
4824                d.detail(),
4825                d.choices(),
4826            );
4827            match Questions::open().put(&mut q) {
4828                Ok(()) => {
4829                    task.last_error = Some(format!("{e:#}"));
4830                    // Consumed above by `take`; the answer has to reach a review
4831                    // of this same branch, so keep pointing the task at it.
4832                    task.review_branch = Some(d.branch.clone());
4833                    task.review_instruction = Some(task.instruction.clone());
4834                    task.block(vec![q.id.clone()], Some(d.summary()));
4835                }
4836                Err(put) => {
4837                    tracing::warn!("could not file the divergence question: {put:#}");
4838                    task.attempts += 1;
4839                    task.fail_startup(
4840                        "startup-question-store",
4841                        format!("{start_failed}{e:#}"),
4842                        opts.max_attempts,
4843                    );
4844                }
4845            }
4846            record(queue, task);
4847            return Vec::new();
4848        }
4849        Err(e) => {
4850            // The answer was stale and nothing was applied: keep pointing at
4851            // the branch so the next attempt asks again against its new tips.
4852            // Nothing went wrong with the task, so no attempt is spent: a
4853            // budget one short of its limit must not hold it instead of
4854            // letting the question be asked again.
4855            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4856                && let Starter::Review(branch) = &starter
4857            {
4858                task.review_branch = Some(branch.clone());
4859                task.review_instruction = Some(task.instruction.clone());
4860                task.last_error = Some(format!("{start_failed}{e:#}"));
4861                task.status = crate::queue::TaskStatus::Failed;
4862                record(queue, task);
4863                return Vec::new();
4864            }
4865            task.attempts += 1;
4866            task.last_error = Some(format!("{start_failed}{e:#}"));
4867            task.startup_notice_cause("startup-source");
4868            task.hold_unrequested_retry(Some(format!(
4869                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4870            )));
4871            record(queue, task);
4872            return Vec::new();
4873        }
4874    };
4875    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4876        runner.state.recovery_config = Some(config_evidence);
4877    }
4878    if let Some(replacement) = &task.replacement {
4879        if matches!(starter, Starter::Start) {
4880            runner.state.instruction.push_str(&format!(
4881                "\n\n# Replacement review context\n{}",
4882                replacement.context
4883            ));
4884        }
4885        runner.state.replaces = Some(replacement.clone());
4886        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4887        if let Ok(mut old) = RunState::load(&replacement.run)
4888            && let Some(d) = &mut old.merge_decision
4889        {
4890            d.replacement_run = Some(runner.state.id.clone());
4891            old.event(
4892                "replacement",
4893                format!(
4894                    "replacement run {} owns the next attempt; old PR remains closed",
4895                    runner.state.id
4896                ),
4897            );
4898            if let Err(e) = old.save() {
4899                let error = runner.fail_startup("replacement-history", e);
4900                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4901                    task.record_startup_failure(failure.clone());
4902                }
4903                task.hold_manual(Some(format!(
4904                    "Could not link replacement history: {error:#}; no agents dispatched"
4905                )));
4906                record(queue, task);
4907                return Vec::new();
4908            }
4909        }
4910    }
4911    runner.state.task_instruction = Some(task.instruction.clone());
4912    // The follow-up depth is fixed now, while the task certainly exists:
4913    // deleting it later must not reset the cap (`crate::followup`).
4914    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4915    if runner.state.origin_chat.is_none() {
4916        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4917    }
4918    // A stop that means "park" reaches the graph through this handle.
4919    runner.on_pause(stop.pause());
4920    // `poll`'s interrupt scheduler reaches this one run - and no other -
4921    // through this handle. See `Pause`'s own doc for why these are never
4922    // the same one.
4923    runner.watch_interrupt(interrupt_pause);
4924
4925    // `start` has minted the run, so the task can now point at it. Persisting
4926    // `Running` before `execute` is what makes a crash mid-run legible.
4927    let run = runner.state.id.clone();
4928    let before_start = task.clone();
4929    task.start(run.clone());
4930    if let Err(error) = queue.put(task) {
4931        *task = before_start;
4932        let error = runner.fail_startup("task-start", error);
4933        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4934            task.record_startup_failure(failure.clone());
4935        }
4936        task.hold_manual(Some(format!(
4937            "Could not persist task start; no agents dispatched: {error:#}"
4938        )));
4939        record(queue, task);
4940        return Vec::new();
4941    }
4942    lock(status).current.push(Current {
4943        worker: None,
4944        task: task.id.clone(),
4945        run,
4946    });
4947
4948    // `RunState::quota` is the run's whole history across every resume, so
4949    // only what this execution added may arm the cooldown or earn a refund.
4950    let quota_before = runner.state.quota.clone();
4951    runner.state.carry_dispatched_resumes(task);
4952    runner.state.next_pass_task_entry = true;
4953    let result = runner.execute().await;
4954    finish_attempt(
4955        opts.max_attempts,
4956        queue,
4957        task,
4958        &runner.state,
4959        &quota_before,
4960        result,
4961    )
4962}
4963
4964/// Settle `task` after its run executed: the verdict, the diagnosis, the
4965/// supersession of earlier attempts and the save. Shared by the loop and by
4966/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4967/// Returns the quota losses this execution added to the run.
4968pub fn finish_attempt(
4969    max_attempts: usize,
4970    queue: &Queue,
4971    task: &mut Task,
4972    state: &RunState,
4973    quota_before: &[QuotaLoss],
4974    result: Result<()>,
4975) -> Vec<QuotaLoss> {
4976    let detail = match result {
4977        Ok(()) => describe(state),
4978        Err(e) => format!("{e:#}"),
4979    };
4980    let fresh = losses_this_attempt(quota_before, &state.quota);
4981    let verdict = Verdict {
4982        status: state.status,
4983        // A run that opened a pull request handed its work over, whatever the
4984        // gate then decided about merging it.
4985        left_pr: state.pr.is_some(),
4986        // Only a rate limit earns the task its attempt back - and only one
4987        // suffered now: a refund justified by a previous session's loss is
4988        // the same mistake as re-arming the cooldown from it. A stalled run
4989        // resumed without hitting quota again therefore spends its attempt,
4990        // like any other failure of the task's own.
4991        quota_hit: !fresh.is_empty(),
4992        // A run that parked was asked to stop; that is not a failure and must
4993        // not spend an attempt, or replacing the binary a few times would
4994        // exhaust a task's budget without an agent ever misbehaving.
4995        parked: state.parked,
4996        // A quota loss that left nothing viable is the same machine fact as a
4997        // `Stalled` quota loss; see `settle`'s doc table.
4998        no_viable_candidates: state.viable().is_empty(),
4999    };
5000    if let Some(replacement) = &state.replaces
5001        && let Some(pr) = &state.pr
5002        && let Ok(mut old) = RunState::load(&replacement.run)
5003        && let Some(d) = &mut old.merge_decision
5004    {
5005        d.replacement_pr = Some(pr.url.clone());
5006        let _ = old.save();
5007    }
5008    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5009    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5010        task.hold_unrequested_retry(Some(format!(
5011            "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.",
5012            task.short()
5013        )));
5014    }
5015    if task.status == TaskStatus::Done {
5016        supersede_prior_runs(task, &crate::run::home());
5017    }
5018    record(queue, task);
5019    tracing::info!(
5020        "task {} is {} after run {} ({})",
5021        task.short(),
5022        task.status.as_str(),
5023        state.short(),
5024        label(state.status)
5025    );
5026    fresh
5027}
5028
5029/// A task a hand-started run leaves runnable (failed with attempts to spare,
5030/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5031/// later must not spend agent calls on it. `magi task release` retries.
5032pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5033    // Parked work (including legacy Failed records with a parked run) is a
5034    // checkpoint or owner handoff, not an unrequested retry.
5035    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5036        && !awaiting_resume_with(task, RunState::load)
5037        // A run parked on the owner's word about a withheld PR title/body
5038        // resumes via `land_resume_state`, including review-only tasks that
5039        // `awaiting_resume_with` does not consider.
5040        && withheld_text_wait(task).is_none()
5041        && !(task.fresh_start && task.replacement.is_some())
5042    {
5043        let why = task.last_error.clone().map_or_else(
5044            || "the run did not finish".to_owned(),
5045            |e| format!("the run did not finish: {e}"),
5046        );
5047        task.hold_unrequested_retry(Some(format!(
5048            "{why}. It was started by hand, so it is not retried \
5049             automatically; `magi task release` retries it."
5050        )));
5051        record(queue, task);
5052    }
5053}
5054
5055/// Whether an attempt at a task whose newest run is `run` would resume that
5056/// run rather than start a fresh competition. `magi run --resume` hands a run
5057/// to a live loop only when this holds.
5058#[must_use]
5059pub fn loop_would_resume(run: &str) -> bool {
5060    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5061}
5062
5063/// A loop in another process that is alive right now: a fresh heartbeat in
5064/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5065/// carries the pid it published (`None` inside when it published none - a
5066/// fresh heartbeat is still evidence of a live loop).
5067///
5068/// The one judgement of "is somebody else serving this queue", shared by the
5069/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5070/// deciding whether to hand a task to the loop. A claim file proves nothing
5071/// here: whether a claim succeeds says nothing about whether its owner lives.
5072#[must_use]
5073pub fn foreign_loop(
5074    reading: Option<&Reading>,
5075    now: Timestamp,
5076    own_pid: u32,
5077) -> Option<Option<u32>> {
5078    let reading = reading.filter(|r| r.running(now))?;
5079    match reading.pid {
5080        Some(pid) if pid == own_pid => None,
5081        pid => Some(pid),
5082    }
5083}
5084
5085fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5086    reading.worker_protocol != Some(1)
5087        && (foreign_loop(Some(reading), now, own_pid).is_some()
5088            || reading
5089                .pid
5090                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5091}
5092
5093/// Low-level claimed-task execution shared by the detached standalone worker
5094/// and focused lifecycle fixtures. The caller must retain the queue claim for
5095/// this entire call. CLI callers transfer ownership through
5096/// [`run_detached_claimed`] instead of executing inside their own runtime.
5097///
5098/// The one deliberate difference from the loop: a task the attempt leaves
5099/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5100/// Nobody asked for a retry, and a daemon starting later must not spend agent
5101/// calls re-running a hand-started task behind the operator's back;
5102/// `magi task release` is the explicit retry.
5103pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5104    run_claimed_until(opts, queue, task, &Stop::new()).await;
5105}
5106
5107async fn run_claimed_until(
5108    opts: &Opts,
5109    queue: &Queue,
5110    task: &mut Task,
5111    stop: &Stop,
5112) -> Vec<QuotaLoss> {
5113    let status = Arc::new(Mutex::new(Status::new()));
5114    // An attempt embeds startup and graph futures. Keep it off the standalone
5115    // caller's stack, on both the initial execution and withheld-text resume.
5116    let mut quota = Box::pin(attempt(
5117        opts,
5118        queue,
5119        &status,
5120        stop,
5121        crate::graph::Pause::new(),
5122        task,
5123    ))
5124    .await;
5125    // A run parked on the owner's word about a withheld PR title/body has no
5126    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5127    // here with the claim still held, and resume once the question is settled
5128    // (answered, or abandoned at its deadline -> the neutral text).
5129    // A rejected reply files one more question (the gate asks at most twice),
5130    // so after a resume the run may be waiting again: keep going, with a fresh
5131    // limit for the new question. `resumes` bounds it even if a resume parks
5132    // without asking anything new.
5133    let mut resumes = 0;
5134    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5135        let Some(timeout) = withheld_text_wait(task) else {
5136            break;
5137        };
5138        eprintln!(
5139            "waiting for the owner's answer on a withheld pull request text \
5140             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5141        );
5142        // The deadline abandons the question itself; the extra margin only
5143        // covers an abandon that could not be saved.
5144        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5145        let ready = loop {
5146            match land_resume_state(task) {
5147                LandResume::StillWaiting
5148                    if !stop.parking() && std::time::Instant::now() < limit =>
5149                {
5150                    tokio::time::sleep(WITHHELD_POLL).await;
5151                }
5152                LandResume::Ready => break true,
5153                _ => break false,
5154            }
5155        };
5156        if !ready || stop.parking() {
5157            break;
5158        }
5159        resumes += 1;
5160        quota.extend(
5161            Box::pin(attempt(
5162                opts,
5163                queue,
5164                &status,
5165                stop,
5166                crate::graph::Pause::new(),
5167                task,
5168            ))
5169            .await,
5170        );
5171    }
5172    hold_if_runnable(queue, task);
5173    quota
5174}
5175
5176/// Resumes an in-process run makes for withheld-text questions: the gate asks
5177/// at most twice, plus one for a resume that asks nothing new.
5178const MAX_WITHHELD_RESUMES: u32 = 3;
5179
5180/// How often an in-process run rechecks its withheld-text question.
5181const WITHHELD_POLL: Duration = Duration::from_secs(15);
5182
5183/// The `answer_timeout` (seconds) of the task's last run when that run is
5184/// parked on an unresolved withheld-text question; `None` otherwise.
5185fn withheld_text_wait(task: &Task) -> Option<u64> {
5186    let id = task.execution_runs().last()?;
5187    let s = RunState::load(id).ok()?;
5188    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5189        .then_some(s.config.graph.answer_timeout)
5190}
5191
5192/// The quota losses `after` holds that `before` did not: what one execution
5193/// suffered, as opposed to the run's history.
5194///
5195/// Compared by value rather than by length or position because
5196/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5197/// the vector can shrink and shift under a resume. A retried seat that hits
5198/// quota again is a `push` with a new `at`, so it shows up as new here.
5199/// Crash recovery uses the recorded pass start as its boundary when available;
5200/// legacy records without passes retain their original history-based policy.
5201fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5202    after
5203        .iter()
5204        .filter(|q| !before.contains(q))
5205        .cloned()
5206        .collect()
5207}
5208
5209/// When the loop-wide quota cooldown should end, given this attempt's losses;
5210/// `None` when there were none. Reset-hint parsing and the cap live here.
5211fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5212    let quota: Vec<_> = quota
5213        .iter()
5214        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5215        .collect();
5216    if quota.is_empty() {
5217        return None;
5218    }
5219    let with_hint = quota.iter().find(|q| q.reset.is_some());
5220    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5221    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5222    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5223    Some(
5224        now.checked_add(jiff::SignedDuration::from_secs(secs))
5225            .unwrap_or(Timestamp::MAX),
5226    )
5227}
5228
5229/// An explicit task count must agree with a run before any resume.
5230fn implementers_match(task: &Task, state: &RunState) -> bool {
5231    task.replacement.as_ref().map_or_else(
5232        || {
5233            task.implementers()
5234                .is_none_or(|n| n == state.config.graph.implementers)
5235        },
5236        |replacement| {
5237            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5238                && state.config.graph.implementers == 1
5239        },
5240    )
5241}
5242
5243/// Never resume or take over candidate work built for a different seat count.
5244fn starter_with_implementers(
5245    task: &Task,
5246    previous: Option<&RunState>,
5247    proposed: Starter,
5248) -> Starter {
5249    if previous.is_some_and(|s| !implementers_match(task, s)) {
5250        task.review_of
5251            .as_ref()
5252            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5253    } else {
5254        proposed
5255    }
5256}
5257
5258/// Apply this task's explicit count to the new attempt, without changing defaults.
5259fn apply_task_implementers(config: &mut Config, task: &Task) {
5260    if let Some(n) = task.implementers() {
5261        config.graph.implementers = n;
5262    }
5263}
5264
5265/// [`prepare`] for one task: its own `--config` and command-line overrides
5266/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5267/// over the loop's, so handing a hand-started task to a daemon changes nothing
5268/// about what it does.
5269#[cfg(test)]
5270fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5271    let explicit = match &task.overrides {
5272        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5273        _ => opts.config.as_deref(),
5274    };
5275    let (mut config, _) = Config::discover(repo, explicit)?;
5276    apply_options(&mut config, opts, task)?;
5277    Ok(config)
5278}
5279
5280fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5281    if task
5282        .overrides
5283        .as_ref()
5284        .is_none_or(|o| o.inherit_daemon_options)
5285        && let Some(mode) = opts.merge.as_deref()
5286    {
5287        config.merge.mode = merge_mode(mode)?;
5288    }
5289    if let Some(o) = &task.overrides {
5290        o.apply(config);
5291    }
5292    Ok(())
5293}
5294
5295/// Load the config for a task's repository, with the merge override applied.
5296fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5297    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5298    if let Some(mode) = &opts.merge {
5299        config.merge.mode = merge_mode(mode)?;
5300    }
5301    Ok(config)
5302}
5303
5304/// Prune the shared build cache at a between-runs boundary. The detached cache
5305/// service checks authoritative task jobs first; dispatch waits for that finite
5306/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5307/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5308async fn maybe_prune_cache_between_runs(
5309    repo: &Path,
5310    opts: &Opts,
5311    home: &Path,
5312    stop: &Stop,
5313    last_checked: &mut Option<Timestamp>,
5314    now: Timestamp,
5315) {
5316    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5317        return;
5318    }
5319    *last_checked = Some(now);
5320    let cfg = match prepare(repo, opts) {
5321        Ok(cfg) => cfg,
5322        Err(e) => {
5323            tracing::warn!("cache check: no config: {e:#}");
5324            return;
5325        }
5326    };
5327    match clean::prune_cache_if_over_limit(&cfg, home) {
5328        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5329            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5330            pruned.files,
5331            pruned.freed
5332        ),
5333        Ok(_) => {}
5334        Err(e) => {
5335            tracing::warn!("housekeep: prune cache: {e:#}");
5336            notices::raise_in(
5337                home,
5338                Notice::warn(
5339                    "housekeep:cache",
5340                    format!(
5341                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5342                        e.to_string()
5343                            .lines()
5344                            .next()
5345                            .unwrap_or("unknown cleanup error")
5346                    ),
5347                ),
5348            );
5349        }
5350    }
5351}
5352
5353/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5354/// now, given when it last did (if ever). Pure, so the cadence is asserted
5355/// directly rather than by waiting out real minutes in a test.
5356fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5357    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5358}
5359
5360/// The disk janitor, with its housekeeping logged rather than fatal.
5361///
5362/// Called only at the loop's idle points, for the reason the caller documents:
5363/// a prune racing a live compile would delete files mid-build. The config is
5364/// re-read on every call because the repository that just ran may not be the
5365/// daemon's own default, and the cache directory is a repository fact.
5366///
5367/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5368/// and [`crate::run::default_worktree_root`] read here, for the same reason
5369/// [`drive`] takes its queue and status file rather than resolving them: a
5370/// test driving the loop must not reach through to the operator's real home
5371/// or worktree bay just because the janitor runs on every idle tick.
5372/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5373/// to get wrong silently - a test's `home` was already isolated, but nothing
5374/// exercised the parameter next to it, so a real worktree bay stayed wired in
5375/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5376/// it for real, every test in this file that drives the loop at all started
5377/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5378async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5379    let cfg = match prepare(repo, opts) {
5380        Ok(cfg) => cfg,
5381        Err(e) => {
5382            tracing::warn!("housekeep: no config: {e:#}");
5383            return;
5384        }
5385    };
5386    // A run's own worktree lives under `config.graph.worktree_root` when the
5387    // repository sets one - the same precedence `RunState::worktree_root`
5388    // uses - and `worktrees_root` only stands in for the *default* an
5389    // unconfigured repository resolves to (see this function's own
5390    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5391    // that always swept the default regardless of this override would never
5392    // see, and so never reclaim, a single worktree for a repository that
5393    // relocated them elsewhere.
5394    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5395    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5396    // Reported whenever there is anything to say, not only when `folded > 0`:
5397    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5398    // folded, on every single pass, for months - a report gated on `folded`
5399    // would have stayed silent through every one of them.
5400    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5401        let mut extra = Vec::new();
5402        if out.unreadable > 0 {
5403            extra.push(format!("{} unreadable", out.unreadable));
5404        }
5405        if out.orphaned_worktrees > 0 {
5406            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5407        }
5408        let detail = if extra.is_empty() {
5409            String::new()
5410        } else {
5411            format!(" ({})", extra.join(", "))
5412        };
5413        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5414    }
5415    if out.external_merges_recorded > 0 {
5416        tracing::info!(
5417            "housekeep: recorded {} run(s) as merged externally",
5418            out.external_merges_recorded
5419        );
5420    }
5421    if out.stale_pr_states_repaired > 0 {
5422        tracing::info!(
5423            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5424            out.stale_pr_states_repaired
5425        );
5426    }
5427    if out.cache_files > 0 {
5428        tracing::info!(
5429            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5430            out.cache_files,
5431            out.cache_freed
5432        );
5433    }
5434    if out.questions_abandoned > 0 {
5435        tracing::info!(
5436            "housekeep: abandoned {} question(s) left open by a finished run",
5437            out.questions_abandoned
5438        );
5439    }
5440}
5441
5442/// Run [`triage::run_once`] and log whatever it did, the same "only when
5443/// there is something to say" rule [`janitor`] follows for its own report.
5444///
5445/// Called at the same idle points as [`janitor`] - once per full poll
5446/// interval, never mid-attempt - for the same reason: it is not liveness
5447/// critical, and a task's own `hold_reason` string is the one thing this
5448/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5449/// tick for no benefit.
5450async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5451    let questions = Questions::at(home.join("questions"));
5452    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5453    if report.is_empty() {
5454        return;
5455    }
5456    if !report.quarantined.is_empty() {
5457        tracing::info!(
5458            "triage: held {} blocked task(s) whose blocked-on task or \
5459             question no longer exists: {}",
5460            report.quarantined.len(),
5461            report.quarantined.join(", ")
5462        );
5463    }
5464    if !report.resumed.is_empty() {
5465        tracing::info!(
5466            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5467            report.resumed.len(),
5468            report.resumed.join(", ")
5469        );
5470    }
5471    if !report.asked.is_empty() {
5472        tracing::info!(
5473            "triage: asked about {} held task(s): {}",
5474            report.asked.len(),
5475            report.asked.join(", ")
5476        );
5477    }
5478    if !report.answered.is_empty() {
5479        tracing::info!(
5480            "triage: applied {} operator answer(s): {}",
5481            report.answered.len(),
5482            report.answered.join(", ")
5483        );
5484    }
5485}
5486
5487/// The free-space gate: what stands between this task and a new run, if
5488/// anything. `Some(reason)` holds the task; `None` lets it start.
5489///
5490/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5491/// the operator opted out. A measurement failure is a gate, not a pass: both
5492/// sides of "cannot tell" are served by not starting.
5493pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5494    disk_gate_with(repo, config, crate::disk::free_bytes)
5495}
5496
5497/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5498/// test can assert the exact wiring `attempt` runs - config's threshold in,
5499/// task-holding reason out - without asking the real machine's disk anything.
5500fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5501    repo: &Path,
5502    config: &Config,
5503    free_bytes: F,
5504) -> Option<String> {
5505    let min = config.disk.min_free_bytes;
5506    if min == 0 {
5507        return None;
5508    }
5509    let mut paths = vec![repo.to_owned()];
5510    if let Some(cache) = config.cache_dir() {
5511        paths.push(cache);
5512    }
5513    if let Some(root) = &config.graph.worktree_root {
5514        paths.push(root.clone());
5515    }
5516    for path in paths {
5517        let probe = if path == repo {
5518            path.as_path()
5519        } else {
5520            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5521        };
5522        let reason = match free_bytes(probe) {
5523            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5524            Err(e) => Some(crate::disk::unmeasured_in(
5525                probe,
5526                &e,
5527                &config.graph.language,
5528            )),
5529        };
5530        if reason.is_some() {
5531            return reason;
5532        }
5533    }
5534    None
5535}
5536
5537/// How long to wait before offering another task when a run lost a seat to a
5538/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5539/// could read, or carried nothing at all. Long enough that a quota outage
5540/// cannot burn through a whole backlog in the few seconds each doomed attempt
5541/// takes to fail; short enough that a quota which clears early is not left
5542/// idle for the fallback's sake.
5543const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5544
5545/// Longest a parsed reset hint may push the wait out to. The hint comes from
5546/// the CLI's own words, not a contract, so a parsing slip that lands a day
5547/// away must not leave the loop asleep for a day.
5548const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5549
5550/// How long [`poll`] should wait before offering the next task, after a run
5551/// lost at least one seat to a rate limit.
5552///
5553/// Pure and separate from the loop so the policy can be exercised without a
5554/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5555/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5556/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5557/// far a parsed hint is trusted to push the wait out.
5558fn quota_wait(
5559    reset_at: Option<Timestamp>,
5560    now: Timestamp,
5561    fallback: Duration,
5562    cap: Duration,
5563) -> Duration {
5564    match reset_at {
5565        Some(at) if at > now => {
5566            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5567            Duration::from_secs(secs).min(cap)
5568        }
5569        _ => fallback,
5570    }
5571}
5572
5573/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5574///
5575/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5576/// explains why parsing it exactly "would be a bug factory" — so this only
5577/// recognises the shapes actually observed in the wild, and returns `None`
5578/// for anything else rather than guess at a format nobody has seen.
5579///
5580/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5581/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5582/// said it, not from whenever this loop happens to read it: anchoring on `now`
5583/// would push the reset later on every read and would read an already-elapsed
5584/// reset as still in the future. (A long hint is still clamped by
5585/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5586fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5587    parse_reset_hint_zoned(text, now)
5588        .or_else(|| parse_reset_hint_dated(text))
5589        .or_else(|| parse_reset_hint_relative(text, recorded))
5590}
5591
5592/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5593/// optional but at least one required, in that order. A bare number or any
5594/// unknown unit is refused.
5595fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5596    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5597    let mut rest = rest.trim();
5598    if rest.is_empty() {
5599        return None;
5600    }
5601    let mut total: i64 = 0;
5602    let mut matched = false;
5603    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5604        if let Some((digits, tail)) = rest.split_once(unit)
5605            && !digits.is_empty()
5606            && digits.bytes().all(|b| b.is_ascii_digit())
5607        {
5608            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5609            rest = tail;
5610            matched = true;
5611        }
5612    }
5613    if !rest.is_empty() || !matched {
5614        return None;
5615    }
5616    recorded
5617        .checked_add(jiff::SignedDuration::from_secs(total))
5618        .ok()
5619}
5620
5621/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5622/// case-insensitive) into a 24-hour hour and minute. Shared by every
5623/// reset-hint shape below.
5624fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5625    let clock = clock.trim().to_lowercase();
5626    let (digits, pm) = clock
5627        .strip_suffix("am")
5628        .map(|d| (d, false))
5629        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5630    let (h, m) = digits.trim().split_once(':')?;
5631    let mut hour: i8 = h.trim().parse().ok()?;
5632    let minute: i8 = m.trim().parse().ok()?;
5633    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5634        return None;
5635    }
5636    if pm && hour != 12 {
5637        hour += 12;
5638    } else if !pm && hour == 12 {
5639        hour = 0;
5640    }
5641    Some((hour, minute))
5642}
5643
5644/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5645/// and a zone, never a date. A clock reading already past today is read as
5646/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5647/// the window rolled over while nothing was watching.
5648fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5649    let open = text.find('(')?;
5650    let close = text.rfind(')')?;
5651    if close <= open {
5652        return None;
5653    }
5654    let zone = text[open + 1..close].trim();
5655    let (hour, minute) = parse_12h_clock(&text[..open])?;
5656    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5657    let candidate = now
5658        .to_zoned(tz)
5659        .with()
5660        .hour(hour)
5661        .minute(minute)
5662        .second(0)
5663        .millisecond(0)
5664        .microsecond(0)
5665        .nanosecond(0)
5666        .build()
5667        .ok()?;
5668    let mut at = candidate.timestamp();
5669    if at <= now {
5670        at += jiff::SignedDuration::from_hours(24);
5671    }
5672    Some(at)
5673}
5674
5675/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5676/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5677/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5678/// "already past today" correction to make: the year already disambiguates
5679/// it. Scanned as a five-word window so it can be pulled out of the middle
5680/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5681/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5682/// any other timestamp with no zone attached.
5683fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5684    let words: Vec<&str> = text.split_whitespace().collect();
5685    if words.len() < 5 {
5686        return None;
5687    }
5688    (0..=words.len() - 5)
5689        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5690}
5691
5692/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5693/// parenthesis right after the window is refused rather than ignored — it
5694/// reads as an explicit zone annotation on a shape that otherwise carries
5695/// none, and guessing UTC anyway would be exactly the silent misread this
5696/// module's parsing otherwise avoids.
5697fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5698    if trailing.is_some_and(|next| next.starts_with('(')) {
5699        return None;
5700    }
5701    let month = month_number(window[0])?;
5702    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5703    let day_digits = ["st", "nd", "rd", "th"]
5704        .iter()
5705        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5706    let day: i8 = day_digits.parse().ok()?;
5707    let year_token = window[2];
5708    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5709        return None;
5710    }
5711    let year: i16 = year_token.parse().ok()?;
5712    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5713    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5714    // reusing the same 12-hour clock reader the bracketed shape uses.
5715    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5716    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5717    let date = jiff::civil::Date::new(year, month, day).ok()?;
5718    let candidate = date
5719        .at(hour, minute, 0, 0)
5720        .to_zoned(jiff::tz::TimeZone::UTC)
5721        .ok()?;
5722    Some(candidate.timestamp())
5723}
5724
5725/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5726/// case-insensitively, into a 1-based month number.
5727fn month_number(name: &str) -> Option<i8> {
5728    const NAMES: [&str; 12] = [
5729        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5730    ];
5731    let lower = name.to_lowercase();
5732    NAMES
5733        .iter()
5734        .position(|n| *n == lower.as_str())
5735        .map(|i| i as i8 + 1)
5736}
5737
5738/// Test probe for the shared resume policy's review-budget exclusion.
5739#[cfg(test)]
5740fn exhausted_review_budget(state: &RunState) -> bool {
5741    // A run whose task-head publication failed has nothing left to review:
5742    // resuming it only retries the publication, so it is never "exhausted".
5743    !crate::handover::can_resume(state)
5744        && state.status == RunStatus::Blocked
5745        && !state.released()
5746        && state.retired_to.is_none()
5747}
5748
5749/// This task's *most recent* run, if resuming it would actually make
5750/// progress. `short` is only for the warning's own message.
5751///
5752/// Only ever `runs.last()` — never a search back through older history.
5753/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5754/// mint, oldest first, and every entry before the last one was already
5755/// superseded at the moment it was minted: the daemon only ever starts a new
5756/// run when the previous one was not worth resuming (unresumable, exhausted,
5757/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5758/// opens a fresh review-only run alongside an older, already-failed
5759/// competition. Searching further back would let an old run that merely
5760/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5761/// behind, say — get resumed instead of the fresh competition
5762/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5763/// nothing asked to revisit.
5764///
5765/// Two runs paid for the "prefer resuming over restarting" half of this
5766/// lesson, which is why this still checks `runs.last()` rather than always
5767/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5768/// task a moment later, duplicating two and a half hours of agent work. Then
5769/// b25f stalled on a judge that timed out and one that answered with no JSON
5770/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5771/// **one second** later, buying three fresh implementations to reach the
5772/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5773/// the second case: a stall is terminal, and its cheap recovery re-asks only
5774/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5775/// that is technically `resumable()` but provably cannot progress must not
5776/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5777/// no-op instead of the fresh competition it promises.
5778///
5779/// A load failure is warned about rather than silently read as "not
5780/// resumable": the alternative is exactly what let a schema mismatch on run
5781/// `eba2` fall through to a full re-competition with nobody told why.
5782/// `crate::conduct` is what actually offers a better answer than
5783/// `Runner::start` here (see `Recovery::Review`), once this task's next
5784/// failure shows it up as `held`/`failed` with the run state unreadable.
5785fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5786    unfinished_run_with(runs, short, RunState::load)
5787}
5788
5789/// [`unfinished_run`] with an injected state reader. Tests provide their
5790/// fixtures directly rather than touching the process-global run home.
5791pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5792where
5793    F: FnMut(&str) -> Result<RunState>,
5794{
5795    let mut id = runs.last()?.clone();
5796    let mut visited = std::collections::BTreeSet::new();
5797    let mut repo = None;
5798    loop {
5799        if !runs.contains(&id) || !visited.insert(id.clone()) {
5800            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5801            return None;
5802        }
5803        let state = match load(&id) {
5804            Ok(state) if state.id == id => state,
5805            Ok(_) => return None,
5806            Err(e) => {
5807                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5808                return None;
5809            }
5810        };
5811        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5812            return None;
5813        }
5814        repo = Some(state.repo.clone());
5815        if let Some(authority) = state.retired_to {
5816            id = authority;
5817            continue;
5818        }
5819        return (crate::handover::can_resume(&state)
5820            && state.liveness(false) != crate::run::Liveness::Live)
5821            .then_some(id);
5822    }
5823}
5824
5825/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5826/// that [`attempt`] will resume it on its own?
5827///
5828/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5829/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5830/// injected reader like its sibling. An unreadable run is not awaiting
5831/// anything: it keeps going to the conductor as before.
5832fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5833where
5834    F: FnOnce(&str) -> Result<RunState>,
5835{
5836    // `Failed` stays: a record an older build wrote for a parked run.
5837    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5838        || task.fresh_start
5839        || task.review_branch.is_some()
5840    {
5841        return false;
5842    }
5843    let Some(id) = task.execution_runs().last() else {
5844        return false;
5845    };
5846    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5847}
5848
5849/// Which of the three ways [`attempt`] can mint or continue a run this task
5850/// should use.
5851#[derive(Debug, Clone, PartialEq, Eq)]
5852enum Starter {
5853    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5854    /// and that still exists.
5855    Review(String),
5856    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5857    Resume(String),
5858    /// `crate::graph::Runner::start`: a fresh competition.
5859    Start,
5860}
5861
5862/// A second bound independent of inputs and the resettable failure counter.
5863/// Count execution and failed-startup recovery records once per run. Startup
5864/// failures can retain unrecorded preparation assets without an execution pass.
5865/// Unknown history is not evidence that a new set of worktrees is affordable.
5866fn retained_attempt_hold(
5867    task: &Task,
5868    starter: &Starter,
5869    limit: usize,
5870    mut load: impl FnMut(&str) -> Result<RunState>,
5871) -> Option<String> {
5872    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5873        return None;
5874    }
5875    let mut retained = 0;
5876    for id in task
5877        .runs
5878        .iter()
5879        .chain(task.startup_failures.iter().map(|failure| &failure.run))
5880        .collect::<std::collections::BTreeSet<_>>()
5881    {
5882        let state = match load(id) {
5883            Ok(state) if state.id == *id => state,
5884            _ => {
5885                return Some(format!(
5886                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5887                ));
5888            }
5889        };
5890        if state.retired_to.is_some() || state.released() {
5891            continue;
5892        }
5893        // Neither a completed status nor an empty candidate array proves that
5894        // all recovery sources (including unrecorded preparation) were retired.
5895        retained += 1;
5896    }
5897    (retained >= limit).then(|| format!(
5898        "[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."
5899    ))
5900}
5901
5902/// A selected public implementation overrides every historical candidate and pin.
5903fn selected_starter(
5904    selected: &crate::pr_recovery::Selection,
5905    previous: Option<&RunState>,
5906    unfinished: Option<&str>,
5907) -> Starter {
5908    if let Some(id) = unfinished
5909        && previous.is_some_and(|r| {
5910            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5911        })
5912    {
5913        Starter::Resume(id.to_owned())
5914    } else {
5915        Starter::Review(selected.branch.clone())
5916    }
5917}
5918
5919/// The owner's answer to this branch's divergence question, consumed from the
5920/// task so a later, different divergence asks again. The runner applies it
5921/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5922fn take_divergence_answer(
5923    branch: &str,
5924    remote: &str,
5925    task: &mut Task,
5926) -> Option<crate::reconcile::Choice> {
5927    let summary = crate::reconcile::summary_for(branch, remote);
5928    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5929        (a.question == summary)
5930            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5931            .flatten()
5932            .map(|c| (i, c))
5933    })?;
5934    task.answers.remove(idx);
5935    Some(choice)
5936}
5937
5938/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5939/// this attempt should use. Pure, and separate from [`attempt`], so the
5940/// routing itself is assertable without spawning a real graph or a git
5941/// process: `attempt`'s own `crate::git::branch_exists` call has already
5942/// happened by the time this is called.
5943///
5944/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5945/// whose branch is gone falls all the way through to [`Starter::Start`], not
5946/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5947/// old (likely `Blocked`) run in the first place, and a branch that vanished
5948/// out from under that choice is not evidence resuming it would fare better.
5949fn choose_starter(
5950    review_branch: Option<&str>,
5951    branch_exists: bool,
5952    unfinished: Option<&str>,
5953) -> Starter {
5954    match review_branch {
5955        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5956        Some(_) => Starter::Start,
5957        None => match unfinished {
5958            Some(id) => Starter::Resume(id.to_owned()),
5959            None => Starter::Start,
5960        },
5961    }
5962}
5963
5964/// Reuse a compatible latest review owner instead of taking its checked-out
5965/// branch into a new run. Different branches and changed criteria still use
5966/// the ordinary review/takeover policy.
5967fn review_retry_starter(
5968    task: &Task,
5969    previous: Option<&RunState>,
5970    branch: Option<&str>,
5971    exists: bool,
5972    unfinished: Option<&str>,
5973) -> Starter {
5974    if let Some(run) = previous
5975        && unfinished == Some(run.id.as_str())
5976        && run.reviewed_commits.is_some()
5977        && branch.is_some_and(|branch| {
5978            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5979        })
5980        && may_resume_run(run, task)
5981    {
5982        return Starter::Resume(run.id.clone());
5983    }
5984    match (branch, unfinished, &task.review_of) {
5985        (None, None, Some(branch)) => Starter::Review(branch.clone()),
5986        _ => choose_starter(branch, exists, unfinished),
5987    }
5988}
5989
5990/// Consume a retained review only while its authored criteria still match.
5991fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5992    let branch = task.review_branch.take();
5993    let instruction = task.review_instruction.take();
5994    branch.filter(|branch| match &instruction {
5995        Some(authored) => *authored == task.instruction,
5996        // Legacy retained branches must agree with their prior run; only an
5997        // explicitly pinned review can proceed without recoverable provenance.
5998        None => previous.map_or_else(
5999            || task.review_of.as_ref() == Some(branch),
6000            |run| compatible_run_instruction(run, task),
6001        ),
6002    })
6003}
6004
6005/// A current explicit pin can select an otherwise incompatible run. Edits
6006/// and subsequent approvals invalidate pins selected for earlier criteria.
6007fn may_resume_run(run: &RunState, task: &Task) -> bool {
6008    if !task.assignment_accepts(run) {
6009        return false;
6010    }
6011    task.resume_override
6012        .as_ref()
6013        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6014        || compatible_run_instruction(run, task)
6015}
6016
6017/// Review scaffolding is execution context, not evidence of an operator edit.
6018pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6019    if let Some(authored) = &run.task_instruction {
6020        return compatible_instruction(authored, task);
6021    }
6022    if compatible_instruction(&run.instruction, task) {
6023        return true;
6024    }
6025    // Recognize only the existing generated review shapes on legacy runs.
6026    // Ordinary authored text with a similar heading is left intact.
6027    if run.reviewed_commits.is_some() {
6028        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6029            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6030        }
6031        if let Some(branch) = &task.review_of {
6032            let canonical = format!(
6033                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6034            );
6035            let generated = format!(
6036                "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"
6037            );
6038            return task.instruction == canonical && run.instruction.starts_with(&generated);
6039        }
6040    }
6041    false
6042}
6043
6044/// Compare authored instructions, excluding answer blocks appended by the daemon.
6045pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6046    strip_answers_block(old, task) == task.instruction
6047}
6048
6049/// Which repository a task runs in. A task that names none — the normal case
6050/// for one filed from a phone — runs in the daemon's own default.
6051fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6052    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6053        return fallback.to_path_buf();
6054    }
6055    task.repo.clone()
6056}
6057
6058/// The header [`append_answers`] appends operator answers under. Shared with
6059/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6060/// rather than grown a new block on every resume.
6061const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6062
6063/// Render the first `count` answers in the block appended to an instruction.
6064fn answers_block(task: &Task, count: usize) -> String {
6065    let mut s = ANSWERS_HEADER.to_owned();
6066    for a in &task.answers[..count] {
6067        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6068    }
6069    s
6070}
6071
6072/// Render the approval independently of transient task state, so historical
6073/// suffixes remain recognizable after another explicit release.
6074fn resumption_block(r: &crate::queue::Resumption) -> String {
6075    format!(
6076        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6077         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6078        r.generation, r.at, r.instruction, r.answers_through,
6079    )
6080}
6081
6082/// Append audit answers and the latest explicit approval to the instruction.
6083fn append_answers(base: &str, task: &Task) -> String {
6084    let mut s = base.to_owned();
6085    if !task.answers.is_empty() {
6086        s.push_str(&answers_block(task, task.answers.len()));
6087    }
6088    if let Some(r) = &task.resumption {
6089        s.push_str(&resumption_block(r));
6090    }
6091    s
6092}
6093
6094/// Drop the prior answer block only when it is exactly the suffix this task
6095/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6096/// the task author is ordinary instruction text, not a block to remove.
6097fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6098    let mut instruction = instruction;
6099    for approval in task
6100        .resumption
6101        .iter()
6102        .chain(task.resumption_history.iter().rev())
6103    {
6104        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6105            instruction = base;
6106            break;
6107        }
6108    }
6109    for count in (1..=task.answers.len()).rev() {
6110        let block = answers_block(task, count);
6111        if let Some(base) = instruction.strip_suffix(&block) {
6112            return base;
6113        }
6114    }
6115    instruction
6116}
6117
6118/// The instruction handed to `Runner::start`: the task's own text, plus any
6119/// operator answers `crate::conduct` collected for it (see
6120/// [`Task::answers`]), so a decision the operator actually made reaches the
6121/// implementers rather than only clearing the block that was waiting on it.
6122///
6123/// Appended rather than merged into [`Task::instruction`] itself, so the
6124/// task's own record stays exactly what its author wrote.
6125fn instruction_for(task: &Task) -> String {
6126    append_answers(&task.instruction, task)
6127}
6128
6129/// The instruction a resumed run should carry on with: whatever it already
6130/// had, refreshed with the task's *current* operator answers.
6131///
6132/// A resumable run's own `RunState::instruction` predates any answer
6133/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6134/// the behaviour before this function existed — silently drops the very
6135/// decision the operator made to unblock it. Re-stripping any block this
6136/// function appended on an earlier resume before re-appending the current
6137/// list (rather than blindly appending again) is what keeps a task resumed
6138/// three times over three answered questions from carrying the same answer
6139/// three times.
6140fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6141    append_answers(strip_answers_block(old_instruction, task), task)
6142}
6143
6144/// Preserve the producer's verified boundary and target, independent of prose.
6145fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6146    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6147    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6148    if let Some(cause) = task.hold_notice_cause.as_mut() {
6149        cause.target = failure.map(|f| f.target.clone());
6150    }
6151}
6152
6153#[derive(Debug, thiserror::Error)]
6154#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6155struct MissingAttachment {
6156    name: String,
6157    path: PathBuf,
6158}
6159
6160/// The task's attachments as absolute paths, each checked to still exist.
6161fn task_attachments(
6162    queue: &Queue,
6163    task: &Task,
6164) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6165    let paths = queue.attachment_paths(task);
6166    for (name, path) in task.attachments.iter().zip(&paths) {
6167        if !path.is_file() {
6168            return Err(MissingAttachment {
6169                name: name.clone(),
6170                path: path.clone(),
6171            });
6172        }
6173    }
6174    Ok(paths)
6175}
6176
6177/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6178/// answers before handing it to `Runner` — the actual boundary between
6179/// [`choose_starter`]'s routing and the graph, factored out so it is
6180/// assertable without a real repository, git branch, or agent CLI.
6181///
6182/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6183/// instruction from the reviewed branch's own commit log because there is no
6184/// task statement to speak of for hand-written work, and splicing operator
6185/// answers into that text would contradict the very message it sends
6186/// reviewers ("there is no task statement").
6187fn prepare_instruction(
6188    starter: &Starter,
6189    old_instruction: Option<&str>,
6190    task: &Task,
6191) -> Option<String> {
6192    match starter {
6193        Starter::Start => Some(instruction_for(task)),
6194        Starter::Resume(_) => Some(resumed_instruction(
6195            old_instruction.expect("a resumed run always has a prior instruction"),
6196            task,
6197        )),
6198        Starter::Review(_) => None,
6199    }
6200}
6201
6202/// Persist a transition. A queue write failure is logged rather than fatal: the
6203/// run already happened, and taking the daemon down would only add a lost
6204/// backlog to a full disk.
6205fn record(queue: &Queue, task: &mut Task) {
6206    if let Err(e) = queue.put(task) {
6207        tracing::error!("could not record task {}: {e:#}", task.short());
6208        let notice = Notice::error(
6209            "loop:record",
6210            format!(
6211                "Task {} state could not be saved: {}. Check the disk.",
6212                task.id,
6213                e.to_string().lines().next().unwrap_or("unknown save error")
6214            ),
6215        )
6216        .link(Link::Task {
6217            id: task.id.clone(),
6218        });
6219        // The queue lives at `<home>/queue`, so its parent is the home.
6220        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6221            Some(home) => notices::raise_in(home, notice),
6222            None => notices::raise(notice),
6223        }
6224    }
6225}
6226
6227/// Every runnable task, in the order the loop should try them.
6228///
6229/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6230/// tail exists so that a claim somebody else holds costs the loop the next
6231/// candidate rather than a whole poll interval of idleness.
6232fn runnable(queue: &Queue) -> Vec<Task> {
6233    let mut tasks: Vec<Task> = queue
6234        .list()
6235        .into_iter()
6236        .filter(|t| t.status.runnable())
6237        .collect();
6238    tasks.sort_unstable_by(crate::queue::dispatch_order);
6239    tasks
6240}
6241
6242/// Why a run ended where it did, in one line, for [`Task::last_error`].
6243///
6244/// A stalled run names the seats the quota took out: "out of quota" is not
6245/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6246/// agent to replace or which plan to top up.
6247///
6248/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6249/// purpose: unlike `label`'s other callers (an internal log line, an
6250/// already-a-bug fallback message), this string becomes `Task::last_error`
6251/// verbatim, which the phone renders in the same alarm-styled box an
6252/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6253/// `.err` styling. A bare `verified_noop` there would read exactly like the
6254/// failure this whole feature exists to tell apart from one.
6255fn describe(state: &RunState) -> String {
6256    let p = phrases(&state.config.graph.language);
6257    let mut detail = if state.status == RunStatus::Stalled {
6258        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6259        seats.sort_unstable();
6260        seats.dedup();
6261        if seats.is_empty() {
6262            p.quorum_lost.to_owned()
6263        } else {
6264            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6265        }
6266    } else {
6267        format!("{}{}", p.run_ended, state.status.display_label())
6268    };
6269    if let Some(cause) = state.verification_blocking_cause() {
6270        detail.push_str(&format!(" ({cause})"));
6271    } else if let Some(last) = state.events.last() {
6272        // The review loop's "never answered" stop is the one event worth
6273        // translating; it is recognised from structured state, not by
6274        // matching the English event text (which stays as recorded).
6275        let unanswered = state
6276            .reviews
6277            .last()
6278            .filter(|r| {
6279                state.status == RunStatus::Blocked
6280                    && last.node == "review"
6281                    && r.incomplete()
6282                    && r.blocking == 0
6283                    && r.round == state.config.graph.review_rounds
6284                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6285            })
6286            .map(|r| (r.expected - r.answered, r.round));
6287        match unanswered {
6288            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6289                detail.push_str(&format!(
6290                    " ({}: {})",
6291                    last.node,
6292                    (p.reviewers_never_answered)(missing, rounds)
6293                ));
6294            }
6295            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6296        }
6297    }
6298    detail.push_str(&format!(" [run {}]", state.id));
6299    detail
6300}
6301
6302/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6303///
6304/// The task file lives in the backlog indefinitely; a diagnostic is an
6305/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6306/// stay small regardless of how much a gate command or a candidate printed.
6307const DIAGNOSTIC_MAX: usize = 4_000;
6308
6309/// Tail kept from a single failing command's output inside a diagnostic.
6310/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6311/// pointer for a human deciding whether to go read the full artifact by hand,
6312/// not a replacement for reading it.
6313const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6314
6315/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6316/// `magi task show` says more than the one-line reason in [`describe`].
6317///
6318/// The one-liner answers "where did the run stop"; this answers "what would a
6319/// human have found opening `artifacts/` by hand" — the point of the whole
6320/// feature is the case that one-liner actively misleads on: a run held as "no
6321/// candidate produced a change" can mean the implementer actually finished
6322/// the task (opened a PR, merged it, tagged a release) and only left a clean
6323/// local worktree behind, which reads as "nothing happened" unless someone
6324/// goes and reads what the agent actually said. `None` when the run carries
6325/// none of the three shapes this recognises — an ordinary run held for
6326/// something not diagnosable from `RunState` alone still explains itself
6327/// through `Task::last_error`.
6328fn diagnostic(state: &RunState) -> Option<String> {
6329    let mut parts: Vec<String> = Vec::new();
6330
6331    // Gate failure: which check(s), and the tail of what each printed.
6332    for o in state.gate.iter().filter(|o| !o.ok()) {
6333        parts.push(format!(
6334            "gate `{}` failed ({}):\n{}",
6335            o.command,
6336            notices::exit_status(o.code),
6337            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6338        ));
6339    }
6340
6341    // The land loop gave up because the fixer declined while checks were
6342    // still red: the message already names them (see `land::run`).
6343    if let Some(last) = state
6344        .events
6345        .iter()
6346        .rev()
6347        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6348    {
6349        parts.push(last.message.clone());
6350    }
6351
6352    // No viable candidate: every implementer's own final word, sanitized the
6353    // same way a judge would have read it, so a run that actually finished
6354    // the job does not read as an unexplained failure. A verified no-op is
6355    // called out ahead of its own summary and apart from an ordinary
6356    // failure's `why` — this is the one candidate shape whose diagnostic a
6357    // human is expected to actually judge, not just skim.
6358    if state.viable().is_empty() {
6359        for c in &state.candidates {
6360            if let Some(evidence) = &c.verified_noop {
6361                parts.push(format!(
6362                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6363                    c.label
6364                ));
6365            } else if !c.summary.trim().is_empty() {
6366                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6367            } else if let Some(why) = &c.failed {
6368                parts.push(format!("candidate {}: {why}", c.label));
6369            }
6370        }
6371    }
6372
6373    if parts.is_empty() {
6374        return None;
6375    }
6376    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6377    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6378    // back slightly over. Leave it enough room to always land under the
6379    // limit.
6380    Some(crate::run::tail(
6381        &parts.join("\n\n"),
6382        DIAGNOSTIC_MAX.saturating_sub(100),
6383    ))
6384}
6385
6386/// Stable lower-case name for a run status, for an internal log line and the
6387/// "graph stopped without reaching a terminal status" bug message in
6388/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6389/// doc for why that one reads [`RunStatus::display_label`] instead. One
6390/// definition of a status's name, on the type that owns it: this table used
6391/// to live here as a second copy, and a status renamed in one place would
6392/// have gone on reading correctly in the other.
6393fn label(status: RunStatus) -> &'static str {
6394    status.as_str()
6395}
6396
6397/// Parse a merge mode override.
6398pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6399    match mode {
6400        "none" => Ok(MergeMode::None),
6401        "local" => Ok(MergeMode::Local),
6402        "pr" => Ok(MergeMode::Pr),
6403        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6404    }
6405}
6406
6407/// Take the status lock, recovering from a poisoned one.
6408///
6409/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6410/// data, and the worst a poisoned lock can hold is a stale timestamp.
6411fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6412    mutex
6413        .lock()
6414        .unwrap_or_else(std::sync::PoisonError::into_inner)
6415}
6416
6417#[cfg(test)]
6418mod tests {
6419    use super::*;
6420    use crate::queue::{Source, TaskStatus};
6421    use crate::run::{Candidate, CommandOutcome};
6422    use pretty_assertions::assert_eq;
6423
6424    fn task() -> Task {
6425        Task::new(
6426            "add retries".to_owned(),
6427            "add retries".to_owned(),
6428            PathBuf::from("/repo"),
6429            Source::Human,
6430        )
6431    }
6432
6433    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6434        let job = crate::worker::Job {
6435            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6436            sequence: 1,
6437            kind: "task".into(),
6438            key: format!("task:{}", request.task),
6439            payload: serde_json::to_value(request).unwrap(),
6440            generation: "a".repeat(64),
6441            version: None,
6442            status: crate::worker::Status::Starting,
6443            result: None,
6444            pid: None,
6445            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6446            finished_at: None,
6447        };
6448        let dir = home.join("workers/jobs").join(&job.id);
6449        std::fs::create_dir_all(&dir).unwrap();
6450        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6451        job
6452    }
6453
6454    #[test]
6455    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6456        let home = tempfile::tempdir().unwrap();
6457        let request = TaskWorker {
6458            opts: Opts::default(),
6459            queue: home.path().join("queue"),
6460            task: "startup".into(),
6461            lane: PermitKind::Ordinary,
6462            standalone: false,
6463        };
6464        let job = starting_task_reservation(home.path(), &request);
6465        let error = task_worker_spawn_error(
6466            home.path(),
6467            &request,
6468            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6469        )
6470        .expect_err("our own reservation must not turn a failed spawn into a resync");
6471        let active = crate::worker::active(home.path()).unwrap();
6472        assert_eq!(active.len(), 1);
6473        assert_eq!(active[0].id, job.id);
6474        assert_eq!(active[0].status, crate::worker::Status::Starting);
6475        assert!(
6476            crate::worker::control(home.path(), &job.key)
6477                .unwrap()
6478                .is_none()
6479        );
6480        let notices = notices::Notices::at(home.path().join("notifications")).list();
6481        assert_eq!(notices.len(), 1);
6482        assert_eq!(notices[0].key, "loop:worker-startup");
6483        assert!(!notices[0].message.contains("private-error-detail"));
6484        assert!(notices[0].message.contains(&request.task));
6485        assert!(
6486            notices[0]
6487                .message
6488                .contains("could not be started or acknowledged")
6489        );
6490        assert!(notices[0].message.contains("worker.log"));
6491        assert_eq!(
6492            notices[0].link,
6493            Some(Link::Task {
6494                id: request.task.clone()
6495            })
6496        );
6497        assert!(format!("{error:#}").contains("private-error-detail"));
6498    }
6499
6500    #[test]
6501    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6502        let home = tempfile::tempdir().unwrap();
6503        let mut request = TaskWorker {
6504            opts: Opts::default(),
6505            queue: home.path().join("queue"),
6506            task: "handoff".into(),
6507            lane: PermitKind::Ordinary,
6508            standalone: true,
6509        };
6510        let job = starting_task_reservation(home.path(), &request);
6511        request.standalone = false;
6512        task_worker_spawn_error(
6513            home.path(),
6514            &request,
6515            anyhow::anyhow!("operation key is already reserved for a different request"),
6516        )
6517        .expect("a different standalone request is the handoff race, not our startup failure");
6518        let active = crate::worker::active(home.path()).unwrap();
6519        assert_eq!(active.len(), 1);
6520        assert_eq!(active[0].id, job.id);
6521        assert_eq!(active[0].payload, job.payload);
6522        assert!(
6523            notices::Notices::at(home.path().join("notifications"))
6524                .list()
6525                .is_empty()
6526        );
6527    }
6528
6529    #[test]
6530    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6531        let home = tempfile::tempdir().unwrap();
6532        let queue = Queue::at(home.path().join("queue"));
6533        let mut task = task();
6534        task.runs = vec!["previous".into()];
6535        queue.put(&mut task).unwrap();
6536        let request = TaskWorker {
6537            opts: Opts::default(),
6538            queue: home.path().join("queue"),
6539            task: task.id.clone(),
6540            lane: PermitKind::Ordinary,
6541            standalone: false,
6542        };
6543        let job = starting_task_reservation(home.path(), &request);
6544        let claims = current_work(home.path(), Timestamp::now());
6545        assert_eq!(claims.len(), 1);
6546        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6547        assert_eq!(claims[0].run, "previous");
6548        assert!(other_claims_run(&claims, "previous", None));
6549        // Only after confirming the executing caller may admission ignore
6550        // this exact projection. Cleanup continues to observe it as live.
6551        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6552        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6553    }
6554
6555    #[test]
6556    fn admission_excludes_only_the_callers_exact_reservation() {
6557        let own = Current {
6558            worker: Some("own".into()),
6559            task: "same-task".into(),
6560            run: "previous".into(),
6561        };
6562        assert!(!other_claims_run(
6563            std::slice::from_ref(&own),
6564            "previous",
6565            Some("own")
6566        ));
6567        assert!(other_claims_run(
6568            std::slice::from_ref(&own),
6569            "previous",
6570            None
6571        ));
6572        for worker in [None, Some("other".into())] {
6573            let other = Current {
6574                worker,
6575                ..own.clone()
6576            };
6577            assert!(other_claims_run(
6578                &[own.clone(), other],
6579                "previous",
6580                Some("own")
6581            ));
6582        }
6583        let legacy: Current =
6584            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6585        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6586    }
6587
6588    #[test]
6589    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6590        let mut task = task();
6591        let mut run = run_state(RunStatus::Reviewing);
6592        run.task_instruction = Some(task.instruction.clone());
6593        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6594        let branch = "magi/test/B";
6595        run.candidates.push(crate::run::Candidate {
6596            branch: branch.into(),
6597            ..candidate('B', "preserved work", false, None)
6598        });
6599        task.runs = vec![run.id.clone()];
6600        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6601        assert_eq!(
6602            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6603            Starter::Resume(run.id.clone())
6604        );
6605        assert!(matches!(
6606            review_retry_starter(
6607                &task,
6608                Some(&run),
6609                Some("different"),
6610                true,
6611                unfinished.as_deref()
6612            ),
6613            Starter::Review(_)
6614        ));
6615        assert_eq!(
6616            review_retry_starter(
6617                &task,
6618                Some(&run),
6619                Some(branch),
6620                false,
6621                unfinished.as_deref()
6622            ),
6623            Starter::Start
6624        );
6625        task.instruction.push_str(" changed criteria");
6626        assert!(matches!(
6627            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6628            Starter::Review(_)
6629        ));
6630        assert!(matches!(
6631            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6632            Starter::Review(_)
6633        ));
6634    }
6635
6636    #[test]
6637    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6638        let dir = tempfile::tempdir().unwrap();
6639        let queue = Queue::at(dir.path().join("queue"));
6640        let mut task = task();
6641        task.status = TaskStatus::Running;
6642        task.attempts = 1;
6643        queue.put(&mut task).unwrap();
6644        let live = std::collections::BTreeSet::from([task.id.clone()]);
6645        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6646        drop(queue.claim(&task.id).unwrap());
6647        let saved = queue.get(&task.id).unwrap();
6648        assert_eq!(saved.status, TaskStatus::Running);
6649        assert_eq!(saved.attempts, 1);
6650        assert!(saved.last_error.is_none());
6651    }
6652
6653    #[test]
6654    fn standalone_workers_do_not_consume_scheduler_lanes() {
6655        let request = |task: &str, lane, standalone| TaskWorker {
6656            opts: Opts::default(),
6657            queue: PathBuf::from("/queue"),
6658            task: task.to_owned(),
6659            lane,
6660            standalone,
6661        };
6662        let mut jobs = vec![
6663            request("ordinary", PermitKind::Ordinary, false),
6664            request("standalone-urgent", PermitKind::Urgent, true),
6665            request("standalone-ordinary", PermitKind::Ordinary, true),
6666            request("decision", PermitKind::None, false),
6667        ];
6668        assert_eq!(available_slots(&jobs, 2), (1, 1));
6669        jobs.push(request("urgent", PermitKind::Urgent, false));
6670        assert_eq!(available_slots(&jobs, 2), (1, 0));
6671        assert_eq!(available_slots(&jobs, 0), (0, 0));
6672    }
6673
6674    #[test]
6675    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6676        let now = Timestamp::now();
6677        let mut reading = Reading {
6678            pid: Some(std::process::id()),
6679            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6680            ..Reading::default()
6681        };
6682        assert!(!reading.running(now));
6683        assert!(legacy_scheduler_running(&reading, now, 0));
6684        reading.worker_protocol = Some(1);
6685        assert!(!legacy_scheduler_running(&reading, now, 0));
6686    }
6687
6688    #[test]
6689    fn selected_public_head_overrides_historical_resume_and_pin() {
6690        let mut t = task();
6691        let mut old = run_state(RunStatus::Blocked);
6692        let selection = crate::pr_recovery::Selection {
6693            url: "url".into(),
6694            branch: format!("magi/task-{}", t.id),
6695            head: "a".repeat(40),
6696            source_head: None,
6697            source_run: None,
6698            source_proof: None,
6699            disposition: Some(crate::pr_recovery::Disposition::Review),
6700            instruction: t.instruction.clone(),
6701            approved_at: Timestamp::now(),
6702        };
6703        t.resume_override = Some(crate::queue::OperatorResume {
6704            pinned_run: Some(old.id.clone()),
6705            question_id: "choice".into(),
6706            at: Timestamp::now(),
6707            conductor_rehold: None,
6708            forced: false,
6709        });
6710        assert_eq!(
6711            selected_starter(&selection, Some(&old), Some(&old.id)),
6712            Starter::Review(selection.branch.clone())
6713        );
6714        old.pr_recovery = Some(selection.clone());
6715        assert_eq!(
6716            selected_starter(&selection, Some(&old), Some(&old.id)),
6717            Starter::Review(selection.branch.clone())
6718        );
6719        old.reviewed_commits = Some(vec!["implementation".into()]);
6720        assert_eq!(
6721            selected_starter(&selection, Some(&old), Some(&old.id)),
6722            Starter::Resume(old.id.clone())
6723        );
6724        let mut changed = selection.clone();
6725        changed.head = "b".repeat(40);
6726        assert_eq!(
6727            selected_starter(&changed, Some(&old), Some(&old.id)),
6728            Starter::Review(changed.branch)
6729        );
6730    }
6731
6732    #[test]
6733    fn candidate_transplant_failure_is_one_actionable_hold() {
6734        let dir = tempfile::tempdir().unwrap();
6735        let q = Queue::at(dir.path().join("queue"));
6736        let mut t = task();
6737        let mut state = run_state(RunStatus::Blocked);
6738        state.event("prep", "cannot apply referenced commit: conflict");
6739        state.prep_failure = Some("conflict".into());
6740        t.start(state.id.clone());
6741        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6742        assert_eq!(t.attempts, 1);
6743        assert_eq!(t.status, TaskStatus::Held);
6744        assert!(t.operator_held());
6745        assert!(!t.status.runnable());
6746        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6747        let first = t.chat_notice_key().unwrap();
6748        t.chat_notices.push(first.clone());
6749        t.release_operator("test", None);
6750        state.id = "another-unprepared-run".into();
6751        t.start(state.id.clone());
6752        finish_attempt(
6753            3,
6754            &q,
6755            &mut t,
6756            &state,
6757            &[],
6758            Err(anyhow::anyhow!("still conflicts")),
6759        );
6760        assert_eq!(
6761            t.chat_notice_key().as_ref(),
6762            Some(&first),
6763            "no work happened"
6764        );
6765        t.release_operator("test", None);
6766        state.prep_failure = None;
6767        state.status = RunStatus::Failed;
6768        state.begin_pass();
6769        t.start(state.id.clone());
6770        finish_attempt(
6771            1,
6772            &q,
6773            &mut t,
6774            &state,
6775            &[],
6776            Err(anyhow::anyhow!("new gate failure")),
6777        );
6778        let failure = t.chat_notice_key().unwrap();
6779        assert_ne!(failure, first, "approved recovery reached a real failure");
6780        t.release_operator("test", None);
6781        state.begin_pass();
6782        t.start(state.id.clone());
6783        finish_attempt(
6784            1,
6785            &q,
6786            &mut t,
6787            &state,
6788            &[],
6789            Err(anyhow::anyhow!("new failure on resume")),
6790        );
6791        assert_ne!(
6792            t.chat_notice_key().as_ref(),
6793            Some(&failure),
6794            "a new settled pass"
6795        );
6796    }
6797
6798    #[test]
6799    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6800        for source in ["cli", "web"] {
6801            let mut t = task();
6802            let mut run = run_state(RunStatus::Blocked);
6803            run.instruction = "Run A original criteria".into();
6804            run.task_instruction = Some(run.instruction.clone());
6805            t.start(run.id.clone());
6806            t.release_operator("choice", Some("resume-question"));
6807            t.resume_override = Some(crate::queue::OperatorResume {
6808                question_id: "resume-question".into(),
6809                at: Timestamp::now(),
6810                conductor_rehold: None,
6811                forced: true,
6812                pinned_run: Some(run.id.clone()),
6813            });
6814            t.hold_machine(Some("not enough free space to start a run".into()));
6815            let mut unchanged = t.clone();
6816            unchanged
6817                .edit("title changed".into(), unchanged.instruction.clone())
6818                .unwrap();
6819            unchanged.release_operator(source, None);
6820            assert_eq!(
6821                unchanged
6822                    .resume_override
6823                    .as_ref()
6824                    .unwrap()
6825                    .pinned_run
6826                    .as_deref(),
6827                Some(run.id.as_str())
6828            );
6829            assert!(!compatible_run_instruction(&run, &unchanged));
6830            assert!(may_resume_run(&run, &unchanged));
6831
6832            t.edit(
6833                "approved recovery".into(),
6834                "Reuse measured PR head B; fix Clippy; review".into(),
6835            )
6836            .unwrap();
6837            assert!(t.resume_override.is_none());
6838            t.release_operator(source, None);
6839            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6840            assert!(reloaded.resume_override.is_none());
6841            assert!(!may_resume_run(&run, &reloaded));
6842            let unfinished =
6843                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6844                    .filter(|_| may_resume_run(&run, &reloaded));
6845            assert_eq!(
6846                choose_starter(None, false, unfinished.as_deref()),
6847                Starter::Start
6848            );
6849            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6850            assert_eq!(
6851                reloaded.resumption_history[0].question_id.as_deref(),
6852                Some("resume-question")
6853            );
6854
6855            // A revision already persisted with the old approval/pin is also
6856            // invalidated when the new operator release is recorded.
6857            unchanged.instruction = "Reuse measured PR head B".into();
6858            unchanged.hold_machine(Some("disk hold".into()));
6859            unchanged.release_operator(source, None);
6860            assert!(unchanged.resume_override.is_none());
6861            assert!(!may_resume_run(&run, &unchanged));
6862        }
6863    }
6864
6865    #[test]
6866    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6867        let mut t = task();
6868        let mut run = run_state(RunStatus::Blocked);
6869        t.review_of = Some("approved-head".into());
6870        t.instruction =
6871            "Review the branch `approved-head` (review-only: no implementation, no judging)."
6872                .into();
6873        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();
6874        run.reviewed_commits = Some(vec!["Commit log".into()]);
6875        t.start(run.id.clone());
6876        t.hold_machine(Some("interrupted review".into()));
6877        t.release_operator("cli", None);
6878        assert!(
6879            compatible_run_instruction(&run, &t),
6880            "legacy explicit review remains resumable"
6881        );
6882        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6883            .filter(|_| compatible_run_instruction(&run, &t));
6884        assert_eq!(
6885            choose_starter(None, false, unfinished.as_deref()),
6886            Starter::Resume(run.id.clone())
6887        );
6888        run.task_instruction = Some(t.instruction.clone());
6889        assert!(compatible_run_instruction(&run, &t));
6890        let reloaded: RunState =
6891            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6892        assert!(compatible_run_instruction(&reloaded, &t));
6893        t.edit(
6894            "new approved head".into(),
6895            "Reuse measured PR head B".into(),
6896        )
6897        .unwrap();
6898        assert!(!compatible_run_instruction(&run, &t));
6899
6900        // Legacy recovery reviews retain the task criteria ahead of the log.
6901        t.review_of = None;
6902        t.instruction = "Fix Clippy on approved head".into();
6903        run.task_instruction = None;
6904        run.instruction = format!(
6905            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6906            t.instruction
6907        );
6908        assert!(compatible_run_instruction(&run, &t));
6909        t.instruction.push('\n');
6910        assert!(
6911            compatible_run_instruction(&run, &t),
6912            "legacy generated review trimmed the original criteria"
6913        );
6914        t.hold_for_handover(Some("approved-head".into()), "refused".into());
6915        let mut unchanged = t.clone();
6916        assert_eq!(
6917            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6918            Some("approved-head")
6919        );
6920        t.edit("new plan".into(), "Reuse measured PR head B".into())
6921            .unwrap();
6922        assert!(take_review_branch(&mut t, Some(&run)).is_none());
6923        assert!(!compatible_run_instruction(&run, &t));
6924        t.review_branch = Some("approved-head".into());
6925        t.review_instruction = None;
6926        assert!(
6927            take_review_branch(&mut t, Some(&run)).is_none(),
6928            "legacy retained candidate cannot replace a revised approved head"
6929        );
6930    }
6931
6932    #[test]
6933    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6934        let home = crate::run::test_home();
6935        crate::run::pin_test_home();
6936        let dir = tempfile::tempdir().unwrap();
6937        let queue = Queue::at(dir.path().join("queue"));
6938        for resume in [true, false] {
6939            let state = run_state(RunStatus::Blocked);
6940            let mut t = task();
6941            t.start(state.id.clone());
6942            let action = if resume {
6943                ask::ChoiceAction::Resume {
6944                    run: state.id.clone(),
6945                }
6946            } else {
6947                ask::ChoiceAction::Requeue
6948            };
6949            let mut q = action_question(&state.id, action);
6950            q.status = ask::QuestionStatus::Open;
6951            q.answer = None;
6952            q.answered_at = None;
6953            t.fail("run stopped with a question", 3);
6954            hold_if_runnable(&queue, &mut t);
6955            assert!(t.operator_decided_at.is_none());
6956            assert!(t.operator_held());
6957            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6958            let expected = if resume {
6959                ActionDecision::Resume(state.id.clone())
6960            } else {
6961                ActionDecision::Requeue
6962            };
6963            assert_eq!(
6964                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6965                expected
6966            );
6967            t.hold_manual(Some("later explicit hold".into()));
6968            assert_eq!(
6969                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6970                ActionDecision::Stale
6971            );
6972        }
6973    }
6974
6975    #[test]
6976    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6977        let mut t = task();
6978        t.answers.push(crate::queue::AnsweredQuestion {
6979            question: "Inspect the remote?".into(),
6980            answer: "Inspect then wait".into(),
6981        });
6982        let old = instruction_for(&t);
6983        assert!(compatible_instruction(&old, &t));
6984        t.instruction = "Reuse approved PR head and review".into();
6985        t.release_operator("cli", None);
6986        assert!(!compatible_instruction(&old, &t));
6987        let approved = instruction_for(&t);
6988        assert!(approved.contains("waiting premises are superseded"));
6989        assert!(compatible_instruction(&approved, &t));
6990        assert_eq!(resumed_instruction(&approved, &t), approved);
6991        t.release_operator("web", None);
6992        assert!(compatible_instruction(&approved, &t));
6993        assert_eq!(t.resumption_history.len(), 1);
6994        t.start("run".into());
6995        assert!(instruction_for(&t).contains("Explicit operator resumption"));
6996    }
6997
6998    /// A run that stopped on an infrastructure wait asked no agent anything:
6999    /// the task is held by the machine under a `[resource]` reason (resumable,
7000    /// re-checked by triage), and the attempt it started is given back.
7001    #[test]
7002    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7003        let mut state = RunState::new(
7004            PathBuf::from("/repo"),
7005            "main".into(),
7006            "base".into(),
7007            "task".into(),
7008            Config::default(),
7009        );
7010        state.status = RunStatus::Landing;
7011        state.parked = true;
7012        state.pr_pushed_head = Some("head".into());
7013        state.land_unrelated = Some(
7014            serde_json::from_value(serde_json::json!({
7015                "head": "head", "question": "ci-question",
7016                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7017            }))
7018            .unwrap(),
7019        );
7020        let mut t = task();
7021        t.start(state.id.clone());
7022        let verdict = Verdict {
7023            status: RunStatus::Landing,
7024            left_pr: true,
7025            quota_hit: false,
7026            parked: true,
7027            no_viable_candidates: false,
7028        };
7029        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7030        assert_eq!(t.attempts, 0);
7031        assert_eq!(t.status, TaskStatus::Held);
7032        assert!(!t.operator_held());
7033        assert!(
7034            t.hold_reason
7035                .as_deref()
7036                .unwrap()
7037                .starts_with("[ci-unrelated]")
7038        );
7039        // A second settlement must not refund an earlier task attempt.
7040        t.attempts = 1;
7041        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7042        assert_eq!(t.attempts, 1);
7043        assert_eq!(t.passes.len(), 1);
7044        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7045        state.pr_pushed_head = Some("new-head".into());
7046        state.parked = false;
7047        state.status = RunStatus::Blocked;
7048        let stale = Verdict {
7049            status: RunStatus::Blocked,
7050            parked: false,
7051            ..verdict
7052        };
7053        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7054        assert_eq!(t.attempts, 1);
7055        // A new execution pass can refund its own newly charged attempt.
7056        state.begin_pass();
7057        state.begin_pass();
7058        state.status = RunStatus::Landing;
7059        state.parked = true;
7060        state.pr_pushed_head = Some("head".into());
7061        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7062        assert_eq!(t.attempts, 0);
7063        assert_eq!(t.passes.len(), 2);
7064    }
7065
7066    #[test]
7067    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7068        let mut state = run_state(RunStatus::Failed);
7069        state
7070            .quota
7071            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7072        state.begin_pass();
7073        let mut t = task();
7074        t.start(state.id.clone());
7075        reclaim(&mut t, Some(state), 2, "en");
7076        assert_eq!(t.attempts, 1);
7077    }
7078
7079    #[test]
7080    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7081        let mut state = run_state(RunStatus::Blocked);
7082        let losses: Vec<_> = ["alpha", "beta"]
7083            .into_iter()
7084            .enumerate()
7085            .map(|(i, agent)| {
7086                QuotaLoss::from_report(
7087                    format!("advisor-{i}"),
7088                    "advise",
7089                    Some(&crate::agent::Quota {
7090                        cause: crate::agent::QuotaCause::Authentication,
7091                        agent: agent.to_owned(),
7092                        reset: None,
7093                    }),
7094                )
7095            })
7096            .collect();
7097        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7098        state.quota = losses;
7099        let mut t = task();
7100        t.start(state.id.clone());
7101        let verdict = Verdict {
7102            status: state.status,
7103            left_pr: false,
7104            quota_hit: true,
7105            parked: false,
7106            no_viable_candidates: true,
7107        };
7108        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7109        assert_eq!(t.attempts, 0);
7110        assert_eq!(t.status, TaskStatus::Held);
7111        assert!(!t.operator_held());
7112        let reason = t.hold_reason.as_deref().unwrap();
7113        assert!(reason.starts_with("[authentication]"));
7114        assert!(
7115            reason.contains("alpha")
7116                && reason.contains("beta")
7117                && reason.contains("re-authenticate")
7118        );
7119        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7120        // Orphan recovery uses the same settlement and cannot spend an attempt.
7121        let mut orphan = task();
7122        orphan.start(state.id.clone());
7123        reclaim(&mut orphan, Some(state), 2, "en");
7124        assert_eq!(orphan.attempts, 0);
7125        assert_eq!(orphan.status, TaskStatus::Held);
7126    }
7127
7128    #[test]
7129    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7130        let mut state = RunState::new(
7131            PathBuf::from("/repo"),
7132            "main".to_owned(),
7133            "abc1234".to_owned(),
7134            "task".to_owned(),
7135            Config::default(),
7136        );
7137        state.status = RunStatus::Blocked;
7138        state.resource_block = Some(crate::run::ResourceBlock {
7139            cause: crate::run::ResourceBlockCause::Other,
7140            node: "graft".to_owned(),
7141            kind: "shared build cache".to_owned(),
7142            detail: "timed out".to_owned(),
7143            at: jiff::Timestamp::now(),
7144        });
7145        let mut t = task();
7146        t.start("20260902-000000-aaaa".to_owned());
7147        assert_eq!(t.attempts, 1);
7148        let verdict = Verdict {
7149            status: RunStatus::Blocked,
7150            left_pr: false,
7151            quota_hit: false,
7152            parked: false,
7153            no_viable_candidates: false,
7154        };
7155        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7156        assert_eq!(t.status, TaskStatus::Held);
7157        assert_eq!(t.attempts, 0, "the attempt is refunded");
7158        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7159        assert!(
7160            !t.operator_held(),
7161            "a machine hold, released without a human"
7162        );
7163
7164        let mut selected = task();
7165        selected.start("20260902-000000-cccc".into());
7166        selected.replacement = Some(crate::merge_decision::Replacement {
7167            question: "fixture".into(),
7168            run: "earlier".into(),
7169            pr: "https://example.invalid/pr/1".into(),
7170            agent: "selected".into(),
7171            context: "fixture".into(),
7172        });
7173        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7174        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7175        assert_eq!(selected.attempts, 0);
7176        assert!(
7177            !selected.operator_held(),
7178            "a selected agent also retains a machine resource hold"
7179        );
7180        assert!(
7181            selected
7182                .hold_reason
7183                .as_deref()
7184                .unwrap()
7185                .starts_with("[resource] ")
7186        );
7187
7188        // A park request outranks it: still the operator's doing.
7189        let mut p = task();
7190        p.start("20260902-000000-bbbb".to_owned());
7191        settle_and_diagnose(
7192            &mut p,
7193            Verdict {
7194                parked: true,
7195                ..verdict
7196            },
7197            "parked",
7198            2,
7199            &state,
7200        );
7201        assert_eq!(p.status, TaskStatus::Parked);
7202        assert_eq!(
7203            p.attempts, 0,
7204            "parking refunds once rather than also settling the resource hold"
7205        );
7206    }
7207
7208    #[test]
7209    fn record_failure_notice_links_the_task() {
7210        let dir = tempfile::tempdir().unwrap();
7211        // A regular file where the queue directory should be makes every
7212        // `put` fail, on every platform and whoever runs the test.
7213        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7214        let queue = Queue::at(dir.path().join("queue"));
7215        let mut t = interrupt_task("rec-fail-1");
7216        record(&queue, &mut t);
7217
7218        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7219        assert_eq!(found.len(), 1);
7220        assert_eq!(found[0].key, "loop:record");
7221        assert_eq!(
7222            found[0].link,
7223            Some(Link::Task {
7224                id: "rec-fail-1".to_owned()
7225            })
7226        );
7227    }
7228
7229    /// A runnable task marked to interrupt, with an id fixed for assertions
7230    /// rather than the random one [`Task::new`] mints.
7231    fn interrupt_task(id: &str) -> Task {
7232        let mut t = task();
7233        t.id = id.to_owned();
7234        t.interrupt = true;
7235        t
7236    }
7237
7238    /// An ordinary runnable task with an id fixed for assertions.
7239    fn task_with_id(id: &str) -> Task {
7240        let mut t = task();
7241        t.id = id.to_owned();
7242        t
7243    }
7244
7245    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7246    fn urgent_task(id: &str) -> Task {
7247        let mut t = task();
7248        t.id = id.to_owned();
7249        t.urgent = true;
7250        t
7251    }
7252
7253    #[test]
7254    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7255        let dir = tempfile::tempdir().unwrap();
7256        let queue = Queue::at(dir.path().join("queue"));
7257        let mut parked = task_with_id("parked");
7258        parked.start("run".into());
7259        parked.park("upgrade");
7260        parked.record_pass_at(
7261            "run",
7262            0,
7263            Some(Timestamp::now()),
7264            1,
7265            Some(crate::run::ParkCause::Upgrade {
7266                from: "old".into(),
7267                to: None,
7268            }),
7269        );
7270        let mut fresh = task_with_id("fresh");
7271        fresh.priority = 100;
7272        let mut urgent_task = urgent_task("urgent");
7273        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7274            queue.put(t).unwrap();
7275        }
7276        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7277        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7278        let candidates = runnable(&queue);
7279        assert_eq!(candidates[0].id, parked.id);
7280        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7281        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7282        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7283        drop(first);
7284        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7285        let next = runnable(&queue)
7286            .into_iter()
7287            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7288            .unwrap();
7289        assert_eq!(next.task.id, fresh.id);
7290        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7291        drop(claimed_elsewhere);
7292        drop(next);
7293        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7294    }
7295
7296    #[test]
7297    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7298        let dir = tempfile::tempdir().unwrap();
7299        let queue = Queue::at(dir.path().join("queue"));
7300        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7301        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7302        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7303        let mut first = task();
7304        queue.put(&mut first).unwrap();
7305        let stale_plain = queue.get(&first.id).unwrap();
7306        first.set_urgent(true).unwrap();
7307        queue.put(&mut first).unwrap();
7308        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7309        let mut second = urgent_task("second");
7310        queue.put(&mut second).unwrap();
7311        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7312        drop(queue.claim(&second.id).unwrap());
7313        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7314        drop(dispatched);
7315        let stale_urgent = queue.get(&first.id).unwrap();
7316        first.set_urgent(false).unwrap();
7317        queue.put(&mut first).unwrap();
7318        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7319        assert_eq!(urgent.available_permits(), 1);
7320        drop(queue.claim(&first.id).unwrap());
7321        drop(occupied);
7322    }
7323
7324    #[test]
7325    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7326        let dir = tempfile::tempdir().unwrap();
7327        let queue = Queue::at(dir.path().join("queue"));
7328        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7329        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7330        let mut t = task();
7331        queue.put(&mut t).unwrap();
7332        for enabled in [true, false] {
7333            let stale = queue.get(&t.id).unwrap();
7334            t.set_urgent(enabled).unwrap();
7335            queue.put(&mut t).unwrap();
7336            assert_ne!(stale.urgent, enabled);
7337            let DispatchClaim {
7338                task: fresh,
7339                claim,
7340                permit,
7341            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7342            assert_eq!(fresh.urgent, enabled);
7343            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7344            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7345            assert!(queue.claim(&t.id).is_err());
7346            assert_eq!(fresh.attempts, stale.attempts);
7347            drop((claim, permit));
7348            assert_eq!(ordinary.available_permits(), 1);
7349            assert_eq!(urgent.available_permits(), 1);
7350        }
7351        t.set_urgent(true).unwrap();
7352        queue.put(&mut t).unwrap();
7353        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7354        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7355        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7356        drop(queue.claim(&t.id).unwrap());
7357        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7358        drop(occupied);
7359        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7360        drop(queue.claim(&t.id).unwrap());
7361        let held = queue.claim(&t.id).unwrap();
7362        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7363        drop(held);
7364        t.status = TaskStatus::Held;
7365        queue.put(&mut t).unwrap();
7366        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7367        drop(queue.claim(&t.id).unwrap());
7368        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7369        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7370        drop(queue.claim(&t.id).unwrap());
7371        assert_eq!(urgent.available_permits(), 1);
7372    }
7373
7374    /// The land-resume exemption wins outright, whether or not the candidate
7375    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7376    /// queue behind anything" guarantee cannot be weaker just because the
7377    /// same task was also filed with `--urgent`.
7378    #[test]
7379    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7380        assert_eq!(permit_kind(true, false), PermitKind::None);
7381        assert_eq!(permit_kind(true, true), PermitKind::None);
7382    }
7383
7384    /// The one property this whole feature exists for: `--urgent` draws from
7385    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7386    /// ordinary candidate draws from the ordinary pool exactly as before,
7387    /// untouched by the urgent slot's existence.
7388    #[test]
7389    fn permit_kind_separates_urgent_from_ordinary() {
7390        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7391        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7392    }
7393
7394    /// The exact wiring `attempt` runs before minting anything: a config's
7395    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7396    /// Free space is injected rather than asked of the real disk - the point
7397    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7398    /// is deterministic on every machine this test runs on, never dependent
7399    /// on how full the CI runner's own disk happens to be.
7400    #[test]
7401    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7402        let cfg = Config::default();
7403        let repo = Path::new("/any/repo/path");
7404
7405        let reason =
7406            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7407        assert!(reason.contains("1024"), "{reason}");
7408        assert!(
7409            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7410            "{reason}"
7411        );
7412
7413        assert_eq!(
7414            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7415            None,
7416            "exactly at the floor is open"
7417        );
7418        assert_eq!(
7419            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7420            None,
7421            "comfortably above the floor is open"
7422        );
7423    }
7424
7425    #[test]
7426    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7427        let mut cfg = Config::default();
7428        cfg.disk.min_free_bytes = 0;
7429        let repo = Path::new("/any/repo/path");
7430        assert_eq!(
7431            disk_gate_with(repo, &cfg, |_| Ok(0)),
7432            None,
7433            "a zero floor never measures at all"
7434        );
7435    }
7436
7437    #[test]
7438    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7439        let cfg = Config::default();
7440        let repo = Path::new("/any/repo/path");
7441        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7442            .expect("a measurement failure must close the gate, not open it");
7443        assert!(reason.contains("could not measure"), "{reason}");
7444    }
7445
7446    #[test]
7447    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7448        let ordinary = task();
7449        let next = advance_interrupt(
7450            Interrupt::Idle,
7451            std::slice::from_ref(&ordinary.id),
7452            std::slice::from_ref(&ordinary),
7453        );
7454        assert_eq!(next, Interrupt::Idle);
7455    }
7456
7457    #[test]
7458    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7459        // Nothing to interrupt - this is just an ordinary candidate, and the
7460        // loop's normal dispatch will pick it up like any other.
7461        let marked = interrupt_task("marked");
7462        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7463        assert_eq!(next, Interrupt::Idle);
7464    }
7465
7466    #[test]
7467    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7468        let marked = interrupt_task("marked");
7469        let next = advance_interrupt(
7470            Interrupt::Idle,
7471            &["running".to_owned()],
7472            std::slice::from_ref(&marked),
7473        );
7474        assert_eq!(
7475            next,
7476            Interrupt::Parking {
7477                parked: vec!["running".to_owned()],
7478                interrupt_task: "marked".to_owned(),
7479            }
7480        );
7481    }
7482
7483    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7484    /// one run can be in flight when a task becomes runnable and marked.
7485    /// Parking all of them would mean `Resuming` later has more than one id
7486    /// to release back to ordinary dispatch, which cannot be made safe
7487    /// against that same setting's own extra concurrency slots letting two
7488    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7489    /// The simplification the task's own constraints ask for: do not begin
7490    /// a sequence at all until the herd settles back to exactly one.
7491    #[test]
7492    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7493        let marked = interrupt_task("marked");
7494
7495        let two = advance_interrupt(
7496            Interrupt::Idle,
7497            &["a".to_owned(), "b".to_owned()],
7498            std::slice::from_ref(&marked),
7499        );
7500        assert_eq!(two, Interrupt::Idle);
7501
7502        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7503        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7504    }
7505
7506    #[test]
7507    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7508        let state = Interrupt::Parking {
7509            parked: vec!["running".to_owned()],
7510            interrupt_task: "marked".to_owned(),
7511        };
7512        // Still in flight: no change.
7513        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7514        assert_eq!(still_going, state);
7515
7516        // Left flight, but the interrupt task has not been dispatched yet on
7517        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7518        // as long as it is still runnable.
7519        let stopped_but_not_yet_dispatched =
7520            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7521        assert_eq!(stopped_but_not_yet_dispatched, state);
7522
7523        // Left flight, and the interrupt task is now in flight itself.
7524        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7525        assert_eq!(
7526            dispatched,
7527            Interrupt::Running {
7528                parked: vec!["running".to_owned()],
7529                interrupt_task: "marked".to_owned(),
7530            }
7531        );
7532    }
7533
7534    #[test]
7535    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7536        let state = Interrupt::Running {
7537            parked: vec!["running".to_owned()],
7538            interrupt_task: "marked".to_owned(),
7539        };
7540        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7541        assert_eq!(still_running, state);
7542
7543        // Whatever it ended as - merged, failed, held - is not this
7544        // function's concern: leaving flight is the only trigger, driven
7545        // straight off the same in-flight list `poll` already reaps. It does
7546        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7547        // why that would let an unrelated task start ahead of, or alongside,
7548        // the guaranteed resume.
7549        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7550        assert_eq!(
7551            ended,
7552            Interrupt::Resuming {
7553                parked: vec!["running".to_owned()]
7554            }
7555        );
7556    }
7557
7558    #[test]
7559    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7560        let state = Interrupt::Resuming {
7561            parked: vec!["running".to_owned()],
7562        };
7563        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7564        assert_eq!(still_waiting, state);
7565
7566        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7567        assert_eq!(dispatched, Interrupt::Idle);
7568    }
7569
7570    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7571    /// or otherwise moved on by an operator with no claim standing in the
7572    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7573    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7574    /// come. The parked run still gets its resume.
7575    #[test]
7576    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7577    {
7578        let state = Interrupt::Parking {
7579            parked: vec!["running".to_owned()],
7580            interrupt_task: "marked".to_owned(),
7581        };
7582        // `marked` has been held/blocked/deleted since the sequence began:
7583        // it no longer appears in `runnable` at all.
7584        let next = advance_interrupt(state, &[], &[]);
7585        assert_eq!(
7586            next,
7587            Interrupt::Resuming {
7588                parked: vec!["running".to_owned()]
7589            },
7590            "abandoning the interrupt must not abandon the resume it owes"
7591        );
7592    }
7593
7594    /// The same abandonment, one step later: `Resuming` itself must not wait
7595    /// forever for a parked task that has since become unrunnable.
7596    #[test]
7597    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7598        let state = Interrupt::Resuming {
7599            parked: vec!["running".to_owned()],
7600        };
7601        let next = advance_interrupt(state, &[], &[]);
7602        assert_eq!(
7603            next,
7604            Interrupt::Idle,
7605            "nothing is left to wait for; the loop must not stay wedged"
7606        );
7607    }
7608
7609    #[test]
7610    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7611        let marked = interrupt_task("marked");
7612        let next = advance_interrupt_tick(
7613            false,
7614            Interrupt::Idle,
7615            &["running".to_owned()],
7616            std::slice::from_ref(&marked),
7617        );
7618        assert_eq!(
7619            next,
7620            Interrupt::Idle,
7621            "an unmarked, unconfigured daemon must behave exactly as before"
7622        );
7623    }
7624
7625    #[test]
7626    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7627        let state = Interrupt::Parking {
7628            parked: vec!["running".to_owned()],
7629            interrupt_task: "marked".to_owned(),
7630        };
7631        let candidates = vec![interrupt_task("marked"), task()];
7632        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7633        assert!(
7634            allowed.is_empty(),
7635            "nothing may dispatch - not even the interrupt task itself - \
7636             until the parked run has actually stopped"
7637        );
7638    }
7639
7640    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7641    /// grow a special case for it: an urgent candidate that is not the
7642    /// interrupt task withholds exactly like an ordinary one for as long as
7643    /// the parked run it is racing has not actually left flight. A version
7644    /// of this feature once bypassed the gate for urgent candidates, on the
7645    /// theory that a genuinely separate concurrency lane could not collide
7646    /// with 75dd's own; it could, and did - the bypassed task dispatched
7647    /// alongside a run 75dd's own state machine had only *asked* to park,
7648    /// not yet confirmed gone, which is exactly the second run
7649    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7650    /// tick during Parking/Running/Resuming where letting an extra
7651    /// candidate through is safe, urgent or not - the parked run may still
7652    /// be genuinely mid-call.
7653    #[test]
7654    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7655        for state in [
7656            Interrupt::Parking {
7657                parked: vec!["running".to_owned()],
7658                interrupt_task: "marked".to_owned(),
7659            },
7660            Interrupt::Running {
7661                parked: vec!["running".to_owned()],
7662                interrupt_task: "marked".to_owned(),
7663            },
7664            Interrupt::Resuming {
7665                parked: vec!["running".to_owned()],
7666            },
7667        ] {
7668            let candidates = vec![
7669                interrupt_task("marked"),
7670                urgent_task("hot"),
7671                task_with_id("ordinary"),
7672            ];
7673            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7674            assert!(
7675                !allowed.iter().any(|t| t.id == "hot"),
7676                "an urgent candidate must wait out the same gate as anything \
7677                 else while the run it would run alongside has not actually \
7678                 left flight, for state {state:?}: {allowed:?}"
7679            );
7680        }
7681    }
7682
7683    /// The one case where marking a task `--urgent` and `interrupt` at once
7684    /// is not redundant: once the interrupt sequence's own guaranteed
7685    /// resume/dispatch actually admits the task, it is unaffected by also
7686    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7687    /// never on the urgent flag.
7688    #[test]
7689    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7690        let state = Interrupt::Resuming {
7691            parked: vec!["hot".to_owned()],
7692        };
7693        let candidates = vec![urgent_task("hot"), task()];
7694        let allowed = interrupt_gate(&state, &[], candidates);
7695        assert_eq!(
7696            allowed.iter().filter(|t| t.id == "hot").count(),
7697            1,
7698            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7699        );
7700    }
7701
7702    #[test]
7703    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7704        let state = Interrupt::Parking {
7705            parked: vec!["running".to_owned()],
7706            interrupt_task: "marked".to_owned(),
7707        };
7708        let other = task();
7709        let candidates = vec![interrupt_task("marked"), other.clone()];
7710        let allowed = interrupt_gate(&state, &[], candidates);
7711        assert_eq!(allowed.len(), 1);
7712        assert_eq!(allowed[0].id, "marked");
7713    }
7714
7715    #[test]
7716    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7717        let state = Interrupt::Running {
7718            parked: vec!["running".to_owned()],
7719            interrupt_task: "marked".to_owned(),
7720        };
7721        let candidates = vec![task(), task()];
7722        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7723        assert!(allowed.is_empty());
7724    }
7725
7726    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7727    /// sequence began (only reachable above the default
7728    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7729    /// never both in the same tick, which is what "exactly one resume, no
7730    /// simultaneous run" actually requires structurally rather than by
7731    /// coincidence of how many ordinary slots happen to be free.
7732    #[test]
7733    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7734        let state = Interrupt::Resuming {
7735            parked: vec!["a".to_owned(), "c".to_owned()],
7736        };
7737        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7738        let allowed = interrupt_gate(&state, &[], candidates);
7739        assert_eq!(
7740            allowed.len(),
7741            1,
7742            "at most one candidate may be offered while resuming: {allowed:?}"
7743        );
7744        assert_eq!(allowed[0].id, "a");
7745    }
7746
7747    #[test]
7748    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7749        let state = Interrupt::Resuming {
7750            parked: vec!["a".to_owned()],
7751        };
7752        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7753        assert!(allowed.is_empty());
7754    }
7755
7756    /// The invariant the completion criteria ask for by name: across a whole
7757    /// simulated sequence, there is never a tick where the gate would let
7758    /// through both the parked run's resume and the interrupt task, and
7759    /// exactly one candidate resumes the instant the interrupt task's run
7760    /// ends - never zero, never more than one.
7761    #[test]
7762    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7763        let running = task(); // id: whatever `Task::new` minted
7764        let marked = interrupt_task("marked");
7765
7766        let mut state = Interrupt::Idle;
7767        // Tick 1: `running` is in flight, `marked` becomes runnable.
7768        let in_flight = vec![running.id.clone()];
7769        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7770        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7771        assert!(gated.is_empty(), "still waiting on `running` to park");
7772
7773        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7774        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7775        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7776        assert_eq!(
7777            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7778            vec!["marked"],
7779            "only the interrupt task may be offered to the dispatcher now"
7780        );
7781
7782        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7783        state = advance_interrupt_tick(
7784            true,
7785            state,
7786            &["marked".to_owned()],
7787            std::slice::from_ref(&running),
7788        );
7789        let gated = interrupt_gate(
7790            &state,
7791            &["marked".to_owned()],
7792            vec![marked.clone(), running.clone()],
7793        );
7794        assert!(
7795            gated.is_empty(),
7796            "the parked run must not be offered back while the interrupt \
7797             task is still running"
7798        );
7799
7800        // Tick 4: `marked`'s run reached a terminal status and left flight.
7801        // A higher-priority ordinary task `other` is also runnable now - it
7802        // must not be let through instead of, or alongside, `running`.
7803        let other = task_with_id("other");
7804        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7805        assert_eq!(
7806            state,
7807            Interrupt::Resuming {
7808                parked: vec![running.id.clone()]
7809            }
7810        );
7811        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7812        assert_eq!(
7813            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7814            vec![running.id.as_str()],
7815            "exactly the parked run resumes - not the unrelated task, even \
7816             though it was offered first"
7817        );
7818
7819        // Tick 5: `running` is now in flight (dispatched from tick 4's
7820        // gate). Only now does the sequence end and ordinary dispatch fully
7821        // resume.
7822        state = advance_interrupt_tick(
7823            true,
7824            state,
7825            std::slice::from_ref(&running.id),
7826            std::slice::from_ref(&other),
7827        );
7828        assert_eq!(state, Interrupt::Idle);
7829        let gated = interrupt_gate(
7830            &state,
7831            std::slice::from_ref(&running.id),
7832            vec![other.clone()],
7833        );
7834        assert_eq!(
7835            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7836            vec![other.id.as_str()],
7837            "ordinary dispatch is unrestricted again"
7838        );
7839    }
7840
7841    #[test]
7842    fn every_run_status_settles_the_task_it_came_from() {
7843        // run status, resulting task status, attempts still standing after one
7844        let table = [
7845            (RunStatus::Merged, TaskStatus::Done, 1),
7846            (RunStatus::Ready, TaskStatus::Done, 1),
7847            (RunStatus::Stalled, TaskStatus::Failed, 0),
7848            (RunStatus::Blocked, TaskStatus::Failed, 1),
7849            (RunStatus::Failed, TaskStatus::Failed, 1),
7850            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7851            (RunStatus::Prep, TaskStatus::Failed, 1),
7852            (RunStatus::Implementing, TaskStatus::Failed, 1),
7853            (RunStatus::Judging, TaskStatus::Failed, 1),
7854            (RunStatus::Deliberating, TaskStatus::Failed, 1),
7855            (RunStatus::Voting, TaskStatus::Failed, 1),
7856            (RunStatus::Reviewing, TaskStatus::Failed, 1),
7857            (RunStatus::Gating, TaskStatus::Failed, 1),
7858        ];
7859        for (run, want, attempts) in table {
7860            let mut t = task();
7861            t.start("20260902-000000-aaaa".to_owned());
7862            settle(
7863                &mut t,
7864                Verdict {
7865                    status: run,
7866                    left_pr: false,
7867                    parked: false,
7868                    quota_hit: matches!(run, RunStatus::Stalled),
7869                    no_viable_candidates: false,
7870                },
7871                "why",
7872                2,
7873            );
7874            assert_eq!(t.status, want, "task status after {}", label(run));
7875            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7876        }
7877    }
7878
7879    #[test]
7880    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7881        let mut stalled = task();
7882        stalled.start("20260902-000000-aaaa".to_owned());
7883        settle(
7884            &mut stalled,
7885            Verdict {
7886                status: RunStatus::Stalled,
7887                left_pr: false,
7888                parked: false,
7889                quota_hit: true,
7890                no_viable_candidates: false,
7891            },
7892            "quota",
7893            1,
7894        );
7895        assert_eq!(stalled.attempts, 0);
7896        assert!(
7897            stalled.status.runnable(),
7898            "a machine problem must leave the task in line"
7899        );
7900
7901        let mut blocked = task();
7902        blocked.start("20260902-000000-aaaa".to_owned());
7903        settle(
7904            &mut blocked,
7905            Verdict {
7906                status: RunStatus::Blocked,
7907                left_pr: false,
7908                parked: false,
7909                quota_hit: false,
7910                no_viable_candidates: false,
7911            },
7912            "findings open",
7913            1,
7914        );
7915        assert_eq!(blocked.attempts, 1);
7916        assert_eq!(
7917            blocked.status,
7918            TaskStatus::Held,
7919            "the last attempt hands the task to a human"
7920        );
7921    }
7922
7923    #[test]
7924    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7925        // Attempts to spare: without the pull request this task would go
7926        // straight back in line and run the whole competition again.
7927        let mut delivered = task();
7928        delivered.start("20260903-080619-01c2".to_owned());
7929        settle(
7930            &mut delivered,
7931            Verdict {
7932                status: RunStatus::Blocked,
7933                left_pr: true,
7934                parked: false,
7935                quota_hit: false,
7936                no_viable_candidates: false,
7937            },
7938            "no check status",
7939            4,
7940        );
7941        assert_eq!(
7942            delivered.status,
7943            TaskStatus::Held,
7944            "a pull request waiting on CI or a person is not a retryable failure"
7945        );
7946        assert!(
7947            !delivered.status.runnable(),
7948            "the loop must not pick this task up again"
7949        );
7950        assert_eq!(
7951            delivered.last_error.as_deref(),
7952            Some("no check status"),
7953            "the operator needs to be told what the gate was waiting for"
7954        );
7955
7956        // The same status without a pull request is a plain failure, and with
7957        // attempts left it is retried.
7958        let mut empty_handed = task();
7959        empty_handed.start("20260903-080619-01c2".to_owned());
7960        settle(
7961            &mut empty_handed,
7962            Verdict {
7963                status: RunStatus::Blocked,
7964                left_pr: false,
7965                parked: false,
7966                quota_hit: false,
7967                no_viable_candidates: false,
7968            },
7969            "findings open",
7970            4,
7971        );
7972        assert_eq!(empty_handed.status, TaskStatus::Failed);
7973        assert!(empty_handed.status.runnable());
7974    }
7975
7976    #[test]
7977    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7978        // Every candidate agreed, with evidence, that nothing belonged in the
7979        // worktree. That is not a confirmed success to close automatically -
7980        // a human still has to check the claim - and it is not an ordinary
7981        // failure either, so this settles exactly like a pull request nobody
7982        // merged yet: `Held`, same as `Blocked` with a PR.
7983        let mut noop = task();
7984        noop.start("20260912-131304-391f".to_owned());
7985        settle(
7986            &mut noop,
7987            Verdict {
7988                status: RunStatus::VerifiedNoop,
7989                left_pr: false,
7990                parked: false,
7991                quota_hit: false,
7992                no_viable_candidates: true,
7993            },
7994            "candidate A: already fixed by b32cfc4, on main",
7995            4,
7996        );
7997        assert_eq!(
7998            noop.status,
7999            TaskStatus::Held,
8000            "an unverified claim is a request for a human, not a failure"
8001        );
8002        assert!(
8003            !noop.status.runnable(),
8004            "the loop must not requeue this on the same unverified claim"
8005        );
8006        // `Task::release` resets attempts to zero the moment a human looks at
8007        // the evidence and lets it run again, so it does not matter here
8008        // whether the one attempt already spent stays spent - what matters is
8009        // that nothing retries this task unattended in the meantime.
8010        assert_eq!(noop.attempts, 1);
8011    }
8012
8013    #[test]
8014    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8015        // Parking is the operator asking for the process back - to replace the
8016        // binary, most of all. The run's work is intact on disk, so this is
8017        // not a failed attempt, and charging for it would mean a few upgrades
8018        // could exhaust a budget meant for agents that misbehaved.
8019        let mut parked = task();
8020        parked.start("20260903-183634-2d98".to_owned());
8021        settle(
8022            &mut parked,
8023            Verdict {
8024                status: RunStatus::Implementing,
8025                left_pr: false,
8026                quota_hit: false,
8027                parked: true,
8028                no_viable_candidates: false,
8029            },
8030            "parked after `implementing`",
8031            2,
8032        );
8033        assert_eq!(parked.attempts, 0, "a park is refunded");
8034        assert!(
8035            parked.status.runnable(),
8036            "and the task stays in line so the next loop resumes its run"
8037        );
8038        assert_eq!(parked.status, TaskStatus::Parked);
8039        assert_eq!(
8040            parked.park_reason.as_deref(),
8041            Some("parked after `implementing`"),
8042            "the card says where it stopped"
8043        );
8044        assert_eq!(parked.last_error, None, "nothing failed");
8045
8046        // Without the park flag the same non-terminal status is what it always
8047        // was: `execute` returning mid-flight, which is a bug and spends an
8048        // attempt so a task cannot loop on it forever.
8049        let mut broken = task();
8050        broken.start("20260903-183634-2d98".to_owned());
8051        settle(
8052            &mut broken,
8053            Verdict {
8054                status: RunStatus::Implementing,
8055                left_pr: false,
8056                quota_hit: false,
8057                parked: false,
8058                no_viable_candidates: false,
8059            },
8060            "returned mid-flight",
8061            2,
8062        );
8063        assert_eq!(broken.attempts, 1);
8064    }
8065
8066    #[test]
8067    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8068        // Run e633: quorum lost because two judges answered with the wrong
8069        // JSON shape, `quota: []`. Refunding that takes the bound off the
8070        // retry loop, and each retry pays for a fresh hour-long implement
8071        // wave before it can fail the same way.
8072        let mut flaky = task();
8073        flaky.start("20260903-123023-e633".to_owned());
8074        settle(
8075            &mut flaky,
8076            Verdict {
8077                status: RunStatus::Stalled,
8078                left_pr: false,
8079                parked: false,
8080                quota_hit: false,
8081                no_viable_candidates: false,
8082            },
8083            "verdict rests on 1 of 3 judges",
8084            2,
8085        );
8086        assert_eq!(
8087            flaky.attempts, 1,
8088            "flakiness spends an attempt, so `max_attempts` still bounds it"
8089        );
8090        assert!(flaky.status.runnable(), "and it is still worth retrying");
8091
8092        // The same status, lost to a rate limit, is the machine's fault.
8093        let mut limited = task();
8094        limited.start("20260903-123023-e633".to_owned());
8095        settle(
8096            &mut limited,
8097            Verdict {
8098                status: RunStatus::Stalled,
8099                left_pr: false,
8100                parked: false,
8101                quota_hit: true,
8102                no_viable_candidates: false,
8103            },
8104            "judge-2, judge-3 out of quota",
8105            2,
8106        );
8107        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8108        assert!(limited.status.runnable());
8109
8110        // And the bound really binds: a task that keeps stalling on flakiness
8111        // reaches a human instead of running the roster forever.
8112        let mut worn = task();
8113        for _ in 0..2 {
8114            worn.release();
8115        }
8116        worn.start("20260903-123023-e633".to_owned());
8117        worn.attempts = 2;
8118        settle(
8119            &mut worn,
8120            Verdict {
8121                status: RunStatus::Stalled,
8122                left_pr: false,
8123                parked: false,
8124                quota_hit: false,
8125                no_viable_candidates: false,
8126            },
8127            "no quorum again",
8128            2,
8129        );
8130        assert_eq!(worn.status, TaskStatus::Held);
8131        assert!(!worn.status.runnable());
8132    }
8133
8134    #[test]
8135    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8136        // The implement wave loses every seat to the same rate limit and
8137        // `after_implement` bails with nothing viable, which surfaces as
8138        // `Failed` rather than `Stalled`. That is the same machine fact the
8139        // `Stalled`-quota row already refunds, and must be refunded the same
8140        // way, or a quota outage quietly holds every task it touches instead
8141        // of leaving them in line for the reset.
8142        let mut wiped_out = task();
8143        wiped_out.start("20260907-025000-a1b2".to_owned());
8144        settle(
8145            &mut wiped_out,
8146            Verdict {
8147                status: RunStatus::Failed,
8148                left_pr: false,
8149                parked: false,
8150                quota_hit: true,
8151                no_viable_candidates: true,
8152            },
8153            "no candidate produced a change; nothing to judge",
8154            2,
8155        );
8156        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8157        assert!(
8158            wiped_out.status.runnable(),
8159            "a machine problem must leave the task in line"
8160        );
8161
8162        // This is the exemption that must stay narrow: a candidate that did
8163        // produce a change, and then failed for some other reason, still
8164        // spends the attempt even though a seat elsewhere hit its quota.
8165        // Otherwise every ordinary failure that happens to share a run with
8166        // an unrelated rate limit would be refunded for free.
8167        let mut partial_progress = task();
8168        partial_progress.start("20260907-025500-c3d4".to_owned());
8169        settle(
8170            &mut partial_progress,
8171            Verdict {
8172                status: RunStatus::Failed,
8173                left_pr: false,
8174                parked: false,
8175                quota_hit: true,
8176                no_viable_candidates: false,
8177            },
8178            "gate failed on the winning candidate",
8179            2,
8180        );
8181        assert_eq!(
8182            partial_progress.attempts, 1,
8183            "a candidate that actually produced a change spends the attempt \
8184             even though some other seat hit its quota"
8185        );
8186        assert!(partial_progress.status.runnable());
8187    }
8188
8189    #[test]
8190    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8191        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8192        // disk, and that construction must reach the same conclusion as the
8193        // one `attempt` builds from a live run, or a crash at exactly the
8194        // wrong moment gives a recovered task a different policy than one a
8195        // daemon finished settling itself.
8196        let mut t = task();
8197        t.start("20260907-025000-a1b2".to_owned());
8198        let mut state = run_state(RunStatus::Failed);
8199        state.quota.push(QuotaLoss {
8200            cause: crate::agent::QuotaCause::UsageLimit,
8201            agent: String::new(),
8202            seat: "cand-a".to_owned(),
8203            node: "implement".to_owned(),
8204            at: Timestamp::now(),
8205            reset: None,
8206        });
8207        assert!(
8208            state.viable().is_empty(),
8209            "no candidate was added, so nothing is viable"
8210        );
8211        reclaim(&mut t, Some(state), 2, "en");
8212        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8213        assert!(t.status.runnable());
8214    }
8215
8216    #[test]
8217    fn a_held_task_is_never_offered_to_the_loop() {
8218        let dir = tempfile::tempdir().unwrap();
8219        let queue = Queue::at(dir.path().to_path_buf());
8220        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8221            let mut t = task();
8222            t.id = format!("2026090{n}-000000-000{n}");
8223            t.priority = priority;
8224            queue.put(&mut t).unwrap();
8225        }
8226        let mut held = task();
8227        held.id = "20260909-000000-9999".to_owned();
8228        held.priority = 99;
8229        held.hold_machine(None);
8230        queue.put(&mut held).unwrap();
8231
8232        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8233        assert_eq!(order.len(), 3);
8234        assert!(!order.contains(&held.id));
8235        assert_eq!(
8236            order.first().cloned(),
8237            queue.next_runnable().map(|t| t.id),
8238            "the loop's first candidate is exactly what the queue offers"
8239        );
8240        assert_eq!(
8241            order,
8242            vec![
8243                "20260902-000000-0002".to_owned(),
8244                "20260903-000000-0003".to_owned(),
8245                "20260901-000000-0001".to_owned(),
8246            ],
8247            "priority first, then oldest, so nothing starves"
8248        );
8249    }
8250
8251    #[test]
8252    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8253        let dir = tempfile::tempdir().unwrap();
8254        let queue = Queue::at(dir.path().to_path_buf());
8255        let mut old = task();
8256        old.id = "20260101-000000-old0".to_owned();
8257        queue.put(&mut old).unwrap();
8258        let mut fresh = task();
8259        fresh.id = "20260101-000000-new0".to_owned();
8260        queue.put(&mut fresh).unwrap();
8261
8262        // No parseable pid at all, so age is the only signal there is to
8263        // check - unlike a real `Queue::claim`, which always names a real,
8264        // and therefore alive, pid this test cannot fake as dead.
8265        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8266        std::thread::sleep(Duration::from_millis(60));
8267        let live = queue.claim(&fresh.id).unwrap();
8268
8269        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8270        assert_eq!(swept, vec![old.id.clone()]);
8271        assert!(
8272            queue.claim(&old.id).is_ok(),
8273            "an unparseable lock older than the threshold is swept"
8274        );
8275        assert!(
8276            queue.claim(&fresh.id).is_err(),
8277            "a live pid protects its lock regardless of age"
8278        );
8279        drop(live);
8280    }
8281
8282    #[test]
8283    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8284        // A live worker's claim remains authoritative even beyond the sweep's
8285        // age limit. Sweeping it would permit a second competing attempt.
8286        let dir = tempfile::tempdir().unwrap();
8287        let queue = Queue::at(dir.path().to_path_buf());
8288        let mut t = task();
8289        t.id = "20260101-000000-live".to_owned();
8290        queue.put(&mut t).unwrap();
8291
8292        let claim = queue.claim(&t.id).unwrap();
8293        std::thread::sleep(Duration::from_millis(60));
8294
8295        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8296        assert!(
8297            swept.is_empty(),
8298            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8299        );
8300        assert!(
8301            queue.claim(&t.id).is_err(),
8302            "the lock still protects its task"
8303        );
8304        drop(claim);
8305    }
8306
8307    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8308    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8309    fn injected_dead_pid() -> u32 {
8310        std::process::id().checked_add(1).unwrap_or(1)
8311    }
8312
8313    #[test]
8314    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8315        let dir = tempfile::tempdir().unwrap();
8316        let queue = Queue::at(dir.path().to_path_buf());
8317        let mut t = task();
8318        t.id = "20260101-000000-dead".to_owned();
8319        queue.put(&mut t).unwrap();
8320        let dead_pid = injected_dead_pid();
8321
8322        // Written directly rather than through `Queue::claim`, which would
8323        // stamp this test process's own very much alive pid and defeat the
8324        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8325        // like moments after it died, not six hours later.
8326        std::fs::write(
8327            dir.path().join(format!("{}.lock", t.id)),
8328            dead_pid.to_string(),
8329        )
8330        .unwrap();
8331
8332        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8333            pid != dead_pid
8334        });
8335        assert_eq!(
8336            swept,
8337            vec![t.id.clone()],
8338            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8339        );
8340        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8341    }
8342
8343    #[test]
8344    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8345        let dir = tempfile::tempdir().unwrap();
8346        let queue = Queue::at(dir.path().to_path_buf());
8347        let mut t = task();
8348        t.id = "20260101-000000-late".to_owned();
8349        queue.put(&mut t).unwrap();
8350        let dead_pid = injected_dead_pid();
8351
8352        // Tick one, standing in for the sweep `poll` already runs at
8353        // startup: nothing to find yet.
8354        assert!(
8355            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8356            "nothing has claimed the task yet"
8357        );
8358
8359        // A second daemon claims the task and dies before it ever writes
8360        // `running`, well after this loop's own startup sweep already ran.
8361        std::fs::write(
8362            dir.path().join(format!("{}.lock", t.id)),
8363            dead_pid.to_string(),
8364        )
8365        .unwrap();
8366
8367        // Tick two, standing in for a poll long into this daemon's uptime:
8368        // the same function, called again, notices what only just appeared -
8369        // proving the sweep is not a one-shot startup check.
8370        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8371            pid != dead_pid
8372        });
8373        assert_eq!(swept, vec![t.id.clone()]);
8374    }
8375
8376    #[test]
8377    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8378        // `reclaim_orphaned_running` looks up the task's last run, which
8379        // touches `run::home()`; the first call anywhere in this binary wins,
8380        // so this is a no-op if another test already pinned one, and either
8381        // way the run id below is never written under it.
8382        crate::run::pin_test_home();
8383        let dir = tempfile::tempdir().unwrap();
8384        let queue = Queue::at(dir.path().to_path_buf());
8385        let mut t = task();
8386        t.id = "20260101-000000-crsh".to_owned();
8387        t.status = TaskStatus::Running;
8388        t.attempts = 1;
8389        // No `run.json` behind this id: standing in for a run this test does
8390        // not need to make readable, since the point is the lock, not the
8391        // recovery table `reclaim` already has its own tests for.
8392        t.runs.push("20260904-000000-4043".to_owned());
8393        queue.put(&mut t).unwrap();
8394        let dead_pid = injected_dead_pid();
8395
8396        // The crashed daemon's own claim, naming a pid nothing on the
8397        // machine holds anymore.
8398        std::fs::write(
8399            dir.path().join(format!("{}.lock", t.id)),
8400            dead_pid.to_string(),
8401        )
8402        .unwrap();
8403
8404        // Before the lock is swept the task looks claimed, and
8405        // `reclaim_orphaned_running` must leave it alone - this is exactly
8406        // the bug: a `running` task stranded behind a dead daemon's lock,
8407        // invisible to the claim-as-proof check because the lock outlived
8408        // the process that wrote it.
8409        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8410        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8411
8412        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8413            pid != dead_pid
8414        });
8415        assert_eq!(swept, vec![t.id.clone()]);
8416
8417        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8418        assert_eq!(reclaimed, vec![t.id.clone()]);
8419        let after = queue.get(&t.id).unwrap();
8420        assert_eq!(
8421            after.status,
8422            TaskStatus::Held,
8423            "no run.json to recover from, so a human is asked"
8424        );
8425        assert_eq!(
8426            after.runs,
8427            vec!["20260904-000000-4043".to_owned()],
8428            "the crashed run's id is kept as evidence, not discarded"
8429        );
8430    }
8431
8432    #[test]
8433    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8434        let dir = tempfile::tempdir().unwrap();
8435        let queue = Queue::at(dir.path().to_path_buf());
8436        let mut t = task();
8437        t.id = "20260101-000000-unknown".to_owned();
8438        queue.put(&mut t).unwrap();
8439        let dead_pid = injected_dead_pid();
8440        std::fs::write(
8441            dir.path().join(format!("{}.lock", t.id)),
8442            dead_pid.to_string(),
8443        )
8444        .unwrap();
8445
8446        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8447        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8448        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8449    }
8450
8451    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8452        let mut s = run_state(status);
8453        s.config.graph.language = language.to_owned();
8454        s
8455    }
8456
8457    fn unstarted_verdict(status: RunStatus) -> Verdict {
8458        Verdict {
8459            status,
8460            left_pr: false,
8461            quota_hit: false,
8462            parked: false,
8463            no_viable_candidates: false,
8464        }
8465    }
8466
8467    #[test]
8468    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8469        let mut t = task();
8470        t.attempts = 1;
8471        settle_in(
8472            &mut t,
8473            unstarted_verdict(RunStatus::AlreadyInBase),
8474            "already in main",
8475            1,
8476            phrases("en"),
8477        );
8478        assert_eq!(t.status, TaskStatus::Done);
8479        assert_eq!(t.attempts, 0);
8480    }
8481
8482    #[test]
8483    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8484        let reason = |language: &str| {
8485            let mut t = task();
8486            settle_in(
8487                &mut t,
8488                unstarted_verdict(RunStatus::Judging),
8489                "boom",
8490                1,
8491                phrases(language),
8492            );
8493            t.last_error.or(t.hold_reason).unwrap_or_default()
8494        };
8495        assert!(
8496            reason("en").starts_with("the graph stopped at `"),
8497            "{}",
8498            reason("en")
8499        );
8500        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8501        assert!(reason("日本語").contains("boom"));
8502        assert_eq!(reason("fr"), reason("en"));
8503    }
8504
8505    #[test]
8506    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8507        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8508        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8509        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8510        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8511        assert!(ja.contains("[run "), "{ja}");
8512        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8513        assert!(ended.starts_with("run 終了: "), "{ended}");
8514        let mut de = run_state_in(RunStatus::Failed, "de");
8515        let mut en = run_state_in(RunStatus::Failed, "en");
8516        de.id = "same".to_owned();
8517        en.id = "same".to_owned();
8518        assert_eq!(describe(&de), describe(&en));
8519    }
8520
8521    #[test]
8522    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8523        use crate::handover::Refused;
8524        let cases = [
8525            Refused::Foreign {
8526                branch: "b".into(),
8527                path: "/w/x".into(),
8528                why: "made by hand".into(),
8529            },
8530            Refused::Unsafe {
8531                branch: "b".into(),
8532                path: "/w/x".into(),
8533                why: "its worktree has uncommitted changes (a.rs)".into(),
8534            },
8535            Refused::ReleaseFailed {
8536                branch: "b".into(),
8537                path: "/w/x".into(),
8538                run: "ab12".into(),
8539            },
8540        ];
8541        for r in &cases {
8542            let en = (phrases("en").handover_refused)(r);
8543            assert_eq!(en, r.to_string());
8544            let ja = (phrases("ja").handover_refused)(r);
8545            assert!(
8546                !ja.contains("is checked out") && !ja.contains("try again"),
8547                "{ja}"
8548            );
8549            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8550            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8551                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8552            }
8553        }
8554        assert!(phrases("en").handover_hint.contains("release the task"));
8555        assert!(phrases("ja").handover_hint.contains("解放"));
8556    }
8557
8558    #[test]
8559    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8560        let build = |lang: &str| {
8561            let mut s = run_state_in(RunStatus::Blocked, lang);
8562            s.id = "same".to_owned();
8563            s.config.graph.review_rounds = 3;
8564            let mut r = review_round(3);
8565            r.expected = 3;
8566            r.answered = 1;
8567            s.reviews.push(r);
8568            s.event(
8569                "review",
8570                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8571            );
8572            s
8573        };
8574        let en = describe(&build("en"));
8575        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8576        let ja = describe(&build("ja"));
8577        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8578        assert!(!ja.contains("never answered"), "{ja}");
8579        assert!(ja.contains("[run "), "{ja}");
8580
8581        // An incomplete panel whose verification failed is a different stop:
8582        // the real event must survive in ja too.
8583        let mut failed = build("ja");
8584        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8585            command: "cargo test".to_owned(),
8586            code: Some(1),
8587            output_tail: String::new(),
8588            duration_ms: 0,
8589            resource_blocked: false,
8590        });
8591        failed.event("review", "stopped; e2e failed: cargo test");
8592        let ja = describe(&failed);
8593        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8594        assert!(!ja.contains("席のレビュアー"), "{ja}");
8595    }
8596
8597    #[test]
8598    fn refusals_and_recovery_prose_follow_the_language() {
8599        let home = crate::run::test_home();
8600        let t = held_task_with("r1");
8601        let q = action_question(
8602            "r1",
8603            ask::ChoiceAction::Resume {
8604                run: "r1".to_owned(),
8605            },
8606        );
8607        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
8608            ActionDecision::Refuse(s) => s,
8609            other => panic!("{other:?}"),
8610        };
8611        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8612        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8613        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8614
8615        let mut held = task();
8616        reclaim(&mut held, None, 2, "ja");
8617        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8618        let mut held = task();
8619        reclaim(&mut held, None, 2, "xx");
8620        assert!(held.hold_reason.unwrap().contains("held for a human"));
8621    }
8622
8623    fn run_state(status: RunStatus) -> RunState {
8624        let mut state = RunState::new(
8625            PathBuf::from("/repo"),
8626            "main".to_owned(),
8627            "abc1234def".to_owned(),
8628            "add retries".to_owned(),
8629            Config::default(),
8630        );
8631        state.status = status;
8632        state
8633    }
8634
8635    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8636        Candidate {
8637            index: 0,
8638            label,
8639            agent: "claude".to_owned(),
8640            branch: format!("magi/x/{label}"),
8641            worktree: PathBuf::from("/repo"),
8642            summary: summary.to_owned(),
8643            stat: String::new(),
8644            files: 0,
8645            commits: usize::from(!empty),
8646            empty,
8647            failed: failed.map(str::to_owned),
8648            verified_noop: None,
8649            duration_ms: 0,
8650            folded: false,
8651        }
8652    }
8653
8654    #[test]
8655    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8656        let mut state = run_state(RunStatus::Blocked);
8657        state.gate = vec![
8658            CommandOutcome {
8659                command: "cargo make check".to_owned(),
8660                code: Some(0),
8661                output_tail: "ok".to_owned(),
8662                duration_ms: 0,
8663                resource_blocked: false,
8664            },
8665            CommandOutcome {
8666                command: "cargo test".to_owned(),
8667                code: Some(101),
8668                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8669                duration_ms: 0,
8670                resource_blocked: false,
8671            },
8672        ];
8673        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8674        assert!(d.contains("cargo test"), "{d}");
8675        assert!(
8676            !d.contains("cargo make check"),
8677            "a passing check is not a diagnostic: {d}"
8678        );
8679        assert!(d.contains("assertion failed"), "{d}");
8680    }
8681
8682    #[test]
8683    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8684        let mut state = run_state(RunStatus::Blocked);
8685        state.event(
8686            "land",
8687            "stopped: the fixer produced no commit while 2 check(s) were failing \
8688             (build, lint); stopping instead of looping on an unchanged tree",
8689        );
8690        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8691        assert!(d.contains("build"), "{d}");
8692        assert!(d.contains("lint"), "{d}");
8693        assert!(d.contains("fixer produced no commit"), "{d}");
8694    }
8695
8696    #[test]
8697    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8698        // `describe`'s output becomes `Task::last_error` verbatim, and the
8699        // phone renders that in the same alarm-styled box an ordinary
8700        // failure gets. A bare `verified_noop` there would read exactly like
8701        // the failure this status exists to be told apart from.
8702        let state = run_state(RunStatus::VerifiedNoop);
8703        let d = describe(&state);
8704        assert!(
8705            d.contains("agent-verified no-op"),
8706            "expected the display label, not the wire spelling: {d}"
8707        );
8708        assert!(!d.contains("verified_noop"), "{d}");
8709    }
8710
8711    #[test]
8712    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8713        let mut state = run_state(RunStatus::Failed);
8714        state.gate.push(crate::run::CommandOutcome {
8715            command: "cargo test".into(),
8716            code: Some(101),
8717            output_tail: format!(
8718                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8719                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8720            ),
8721            duration_ms: 1,
8722            resource_blocked: false,
8723        });
8724        let d = diagnostic(&state).unwrap();
8725        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8726        assert!(d.contains("assertion failed: widget missing"));
8727        assert!(d.contains("widget log"));
8728    }
8729
8730    #[test]
8731    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8732        // The whole point of the feature: a run held as "no candidate produced
8733        // a change" can mean the implementer actually finished the task and
8734        // only left a clean local tree behind - see AGENTS.md on this exact
8735        // failure mode. The diagnostic has to carry what the agent actually
8736        // said, not just the fact that nothing was there to judge.
8737        let mut state = run_state(RunStatus::Failed);
8738        state.candidates = vec![candidate(
8739            'A',
8740            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8741            true,
8742            None,
8743        )];
8744        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8745        assert!(d.contains("candidate A"), "{d}");
8746        assert!(d.contains("tagged v1.2.3"), "{d}");
8747    }
8748
8749    #[test]
8750    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8751        let mut state = run_state(RunStatus::Failed);
8752        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8753        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8754        assert!(d.contains("candidate A"), "{d}");
8755        assert!(d.contains("agent timed out"), "{d}");
8756    }
8757
8758    #[test]
8759    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8760        // A viable candidate existed, the gate never ran, and nothing land
8761        // said matches - `Task::last_error` is left to explain this one alone.
8762        let mut state = run_state(RunStatus::Failed);
8763        state.candidates = vec![candidate('A', "did the work", false, None)];
8764        assert!(diagnostic(&state).is_none());
8765    }
8766
8767    #[test]
8768    fn diagnostic_is_bounded_however_much_a_run_printed() {
8769        let mut state = run_state(RunStatus::Blocked);
8770        state.gate = vec![
8771            CommandOutcome {
8772                command: "cargo test".to_owned(),
8773                code: Some(101),
8774                output_tail: "x".repeat(50_000),
8775                duration_ms: 0,
8776                resource_blocked: false,
8777            },
8778            CommandOutcome {
8779                command: "cargo clippy".to_owned(),
8780                code: Some(1),
8781                output_tail: "y".repeat(50_000),
8782                duration_ms: 0,
8783                resource_blocked: false,
8784            },
8785        ];
8786        state.candidates = vec![
8787            candidate('A', &"z".repeat(50_000), true, None),
8788            candidate('B', &"w".repeat(50_000), true, None),
8789        ];
8790        let d = diagnostic(&state).expect("plenty here to diagnose");
8791        assert!(
8792            d.len() <= DIAGNOSTIC_MAX,
8793            "diagnostic grew to {} bytes, unbounded",
8794            d.len()
8795        );
8796    }
8797
8798    #[test]
8799    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8800        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8801            let mut t = task();
8802            let mut state = run_state(status);
8803            t.pr_recovery = Some(crate::pr_recovery::Selection {
8804                url: "url".into(),
8805                branch: format!("magi/task-{}", t.id),
8806                head: "a".repeat(40),
8807                source_head: None,
8808                source_run: None,
8809                source_proof: None,
8810                disposition: Some(crate::pr_recovery::Disposition::Land),
8811                instruction: t.instruction.clone(),
8812                approved_at: Timestamp::now(),
8813            });
8814            state.pr_recovery = t.pr_recovery.clone();
8815            t.start(state.id.clone());
8816            settle_and_diagnose(
8817                &mut t,
8818                Verdict {
8819                    status,
8820                    left_pr: false,
8821                    quota_hit: false,
8822                    parked: false,
8823                    no_viable_candidates: false,
8824                },
8825                "delivery stopped",
8826                5,
8827                &state,
8828            );
8829            assert_eq!(t.status, TaskStatus::Held);
8830            let reason = t.hold_reason.as_deref().unwrap();
8831            if status == RunStatus::Ready {
8832                assert!(reason.contains("Selected PR delivery is incomplete"));
8833                assert!(t.recovery_budget.is_none());
8834            } else {
8835                assert!(reason.contains("Selected recovery stopped"));
8836                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8837            }
8838            assert!(t.pr_recovery.is_some());
8839        }
8840    }
8841
8842    #[test]
8843    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8844        let mut state = run_state(RunStatus::Voting);
8845        state.base_sync = Some(crate::run::BaseSync {
8846            tip: "base-tip".into(),
8847            behind: 3,
8848            attempts: 4,
8849            conflict: Some("base stopped".into()),
8850            already_in: None,
8851        });
8852        state.record_base_sync_stop("candidate-head");
8853        let mut t = task();
8854        t.start(state.id.clone());
8855        let verdict = Verdict {
8856            status: RunStatus::Blocked,
8857            left_pr: false,
8858            quota_hit: false,
8859            parked: false,
8860            no_viable_candidates: false,
8861        };
8862        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8863        assert_eq!(
8864            t.status,
8865            TaskStatus::Held,
8866            "unspent task attempts cannot start another competition"
8867        );
8868        let at = t.held_at;
8869        let cause = t.hold_notice_cause.clone();
8870        state.begin_pass();
8871        t.release_operator("test-resume", None);
8872        t.start(state.id.clone());
8873        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8874        assert_eq!(t.status, TaskStatus::Held);
8875        assert_eq!(t.held_at, at);
8876        assert_eq!(t.hold_notice_cause, cause);
8877    }
8878
8879    #[test]
8880    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8881        let mut state = run_state(RunStatus::Blocked);
8882        state.gate = vec![CommandOutcome {
8883            command: "cargo test".to_owned(),
8884            code: Some(101),
8885            output_tail: "assertion failed".to_owned(),
8886            duration_ms: 0,
8887            resource_blocked: false,
8888        }];
8889        let verdict = Verdict {
8890            status: RunStatus::Blocked,
8891            left_pr: false,
8892            quota_hit: false,
8893            parked: false,
8894            no_viable_candidates: false,
8895        };
8896
8897        // Attempt one of two still has a retry coming: no diagnostic yet, the
8898        // task is going to run again and this run's evidence would go stale.
8899        let mut t = task();
8900        t.start("run-1".to_owned());
8901        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8902        assert_eq!(t.status, TaskStatus::Failed);
8903        assert!(t.diagnostic.is_none());
8904
8905        // Attempt two exhausts the budget: now it is held, and the
8906        // diagnostic is what `magi task show` has to say more than one line.
8907        t.start("run-2".to_owned());
8908        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8909        assert_eq!(t.status, TaskStatus::Held);
8910        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8911        assert!(d.contains("cargo test"), "{d}");
8912    }
8913
8914    #[test]
8915    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8916        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8917        // `magi ask` question settled Held with `hold_reason: null`, so the
8918        // notification said nothing actionable. `note_open_question` should
8919        // append the question id to whatever `handed_off` already wrote.
8920        crate::run::pin_test_home();
8921        let home = crate::run::home();
8922        let state = run_state(RunStatus::VerifiedNoop);
8923        let mut q = ask::Question::new(
8924            state.id.clone(),
8925            "implement".to_owned(),
8926            "impl-A".to_owned(),
8927            "is this really a no-op?".to_owned(),
8928            String::new(),
8929            Vec::new(),
8930        );
8931        Questions::at(home.join("questions")).put(&mut q).unwrap();
8932
8933        let verdict = Verdict {
8934            status: RunStatus::VerifiedNoop,
8935            left_pr: false,
8936            quota_hit: false,
8937            parked: false,
8938            no_viable_candidates: false,
8939        };
8940        let mut t = task();
8941        t.start(state.id.clone());
8942        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8943
8944        assert_eq!(t.status, TaskStatus::Held);
8945        let reason = t.hold_reason.expect("a held task must record why");
8946        assert!(
8947            reason.starts_with("run ended agent-verified no-op"),
8948            "the original settle reason must survive unchanged: {reason}"
8949        );
8950        assert!(
8951            reason.contains(q.short()),
8952            "the open question's id must be named so the notice is actionable: {reason}"
8953        );
8954    }
8955
8956    #[test]
8957    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8958        crate::run::pin_test_home();
8959        let state = run_state(RunStatus::VerifiedNoop);
8960
8961        let verdict = Verdict {
8962            status: RunStatus::VerifiedNoop,
8963            left_pr: false,
8964            quota_hit: false,
8965            parked: false,
8966            no_viable_candidates: false,
8967        };
8968        let mut t = task();
8969        t.start(state.id.clone());
8970        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8971
8972        assert_eq!(t.status, TaskStatus::Held);
8973        assert_eq!(
8974            t.hold_reason.as_deref(),
8975            Some("run ended agent-verified no-op"),
8976            "nothing to append when the question was already answered or never asked"
8977        );
8978    }
8979
8980    #[test]
8981    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8982        crate::run::pin_test_home();
8983        let mut first = run_state(RunStatus::Blocked);
8984        first.id = "20260101-000000-sup1".to_owned();
8985        first.save().unwrap();
8986        let mut second = run_state(RunStatus::Merged);
8987        second.id = "20260101-000000-sup2".to_owned();
8988        second.save().unwrap();
8989
8990        let mut t = task();
8991        t.runs = vec![first.id.clone(), second.id.clone()];
8992        t.status = TaskStatus::Done;
8993
8994        supersede_prior_runs(&t, &crate::run::home());
8995
8996        assert_eq!(
8997            RunState::load(&first.id).unwrap().status,
8998            RunStatus::Superseded,
8999            "the first attempt's Blocked no longer needs anyone's attention"
9000        );
9001        assert_eq!(
9002            RunState::load(&second.id).unwrap().status,
9003            RunStatus::Merged,
9004            "the run that actually succeeded is left exactly as it was"
9005        );
9006    }
9007
9008    #[test]
9009    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9010        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9011        // --resume` invoked by hand outside the daemon never touches
9012        // `daemon.json` at all, so it would look identical to a genuinely
9013        // idle run without also consulting `RunState::liveness`, which reads
9014        // this run's own recorded `driver_pid` instead.
9015        crate::run::pin_test_home();
9016        let mut first = run_state(RunStatus::Blocked);
9017        first.id = "20260101-000000-sup9".to_owned();
9018        // This test process's own pid: guaranteed alive without needing a
9019        // real second process or daemon.
9020        first.driver_pid = Some(std::process::id());
9021        first.driver_started_at = Some(
9022            crate::proc::process_started_at(std::process::id())
9023                .expect("this test process's own start time must be queryable"),
9024        );
9025        first.save().unwrap();
9026        let mut second = run_state(RunStatus::Merged);
9027        second.id = "20260101-000000-supa".to_owned();
9028        second.save().unwrap();
9029
9030        let mut t = task();
9031        t.runs = vec![first.id.clone(), second.id.clone()];
9032        t.status = TaskStatus::Done;
9033
9034        supersede_prior_runs(&t, &crate::run::home());
9035
9036        assert_eq!(
9037            RunState::load(&first.id).unwrap().status,
9038            RunStatus::Blocked,
9039            "a live driver_pid means something is still actually working this run, \
9040             even though no daemon claims it - rewriting under it would just be \
9041             undone the next time that process saves"
9042        );
9043    }
9044
9045    #[test]
9046    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9047        // The first resweep must skip a still-live attempt exactly like
9048        // `supersede_prior_runs` itself does; a later resweep, once that
9049        // process is no longer actually driving it, is what closes the gap
9050        // `supersede_prior_runs` alone leaves - a task only ever reaches
9051        // `Done` once, so nothing else would ever look at this run again.
9052        let dir = tempfile::tempdir().unwrap();
9053        let home = dir.path().to_path_buf();
9054        let queue = Queue::at(dir.path().join("queue"));
9055
9056        let mut first = run_state(RunStatus::Blocked);
9057        first.id = "20260101-000000-supd".to_owned();
9058        first.driver_pid = Some(std::process::id());
9059        first.driver_started_at = Some(
9060            crate::proc::process_started_at(std::process::id())
9061                .expect("this test process's own start time must be queryable"),
9062        );
9063        first.save_under(&home).unwrap();
9064        let mut second = run_state(RunStatus::Merged);
9065        second.id = "20260101-000000-supe".to_owned();
9066        second.save_under(&home).unwrap();
9067
9068        let mut t = task();
9069        t.runs = vec![first.id.clone(), second.id.clone()];
9070        t.status = TaskStatus::Done;
9071        queue.put(&mut t).unwrap();
9072
9073        resweep_superseded_attempts(&queue, &home);
9074        assert_eq!(
9075            RunState::load_under(&first.id, &home).unwrap().status,
9076            RunStatus::Blocked,
9077            "still live on the first pass, so still untouched"
9078        );
9079
9080        // Stand in for the manual process no longer being the one driving
9081        // this run: same pid (this test process really is still alive), but
9082        // an identity marker that no longer matches it - see
9083        // `RunState::liveness`'s own doc for why a mismatched
9084        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9085        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9086        stale.driver_started_at = Some("1".to_owned());
9087        stale.save_under(&home).unwrap();
9088
9089        resweep_superseded_attempts(&queue, &home);
9090        assert_eq!(
9091            RunState::load_under(&first.id, &home).unwrap().status,
9092            RunStatus::Superseded,
9093            "the second pass catches up what the first one correctly skipped"
9094        );
9095    }
9096
9097    #[test]
9098    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9099        crate::run::pin_test_home();
9100        let mut first = run_state(RunStatus::Blocked);
9101        first.id = "20260101-000000-sup3".to_owned();
9102        first.save().unwrap();
9103        let mut second = run_state(RunStatus::Blocked);
9104        second.id = "20260101-000000-sup4".to_owned();
9105        second.save().unwrap();
9106
9107        let mut t = task();
9108        t.runs = vec![first.id.clone(), second.id.clone()];
9109        // Still retrying: nothing about this task's story is settled yet, so
9110        // neither Blocked run may be relabelled, even though a later attempt
9111        // already exists.
9112        t.status = TaskStatus::Failed;
9113
9114        supersede_prior_runs(&t, &crate::run::home());
9115
9116        assert_eq!(
9117            RunState::load(&first.id).unwrap().status,
9118            RunStatus::Blocked
9119        );
9120        assert_eq!(
9121            RunState::load(&second.id).unwrap().status,
9122            RunStatus::Blocked
9123        );
9124    }
9125
9126    #[test]
9127    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9128        // `magi task done` (or the API's equivalent) can close a task with no
9129        // run of its own ever having succeeded - there is nothing here that
9130        // counts as "the attempt that finished it", so nothing is rewritten.
9131        crate::run::pin_test_home();
9132        let mut first = run_state(RunStatus::Blocked);
9133        first.id = "20260101-000000-sup5".to_owned();
9134        first.save().unwrap();
9135
9136        let mut t = task();
9137        t.runs = vec![first.id.clone()];
9138        t.status = TaskStatus::Done;
9139
9140        supersede_prior_runs(&t, &crate::run::home());
9141
9142        assert_eq!(
9143            RunState::load(&first.id).unwrap().status,
9144            RunStatus::Blocked,
9145            "a single-attempt task has no earlier run to supersede"
9146        );
9147    }
9148
9149    #[test]
9150    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9151        // `magi task done` (or the web/conductor equivalents) can close a
9152        // task in any status, including one whose *last* recorded attempt is
9153        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9154        // never watched, say. `runs.last()` being `Done`-adjacent is not
9155        // proof it actually succeeded, so nothing earlier may be relabelled
9156        // on its say-so alone.
9157        crate::run::pin_test_home();
9158        let mut first = run_state(RunStatus::Blocked);
9159        first.id = "20260101-000000-supb".to_owned();
9160        first.save().unwrap();
9161        let mut second = run_state(RunStatus::Failed);
9162        second.id = "20260101-000000-supc".to_owned();
9163        second.save().unwrap();
9164
9165        let mut t = task();
9166        t.runs = vec![first.id.clone(), second.id.clone()];
9167        t.status = TaskStatus::Done;
9168
9169        supersede_prior_runs(&t, &crate::run::home());
9170
9171        assert_eq!(
9172            RunState::load(&first.id).unwrap().status,
9173            RunStatus::Blocked,
9174            "the task's last attempt never landed, so there is nothing here \
9175             actually superseding it"
9176        );
9177    }
9178
9179    #[test]
9180    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9181        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9182        // to look" - `Failed` and `VerifiedNoop` are already their own
9183        // terminal answers and must not be relabelled into a third one.
9184        crate::run::pin_test_home();
9185        let mut failed = run_state(RunStatus::Failed);
9186        failed.id = "20260101-000000-sup6".to_owned();
9187        failed.save().unwrap();
9188        let mut noop = run_state(RunStatus::VerifiedNoop);
9189        noop.id = "20260101-000000-sup7".to_owned();
9190        noop.save().unwrap();
9191        let mut winner = run_state(RunStatus::Ready);
9192        winner.id = "20260101-000000-sup8".to_owned();
9193        winner.save().unwrap();
9194
9195        let mut t = task();
9196        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9197        t.status = TaskStatus::Done;
9198
9199        supersede_prior_runs(&t, &crate::run::home());
9200
9201        assert_eq!(
9202            RunState::load(&failed.id).unwrap().status,
9203            RunStatus::Failed
9204        );
9205        assert_eq!(
9206            RunState::load(&noop.id).unwrap().status,
9207            RunStatus::VerifiedNoop
9208        );
9209    }
9210
9211    fn approval_question(run: &str) -> ask::Question {
9212        ask::Question::new(
9213            run.to_owned(),
9214            land::APPROVAL_NODE.to_owned(),
9215            "land".to_owned(),
9216            "merge?".to_owned(),
9217            String::new(),
9218            vec!["merge".to_owned(), "hold".to_owned()],
9219        )
9220    }
9221
9222    #[test]
9223    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9224        crate::run::pin_test_home();
9225        let mut state = run_state(RunStatus::Landing);
9226        state.id = "20260101-000000-fre1".to_owned();
9227        state.parked = true;
9228        state.save().unwrap();
9229        ask::Questions::open()
9230            .put(&mut approval_question(&state.id))
9231            .unwrap();
9232
9233        let mut t = task();
9234        t.runs.push(state.id.clone());
9235        assert_eq!(
9236            land_resume_state(&t),
9237            LandResume::StillWaiting,
9238            "nobody has answered and the timeout has not passed"
9239        );
9240    }
9241
9242    #[test]
9243    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9244        crate::run::pin_test_home();
9245        let mut state = run_state(RunStatus::Gating);
9246        state.id = "20260101-000000-gt01".to_owned();
9247        state.parked = true;
9248        state.config.graph.answer_timeout = 60;
9249        state.github_text = Some(crate::run::GithubTextAsk {
9250            rewrite: None,
9251            fingerprint: "f".into(),
9252            title: true,
9253            body: false,
9254            categories: vec!["title-language".into()],
9255            question: None,
9256            asks: 1,
9257            resolved: false,
9258            chosen_title: None,
9259            choice: None,
9260            publication: None,
9261        });
9262        state.save().unwrap();
9263        let store = ask::Questions::open();
9264        let mut q = ask::Question::new(
9265            state.id.clone(),
9266            crate::github_text::ASK_NODE.to_owned(),
9267            crate::github_text::ASK_SEAT.to_owned(),
9268            "s".into(),
9269            String::new(),
9270            vec!["use fallback".into()],
9271        );
9272        store.put(&mut q).unwrap();
9273        let mut t = task();
9274        t.runs.push(state.id.clone());
9275        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9276        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9277        store.put(&mut q).unwrap();
9278        assert_eq!(land_resume_state(&t), LandResume::Ready);
9279        assert!(!store.get(&q.id).unwrap().status.open());
9280        // Once decided, a parked run is an ordinary candidate again.
9281        state.github_text.as_mut().unwrap().resolved = true;
9282        state.save().unwrap();
9283        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9284    }
9285
9286    #[test]
9287    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9288        // `ask::ask_and_wait`'s own deadline used to retire a question
9289        // nobody answered; land's approval bypasses that wait (see
9290        // `land::approval_gate`), so this is now the only place
9291        // `graph.answer_timeout` is enforced for a land approval at all.
9292        crate::run::pin_test_home();
9293        let mut state = run_state(RunStatus::Landing);
9294        state.id = "20260101-000000-exp1".to_owned();
9295        state.parked = true;
9296        state.config.graph.answer_timeout = 60;
9297        state.save().unwrap();
9298
9299        let store = ask::Questions::open();
9300        let mut q = approval_question(&state.id);
9301        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9302        store.put(&mut q).unwrap();
9303
9304        let mut t = task();
9305        t.runs.push(state.id.clone());
9306        assert_eq!(
9307            land_resume_state(&t),
9308            LandResume::Ready,
9309            "an expired question must not be waited on forever"
9310        );
9311
9312        let after = store.get(&q.id).unwrap();
9313        assert!(
9314            !after.status.open(),
9315            "the question is abandoned, not silently ignored"
9316        );
9317        assert!(
9318            after.resolution().is_none(),
9319            "an abandoned question is not read as a decision"
9320        );
9321    }
9322
9323    #[test]
9324    fn reclaim_settles_a_running_task_against_its_last_run() {
9325        let mut t = task();
9326        t.start("20260904-000000-4043".to_owned());
9327        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9328        assert_eq!(
9329            t.status,
9330            TaskStatus::Done,
9331            "a run that actually finished must not stay `running` forever"
9332        );
9333    }
9334
9335    #[test]
9336    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
9337        let dir = tempfile::tempdir().unwrap();
9338        let queue = Queue::at(dir.path().join("queue"));
9339        let mut task = task();
9340        let mut run = run_state(RunStatus::Blocked);
9341        run.reserve_under(dir.path()).unwrap();
9342        run.driver_exited = true;
9343        run.save_under(dir.path()).unwrap();
9344        queue.put(&mut task).unwrap();
9345        let stale = task.clone();
9346        task.resume_override = Some(crate::queue::OperatorResume {
9347            question_id: "pending-resume".into(),
9348            at: Timestamp::now(),
9349            conductor_rehold: None,
9350            forced: true,
9351            pinned_run: Some(run.id.clone()),
9352        });
9353        task.start(run.id.clone());
9354        queue.put(&mut task).unwrap();
9355        // Discard every in-memory handoff, as a worker death before execute does.
9356        let mut recovered = queue.get(&task.id).unwrap();
9357        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
9358        reclaim(&mut recovered, Some(disk), 2, "en");
9359        queue.put(&mut recovered).unwrap();
9360        assert!(recovered.resume_override.is_none());
9361        assert_eq!(
9362            recovered.dispatched_resumes.get("pending-resume"),
9363            Some(&run.id)
9364        );
9365        let mut stale = stale;
9366        queue.put(&mut stale).unwrap();
9367        assert_eq!(
9368            stale.dispatched_resumes, recovered.dispatched_resumes,
9369            "a stale task writer cannot erase dispatch ownership"
9370        );
9371        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
9372        assert!(resumed.decision_starts.is_empty());
9373        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
9374        assert!(
9375            resumed.decision_starts.is_empty(),
9376            "handoff is not execution proof"
9377        );
9378        resumed.begin_pass();
9379        resumed.save_under(dir.path()).unwrap();
9380        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
9381        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
9382        disk.carry_dispatched_resumes(&recovered);
9383        disk.begin_pass();
9384        assert_eq!(
9385            disk.decision_starts.get("pending-resume"),
9386            Some(&0),
9387            "later execution must preserve the original pass receipt"
9388        );
9389    }
9390
9391    #[test]
9392    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9393        let mut t = task();
9394        t.start("20260904-000000-4043".to_owned());
9395        t.last_error = Some("earlier trouble".to_owned());
9396        let mut state = run_state(RunStatus::Judging);
9397        state.parked = true;
9398        reclaim(&mut t, Some(state), 1, "en");
9399        assert_eq!(t.status, TaskStatus::Parked);
9400        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9401        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9402        assert!(t.park_reason.is_some());
9403        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9404        assert!(!t.fresh_start);
9405        assert!(t.status.runnable());
9406    }
9407
9408    #[test]
9409    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9410        let mut t = task();
9411        t.start("20260904-000000-4043".to_owned());
9412        t.last_error = Some("earlier trouble".to_owned());
9413        settle(
9414            &mut t,
9415            Verdict {
9416                status: RunStatus::Judging,
9417                left_pr: false,
9418                quota_hit: false,
9419                parked: true,
9420                no_viable_candidates: false,
9421            },
9422            "parked after `judging`",
9423            1,
9424        );
9425        assert_eq!(t.status, TaskStatus::Parked);
9426        assert_eq!(t.attempts, 0);
9427        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9428        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9429        assert_eq!(t.schema, crate::queue::SCHEMA);
9430        assert!(
9431            crate::notices::task_held(&t).is_none(),
9432            "a park is not news"
9433        );
9434        t.start("20260904-000000-4043".to_owned());
9435        assert_eq!(t.park_reason, None);
9436    }
9437
9438    #[test]
9439    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9440        // A blocked run with attempts left goes back to `Failed`, exactly as
9441        // it would from `attempt` itself - `reclaim` must not invent a second
9442        // policy for a task a daemon merely stopped without reporting.
9443        let mut t = task();
9444        t.start("20260904-000000-4043".to_owned());
9445        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9446        assert_eq!(t.status, TaskStatus::Failed);
9447        assert!(t.status.runnable());
9448    }
9449
9450    #[test]
9451    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9452        let mut t = task();
9453        t.start("20260904-000000-4043".to_owned());
9454        assert_eq!(t.attempts, 1);
9455        let mut run = run_state(RunStatus::Implementing);
9456        run.id = "20260904-000000-4043".to_owned();
9457        run.begin_pass();
9458        let cause = crate::run::ParkCause::Upgrade {
9459            from: "0.121.0".to_owned(),
9460            to: Some("0.121.1".to_owned()),
9461        };
9462        run.end_pass_parked(cause.clone());
9463        run.parked = true;
9464        let verdict = Verdict {
9465            status: run.status,
9466            left_pr: false,
9467            quota_hit: false,
9468            parked: true,
9469            no_viable_candidates: false,
9470        };
9471        // A crash after the checkpoint but before queue settlement must
9472        // recover exactly the same scheduling evidence and refund.
9473        let mut orphan = t.clone();
9474        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9475        assert_eq!(orphan.status, TaskStatus::Parked);
9476        assert_eq!(orphan.attempts, 0);
9477        assert_eq!(
9478            orphan.upgrade_resume_key(),
9479            Some((run.passes[0].started_at, orphan.id.as_str()))
9480        );
9481        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9482        assert_eq!(t.attempts, 0);
9483        assert_eq!(t.passes.len(), 1);
9484        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9485        assert_eq!(t.passes[0].parked, Some(cause));
9486        assert_eq!(t.passes[0].pass_index, 0);
9487        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9488        assert!(t.upgrade_resume_key().is_some());
9489
9490        // A resumed pass that then fails spends its attempt, and the earlier
9491        // pass's entry is untouched.
9492        t.start("20260904-000000-4043".to_owned());
9493        run.begin_pass();
9494        run.status = RunStatus::Failed;
9495        let verdict = Verdict {
9496            status: RunStatus::Failed,
9497            left_pr: false,
9498            quota_hit: false,
9499            parked: false,
9500            no_viable_candidates: false,
9501        };
9502        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9503        assert_eq!(t.passes.len(), 2);
9504        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9505        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9506        assert_eq!(t.passes[1].pass_index, 1);
9507        assert_eq!(t.attempts, 1);
9508    }
9509
9510    #[test]
9511    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9512        let mut t = task();
9513        t.start("20260904-000000-4043".to_owned());
9514        reclaim(&mut t, None, 2, "en");
9515        assert_eq!(t.status, TaskStatus::Held);
9516        assert!(
9517            t.last_error
9518                .as_deref()
9519                .is_some_and(|e| e.contains("running")),
9520            "the operator needs to know why this task was held"
9521        );
9522    }
9523
9524    #[test]
9525    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9526        let dir = tempfile::tempdir().unwrap();
9527        let queue = Queue::at(dir.path().to_path_buf());
9528
9529        // No run recorded, so this never has to touch `RunState::load`.
9530        let mut orphaned = task();
9531        orphaned.id = "20260904-000000-orph".to_owned();
9532        orphaned.status = TaskStatus::Running;
9533        orphaned.attempts = 1;
9534        queue.put(&mut orphaned).unwrap();
9535
9536        let mut alive = task();
9537        alive.id = "20260904-000000-live".to_owned();
9538        alive.status = TaskStatus::Running;
9539        alive.attempts = 1;
9540        queue.put(&mut alive).unwrap();
9541        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9542
9543        let mut queued = task();
9544        queued.id = "20260904-000000-wait".to_owned();
9545        queue.put(&mut queued).unwrap();
9546
9547        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9548        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9549
9550        assert_eq!(
9551            queue.get(&orphaned.id).unwrap().status,
9552            TaskStatus::Held,
9553            "nothing was driving it and there was no run to recover"
9554        );
9555        assert_eq!(
9556            queue.get(&alive.id).unwrap().status,
9557            TaskStatus::Running,
9558            "a live claim must protect the task it belongs to"
9559        );
9560        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9561    }
9562
9563    /// Read a run.json back from an explicit `home`, the same way
9564    /// `reclaim_abandoned_runs` itself does - never through the
9565    /// process-global `RunState::load`, which this test's own `home` (an
9566    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9567    /// use at all.
9568    fn read_run_under(home: &Path, id: &str) -> RunState {
9569        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9570        serde_json::from_str(&body).unwrap()
9571    }
9572
9573    #[test]
9574    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9575        let dir = tempfile::tempdir().unwrap();
9576        let home = dir.path().to_path_buf();
9577        let now = Timestamp::now();
9578        let overrun_seat = || crate::run::ActiveSeat {
9579            node: "implement".to_owned(),
9580            started_at: now - jiff::SignedDuration::new(21_000, 0),
9581            timeout_secs: 3_600,
9582            attempt: 0,
9583            task: None,
9584            command: None,
9585            index: None,
9586            total: None,
9587        };
9588
9589        let mut dead = run_state(RunStatus::Implementing);
9590        dead.id = "20260101-000000-dead".to_owned();
9591        dead.active.insert("impl-A".to_owned(), overrun_seat());
9592        // A `driver_pid` the injected query below confirms gone outright —
9593        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9594        dead.driver_pid = Some(4242);
9595        dead.save_under(&home).unwrap();
9596
9597        // Same shape, but a live daemon's heartbeat names it: must be left
9598        // exactly alone, however far past its own timeout the seat sits.
9599        let mut alive = run_state(RunStatus::Implementing);
9600        alive.id = "20260101-000000-aliv".to_owned();
9601        alive.active.insert("impl-A".to_owned(), overrun_seat());
9602        alive.save_under(&home).unwrap();
9603        let mut status = Status::new();
9604        status.current = vec![Current {
9605            worker: None,
9606            task: "20260101-000000-task".to_owned(),
9607            run: alive.id.clone(),
9608        }];
9609        write_status_to(&home.join("daemon.json"), &status).unwrap();
9610
9611        // The abandoned seat left an open question behind: nobody is left to
9612        // read an answer once the run is failed, and this must not wait for
9613        // some later daemon startup's own sweep to notice that.
9614        let questions = Questions::at(home.join("questions"));
9615        let mut q = ask::Question::new(
9616            dead.id.clone(),
9617            "implement".to_owned(),
9618            "impl-A".to_owned(),
9619            "Which storage backend?".to_owned(),
9620            String::new(),
9621            vec!["SQLite".to_owned(), "Redis".to_owned()],
9622        );
9623        questions.put(&mut q).unwrap();
9624
9625        let abandoned = reclaim_abandoned_runs_with(
9626            &home,
9627            now,
9628            |pid| if pid == 4242 { Some(false) } else { None },
9629            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9630        );
9631        assert_eq!(abandoned, vec![dead.id.clone()]);
9632
9633        let reloaded = read_run_under(&home, &dead.id);
9634        assert_eq!(reloaded.status, RunStatus::Failed);
9635        assert!(reloaded.active.is_empty());
9636        assert!(
9637            !questions.get(&q.id).unwrap().status.open(),
9638            "the failed run's own open question must be settled in the same pass"
9639        );
9640
9641        let still_alive = read_run_under(&home, &alive.id);
9642        assert_eq!(
9643            still_alive.status,
9644            RunStatus::Implementing,
9645            "a live daemon's claim protects it"
9646        );
9647        assert!(!still_alive.active.is_empty());
9648    }
9649
9650    /// The exact shape a review round flagged as broken: `magi serve` running
9651    /// in this same `home` scans *every* run on disk, including a manual
9652    /// `magi review` / `magi run` this daemon never started and that
9653    /// therefore claims no heartbeat of its own. Before this scan asked
9654    /// `liveness` rather than just `is_working_on`, a manual run whose active
9655    /// seat merely ran a little past its own timeout — the CLI finishing up,
9656    /// its result still being collected — got wiped and failed by a daemon
9657    /// that had nothing to do with it, out from under a process that was
9658    /// still very much running.
9659    #[test]
9660    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9661        let dir = tempfile::tempdir().unwrap();
9662        let home = dir.path().to_path_buf();
9663        let now = Timestamp::now();
9664
9665        let mut manual = run_state(RunStatus::Reviewing);
9666        manual.id = "20260101-000000-manl".to_owned();
9667        manual.active.insert(
9668            "review-1".to_owned(),
9669            crate::run::ActiveSeat {
9670                node: "review".to_owned(),
9671                started_at: now - jiff::SignedDuration::new(21_000, 0),
9672                timeout_secs: 3_600,
9673                attempt: 0,
9674                task: None,
9675                command: None,
9676                index: None,
9677                total: None,
9678            },
9679        );
9680        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9681        // but a real, still-running process: `liveness` must corroborate this
9682        // as `Live`, not read the missing daemon claim as death.
9683        manual.driver_pid = Some(4242);
9684        manual.driver_started_at = Some("1790000000".to_owned());
9685        manual.save_under(&home).unwrap();
9686
9687        let abandoned = reclaim_abandoned_runs_with(
9688            &home,
9689            now,
9690            |pid| if pid == 4242 { Some(true) } else { None },
9691            |pid| {
9692                if pid == 4242 {
9693                    Some("1790000000".to_owned())
9694                } else {
9695                    None
9696                }
9697            },
9698        );
9699        assert!(
9700            abandoned.is_empty(),
9701            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9702        );
9703
9704        let reloaded = read_run_under(&home, &manual.id);
9705        assert_eq!(reloaded.status, RunStatus::Reviewing);
9706        assert!(!reloaded.active.is_empty());
9707    }
9708
9709    #[test]
9710    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9711        let dir = tempfile::tempdir().unwrap();
9712        let queue = Queue::at(dir.path().to_path_buf());
9713        let mut only = task();
9714        queue.put(&mut only).unwrap();
9715
9716        let _elsewhere = queue.claim(&only.id).unwrap();
9717        let candidates = runnable(&queue);
9718        assert_eq!(candidates.len(), 1, "the task is still runnable");
9719        assert!(
9720            queue.claim(&candidates[0].id).is_err(),
9721            "the loop cannot take a claim somebody else holds"
9722        );
9723
9724        let after = queue.get(&only.id).unwrap();
9725        assert_eq!(after.status, TaskStatus::Queued);
9726        assert_eq!(
9727            after.attempts, 0,
9728            "losing the race is not an attempt at the task"
9729        );
9730        assert_eq!(after.last_error, None);
9731    }
9732
9733    #[test]
9734    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9735        let dir = tempfile::tempdir().unwrap();
9736        let path = dir.path().join("daemon.json");
9737
9738        let mut status = Status::new();
9739        status.idle = false;
9740        status.completed = 7;
9741        status.current = vec![Current {
9742            worker: None,
9743            task: "20260902-000000-t111".to_owned(),
9744            run: "20260902-000001-r111".to_owned(),
9745        }];
9746        write_status_to(&path, &status).unwrap();
9747        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9748        assert_eq!(first.schema, SCHEMA);
9749        assert_eq!(first.pid, std::process::id());
9750        assert!(!first.idle);
9751        assert_eq!(first.completed, 7);
9752        assert_eq!(first.current, status.current);
9753        assert!(
9754            !path.with_extension("json.tmp").exists(),
9755            "the temp file is renamed, not left behind"
9756        );
9757
9758        std::thread::sleep(Duration::from_millis(5));
9759        status.updated_at = Timestamp::now();
9760        status.polls = 3;
9761        write_status_to(&path, &status).unwrap();
9762        let second: Status =
9763            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9764        assert!(
9765            second.updated_at > first.updated_at,
9766            "a reader can only detect staleness if the heartbeat moves"
9767        );
9768        assert_eq!(
9769            second.started_at, first.started_at,
9770            "the start time is not a heartbeat"
9771        );
9772        assert_eq!(second.polls, 3);
9773    }
9774
9775    #[test]
9776    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9777        let dir = tempfile::tempdir().unwrap();
9778
9779        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9780
9781        let mut status = Status::new();
9782        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9783        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9784        let stale = read_status(dir.path()).unwrap();
9785        assert!(
9786            !stale.running(Timestamp::now()),
9787            "a minute without a heartbeat is a dead daemon, not a busy one"
9788        );
9789        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9790
9791        status.updated_at = Timestamp::now();
9792        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9793        let fresh = read_status(dir.path()).unwrap();
9794        assert!(fresh.running(Timestamp::now()));
9795    }
9796
9797    #[test]
9798    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9799        let dir = tempfile::tempdir().unwrap();
9800        let now = Timestamp::now();
9801        let mine = "20260903-080619-01c2";
9802
9803        assert!(
9804            !is_working_on(dir.path(), mine, now),
9805            "no status file means nobody is working on anything"
9806        );
9807
9808        let mut status = Status::new();
9809        status.current = vec![Current {
9810            worker: None,
9811            task: "20260903-080340-0167".to_owned(),
9812            run: mine.to_owned(),
9813        }];
9814        status.updated_at = now;
9815        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9816        assert!(is_working_on(dir.path(), mine, now));
9817        assert!(
9818            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9819            "a daemon busy with one run is not working on another"
9820        );
9821
9822        // A killed daemon stops writing heartbeats but leaves the file behind
9823        // naming the run it died in. That run must not be undeletable forever.
9824        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9825        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9826        assert!(
9827            !is_working_on(dir.path(), mine, now),
9828            "a stale heartbeat is a dead daemon, so its run is a leftover"
9829        );
9830    }
9831
9832    #[test]
9833    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9834        let dir = tempfile::tempdir().unwrap();
9835        let now = Timestamp::now();
9836
9837        assert!(
9838            !is_working_on_short(dir.path(), "01c2", now),
9839            "no status file means nobody is working on anything"
9840        );
9841
9842        let mut status = Status::new();
9843        status.current = vec![Current {
9844            worker: None,
9845            task: "20260903-080340-0167".to_owned(),
9846            run: "20260903-080619-01c2".to_owned(),
9847        }];
9848        status.updated_at = now;
9849        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9850        assert!(
9851            is_working_on_short(dir.path(), "01c2", now),
9852            "the run's short id is the last block of its full id"
9853        );
9854        assert!(
9855            !is_working_on_short(dir.path(), "3cbf", now),
9856            "a daemon busy with one worktree bay is not working on another"
9857        );
9858    }
9859
9860    #[test]
9861    fn a_newer_status_file_still_yields_a_reading() {
9862        let dir = tempfile::tempdir().unwrap();
9863        // A field this build has never heard of must not turn the reading into
9864        // nothing at all; that is the whole reason the reader is permissive.
9865        std::fs::write(
9866            dir.path().join("daemon.json"),
9867            serde_json::json!({
9868                "schema": 2,
9869                "updated_at": Timestamp::now().to_string(),
9870                "idle": true,
9871                "surprise": { "nested": [1, 2, 3] },
9872            })
9873            .to_string(),
9874        )
9875        .unwrap();
9876
9877        let reading = read_status(dir.path()).expect("a forward-compatible read");
9878        assert!(reading.running(Timestamp::now()));
9879        assert!(reading.idle);
9880        assert!(reading.current.is_empty());
9881    }
9882
9883    #[test]
9884    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9885        // A daemon started before `current` became a list keeps writing this
9886        // shape on every heartbeat until it is restarted. A rolling upgrade
9887        // - a newer `magi web` or `magi doctor` reading an older `magi
9888        // serve`'s heartbeat - must still see the run it is on, not "no
9889        // daemon" from a type mismatch failing the whole struct.
9890        let dir = tempfile::tempdir().unwrap();
9891        std::fs::write(
9892            dir.path().join("daemon.json"),
9893            serde_json::json!({
9894                "schema": 1,
9895                "pid": 4242,
9896                "updated_at": Timestamp::now().to_string(),
9897                "idle": false,
9898                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9899                "completed": 3,
9900                "polls": 9,
9901            })
9902            .to_string(),
9903        )
9904        .unwrap();
9905
9906        let reading = read_status(dir.path()).expect("an older shape must still parse");
9907        assert!(reading.running(Timestamp::now()));
9908        assert_eq!(
9909            reading.current,
9910            vec![Current {
9911                worker: None,
9912                task: "20260902-140501-aaaa".to_owned(),
9913                run: "20260902-140502-bbbb".to_owned(),
9914            }]
9915        );
9916    }
9917
9918    #[test]
9919    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9920        let dir = tempfile::tempdir().unwrap();
9921        std::fs::write(
9922            dir.path().join("daemon.json"),
9923            serde_json::json!({
9924                "schema": 1,
9925                "updated_at": Timestamp::now().to_string(),
9926                "idle": true,
9927                "current": null,
9928            })
9929            .to_string(),
9930        )
9931        .unwrap();
9932        let with_null = read_status(dir.path()).expect("null must still parse");
9933        assert!(with_null.current.is_empty());
9934
9935        std::fs::write(
9936            dir.path().join("daemon.json"),
9937            serde_json::json!({
9938                "schema": 1,
9939                "updated_at": Timestamp::now().to_string(),
9940                "idle": true,
9941            })
9942            .to_string(),
9943        )
9944        .unwrap();
9945        let absent = read_status(dir.path()).expect("a missing field must still parse");
9946        assert!(absent.current.is_empty());
9947    }
9948
9949    #[test]
9950    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9951        let fallback = Path::new("/default");
9952        let mut blank = task();
9953        blank.repo = PathBuf::new();
9954        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9955        let mut dot = task();
9956        dot.repo = PathBuf::from(".");
9957        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9958        assert_eq!(
9959            repo_for(&task(), fallback),
9960            PathBuf::from("/repo"),
9961            "a task that names a repository keeps it"
9962        );
9963    }
9964
9965    #[test]
9966    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9967        let dir = tempfile::tempdir().unwrap();
9968        let path = dir.path().join("explicit.toml");
9969        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9970        let opts = Opts {
9971            config: Some(path),
9972            merge: Some("none".into()),
9973            ..Default::default()
9974        };
9975        let mut t = task();
9976        t.set_implementers(
9977            2,
9978            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9979                .unwrap(),
9980        )
9981        .unwrap();
9982        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9983        assert_eq!(cfg.graph.implementers, 2);
9984        assert_eq!(cfg.graph.judges, 1);
9985        assert_eq!(cfg.merge.mode, MergeMode::None);
9986        t.set_implementers(1, &cfg).unwrap();
9987        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9988        apply_task_implementers(&mut cfg, &t);
9989        assert_eq!(cfg.graph.implementers, 1);
9990        assert_eq!(cfg.graph.judges, 1);
9991        assert_eq!(cfg.merge.mode, MergeMode::None);
9992    }
9993
9994    #[test]
9995    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9996        let dir = tempfile::tempdir().unwrap();
9997        let repo = dir.path().join("repo");
9998        std::fs::create_dir(&repo).unwrap();
9999        std::fs::write(
10000            repo.join("magi.toml"),
10001            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10002        )
10003        .unwrap();
10004        let daemon_config = dir.path().join("daemon.toml");
10005        std::fs::write(
10006            &daemon_config,
10007            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10008        )
10009        .unwrap();
10010        let opts = Opts {
10011            config: Some(daemon_config),
10012            merge: Some("pr".into()),
10013            ..Default::default()
10014        };
10015        let q = Queue::at(dir.path().join("queue"));
10016        let validation: Config =
10017            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10018                .unwrap();
10019        // No provenance field on legacy direct tasks: both shapes stay isolated.
10020        for record in ["{}", r#"{"candidates":2}"#] {
10021            let overrides = serde_json::from_str(record).unwrap();
10022            let filing = crate::direct::Filing {
10023                instruction: "work".into(),
10024                title: "direct".into(),
10025                repo: repo.clone(),
10026                source: crate::queue::Source::Human,
10027                solo: false,
10028                overrides,
10029                review_of: None,
10030                sources: Default::default(),
10031            };
10032            let filed =
10033                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
10034            let crate::direct::Filed::Standalone {
10035                mut task,
10036                claim: _claim,
10037            } = filed
10038            else {
10039                panic!("local filing")
10040            };
10041            let before = prepare_for(&repo, &opts, &task).unwrap();
10042            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
10043            assert_eq!(
10044                before.merge.mode,
10045                MergeMode::None,
10046                "daemon --merge must not leak"
10047            );
10048            for n in [2, 1, 2] {
10049                task.set_implementers(n, &validation).unwrap();
10050                q.put(&mut task).unwrap();
10051                task = q.get(&task.id).unwrap();
10052                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
10053                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
10054                apply_task_implementers(&mut cfg, &task);
10055                assert_eq!(cfg.graph.implementers, usize::from(n));
10056                assert_eq!(cfg.graph.judges, 2);
10057                assert_eq!(cfg.merge.mode, MergeMode::None);
10058            }
10059        }
10060    }
10061
10062    #[test]
10063    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
10064        let cfg: Config =
10065            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10066                .unwrap();
10067        let mut t = task();
10068        t.review_of = Some("review-target".into());
10069        t.hold_manual(Some("retry".into()));
10070        let mut previous = RunState::new(
10071            PathBuf::from("/repo"),
10072            "main".into(),
10073            "abc1234".into(),
10074            "review".into(),
10075            cfg.clone(),
10076        );
10077        previous.config.graph.implementers = 2;
10078        for count in [1, 3] {
10079            t.set_implementers(count, &cfg).unwrap();
10080            t.release();
10081            assert_eq!(t.review_of.as_deref(), Some("review-target"));
10082            for proposed in [
10083                Starter::Resume(previous.id.clone()),
10084                Starter::Review("recovery-target".into()),
10085            ] {
10086                assert_eq!(
10087                    starter_with_implementers(&t, Some(&previous), proposed),
10088                    Starter::Review("review-target".into())
10089                );
10090            }
10091            let mut configured = cfg.clone();
10092            apply_task_implementers(&mut configured, &t);
10093            assert_eq!(configured.graph.implementers, usize::from(count));
10094            assert_eq!(previous.config.graph.implementers, 2);
10095        }
10096    }
10097
10098    #[test]
10099    fn task_implementers_dispatch_and_resume_agree() {
10100        let mut t = task();
10101        let cfg: crate::config::Config =
10102            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10103                .unwrap();
10104        let mut run = RunState::new(
10105            PathBuf::from("/repo"),
10106            "main".into(),
10107            "abc1234".into(),
10108            "work".into(),
10109            cfg.clone(),
10110        );
10111        run.config.graph.implementers = 2;
10112        for n in [2, 1, 3, 2] {
10113            t.set_implementers(n, &cfg).unwrap();
10114            let mut dispatched = cfg.clone();
10115            apply_task_implementers(&mut dispatched, &t);
10116            assert_eq!(dispatched.graph.implementers, usize::from(n));
10117            assert_eq!(implementers_match(&t, &run), n == 2);
10118            for proposed in [
10119                Starter::Resume(run.id.clone()),
10120                Starter::Review("old-branch".into()),
10121            ] {
10122                let expected = if n == 2 {
10123                    proposed.clone()
10124                } else {
10125                    Starter::Start
10126                };
10127                assert_eq!(
10128                    starter_with_implementers(&t, Some(&run), proposed),
10129                    expected
10130                );
10131            }
10132            assert_eq!(
10133                run.config.graph.implementers, 2,
10134                "history must not be rewritten"
10135            );
10136        }
10137        t.solo = false;
10138        t.overrides = None;
10139        assert!(implementers_match(&t, &run));
10140    }
10141
10142    #[test]
10143    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10144        // Three seats said out loud. What `solo` promises is one candidate
10145        // *whatever the config asks for*, so the contrast has to be a number
10146        // this test owns - it used to be `Config::default()`'s, which became
10147        // 1 when one implementation became the default and left the two
10148        // halves of this test asserting the same thing.
10149        let mut solo_cfg = Config::default();
10150        solo_cfg.graph.implementers = 3;
10151        let mut solo_task = task();
10152        solo_task.solo = true;
10153        apply_task_implementers(&mut solo_cfg, &solo_task);
10154        assert_eq!(solo_cfg.graph.implementers, 1);
10155
10156        let mut plain_cfg = Config::default();
10157        plain_cfg.graph.implementers = 3;
10158        let plain_task = task();
10159        assert!(!plain_task.solo);
10160        apply_task_implementers(&mut plain_cfg, &plain_task);
10161        assert_eq!(
10162            plain_cfg.graph.implementers, 3,
10163            "a task that did not ask to run alone keeps the config's candidates"
10164        );
10165    }
10166
10167    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10168        QuotaLoss {
10169            cause: crate::agent::QuotaCause::UsageLimit,
10170            agent: String::new(),
10171            seat: seat.into(),
10172            node: "judge".into(),
10173            at: at.parse().unwrap(),
10174            reset: reset.map(str::to_string),
10175        }
10176    }
10177
10178    #[test]
10179    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10180        let now = Timestamp::now();
10181        for reset in [None, Some("in 1h")] {
10182            let auth = crate::agent::Quota {
10183                cause: crate::agent::QuotaCause::Authentication,
10184                agent: "alpha".into(),
10185                reset: reset.map(str::to_owned),
10186            };
10187            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10188            assert_eq!(cooldown_until(&[loss], now), None);
10189        }
10190    }
10191
10192    #[test]
10193    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10194        let old: Vec<QuotaLoss> = (1..=4)
10195            .map(|i| {
10196                loss(
10197                    &format!("judge-{i}"),
10198                    "2026-09-23T05:23:00Z",
10199                    Some("2:40pm (Asia/Tokyo)"),
10200                )
10201            })
10202            .collect();
10203        let fresh = losses_this_attempt(&old, &old);
10204        assert!(fresh.is_empty());
10205        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10206        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10207    }
10208
10209    #[test]
10210    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10211        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10212        let now = Timestamp::now();
10213        let mut after = old.clone();
10214        after.push(loss("judge-2", &now.to_string(), None));
10215        let fresh = losses_this_attempt(&old, &after);
10216        assert_eq!(fresh, vec![after[1].clone()]);
10217        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10218        assert_eq!(
10219            until,
10220            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10221        );
10222    }
10223
10224    #[test]
10225    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10226        // `recover_stall` removes judge-1's loss and the retry then hits quota
10227        // again: the vector is the same length, so an index diff sees nothing.
10228        let before = vec![
10229            loss("judge-1", "2026-09-23T05:23:00Z", None),
10230            loss("judge-2", "2026-09-23T05:24:00Z", None),
10231        ];
10232        let after = vec![
10233            loss("judge-2", "2026-09-23T05:24:00Z", None),
10234            loss("judge-1", "2026-09-24T01:00:00Z", None),
10235        ];
10236        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10237    }
10238
10239    #[test]
10240    fn merge_overrides_are_parsed_or_refused() {
10241        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10242        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10243        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10244        assert!(merge_mode("squash").is_err());
10245    }
10246
10247    #[test]
10248    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10249        let now = Timestamp::now();
10250        let fallback = Duration::from_secs(300);
10251        let cap = Duration::from_secs(1800);
10252
10253        // No reset hint at all: the fallback.
10254        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10255
10256        // A reset ten minutes out, well inside the cap: waited for exactly.
10257        let soon = now + jiff::SignedDuration::from_secs(600);
10258        assert_eq!(
10259            quota_wait(Some(soon), now, fallback, cap),
10260            Duration::from_secs(600)
10261        );
10262
10263        // A reset already in the past is not trusted: the fallback, not a
10264        // zero or negative wait that would spin the loop right back around.
10265        let past = now - jiff::SignedDuration::from_secs(60);
10266        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10267
10268        // A reset further out than the cap is trusted for direction but not
10269        // for magnitude: a parsing slip must not sleep the loop for a day.
10270        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10271        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10272    }
10273
10274    #[test]
10275    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10276        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10277
10278        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10279        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10280
10281        // Same clock reading, but it has already gone by today: read as
10282        // tomorrow's, since the CLI would not still be reporting a limit past
10283        // its own stated reset.
10284        let already_past =
10285            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10286        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10287
10288        assert!(
10289            parse_reset_hint("session limit reached", now, now).is_none(),
10290            "free text with no recognised shape is not guessed at"
10291        );
10292        assert!(
10293            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10294            "an unresolvable zone name is not guessed at either"
10295        );
10296    }
10297
10298    #[test]
10299    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10300        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10301
10302        let at = parse_reset_hint(
10303            "You've hit your usage limit. Visit \
10304             https://chatgpt.com/codex/settings/usage to purchase more \
10305             credits or try again at Sep 19th, 2026 5:10 PM.",
10306            now,
10307            now,
10308        )
10309        .expect("the codex reset wording is a recognised shape");
10310        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10311
10312        // The month is explicit, so a date already earlier in the same
10313        // sentence-implied year than `now` is trusted as written rather than
10314        // rolled forward a year the way the bracketed shape rolls a
10315        // same-day clock reading to tomorrow.
10316        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10317            .expect("an explicit year needs no rollover");
10318        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10319
10320        assert!(
10321            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10322            "a two-digit year is not the documented shape and is not guessed at"
10323        );
10324        assert!(
10325            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10326            "a four-letter month name is not the documented three-letter abbreviation"
10327        );
10328        assert!(
10329            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10330            "an explicit zone on the dated shape is a format nobody has \
10331             documented, and is refused rather than guessed at as UTC"
10332        );
10333    }
10334
10335    #[test]
10336    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10337        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10338        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10339
10340        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10341        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10342
10343        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10344        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10345
10346        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10347            assert!(
10348                parse_reset_hint(bad, now, recorded).is_none(),
10349                "{bad:?} must not be guessed at"
10350            );
10351        }
10352    }
10353
10354    /// A loop whose queue lives in a temp tree and whose poll interval is far
10355    /// longer than the test's patience, so anything that waits out a poll
10356    /// instead of noticing the stop fails rather than merely being slow.
10357    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10358        let config = dir.join("magi.toml");
10359        std::fs::write(
10360            &config,
10361            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10362        )
10363        .unwrap();
10364        let opts = Opts {
10365            poll: Duration::from_secs(30),
10366            config: Some(config),
10367            // The explicit fixture config keeps startup cleanup from reading
10368            // machine configuration. This fictional repository likewise
10369            // keeps any best-effort git cleanup away from this checkout.
10370            repo: dir.join("repo"),
10371            ..Opts::default()
10372        };
10373        // The status file goes in a directory that does not exist yet, so its
10374        // creation is itself evidence the loop published one. `worktrees`
10375        // must be just as fictional: the janitor reclaims worktrees under it
10376        // for real, and a test that let it fall through to
10377        // `crate::run::default_worktree_root()` would have it reclaim
10378        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10379        // which is exactly what happened before this function took the
10380        // parameter at all.
10381        let home = dir.join("home");
10382        // These control-only fixtures do not launch native workers. Give the
10383        // independently tested maintenance services a fresh cadence receipt.
10384        let stamps = home.join("service-ticks");
10385        std::fs::create_dir_all(&stamps).unwrap();
10386        for service in ["waiter", "deputies", "release-watch"] {
10387            std::fs::write(
10388                stamps.join(service),
10389                Timestamp::now().as_second().to_string(),
10390            )
10391            .unwrap();
10392        }
10393        for operation in [
10394            "conductor",
10395            "maintenance",
10396            "housekeeping",
10397            "disk-pressure",
10398            "cache",
10399            "fetch",
10400        ] {
10401            std::fs::write(
10402                stamps.join(format!("daemon-{operation}")),
10403                serde_json::to_vec(&Timestamp::now()).unwrap(),
10404            )
10405            .unwrap();
10406        }
10407        let worktrees = dir.join("wt");
10408        (
10409            opts,
10410            Queue::at(dir.join("queue")),
10411            home.join("daemon.json"),
10412            home,
10413            worktrees,
10414        )
10415    }
10416
10417    #[test]
10418    fn a_stop_is_idempotent_and_once_set_stays_set() {
10419        let stop = Stop::new();
10420        assert!(!stop.stopped());
10421
10422        stop.stop();
10423        assert!(stop.stopped());
10424        stop.stop();
10425        assert!(stop.stopped(), "a second stop is not a toggle");
10426
10427        let shared = stop.clone();
10428        assert!(
10429            shared.stopped(),
10430            "a clone is the same stop; that is how the loop and its caller share one"
10431        );
10432    }
10433
10434    #[tokio::test]
10435    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10436        for operation in ["conductor", "maintenance", "housekeeping"] {
10437            let dir = tempfile::tempdir().unwrap();
10438            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10439            opts.once = true;
10440            opts.poll = Duration::from_millis(1);
10441            let mut task = task();
10442            task.runs.push("fixture-run".into());
10443            queue.put(&mut task).unwrap();
10444            let claim = queue.claim(&task.id).unwrap();
10445
10446            // Model a live service holding the task's claim across the
10447            // scheduler's dispatch scan. No real subprocess or timed race.
10448            let directory = home.join("workers/jobs/abcdef");
10449            std::fs::create_dir_all(&directory).unwrap();
10450            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10451            crate::pr_head::try_lock_file(&lease).unwrap();
10452            let mut job = crate::worker::Job {
10453                id: "abcdef".into(),
10454                sequence: 1,
10455                kind: "daemon-service".into(),
10456                key: format!("service:daemon-{operation}"),
10457                payload: serde_json::Value::Null,
10458                generation: "fixture".into(),
10459                version: None,
10460                status: crate::worker::Status::Running,
10461                result: None,
10462                pid: Some(std::process::id()),
10463                created_at: Timestamp::now().as_second() as u64,
10464                finished_at: None,
10465            };
10466            let record = directory.join("job.json");
10467            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10468
10469            let status = Arc::new(Mutex::new(Status::new()));
10470            let stop = Stop::new();
10471            let mut drain = Box::pin(poll(
10472                &opts,
10473                &queue,
10474                &status,
10475                &home,
10476                &worktrees,
10477                &stop,
10478                DispatchLimits {
10479                    max_concurrent: 1,
10480                    pause_for_interrupts: false,
10481                    recovery_cfg: None,
10482                },
10483            ));
10484            std::future::poll_fn(|cx| {
10485                use std::future::Future;
10486                assert!(
10487                    drain.as_mut().poll(cx).is_pending(),
10488                    "--once must wait for {operation} to release its queue claim"
10489                );
10490                std::task::Poll::Ready(())
10491            })
10492            .await;
10493            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10494
10495            // An answer arrives while the service still owns the claim. A
10496            // fresh scheduling pass must apply it before declaring idle.
10497            let questions = Questions::at(home.join("questions"));
10498            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10499            questions.put(&mut q).unwrap();
10500            drop(claim);
10501            // Model services that took longer than their cadence, without a
10502            // wall-clock sleep. The final scans must not respawn them even
10503            // though their receipts now permit another periodic invocation.
10504            let expired =
10505                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10506            for service in [operation, "housekeeping"] {
10507                std::fs::write(
10508                    home.join("service-ticks").join(format!("daemon-{service}")),
10509                    &expired,
10510                )
10511                .unwrap();
10512            }
10513            job.status = crate::worker::Status::Finished;
10514            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10515            drop(lease);
10516            tokio::time::timeout(Duration::from_secs(2), drain)
10517                .await
10518                .expect("the settled service must allow the drain to finish")
10519                .unwrap();
10520            let after = queue.get(&task.id).unwrap();
10521            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10522            assert!(after.action_applied(&q.id));
10523            for service in [operation, "housekeeping"] {
10524                assert_eq!(
10525                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10526                        .unwrap(),
10527                    expired,
10528                    "the final once rescan must not restart {service}"
10529                );
10530            }
10531        }
10532    }
10533
10534    #[test]
10535    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10536        let stop = Stop::new();
10537        stop.busy.store(1, Ordering::SeqCst);
10538        assert!(
10539            !stop.finishing(),
10540            "a busy loop nobody has asked to stop is just running"
10541        );
10542
10543        stop.stop();
10544        assert!(
10545            stop.finishing(),
10546            "a stop asked for mid-run has not landed until the run is settled"
10547        );
10548
10549        stop.busy.store(0, Ordering::SeqCst);
10550        assert!(
10551            !stop.finishing(),
10552            "once the run is settled the stop has landed and there is nothing to finish"
10553        );
10554    }
10555
10556    #[test]
10557    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10558        let stop = Stop::new();
10559        stop.busy.store(2, Ordering::SeqCst);
10560        stop.stop();
10561        assert!(stop.finishing(), "two runs still in flight");
10562
10563        stop.busy.store(1, Ordering::SeqCst);
10564        assert!(
10565            stop.finishing(),
10566            "one run finished, but a sibling is still working"
10567        );
10568
10569        stop.busy.store(0, Ordering::SeqCst);
10570        assert!(
10571            !stop.finishing(),
10572            "the last run out is what actually lands the stop"
10573        );
10574    }
10575
10576    #[tokio::test]
10577    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10578        let dir = tempfile::tempdir().unwrap();
10579        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10580        let stop = Stop::new();
10581        stop.stop();
10582
10583        let began = std::time::Instant::now();
10584        tokio::time::timeout(
10585            Duration::from_secs(2),
10586            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10587        )
10588        .await
10589        .expect("a stopped loop must return, not sit out its poll interval")
10590        .expect("the loop's own setup and teardown must not fail");
10591        assert!(
10592            began.elapsed() < opts.poll,
10593            "returned only after {:?}, which is a poll interval, not a stop",
10594            began.elapsed()
10595        );
10596    }
10597
10598    #[tokio::test]
10599    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10600        let dir = tempfile::tempdir().unwrap();
10601        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10602        let stop = Stop::new();
10603
10604        // Asked for after the loop is already parked on its empty queue, which
10605        // is the case an operator tapping stop on a phone actually hits.
10606        let asker = {
10607            let stop = stop.clone();
10608            tokio::spawn(async move {
10609                tokio::time::sleep(Duration::from_millis(20)).await;
10610                stop.stop();
10611            })
10612        };
10613
10614        let began = std::time::Instant::now();
10615        tokio::time::timeout(
10616            Duration::from_secs(2),
10617            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10618        )
10619        .await
10620        .expect("a stop asked for while idle must wake the wait")
10621        .expect("the loop's own setup and teardown must not fail");
10622        asker.await.unwrap();
10623        assert!(
10624            began.elapsed() < opts.poll,
10625            "returned only after {:?}, so the stop waited on the sleep",
10626            began.elapsed()
10627        );
10628    }
10629
10630    #[tokio::test]
10631    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10632        let dir = tempfile::tempdir().unwrap();
10633        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10634        let stop = Stop::new();
10635        stop.stop();
10636
10637        tokio::time::timeout(
10638            Duration::from_secs(2),
10639            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10640        )
10641        .await
10642        .expect("a stopped loop must return")
10643        .expect("the loop's own setup and teardown must not fail");
10644
10645        assert!(
10646            home.is_dir(),
10647            "the loop did publish a status file, so its removal is the teardown and not an absence"
10648        );
10649        assert!(
10650            !status_file.exists(),
10651            "a stopped loop clears its status file"
10652        );
10653        assert!(
10654            read_status(&home).is_none(),
10655            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10656        );
10657    }
10658
10659    #[tokio::test]
10660    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10661        let dir = tempfile::tempdir().unwrap();
10662        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10663
10664        let mut settled = RunState::new(
10665            dir.path().join("repo"),
10666            "main".to_owned(),
10667            "abc1234".to_owned(),
10668            "fixture".to_owned(),
10669            Config::default(),
10670        );
10671        settled.status = RunStatus::Ready;
10672        let run_dir = home.join("runs").join(&settled.id);
10673        std::fs::create_dir_all(&run_dir).unwrap();
10674        std::fs::write(
10675            run_dir.join("run.json"),
10676            serde_json::to_string_pretty(&settled).unwrap(),
10677        )
10678        .unwrap();
10679        let questions = Questions::at(home.join("questions"));
10680        let mut question = ask::Question::new(
10681            settled.id.clone(),
10682            "review".to_owned(),
10683            "reviewer-1".to_owned(),
10684            "Continue?".to_owned(),
10685            String::new(),
10686            Vec::new(),
10687        );
10688        questions.put(&mut question).unwrap();
10689
10690        run_service_worker(
10691            &home,
10692            serde_json::to_value(ServiceWorker {
10693                opts,
10694                queue: queue.root().to_path_buf(),
10695                worktrees_root: worktrees,
10696                operation: "housekeeping".to_owned(),
10697            })
10698            .unwrap(),
10699        )
10700        .await
10701        .unwrap();
10702
10703        assert_eq!(
10704            questions.get(&question.id).unwrap().status,
10705            ask::QuestionStatus::Abandoned,
10706            "the independent housekeeping worker settles ended-run questions"
10707        );
10708    }
10709
10710    #[test]
10711    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10712        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10713
10714        assert!(
10715            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10716            "never checked before: due at once"
10717        );
10718
10719        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10720        assert!(
10721            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10722            "well inside the interval: not due yet"
10723        );
10724
10725        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10726        assert!(
10727            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10728            "exactly at the edge: not yet due, same convention as `clean::due`"
10729        );
10730
10731        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10732        assert!(
10733            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10734            "past the interval: due again"
10735        );
10736    }
10737
10738    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10739    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10740    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10741    /// and the congestion test below both need, and must not drift apart.
10742    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10743        let config = dir.join("magi.toml");
10744        // A literal (single-quoted) TOML string, not a basic one: the cache
10745        // path is a Windows path full of backslashes, and a basic string
10746        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10747        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10748        // `{{ vars.cache }}` rendering documents.
10749        std::fs::write(
10750            &config,
10751            format!(
10752                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10753                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10754                cache_dir.display()
10755            ),
10756        )
10757        .unwrap();
10758        Opts {
10759            config: Some(config),
10760            repo: dir.join("repo"),
10761            ..Opts::default()
10762        }
10763    }
10764
10765    #[tokio::test]
10766    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10767        let dir = tempfile::tempdir().unwrap();
10768        let home = dir.path().join("home");
10769        let cache_dir = dir.path().join("cache");
10770        std::fs::create_dir_all(&cache_dir).unwrap();
10771        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10772        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10773
10774        // Nobody has asked this daemon to stop, which is the ordinary case;
10775        // the skip that a stop buys is asserted by its own test below.
10776        let running = Stop::new();
10777        let mut last_checked = None;
10778        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10779        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10780            .await;
10781        assert_eq!(
10782            crate::disk::dir_size(&cache_dir),
10783            0,
10784            "over the cap on the first check ever: pruned at once, no idle queue required"
10785        );
10786        assert_eq!(last_checked, Some(t0));
10787
10788        // A fresh oversized file lands, but the next check is not due yet.
10789        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10790        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10791        maybe_prune_cache_between_runs(
10792            &opts.repo,
10793            &opts,
10794            &home,
10795            &running,
10796            &mut last_checked,
10797            too_soon,
10798        )
10799        .await;
10800        assert_eq!(
10801            crate::disk::dir_size(&cache_dir),
10802            10,
10803            "too soon since the last check: left alone rather than rescanned every call"
10804        );
10805        assert_eq!(
10806            last_checked,
10807            Some(t0),
10808            "an idle check does not reset the clock"
10809        );
10810
10811        // Once the interval elapses, the same oversized cache is caught again.
10812        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10813        maybe_prune_cache_between_runs(
10814            &opts.repo,
10815            &opts,
10816            &home,
10817            &running,
10818            &mut last_checked,
10819            due_again,
10820        )
10821        .await;
10822        assert_eq!(
10823            crate::disk::dir_size(&cache_dir),
10824            0,
10825            "due again: pruned back under the cap"
10826        );
10827    }
10828
10829    /// A stop must not queue behind housekeeping. The prune below is a
10830    /// synchronous walk of the whole cache with no await point in it, so a
10831    /// loop that entered it could not get back to its own `stopped()` test
10832    /// until the walk finished - and because no run is in flight at this
10833    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10834    /// the stop had already landed. The idle branch has always made this same
10835    /// check before reaching `janitor`; the between-runs path makes it too.
10836    #[tokio::test]
10837    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10838        let dir = tempfile::tempdir().unwrap();
10839        let home = dir.path().join("home");
10840        let cache_dir = dir.path().join("cache");
10841        std::fs::create_dir_all(&cache_dir).unwrap();
10842        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10843        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10844
10845        let stop = Stop::new();
10846        stop.stop();
10847        assert!(
10848            !stop.finishing(),
10849            "no run is in flight at a between-runs boundary, so nothing else \
10850             would tell the operator this stop had not taken effect yet"
10851        );
10852
10853        let mut last_checked = None;
10854        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10855        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10856            .await;
10857        assert_eq!(
10858            crate::disk::dir_size(&cache_dir),
10859            10,
10860            "over its cap, and due for the first check ever, but a stop outranks \
10861             it: the cap is a standing policy the next start measures again"
10862        );
10863        assert_eq!(
10864            last_checked, None,
10865            "a check that never happened must not claim the interval"
10866        );
10867    }
10868
10869    /// A backlog must not starve cache pruning. The finite cache worker runs
10870    /// independently of queue drain and must not consume any task attempts.
10871    #[tokio::test]
10872    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10873        let dir = tempfile::tempdir().unwrap();
10874        let cache_dir = dir.path().join("cache");
10875        std::fs::create_dir_all(&cache_dir).unwrap();
10876        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10877
10878        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10879        opts.poll = Duration::from_millis(20);
10880        opts.max_attempts = 1_000;
10881
10882        let queue = Queue::at(dir.path().join("queue"));
10883        for i in 0..128 {
10884            let mut task = Task::new(
10885                format!("queued work {i}"),
10886                format!("queued work {i}"),
10887                opts.repo.clone(),
10888                Source::Human,
10889            );
10890            queue.put(&mut task).unwrap();
10891        }
10892
10893        let home = dir.path().join("home");
10894        let worktrees = dir.path().join("wt");
10895        run_service_worker(
10896            &home,
10897            serde_json::to_value(ServiceWorker {
10898                opts,
10899                queue: queue.root().to_path_buf(),
10900                worktrees_root: worktrees,
10901                operation: "cache".to_owned(),
10902            })
10903            .unwrap(),
10904        )
10905        .await
10906        .unwrap();
10907        let after = queue.list();
10908        assert_eq!(after.len(), 128);
10909        assert!(
10910            after
10911                .iter()
10912                .all(|task| task.status.runnable() && task.attempts == 0)
10913        );
10914
10915        assert_eq!(
10916            crate::disk::dir_size(&cache_dir),
10917            0,
10918            "an oversized cache must not be left to grow unboundedly just because the \
10919             queue kept the loop busy the whole time"
10920        );
10921    }
10922
10923    #[test]
10924    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10925        let dir = tempfile::tempdir().unwrap();
10926        let queue = Queue::at(dir.path().join("queue"));
10927        let questions = Questions::at(dir.path().join("questions"));
10928        let mut task = task();
10929        queue.put(&mut task).unwrap();
10930
10931        let mut task_question = ask::Question::new(
10932            task.id.clone(),
10933            crate::conduct::NODE.to_owned(),
10934            "conduct".to_owned(),
10935            "Which backend?".to_owned(),
10936            String::new(),
10937            Vec::new(),
10938        );
10939        questions.put(&mut task_question).unwrap();
10940        task.block(vec![task_question.id.clone()], None);
10941        queue.put(&mut task).unwrap();
10942
10943        let mut run_question = ask::Question::new(
10944            "20260101-000000-run1".to_owned(),
10945            "review".to_owned(),
10946            "reviewer-1".to_owned(),
10947            "Run question".to_owned(),
10948            String::new(),
10949            Vec::new(),
10950        );
10951        questions.put(&mut run_question).unwrap();
10952
10953        // A question from another node whose `run` happens to equal this
10954        // task's id — the same field, filled in for an unrelated reason. Only
10955        // `crate::conduct::NODE` questions use `run` as a task id; this one
10956        // must never be touched by this reconciliation, even after release.
10957        let mut coincidental = ask::Question::new(
10958            task.id.clone(),
10959            "review".to_owned(),
10960            "reviewer-1".to_owned(),
10961            "Unrelated review question".to_owned(),
10962            String::new(),
10963            Vec::new(),
10964        );
10965        questions.put(&mut coincidental).unwrap();
10966
10967        reconcile_task_questions(&queue, &questions);
10968        assert!(questions.get(&task_question.id).unwrap().status.open());
10969        assert!(questions.get(&run_question.id).unwrap().status.open());
10970        assert!(questions.get(&coincidental.id).unwrap().status.open());
10971
10972        task.release();
10973        queue.put(&mut task).unwrap();
10974        reconcile_task_questions(&queue, &questions);
10975        assert_eq!(
10976            questions.get(&task_question.id).unwrap().status,
10977            ask::QuestionStatus::Abandoned
10978        );
10979        assert!(
10980            questions.get(&run_question.id).unwrap().status.open(),
10981            "run questions remain the run janitor's responsibility"
10982        );
10983        assert!(
10984            questions.get(&coincidental.id).unwrap().status.open(),
10985            "a non-conductor question must not be abandoned just because its \
10986             run id coincides with a task id"
10987        );
10988    }
10989
10990    #[test]
10991    fn a_freshly_started_running_task_is_never_stalled() {
10992        let dir = tempfile::tempdir().unwrap();
10993        let mut t = task();
10994        t.start("run-1".to_owned());
10995        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10996        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10997        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10998    }
10999
11000    #[test]
11001    fn a_long_running_task_with_no_live_daemon_is_stalled() {
11002        let dir = tempfile::tempdir().unwrap();
11003        let mut t = task();
11004        t.start("run-1".to_owned());
11005        t.updated_at = Timestamp::now()
11006            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11007        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
11008        assert_eq!(
11009            stalled_tasks(
11010                &Queue::at(dir.path().join("q")),
11011                dir.path(),
11012                Timestamp::now()
11013            )
11014            .len(),
11015            0,
11016            "the task was never written to this queue"
11017        );
11018    }
11019
11020    #[test]
11021    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
11022        let dir = tempfile::tempdir().unwrap();
11023        let mut t = task();
11024        t.id = "20260903-080340-0167".to_owned();
11025        t.start("20260903-080619-01c2".to_owned());
11026        t.updated_at = Timestamp::now()
11027            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11028
11029        let mut status = Status::new();
11030        status.current = vec![Current {
11031            worker: None,
11032            task: t.id.clone(),
11033            run: "20260903-080619-01c2".to_owned(),
11034        }];
11035        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11036
11037        assert!(
11038            !is_stalled(&t, dir.path(), Timestamp::now()),
11039            "a live daemon's own heartbeat rules out stalled, however long the task has run"
11040        );
11041    }
11042
11043    /// Rewrite a task's `updated_at` on disk directly, bypassing
11044    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
11045    /// a fixture look like it has genuinely been `running` for a while.
11046    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
11047        let path = queue.path_of(id);
11048        let body = std::fs::read_to_string(&path).unwrap();
11049        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
11050        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
11051        v["updated_at"] = serde_json::Value::String(old.to_string());
11052        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
11053    }
11054
11055    #[test]
11056    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
11057        // The realistic `poll()` ordering, not `is_stalled` in isolation:
11058        // `reclaim_orphaned_running` runs first, on every poll, and settles
11059        // any `running` task whose claim it can actually take. For most
11060        // crashes that is immediate - a dead pid is proof enough for
11061        // `sweep_stale_claims` to drop the lock the same tick, and the very
11062        // next claim attempt succeeds. But a lock whose pid cannot be parsed
11063        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
11064        // `sweep_stale_claims`'s own doc), so the lock - and the claim
11065        // failure behind it - can legitimately outlive many polls. This is
11066        // exactly the gap `stalled_tasks` exists to surface well before that
11067        // six-hour sweep would: reclaim leaves the task `running`, and it
11068        // must still reach the conductor as stalled.
11069        let dir = tempfile::tempdir().unwrap();
11070        let queue = Queue::at(dir.path().join("queue"));
11071        let home = dir.path().join("home");
11072
11073        let mut t = task();
11074        t.id = "20260101-000001-lock".to_owned();
11075        t.start("run-1".to_owned());
11076        queue.put(&mut t).unwrap();
11077        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11078        std::fs::write(
11079            dir.path().join("queue").join(format!("{}.lock", t.id)),
11080            "not a pid",
11081        )
11082        .unwrap();
11083
11084        let now = Timestamp::now();
11085        assert!(
11086            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
11087            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
11088             and reclaim must leave the task alone"
11089        );
11090        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11091
11092        let stalled = stalled_tasks(&queue, &home, now);
11093        assert_eq!(
11094            stalled.len(),
11095            1,
11096            "reclaim's inability to claim it yet must not hide it from the conductor"
11097        );
11098        assert_eq!(stalled[0].id, t.id);
11099    }
11100
11101    #[test]
11102    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
11103        let dir = tempfile::tempdir().unwrap();
11104        crate::run::set_home(dir.path().join("run-home"));
11105        let queue = Queue::at(dir.path().join("queue"));
11106        let home = dir.path().join("home");
11107        let questions = Questions::at(dir.path().join("questions"));
11108
11109        let mut t = task();
11110        t.id = "20260101-000003-dead".to_owned();
11111        t.start("missing-run".to_owned());
11112        queue.put(&mut t).unwrap();
11113        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11114
11115        // This is the real poll ordering: retain the deterministic stalled
11116        // input before a claim proves the owner is gone and reclaims it.
11117        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11118        assert_eq!(
11119            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
11120            [&t.id]
11121        );
11122        assert_eq!(
11123            reclaim_orphaned_running(&queue, 2, &Default::default()),
11124            [t.id.clone()]
11125        );
11126        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11127
11128        // Reclaim drops its guard before conductor decisions are applied, so
11129        // the decision for the captured stalled input has a real write path.
11130        crate::conduct::apply(
11131            &queue,
11132            &questions,
11133            &crate::conduct::Verdict {
11134                decisions: vec![crate::conduct::Decision {
11135                    id: t.id.clone(),
11136                    recovery: Some(crate::conduct::Recovery::Requeue),
11137                    ..crate::conduct::Decision::default()
11138                }],
11139            },
11140        )
11141        .unwrap();
11142        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11143    }
11144
11145    #[test]
11146    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
11147        let dir = tempfile::tempdir().unwrap();
11148        let queue = Queue::at(dir.path().join("queue"));
11149        let home = dir.path().join("home");
11150
11151        let mut fresh = task();
11152        fresh.id = "20260101-000001-aaaa".to_owned();
11153        fresh.start("run-1".to_owned());
11154        queue.put(&mut fresh).unwrap();
11155
11156        let mut old = task();
11157        old.id = "20260101-000002-bbbb".to_owned();
11158        old.start("run-2".to_owned());
11159        queue.put(&mut old).unwrap();
11160        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
11161
11162        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11163        assert_eq!(stalled.len(), 1);
11164        assert_eq!(stalled[0].id, old.id);
11165    }
11166
11167    #[test]
11168    fn queued_and_finished_task_views_partition_by_status() {
11169        let dir = tempfile::tempdir().unwrap();
11170        let queue = Queue::at(dir.path().join("queue"));
11171
11172        let mut queued = task();
11173        queued.id = "20260101-000001-aaaa".to_owned();
11174        queue.put(&mut queued).unwrap();
11175
11176        let mut failed = task();
11177        failed.id = "20260101-000002-bbbb".to_owned();
11178        failed.start("run-1".to_owned());
11179        failed.fail("gate red", 5);
11180        queue.put(&mut failed).unwrap();
11181
11182        let mut held = task();
11183        held.id = "20260101-000003-cccc".to_owned();
11184        held.hold_machine(None);
11185        queue.put(&mut held).unwrap();
11186
11187        let mut running = task();
11188        running.id = "20260101-000004-dddd".to_owned();
11189        running.start("run-2".to_owned());
11190        queue.put(&mut running).unwrap();
11191
11192        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11193        assert_eq!(queued_ids, [queued.id.clone()]);
11194
11195        let mut finished_ids: Vec<String> =
11196            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11197        finished_ids.sort_unstable();
11198        let mut want = vec![failed.id.clone(), held.id.clone()];
11199        want.sort_unstable();
11200        assert_eq!(finished_ids, want);
11201    }
11202
11203    #[test]
11204    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11205        for short in [false, true] {
11206            let dir = tempfile::tempdir().unwrap();
11207            let queue = Queue::at(dir.path().join("queue"));
11208            let questions = ask::Questions::at(dir.path().join("questions"));
11209            let mut running = task();
11210            running.id = "20261013-192213-feb2".into();
11211            running.start("existing-run".into());
11212            queue.put(&mut running).unwrap();
11213            let mut middle = task();
11214            middle.id = "20261013-193611-ca5b".into();
11215            middle.block(
11216                vec![if short {
11217                    "feb2".into()
11218                } else {
11219                    running.id.clone()
11220                }],
11221                None,
11222            );
11223            queue.put(&mut middle).unwrap();
11224            let mut waiting = task();
11225            waiting.id = "20261013-202849-ee37".into();
11226            waiting.block(
11227                vec![if short {
11228                    "ca5b".into()
11229                } else {
11230                    middle.id.clone()
11231                }],
11232                Some("wait for implementation".into()),
11233            );
11234            queue.put(&mut waiting).unwrap();
11235            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11236            let inv = crate::blockers::Inventory::load(&queue, &questions);
11237            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11238            assert!(inv.stuck().is_empty());
11239            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11240            assert!(report.quarantined.is_empty());
11241            assert!(report.asked.is_empty());
11242            resolve_blockers(&queue, &questions);
11243            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11244            assert!(questions.list().is_empty());
11245            // Finishing the transitive prerequisite alone does not satisfy
11246            // the task's direct dependency.
11247            running.succeed();
11248            queue.put(&mut running).unwrap();
11249            resolve_blockers(&queue, &questions);
11250            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11251            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11252            middle = queue.get(&middle.id).unwrap();
11253            middle.succeed();
11254            queue.put(&mut middle).unwrap();
11255            resolve_blockers(&queue, &questions);
11256            let after = queue.get(&waiting.id).unwrap();
11257            assert_eq!(after.status, TaskStatus::Queued);
11258            assert!(after.blocked_by.is_empty());
11259            assert_eq!(after.instruction, waiting.instruction);
11260        }
11261    }
11262
11263    #[test]
11264    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11265        for future_schema in [false, true] {
11266            let name = "20261013-193611-ca5b";
11267            let mut future = task();
11268            future.id = name.into();
11269            future.schema = crate::queue::SCHEMA + 1;
11270            let contents = if future_schema {
11271                serde_json::to_string(&future).unwrap()
11272            } else {
11273                "corrupt".into()
11274            };
11275            let dir = tempfile::tempdir().unwrap();
11276            let queue = Queue::at(dir.path().join("queue"));
11277            let questions = ask::Questions::at(dir.path().join("questions"));
11278            let mut waiting = task();
11279            waiting.id = "20261013-202849-ee37".into();
11280            waiting.block(vec!["ca5b".into()], None);
11281            queue.put(&mut waiting).unwrap();
11282            std::fs::write(queue.path_of(name), contents).unwrap();
11283            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11284            assert!(
11285                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11286            );
11287            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11288            assert!(report.asked.is_empty());
11289            resolve_blockers(&queue, &questions);
11290            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11291            assert!(questions.list().is_empty());
11292        }
11293        let dir = tempfile::tempdir().unwrap();
11294        let queue = Queue::at(dir.path().join("queue"));
11295        let questions = ask::Questions::at(dir.path().join("questions"));
11296        let mut waiting = task();
11297        waiting.id = "20261013-202849-ee37".into();
11298        waiting.block(vec!["ca5b".into()], None);
11299        queue.put(&mut waiting).unwrap();
11300        let mut done = task();
11301        done.id = "20261013-193611-ca5b".into();
11302        done.succeed();
11303        queue.put(&mut done).unwrap();
11304        // An unreadable second match must not disappear from uniqueness
11305        // checks just because Queue::list skips it.
11306        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11307        assert!(queue.get("ca5b").is_err());
11308        assert_eq!(
11309            crate::queue::dependency(&queue, &questions, "ca5b"),
11310            crate::queue::Dependency::Ambiguous
11311        );
11312        resolve_blockers(&queue, &questions);
11313        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11314        assert!(report.asked.is_empty());
11315        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11316        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11317    }
11318
11319    #[test]
11320    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11321        for held in [false, true] {
11322            for question in [false, true] {
11323                for reference in ["ca5b", "20261013-193611-ca5b"] {
11324                    let dir = tempfile::tempdir().unwrap();
11325                    let queue = Queue::at(dir.path().join("queue"));
11326                    let questions = ask::Questions::at(dir.path().join("questions"));
11327                    let mut prerequisite = task();
11328                    prerequisite.id = "20261013-193611-ca5b".into();
11329                    prerequisite.start("existing-run".into());
11330                    queue.put(&mut prerequisite).unwrap();
11331                    let mut waiting = task();
11332                    waiting.id = "20261013-202849-ee37".into();
11333                    if held {
11334                        waiting.hold_machine(Some("waiting for separate consent".into()));
11335                    }
11336                    queue.put(&mut waiting).unwrap();
11337                    let reason = "Deleting saved data requires separate owner consent";
11338                    crate::conduct::apply(
11339                        &queue,
11340                        &questions,
11341                        &crate::conduct::Verdict {
11342                            decisions: vec![crate::conduct::Decision {
11343                                id: waiting.id.clone(),
11344                                blocked_by: vec![reference.into()],
11345                                question: question.then(|| "May the saved data be deleted?".into()),
11346                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11347                                reason: Some(reason.into()),
11348                                ..crate::conduct::Decision::default()
11349                            }],
11350                        },
11351                    )
11352                    .unwrap();
11353                    let before = queue.get(&waiting.id).unwrap();
11354                    if question {
11355                        assert_eq!(before.status, TaskStatus::Blocked);
11356                        let q = questions.get(&before.blocked_by[0]).unwrap();
11357                        assert_eq!(q.summary, "May the saved data be deleted?");
11358                        assert!(q.status.open());
11359                    } else {
11360                        assert_eq!(before.status, TaskStatus::Held);
11361                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11362                        assert!(recorded_reason.starts_with(reason));
11363                        if held {
11364                            assert!(recorded_reason.contains("waiting for separate consent"));
11365                        }
11366                    }
11367                    prerequisite.succeed();
11368                    queue.put(&mut prerequisite).unwrap();
11369                    resolve_blockers(&queue, &questions);
11370                    let after = queue.get(&waiting.id).unwrap();
11371                    assert_eq!(after.status, before.status);
11372                    assert_eq!(after.blocked_by, before.blocked_by);
11373                    assert_eq!(after.hold_reason, before.hold_reason);
11374                    assert_eq!(after.instruction, waiting.instruction);
11375                    if question {
11376                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11377                    }
11378                    assert!(
11379                        queue.next_runnable().is_none(),
11380                        "dependency completion is not consent"
11381                    );
11382                }
11383            }
11384        }
11385    }
11386
11387    #[test]
11388    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11389        let dir = tempfile::tempdir().unwrap();
11390        let queue = Queue::at(dir.path().join("queue"));
11391        let questions = ask::Questions::at(dir.path().join("questions"));
11392
11393        let mut dep = task();
11394        dep.id = "20260101-000001-dep0".to_owned();
11395        dep.succeed();
11396        queue.put(&mut dep).unwrap();
11397
11398        let mut still_going = task();
11399        still_going.id = "20260101-000002-dep1".to_owned();
11400        queue.put(&mut still_going).unwrap();
11401
11402        let mut blocked = task();
11403        blocked.id = "20260101-000003-main".to_owned();
11404        blocked.block(
11405            vec![dep.id.clone(), still_going.id.clone()],
11406            Some("waits on both".to_owned()),
11407        );
11408        queue.put(&mut blocked).unwrap();
11409
11410        resolve_blockers(&queue, &questions);
11411
11412        let after = queue.get(&blocked.id).unwrap();
11413        assert_eq!(
11414            after.status,
11415            TaskStatus::Blocked,
11416            "one dependency is still outstanding"
11417        );
11418        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11419    }
11420
11421    #[test]
11422    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11423        let dir = tempfile::tempdir().unwrap();
11424        let queue = Queue::at(dir.path().join("queue"));
11425        let questions = ask::Questions::at(dir.path().join("questions"));
11426
11427        let mut q = crate::ask::Question::new(
11428            "20260101-000001-main".to_owned(),
11429            crate::conduct::NODE.to_owned(),
11430            "conduct".to_owned(),
11431            "Which backend?".to_owned(),
11432            String::new(),
11433            Vec::new(),
11434        );
11435        questions.put(&mut q).unwrap();
11436        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11437            .unwrap();
11438        questions.put(&mut q).unwrap();
11439
11440        let mut blocked = task();
11441        blocked.id = "20260101-000001-main".to_owned();
11442        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11443        queue.put(&mut blocked).unwrap();
11444
11445        resolve_blockers(&queue, &questions);
11446
11447        let after = queue.get(&blocked.id).unwrap();
11448        assert_eq!(
11449            after.status,
11450            TaskStatus::Queued,
11451            "the only blocker resolved"
11452        );
11453        assert_eq!(after.answers.len(), 1);
11454        assert_eq!(after.answers[0].question, "Which backend?");
11455        assert_eq!(after.answers[0].answer, "SQLite");
11456
11457        // And the run this task starts next is told about it.
11458        let instruction = instruction_for(&after);
11459        assert!(instruction.contains("Which backend?"));
11460        assert!(instruction.contains("SQLite"));
11461    }
11462
11463    #[test]
11464    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11465        let dir = tempfile::tempdir().unwrap();
11466        let queue = Queue::at(dir.path().join("queue"));
11467        let questions = ask::Questions::at(dir.path().join("questions"));
11468
11469        let mut q = crate::ask::Question::new(
11470            "20260101-000001-main".to_owned(),
11471            crate::conduct::NODE.to_owned(),
11472            "conduct".to_owned(),
11473            "Is the setup done?".to_owned(),
11474            String::new(),
11475            Vec::new(),
11476        );
11477        q.abandon("no answer within 60s of asking");
11478        questions.put(&mut q).unwrap();
11479
11480        let mut blocked = task();
11481        blocked.id = "20260101-000001-main".to_owned();
11482        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11483        queue.put(&mut blocked).unwrap();
11484
11485        resolve_blockers(&queue, &questions);
11486
11487        let after = queue.get(&blocked.id).unwrap();
11488        assert_eq!(
11489            after.status,
11490            TaskStatus::Held,
11491            "never left blocked on nothing"
11492        );
11493        assert!(!after.operator_held(), "a machine hold, for triage");
11494        assert!(
11495            after
11496                .hold_reason
11497                .as_deref()
11498                .unwrap_or_default()
11499                .contains("went unanswered")
11500        );
11501    }
11502
11503    #[test]
11504    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11505        // Reproduces the reported bug (task 3958): a task held out of
11506        // attempts, blocked on a `crate::conduct` follow-up question, must
11507        // come back `held` once that question is answered - never `queued`,
11508        // whatever the answer said - or it silently re-enters the
11509        // competition queue with its attempts already exhausted.
11510        let dir = tempfile::tempdir().unwrap();
11511        let queue = Queue::at(dir.path().join("queue"));
11512        let questions = ask::Questions::at(dir.path().join("questions"));
11513
11514        let mut q = crate::ask::Question::new(
11515            "20260101-000001-main".to_owned(),
11516            crate::conduct::NODE.to_owned(),
11517            "conduct".to_owned(),
11518            "How should this be handled?".to_owned(),
11519            String::new(),
11520            Vec::new(),
11521        );
11522        questions.put(&mut q).unwrap();
11523        q.answer(crate::ask::Answer::Text(
11524            "leave it held, a human will look at it later".to_owned(),
11525        ))
11526        .unwrap();
11527        questions.put(&mut q).unwrap();
11528
11529        let mut held = task();
11530        held.id = "20260101-000001-main".to_owned();
11531        held.hold_machine(Some("out of attempts".to_owned()));
11532        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11533        queue.put(&mut held).unwrap();
11534
11535        resolve_blockers(&queue, &questions);
11536
11537        let after = queue.get(&held.id).unwrap();
11538        assert_eq!(after.status, TaskStatus::Held);
11539        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11540        assert_eq!(
11541            after.answers[0].answer,
11542            "leave it held, a human will look at it later"
11543        );
11544    }
11545
11546    #[test]
11547    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11548        let dir = tempfile::tempdir().unwrap();
11549        let queue = Queue::at(dir.path().join("queue"));
11550        let questions = ask::Questions::at(dir.path().join("questions"));
11551        let mut dep = task();
11552        dep.id = "20260101-000001-gone".to_owned();
11553        queue.put(&mut dep).unwrap();
11554        let mut blocked = task();
11555        blocked.id = "20260101-000003-main".to_owned();
11556        blocked.block(vec![dep.id.clone()], None);
11557        queue.put(&mut blocked).unwrap();
11558
11559        // Claimed, so `remove` cannot rewrite it and the resolver must.
11560        let claim = queue.claim(&blocked.id).unwrap();
11561        queue.remove(&dep.id, false, &questions).unwrap();
11562        drop(claim);
11563        resolve_blockers(&queue, &questions);
11564
11565        let after = queue.get(&blocked.id).unwrap();
11566        assert_eq!(after.status, TaskStatus::Queued);
11567        assert!(after.blocked_by.is_empty());
11568    }
11569
11570    #[test]
11571    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11572        // Reproduces the reported bug: a task blocked on a task id that was
11573        // removed (`magi task rm`, or deleted by hand) can never see that id
11574        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11575        // would otherwise leave the task `blocked` forever with no way for an
11576        // operator to find out why.
11577        let dir = tempfile::tempdir().unwrap();
11578        let queue = Queue::at(dir.path().join("queue"));
11579        let questions = ask::Questions::at(dir.path().join("questions"));
11580
11581        let mut still_going = task();
11582        still_going.id = "20260101-000002-dep1".to_owned();
11583        queue.put(&mut still_going).unwrap();
11584
11585        let mut blocked = task();
11586        blocked.id = "20260101-000003-main".to_owned();
11587        blocked.block(
11588            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11589            Some("waits on both".to_owned()),
11590        );
11591        queue.put(&mut blocked).unwrap();
11592
11593        resolve_blockers(&queue, &questions);
11594
11595        let after = queue.get(&blocked.id).unwrap();
11596        assert_eq!(
11597            after.status,
11598            TaskStatus::Held,
11599            "a missing dependency must not leave the task blocked forever"
11600        );
11601        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11602        assert!(after.blocked_by.is_empty());
11603        let reason = after.hold_reason.as_deref().unwrap_or_default();
11604        assert!(
11605            reason.contains("20260101-000001-gone"),
11606            "the missing id must be named so an operator can tell what happened: {reason}"
11607        );
11608        assert!(
11609            reason.contains(&still_going.id),
11610            "the still-valid dependency must not silently vanish from the record: {reason}"
11611        );
11612    }
11613
11614    #[test]
11615    fn instruction_for_is_unchanged_without_any_answers() {
11616        let t = task();
11617        assert_eq!(instruction_for(&t), t.instruction);
11618    }
11619
11620    #[test]
11621    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11622        let dir = tempfile::tempdir().unwrap();
11623        let q = Queue::at(dir.path().join("queue"));
11624        let src = dir.path().join("shot.png");
11625        std::fs::write(&src, "x").unwrap();
11626        let mut t = task();
11627        q.attach(&mut t, &[src]).unwrap();
11628        let paths = task_attachments(&q, &t).unwrap();
11629        assert_eq!(paths.len(), 1);
11630        assert!(paths[0].is_absolute() && paths[0].is_file());
11631        std::fs::remove_file(&paths[0]).unwrap();
11632        let err = task_attachments(&q, &t).unwrap_err().to_string();
11633        assert!(err.contains("shot.png"), "{err}");
11634    }
11635
11636    #[tokio::test]
11637    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11638        let dir = tempfile::tempdir().unwrap();
11639        let queue_path = dir.path().join("queue");
11640        let queue = Queue::at(queue_path.clone());
11641        let mut t = task();
11642        t.source = Source::Agent {
11643            run: "originating-chat".into(),
11644            node: crate::queue::CHAT_NODE.into(),
11645        };
11646        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11647            stage: "config-fetch",
11648            target: "origin/main".into(),
11649        });
11650        record_config_failure(&mut t, &fetch);
11651        t.hold_machine(Some(format!("{fetch:#}")));
11652        let fetch_key = t.chat_notice_due().unwrap();
11653        t.chat_notices.push(fetch_key.clone());
11654        queue.put(&mut t).unwrap();
11655
11656        let queue = Queue::at(queue_path);
11657        let mut t = queue.get(&t.id).unwrap();
11658        let a = dir.path().join("a.toml");
11659        let b = dir.path().join("b.toml");
11660        for (path, text, new_cause) in [
11661            (&a, "[graph", true),
11662            (&a, "[verify", false),
11663            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11664            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11665        ] {
11666            t.release_operator("test", None);
11667            std::fs::write(path, text).unwrap();
11668            let error = Config::discover_fetched(dir.path(), Some(path))
11669                .await
11670                .unwrap_err();
11671            record_config_failure(&mut t, &error);
11672            t.hold_machine(Some(format!("{error:#}")));
11673            let due = t.chat_notice_due();
11674            assert_eq!(due.is_some(), new_cause, "{error:#}");
11675            if let Some(key) = due {
11676                assert_ne!(key, fetch_key);
11677                t.chat_notices.push(key);
11678            }
11679        }
11680        t.succeed();
11681        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11682    }
11683
11684    #[test]
11685    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11686        let dir = tempfile::tempdir().unwrap();
11687        let queue_path = dir.path().join("queue");
11688        let queue = Queue::at(queue_path.clone());
11689        let mut t = task();
11690        t.source = crate::queue::Source::Agent {
11691            run: "originating-chat".into(),
11692            node: crate::queue::CHAT_NODE.into(),
11693        };
11694        let a = dir.path().join("a.png");
11695        let b = dir.path().join("b.png");
11696        std::fs::write(&a, "a").unwrap();
11697        std::fs::write(&b, "b").unwrap();
11698        queue.attach(&mut t, &[a, b]).unwrap();
11699        let paths = task_attachments(&queue, &t).unwrap();
11700        for path in &paths {
11701            std::fs::remove_file(path).unwrap();
11702        }
11703        let missing = task_attachments(&queue, &t).unwrap_err();
11704        t.attempts += 1;
11705        let reason = missing.to_string();
11706        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11707        let first = t.chat_notice_due().expect("first attachment notice");
11708        t.chat_notices.push(first.clone());
11709        queue.put(&mut t).unwrap();
11710
11711        let queue = Queue::at(queue_path.clone());
11712        let mut t = queue.get(&t.id).unwrap();
11713        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11714        t.release_operator("test", None);
11715        t.attempts += 1;
11716        let missing = task_attachments(&queue, &t).unwrap_err();
11717        t.fail_startup_target(
11718            "startup-attachments",
11719            missing.name,
11720            "same missing attachment with regenerated wording",
11721            1,
11722        );
11723        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11724
11725        std::fs::write(&paths[0], "restored").unwrap();
11726        t.release_operator("test", None);
11727        t.attempts += 1;
11728        let missing = task_attachments(&queue, &t).unwrap_err();
11729        let reason = missing.to_string();
11730        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11731        let second = t
11732            .chat_notice_due()
11733            .expect("different attachment must notify");
11734        assert_ne!(first, second);
11735        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11736    }
11737
11738    #[test]
11739    fn resumed_instruction_is_unchanged_without_any_answers() {
11740        let t = task();
11741        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11742    }
11743
11744    #[test]
11745    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11746        let mut t = task();
11747        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11748        // The run's own instruction on disk predates the answer: it is the
11749        // plain original text `Runner::start` saved before the operator was
11750        // ever asked anything.
11751        let old = t.instruction.clone();
11752
11753        let refreshed = resumed_instruction(&old, &t);
11754        assert!(refreshed.starts_with(&old), "the original text is kept");
11755        assert!(refreshed.contains("Which backend?"));
11756        assert!(refreshed.contains("SQLite"));
11757    }
11758
11759    #[test]
11760    fn resumed_instruction_keeps_an_original_answers_heading() {
11761        let mut t = task();
11762        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11763        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11764
11765        let refreshed = resumed_instruction(&t.instruction, &t);
11766
11767        assert!(
11768            refreshed.starts_with(&t.instruction),
11769            "an answers heading in the original instruction is not the appended block"
11770        );
11771        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11772        assert!(refreshed.contains("Which backend?"));
11773        assert!(refreshed.contains("SQLite"));
11774
11775        let repeated = resumed_instruction(&refreshed, &t);
11776        assert_eq!(
11777            repeated, refreshed,
11778            "only the final appended block is refreshed"
11779        );
11780    }
11781
11782    #[test]
11783    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11784        let mut t = task();
11785        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11786
11787        // A first resume appends the block; a second resume of the same run,
11788        // with no new answer in between, must reproduce exactly the same
11789        // text rather than appending the block a second time.
11790        let once = resumed_instruction(&t.instruction, &t);
11791        let twice = resumed_instruction(&once, &t);
11792        assert_eq!(once, twice);
11793        assert_eq!(once.matches("Which backend?").count(), 1);
11794
11795        // A later answer replaces the block wholesale rather than growing it.
11796        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11797        let refreshed = resumed_instruction(&once, &t);
11798        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11799        assert!(refreshed.contains("Which backend?"));
11800        assert!(refreshed.contains("Which cache?"));
11801    }
11802
11803    #[test]
11804    fn prepare_instruction_covers_all_three_starters() {
11805        let mut t = task();
11806        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11807
11808        // Start: a fresh run gets the task text plus every answer so far —
11809        // exactly `instruction_for`.
11810        assert_eq!(
11811            prepare_instruction(&Starter::Start, None, &t),
11812            Some(instruction_for(&t))
11813        );
11814
11815        // Resume: the run's prior instruction is refreshed with the answer,
11816        // not discarded and not left stale.
11817        let old = t.instruction.clone();
11818        assert_eq!(
11819            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11820            Some(resumed_instruction(&old, &t))
11821        );
11822
11823        // Review: a review-only pass builds its own instruction from the
11824        // branch's history in `crate::graph`, with no task statement at all -
11825        // this boundary must leave it alone.
11826        assert_eq!(
11827            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11828            None
11829        );
11830    }
11831
11832    #[test]
11833    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11834        assert_eq!(
11835            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11836            Starter::Review("magi/eba2/A".to_owned())
11837        );
11838    }
11839
11840    #[test]
11841    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11842        assert_eq!(
11843            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11844            Starter::Start,
11845            "a vanished review branch must not fall back to resuming the old run either"
11846        );
11847    }
11848
11849    #[test]
11850    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11851        let mut t = task();
11852        t.start("old-run".to_owned());
11853        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11854        t.release();
11855        let branch = t.review_branch.take();
11856        assert_eq!(
11857            choose_starter(branch.as_deref(), true, Some("old-run")),
11858            Starter::Review("magi/eba2/A".to_owned()),
11859            "a review wins over resuming the old run"
11860        );
11861    }
11862
11863    #[test]
11864    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11865        assert_eq!(
11866            choose_starter(None, false, Some("some-run")),
11867            Starter::Resume("some-run".to_owned())
11868        );
11869        assert_eq!(choose_starter(None, false, None), Starter::Start);
11870    }
11871
11872    #[test]
11873    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11874        let mut released = task();
11875        released.start("stalled-run".to_owned());
11876        released.requeue();
11877        let unfinished = (!released.fresh_start)
11878            .then(|| Some("stalled-run".to_owned()))
11879            .flatten();
11880        assert_eq!(
11881            choose_starter(None, false, unfinished.as_deref()),
11882            Starter::Start,
11883            "release keeps run history but must not resume it"
11884        );
11885        assert_eq!(released.runs, ["stalled-run"]);
11886    }
11887
11888    #[test]
11889    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
11890        let dir = tempfile::tempdir().unwrap();
11891        let queue = Queue::at(dir.path().join("queue"));
11892        let mut state = run_state(RunStatus::Blocked);
11893        state.merge_decision = Some(crate::merge_decision::Decision {
11894            question: "hold-inquiry".into(),
11895            target: crate::merge_decision::Target {
11896                pr: "https://example.test/pull/1".into(),
11897                head: "reviewed-head".into(),
11898                language: "en".into(),
11899            },
11900            choice: land::HOLD.into(),
11901            closed: false,
11902            replacement_run: None,
11903            replacement_pr: None,
11904        });
11905        let mut t = task();
11906        t.start(state.id.clone());
11907        settle_and_diagnose(
11908            &mut t,
11909            Verdict {
11910                status: RunStatus::Blocked,
11911                left_pr: true,
11912                quota_hit: false,
11913                parked: false,
11914                no_viable_candidates: false,
11915            },
11916            "held",
11917            2,
11918            &state,
11919        );
11920        queue.put(&mut t).unwrap();
11921        t.release_operator("chat", None);
11922        t.edit("revised".into(), "revised instruction".into())
11923            .unwrap();
11924        queue.put(&mut t).unwrap();
11925        drop(state);
11926        assert_eq!(
11927            queue
11928                .get(&t.id)
11929                .unwrap()
11930                .decision_effects
11931                .get("hold-inquiry"),
11932            Some(&format!("decision: {}", land::HOLD))
11933        );
11934    }
11935
11936    fn stopped_public_run(status: RunStatus) -> RunState {
11937        let mut state = run_state(status);
11938        state.driver_exited = true;
11939        state.config.graph.land = true;
11940        state.config.graph.review_rounds = 1;
11941        state.reviews = vec![review_round(1)];
11942        state.merge = Some(crate::run::MergeOutcome {
11943            mode: MergeMode::Pr,
11944            ok: false,
11945            detail: "landing stopped".into(),
11946            empty: false,
11947        });
11948        state.pr = Some(crate::run::PrRecord {
11949            url: "https://example.test/pull/1".into(),
11950            number: 1,
11951            state: "open".into(),
11952            checks: "red".into(),
11953            round: 1,
11954            rounds: 1,
11955            red_at_merge: Vec::new(),
11956        });
11957        state
11958    }
11959
11960    #[test]
11961    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11962        for status in [RunStatus::Blocked, RunStatus::Gating] {
11963            let home = tempfile::tempdir().unwrap();
11964            let mut state = stopped_public_run(status);
11965            state.save_under(home.path()).unwrap();
11966            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11967            assert!(!exhausted_review_budget(&state));
11968            let mut task = held_task_with(&state.id);
11969            task.release();
11970            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11971            assert_eq!(
11972                choose_starter(None, false, unfinished.as_deref()),
11973                Starter::Resume(state.id.clone())
11974            );
11975            let question = action_question(&state.id, resume_action(&state.id));
11976            assert_eq!(
11977                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11978                    state.clone()
11979                )),
11980                ActionDecision::Resume(state.id.clone())
11981            );
11982            // The control-plane command uses this same preflight before pinning.
11983            assert_eq!(
11984                crate::resume::validate(home.path(), &state.id).unwrap().id,
11985                state.id
11986            );
11987            let queue = Queue::at(home.path().join("queue"));
11988            let mut controlled = Task::new(
11989                "resume land".into(),
11990                state.instruction.clone(),
11991                state.repo.clone(),
11992                Source::Agent {
11993                    run: "talk".into(),
11994                    node: crate::queue::CHAT_NODE.into(),
11995                },
11996            );
11997            controlled.runs.push(state.id.clone());
11998            controlled.hold_machine(Some("land stopped".into()));
11999            queue.put(&mut controlled).unwrap();
12000            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12001            assert_eq!(resumed.status, TaskStatus::Queued);
12002            assert_eq!(
12003                resumed.resume_override.unwrap().pinned_run,
12004                Some(state.id.clone())
12005            );
12006            assert_eq!(resumed.attempts, 0);
12007        }
12008    }
12009
12010    #[test]
12011    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
12012        for review_rounds in [0, 1] {
12013            let home = tempfile::tempdir().unwrap();
12014            let mut state = run_state(RunStatus::Blocked);
12015            state.config.graph.review_rounds = review_rounds;
12016            if review_rounds > 0 {
12017                let mut review = review_round(1);
12018                review.clean = true;
12019                state.reviews = vec![review];
12020            }
12021            state.gate_ran = true;
12022            state.gate = vec![crate::run::CommandOutcome {
12023                command: "verify".into(),
12024                code: Some(1),
12025                output_tail: "gate failed after repair budget exhausted".into(),
12026                duration_ms: 0,
12027                resource_blocked: false,
12028            }];
12029            state.save_under(home.path()).unwrap();
12030            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12031            assert!(exhausted_review_budget(&state));
12032            let mut task = held_task_with(&state.id);
12033            task.release();
12034            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
12035            let question = action_question(&state.id, resume_action(&state.id));
12036            assert_ne!(
12037                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12038                    state.clone()
12039                )),
12040                ActionDecision::Resume(state.id.clone())
12041            );
12042            let error = crate::resume::validate(home.path(), &state.id)
12043                .unwrap_err()
12044                .to_string();
12045            assert!(!error.contains("review budget exhausted"), "{error}");
12046            assert!(
12047                error.contains(if review_rounds == 0 {
12048                    "review is disabled"
12049                } else {
12050                    "gate already ran"
12051                }),
12052                "{error}"
12053            );
12054
12055            // An unexecuted gate still has work to do with or without reviews.
12056            state.gate_ran = false;
12057            state.gate.clear();
12058            assert!(!exhausted_review_budget(&state));
12059            assert_eq!(
12060                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
12061                Some(state.id)
12062            );
12063        }
12064    }
12065
12066    #[test]
12067    fn resource_blocked_verification_resumes_the_same_run() {
12068        for (kind, stage) in [
12069            ("cache", "clean"),
12070            ("coordination", "clean"),
12071            ("cache", "review-e2e"),
12072            ("coordination", "no-reviews"),
12073            ("coordination", "handoff"),
12074        ] {
12075            let home = tempfile::tempdir().unwrap();
12076            let mut state = run_state(RunStatus::Blocked);
12077            state.config.graph.review_rounds = 1;
12078            let mut review = review_round(1);
12079            review.clean = true;
12080            state.reviews = vec![review];
12081            if stage == "review-e2e" {
12082                let review = &mut state.reviews[0];
12083                review.clean = false;
12084                review.blocking = 1;
12085                review.e2e = vec![crate::run::CommandOutcome {
12086                    command: "verify".into(),
12087                    code: None,
12088                    output_tail: "resource wait expired".into(),
12089                    duration_ms: 0,
12090                    resource_blocked: true,
12091                }];
12092            } else if stage == "no-reviews" {
12093                state.config.graph.review_rounds = 0;
12094                state.reviews.clear();
12095            } else if stage == "handoff" {
12096                // A completed final verification can hand off to the gate
12097                // even when the review still carries contested findings.
12098                let review = &mut state.reviews[0];
12099                review.clean = false;
12100                review.blocking = 1;
12101                review.e2e = vec![crate::run::CommandOutcome {
12102                    command: "verify".into(),
12103                    code: Some(0),
12104                    output_tail: String::new(),
12105                    duration_ms: 0,
12106                    resource_blocked: false,
12107                }];
12108            }
12109            state.gate_ran = false;
12110            state.resource_block = Some(crate::run::ResourceBlock {
12111                cause: crate::run::ResourceBlockCause::Other,
12112                node: if stage == "review-e2e" {
12113                    "review"
12114                } else {
12115                    "gate"
12116                }
12117                .into(),
12118                kind: kind.into(),
12119                detail: "resource wait expired".into(),
12120                at: jiff::Timestamp::now(),
12121            });
12122            state.save_under(home.path()).unwrap();
12123            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12124            assert!(!exhausted_review_budget(&state));
12125            let mut task = held_task_with(&state.id);
12126            task.release();
12127            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12128            assert_eq!(
12129                choose_starter(None, false, unfinished.as_deref()),
12130                Starter::Resume(state.id.clone())
12131            );
12132            let question = action_question(&state.id, resume_action(&state.id));
12133            assert_eq!(
12134                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12135                    state.clone()
12136                )),
12137                ActionDecision::Resume(state.id.clone())
12138            );
12139            assert_eq!(
12140                crate::resume::validate(home.path(), &state.id).unwrap().id,
12141                state.id
12142            );
12143            let queue = Queue::at(home.path().join("queue"));
12144            let mut controlled = Task::new(
12145                "resume verification".into(),
12146                state.instruction.clone(),
12147                state.repo.clone(),
12148                Source::Agent {
12149                    run: "talk".into(),
12150                    node: crate::queue::CHAT_NODE.into(),
12151                },
12152            );
12153            controlled.runs.push(state.id.clone());
12154            controlled.hold_machine(Some("verification resource unavailable".into()));
12155            queue.put(&mut controlled).unwrap();
12156            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12157            assert_eq!(resumed.status, TaskStatus::Queued);
12158            assert_eq!(
12159                resumed.resume_override.unwrap().pinned_run,
12160                Some(state.id.clone())
12161            );
12162            assert_eq!(resumed.attempts, 0);
12163
12164            // A genuinely unresolved final review still exhausts the budget.
12165            state.config.graph.review_rounds = 1;
12166            let mut unresolved = review_round(1);
12167            unresolved.blocking = 1;
12168            state.reviews = vec![unresolved];
12169            state.resource_block = None;
12170            state.save_under(home.path()).unwrap();
12171            assert!(exhausted_review_budget(&state));
12172            assert!(crate::resume::validate(home.path(), &state.id).is_err());
12173        }
12174    }
12175
12176    #[tokio::test]
12177    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
12178        if !crate::standalone_test(
12179            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
12180        ) {
12181            return;
12182        }
12183        let home = tempfile::tempdir().unwrap();
12184        let mut owner = stopped_public_run(RunStatus::Blocked);
12185        owner.save_under(home.path()).unwrap();
12186        let history = vec![owner.id.clone()];
12187        let repo = owner.repo.clone();
12188        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
12189        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
12190        let initial =
12191            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
12192        assert!(
12193            initial.is_pending(),
12194            "a busy record must not hold or resume the task"
12195        );
12196        owner.retired_to = Some("20260101-000001-bbbb".into());
12197        owner.save_under(home.path()).unwrap();
12198        drop(lock);
12199        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
12200            .await
12201            .expect("ownership lock released")
12202            .expect("read settled owner");
12203        assert!(
12204            result.is_none(),
12205            "the retired owner must not be resumed from a stale read"
12206        );
12207    }
12208
12209    #[tokio::test]
12210    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
12211        if !crate::standalone_test(
12212            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
12213        ) {
12214            return;
12215        }
12216        let home = tempfile::tempdir().unwrap();
12217        let mut owner = stopped_public_run(RunStatus::Blocked);
12218        let repo = tempfile::tempdir().unwrap();
12219        crate::git::git(repo.path(), &["init"]).await.unwrap();
12220        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12221        owner.id = "20260101-000000-aaaa".into();
12222        owner.save_under(home.path()).unwrap();
12223        let mut successor = run_state(RunStatus::Blocked);
12224        successor.id = "20260101-000001-bbbb".into();
12225        successor.save_under(home.path()).unwrap();
12226        let runs = vec![owner.id.clone(), successor.id.clone()];
12227        assert_eq!(
12228            public_resume_owner(home.path(), &runs, &owner.repo)
12229                .await
12230                .unwrap()
12231                .unwrap()
12232                .id,
12233            owner.id
12234        );
12235        let subdir = owner.repo.join("nested");
12236        std::fs::create_dir(&subdir).unwrap();
12237        assert_eq!(
12238            public_resume_owner(home.path(), &runs, &subdir)
12239                .await
12240                .unwrap()
12241                .unwrap()
12242                .id,
12243            owner.id
12244        );
12245        #[cfg(unix)]
12246        {
12247            let alias = home.path().join("repo-alias");
12248            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12249            assert_eq!(
12250                public_resume_owner(home.path(), &runs, &alias.join("nested"))
12251                    .await
12252                    .unwrap()
12253                    .unwrap()
12254                    .id,
12255                owner.id
12256            );
12257        }
12258        let different = tempfile::tempdir().unwrap();
12259        crate::git::git(different.path(), &["init"]).await.unwrap();
12260        assert!(
12261            public_resume_owner(home.path(), &runs, different.path())
12262                .await
12263                .is_err()
12264        );
12265        std::fs::remove_file(
12266            home.path()
12267                .join("runs")
12268                .join(&successor.id)
12269                .join("run.json"),
12270        )
12271        .unwrap();
12272        assert!(
12273            public_resume_owner(home.path(), &runs, &owner.repo)
12274                .await
12275                .is_err()
12276        );
12277    }
12278
12279    #[test]
12280    fn an_ordinary_release_keeps_a_resumable_run_available() {
12281        let mut released = task();
12282        released.start("stalled-run".to_owned());
12283        released.release();
12284        let unfinished = (!released.fresh_start)
12285            .then(|| Some("stalled-run".to_owned()))
12286            .flatten();
12287        assert_eq!(
12288            choose_starter(None, false, unfinished.as_deref()),
12289            Starter::Resume("stalled-run".to_owned()),
12290            "manual release must preserve the normal resume path"
12291        );
12292    }
12293
12294    #[test]
12295    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12296        use crate::handover::{ResumeRefusal, resume_refusal_under};
12297        let home = tempfile::tempdir().unwrap();
12298        let mut exhausted = run_state(RunStatus::Blocked);
12299        exhausted.driver_exited = true;
12300        exhausted.config.graph.review_rounds = 3;
12301        exhausted.reviews = (1..=3).map(review_round).collect();
12302        for refusal in [
12303            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12304            ResumeRefusal::Status(RunStatus::Ready),
12305            ResumeRefusal::Released("20261022-000000-aaaa".into()),
12306            ResumeRefusal::Retired("retirement-successor".into()),
12307            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12308        ] {
12309            let mut state = exhausted.clone();
12310            let expected = match refusal {
12311                ResumeRefusal::Status(_) => {
12312                    state.status = RunStatus::Ready;
12313                    "status `ready`"
12314                }
12315                ResumeRefusal::Released(ref target) => {
12316                    state.released_to = Some(target.clone());
12317                    "execution was released"
12318                }
12319                ResumeRefusal::Retired(ref target) => {
12320                    state.retired_to = Some(target.clone());
12321                    "execution was retired"
12322                }
12323                ResumeRefusal::OwnershipTransferred(ref target) => {
12324                    state.pr_taken_over_by = Some(target.clone());
12325                    "PR ownership was transferred"
12326                }
12327                _ => "review budget exhausted (3/3 rounds used)",
12328            };
12329            assert_eq!(
12330                resume_refusal_under(&state, Some(home.path())),
12331                Some(refusal.clone())
12332            );
12333            assert_eq!(
12334                refusal.successor(),
12335                state
12336                    .released_to
12337                    .as_deref()
12338                    .or(state.retired_to.as_deref())
12339                    .or(state.pr_taken_over_by.as_deref())
12340            );
12341            state.save_under(home.path()).unwrap();
12342            let queue = Queue::at(home.path().join("queue"));
12343            let mut task = Task::new(
12344                "retained implementation".into(),
12345                state.instruction.clone(),
12346                state.repo.clone(),
12347                Source::Agent {
12348                    run: "talk".into(),
12349                    node: crate::queue::CHAT_NODE.into(),
12350                },
12351            );
12352            task.runs.push(state.id.clone());
12353            task.hold_machine(Some("stopped".into()));
12354            queue.put(&mut task).unwrap();
12355            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12356            let before_run = serde_json::to_value(&state).unwrap();
12357            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12358                .unwrap_err()
12359                .to_string();
12360            assert!(error.contains(expected), "{error}");
12361            assert!(!error.contains("only a stalled or blocked"), "{error}");
12362            if matches!(refusal, ResumeRefusal::Status(_)) {
12363                assert!(
12364                    error.contains("is final; there is nothing left to resume"),
12365                    "{error}"
12366                );
12367            }
12368            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12369                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12370                assert!(error.contains("review-only successor with a new review budget"));
12371                assert!(error.contains("does not resume this run"));
12372            }
12373            for target in [
12374                &state.released_to,
12375                &state.retired_to,
12376                &state.pr_taken_over_by,
12377            ]
12378            .into_iter()
12379            .flatten()
12380            {
12381                let short = if state.retired_to.as_ref() == Some(target) {
12382                    target.as_str()
12383                } else {
12384                    crate::run::short_of(target)
12385                };
12386                assert!(
12387                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12388                    "{error}"
12389                );
12390                if short != target {
12391                    assert!(!error.contains(target), "full successor id leaked: {error}");
12392                }
12393            }
12394            assert_eq!(
12395                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12396                before_task
12397            );
12398            assert_eq!(
12399                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12400                    .unwrap(),
12401                before_run
12402            );
12403            let question = action_question(&state.id, resume_action(&state.id));
12404            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12405                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12406                    RunState::load_under(id, home.path())
12407                });
12408                let ActionDecision::Refuse(detail) = decision else {
12409                    panic!(
12410                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12411                        state.id,
12412                        home.path().display()
12413                    );
12414                };
12415                assert!(detail.contains(expected), "{detail}");
12416            }
12417        }
12418        // Preserve predicate ordering, while keeping every recorded destination visible.
12419        exhausted.status = RunStatus::Ready;
12420        exhausted.released_to = Some("released".into());
12421        exhausted.retired_to = Some("retired".into());
12422        exhausted.pr_taken_over_by = Some("owner".into());
12423        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12424        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12425        let detail = reason.diagnostic(&exhausted);
12426        for target in ["released", "retired", "owner"] {
12427            assert!(detail.contains(&format!("magi show {target}")));
12428        }
12429    }
12430
12431    #[test]
12432    fn resume_action_ignores_question_checkpoints_in_another_home() {
12433        crate::run::pin_test_home();
12434        let home = tempfile::tempdir().unwrap();
12435        let mut state = run_state(RunStatus::Blocked);
12436        // The private directory reserves this fixture's identity even while
12437        // other tests write questions into the process-wide store.
12438        state.id = format!(
12439            "resume-context-{}",
12440            home.path().file_name().unwrap().to_str().unwrap()
12441        );
12442        state.driver_exited = true;
12443        state.config.graph.review_rounds = 1;
12444        state.reviews = vec![review_round(1)];
12445        state.save_under(home.path()).unwrap();
12446        let task = held_task_with(&state.id);
12447        let answer = action_question(&state.id, resume_action(&state.id));
12448        let mut checkpoint = approval_question(&state.id);
12449        let foreign = Questions::open();
12450        foreign.put(&mut checkpoint).unwrap();
12451        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
12452        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12453            RunState::load_under(id, home.path())
12454        });
12455        let matching: Vec<_> = foreign
12456            .list()
12457            .into_iter()
12458            .filter(|q| q.run == state.id && q.status.open())
12459            .collect();
12460        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
12461        assert!(
12462            matches!(decision, ActionDecision::Refuse(_)),
12463            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
12464            state.id,
12465            home.path().display(),
12466            crate::run::test_home().display()
12467        );
12468        assert_eq!(
12469            refusal,
12470            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
12471        );
12472        let local = Questions::at(home.path().join("questions"));
12473        for status in [
12474            ask::QuestionStatus::Open,
12475            ask::QuestionStatus::Answered,
12476            ask::QuestionStatus::Abandoned,
12477        ] {
12478            let mut question = checkpoint.clone();
12479            match status {
12480                ask::QuestionStatus::Open => {}
12481                ask::QuestionStatus::Answered => {
12482                    question
12483                        .answer(ask::Answer::Choice(question.choices[0].clone()))
12484                        .unwrap();
12485                }
12486                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
12487            }
12488            local.put(&mut question).unwrap();
12489            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12490                RunState::load_under(id, home.path())
12491            });
12492            if status.open() {
12493                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
12494            } else {
12495                assert!(
12496                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
12497                    "status={status:?}, decision={decision:?}"
12498                );
12499            }
12500        }
12501    }
12502
12503    #[test]
12504    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
12505        let home = tempfile::tempdir().unwrap();
12506        let mut state = run_state(RunStatus::Stalled);
12507        state.id = format!(
12508            "resume-driver-{}",
12509            home.path().file_name().unwrap().to_str().unwrap()
12510        );
12511        state.driver_claimed = Some(false);
12512        state.save_under(home.path()).unwrap();
12513        let task = held_task_with(&state.id);
12514        let question = action_question(&state.id, resume_action(&state.id));
12515        let decide = || {
12516            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
12517                RunState::load_under(id, home.path())
12518            })
12519        };
12520        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
12521        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
12522        assert_eq!(
12523            decide(),
12524            ActionDecision::Refuse("run already has a live driver".into())
12525        );
12526        drop(lease);
12527        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
12528    }
12529
12530    #[test]
12531    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12532        let home = tempfile::tempdir().unwrap();
12533        let mut state = run_state(RunStatus::Blocked);
12534        state.driver_exited = true;
12535        state.config.graph.review_rounds = 1;
12536        state.reviews = vec![review_round(1)];
12537        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12538        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12539            let mut saved = state.clone();
12540            match checkpoint {
12541                "publication" => saved.pr_publication_pending = true,
12542                "approval" => {
12543                    saved.land_approval = Some(crate::run::LandApproval {
12544                        question: "approval".into(),
12545                        head: "head".into(),
12546                    })
12547                }
12548                "armed" => saved.land_armed_head = Some("head".into()),
12549                "landing" => saved.status = RunStatus::Landing,
12550                _ => {
12551                    let mut question = ask::Question::new(
12552                        saved.id.clone(),
12553                        "review".into(),
12554                        "review-1".into(),
12555                        "continue?".into(),
12556                        String::new(),
12557                        vec!["continue".into()],
12558                    );
12559                    ask::Questions::at(home.path().join("questions"))
12560                        .put(&mut question)
12561                        .unwrap();
12562                }
12563            }
12564            saved.save_under(home.path()).unwrap();
12565            assert!(
12566                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12567                "{checkpoint}"
12568            );
12569            assert!(
12570                crate::resume::validate(home.path(), &saved.id).is_ok(),
12571                "{checkpoint}"
12572            );
12573        }
12574    }
12575
12576    #[test]
12577    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12578        let mut state = run_state(RunStatus::Blocked);
12579        state.config.graph.review_rounds = 3;
12580        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12581        assert!(exhausted_review_budget(&state));
12582
12583        // One round still unused: resuming can still ask a reviewer something.
12584        state.reviews.pop();
12585        assert!(!exhausted_review_budget(&state));
12586
12587        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12588        // count: only a `Blocked` run re-enters the review loop on resume.
12589        let mut stalled = run_state(RunStatus::Stalled);
12590        stalled.config.graph.review_rounds = 1;
12591        stalled.reviews = vec![review_round(1)];
12592        assert!(!exhausted_review_budget(&stalled));
12593    }
12594
12595    fn review_round(round: usize) -> crate::run::ReviewRound {
12596        crate::run::ReviewRound {
12597            round,
12598            head: "deadbeef".to_owned(),
12599            verified_head: None,
12600            verified_at: None,
12601            reviews: Vec::new(),
12602            e2e: Vec::new(),
12603            verify_retried: false,
12604            e2e_deferred: false,
12605            e2e_defer_reason: None,
12606            fix: None,
12607            blocking: 0,
12608            answered: 1,
12609            expected: 1,
12610            clean: false,
12611            progressed: true,
12612            vote_split: false,
12613            reconsideration: Vec::new(),
12614            verdict: None,
12615        }
12616    }
12617
12618    #[test]
12619    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12620        let mut run = RunState::new(
12621            PathBuf::from("/repo"),
12622            "main".to_owned(),
12623            "abc1234def".to_owned(),
12624            "add retries".to_owned(),
12625            Config::default(),
12626        );
12627        run.status = RunStatus::Judging;
12628        run.parked = true;
12629        let mut task = Task::new(
12630            "add retries".to_owned(),
12631            "add retries".to_owned(),
12632            PathBuf::from("/repo"),
12633            crate::queue::Source::Human,
12634        );
12635        task.status = TaskStatus::Failed;
12636        task.runs = vec![run.id.clone()];
12637        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12638        assert!(with(&task, &run), "parked after judging is the case");
12639        let mut parked_task = task.clone();
12640        parked_task.status = TaskStatus::Parked;
12641        assert!(with(&parked_task, &run), "the Parked status is the case");
12642
12643        let mut not_parked = run.clone();
12644        not_parked.parked = false;
12645        not_parked.status = RunStatus::Stalled;
12646        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12647
12648        let mut fresh = task.clone();
12649        fresh.fresh_start = true;
12650        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12651
12652        let mut review = task.clone();
12653        review.review_branch = Some("magi/x/A".to_owned());
12654        assert!(!with(&review, &run), "review is ranked before resume");
12655
12656        let mut held = task.clone();
12657        held.status = TaskStatus::Held;
12658        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12659
12660        let mut released = run.clone();
12661        released.released_to = Some("20260901-000000-new1".to_owned());
12662        assert!(!with(&task, &released), "nothing left to resume into");
12663
12664        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12665            "unreadable"
12666        )));
12667    }
12668
12669    #[test]
12670    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12671        let mut released = RunState::new(
12672            PathBuf::from("/repo"),
12673            "main".to_owned(),
12674            "abc1234def".to_owned(),
12675            "add retries".to_owned(),
12676            Config::default(),
12677        );
12678        released.status = RunStatus::Blocked;
12679        assert_eq!(
12680            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12681            Some(released.id.clone())
12682        );
12683        released.released_to = Some("20260901-000000-new1".to_owned());
12684        assert_eq!(
12685            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12686            None,
12687            "there is nothing left to resume it into"
12688        );
12689    }
12690
12691    #[test]
12692    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12693        // Mirrors the failure this exists to close: a task's last run ended
12694        // `Blocked` with the review budget spent, `crate::conduct` chose
12695        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12696        // evidence), and without this check `attempt` would go on treating
12697        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12698        // review loop iterates zero times over an already-spent budget, so
12699        // the resumed run settles right back to `Blocked` having asked nobody
12700        // anything, and `Requeue`'s promised fresh competition never happens.
12701        let mut exhausted = RunState::new(
12702            PathBuf::from("/repo"),
12703            "main".to_owned(),
12704            "abc1234def".to_owned(),
12705            "add retries".to_owned(),
12706            Config::default(),
12707        );
12708        exhausted.status = RunStatus::Blocked;
12709        exhausted.config.graph.review_rounds = 1;
12710        exhausted.reviews = vec![review_round(1)];
12711
12712        assert_eq!(
12713            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12714            None,
12715            "an exhausted `Blocked` run must not be offered as resumable"
12716        );
12717
12718        // A `Blocked` run with rounds still unused is genuinely worth
12719        // resuming, and must still be found.
12720        let mut has_budget_left = RunState::new(
12721            PathBuf::from("/repo"),
12722            "main".to_owned(),
12723            "abc1234def".to_owned(),
12724            "add retries".to_owned(),
12725            Config::default(),
12726        );
12727        has_budget_left.status = RunStatus::Blocked;
12728        has_budget_left.config.graph.review_rounds = 3;
12729        has_budget_left.reviews = vec![review_round(1)];
12730
12731        assert_eq!(
12732            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12733                Ok(has_budget_left.clone())
12734            }),
12735            Some(has_budget_left.id.clone())
12736        );
12737    }
12738
12739    #[test]
12740    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12741        let mut run = RunState::new(
12742            PathBuf::from("/repo"),
12743            "main".to_owned(),
12744            "abc1234def".to_owned(),
12745            "add retries".to_owned(),
12746            Config::default(),
12747        );
12748        run.status = RunStatus::Blocked;
12749        run.config.graph.review_rounds = 1;
12750        run.reviews = vec![review_round(1)];
12751        run.pr_publication_pending = true;
12752        assert_eq!(
12753            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12754            Some(run.id.clone()),
12755            "a spent review budget must not turn a failed publication into a re-competition"
12756        );
12757    }
12758
12759    #[test]
12760    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12761        let mut task = Task::new(
12762            "recover work".into(),
12763            "recover work".into(),
12764            PathBuf::from("/repo"),
12765            crate::queue::Source::Human,
12766        );
12767        let mut history = std::collections::BTreeMap::new();
12768        for index in 0..8 {
12769            let mut run = run_state(RunStatus::Blocked);
12770            run.id = format!("20260101-000000-{index:04}");
12771            run.base_commit = format!("upstream-{index}");
12772            // Seven empty newer attempts must not erase the old recovery owner.
12773            if index > 0 {
12774                run.candidates.clear();
12775            }
12776            task.runs.extend([run.id.clone(), run.id.clone()]);
12777            history.insert(run.id.clone(), run);
12778            task.requeue();
12779        }
12780        let check = |task: &Task, starter: &Starter, limit| {
12781            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12782        };
12783        assert!(
12784            check(&task, &Starter::Start, 8)
12785                .unwrap()
12786                .contains("8 unretired")
12787        );
12788        assert!(check(&task, &Starter::Start, 9).is_none());
12789        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12790        task.release_operator("owner", None);
12791        assert_eq!(task.attempts, 0);
12792        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12793        assert!(check(&restored, &Starter::Start, 8).is_some());
12794        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12795        assert!(check(&restored, &Starter::Start, 0).is_none());
12796    }
12797
12798    #[test]
12799    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
12800        let tmp = tempfile::tempdir().unwrap();
12801        let mut task = Task::new(
12802            "recover selected PR".into(),
12803            "preserve implementation".into(),
12804            tmp.path().join("repo"),
12805            crate::queue::Source::Human,
12806        );
12807        let mut failed = run_state(RunStatus::Failed);
12808        failed.id = "20260101-000000-fail".into();
12809        failed.candidates.clear();
12810        failed.prep_complete = Some(false);
12811        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
12812        failed.startup = Some(crate::run::Startup {
12813            kind: "pr-recovery".into(),
12814            branch: Some("selected-public-head".into()),
12815            stage: "worktree-setup".into(),
12816            complete: false,
12817            failure: Some("setup modified a tracked file and failed".into()),
12818        });
12819        // Setup may fail before a candidate is recorded; its dirty worktree
12820        // still needs protection and consumes the independent retained bound.
12821        let worktree = failed.worktree_root().join("under-review");
12822        std::fs::create_dir_all(&worktree).unwrap();
12823        let retained_edit = worktree.join("implementation");
12824        std::fs::write(&retained_edit, "retained setup edit").unwrap();
12825        task.record_startup_failure(crate::run::StartupFailure {
12826            run: failed.id.clone(),
12827            stage: "worktree-setup".into(),
12828        });
12829        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12830        assert!(task.runs.is_empty() && task.passes.is_empty());
12831        assert_eq!(task.attempts, 0);
12832        let starter = Starter::Review("selected-public-head".into());
12833        assert!(
12834            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
12835                .unwrap()
12836                .contains("1 unretired")
12837        );
12838        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
12839        assert!(
12840            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
12841                .unwrap()
12842                .contains("Cannot verify")
12843        );
12844        // Older or mixed writers can link the same reservation in both lists.
12845        let mut mixed = task.clone();
12846        mixed.runs.push(failed.id.clone());
12847        mixed
12848            .startup_failures
12849            .push(task.startup_failures[0].clone());
12850        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
12851        failed.retired_to = Some("verified-recovery-owner".into());
12852        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
12853        assert!(
12854            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
12855                panic!("resuming the existing owner must not allocate a new attempt")
12856            })
12857            .is_none()
12858        );
12859        assert_eq!(
12860            std::fs::read_to_string(retained_edit).unwrap(),
12861            "retained setup edit"
12862        );
12863        assert!(task.runs.is_empty() && task.passes.is_empty());
12864        assert_eq!(task.attempts, 0);
12865    }
12866
12867    #[test]
12868    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12869        let mut task = Task::new(
12870            "recover work".into(),
12871            "recover work".into(),
12872            PathBuf::from("/repo"),
12873            crate::queue::Source::Human,
12874        );
12875        let mut run = run_state(RunStatus::Superseded);
12876        run.candidates.clear();
12877        task.runs.push(run.id.clone());
12878        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12879        run.retired_to = Some("authority".into());
12880        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12881        run.retired_to = None;
12882        run.released_to = Some("authority".into());
12883        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12884        assert!(
12885            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12886                .unwrap()
12887                .contains("Cannot verify")
12888        );
12889        // Resuming an existing owner needs no new inventory or worktree budget.
12890        assert!(
12891            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12892                panic!("resume must not load historical attempts")
12893            })
12894            .is_none()
12895        );
12896    }
12897
12898    #[test]
12899    fn retired_resume_requires_a_valid_same_repository_authority() {
12900        let mut source = run_state(RunStatus::Blocked);
12901        let mut empty = run_state(RunStatus::Blocked);
12902        empty.retired_to = Some(source.id.clone());
12903        let runs = vec![source.id.clone(), empty.id.clone()];
12904        let resolve = |source: &RunState, empty: &RunState| {
12905            unfinished_run_with(&runs, "fixture", |id| {
12906                if id == source.id {
12907                    Ok(source.clone())
12908                } else if id == empty.id {
12909                    Ok(empty.clone())
12910                } else {
12911                    bail!("unreadable authority")
12912                }
12913            })
12914        };
12915        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12916        assert_eq!(
12917            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12918            Starter::Resume(source.id.clone())
12919        );
12920        source.retired_to = Some(empty.id.clone());
12921        assert!(
12922            resolve(&source, &empty).is_none(),
12923            "cycles do not revive obsolete runs"
12924        );
12925        source.retired_to = None;
12926        source.repo = PathBuf::from("/another-repository");
12927        assert!(resolve(&source, &empty).is_none());
12928        source.repo = empty.repo.clone();
12929        source.released_to = Some("later".into());
12930        assert!(resolve(&source, &empty).is_none());
12931        empty.retired_to = Some("unlisted-run".into());
12932        assert!(resolve(&source, &empty).is_none());
12933    }
12934
12935    #[test]
12936    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12937        // A task whose history holds an *older* run that still looks
12938        // resumable (say, a competition `Runner::review` was started
12939        // alongside after that older run went `Stalled`) and a *newest* run
12940        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12941        // on this task must mean a fresh competition — falling back to the
12942        // stale, superseded `Stalled` run instead would resurrect history
12943        // nothing asked to revisit and silently defeat the requeue.
12944        let mut older_stalled = RunState::new(
12945            PathBuf::from("/repo"),
12946            "main".to_owned(),
12947            "abc1234def".to_owned(),
12948            "add retries".to_owned(),
12949            Config::default(),
12950        );
12951        older_stalled.status = RunStatus::Stalled;
12952
12953        let mut newest_exhausted = RunState::new(
12954            PathBuf::from("/repo"),
12955            "main".to_owned(),
12956            "abc1234def".to_owned(),
12957            "add retries".to_owned(),
12958            Config::default(),
12959        );
12960        newest_exhausted.status = RunStatus::Blocked;
12961        newest_exhausted.config.graph.review_rounds = 1;
12962        newest_exhausted.reviews = vec![review_round(1)];
12963
12964        assert_eq!(
12965            unfinished_run_with(
12966                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12967                "t",
12968                |_| Ok(newest_exhausted.clone())
12969            ),
12970            None,
12971            "the newest run is exhausted, so nothing here is worth resuming - \
12972             least of all the older, already-superseded run"
12973        );
12974    }
12975
12976    #[test]
12977    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12978        assert_eq!(
12979            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12980                Err(anyhow::anyhow!("fixture is absent"))
12981            }),
12982            None
12983        );
12984    }
12985
12986    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12987        let mut q = ask::Question::new(
12988            run.to_owned(),
12989            "implement".to_owned(),
12990            "impl-A".to_owned(),
12991            "continue?".to_owned(),
12992            String::new(),
12993            vec!["resume で続行する".to_owned(), "other".to_owned()],
12994        );
12995        q.actions.insert("resume で続行する".to_owned(), action);
12996        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12997            .unwrap();
12998        q
12999    }
13000
13001    fn held_task_with(run: &str) -> Task {
13002        let mut t = task();
13003        t.runs = vec![run.to_owned()];
13004        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
13005        t
13006    }
13007
13008    fn resume_action(run: &str) -> ask::ChoiceAction {
13009        ask::ChoiceAction::Resume { run: run.into() }
13010    }
13011
13012    #[test]
13013    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
13014        let home = crate::run::test_home();
13015        for parked in [false, true] {
13016            let mut t = task();
13017            t.start("A".into());
13018            t.start("B".into());
13019            assert_eq!(t.runs, vec!["A", "B"]);
13020            t.start("A".into());
13021            let mut resumed = run_state(RunStatus::Blocked);
13022            resumed.id = "A".into();
13023            resumed.parked = parked;
13024            resumed.driver_exited = true;
13025            t.hold_machine(Some("resumed run stopped".into()));
13026            let q = action_question("A", resume_action("A"));
13027            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13028            assert_eq!(
13029                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
13030                    assert_eq!(id, "A");
13031                    Ok(resumed.clone())
13032                }),
13033                ActionDecision::Resume("A".into())
13034            );
13035            assert_eq!(
13036                action_standing(&t, &action_question("B", resume_action("B"))),
13037                ActionStanding::Stale
13038            );
13039            t.release_operator("cli", None);
13040            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
13041                assert_eq!(id, "A");
13042                Ok(resumed.clone())
13043            });
13044            assert_eq!(
13045                choose_starter(None, false, unfinished.as_deref()),
13046                Starter::Resume("A".into())
13047            );
13048            assert_eq!(t.runs, vec!["B", "A"]);
13049        }
13050    }
13051
13052    #[test]
13053    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
13054        let home = crate::run::test_home();
13055        let mut state = crate::land::tests::repair_state(true, true);
13056        state.status = RunStatus::Landing;
13057        state.parked = true;
13058        state.driver_exited = true;
13059        let mut q = ask::Question::new(
13060            state.id.clone(),
13061            land::APPROVAL_NODE.into(),
13062            "land".into(),
13063            "Merge?".into(),
13064            String::new(),
13065            vec![land::APPROVE.into(), land::HOLD.into()],
13066        );
13067        q.id = state.id.clone();
13068        state.land_approval = Some(crate::run::LandApproval {
13069            question: q.id.clone(),
13070            head: "current-head".into(),
13071        });
13072        assert!(land::upgrade_repair_choice(&mut q, &state));
13073        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13074        let mut task = held_task_with(&state.id);
13075        task.status = TaskStatus::Parked;
13076        assert_eq!(
13077            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13078            ActionDecision::Resume(state.id.clone())
13079        );
13080        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13081        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
13082        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
13083        assert_eq!(
13084            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13085            ActionDecision::Resume(state.id.clone()),
13086            "a repair answer newer than the manual hold resumes the existing owner"
13087        );
13088        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13089        for answered_at in [q.answered_at, None] {
13090            let mut older = q.clone();
13091            older.answered_at = answered_at;
13092            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
13093                panic!("a later manual hold must prevent dispatch")
13094            });
13095            let ActionDecision::Refuse(reason) = refused else {
13096                panic!("expected an actionable refusal, got {refused:?}");
13097            };
13098            assert!(reason.contains("later operator decision"));
13099            assert!(reason.contains(&format!("magi task release {}", task.id)));
13100        }
13101        task.operator_decided_at = None;
13102        let mut superseded = state.clone();
13103        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
13104        assert_eq!(
13105            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
13106            ActionDecision::Stale
13107        );
13108        for case in 1..4 {
13109            let mut changed = state.clone();
13110            match case {
13111                1 => changed.status = RunStatus::Blocked,
13112                2 => changed.released_to = Some("new-owner".into()),
13113                _ => changed.land_approval.as_mut().unwrap().head.clear(),
13114            }
13115            assert!(matches!(
13116                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
13117                ActionDecision::Refuse(_)
13118            ));
13119        }
13120        assert!(matches!(
13121            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
13122                "missing owner"
13123            )),
13124            ActionDecision::Refuse(_)
13125        ));
13126        task.runs.push("replacement".into());
13127        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13128        assert_eq!(
13129            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
13130                "old owner must not load"
13131            )),
13132            ActionDecision::Stale
13133        );
13134    }
13135
13136    #[test]
13137    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
13138        let mut state = crate::land::tests::repair_state(true, true);
13139        state.status = RunStatus::Landing;
13140        state.parked = true;
13141        state.driver_exited = true;
13142        let mut q = ask::Question::new(
13143            state.id.clone(),
13144            land::APPROVAL_NODE.into(),
13145            "land".into(),
13146            "Merge?".into(),
13147            String::new(),
13148            vec![land::APPROVE.into(), land::HOLD.into()],
13149        );
13150        q.id = state.id.clone();
13151        state.land_approval = Some(crate::run::LandApproval {
13152            question: q.id.clone(),
13153            head: "current-head".into(),
13154        });
13155        state.save().unwrap();
13156        land::upgrade_repair_choice(&mut q, &state);
13157        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13158        Questions::open().put(&mut q).unwrap();
13159        let tmp = tempfile::tempdir().unwrap();
13160        let queue = Queue::at(tmp.path().join("queue"));
13161        let mut task = held_task_with(&state.id);
13162        task.status = TaskStatus::Parked;
13163        queue.put(&mut task).unwrap();
13164        let empty = Arc::new(tokio::sync::Semaphore::new(0));
13165        let free = Arc::new(tokio::sync::Semaphore::new(1));
13166        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
13167        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
13168        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
13169        assert!(claim.permit.is_some());
13170        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
13171        drop(claim);
13172        Questions::open()
13173            .update(&q.id, |q| {
13174                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
13175                Ok(())
13176            })
13177            .unwrap();
13178        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
13179        assert!(claim.permit.is_none());
13180        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
13181    }
13182
13183    #[test]
13184    fn decide_action_resumes_only_the_latest_resumable_run() {
13185        let home = crate::run::test_home();
13186        let t = held_task_with("r1");
13187        let q = action_question("r1", resume_action("r1"));
13188        let load = |s: RunState| move |_: &str| Ok(s);
13189        assert_eq!(
13190            decide_action(
13191                &home,
13192                &t,
13193                &q,
13194                &PHRASES_EN,
13195                load(run_state(RunStatus::Blocked))
13196            ),
13197            ActionDecision::Resume("r1".into())
13198        );
13199        // Not the latest run of the task.
13200        let q_other = action_question("r1", resume_action("r0"));
13201        assert!(matches!(
13202            decide_action(
13203                &home,
13204                &t,
13205                &q_other,
13206                &PHRASES_EN,
13207                load(run_state(RunStatus::Blocked))
13208            ),
13209            ActionDecision::Refuse(_)
13210        ));
13211        // A finished run cannot make progress.
13212        assert!(matches!(
13213            decide_action(
13214                &home,
13215                &t,
13216                &q,
13217                &PHRASES_EN,
13218                load(run_state(RunStatus::Ready))
13219            ),
13220            ActionDecision::Refuse(_)
13221        ));
13222        // A released one either.
13223        let mut released = run_state(RunStatus::Blocked);
13224        released.released_to = Some("elsewhere".into());
13225        assert!(matches!(
13226            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13227            ActionDecision::Refuse(_)
13228        ));
13229        // Unreadable state is a refusal, never a fresh competition.
13230        assert!(matches!(
13231            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13232            ActionDecision::Refuse(_)
13233        ));
13234    }
13235
13236    #[test]
13237    fn decide_action_ignores_a_question_about_an_earlier_run() {
13238        let home = crate::run::test_home();
13239        let mut t = held_task_with("r1");
13240        t.runs.push("r2".to_owned());
13241        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13242        assert_eq!(
13243            decide_action(
13244                &home,
13245                &t,
13246                &action_question("r1", ask::ChoiceAction::Done),
13247                &PHRASES_EN,
13248                never
13249            ),
13250            ActionDecision::Stale
13251        );
13252    }
13253
13254    #[test]
13255    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13256        let home = crate::run::test_home();
13257        let mut t = held_task_with("r1");
13258        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13259        assert_eq!(
13260            decide_action(
13261                &home,
13262                &t,
13263                &action_question("r1", ask::ChoiceAction::Requeue),
13264                &PHRASES_EN,
13265                never
13266            ),
13267            ActionDecision::Requeue
13268        );
13269        let done_q = action_question("r1", ask::ChoiceAction::Done);
13270        assert_eq!(
13271            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13272            ActionDecision::Done
13273        );
13274        t.mark_action_applied(&done_q.id);
13275        assert_eq!(
13276            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13277            ActionDecision::Skip
13278        );
13279
13280        // A plain answer (no action for that label) does nothing.
13281        let mut plain = action_question("r1", ask::ChoiceAction::Done);
13282        plain.actions.clear();
13283        assert_eq!(
13284            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13285            ActionDecision::Skip
13286        );
13287        // A running task is left alone.
13288        let mut running = held_task_with("r1");
13289        running.status = TaskStatus::Running;
13290        assert_eq!(
13291            decide_action(
13292                &home,
13293                &running,
13294                &action_question("r1", ask::ChoiceAction::Done),
13295                &PHRASES_EN,
13296                never
13297            ),
13298            ActionDecision::Skip
13299        );
13300    }
13301
13302    #[test]
13303    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13304        crate::run::pin_test_home();
13305        for legacy in [false, true] {
13306            let dir = tempfile::tempdir().unwrap();
13307            let queue = Queue::at(dir.path().join("queue"));
13308            let questions = Questions::at(dir.path().join("questions"));
13309            let run = "20260101-000000-hold";
13310            let mut task = held_task_with(run);
13311            task.status = TaskStatus::Parked;
13312            let mut q = ask::Question::new(
13313                run.into(),
13314                land::APPROVAL_NODE.into(),
13315                "land".into(),
13316                "Repair?".into(),
13317                String::new(),
13318                vec![land::REPAIR.into()],
13319            );
13320            q.actions.insert(land::REPAIR.into(), resume_action(run));
13321            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13322            // Deterministically order the answer before the actual manual hold.
13323            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13324            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13325            questions.put(&mut q).unwrap();
13326            task.hold_manual(Some("Keep this PR paused".into()));
13327            if legacy {
13328                task.hold_source = None;
13329            }
13330            queue.put(&mut task).unwrap();
13331
13332            apply_task_choice_actions(&queue, &questions, dir.path());
13333            let after = queue.get(&task.id).unwrap();
13334            assert!(after.operator_held());
13335            assert_eq!(after.hold_source, task.hold_source);
13336            assert_eq!(after.operator_decided_at, task.operator_decided_at);
13337            assert_eq!(after.runs, task.runs);
13338            assert_eq!(after.instruction, task.instruction);
13339            assert!(after.resume_override.is_none());
13340            assert!(after.action_applied(&q.id));
13341            let reason = after.hold_reason.as_deref().unwrap();
13342            assert!(reason.starts_with("Keep this PR paused"));
13343            assert!(reason.contains("later operator decision"));
13344            assert!(reason.contains(&format!("magi task release {}", task.id)));
13345
13346            for recovery in [
13347                crate::conduct::Recovery::Review,
13348                crate::conduct::Recovery::Requeue,
13349            ] {
13350                crate::conduct::apply(
13351                    &queue,
13352                    &questions,
13353                    &crate::conduct::Verdict {
13354                        decisions: vec![crate::conduct::Decision {
13355                            id: task.id.clone(),
13356                            recovery: Some(recovery),
13357                            ..Default::default()
13358                        }],
13359                    },
13360                )
13361                .unwrap();
13362            }
13363            // Reconciliation is idempotent, and automatic recovery cannot
13364            // reopen this owner after it observes the rejected repair answer.
13365            apply_task_choice_actions(&queue, &questions, dir.path());
13366            let still_held = queue.get(&task.id).unwrap();
13367            assert!(still_held.operator_held());
13368            assert_eq!(still_held.hold_reason, after.hold_reason);
13369            assert_eq!(still_held.runs, task.runs);
13370            assert!(still_held.review_branch.is_none());
13371            assert!(!still_held.fresh_start);
13372            assert!(queue.next_runnable().is_none());
13373        }
13374    }
13375
13376    #[test]
13377    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13378        for held in [false, true] {
13379            for retry in [false, true] {
13380                let dir = tempfile::tempdir().unwrap();
13381                let queue = Queue::at(dir.path().join("queue"));
13382                let questions = Questions::at(dir.path().join("questions"));
13383                let home = dir.path().join("home");
13384                let mut t = task();
13385                if held {
13386                    t.hold_machine(Some("driver state unknown".into()));
13387                }
13388                queue.put(&mut t).unwrap();
13389                let verdict = serde_json::from_value(serde_json::json!({
13390                    "decisions": [{
13391                        "id": t.id,
13392                        "question": "Driver state unknown; retry the checks or hold?",
13393                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13394                        "actions": {
13395                            "daemon: recheck and retry": {"do": "requeue"},
13396                            "daemon: hold the task": {"do": "hold"}
13397                        }
13398                    }]
13399                }))
13400                .unwrap();
13401                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13402                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13403                let mut q = questions.list().pop().unwrap();
13404                let choice = if retry {
13405                    "daemon: recheck and retry"
13406                } else {
13407                    "daemon: hold the task"
13408                };
13409                assert_eq!(q.actions.len(), 2);
13410                q.answer(ask::Answer::Choice(choice.into())).unwrap();
13411                questions.put(&mut q).unwrap();
13412
13413                // A Web answer does not remove the deputy's fresh lease.
13414                questions.beat(&q.id, ask::WaiterKind::Deputy);
13415                for _ in 0..2 {
13416                    resolve_blockers(&queue, &questions);
13417                    apply_task_choice_actions(&queue, &questions, &home);
13418                    let waiting = queue.get(&t.id).unwrap();
13419                    assert_eq!(waiting.status, TaskStatus::Blocked);
13420                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
13421                    assert!(waiting.answers.is_empty());
13422                    assert!(!waiting.action_applied(&q.id));
13423                    assert!(runnable(&queue).is_empty());
13424                    let free = Arc::new(tokio::sync::Semaphore::new(1));
13425                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
13426                }
13427                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13428
13429                // Releasing the blocker and applying the operation share one save.
13430                resolve_blockers(&queue, &questions);
13431                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13432                apply_task_choice_actions(&queue, &questions, &home);
13433                let after = queue.get(&t.id).unwrap();
13434                assert_eq!(
13435                    after.status,
13436                    if retry {
13437                        TaskStatus::Queued
13438                    } else {
13439                        TaskStatus::Held
13440                    }
13441                );
13442                assert!(after.action_applied(&q.id));
13443                assert_eq!(after.operator_held(), !retry);
13444                assert_eq!(after.answers.len(), 1);
13445
13446                // A later operator decision must not replay this answer.
13447                let mut changed = after;
13448                if retry {
13449                    changed.hold_manual(Some("later hold".into()));
13450                } else {
13451                    changed.release_operator("test", None);
13452                }
13453                let expected = changed.status;
13454                queue.put(&mut changed).unwrap();
13455                apply_task_choice_actions(&queue, &questions, &home);
13456                assert_eq!(queue.get(&t.id).unwrap().status, expected);
13457            }
13458        }
13459    }
13460
13461    #[test]
13462    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13463        let dir = tempfile::tempdir().unwrap();
13464        let queue = Queue::at(dir.path().join("queue"));
13465        let questions = Questions::at(dir.path().join("questions"));
13466        let home = dir.path().join("home");
13467        let mut state = run_state(RunStatus::Blocked);
13468        state.id = "20260101-000000-act1".to_owned();
13469        state.save_under(&home).unwrap();
13470
13471        let mut t = held_task_with(&state.id);
13472        queue.put(&mut t).unwrap();
13473        let mut q = action_question(&state.id, resume_action(&state.id));
13474        questions.put(&mut q).unwrap();
13475
13476        apply_task_choice_actions(&queue, &questions, &home);
13477        let after = queue.get(&t.id).unwrap();
13478        assert_eq!(after.status, TaskStatus::Queued);
13479        assert!(!after.fresh_start);
13480        assert!(after.action_applied(&q.id));
13481        let pin = after.resume_override.clone().unwrap();
13482        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13483        assert!(pin.forced);
13484
13485        // Held again later: the same answer does not release it a second time.
13486        let mut again = queue.get(&t.id).unwrap();
13487        again.hold_machine(Some("later".into()));
13488        queue.put(&mut again).unwrap();
13489        apply_task_choice_actions(&queue, &questions, &home);
13490        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13491    }
13492
13493    #[test]
13494    fn a_delivered_answer_is_still_acted_on_exactly_once() {
13495        let dir = tempfile::tempdir().unwrap();
13496        let queue = Queue::at(dir.path().join("queue"));
13497        let questions = Questions::at(dir.path().join("questions"));
13498        let home = dir.path().join("home");
13499        let mut state = run_state(RunStatus::Blocked);
13500        state.id = "20260101-000000-act2".to_owned();
13501        state.save_under(&home).unwrap();
13502
13503        let mut t = held_task_with(&state.id);
13504        queue.put(&mut t).unwrap();
13505        let mut q = action_question(&state.id, resume_action(&state.id));
13506        q.answer_delivered = true;
13507        questions.put(&mut q).unwrap();
13508
13509        // Delivered, and the agent then died: the task is still held, so the
13510        // chosen action applies.
13511        apply_task_choice_actions(&queue, &questions, &home);
13512        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13513        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13514
13515        // Held again: the same answer does nothing a second time.
13516        let mut again = queue.get(&t.id).unwrap();
13517        again.hold_machine(Some("later".into()));
13518        queue.put(&mut again).unwrap();
13519        apply_task_choice_actions(&queue, &questions, &home);
13520        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13521    }
13522
13523    #[test]
13524    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13525        let dir = tempfile::tempdir().unwrap();
13526        let queue = Queue::at(dir.path().join("queue"));
13527        let questions = Questions::at(dir.path().join("questions"));
13528        let home = dir.path().join("home");
13529        let mut state = run_state(RunStatus::Blocked);
13530        state.id = "20260101-000000-act3".to_owned();
13531        state.save_under(&home).unwrap();
13532        let mut t = held_task_with(&state.id);
13533        queue.put(&mut t).unwrap();
13534        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13535        questions.put(&mut q).unwrap();
13536
13537        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13538        apply_task_choice_actions(&queue, &questions, &home);
13539        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13540
13541        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13542        apply_task_choice_actions(&queue, &questions, &home);
13543        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13544    }
13545
13546    #[test]
13547    fn action_standing_tells_the_reasons_apart() {
13548        let mut t = held_task_with("r1");
13549        let q = action_question("r1", ask::ChoiceAction::Requeue);
13550        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13551        let mut plain = q.clone();
13552        plain.actions.clear();
13553        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13554
13555        // Applied wins over everything, even a running task.
13556        t.mark_action_applied(&q.id);
13557        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13558
13559        // A newer attempt running: the old question is Stale, not Busy.
13560        let mut t = held_task_with("r1");
13561        t.start("r2".to_owned());
13562        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13563        // The same question about the latest run just waits.
13564        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13565        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13566        t.status = TaskStatus::Blocked;
13567        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13568
13569        // A conductor question is keyed by the task, never stale.
13570        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13571        c.node = crate::conduct::NODE.to_owned();
13572        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13573        assert!(!ActionStanding::Busy.daemon_owns());
13574    }
13575
13576    #[test]
13577    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13578        let dir = tempfile::tempdir().unwrap();
13579        let queue = Queue::at(dir.path().join("queue"));
13580        let questions = Questions::at(dir.path().join("questions"));
13581        let home = dir.path().join("home");
13582        let mut state = run_state(RunStatus::Blocked);
13583        state.id = "20260101-000000-act4".to_owned();
13584        state.save_under(&home).unwrap();
13585        let mut t = held_task_with(&state.id);
13586        t.status = TaskStatus::Running;
13587        queue.put(&mut t).unwrap();
13588        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13589        q.cwd = Some(dir.path().display().to_string());
13590        questions.put(&mut q).unwrap();
13591
13592        // While the task runs the daemon will not act, so the waiter still
13593        // delivers the word to the dead asker's seat ...
13594        let running = queue.get(&t.id).unwrap();
13595        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13596        assert!(matches!(
13597            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13598            crate::waiter::Action::Deliver(_)
13599        ));
13600        // ... and the daemon waits while the task runs, then applies once.
13601        apply_task_choice_actions(&queue, &questions, &home);
13602        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13603        let mut back = queue.get(&t.id).unwrap();
13604        back.hold_machine(Some("later".into()));
13605        queue.put(&mut back).unwrap();
13606        apply_task_choice_actions(&queue, &questions, &home);
13607        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13608        let mut again = queue.get(&t.id).unwrap();
13609        again.hold_machine(Some("again".into()));
13610        queue.put(&mut again).unwrap();
13611        apply_task_choice_actions(&queue, &questions, &home);
13612        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13613    }
13614}