Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// Effective startup capabilities of the question recovery loops.
137    #[serde(default)]
138    pub question_recovery: Option<crate::question_delivery::Recovery>,
139    /// Independent-worker control protocol supported by this scheduler.
140    #[serde(default)]
141    pub worker_protocol: Option<u32>,
142}
143
144impl Status {
145    /// A fresh, idle status for this process.
146    #[must_use]
147    pub fn new() -> Self {
148        let now = Timestamp::now();
149        Self {
150            schema: SCHEMA,
151            pid: std::process::id(),
152            started_at: now,
153            updated_at: now,
154            idle: true,
155            current: Vec::new(),
156            completed: 0,
157            polls: 0,
158            question_recovery: None,
159            worker_protocol: Some(1),
160        }
161    }
162}
163
164impl Default for Status {
165    fn default() -> Self {
166        Self::new()
167    }
168}
169
170/// How the loop should behave.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(default)]
173pub struct Opts {
174    /// Repository used by tasks that name none.
175    pub repo: PathBuf,
176    /// Explicit `magi.toml`, instead of the discovered layer stack.
177    pub config: Option<PathBuf>,
178    /// Queue poll interval.
179    pub poll: Duration,
180    /// Attempts a task gets before it is held for a human.
181    pub max_attempts: usize,
182    /// Drain what is runnable now, then return, instead of waiting for more.
183    pub once: bool,
184    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
185    pub merge: Option<String>,
186    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
187    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
188    /// `None` resolves to [`crate::run::default_worktree_root`] - the
189    /// operator's real `~/wt/<repo>` - the same way a run with no
190    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
191    /// that does not own that directory (a test, an embedding that manages
192    /// worktrees itself) must set this, or every idle tick reclaims worktrees
193    /// out from under whoever actually does.
194    pub worktrees_root: Option<PathBuf>,
195}
196
197impl Default for Opts {
198    fn default() -> Self {
199        Self {
200            repo: PathBuf::from("."),
201            config: None,
202            poll: POLL,
203            max_attempts: 2,
204            once: false,
205            merge: None,
206            worktrees_root: None,
207        }
208    }
209}
210
211impl Opts {
212    fn absolute(&self) -> Result<Self> {
213        let mut opts = self.clone();
214        opts.repo = std::path::absolute(&opts.repo)?;
215        opts.config = opts
216            .config
217            .as_deref()
218            .map(std::path::absolute)
219            .transpose()?;
220        opts.worktrees_root = opts
221            .worktrees_root
222            .as_deref()
223            .map(std::path::absolute)
224            .transpose()?;
225        Ok(opts)
226    }
227}
228
229/// How many runs a plain `usize` from config may drive concurrently, floored
230/// at one. A `0` in a config file would otherwise stall the loop entirely -
231/// no runnable task could ever start - which is never what an operator who
232/// wrote `0` meant.
233fn max_concurrent(n: usize) -> usize {
234    n.max(1)
235}
236
237/// Where the status file lives.
238#[must_use]
239pub fn status_path() -> PathBuf {
240    crate::run::home().join("daemon.json")
241}
242
243/// Publish the status file for this process.
244pub fn write_status(status: &Status) -> Result<()> {
245    write_status_to(&status_path(), status)
246}
247
248/// Publish a status to an explicit path.
249///
250/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
251/// on every health poll and must never see a half-written one.
252pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
253    if let Some(parent) = path.parent() {
254        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
255    }
256    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
257    let tmp = path.with_extension("json.tmp");
258    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
259    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
260    Ok(())
261}
262
263/// Delete the status file. Called on the way out so a clean exit reads as
264/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
265pub fn clear_status() {
266    clear_status_at(&status_path());
267}
268
269/// Delete a status file at an explicit path, so the loop's teardown and
270/// [`clear_status`] cannot drift apart: the loop is handed the path it
271/// published to, and a test can watch a temp file disappear.
272fn clear_status_at(path: &Path) {
273    let _ = std::fs::remove_file(path);
274}
275
276/// A cooperative stop, shared with whoever asked the loop to run.
277///
278/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
279/// Ctrl-C listener and the web UI keep others, and every clone points at the
280/// same flag. There is no channel because there is nothing to send — the only
281/// message is "stop", it is idempotent, and a flag cannot be missed by a
282/// receiver that was not listening yet.
283///
284/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
285/// detached task workers keep their own lifetimes and ownership after this
286/// handle's scheduler exits.
287#[derive(Debug, Clone, Default)]
288pub struct Stop {
289    /// Set once, never cleared: a stop is not something an operator takes back
290    /// half way through, and a clearable flag would let a start racing a stop
291    /// resurrect a loop that is already unwinding.
292    stopped: Arc<AtomicBool>,
293    /// Live task workers observed by the scheduler's latest dispatch snapshot.
294    busy: Arc<std::sync::atomic::AtomicUsize>,
295    /// Wakes the idle wait. Without this a stop would not be seen until the
296    /// poll interval elapsed, and an operator tapping stop on a phone would
297    /// watch a button do nothing for five seconds.
298    wake: Arc<Notify>,
299    /// Handed to the run in flight, so a stop can also mean "park at the next
300    /// node boundary" instead of "finish the whole competition first".
301    pause: crate::graph::Pause,
302}
303
304impl Stop {
305    /// A stop nobody has asked for yet.
306    #[must_use]
307    pub fn new() -> Self {
308        Self::default()
309    }
310
311    /// Ask the loop to stop. Idempotent, and safe to call before the loop
312    /// starts: the flag is checked before the first poll.
313    pub fn stop(&self) {
314        self.stopped.store(true, Ordering::SeqCst);
315        // `notify_one` rather than `notify_waiters` because the loop may not be
316        // parked yet: this stores a permit, so a wait that registers a moment
317        // later returns at once instead of sleeping out the whole interval.
318        self.wake.notify_one();
319    }
320
321    /// Has a stop been asked for?
322    #[must_use]
323    pub fn stopped(&self) -> bool {
324        self.stopped.load(Ordering::SeqCst)
325    }
326
327    /// Whether a requested scheduler retirement still has an active snapshot.
328    /// Workers continue independently after the scheduler has retired.
329    #[must_use]
330    pub fn finishing(&self) -> bool {
331        self.stopped() && self.busy_now()
332    }
333
334    /// Ask the loop to stop *and* the run in flight to park at its next node
335    /// boundary.
336    ///
337    /// Unlike plain stop, explicit park asks workers to checkpoint at their
338    /// existing safe boundaries. Binary replacement never needs a park.
339    pub fn park(&self, cause: crate::run::ParkCause) {
340        self.pause.park_for(cause);
341        self.stop();
342    }
343
344    /// Has a park been asked for?
345    #[must_use]
346    pub fn parking(&self) -> bool {
347        self.pause.parked()
348    }
349
350    /// The pause handle to give a runner.
351    #[must_use]
352    pub fn pause(&self) -> crate::graph::Pause {
353        self.pause.clone()
354    }
355
356    /// Whether the scheduler's latest snapshot contains active task workers.
357    #[must_use]
358    pub fn busy_now(&self) -> bool {
359        self.busy.load(Ordering::SeqCst) > 0
360    }
361
362    /// Wait out one poll interval, returning early once a stop is asked for.
363    async fn idle(&self, poll: Duration) {
364        tokio::select! {
365            () = tokio::time::sleep(poll) => {}
366            () = self.wake.notified() => {}
367        }
368    }
369}
370
371/// The daemon's published state, read permissively.
372///
373/// This mirrors [`Status`], but is a separate declaration on purpose: every
374/// field defaults, so a status file from an older or newer magi still yields
375/// a usable reading — one this build has never heard of — instead of a parse
376/// error that hides the daemon entirely.
377#[derive(Debug, Clone, Default, Deserialize)]
378#[serde(default)]
379pub struct Reading {
380    /// Format version the daemon claims.
381    pub schema: u32,
382    /// Daemon process id, for an operator who wants to stop it.
383    pub pid: Option<u32>,
384    /// When that process started.
385    pub started_at: Option<Timestamp>,
386    /// Last heartbeat. Absent means the file is unusable, hence not running.
387    pub updated_at: Option<Timestamp>,
388    /// True when the queue had nothing runnable at the last poll.
389    pub idle: bool,
390    /// What the daemon is working on. Empty means idle; more than one entry
391    /// means more than one run is in flight at once.
392    ///
393    /// `deserialize_with` rather than the plain derive: a daemon started
394    /// before this field became a list is still out there writing the old
395    /// shape — a single `{"task":...,"run":...}` object, or its absence —
396    /// on every heartbeat until it is restarted, and a live process reading
397    /// that file during the rollout must still see it as running rather than
398    /// as absent. A bare type change here would fail the whole struct's
399    /// deserialization on a type mismatch, defeating the permissiveness this
400    /// type exists for.
401    #[serde(deserialize_with = "de_current")]
402    pub current: Vec<Current>,
403    /// Tasks this daemon process has finished.
404    pub completed: u64,
405    /// Queue polls this daemon process has made.
406    pub polls: u64,
407    /// Effective startup capabilities of the question recovery loops.
408    #[serde(default)]
409    pub question_recovery: Option<crate::question_delivery::Recovery>,
410    /// Independent-worker control protocol, absent on legacy embedded loops.
411    pub worker_protocol: Option<u32>,
412}
413
414/// Accept the old single-`Current`-or-absent shape as well as the current
415/// list, so a reader never has to know which build wrote the file.
416fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
417where
418    D: serde::Deserializer<'de>,
419{
420    #[derive(Deserialize)]
421    #[serde(untagged)]
422    enum Shape {
423        Many(Vec<Current>),
424        One(Current),
425    }
426    Ok(
427        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
428            Shape::Many(v) => v,
429            Shape::One(c) => vec![c],
430        }),
431    )
432}
433
434impl Reading {
435    /// Seconds since the last heartbeat, or `None` when there has never been
436    /// one.
437    #[must_use]
438    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
439        self.updated_at
440            .map(|at| (now.as_second() - at.as_second()).max(0))
441    }
442
443    /// Whether the loop counts as running: a heartbeat no older than
444    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
445    /// progress hours after the daemon that owned it was killed.
446    #[must_use]
447    pub fn running(&self, now: Timestamp) -> bool {
448        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
449    }
450}
451
452/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
453/// usable there.
454///
455/// Missing, half-written and unparseable all collapse to `None`, because the
456/// only question a reader asks is whether a daemon is alive, and a file it
457/// cannot read is not evidence that one is.
458#[must_use]
459pub fn read_status(home: &Path) -> Option<Reading> {
460    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
461    serde_json::from_str(&body).ok()
462}
463
464/// Read-only evidence of runs owned by a live daemon or independent worker.
465///
466/// CLI, sandboxed conversation controls and Web cleanup share this observation.
467/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
468/// Starting reservations and unknown worker state remain protected; observing
469/// them never creates, reconciles or archives files in the worker store.
470/// Callers interested in one identity use [`is_working_on`] or
471/// [`is_working_on_task`].
472#[must_use]
473pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
474    let mut current = read_status(home)
475        .filter(|reading| reading.running(now))
476        .map(|reading| reading.current)
477        .unwrap_or_default();
478    let workers = crate::worker::observe_active(home).and_then(|jobs| {
479        jobs.into_iter()
480            .filter(|job| job.kind == "task")
481            .map(|job| {
482                let request: TaskWorker = serde_json::from_value(job.payload)?;
483                let run = Queue::at(request.queue)
484                    .get(&request.task)
485                    .ok()
486                    .and_then(|task| task.runs.last().cloned())
487                    .unwrap_or_default();
488                Ok(Current {
489                    worker: Some(job.id),
490                    task: request.task,
491                    run,
492                })
493            })
494            .collect::<Result<Vec<_>>>()
495    });
496    match workers {
497        Ok(workers) => {
498            for worker in workers {
499                if !current.iter().any(|claim| {
500                    claim.task == worker.task
501                        && claim.run == worker.run
502                        && claim.worker == worker.worker
503                }) {
504                    current.push(worker);
505                }
506            }
507        }
508        Err(error) => {
509            // This API gates destructive cleanup. Unknown worker ownership
510            // protects every known task/run instead of pretending it is idle.
511            tracing::error!("cannot determine active workers: {error:#}");
512            current.extend(
513                Queue::at(home.join("queue"))
514                    .list()
515                    .into_iter()
516                    .map(|task| Current {
517                        worker: None,
518                        task: task.id,
519                        run: task.runs.last().cloned().unwrap_or_default(),
520                    }),
521            );
522            current.extend(
523                crate::run::list_ids_in(&home.join("runs"))
524                    .into_iter()
525                    .map(|run| Current {
526                        worker: None,
527                        task: String::new(),
528                        run,
529                    }),
530            );
531        }
532    }
533    current
534}
535
536/// Whether a live daemon is working on this run at this moment.
537#[must_use]
538pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
539    current_work(home, now).iter().any(|c| c.run == run)
540}
541
542/// Admission may ignore only this process's confirmed worker reservation.
543/// Keep anonymous/legacy daemon claims and every other worker, even for the
544/// same task. The run's execution lease and process identity are checked by
545/// the caller under the owner lock as well.
546pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
547    // A helper or test may inherit an identity from a different run store.
548    // That identity grants no exception here; retain all ownership evidence.
549    let same_home = std::env::var_os("MAGI_WORKER_HOME")
550        .is_some_and(|worker_home| Path::new(&worker_home) == home);
551    let caller = if same_home {
552        crate::worker::current_job(home)?
553    } else {
554        None
555    }
556    .filter(|job| {
557        job.kind == "task"
558            && job.status == crate::worker::Status::Running
559            && job.pid == Some(std::process::id())
560    });
561    Ok(other_claims_run(
562        &current_work(home, now),
563        run,
564        caller.as_ref().map(|job| job.id.as_str()),
565    ))
566}
567
568fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
569    claims
570        .iter()
571        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
572}
573
574/// Whether a live daemon is working on a run whose short id is this one.
575///
576/// For a worktree that has no run record to compare against at all -
577/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
578/// id is not available to hand to [`is_working_on`]. The short id is: a run's
579/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
580/// and it is exactly the gap between the daemon claiming a task and
581/// `RunState::new` saving the first `run.json` that this exists to protect -
582/// a run genuinely in flight but invisible to a scan of `runs/`.
583#[must_use]
584pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
585    current_work(home, now)
586        .iter()
587        .any(|c| crate::run::short_of(&c.run) == short)
588}
589
590/// Whether a live daemon is working on this task at this moment.
591#[must_use]
592pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
593    current_work(home, now).iter().any(|c| c.task == task)
594}
595
596/// Remove claim files whose owner is provably dead, or that have simply
597/// outlived `older_than`, and return the task ids swept.
598///
599/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
600/// destructor, and the orphaned `.lock` file would make its task permanently
601/// unclaimable — the backlog would stop for good at exactly the task that was
602/// in flight when the machine went down.
603///
604/// The pid recorded in the lock is the authority whenever it can be read at
605/// all; age is only a fallback for when it cannot be.
606///
607/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
608///   full stop — dead sweeps the lock immediately, regardless of age; alive
609///   protects it, regardless of age. This is what lets a lock be reclaimed in
610///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
611///   before this daemon even started, next to a `queued` task, no longer has
612///   to sit for six hours before anything notices its owner is gone.
613/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
614///   falls back to `older_than`, since there is nothing else to check.
615///
616/// Age must never override a *positive* liveness confirmation. `sweep`
617/// polls concurrently with independently running task workers. A worker may
618/// legitimately run longer than `older_than`; its live pid must still protect
619/// its claim. Age alone must never turn that claim into a second task attempt,
620/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
621/// to a second attempt — two `Runner`s writing the same `run.json` and the
622/// same worktree at once. `pid_alive` answering "alive" for anything it
623/// cannot determine (a live process, a pid this build cannot check, one
624/// under another account) is exactly what keeps that path from ever
625/// firing on a guess.
626///
627/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
628/// output unreadable must not be license to guess, and the risk of an
629/// unparseable lock outliving a genuinely dead owner is bounded by an order
630/// of magnitude above any plausible run rather than by a positive check.
631///
632/// Runs on every poll, not only at startup — a daemon up for days must keep
633/// noticing a lock some other, now-dead, daemon left behind just as readily
634/// as one it trips over on the way up.
635pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
636    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
637}
638
639/// [`sweep_stale_claims`] with its process-query boundary supplied by the
640/// caller. This keeps the lock policy testable where process listing is
641/// unavailable, while production still uses the platform query above.
642fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
643where
644    F: Fn(u32) -> bool,
645{
646    let this_process = std::process::id();
647    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
648        .into_iter()
649        .flatten()
650        .flatten()
651        .map(|e| e.path())
652        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
653        .filter(|p| {
654            match std::fs::read_to_string(p)
655                .ok()
656                .and_then(|body| body.trim().parse::<u32>().ok())
657            {
658                // This process wrote it and is asking the question right
659                // now, so it is definitionally still alive - settled without
660                // spawning a helper process at all.
661                Some(pid) if pid == this_process => false,
662                Some(pid) => !pid_alive(pid),
663                None => p
664                    .metadata()
665                    .and_then(|m| m.modified())
666                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
667                    .is_ok_and(|age| age >= older_than),
668            }
669        })
670        .filter(|p| std::fs::remove_file(p).is_ok())
671        .filter_map(|p| {
672            p.file_stem()
673                .and_then(|s| s.to_str())
674                .map(std::borrow::ToOwned::to_owned)
675        })
676        .collect();
677    swept.sort_unstable();
678    swept
679}
680
681/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
682/// no live daemon's heartbeat naming it? Deterministic — no model call, and
683/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
684/// shown.
685fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
686    task.status == TaskStatus::Running
687        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
688        && !is_working_on_task(home, &task.id, now)
689}
690
691/// Every task [`is_stalled`] right now — "止まったタスク" in
692/// `crate::conduct`'s vocabulary.
693fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
694    queue
695        .list()
696        .into_iter()
697        .filter(|t| is_stalled(t, home, now))
698        .collect()
699}
700
701/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
702/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
703/// `Failed`-and-so-also-runnable: a task that already attempted and lost
704/// belongs in [`finished_tasks`], where the question is a recovery, not a
705/// dependency.
706fn queued_tasks(queue: &Queue) -> Vec<Task> {
707    queue
708        .list()
709        .into_iter()
710        .filter(|t| t.status == TaskStatus::Queued)
711        .collect()
712}
713
714/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
715/// タスク" in `crate::conduct`'s vocabulary.
716fn finished_tasks(queue: &Queue) -> Vec<Task> {
717    queue
718        .list()
719        .into_iter()
720        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
721        .collect()
722}
723
724/// Deterministically resolve `Task::blocked_by`: a dependency task that
725/// reached `Done`, or a question that was answered, is removed — no model
726/// involved, on every poll. An answered question's content is copied onto
727/// the task ([`Task::record_answer`]) before its id is dropped, so it
728/// reaches the next `crate::conduct` prompt and the next run's instruction
729/// (see [`instruction_for`]) rather than only clearing the block.
730///
731/// A `blocked_by` id that names neither an existing task nor an existing
732/// question - `magi task rm` (or an operator by hand) deleted it while this
733/// task was still waiting - is caught before any of that: it can never
734/// become `Done` or `Answered`, so the ordinary loop below would otherwise
735/// leave the task `blocked` forever with nothing to notice. Such a task is
736/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
737/// which puts it in front of `crate::triage::run_once`'s own walk the next
738/// time it runs - see that module's doc for why the choice is "ask a human",
739/// never "assume the missing dependency was satisfied and unblock anyway".
740fn resolve_blockers(queue: &Queue, questions: &Questions) {
741    for listed in queue.list() {
742        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
743            continue;
744        }
745        let Ok(_claim) = queue.claim(&listed.id) else {
746            continue;
747        };
748        let Ok(mut task) = queue.get(&listed.id) else {
749            continue;
750        };
751        if task.status != TaskStatus::Blocked {
752            continue;
753        }
754        // A dependency deleted on purpose is released, not held - and before
755        // the missing check, so a pass that races the delete (or a claim that
756        // made `Queue::remove` skip this task) settles it quietly.
757        let deleted = queue.apply_deleted_blockers(&mut task, questions);
758        if !deleted.is_empty() {
759            record(queue, &mut task);
760            for id in &deleted {
761                queue.note_dependency_deleted(&task, id);
762            }
763            if task.status != TaskStatus::Blocked {
764                continue;
765            }
766        }
767        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
768        if !missing.is_empty() {
769            let language = language_of(&task, Path::new("."));
770            let mut cause = missing.clone();
771            cause.sort();
772            cause.dedup();
773            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
774            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
775                &task.blocked_by,
776                &missing,
777                &language,
778            )));
779            record(queue, &mut task);
780            continue;
781        }
782        // A conductor question nobody answered in time is retired by the
783        // waiter, and nothing else would ever move the task it blocks.
784        if let Some(q) = task.blocked_by.iter().find_map(|id| {
785            let crate::queue::Dependency::Question(full) =
786                crate::queue::dependency(queue, questions, id)
787            else {
788                return None;
789            };
790            questions.get(&full).ok().filter(|q| {
791                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
792            })
793        }) {
794            let language = language_of(&task, Path::new("."));
795            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
796            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
797            record(queue, &mut task);
798            continue;
799        }
800        let mut changed = false;
801        for id in task.blocked_by.clone() {
802            let resolved = crate::queue::dependency(queue, questions, &id);
803            if let crate::queue::Dependency::Task(full) = &resolved {
804                if queue
805                    .get(full)
806                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
807                {
808                    task.unblock(&id);
809                    changed = true;
810                }
811                continue;
812            }
813            if let crate::queue::Dependency::Question(full) = resolved
814                && let Ok(q) = questions.get(&full)
815                && q.status == ask::QuestionStatus::Answered
816            {
817                // The action sweep releases conductor blockers atomically
818                // with their selected operation. A fresh deputy lease must
819                // never leave an answered hold temporarily runnable.
820                if q.node == crate::conduct::NODE
821                    && q.chosen_action().is_some()
822                    && !task.action_applied(&q.id)
823                {
824                    continue;
825                }
826                let answer = match &q.answer {
827                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
828                    None => String::new(),
829                };
830                task.record_answer(q.summary.clone(), answer);
831                task.unblock(&id);
832                changed = true;
833            }
834        }
835        if changed {
836            record(queue, &mut task);
837        }
838    }
839}
840
841/// The `hold_reason` of a task whose conductor question went unanswered.
842fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
843    if crate::lang::is_japanese(language) {
844        format!(
845            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
846            q.short(),
847            q.summary
848        )
849    } else {
850        format!(
851            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
852            q.short(),
853            q.summary
854        )
855    }
856}
857
858/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
859/// for several unrelated reasons, and the waiter must not read them alike.
860#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub(crate) enum ActionStanding {
862    /// The answer carries no action: the waiter delivers it as before.
863    NoAction,
864    /// The daemon will apply it (not applied, task idle, current attempt).
865    Pending,
866    /// Already applied (`Task::actions_applied`): the daemon has acted, so
867    /// delivering the word to the old seat would run it beside the new work.
868    Applied,
869    /// The question is about an earlier attempt than the task's latest.
870    Stale,
871    /// The task is running / blocked / done: the daemon defers for now.
872    Busy,
873}
874
875impl ActionStanding {
876    /// The daemon has acted or will act: the waiter must not deliver.
877    pub(crate) fn daemon_owns(self) -> bool {
878        matches!(self, Self::Pending | Self::Applied | Self::Stale)
879    }
880}
881
882/// Classify `q`'s chosen action against `task`. `Stale` is judged before
883/// `Busy`: a question about an earlier attempt must be stopped even while a
884/// newer competition is running.
885pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
886    if q.chosen_action().is_none() {
887        ActionStanding::NoAction
888    } else if task.action_applied(&q.id) {
889        ActionStanding::Applied
890    } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891        ActionStanding::Stale
892    } else if matches!(
893        task.status,
894        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
895    ) {
896        ActionStanding::Busy
897    } else {
898        ActionStanding::Pending
899    }
900}
901
902/// What [`decide_action`] concluded about one answered question.
903#[derive(Debug, Clone, PartialEq, Eq)]
904enum ActionDecision {
905    /// Nothing to do now (no action, already applied, or the task is busy).
906    Skip,
907    /// Continue the named run instead of competing again.
908    Resume(String),
909    /// Requeue as a fresh competition.
910    Requeue,
911    /// Hold the task by explicit operator choice.
912    Hold,
913    /// Close the task as done.
914    Done,
915    /// The question is about an earlier attempt than the task's latest; it
916    /// is recorded as handled and changes nothing.
917    Stale,
918    /// The action cannot be carried out; hold the task and say why. Never
919    /// falls back to something else, because the operator chose this one.
920    Refuse(String),
921}
922
923/// Decide what the choice answered on `q` means for `task`. Pure: `load`
924/// reads a run's state, as with [`unfinished_run_with`].
925///
926/// `Resume` only fires on the task's *latest* run, and only while that run
927/// could actually make progress ([`RunStatus::resumable`], not released, review
928/// budget left); an answer naming anything else is refused rather than
929/// reinterpreted as a fresh competition.
930fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
931where
932    F: FnOnce(&str) -> Result<RunState>,
933{
934    let Some(action) = q.chosen_action() else {
935        return ActionDecision::Skip;
936    };
937    if task.action_applied(&q.id)
938        || matches!(
939            task.status,
940            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
941        )
942    {
943        return ActionDecision::Skip;
944    }
945    // A question about an earlier attempt must not act on a newer one. A
946    // conductor question is keyed by the task id, not a run, so it is exempt.
947    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
948        return ActionDecision::Stale;
949    }
950    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
951    let stopping = q.node == land::APPROVAL_NODE
952        && q.resolution()
953            .as_deref()
954            .is_some_and(crate::merge_decision::stops);
955    // An answer is the owner's decision as of when it was given: a manual hold
956    // placed before it (even after the question was asked) was seen and
957    // overruled by it, while a hold or release after it supersedes it.
958    let decision_at = q.answered_at.unwrap_or(q.asked_at);
959    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
960        return if repair || stopping {
961            ActionDecision::Refuse(format!(
962                "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
963                if repair { "repair" } else { "stop" },
964                q.id,
965                q.run,
966                task.id
967            ))
968        } else {
969            ActionDecision::Stale
970        };
971    }
972    match action {
973        a if a.maintenance() => ActionDecision::Skip,
974        ask::ChoiceAction::ResumeRun { .. }
975        | ask::ChoiceAction::ReleaseTask { .. }
976        | ask::ChoiceAction::RerunChecks { .. }
977        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
978        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
979        ask::ChoiceAction::Hold => ActionDecision::Hold,
980        ask::ChoiceAction::Done => ActionDecision::Done,
981        ask::ChoiceAction::Resume { run } => {
982            if task.runs.last() != Some(run) {
983                return ActionDecision::Refuse((p.resume_not_latest)(
984                    q.short(),
985                    ask::short_id(run),
986                ));
987            }
988            match load(run) {
989                Ok(s) if stopping => {
990                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
991                        || !s
992                            .land_approval
993                            .as_ref()
994                            .is_some_and(|binding| binding.question == q.id)
995                    {
996                        ActionDecision::Stale
997                    } else if s.liveness(false) == Liveness::Live {
998                        ActionDecision::Skip
999                    } else if s.status == RunStatus::Landing
1000                        && !s.released()
1001                        && s.retired_to.is_none()
1002                    {
1003                        ActionDecision::Resume(run.clone())
1004                    } else {
1005                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1006                    }
1007                }
1008                Ok(s)
1009                    if q.node == land::APPROVAL_NODE
1010                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1011                {
1012                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1013                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1014                    {
1015                        // A live/manual driver already consumed or superseded
1016                        // this answer. Do not hold its fresh approval wait.
1017                        ActionDecision::Stale
1018                    } else if s.liveness(false) == Liveness::Live {
1019                        ActionDecision::Skip
1020                    } else if s.status != RunStatus::Landing
1021                        || s.released()
1022                        || s.reviews.is_empty()
1023                        || !implementers_match(task, &s)
1024                        || !s
1025                            .land_approval
1026                            .as_ref()
1027                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1028                    {
1029                        ActionDecision::Refuse(format!(
1030                            "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
1031                            q.id, run, run
1032                        ))
1033                    } else {
1034                        ActionDecision::Resume(run.clone())
1035                    }
1036                }
1037                Ok(s) if s.liveness(false) == Liveness::Live => {
1038                    ActionDecision::Refuse("run already has a live driver".into())
1039                }
1040                Ok(s) => match crate::handover::resume_refusal(&s) {
1041                    None => ActionDecision::Resume(run.clone()),
1042                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1043                        q.short(),
1044                        ask::short_id(run),
1045                        &reason.diagnostic(&s),
1046                    )),
1047                },
1048                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1049                    q.short(),
1050                    ask::short_id(run),
1051                    &format!("{e:#}"),
1052                )),
1053            }
1054        }
1055    }
1056}
1057
1058/// The fixed prose the daemon writes into [`Task::last_error`] and
1059/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1060/// `triage::Wording` and `land::Words`: only English and Japanese are
1061/// translated, anything else falls back to English.
1062///
1063/// Rendered when the reason is *generated*, so a reason keeps the language it
1064/// was written in if the setting changes later. The notification frame
1065/// (`Task <id> is held:`) is not here and stays English.
1066///
1067/// Deliberately **not** translated, because other code reads them back by
1068/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1069/// and `gate red`. IDs, node names, paths and external error text are embedded
1070/// as they are.
1071struct Phrases {
1072    /// `{}` = status label, then the detail.
1073    graph_stopped: fn(&str, &str) -> String,
1074    quorum_lost: &'static str,
1075    /// Followed by the seats' names.
1076    quota_took_out: &'static str,
1077    /// Followed by the status label.
1078    run_ended: &'static str,
1079    /// Followed by the question's short id.
1080    waiting_for_answer: &'static str,
1081    recovered_running: &'static str,
1082    no_run_to_recover: &'static str,
1083    could_not_start: &'static str,
1084    resume_not_latest: fn(&str, &str) -> String,
1085    resume_cannot_progress: fn(&str, &str, &str) -> String,
1086    resume_unreadable: fn(&str, &str, &str) -> String,
1087    /// A takeover refusal: the operator-facing text. English is the error's own
1088    /// `Display`; a translation keeps the machine detail apart in parentheses.
1089    handover_refused: fn(&crate::handover::Refused) -> String,
1090    /// Appended to a refused handover's hold reason (leading space included).
1091    handover_hint: &'static str,
1092    /// (seats that never answered, review rounds) for the review loop's
1093    /// "refusing to call it clean" stop.
1094    reviewers_never_answered: fn(usize, usize) -> String,
1095}
1096
1097const PHRASES_EN: Phrases = Phrases {
1098    graph_stopped: |status, detail| {
1099        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1100    },
1101    quorum_lost: "the judging panel lost its quorum",
1102    quota_took_out: "; quota took out ",
1103    run_ended: "run ended ",
1104    waiting_for_answer: " - waiting for operator answer to question ",
1105    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1106    no_run_to_recover: "task was `running` with no live daemon and no readable \
1107                        run to recover; held for a human to check what happened",
1108    could_not_start: "could not start the run: ",
1109    resume_not_latest: |q, run| {
1110        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1111    },
1112    resume_cannot_progress: |q, run, reason| {
1113        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1114    },
1115    resume_unreadable: |q, run, e| {
1116        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1117    },
1118    handover_refused: |r| r.to_string(),
1119    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1120    reviewers_never_answered: |missing, rounds| {
1121        format!(
1122            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1123             refusing to call it clean"
1124        )
1125    },
1126};
1127
1128const PHRASES_JA: Phrases = Phrases {
1129    graph_stopped: |status, detail| {
1130        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1131    },
1132    quorum_lost: "審査パネルが定足数を失いました",
1133    quota_took_out: "。クォータで脱落: ",
1134    run_ended: "run 終了: ",
1135    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1136    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1137    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1138                        何が起きたか人が確認するため保留にしました",
1139    could_not_start: "run を開始できませんでした: ",
1140    resume_not_latest: |q, run| {
1141        format!(
1142            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1143        )
1144    },
1145    resume_cannot_progress: |q, run, reason| {
1146        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1147    },
1148    resume_unreadable: |q, run, e| {
1149        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1150    },
1151    handover_refused: |r| {
1152        use crate::handover::Refused;
1153        match r {
1154            Refused::Foreign { branch, path, why } => format!(
1155                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1156                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1157                 から、やり直してください(詳細: {why})"
1158            ),
1159            Refused::Unsafe { branch, path, why } => format!(
1160                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1161                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1162                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1163            ),
1164            Refused::ReleaseFailed { branch, path, run } => format!(
1165                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1166                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1167                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1168            ),
1169        }
1170    },
1171    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1172    reviewers_never_answered: |missing, rounds| {
1173        format!(
1174            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1175             クリーンとは認めません"
1176        )
1177    },
1178};
1179
1180fn phrases(language: &str) -> &'static Phrases {
1181    if crate::lang::is_japanese(language) {
1182        &PHRASES_JA
1183    } else {
1184        &PHRASES_EN
1185    }
1186}
1187
1188/// The language of the repository a task belongs to, read best-effort for the
1189/// paths that have no run (and so no config of their own) to ask. An unreadable
1190/// config is English, not an error: a hold reason must still get written.
1191fn language_of(task: &Task, fallback: &Path) -> String {
1192    crate::lang::of_repo(&repo_for(task, fallback))
1193}
1194
1195/// The task an answered question speaks for: the one whose runs include the
1196/// question's run, or - for a conductor question, filed under the task's own
1197/// id - the task with that id.
1198pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1199    if q.node == crate::conduct::NODE {
1200        return tasks.iter().find(|t| t.id == q.run);
1201    }
1202    tasks.iter().find(|t| t.runs.contains(&q.run))
1203}
1204
1205/// Legacy conductor prose never becomes a maintenance command by inference.
1206/// Replace unsupported open labels under the question lock before dispatch.
1207fn repair_choice_offers(questions: &Questions) {
1208    for q in questions.list().into_iter().filter(|q| {
1209        q.status.open()
1210            && q.node == crate::conduct::NODE
1211            && q.choices
1212                .iter()
1213                .any(|c| crate::choice_effect::describe(q, c).is_none())
1214    }) {
1215        let _ = questions.update(&q.id, |current| {
1216            if current.status.open() {
1217                crate::choice_effect::executable_conductor(current);
1218                if let Some(deputy) = &mut current.deputy {
1219                    deputy.brief = crate::deputy::brief(
1220                        &current.run,
1221                        &current.detail,
1222                        &current.choices,
1223                        &current.actions,
1224                    );
1225                }
1226            }
1227            Ok(())
1228        });
1229    }
1230}
1231
1232/// Apply answered typed choices. Only the daemon calls this in production;
1233/// deputies settle the question and never execute its actions.
1234pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1235    apply_maintenance_choices(queue, questions, home).await;
1236    apply_task_choice_actions(queue, questions, home);
1237}
1238
1239/// Apply bounded maintenance effects independently of question ownership: a
1240/// release watcher need not have a queue task, and a predecessor is another run.
1241async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1242    for q in questions.list() {
1243        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1244            continue;
1245        };
1246        // Receipt paths use question IDs, whose format is independent of run
1247        // IDs. Apply the question store's filename safety rule to both eras.
1248        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1249            continue;
1250        }
1251        let dir = home.join("choice-actions");
1252        if std::fs::create_dir_all(&dir).is_err() {
1253            continue;
1254        }
1255        let Ok(lock) = std::fs::OpenOptions::new()
1256            .create(true)
1257            .truncate(false)
1258            .write(true)
1259            .open(dir.join(format!("{}.lock", q.id)))
1260        else {
1261            continue;
1262        };
1263        if crate::pr_head::try_lock_file(&lock).is_err() {
1264            continue;
1265        }
1266        let fresh = !home
1267            .join("choice-actions")
1268            .join(format!("{}.json", q.id))
1269            .exists();
1270        let result = async {
1271            let receipt = dir.join(format!("{}.json", q.id));
1272            if receipt.exists() {
1273                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1274                anyhow::ensure!(
1275                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1276                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1277                );
1278                return Ok::<_, anyhow::Error>(());
1279            }
1280            // Never retry an uncertain external effect. The receipt is written
1281            // before calling gh, exactly like release_watch's rerun record.
1282            let record = |status: &str| -> anyhow::Result<()> {
1283                let tmp = receipt.with_extension("tmp");
1284                std::fs::write(
1285                    &tmp,
1286                    serde_json::to_vec(&serde_json::json!({
1287                        "action": action, "status": status,
1288                    }))?,
1289                )?;
1290                std::fs::rename(tmp, &receipt)?;
1291                Ok(())
1292            };
1293            let applied = async {
1294                match action {
1295                    ask::ChoiceAction::ResumeRun { run } => {
1296                        crate::resume::validate(home, run)?;
1297                        record("started")?;
1298                        let decided = q.answered_at.unwrap_or(q.asked_at);
1299                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1300                            crate::resume::validate_unqueued(home, run)?;
1301                            crate::resume::start(home, run.clone()).await?;
1302                        }
1303                    }
1304                    ask::ChoiceAction::ReleaseTask {
1305                        task,
1306                        held_at,
1307                        reason,
1308                    } => {
1309                        anyhow::ensure!(
1310                            queue.resolve_id(task)? == *task,
1311                            "task action requires an exact task ID"
1312                        );
1313                        let _claim = queue.claim(task)?;
1314                        let mut task = queue.get(task)?;
1315                        if task.action_applied(&q.id) {
1316                            return Ok(());
1317                        }
1318                        // Filing this conductor question temporarily wraps the
1319                        // original hold in a Blocked state. Restore only that
1320                        // exact blocker on the local copy before checking the
1321                        // hold binding; unrelated waits never authorize release.
1322                        if q.node == crate::conduct::NODE
1323                            && q.run == task.id
1324                            && task.status == TaskStatus::Blocked
1325                            && task.blocked_from == Some(TaskStatus::Held)
1326                            && task.blocked_by.as_slice() == [q.id.as_str()]
1327                        {
1328                            task.unblock(&q.id);
1329                        }
1330                        anyhow::ensure!(
1331                            task.status == TaskStatus::Held
1332                                && task.held_at == Some(*held_at)
1333                                && task.hold_reason.as_deref() == reason.as_deref()
1334                                && task
1335                                    .operator_decided_at
1336                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1337                            "task no longer has the hold this question names"
1338                        );
1339                        task.release_operator("choice", Some(&q.id));
1340                        task.mark_action_applied(&q.id);
1341                        queue.put(&mut task)?;
1342                    }
1343                    ask::ChoiceAction::AbandonRun { run } => {
1344                        record("started")?;
1345                        crate::driver::abandon_proven_dead(home, run)?;
1346                    }
1347                    ask::ChoiceAction::RerunChecks {
1348                        repo,
1349                        pr,
1350                        head,
1351                        runs,
1352                    } => {
1353                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1354                            .await?;
1355                    }
1356                    _ => unreachable!(),
1357                }
1358                Ok::<_, anyhow::Error>(())
1359            }
1360            .await;
1361            match applied {
1362                Ok(()) => record("applied"),
1363                Err(e) => {
1364                    record(&format!("refused or failed: {e:#}"))?;
1365                    Err(e)
1366                }
1367            }
1368        }
1369        .await;
1370        // Retire the originating blocker as well as the target operation.
1371        // A foreign resume leaves its issuer held instead of competing beside
1372        // the execution just started. Other successful maintenance lets the
1373        // original task retry its normal, guarded path.
1374        if home
1375            .join("choice-actions")
1376            .join(format!("{}.json", q.id))
1377            .exists()
1378            && let Some(listed) = task_of_question(&queue.list(), &q)
1379            && !listed.action_applied(&q.id)
1380            && let Ok(_claim) = queue.claim(&listed.id)
1381            && let Ok(mut origin) = queue.get(&listed.id)
1382        {
1383            if !origin.operator_held()
1384                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1385                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1386            {
1387                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1388                    origin.hold_machine(Some(format!(
1389                        "Maintenance choice {} settled; inspect its target before releasing this task",
1390                        q.id
1391                    )));
1392                } else {
1393                    origin.unblock(&q.id);
1394                }
1395            }
1396            origin.mark_action_applied(&q.id);
1397            let _ = queue.put(&mut origin);
1398        }
1399        if let Err(e) = result
1400            && fresh
1401        {
1402            notices::raise_in(
1403                home,
1404                Notice::warn(
1405                    &format!("action:{}", q.id),
1406                    format!("Choice action {} was not completed: {e:#}", q.id),
1407                )
1408                .link(if q.run_names_task() {
1409                    Link::Task { id: q.run.clone() }
1410                } else {
1411                    Link::Run { id: q.run.clone() }
1412                }),
1413            );
1414        }
1415    }
1416}
1417
1418/// Rerun the named failed workflow runs of a pull request, each at most once
1419/// per `request` (a question id, or a chat operation identity). The head,
1420/// lifecycle and failed state are re-read from the forge first; `started` is
1421/// called once those checks pass and before the first external call, and the
1422/// ledger entry is written before every `gh` call, so an uncertain result is
1423/// never repeated automatically.
1424pub(crate) async fn rerun_checks_once(
1425    home: &Path,
1426    request: &str,
1427    repo: &Path,
1428    pr: &str,
1429    head: &str,
1430    runs: &[String],
1431    started: impl FnOnce() -> anyhow::Result<()>,
1432) -> anyhow::Result<()> {
1433    use crate::release_watch::{GhForge, ReleaseForge};
1434    anyhow::ensure!(
1435        !runs.is_empty()
1436            && runs.len() <= 20
1437            && runs
1438                .iter()
1439                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1440            && !pr.starts_with('-'),
1441        "invalid rerun targets"
1442    );
1443    let snap = GhForge.snapshot(repo, pr).await?;
1444    anyhow::ensure!(
1445        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1446        "pull request head or lifecycle changed"
1447    );
1448    anyhow::ensure!(
1449        runs.iter().all(|r| snap
1450            .checks
1451            .iter()
1452            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1453        "named workflow is no longer failed on this pull request"
1454    );
1455    started()?;
1456    let dir = home.join("choice-actions");
1457    std::fs::create_dir_all(&dir)?;
1458    let rerun_lock = std::fs::OpenOptions::new()
1459        .create(true)
1460        .truncate(false)
1461        .write(true)
1462        .open(dir.join("reruns.lock"))?;
1463    crate::pr_head::try_lock_file(&rerun_lock)?;
1464    let ledger = dir.join("reruns.json");
1465    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1466        serde_json::from_slice(&std::fs::read(&ledger)?)?
1467    } else {
1468        Default::default()
1469    };
1470    for run in runs {
1471        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1472        if !recorded.insert(key) {
1473            continue;
1474        }
1475        let tmp = ledger.with_extension("tmp");
1476        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1477        std::fs::rename(tmp, &ledger)?;
1478        GhForge.rerun(repo, run).await?;
1479    }
1480    Ok(())
1481}
1482
1483/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1484///
1485/// Runs on every poll before the conductor looks at the queue. The task is
1486/// re-read under its claim, so a task somebody completed or held by hand in
1487/// the meantime is judged on what it is now. `Resume` releases the task and
1488/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1489/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1490/// ordinary `unfinished_run` logic resumes that same run.
1491pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1492    let tasks = queue.list();
1493    for q in questions.list() {
1494        // Dismissal is committed by the question writer, never a resume.
1495        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1496            continue;
1497        }
1498        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1499            continue;
1500        }
1501        let Some(listed) = task_of_question(&tasks, &q) else {
1502            if q.node == land::APPROVAL_NODE
1503                && q.resolution().as_deref().is_some_and(|choice| {
1504                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1505                })
1506            {
1507                notices::raise_in(
1508                    home,
1509                    Notice::warn(
1510                        &format!("repair-owner:{}", q.id),
1511                        format!(
1512                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1513                            q.run, q.run
1514                        ),
1515                    ).link(Link::Run { id: q.run.clone() }),
1516                );
1517            }
1518            continue;
1519        };
1520        if listed.action_applied(&q.id) {
1521            continue;
1522        }
1523        let Ok(_claim) = queue.claim(&listed.id) else {
1524            continue;
1525        };
1526        let Ok(mut task) = queue.get(&listed.id) else {
1527            continue;
1528        };
1529        // Work only on this local copy until the action can be committed.
1530        // In particular, a fresh lease below leaves the persisted task blocked.
1531        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1532            let blockers: Vec<_> = task
1533                .blocked_by
1534                .iter()
1535                .filter(|id| {
1536                    crate::queue::dependency(queue, questions, id)
1537                        == crate::queue::Dependency::Question(q.id.clone())
1538                })
1539                .cloned()
1540                .collect();
1541            if !blockers.is_empty() {
1542                for id in blockers {
1543                    task.unblock(&id);
1544                }
1545                let answer = match &q.answer {
1546                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1547                    None => String::new(),
1548                };
1549                task.record_answer(q.summary.clone(), answer);
1550            }
1551        }
1552        let language = language_of(&task, Path::new("."));
1553        let decision = decide_action(&task, &q, phrases(&language), |id| {
1554            RunState::load_under(id, home)
1555        });
1556        let ran = matches!(
1557            decision,
1558            ActionDecision::Resume(_)
1559                | ActionDecision::Requeue
1560                | ActionDecision::Hold
1561                | ActionDecision::Done
1562        );
1563        if ran && asker_may_still_read(questions, &q, home) {
1564            // The asking process or its seat can still take the word; act
1565            // once it has gone quiet. Bound on the remaining window: the
1566            // check is not atomic with the write below, so an asker that
1567            // takes the word in between (at most one poll, never more than
1568            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1569            // and `Task::actions_applied` under the claim keeps the action to
1570            // one application. The waiter does not deliver an answer that
1571            // carries an action (`waiter::decide_owned`), so it cannot race.
1572            continue;
1573        }
1574        let done = matches!(decision, ActionDecision::Done);
1575        match decision {
1576            ActionDecision::Skip => continue,
1577            ActionDecision::Resume(run) => {
1578                task.release_operator("choice", Some(&q.id));
1579                task.resume_override = Some(crate::queue::OperatorResume {
1580                    question_id: q.id.clone(),
1581                    at: Timestamp::now(),
1582                    conductor_rehold: None,
1583                    forced: true,
1584                    pinned_run: Some(run),
1585                });
1586            }
1587            ActionDecision::Stale => {}
1588            ActionDecision::Requeue => {
1589                task.release_operator("choice-requeue", Some(&q.id));
1590                task.requeue();
1591            }
1592            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1593            ActionDecision::Done => task.succeed(),
1594            ActionDecision::Refuse(why) => {
1595                if task.operator_held() {
1596                    // A rejected answer does not release the operator's hold
1597                    // or reclassify it as recoverable by the conductor.
1598                    task.hold_reason = Some(match task.hold_reason.take() {
1599                        Some(reason) => format!("{reason}\n\n{why}"),
1600                        None => why,
1601                    });
1602                } else {
1603                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1604                    task.hold_machine(Some(why));
1605                }
1606                notices::raise(
1607                    Notice::warn(
1608                        &format!("action:{}", q.id),
1609                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1610                    )
1611                    .link(Link::Task {
1612                        id: task.id.clone(),
1613                    }),
1614                );
1615            }
1616        }
1617        task.mark_action_applied(&q.id);
1618        // The applied id travels with the transition, so a failed save loses
1619        // neither and the answer is acted on at the next poll.
1620        record(queue, &mut task);
1621        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1622            supersede_prior_runs(&task, home);
1623        }
1624        // Delivery is only a note of who has read the answer; the task's own
1625        // mark above is the authority. Best effort.
1626        let _ = questions.update(&q.id, |r| {
1627            r.answer_delivered = true;
1628            Ok(())
1629        });
1630    }
1631}
1632
1633/// Whether something may still read the answer to `q`: a fresh lease, or the
1634/// asking seat still listed as active in its run (its CLI can outlive the
1635/// `magi ask` that was killed).
1636fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1637    let now = Timestamp::now();
1638    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1639        return true;
1640    }
1641    q.node != crate::conduct::NODE
1642        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1643            s.seats_active()
1644                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1645        })
1646}
1647
1648/// Retire an unanswered conductor question after its task no longer refers to
1649/// it. Conductor questions use the task id in `Question::run`, so run-based
1650/// cleanup cannot observe a manual release or completion.
1651///
1652/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1653/// own question also carries a `run`, and a run id that happens to collide
1654/// with some task's id is not this loop's business — only a conductor
1655/// question actually uses the task id that way. One `Questions::list()` scan
1656/// is taken up front and matched against the in-memory task set, rather than
1657/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1658fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1659    let tasks = queue.list();
1660    let by_id: std::collections::BTreeMap<&str, &Task> =
1661        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1662    let referenced: Vec<&str> = tasks
1663        .iter()
1664        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1665        .collect();
1666
1667    for mut question in questions.list() {
1668        if !question.status.open() || question.node != crate::conduct::NODE {
1669            continue;
1670        }
1671        // Keep questions a task still names, including when the reference
1672        // moved to a dependent task.
1673        // Preserve even ambiguous references: retiring a possibly referenced
1674        // question is unsafe until the operator disambiguates it.
1675        if referenced
1676            .iter()
1677            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1678        {
1679            continue;
1680        }
1681        let Some(task) = by_id.get(question.run.as_str()) else {
1682            continue;
1683        };
1684        question.abandon(format!(
1685            "task {} no longer waits for this answer",
1686            task.short()
1687        ));
1688        if let Err(e) = questions.put(&mut question) {
1689            tracing::warn!(
1690                "could not retire question {} for task {}: {e:#}",
1691                question.short(),
1692                task.short()
1693            );
1694        }
1695    }
1696}
1697
1698/// What a finished run tells the queue about the task it came from.
1699///
1700/// A struct rather than a fourth and fifth boolean argument: the two flags
1701/// answer different questions about the same run, and a call site passing
1702/// `(…, true, false)` is one transposition away from refunding attempts
1703/// forever.
1704#[derive(Debug, Clone, Copy)]
1705pub struct Verdict {
1706    /// Where the graph stopped.
1707    pub status: RunStatus,
1708    /// The run opened a pull request.
1709    pub left_pr: bool,
1710    /// At least one seat was lost to a rate limit.
1711    pub quota_hit: bool,
1712    /// The run parked at a node boundary because it was asked to.
1713    pub parked: bool,
1714    /// The run never produced a single candidate a judge could look at.
1715    ///
1716    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1717    /// still have another candidate worth judging, in which case the loss was
1718    /// not the reason nothing came of the run. This is `true` only when the
1719    /// implement wave ended with nothing viable at all.
1720    pub no_viable_candidates: bool,
1721}
1722
1723/// Record a finished run against the task it came from.
1724///
1725/// Kept pure and separate from the loop because this mapping *is* the retry
1726/// policy, and a policy that can only be exercised by spawning a graph is a
1727/// policy nobody checks. The table:
1728///
1729/// | run status                           | task becomes        | attempt spent |
1730/// |---------------------------------------|---------------------|---------------|
1731/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1732/// | `Merged`, `Ready`                      | `Done`               | yes          |
1733/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1734/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1735/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1736/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1737/// | `Blocked` with a PR                    | `Held`               | yes          |
1738/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1739/// | `VerifiedNoop`                          | `Held`               | yes          |
1740/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1741///
1742/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1743/// deliberately: every candidate agreeing there is nothing to write is not a
1744/// machine fact about a rate limit, it is an unverified claim about the
1745/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1746/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1747/// claim could be wrong (a misread instruction, a stale check), and closing
1748/// the task automatically on an implementer's say-so would be the exact
1749/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1750/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1751/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1752/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1753/// claim regardless of whether the one already-spent attempt is refunded, and
1754/// [`Task::release`] resets the count to zero anyway the moment a human looks
1755/// at the evidence and lets it run again.
1756///
1757/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1758/// twice, together. A quorum lost to rate limits is a property of the machine
1759/// and not of the task, so the attempt is refunded and a reset quota picks
1760/// the work up where it stopped — and that is just as true when every
1761/// implement seat lost the same race and `after_implement` bails with nothing
1762/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1763/// machine fact. The `no_viable_candidates` guard is what keeps that row
1764/// narrow: a `Failed` run that produced a real candidate which then lost for
1765/// some other reason still spends the attempt, exactly like the quorum lost
1766/// to judges that answered with the wrong shape is ordinary flakiness, and
1767/// refunding *that* takes the bound off the retry loop entirely: run e633
1768/// stalled with `quota: []` after two judges wrote unusable JSON, was
1769/// refunded, and the next attempt paid for a fresh hour-long implement wave
1770/// before it could fail the same way. `max_attempts` exists precisely so
1771/// that cannot repeat forever.
1772///
1773/// A non-terminal status means `execute` returned while the graph was still
1774/// mid-flight, which is a bug rather than a verdict; it is treated as a
1775/// failure so that a task cannot loop on it either.
1776///
1777/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1778/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1779pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1780    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1781}
1782
1783/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1784fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1785    // A parked run is the operator's own doing, and its work is intact on
1786    // disk. The task goes back in line with its attempt refunded so the next
1787    // loop resumes the same run - which `one_task` prefers over competing
1788    // again - and so that swapping the binary a few times cannot exhaust a
1789    // budget meant for agents that actually misbehaved.
1790    if verdict.parked {
1791        task.park(detail);
1792        return;
1793    }
1794    match verdict.status {
1795        RunStatus::Merged | RunStatus::Ready
1796            if task.pr_recovery.as_ref().is_some_and(|s| {
1797                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1798            }) =>
1799        {
1800            task.hold_manual(Some("Public delivery is not confirmed. Inspect the selected PR and run, then use recover-pr --disposition land with the intended source and validation configuration.".into()));
1801        }
1802        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1803        RunStatus::AlreadyInBase => task.already_landed(detail),
1804        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1805        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1806            task.stall(detail)
1807        }
1808        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1809        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1810        RunStatus::Blocked => task.fail(detail, max_attempts),
1811        RunStatus::VerifiedNoop => task.handed_off(detail),
1812        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1813    }
1814}
1815
1816/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1817/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1818/// itself has actually finished *and* its own last attempt is provably why:
1819/// this loads that run and requires `Merged`/`Ready` before touching
1820/// anything earlier in `runs`, since `Task::succeed` can also be called
1821/// directly on a task whose last attempt never landed at all.
1822///
1823/// Called right after whatever call set `task.status` to
1824/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1825/// `reclaim`'s, but also every other place a task can be closed by hand
1826/// without the loop ever settling it itself: `magi task done`
1827/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1828/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1829/// GitHub merge, say, exactly the workflow this repository's own
1830/// "Landing a run's winner by hand" documents — is just as much "this task's
1831/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1832/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1833/// forever, which is the exact backlog this status exists to clear. `pub`
1834/// for those two out-of-module callers; everything else about this stays
1835/// internal bookkeeping.
1836///
1837/// A run something is still actually driving is left alone: a
1838/// task cannot be `Done` while one of its *own* attempts is still in flight,
1839/// so a live one at this point can only be an unrelated process — a manual
1840/// `--resume` of this old, now-moot run — and rewriting under it would just
1841/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1842/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1843/// pair `run_report`/`run_detail` use for the same question elsewhere:
1844/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1845/// --resume` invoked by hand outside it, which `liveness` also checks via
1846/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1847/// (already terminal in some other way, or itself mid-run) is left untouched
1848/// too.
1849///
1850/// Best-effort, like the rest of this module's bookkeeping: a load or save
1851/// failure here is a `tracing::warn`, not a failed settle, and the next time
1852/// this same task's completion is recorded — or a daemon restart replays
1853/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1854/// separate reconciliation pass; if that gap ever matters in practice, one
1855/// can be added then.
1856///
1857/// `home` is a parameter, not the process-global [`crate::run::home`], for
1858/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1859/// calls this with `ui.home`, which is `crate::run::home()` in a real
1860/// process but a fixture's own directory under test — falling through to
1861/// the global there would read and write through whichever home some other
1862/// test in the same binary happened to pin into that `OnceLock` first, not
1863/// the run this call actually means.
1864pub fn supersede_prior_runs(task: &Task, home: &Path) {
1865    let now = Timestamp::now();
1866    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1867    // right behind a `Merged`/`Ready` verdict) from one set directly by
1868    // `magi task done`/its web equivalent/the conductor on a task whose last
1869    // recorded attempt never actually landed - that requires reading the
1870    // run itself, which is exactly what this does before trusting anything
1871    // in `runs` is safe to relabel.
1872    let last_run_succeeded = task
1873        .runs
1874        .last()
1875        .and_then(|id| RunState::load_under(id, home).ok())
1876        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1877    for id in task.superseded_attempts(last_run_succeeded) {
1878        let mut state = match RunState::load_under(id, home) {
1879            Ok(s) => s,
1880            Err(e) => {
1881                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1882                continue;
1883            }
1884        };
1885        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1886            continue;
1887        }
1888        let daemon_claims = is_working_on(home, id, now);
1889        if state.liveness(daemon_claims) == Liveness::Live {
1890            continue;
1891        }
1892        state.status = RunStatus::Superseded;
1893        if let Err(e) = state.save_under(home) {
1894            tracing::warn!("could not mark run {id} superseded: {e:#}");
1895        }
1896    }
1897}
1898
1899/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1900/// finish the moment it was called, because one of its earlier attempts was
1901/// still live then - a `magi run --resume` invoked by hand on an old run,
1902/// most likely.
1903///
1904/// That skip is correct at the time (rewriting under a run something is
1905/// still actively saving would just be undone), but a task only ever
1906/// reaches `Done` once, so without this nothing would ever look at it
1907/// again: if that manual process later ends anywhere other than
1908/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1909/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1910/// backlog this status exists to clear. Called on the same idle-only
1911/// cadence as [`janitor`], next to it rather than folded into it: this
1912/// walks `queue` and `janitor` never otherwise needs one.
1913///
1914/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1915/// more than one attempt, every pass: each call is a handful of local file
1916/// reads bounded by that task's own attempt count, the same order of cost
1917/// [`clean::fold_due`] already pays scanning every run on disk on the same
1918/// cadence, and a task already fully resolved costs one failed liveness
1919/// check turned no-op the moment its lingering attempt is no longer live.
1920fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1921    for task in queue.list() {
1922        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1923            continue;
1924        }
1925        supersede_prior_runs(&task, home);
1926    }
1927}
1928
1929/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1930/// task ends up held.
1931///
1932/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1933/// dead daemon never got back to) share this, so the two cannot drift into
1934/// disagreeing about which held tasks get a diagnostic.
1935fn settle_and_diagnose(
1936    task: &mut Task,
1937    verdict: Verdict,
1938    detail: &str,
1939    max_attempts: usize,
1940    state: &RunState,
1941) {
1942    let p = phrases(&state.config.graph.language);
1943    // Shared by normal completion and crash recovery, under the task claim.
1944    // No new attempt can own the task until the old driver has exited.
1945    if let Some(d) = &state.merge_decision {
1946        use crate::merge_decision as md;
1947        if task.runs.last().is_some_and(|id| id != &state.id) {
1948            return;
1949        }
1950        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1951            task.succeed();
1952        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1953            if state.liveness(false) != Liveness::Dead {
1954                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1955                return;
1956            }
1957            let replacement = md::Replacement {
1958                question: d.question.clone(),
1959                run: state.id.clone(),
1960                pr: d.target.pr.clone(),
1961                agent: agent.to_owned(),
1962                context: format!(
1963                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1964                    d.target.pr,
1965                    state.id,
1966                    serde_json::to_string(&state.reviews).unwrap_or_default()
1967                ),
1968            };
1969            task.requeue();
1970            task.pr_recovery = None;
1971            task.review_of = None;
1972            task.replacement = Some(replacement);
1973        } else {
1974            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1975                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1976            } else { format!("PR closure was not confirmed. Task held; inspect the existing run before starting replacement work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str())) }));
1977        }
1978        task.mark_action_applied(&d.question);
1979        if let Some(pass) = state.passes.last() {
1980            task.record_pass_at(
1981                &state.id,
1982                pass.index,
1983                Some(pass.started_at),
1984                task.attempts,
1985                None,
1986            );
1987        }
1988        return;
1989    }
1990    if let Some(replacement) = &task.replacement
1991        && !state.parked
1992        && state.resource_block.is_none()
1993        && (state.viable().is_empty()
1994            || (state.status == RunStatus::Blocked && state.tally.is_none()))
1995    {
1996        task.hold_manual(Some(format!("Selected implementer `{}` was unavailable, failed or hit quota before producing a viable implementation. No other implementer was dispatched. Inspect the run, restore availability, then explicitly release this task.", replacement.agent)));
1997        return;
1998    }
1999    let attempts_before = task.attempts;
2000    // A run that stopped because a shared resource stayed busy was never a
2001    // failure of the task or of an agent. Earlier nodes may have run; only
2002    // the blocked operation lacks a result. The attempt is
2003    // refunded and the task is held by the machine, under a reason `triage`
2004    // can re-check, so the same run resumes with the same agents once the
2005    // resource is free. A park request still wins (it is the operator's).
2006    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2007        task.notice_cause(
2008            &format!("resource:{}:{}", block.kind, block.node),
2009            None,
2010            None,
2011        );
2012        task.last_error = Some(detail.to_owned());
2013        task.diagnostic = None;
2014        task.attempts = task.attempts.saturating_sub(1);
2015        if block.kind == "disk pressure" {
2016            task.hold_machine(Some(format!(
2017                "{}{}",
2018                crate::disk::RUNNING_PRESSURE,
2019                block.detail
2020            )));
2021        } else {
2022            task.hold_machine(Some(format!(
2023                "{}{}; no attempt was spent; resume to retry the affected operation",
2024                crate::cache::RESOURCE_HOLD,
2025                block.description()
2026            )));
2027        }
2028        if let Some(pass) = state.passes.last() {
2029            task.record_pass_at(
2030                &state.id,
2031                pass.index,
2032                Some(pass.started_at),
2033                attempts_before,
2034                None,
2035            );
2036        }
2037        return;
2038    }
2039    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2040        state.parked
2041            && state.status == RunStatus::Landing
2042            && state
2043                .pr_pushed_head
2044                .as_ref()
2045                .is_none_or(|h| h == &hold.head)
2046            && task.runs.last() == Some(&state.id)
2047    }) {
2048        // Settlement and crash recovery share this idempotency key. A later
2049        // explicit resume is a new pass and may refund its own attempt once.
2050        let pass = state.passes.last().map_or(0, |p| p.index);
2051        if !task
2052            .passes
2053            .iter()
2054            .any(|p| p.run == state.id && p.pass_index == pass)
2055        {
2056            task.attempts = task.attempts.saturating_sub(1);
2057        }
2058        task.hold_machine(Some(format!(
2059            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2060            hold.question
2061        )));
2062        task.last_error = Some(detail.to_owned());
2063        task.diagnostic = None;
2064        task.record_pass_at(
2065            &state.id,
2066            pass,
2067            state.passes.last().map(|p| p.started_at),
2068            attempts_before,
2069            Some(crate::run::ParkCause::Question),
2070        );
2071        return;
2072    }
2073    let unresolved = task.hold_notice_cause.clone();
2074    if !verdict.parked
2075        && task
2076            .pr_recovery
2077            .as_ref()
2078            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2079        && matches!(
2080            verdict.status,
2081            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2082        )
2083    {
2084        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2085            task.succeed();
2086        } else {
2087            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()));
2088        }
2089    } else if !verdict.parked
2090        && task.pr_recovery.is_some()
2091        && matches!(
2092            verdict.status,
2093            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2094        )
2095        && !verdict.quota_hit
2096    {
2097        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.")));
2098    } else {
2099        settle_in(task, verdict, detail, max_attempts, p);
2100    }
2101    if !verdict.parked
2102        && !verdict.quota_hit
2103        && matches!(
2104            verdict.status,
2105            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2106        )
2107    {
2108        task.recovery_failed(state);
2109    }
2110    if state.prep_failure.is_some() {
2111        // Minting a run whose candidates could not be prepared is not work
2112        // on a newly approved attempt. Keep the unresolved outcome anchor.
2113        task.hold_notice_cause = unresolved;
2114        task.startup_notice_cause("startup-candidates");
2115    }
2116    // Written here, where the refund (or not) is decided, so the history is a
2117    // fact and not a later guess from the run's status.
2118    if let Some(pass) = state.passes.last() {
2119        let parked = match &pass.end {
2120            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2121            _ => None,
2122        };
2123        task.record_pass_at(
2124            &state.id,
2125            pass.index,
2126            Some(pass.started_at),
2127            attempts_before,
2128            parked,
2129        );
2130    }
2131    if task.status == TaskStatus::Held {
2132        if state.prep_failure.is_none() {
2133            task.notice_cause(
2134                label(verdict.status),
2135                Some(&state.id),
2136                state.passes.last().map(|p| p.index),
2137            );
2138        }
2139        task.diagnostic = diagnostic(state);
2140        note_open_question(task, &state.id, p);
2141    }
2142}
2143
2144/// If `task` is held with a `magi ask` question still open on `run`, name the
2145/// question in [`Task::hold_reason`] rather than leaving the hold reading
2146/// only [`describe`]'s run summary.
2147///
2148/// This is the shape task 20260928-191407-05fd left underspecified: an
2149/// implementer settled a verified no-op and filed a question for the
2150/// operator, and the hold that followed said nothing about the question
2151/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2152/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2153/// marker) and must keep seeing it unchanged.
2154///
2155/// Best-effort: an unreadable question store must not stop a run from
2156/// settling, so this is a no-op rather than a propagated error when
2157/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2158fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2159    let Some(home) = crate::run::try_home() else {
2160        return;
2161    };
2162    let open = Questions::at(home.join("questions")).open_for(run);
2163    let Some(q) = open.first() else {
2164        return;
2165    };
2166    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2167    decisions.sort_unstable();
2168    task.notice_cause(
2169        &format!("questions:{}", decisions.join(",")),
2170        Some(run),
2171        None,
2172    );
2173    let base = task.hold_reason.clone().unwrap_or_default();
2174    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2175}
2176
2177/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2178/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2179/// by some other means entirely, like a manual `magi run` resume that
2180/// finishes the graph outside the queue's bookkeeping.
2181///
2182/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2183/// `settle` is separate from `attempt`: a task recovered this way must land
2184/// exactly where a live daemon would have put it — the same policy table,
2185/// not a second one that quietly drifts from it — and that is only checkable
2186/// without spawning a real run.
2187fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2188    match last_run {
2189        Some(state) => {
2190            let verdict = Verdict {
2191                status: state.status,
2192                left_pr: state.pr.is_some(),
2193                quota_hit: !state.quota.is_empty(),
2194                parked: state.parked,
2195                no_viable_candidates: state.viable().is_empty(),
2196            };
2197            let detail = format!(
2198                "{}{}",
2199                phrases(&state.config.graph.language).recovered_running,
2200                describe(&state)
2201            );
2202            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2203        }
2204        None => {
2205            // No run, so no config of its own: `language` is the task's
2206            // repository's setting, read by the caller.
2207            let why = phrases(language).no_run_to_recover;
2208            task.last_error = Some(why.to_owned());
2209            // The phone shows `hold_reason`, so a task held by the machine
2210            // says why there too and not only in `last_error`.
2211            task.notice_cause("missing-run", None, None);
2212            task.hold_machine(Some(why.to_owned()));
2213        }
2214    }
2215}
2216
2217/// Find every task left at `running` that no live process is actually
2218/// driving, and settle each one against whatever its last run became.
2219///
2220/// # Why a claim is proof, not a guess
2221///
2222/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2223/// `running`, and the guard is held for the task's whole time in that status:
2224/// `attempt` does not return, and the loop does not move past the scope
2225/// holding the claim, until the run has settled. So a `running` task whose
2226/// lock is gone cannot have a live owner — this process or any other —
2227/// without needing a staleness threshold or a pid check the way
2228/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2229/// task that never got as far as `running` at all. Taking the claim here is
2230/// the whole test: it either fails, because something really does hold it
2231/// and the task is left alone, or it succeeds, which is the proof — and it is
2232/// kept for the rest of the decision so nothing else can start a competing
2233/// run while this one is being written.
2234///
2235/// Called on every poll, not only at startup, for the reason
2236/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2237/// keep noticing this, not only on the one morning it happened to restart.
2238fn reclaim_orphaned_running(
2239    queue: &Queue,
2240    max_attempts: usize,
2241    live_workers: &std::collections::BTreeSet<String>,
2242) -> Vec<String> {
2243    let mut reclaimed = Vec::new();
2244    for listed in queue.list() {
2245        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2246            continue;
2247        }
2248        let Ok(_claim) = queue.claim(&listed.id) else {
2249            continue;
2250        };
2251        // Re-read under the claim: a release or an edit landed by a human
2252        // between the listing above and the claim just taken must not be
2253        // clobbered by a decision based on the stale copy.
2254        let Ok(mut task) = queue.get(&listed.id) else {
2255            continue;
2256        };
2257        if task.status != TaskStatus::Running {
2258            continue;
2259        }
2260        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2261        // `execute` normally abandons a run's own open questions the moment
2262        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2263        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2264        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2265        // with the question still `open`, because the process died before
2266        // reaching that call. `reclaim` itself stays pure on purpose (see its
2267        // own doc), so the same cleanup runs here instead, against the run
2268        // this reclaim is already reading. `settle_run` costs nothing when
2269        // `execute` already got there first.
2270        if let Some(state) = &last_run
2271            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2272        {
2273            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2274        }
2275        let language = if last_run.is_none() {
2276            language_of(&task, Path::new("."))
2277        } else {
2278            String::new()
2279        };
2280        reclaim(&mut task, last_run, max_attempts, &language);
2281        if task.status == TaskStatus::Done {
2282            supersede_prior_runs(&task, &crate::run::home());
2283        }
2284        record(queue, &mut task);
2285        reclaimed.push(task.id.clone());
2286    }
2287    reclaimed
2288}
2289
2290/// Find every run whose `run.json` is provably dead — every seat it still
2291/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2292/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2293/// not merely "no daemon claims it" — and fail it, clearing the leftover
2294/// active seats so the run stops reading as `implementing` (or whichever
2295/// node) forever.
2296///
2297/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2298/// `running`, using whatever `run.json` already says — but nothing in that
2299/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2300/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2301/// never got back to sits exactly where it was left: `active` full of seats
2302/// nobody will ever answer for, `status` stuck on whatever node was in
2303/// flight. `magi show` already tells an operator this in prose (`no live
2304/// daemon claims this run right now`); this is what makes that fact durable
2305/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2306/// stay stuck once nothing is driving it.
2307///
2308/// Runs on every poll, not only at startup, for the reason
2309/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2310/// daemon up for days must keep noticing a run some other, now-dead, daemon
2311/// left behind just as readily as one it trips over on the way up.
2312///
2313/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2314/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2315/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2316/// `runs` directory instead: `home` here is a parameter precisely so a test
2317/// can point it away from the operator's real history (see [`drive`]'s own
2318/// doc), and a scan that fell through to the global home anyway would walk
2319/// whichever directory some *other* process or test pinned into that
2320/// `OnceLock` first — mutating runs this call was never handed.
2321fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2322    reclaim_abandoned_runs_with(
2323        home,
2324        now,
2325        crate::proc::pid_status,
2326        crate::proc::process_started_at,
2327    )
2328}
2329
2330/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2331/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2332/// for the identical reason: this sweep's real damage (wiping a run's active
2333/// seats and failing it) has to be provable against an injected answer in a
2334/// test, not just the real process table.
2335fn reclaim_abandoned_runs_with<F, G>(
2336    home: &Path,
2337    now: Timestamp,
2338    query: F,
2339    identity: G,
2340) -> Vec<String>
2341where
2342    F: Fn(u32) -> Option<bool>,
2343    G: Fn(u32) -> Option<String>,
2344{
2345    let mut abandoned = Vec::new();
2346    for entry in std::fs::read_dir(home.join("runs"))
2347        .into_iter()
2348        .flatten()
2349        .flatten()
2350    {
2351        let id = entry.file_name().to_string_lossy().into_owned();
2352        if !crate::run::is_run_id(&id) {
2353            continue;
2354        }
2355        // Serialize the proof and save with claims and takeover: a new
2356        // execution must not be overwritten after the liveness observation.
2357        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2358            continue;
2359        };
2360        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2361        // that module's docs for why a run this cannot parse is left alone
2362        // rather than guessed at. A different schema number is not that: this
2363        // touches only `status` and `active`, never a field whose meaning a
2364        // schema bump changed, so an old record's values serve this exactly
2365        // as well as a current one's (see `clean::read_state`'s own doc for
2366        // the same reasoning applied to folding).
2367        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2368            continue;
2369        };
2370        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2371            continue;
2372        };
2373        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2374            continue;
2375        }
2376        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2377        // it", which is also the normal, healthy shape of a manual `magi
2378        // run` / `magi review` sharing this same home — this scan walks
2379        // every run on disk, not only ones this daemon itself started. Such
2380        // a run's active seats can legitimately sit past their own timeout
2381        // for a little while (the CLI finishing up, its result still being
2382        // collected) without the process driving it having died. `liveness`
2383        // is what actually tells the two apart, by corroborating
2384        // `driver_pid` against the process it names — see its own doc. Only
2385        // its strongest, provable answer licenses wiping this run's active
2386        // seats and failing it out from under whatever is still running it.
2387        let daemon_claims = is_working_on(home, &id, now);
2388        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2389            != crate::run::Liveness::Dead
2390        {
2391            continue;
2392        }
2393        state.abandon("daemon");
2394        if let Err(e) = state.save_under(home) {
2395            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2396            continue;
2397        }
2398        // This run never passes through `Runner::execute` again, so its end
2399        // is announced here.
2400        if let Some(notice) = notices::run_ended(&state) {
2401            notices::raise_in(home, notice);
2402        }
2403        // The seat that asked is gone for good now, exactly like any other
2404        // door `graph::Runner::settle_questions` closes the moment `status`
2405        // lands somewhere non-resumable - see that method's own doc. Nothing
2406        // else reaches this one before the next `janitor()` startup pass
2407        // (`clean::abandon_settled_questions`), and a daemon that stays up
2408        // for days must not leave an open question badging the operator
2409        // until it happens to restart.
2410        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2411            tracing::warn!("abandon questions for {id}: {e:#}");
2412        }
2413        abandoned.push(id);
2414    }
2415    abandoned
2416}
2417
2418#[derive(Debug, Clone, Serialize, Deserialize)]
2419struct TaskWorker {
2420    opts: Opts,
2421    queue: PathBuf,
2422    task: String,
2423    #[serde(default)]
2424    lane: PermitKind,
2425    #[serde(default)]
2426    standalone: bool,
2427}
2428
2429fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2430    Ok(crate::worker::active(home)?
2431        .into_iter()
2432        .filter(|job| job.kind == "task")
2433        .collect())
2434}
2435
2436fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2437    task_jobs(home)?
2438        .into_iter()
2439        .filter_map(
2440            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2441                Ok(request) if !request.standalone => Some(Ok(job)),
2442                Ok(_) => None,
2443                Err(error) => Some(Err(error.into())),
2444            },
2445        )
2446        .collect()
2447}
2448
2449/// Whether an independent scheduler can be controlled without its web parent.
2450#[must_use]
2451pub fn managed(home: &Path) -> bool {
2452    match crate::worker::active(home) {
2453        Err(error) => {
2454            tracing::error!("cannot determine scheduler ownership: {error:#}");
2455            true
2456        }
2457        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2458        Ok(_) => {
2459            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2460                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2461        }
2462    }
2463}
2464
2465/// Start a detached, singleton scheduler using this executable generation.
2466pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2467    anyhow::ensure!(
2468        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2469        "the scheduler is stopping; wait for retirement before starting it again"
2470    );
2471    crate::worker::spawn(
2472        home,
2473        "scheduler",
2474        "scheduler",
2475        serde_json::to_value(opts.absolute()?)?,
2476    )
2477    .await
2478}
2479
2480fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2481    home.join("worker-parks").join(format!("{}.json", job.id))
2482}
2483
2484fn request_task_park(
2485    home: &Path,
2486    job: &crate::worker::Job,
2487    cause: crate::run::ParkCause,
2488) -> Result<()> {
2489    let path = park_request_path(home, job);
2490    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2491    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2492    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2493}
2494
2495/// Stop dispatch immediately; only an explicit park reaches existing workers.
2496pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2497    if control == crate::worker::Control::Park {
2498        for job in owned_task_jobs(home)? {
2499            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2500        }
2501    }
2502    crate::worker::request(home, "scheduler", control)
2503}
2504
2505/// Replace the scheduler, leaving all active task and conversation jobs alone.
2506pub async fn restart_detached(home: &Path) -> Result<()> {
2507    let active = crate::worker::active(home)?;
2508    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2509    if prior.is_none() && !managed(home) {
2510        return Ok(());
2511    }
2512    let opts: Opts = match prior {
2513        Some(job) => serde_json::from_value(job.payload)?,
2514        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2515    };
2516    request_control(home, crate::worker::Control::Stop)?;
2517    loop {
2518        let reserved = crate::worker::active(home)?
2519            .iter()
2520            .any(|job| job.kind == "scheduler");
2521        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2522            break;
2523        }
2524        tokio::time::sleep(Duration::from_millis(100)).await;
2525    }
2526    spawn_detached(home, &opts).await?;
2527    Ok(())
2528}
2529
2530/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2531pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2532    let opts: Opts = serde_json::from_value(payload)?;
2533    let _ = home;
2534    serve_until(opts, Stop::new()).await
2535}
2536
2537/// Execute and settle one task with the queue claim owned by this process.
2538pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2539    let request: TaskWorker = serde_json::from_value(payload)?;
2540    let queue = Queue::at(request.queue);
2541    let key = format!("task:{}", request.task);
2542    let job = task_jobs(home)?
2543        .into_iter()
2544        .find(|job| job.key == key)
2545        .context("task worker reservation is missing")?;
2546    let park_path = park_request_path(home, &job);
2547    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2548    // our durable reservation. Never execute before that ownership hand-off.
2549    let _claim = loop {
2550        match queue.claim(&request.task) {
2551            Ok(claim) => break claim,
2552            // Only contention (the claim file exists) is worth waiting out; an
2553            // I/O failure must end this worker instead of pinning its lane.
2554            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2555                return Err(e.context("claim the task for its worker"));
2556            }
2557            Err(_) => {
2558                sweep_stale_claims(&queue, STALE_CLAIM);
2559                tokio::time::sleep(Duration::from_millis(50)).await;
2560            }
2561        }
2562    };
2563    let mut task = queue.get(&request.task)?;
2564    if !task.status.runnable()
2565        || (!request.standalone
2566            && request.lane
2567                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2568    {
2569        return Ok(());
2570    }
2571    let stop = Stop::new();
2572    let watcher = {
2573        let home = home.to_path_buf();
2574        let stop = stop.clone();
2575        let park_path = park_path.clone();
2576        tokio::spawn(async move {
2577            loop {
2578                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2579                    let cause = std::fs::read(&park_path)
2580                        .ok()
2581                        .and_then(|body| serde_json::from_slice(&body).ok())
2582                        .unwrap_or(crate::run::ParkCause::Operator);
2583                    stop.park(cause);
2584                    return;
2585                }
2586                tokio::time::sleep(Duration::from_millis(200)).await;
2587            }
2588        })
2589    };
2590    let quota = if request.standalone {
2591        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2592    } else {
2593        let status = Arc::new(Mutex::new(Status::new()));
2594        Box::pin(attempt(
2595            &request.opts,
2596            &queue,
2597            &status,
2598            &stop,
2599            crate::graph::Pause::new(),
2600            &mut task,
2601        ))
2602        .await
2603    };
2604    watcher.abort();
2605    let _ = std::fs::remove_file(park_path);
2606    persist_cooldown(home, &quota).await?;
2607    Ok(())
2608}
2609
2610/// Launch the standalone task worker with a claim-to-reservation handoff.
2611/// Returns only after the worker owns a durable execution reservation.
2612pub async fn spawn_claimed(
2613    home: &Path,
2614    opts: &Opts,
2615    queue: &Queue,
2616    task: &Task,
2617    claim: crate::queue::Claim,
2618) -> Result<crate::worker::Job> {
2619    let request = TaskWorker {
2620        opts: opts.absolute()?,
2621        queue: std::path::absolute(queue.root())?,
2622        task: task.id.clone(),
2623        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2624        standalone: true,
2625    };
2626    let job = crate::worker::spawn(
2627        home,
2628        "task",
2629        &format!("task:{}", task.id),
2630        serde_json::to_value(request)?,
2631    )
2632    .await?;
2633    drop(claim);
2634    Ok(job)
2635}
2636
2637/// Transfer a standalone caller's claim only after the detached worker is live,
2638/// then follow that worker to its final (non-automatically-retrying) outcome.
2639pub async fn run_detached_claimed(
2640    opts: &Opts,
2641    queue: &Queue,
2642    task: &mut Task,
2643    claim: crate::queue::Claim,
2644) -> Result<()> {
2645    let home = crate::run::home();
2646    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2647    loop {
2648        // Reconcile execution leases even without a scheduler. A dead worker
2649        // must become a reported failure, never an infinite persisted wait.
2650        crate::worker::active(&home)?;
2651        let current = crate::worker::get(&home, &job.id)?;
2652        if matches!(
2653            current.status,
2654            crate::worker::Status::Finished | crate::worker::Status::Failed
2655        ) {
2656            *task = queue.get(&task.id)?;
2657            anyhow::ensure!(
2658                current.status != crate::worker::Status::Failed,
2659                "task worker failed: {}",
2660                current.result.as_deref().unwrap_or("unknown failure")
2661            );
2662            return Ok(());
2663        }
2664        tokio::time::sleep(Duration::from_millis(200)).await;
2665    }
2666}
2667
2668async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2669    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2670        let _lease = loop {
2671            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2672                break lease;
2673            }
2674            tokio::time::sleep(Duration::from_millis(10)).await;
2675        };
2676        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2677            let path = home.join("task-quota-cooldown.json");
2678            let temporary = path.with_extension("json.tmp");
2679            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2680            std::fs::rename(temporary, path)?;
2681        }
2682    }
2683    Ok(())
2684}
2685
2686fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2687    match std::fs::read(home.join("task-quota-cooldown.json")) {
2688        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2689        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2690        Err(error) => Err(error.into()),
2691    }
2692}
2693
2694/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2695///
2696/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2697/// sets, so there is one loop body rather than two that drift apart the first
2698/// time the retry policy changes on only one of them.
2699pub async fn serve(opts: Opts) -> Result<()> {
2700    tracing::info!(
2701        "automatic update and restart requires magi web; standalone serve does not restart"
2702    );
2703    serve_until(opts, Stop::new()).await
2704}
2705
2706/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2707///
2708/// A stop retires dispatch promptly, including while a worker launch is being
2709/// acknowledged. Already reserved workers own their attempts independently and
2710/// finish with their started executable. Explicit park additionally forwards
2711/// durable park requests; neither scheduler retirement nor update does so.
2712///
2713/// While the queue is empty the stop is honoured within one wakeup rather than
2714/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2715/// caller that taps stop does not sit through the remainder of a sleep.
2716pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2717    let opts = opts.absolute()?;
2718    let home = crate::run::home();
2719    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2720        .context("another scheduler already owns this home")?;
2721    if let Some(reading) = read_status(&home)
2722        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2723    {
2724        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2725    }
2726    if !crate::worker::active(&home)?
2727        .iter()
2728        .any(|job| job.kind == "scheduler")
2729    {
2730        crate::worker::clear_control(&home, "scheduler")?;
2731    }
2732    std::fs::write(
2733        home.join("scheduler-options.json"),
2734        serde_json::to_vec(&opts)?,
2735    )?;
2736    let control = {
2737        let home = home.clone();
2738        let stop = stop.clone();
2739        tokio::spawn(async move {
2740            loop {
2741                match crate::worker::control(&home, "scheduler").ok().flatten() {
2742                    Some(crate::worker::Control::Park) => {
2743                        let _ = request_control(&home, crate::worker::Control::Park);
2744                        stop.park(crate::run::ParkCause::Operator);
2745                        break;
2746                    }
2747                    Some(crate::worker::Control::Stop) => {
2748                        stop.stop();
2749                        break;
2750                    }
2751                    None => {}
2752                }
2753                tokio::time::sleep(Duration::from_millis(100)).await;
2754            }
2755        })
2756    };
2757    let signal = {
2758        let stop = stop.clone();
2759        tokio::spawn(async move {
2760            if tokio::signal::ctrl_c().await.is_ok() {
2761                stop.stop();
2762                tracing::info!("scheduler shutdown requested; independent workers continue");
2763            }
2764        })
2765    };
2766
2767    let worktrees_root = opts
2768        .worktrees_root
2769        .clone()
2770        .unwrap_or_else(crate::run::default_worktree_root);
2771    let outcome = drive(
2772        &opts,
2773        &Queue::open(),
2774        &status_path(),
2775        &crate::run::home(),
2776        &worktrees_root,
2777        &stop,
2778    )
2779    .await;
2780
2781    signal.abort();
2782    control.abort();
2783    outcome
2784}
2785
2786/// The loop proper: setup, poll, teardown, with the queue and the status file
2787/// supplied rather than discovered.
2788///
2789/// All three of `home`, `worktrees_root` and the queue/status paths are
2790/// parameters rather than resolved here, for the same reason:
2791/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2792/// so a unit test that pinned it would fight every other test in the binary,
2793/// and a loop that resolved its own worktree bay could only be exercised
2794/// against the operator's real `~/wt/<repo>` - publishing over a live
2795/// daemon's status file, claiming tasks out of a live backlog, and, since
2796/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2797/// whatever the operator actually has on disk.
2798async fn drive(
2799    opts: &Opts,
2800    queue: &Queue,
2801    status_file: &Path,
2802    home: &Path,
2803    worktrees_root: &Path,
2804    stop: &Stop,
2805) -> Result<()> {
2806    // The status file is a *snapshot*, not a stream of events: a reader only
2807    // ever wants the latest values, and every tick rewrites the whole file
2808    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2809    // while an mpsc channel would force the loop to re-send unchanged fields on
2810    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2811    // for no gain. The lock is only ever held across a field assignment, never
2812    // across an await.
2813    let recovery_cfg = prepare(&opts.repo, opts).ok();
2814    let daemon_cfg = recovery_cfg
2815        .as_ref()
2816        .map(|c| c.daemon.clone())
2817        .unwrap_or_default();
2818    let reconciled = crate::driver::reconcile(home);
2819    if !reconciled.is_empty() {
2820        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2821    }
2822    let mut initial_status = Status::new();
2823    let owned = owned_task_jobs(home)?;
2824    initial_status.current = current_work(home, Timestamp::now())
2825        .into_iter()
2826        .filter(|current| {
2827            owned
2828                .iter()
2829                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2830        })
2831        .collect();
2832    initial_status.idle = initial_status.current.is_empty();
2833    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2834        recovery_cfg.as_ref(),
2835        daemon_cfg.max_deputies,
2836    ));
2837    let status = Arc::new(Mutex::new(initial_status));
2838    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2839    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2840
2841    // Read once at startup, not per task: how many runs this loop drives at
2842    // once is a property of the machine running it, not of whichever
2843    // repository a given task happens to name - see
2844    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2845    // fact in the same sense the agent roster is.
2846    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2847
2848    tracing::info!(
2849        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2850        queue.root().display(),
2851        opts.poll.as_secs(),
2852        opts.max_attempts,
2853        concurrency,
2854        if daemon_cfg.pause_for_interrupts {
2855            ", interrupts enabled"
2856        } else {
2857            ""
2858        }
2859    );
2860
2861    let outcome = tokio::select! {
2862        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2863            max_concurrent: concurrency,
2864            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2865            recovery_cfg,
2866        }) => outcome,
2867        () = async {
2868            while !stop.stopped() {
2869                tokio::time::sleep(Duration::from_millis(25)).await;
2870            }
2871        } => {
2872            if stop.parking() {
2873                request_control(home, crate::worker::Control::Park)?;
2874            }
2875            Ok(())
2876        }
2877    };
2878
2879    stop.busy.store(0, Ordering::SeqCst);
2880    beat.abort();
2881    clear_status_at(status_file);
2882    outcome
2883}
2884
2885/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2886/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2887pub(crate) fn release_watch_settings_from_config(
2888    home: &Path,
2889    repo: &Path,
2890    cfg: &Config,
2891) -> (Vec<PathBuf>, u64) {
2892    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2893        .into_iter()
2894        .map(|r| r.path)
2895        .collect();
2896    // Repositories the daemon has worked in, wherever they live: a task may
2897    // name one outside `[repos] roots`, and its release PR must be watched too.
2898    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
2899        .list()
2900        .into_iter()
2901        .map(|t| t.repo)
2902        .collect();
2903    let runs = home.join("runs");
2904    for id in crate::run::list_ids_in(&runs) {
2905        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2906            .ok()
2907            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2908            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2909        known.extend(repo);
2910    }
2911    for k in known {
2912        let k = k.canonicalize().unwrap_or(k);
2913        if k.join(".git").exists() && !paths.contains(&k) {
2914            paths.push(k);
2915        }
2916    }
2917    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2918    if !paths.contains(&own) {
2919        paths.push(own);
2920    }
2921    (paths, cfg.daemon.release_stall_minutes)
2922}
2923
2924/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2925const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2926
2927/// Refresh the status file on a fixed tick.
2928///
2929/// Separate from the loop because a run takes tens of minutes: a status file
2930/// written only between tasks would look stale for the whole of every run, and
2931/// a reader would report the daemon dead exactly while it was busiest.
2932async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2933    loop {
2934        tokio::time::sleep(HEARTBEAT).await;
2935        let snapshot = {
2936            let mut guard = lock(&status);
2937            guard.updated_at = Timestamp::now();
2938            guard.clone()
2939        };
2940        if let Err(e) = write_status_to(&path, &snapshot) {
2941            // A failed heartbeat must not take the daemon down: the loop is the
2942            // product, the status file is only the window onto it.
2943            tracing::warn!("could not refresh the daemon status file: {e:#}");
2944        }
2945    }
2946}
2947
2948/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2949/// if so, whether that wait is over.
2950#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2951enum LandResume {
2952    /// The task's last run is not parked on a land approval; schedule it
2953    /// like any other candidate.
2954    NotLanding,
2955    /// Parked in `land`, waiting on a question nobody has answered yet.
2956    /// Left alone: attempting it now would only re-observe the same pull
2957    /// request and park again, spending a `gh` call on a decision that has
2958    /// not changed since the last time this was checked.
2959    StillWaiting,
2960    /// Parked in `land`, and the question is settled - answered or
2961    /// abandoned. Resuming this is the one kind of candidate that must not
2962    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2963    Ready,
2964}
2965
2966/// Classify a runnable candidate by whether it is parked on a land-merge
2967/// approval. Read-only - no claim taken, nothing written - so it is cheap
2968/// enough to call on every candidate, every poll.
2969fn land_resume_state(task: &Task) -> LandResume {
2970    let Some(run_id) = task.runs.last() else {
2971        return LandResume::NotLanding;
2972    };
2973    let Ok(state) = RunState::load(run_id) else {
2974        return LandResume::NotLanding;
2975    };
2976    if !state.parked {
2977        return LandResume::NotLanding;
2978    }
2979    if state.status == RunStatus::Landing
2980        && state.land_approval.as_ref().is_some_and(|binding| {
2981            ask::Questions::open()
2982                .get(&binding.question)
2983                .is_ok_and(|q| {
2984                    q.run == state.id
2985                        && q.resolution()
2986                            .as_deref()
2987                            .is_some_and(crate::merge_decision::stops)
2988                })
2989        })
2990    {
2991        return LandResume::Ready;
2992    }
2993    if !implementers_match(task, &state) {
2994        return LandResume::NotLanding;
2995    }
2996    // Parked in `land` on the merge approval, or at `merge` on the owner's
2997    // word about a title/body the posting gate withheld. Told apart by the
2998    // run's own record, not by a status both can share.
2999    let node = if state.status == RunStatus::Landing {
3000        land::APPROVAL_NODE
3001    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3002        crate::github_text::ASK_NODE
3003    } else {
3004        return LandResume::NotLanding;
3005    };
3006    let store = ask::Questions::open();
3007    let waiting = store
3008        .list()
3009        .into_iter()
3010        .filter(|q| &q.run == run_id && q.node == node)
3011        .max_by(|a, b| a.id.cmp(&b.id));
3012    let Some(mut q) = waiting else {
3013        return LandResume::Ready;
3014    };
3015    if !q.status.open() {
3016        // Repair spends agent resources and must obey concurrency and quota
3017        // waits; only a merge/hold decision may use the decision-only lane.
3018        if q.resolution().as_deref() == Some(land::REPAIR) {
3019            return if state.liveness(false) == Liveness::Live {
3020                LandResume::StillWaiting
3021            } else {
3022                LandResume::NotLanding
3023            };
3024        }
3025        return LandResume::Ready;
3026    }
3027    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3028    // nobody ever answered; land's approval bypasses that wait entirely (see
3029    // `land::approval_gate`), so the same deadline has to be enforced here
3030    // instead, or `graph.answer_timeout` silently stops meaning anything for
3031    // a land approval and a run can sit `StillWaiting` forever with nobody
3032    // told to look at it.
3033    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3034    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3035    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3036        q.abandon(format!(
3037            "no answer within {}s of asking",
3038            timeout.as_secs().max(1)
3039        ));
3040        // If this can't be persisted, do not treat the wait as settled on a
3041        // guess: fall through and try again next poll.
3042        if store.put(&mut q).is_ok() {
3043            return LandResume::Ready;
3044        }
3045    }
3046    LandResume::StillWaiting
3047}
3048
3049/// How often the loop rechecks for new work while something it already
3050/// started is still running, rather than sleeping out the whole
3051/// [`Opts::poll`] interval.
3052///
3053/// Short on purpose: this is what lets a land-merge approval that comes back
3054/// while another task is mid-competition be noticed and resumed within a
3055/// fraction of a second, not within the next multi-second poll.
3056const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3057
3058/// How often [`poll`] rechecks the shared build cache against its cap at a
3059/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3060/// waiting for the queue to run dry.
3061///
3062/// A queue that never empties means the `janitor` call at the bottom of this
3063/// loop's fully-idle branch can go unreached for as long as the backlog
3064/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3065/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3066/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3067/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3068/// backlog of short tasks does not pay for that walk on every poll.
3069const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3070
3071/// State of [`poll`]'s own interrupt-scheduling sequence - see
3072/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3073/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3074/// both kept free of `Task`'s non-identity fields on purpose: every decision
3075/// here turns only on task ids and which ones are in flight, so the "never
3076/// more than one run at once" and "exactly one resume" invariants can be
3077/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3078/// queue - which is exactly the coverage this feature's first two attempts
3079/// were missing.
3080///
3081/// Persisted after every transition, so scheduler replacement preserves the
3082/// interrupt's exclusive turn and the interrupted task's priority resume.
3083#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3084enum Interrupt {
3085    /// No interrupt sequence in progress. Ordinary dispatch applies.
3086    Idle,
3087    /// `interrupt_task` is runnable and exactly one other run is in flight;
3088    /// `parked` names that one task's id. Dispatch is withheld from
3089    /// everyone, including `interrupt_task` itself, until it has left
3090    /// flight - only then is `interrupt_task` let through.
3091    ///
3092    /// `parked` is a `Vec` rather than a bare id for symmetry with
3093    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3094    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3095    /// when exactly one run is in flight, so it is guaranteed to hold
3096    /// exactly one entry in practice - see that branch's own doc for why
3097    /// more than one is deliberately never attempted.
3098    Parking {
3099        parked: Vec<String>,
3100        interrupt_task: String,
3101    },
3102    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3103    /// withheld from everyone until it leaves flight - merged, failed, held,
3104    /// it makes no difference - at which point the sequence moves to
3105    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3106    /// going straight to `Idle` would hand `parked` back to ordinary
3107    /// priority-order dispatch, where a higher-priority task filed in the
3108    /// meantime could start ahead of it.
3109    Running {
3110        parked: Vec<String>,
3111        interrupt_task: String,
3112    },
3113    /// `interrupt_task` left flight; `parked` still names the one run this
3114    /// sequence owes a resume. Dispatch is withheld from everyone except
3115    /// that task - see [`interrupt_gate`] - so the resume this feature
3116    /// promises is never raced by, or run alongside, an unrelated candidate.
3117    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3118    /// own doc on abandonment - the moment it is no longer runnable at all.
3119    Resuming { parked: Vec<String> },
3120}
3121
3122/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3123/// and `runnable` are read-only snapshots of this tick's reality, and the
3124/// only side effect the caller still owes the world is asking whichever
3125/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3126/// site.
3127///
3128/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3129/// accepted rather than a narrower type because that is what [`poll`] already
3130/// has on hand from [`runnable`], and building a second, smaller list on
3131/// every tick just to satisfy this signature would cost more than it proves.
3132///
3133/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3134/// back to a task they are waiting on no longer being [`runnable`] - held,
3135/// blocked, deleted, or finished by some other means entirely, all of which
3136/// an operator can do to a task sitting in the queue with no claim on it at
3137/// all, at any moment, interrupt sequence or not. Without this check the
3138/// sequence would wait forever for a dispatch that can never come, and
3139/// `interrupt_gate` would withhold every other task in the queue right along
3140/// with it - a single `magi task hold` on the wrong id turning into a
3141/// daemon that never dispatches anything again.
3142fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3143    match state {
3144        Interrupt::Idle => {
3145            // Not just "something to interrupt": exactly one thing. More
3146            // than one run in flight only happens above the default
3147            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3148            // one resume, never run alongside anything else" only because
3149            // it is only ever seeded with exactly one id - see
3150            // `Interrupt::Resuming`'s own doc on why releasing more than one
3151            // parked id back to ordinary dispatch cannot be made safe
3152            // against that same setting's own extra concurrency slots.
3153            // Waiting here for the herd to settle to one is the
3154            // simplification this feature's own constraints ask for rather
3155            // than a second concurrency model to reconcile with the first.
3156            if in_flight.len() != 1 {
3157                return Interrupt::Idle;
3158            }
3159            match runnable.iter().find(|t| t.interrupt) {
3160                Some(t) => Interrupt::Parking {
3161                    parked: in_flight.to_vec(),
3162                    interrupt_task: t.id.clone(),
3163                },
3164                None => Interrupt::Idle,
3165            }
3166        }
3167        Interrupt::Parking {
3168            parked,
3169            interrupt_task,
3170        } => {
3171            if in_flight.iter().any(|id| parked.contains(id)) {
3172                // Still waiting for what was in flight to actually stop.
3173                Interrupt::Parking {
3174                    parked,
3175                    interrupt_task,
3176                }
3177            } else if in_flight.contains(&interrupt_task) {
3178                Interrupt::Running {
3179                    parked,
3180                    interrupt_task,
3181                }
3182            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3183                // The parked run(s) are gone, but the interrupt task has not
3184                // been dispatched yet on this tick - `interrupt_gate` is
3185                // what lets it through next.
3186                Interrupt::Parking {
3187                    parked,
3188                    interrupt_task,
3189                }
3190            } else {
3191                // The interrupt task itself is no longer runnable - see this
3192                // function's own doc on abandonment. The parked run(s) still
3193                // get their guaranteed resume; there is simply no interrupt
3194                // to run ahead of them any longer.
3195                Interrupt::Resuming { parked }
3196            }
3197        }
3198        Interrupt::Running {
3199            parked,
3200            interrupt_task,
3201        } => {
3202            if in_flight.contains(&interrupt_task) {
3203                Interrupt::Running {
3204                    parked,
3205                    interrupt_task,
3206                }
3207            } else {
3208                // The interrupt task's own run reached a terminal status,
3209                // whichever one - this is the *only* trigger that moves the
3210                // sequence on, driven straight off the same in-flight
3211                // bookkeeping `poll` already reaps every tick, not a second,
3212                // independent poll of anything.
3213                Interrupt::Resuming { parked }
3214            }
3215        }
3216        Interrupt::Resuming { parked } => {
3217            if in_flight.iter().any(|id| parked.contains(id)) {
3218                // One of the parked runs has been dispatched - the resume
3219                // this sequence owed is fulfilled. Whatever else is left in
3220                // `parked` (ordinarily nothing, at the default concurrency
3221                // of one) rejoins ordinary priority-order dispatch, same as
3222                // any other runnable task.
3223                Interrupt::Idle
3224            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3225                Interrupt::Resuming { parked }
3226            } else {
3227                // Abandonment (see this function's own doc): nothing left in
3228                // `parked` is even runnable any longer.
3229                Interrupt::Idle
3230            }
3231        }
3232    }
3233}
3234
3235/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3236/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3237/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3238/// indistinguishable from any other runnable task - exactly the "off does
3239/// nothing" this feature promises.
3240fn advance_interrupt_tick(
3241    enabled: bool,
3242    state: Interrupt,
3243    in_flight: &[String],
3244    runnable: &[Task],
3245) -> Interrupt {
3246    if !enabled {
3247        return Interrupt::Idle;
3248    }
3249    advance_interrupt(state, in_flight, runnable)
3250}
3251
3252/// Which of this tick's runnable candidates the interrupt sequence actually
3253/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3254/// each half is assertable on its own: this is the half that keeps a
3255/// competition and an interrupt from ever running at the same moment.
3256fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3257    match state {
3258        Interrupt::Idle => candidates,
3259        Interrupt::Parking {
3260            parked,
3261            interrupt_task,
3262        } => {
3263            if in_flight.iter().any(|id| parked.contains(id)) {
3264                Vec::new()
3265            } else {
3266                candidates
3267                    .into_iter()
3268                    .filter(|t| &t.id == interrupt_task)
3269                    .collect()
3270            }
3271        }
3272        Interrupt::Running { .. } => Vec::new(),
3273        // At most one: even if `parked` names more than one id (more than
3274        // one run was in flight when the sequence began, only possible
3275        // above the default `max_concurrent_runs = 1`), only the first match
3276        // is offered. Capping this to a single candidate - not merely to
3277        // `parked`'s own ids - is what makes "exactly one resume, never two
3278        // dispatched together" true regardless of how many ordinary slots
3279        // happen to be free this tick.
3280        Interrupt::Resuming { parked } => candidates
3281            .into_iter()
3282            .find(|t| parked.contains(&t.id))
3283            .into_iter()
3284            .collect(),
3285    }
3286}
3287
3288/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3289/// bundled into one parameter so `poll`'s own signature stays readable -
3290/// see [`drive`]'s call site for where these are actually read.
3291struct DispatchLimits {
3292    /// How many *ordinary* candidates run at once. See
3293    /// [`crate::config::Daemon::max_concurrent_runs`].
3294    max_concurrent: usize,
3295    /// See [`crate::config::Daemon::pause_for_interrupts`].
3296    pause_for_interrupts: bool,
3297    recovery_cfg: Option<Config>,
3298}
3299
3300/// Which semaphore, if any, dispatching a candidate should draw its permit
3301/// from.
3302///
3303/// Pure and separate from [`poll`]'s loop body for the same reason
3304/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3305/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3306/// exactly the policy this feature adds, and a policy only exercisable by
3307/// running the whole loop is a policy nobody checks.
3308#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3309enum PermitKind {
3310    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3311    /// Checked first - a task can be both a land resume and marked
3312    /// [`Task::urgent`], and the resume's own "must not queue behind
3313    /// anything" guarantee takes precedence.
3314    None,
3315    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3316    /// (never in addition to trying) the ordinary pool. This is what lets
3317    /// an urgent task dispatch while every ordinary slot is already checked
3318    /// out, and what stops a second urgent task from opening a third run: it
3319    /// waits on this same one-slot semaphore rather than falling through to
3320    /// the ordinary one.
3321    Urgent,
3322    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3323    /// above.
3324    #[default]
3325    Ordinary,
3326}
3327
3328/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3329/// own boolean, already computed by the caller from [`land_resume_state`].
3330fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3331    if priority {
3332        PermitKind::None
3333    } else if urgent {
3334        PermitKind::Urgent
3335    } else {
3336        PermitKind::Ordinary
3337    }
3338}
3339
3340fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3341    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3342        (0usize, 0usize),
3343        |(ordinary, urgent), request| match request.lane {
3344            PermitKind::Ordinary => (ordinary + 1, urgent),
3345            PermitKind::Urgent => (ordinary, urgent + 1),
3346            PermitKind::None => (ordinary, urgent),
3347        },
3348    );
3349    (
3350        limit.saturating_sub(ordinary),
3351        1usize.saturating_sub(urgent),
3352    )
3353}
3354
3355struct DispatchClaim {
3356    task: Task,
3357    claim: crate::queue::Claim,
3358    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3359}
3360
3361/// Claim and re-read before choosing a lane: a queue listing may predate an
3362/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3363fn claim_dispatch(
3364    queue: &Queue,
3365    candidate: &Task,
3366    cooling_down: bool,
3367    ordinary: &Arc<tokio::sync::Semaphore>,
3368    urgent: &Arc<tokio::sync::Semaphore>,
3369) -> Option<DispatchClaim> {
3370    let Ok(claim) = queue.claim(&candidate.id) else {
3371        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3372        return None;
3373    };
3374    let task = match queue.get(&candidate.id) {
3375        Ok(t) if t.status.runnable() => t,
3376        Ok(_) => return None,
3377        Err(e) => {
3378            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3379            return None;
3380        }
3381    };
3382    let resume = land_resume_state(&task);
3383    if resume == LandResume::StillWaiting {
3384        return None;
3385    }
3386    let priority = resume == LandResume::Ready;
3387    if !priority && cooling_down {
3388        return None;
3389    }
3390    // Never borrow an ordinary slot when the single urgent slot is busy.
3391    // Keep scanning other candidates when either pool has no free slot.
3392    let permit = match permit_kind(priority, task.urgent) {
3393        PermitKind::None => None,
3394        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3395        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3396    };
3397    // Persist the dispatch order under the claim, before config discovery or
3398    // coordination waits can reorder concurrent starts.
3399    let stamp = Timestamp::now();
3400    let mut task = task;
3401    task.dispatched_at = Some(stamp);
3402    if let Err(e) = queue.modify(&task.id, |t| {
3403        t.dispatched_at = Some(stamp);
3404        true
3405    }) {
3406        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3407    }
3408    Some(DispatchClaim {
3409        task,
3410        claim,
3411        permit,
3412    })
3413}
3414
3415/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3416/// teardown and cannot skip the teardown on an early return.
3417///
3418/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3419/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3420/// land approval that has since been answered is dispatched outside that
3421/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3422/// the whole point of parking there is that it must not queue behind
3423/// whatever else the loop happens to be running, even at the default of one.
3424/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3425/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3426/// these exemptions is still subject to the interrupt gate below, urgent
3427/// included: a land-resume or urgent candidate is exactly as much "something
3428/// else running" as an ordinary one from the interrupt sequence's point of
3429/// view, and letting either slip through while a run is being parked, or
3430/// while the interrupt task itself has the floor, is precisely the second
3431/// run 75dd's own "at most one run, ever, at once" guarantee must never
3432/// allow - see [`Interrupt`]'s own doc.
3433#[derive(Serialize, Deserialize)]
3434struct ServiceWorker {
3435    opts: Opts,
3436    queue: PathBuf,
3437    worktrees_root: PathBuf,
3438    operation: String,
3439}
3440
3441fn load_conductor(home: &Path) -> Result<Conductor> {
3442    match std::fs::read(home.join("conductor-state.json")) {
3443        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3444        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3445        Err(error) => Err(error.into()),
3446    }
3447}
3448
3449fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3450    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3451        .into_iter()
3452        .map(|c| c.task)
3453        .collect();
3454    let stalled = stalled_tasks(queue, home, Timestamp::now());
3455    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3456    let finished = finished_tasks(queue)
3457        .into_iter()
3458        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3459        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3460        .collect();
3461    let queued = queued_tasks(queue)
3462        .into_iter()
3463        .filter(|t| !live.contains(&t.id))
3464        .collect();
3465    (queued, stalled, finished)
3466}
3467
3468async fn start_service(
3469    home: &Path,
3470    opts: &Opts,
3471    queue: &Queue,
3472    worktrees_root: &Path,
3473    operation: &str,
3474    cfg: Option<&Config>,
3475    busy: bool,
3476) -> Result<()> {
3477    // Fetch policy is live configuration, unlike question recovery capacity.
3478    // Reload before both cadence and eligibility, including disabled -> enabled.
3479    let fetch_cfg = if operation == "fetch" {
3480        match prepare(&opts.repo, opts) {
3481            Ok(cfg) => Some(cfg),
3482            Err(error) => {
3483                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3484                return Ok(());
3485            }
3486        }
3487    } else {
3488        None
3489    };
3490    let cfg = fetch_cfg.as_ref().or(cfg);
3491    let ticks = home.join("service-ticks");
3492    std::fs::create_dir_all(&ticks)?;
3493    let receipt = ticks.join(format!("daemon-{operation}"));
3494    let last = std::fs::read(&receipt)
3495        .ok()
3496        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3497    let interval = match operation {
3498        "disk-pressure" => 30,
3499        "cache" => CACHE_CHECK_INTERVAL_SECS,
3500        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3501        _ => opts.poll.as_secs().max(1),
3502    };
3503    let now = Timestamp::now();
3504    if !cache_check_due(last, now, interval) {
3505        return Ok(());
3506    }
3507    let key = format!("service:daemon-{operation}");
3508    if crate::worker::active(home)?
3509        .iter()
3510        .any(|job| job.key == key)
3511    {
3512        return Ok(());
3513    }
3514    let eligible = match operation {
3515        "conductor" => {
3516            let (queued, stalled, finished) = conductor_work(queue, home);
3517            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3518                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3519        }
3520        "maintenance" => Questions::at(home.join("questions"))
3521            .list()
3522            .iter()
3523            .any(|q| {
3524                q.chosen_action().is_some_and(|action| action.maintenance())
3525                    && !home
3526                        .join("choice-actions")
3527                        .join(format!("{}.json", q.id))
3528                        .exists()
3529            }),
3530        "housekeeping" => !busy && runnable(queue).is_empty(),
3531        "cache" => {
3532            !busy
3533                && !runnable(queue).is_empty()
3534                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3535        }
3536        "disk-pressure" => busy,
3537        "fetch" => {
3538            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3539        }
3540        _ => false,
3541    };
3542    if !eligible {
3543        return Ok(());
3544    }
3545    let request = ServiceWorker {
3546        opts: opts.absolute()?,
3547        queue: std::path::absolute(queue.root())?,
3548        worktrees_root: std::path::absolute(worktrees_root)?,
3549        operation: operation.to_owned(),
3550    };
3551    if let Err(error) =
3552        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3553    {
3554        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3555    }
3556    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3557    Ok(())
3558}
3559
3560/// Finite maintenance jobs survive scheduler replacement without duplicating
3561/// agent calls or cancelling an operation between its effect and receipt.
3562pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3563    let request: ServiceWorker = serde_json::from_value(payload)?;
3564    let opts = &request.opts;
3565    let queue = Queue::at(request.queue);
3566    let questions = Questions::at(home.join("questions"));
3567    match request.operation.as_str() {
3568        "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3569        "conductor" => {
3570            let path = home.join("conductor-state.json");
3571            let mut conductor = load_conductor(home)?;
3572            let (queued, stalled, finished) = conductor_work(&queue, home);
3573            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3574                && conductor.worth_a_look(&queue, &stalled, &finished)
3575            {
3576                let cfg = prepare(&opts.repo, opts)?;
3577                conductor
3578                    .maybe_run(
3579                        &cfg,
3580                        &opts.repo,
3581                        &queue,
3582                        &questions,
3583                        home,
3584                        &queued,
3585                        &stalled,
3586                        &finished,
3587                        opts.max_attempts,
3588                    )
3589                    .await;
3590                let temporary = path.with_extension("json.tmp");
3591                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3592                std::fs::rename(temporary, path)?;
3593            }
3594        }
3595        "fetch" => {
3596            let cfg = prepare(&opts.repo, opts)?;
3597            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3598                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3599                tracing::debug!("fetch origins: {outcome:?}");
3600            }
3601        }
3602        "cache" => {
3603            if task_jobs(home)?.is_empty() {
3604                let mut checked = None;
3605                maybe_prune_cache_between_runs(
3606                    &opts.repo,
3607                    opts,
3608                    home,
3609                    &Stop::new(),
3610                    &mut checked,
3611                    Timestamp::now(),
3612                )
3613                .await;
3614            }
3615        }
3616        "disk-pressure" => {
3617            if let Ok(cfg) = prepare(&opts.repo, opts) {
3618                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3619                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3620                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3621                }
3622                for current in current_work(home, Timestamp::now()) {
3623                    if let Ok(state) = RunState::load_under(&current.run, home)
3624                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3625                    {
3626                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3627                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3628                        }) {
3629                            request_task_park(
3630                                home,
3631                                &job,
3632                                crate::run::ParkCause::Interrupt {
3633                                    reason: reason.clone(),
3634                                },
3635                            )?;
3636                        }
3637                        notices::raise_in(
3638                            home,
3639                            Notice::warn(
3640                                "disk:pressure",
3641                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3642                            ),
3643                        );
3644                    }
3645                }
3646            }
3647        }
3648        "housekeeping" => {
3649            if task_jobs(home)?.is_empty() {
3650                if let Ok(cfg) = prepare(&opts.repo, opts) {
3651                    crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3652                }
3653                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3654                resweep_superseded_attempts(&queue, home);
3655                triage_held(&queue, home, opts).await;
3656            }
3657        }
3658        operation => bail!("unknown daemon service {operation}"),
3659    }
3660    Ok(())
3661}
3662
3663/// Only a different request under the same key is a dispatch handoff race.
3664/// Our own unacknowledged reservation is a startup failure, not competing work:
3665/// stop dispatch without fencing it, so an already detached child may still run.
3666fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3667    let key = format!("task:{}", request.task);
3668    let payload = serde_json::to_value(request)?;
3669    if crate::worker::active(home)?
3670        .iter()
3671        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3672    {
3673        tracing::warn!(
3674            "task {} acquired a competing worker reservation: {error:#}",
3675            crate::run::short_of(&request.task)
3676        );
3677        return Ok(());
3678    }
3679    tracing::error!("task worker startup stopped dispatch: {error:#}");
3680    notices::raise_in(
3681        home,
3682        Notice::error(
3683            "loop:worker-startup",
3684            // Startup diagnostics may contain private child-process details;
3685            // keep them in the local error/log rather than the chat or notifier.
3686            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),
3687        ).link(Link::Task { id: request.task.clone() }),
3688    );
3689    Err(error).with_context(|| {
3690        format!(
3691            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3692            crate::run::short_of(&request.task)
3693        )
3694    })
3695}
3696
3697async fn poll(
3698    opts: &Opts,
3699    queue: &Queue,
3700    status: &Arc<Mutex<Status>>,
3701    home: &Path,
3702    worktrees_root: &Path,
3703    stop: &Stop,
3704    limits: DispatchLimits,
3705) -> Result<()> {
3706    let mut attempted = Vec::new();
3707    let mut settling_once_services = false;
3708    let interrupt_path = home.join("scheduler-interrupt.json");
3709    let mut interrupt = match std::fs::read(&interrupt_path) {
3710        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3711        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3712        Err(error) => return Err(error.into()),
3713    };
3714    let mut previous = std::collections::BTreeSet::<String>::new();
3715    while !stop.stopped() {
3716        let jobs: Vec<_> = crate::worker::active(home)?
3717            .into_iter()
3718            .filter(|job| job.kind == "task")
3719            .collect();
3720        let requests: Vec<_> = jobs
3721            .iter()
3722            .map(|job| {
3723                serde_json::from_value::<TaskWorker>(job.payload.clone())
3724                    .with_context(|| format!("read live task worker {}", job.id))
3725            })
3726            .collect::<Result<_>>()?;
3727        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3728        let owned: std::collections::BTreeSet<_> = requests
3729            .iter()
3730            .filter(|r| !r.standalone)
3731            .map(|r| r.task.clone())
3732            .collect();
3733        let current: Vec<_> = requests
3734            .iter()
3735            .zip(&jobs)
3736            .filter(|(request, _)| !request.standalone)
3737            .map(|(request, job)| Current {
3738                worker: Some(job.id.clone()),
3739                task: request.task.clone(),
3740                run: queue
3741                    .get(&request.task)
3742                    .ok()
3743                    .and_then(|task| task.runs.last().cloned())
3744                    .unwrap_or_default(),
3745            })
3746            .collect();
3747        {
3748            let mut snapshot = lock(status);
3749            snapshot.polls += 1;
3750            snapshot.completed += previous.difference(&owned).count();
3751            snapshot.current = current;
3752            snapshot.idle = owned.is_empty();
3753        }
3754        previous = owned.clone();
3755        stop.busy.store(owned.len(), Ordering::SeqCst);
3756
3757        // Slots are reconstructed from durable reservations and OS-held worker
3758        // leases, not this scheduler's lifetime or mutable task urgency.
3759        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3760        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3761        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3762        let mut permits = Vec::new();
3763        sweep_stale_claims(queue, STALE_CLAIM);
3764        reclaim_orphaned_running(queue, opts.max_attempts, &live);
3765        reclaim_abandoned_runs(home, Timestamp::now());
3766        let questions = Questions::at(home.join("questions"));
3767
3768        // Deterministic: no model, run before the conductor sees anything so
3769        // its input reflects the queue's current, already-resolved state.
3770        crate::task_chat::sweep(
3771            queue,
3772            &crate::talk::Talks::at(home.join("talks")),
3773            &questions,
3774            home,
3775        );
3776        repair_choice_offers(&questions);
3777        resolve_blockers(queue, &questions);
3778        apply_task_choice_actions(queue, &questions, home);
3779        triage::apply_answers(queue, &questions);
3780        reconcile_task_questions(queue, &questions);
3781        let talks = crate::talk::Talks::at(home.join("talks"));
3782        crate::chat_notify::sweep(queue, &talks, home);
3783        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3784        crate::chat_watch::sweep(home, &talks);
3785        let mut turns = tokio::task::JoinSet::new();
3786        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3787        // start_turns dispatches detached turns; no paid work lives in this set.
3788        while turns.join_next().await.is_some() {}
3789
3790        crate::consult::start_services(
3791            home,
3792            &opts.repo,
3793            limits.recovery_cfg.as_ref(),
3794            opts.config.as_deref(),
3795        )
3796        .await?;
3797        for operation in [
3798            "conductor",
3799            "maintenance",
3800            "housekeeping",
3801            "disk-pressure",
3802            "cache",
3803            "fetch",
3804        ] {
3805            // Once an idle --once drain starts settling services, subsequent
3806            // scans only consume their effects. An expired cadence receipt
3807            // must not start another service and keep the drain alive.
3808            if settling_once_services {
3809                break;
3810            }
3811            start_service(
3812                home,
3813                opts,
3814                queue,
3815                worktrees_root,
3816                operation,
3817                limits.recovery_cfg.as_ref(),
3818                !live.is_empty(),
3819            )
3820            .await?;
3821        }
3822        let latest = crate::worker::active(home)?;
3823        if latest.iter().any(|job| job.key == "service:daemon-cache")
3824            || latest
3825                .iter()
3826                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3827        {
3828            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3829            continue;
3830        }
3831        let candidates: Vec<Task> = runnable(queue)
3832            .into_iter()
3833            .filter(|task| !live.contains(&task.id))
3834            .filter(|task| !opts.once || !attempted.contains(&task.id))
3835            .collect();
3836        let in_flight: Vec<_> = owned.iter().cloned().collect();
3837        let prior_interrupt = std::mem::discriminant(&interrupt);
3838        interrupt = advance_interrupt_tick(
3839            limits.pause_for_interrupts,
3840            interrupt,
3841            &in_flight,
3842            &candidates,
3843        );
3844        // Same-variant transitions preserve their identities. Only an actual
3845        // transition needs a durable write, atomically before sending controls.
3846        if prior_interrupt != std::mem::discriminant(&interrupt) {
3847            let temporary = interrupt_path.with_extension("json.tmp");
3848            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3849            std::fs::rename(temporary, &interrupt_path)?;
3850        }
3851        if let Interrupt::Parking {
3852            parked,
3853            interrupt_task,
3854        } = &interrupt
3855        {
3856            for job in jobs.iter().filter(|job| {
3857                parked
3858                    .iter()
3859                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3860            }) {
3861                if crate::worker::control(home, &job.key)?.is_none() {
3862                    request_task_park(
3863                        home,
3864                        job,
3865                        crate::run::ParkCause::Interrupt {
3866                            reason: format!(
3867                                "task {} asked to run first",
3868                                crate::run::short_of(interrupt_task)
3869                            ),
3870                        },
3871                    )?;
3872                }
3873            }
3874        }
3875        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3876        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3877        let mut started = false;
3878        let mut resync = false;
3879        for candidate in candidates {
3880            if stop.stopped() {
3881                break;
3882            }
3883            let Some(DispatchClaim {
3884                task,
3885                claim,
3886                permit,
3887            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
3888            else {
3889                continue;
3890            };
3891            if crate::worker::active(home)?
3892                .iter()
3893                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3894            {
3895                drop(claim);
3896                resync = true;
3897                break;
3898            }
3899            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
3900            let request = TaskWorker {
3901                opts: opts.absolute()?,
3902                queue: std::path::absolute(queue.root())?,
3903                task: task.id.clone(),
3904                lane,
3905                standalone: false,
3906            };
3907            // Keep the claim until spawn acknowledges the worker's durable
3908            // reservation. The worker then claims and re-reads before attempt.
3909            if let Err(error) = crate::worker::spawn(
3910                home,
3911                "task",
3912                &format!("task:{}", task.id),
3913                serde_json::to_value(&request)?,
3914            )
3915            .await
3916            {
3917                task_worker_spawn_error(home, &request, error)?;
3918                drop(claim);
3919                resync = true;
3920                break;
3921            }
3922            drop(claim);
3923            permits.extend(permit);
3924            attempted.push(task.id);
3925            started = true;
3926        }
3927        if started || resync {
3928            continue;
3929        }
3930        if owned.is_empty() && opts.once {
3931            settling_once_services = true;
3932            // These finite services can own queue claims or publish answers.
3933            // A skipped claim is not an idle queue until they have finished;
3934            // scan again afterwards so their changes are actually scheduled.
3935            if crate::worker::active(home)?.iter().any(|job| {
3936                job.kind == "daemon-service"
3937                    && matches!(
3938                        job.key.as_str(),
3939                        "service:daemon-housekeeping"
3940                            | "service:daemon-conductor"
3941                            | "service:daemon-maintenance"
3942                    )
3943            }) {
3944                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3945                continue;
3946            }
3947            break;
3948        }
3949        stop.idle(if live.is_empty() {
3950            opts.poll
3951        } else {
3952            RECHECK_WHILE_BUSY.min(opts.poll)
3953        })
3954        .await;
3955    }
3956    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
3957    // every queue claim and Runner driver lease through outcome settlement.
3958    stop.busy.store(0, Ordering::SeqCst);
3959    Ok(())
3960}
3961
3962/// A maintenance pass may briefly own the same record while a worker starts.
3963/// Wait without blocking the executor or charging an agent attempt, then read
3964/// ownership again under the acquired lock. Other I/O failures still fail closed.
3965async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
3966    let busy = |error: &anyhow::Error| {
3967        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
3968            error.kind() == std::io::ErrorKind::WouldBlock
3969                || cfg!(windows) && error.raw_os_error() == Some(33)
3970        })
3971    };
3972    match crate::pr_head::owner_lock(home, id) {
3973        Ok(lock) => return Ok(lock),
3974        Err(error) if busy(&error) => {}
3975        Err(error) => return Err(error),
3976    }
3977    let wait = RunState::load_under(id, home)?
3978        .config
3979        .graph
3980        .timeout_resource_wait;
3981    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
3982}
3983
3984/// Historical successors do not revoke a still-resumable public owner. Scan
3985/// under the same lock as publication/driver claims, and fail closed on unknown
3986/// history before spending another attempt.
3987async fn public_resume_owner(
3988    home: &Path,
3989    runs: &[String],
3990    repo: &Path,
3991) -> Result<Option<RunState>> {
3992    let mut owner = None;
3993    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
3994        let _lock = resume_owner_lock(home, id).await?;
3995        let state = RunState::load_under(id, home)?;
3996        if state.released()
3997            || state.retired_to.is_some()
3998            || state.pr_taken_over_by.is_some()
3999            || !crate::handover::landing_checkpoint(&state)
4000        {
4001            continue;
4002        }
4003        anyhow::ensure!(
4004            crate::git::toplevel(&state.repo).await?.canonicalize()?
4005                == crate::git::toplevel(repo).await?.canonicalize()?,
4006            "public owner repository differs; inspect run lineage"
4007        );
4008        anyhow::ensure!(
4009            owner.is_none(),
4010            "multiple retained public owners; inspect run lineage"
4011        );
4012        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4013            anyhow::bail!(reason.diagnostic(&state));
4014        }
4015        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4016        anyhow::ensure!(
4017            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4018            "public owner's driver is live or unknown; wait before retrying"
4019        );
4020        owner = Some(state);
4021    }
4022    Ok(owner)
4023}
4024
4025/// Run one claimed task to a terminal status and record the outcome.
4026///
4027/// Every transition is flushed to the queue as it happens, so the state on disk
4028/// is what actually occurred rather than what this process still intends to
4029/// write.
4030async fn attempt(
4031    opts: &Opts,
4032    queue: &Queue,
4033    status: &Arc<Mutex<Status>>,
4034    stop: &Stop,
4035    interrupt_pause: crate::graph::Pause,
4036    task: &mut Task,
4037) -> Vec<QuotaLoss> {
4038    let repo = repo_for(task, &opts.repo);
4039    tracing::info!(
4040        "task {} — {} (repo {})",
4041        task.short(),
4042        task.title,
4043        repo.display()
4044    );
4045
4046    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4047        Ok(owner) => owner,
4048        Err(e) => {
4049            task.hold_machine(Some(format!(
4050                "Cannot verify existing public owner: {e:#}; no attempt started."
4051            )));
4052            record(queue, task);
4053            return Vec::new();
4054        }
4055    };
4056    let resume_runs = public_owner
4057        .as_ref()
4058        .map(|s| vec![s.id.clone()])
4059        .unwrap_or_else(|| task.runs.clone());
4060
4061    // A stop spends no agent resources and uses the saved landing owner.
4062    // Current roster edits, missing attachments or a failed config fetch must
4063    // never turn it into a new implementation, or prevent a PR from closing.
4064    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4065        && previous
4066            .merge_decision
4067            .as_ref()
4068            .is_some_and(|decision| !decision.closed)
4069        && previous.status != RunStatus::Landing
4070        && !crate::merge_decision::resumable_hold(&previous)
4071    {
4072        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)));
4073        record(queue, task);
4074        return Vec::new();
4075    }
4076    let stop_owner = resume_runs
4077        .last()
4078        .and_then(|id| RunState::load(id).ok())
4079        .filter(|state| {
4080            crate::merge_decision::resumable_hold(state)
4081                || state.status == RunStatus::Landing
4082                    && state.land_approval.as_ref().is_some_and(|binding| {
4083                        Questions::open().get(&binding.question).is_ok_and(|q| {
4084                            q.run == state.id
4085                                && q.resolution()
4086                                    .as_deref()
4087                                    .is_some_and(crate::merge_decision::stops)
4088                        })
4089                    })
4090        });
4091    if let Some(owner) = stop_owner {
4092        let mut runner = match Runner::resume(&owner.id) {
4093            Ok(runner) => runner,
4094            Err(e) => {
4095                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4096                record(queue, task);
4097                return Vec::new();
4098            }
4099        };
4100        runner.on_pause(stop.pause());
4101        runner.watch_interrupt(interrupt_pause);
4102        let quota_before = runner.state.quota.clone();
4103        task.start(owner.id.clone());
4104        record(queue, task);
4105        lock(status).current.push(Current {
4106            worker: None,
4107            task: task.id.clone(),
4108            run: owner.id,
4109        });
4110        runner.state.next_pass_task_entry = true;
4111        let result = runner.execute().await;
4112        return finish_attempt(
4113            opts.max_attempts,
4114            queue,
4115            task,
4116            &runner.state,
4117            &quota_before,
4118            result,
4119        );
4120    }
4121
4122    if let Some(owner) = &public_owner
4123        && (task.fresh_start || !may_resume_run(owner, task))
4124    {
4125        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)));
4126        record(queue, task);
4127        return Vec::new();
4128    }
4129
4130    let unfinished = (!task.fresh_start)
4131        .then(|| unfinished_run(&resume_runs, task.short()))
4132        .flatten()
4133        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4134    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4135    if !task.fresh_start
4136        && task.pr_recovery.is_none()
4137        && task.review_branch.is_none()
4138        && task.resume_override.is_none()
4139        && previous
4140            .as_ref()
4141            .is_some_and(|run| run.retired_to.is_some())
4142        && unfinished.is_none()
4143    {
4144        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()));
4145        record(queue, task);
4146        return Vec::new();
4147    }
4148
4149    let saved_recovery = previous.as_ref().filter(|run| {
4150        task.replacement.is_none()
4151            && task.pr_recovery.as_ref().is_some_and(|selected| {
4152                selected.check_task(&task.id, &task.instruction).is_ok()
4153                    && selected_starter(selected, Some(run), unfinished.as_deref())
4154                        == Starter::Resume(run.id.clone())
4155            })
4156    });
4157
4158    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4159    // failure here is the network's or the operator's, not the task's: hold
4160    // without spending an attempt, never fall back to a possibly stale copy.
4161    let explicit = match &task.overrides {
4162        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4163        Some(_) => opts.config.as_deref(),
4164        None => opts.config.as_deref(),
4165    };
4166    let (mut config, layers) = if let Some(run) = saved_recovery {
4167        // A matching resume owns its resolved configuration and evidence;
4168        // current layers and inherited overrides only configure new work.
4169        let mut saved = run.clone();
4170        if let Err(e) = saved.configure_recovery_resume() {
4171            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4172            record(queue, task);
4173            return Vec::new();
4174        }
4175        (saved.config, Vec::new())
4176    } else {
4177        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4178            Ok(loaded) => loaded,
4179            Err(e) => {
4180                let reason = format!("[config] {e:#}");
4181                record_config_failure(task, &e);
4182                task.last_error = Some(reason.clone());
4183                task.hold_machine(Some(reason));
4184                record(queue, task);
4185                return Vec::new();
4186            }
4187        };
4188        if let Err(e) = apply_options(&mut config, opts, task) {
4189            task.hold_manual(Some(format!(
4190                "[config] {e:#}; correct the merge override before releasing the task"
4191            )));
4192            record(queue, task);
4193            return Vec::new();
4194        }
4195        if let Some(selected) = &task.pr_recovery
4196            && let Err(e) = selected.configure(&mut config)
4197        {
4198            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4199            record(queue, task);
4200            return Vec::new();
4201        }
4202        (config, layers)
4203    };
4204    let config_evidence = crate::pr_recovery::ConfigEvidence {
4205        layers,
4206        overrides: task.overrides.clone(),
4207        daemon_merge: task
4208            .overrides
4209            .as_ref()
4210            .is_none_or(|o| o.inherit_daemon_options)
4211            .then(|| opts.merge.clone())
4212            .flatten(),
4213    };
4214    apply_task_implementers(&mut config, task);
4215    if let Some(replacement) = &task.replacement {
4216        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4217            old.liveness(false) == Liveness::Dead
4218                && old.merge_decision.as_ref().is_some_and(|d| {
4219                    d.closed
4220                        && d.question == replacement.question
4221                        && d.replacement_run.as_ref().is_none_or(|run| {
4222                            task.runs.last() == Some(run)
4223                                && RunState::load(run).is_ok_and(|current| {
4224                                    current.replaces.as_ref().is_some_and(|pin| {
4225                                        pin.question == replacement.question
4226                                            && pin.agent == replacement.agent
4227                                    })
4228                                })
4229                        })
4230                })
4231        });
4232        if !safe {
4233            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()));
4234            record(queue, task);
4235            return Vec::new();
4236        }
4237        match config.agent(&replacement.agent) {
4238            Ok(agent) if crate::agent::installed(agent) => {}
4239            _ => {
4240                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)));
4241                record(queue, task);
4242                return Vec::new();
4243            }
4244        }
4245        config.graph.implementers = 1;
4246        config.graph.land_approval = true;
4247        config.merge.mode = MergeMode::Pr;
4248        config.graph.selected_implementer = Some(replacement.agent.clone());
4249    }
4250    let p = phrases(&config.graph.language);
4251    let start_failed = p.could_not_start;
4252    // Resolve once for both admission and settlement. The inputs are the
4253    // task's explicit sources (never prose), plus an explicit review source's
4254    // current head; review-only runs may rebase later, and neither fact can
4255    // refund a failed automatic generation.
4256    if let Ok(base) =
4257        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4258            .await
4259        && let Ok(head) =
4260            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4261    {
4262        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4263        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4264            let source = crate::git::rev_parse(&repo, branch)
4265                .await
4266                .unwrap_or_default();
4267            inputs.push_str(&format!(";review:{branch}:{source}"));
4268        }
4269        if let Some(reason) = task.recovery_exhausted(
4270            &head,
4271            &inputs,
4272            task.attempt_limit
4273                .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4274        ) {
4275            task.hold_unrequested_retry(Some(reason));
4276            record(queue, task);
4277            return Vec::new();
4278        }
4279        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4280    }
4281
4282    // The free-space gate, checked *before* anything is minted: a task that
4283    // waits out a full disk costs nothing yet, and must not spend an attempt
4284    // or start a run the machine cannot finish. Held tasks stay in the list
4285    // for the human to see, and `magi task release` re-queues them when space
4286    // comes back - the same recovery as any other hold. A volume whose free
4287    // space cannot be measured closes the gate too: starting a run blind on a
4288    // disk that may be full is how the machine ends up with 6.7 GB free.
4289    if let Some(reason) = disk_gate(&repo, &config) {
4290        task.notice_cause("disk-space", None, None);
4291        task.last_error = Some(reason.clone());
4292        task.hold_machine(Some(reason.clone()));
4293        record(queue, task);
4294        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4295        // Stable wording - the free-space figures live in the task's hold
4296        // reason, and changing numbers would relight the bell every poll.
4297        notices::raise(
4298            Notice::warn(
4299                &format!("disk:{}", repo.display()),
4300                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4301            )
4302            .link(Link::Task {
4303                id: task.id.clone(),
4304            }),
4305        );
4306        return Vec::new();
4307    }
4308
4309    // A resumable run of this task is carried on, never re-competed. The
4310    // candidates are built and paid for, and a fresh competition races a
4311    // second implementation against them.
4312    //
4313    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4314    // started 3cbf on the same task a moment later, duplicating two and a
4315    // half hours of agent work. Then b25f stalled on a judge that timed out
4316    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4317    // was to blame for - and 4043 started **one second** later, buying three
4318    // fresh implementations to reach the same panel. `RunStatus::resumable`
4319    // rather than `!done()` is what catches the second case: a stall is
4320    // terminal, and its cheap recovery re-asks only the absent seats.
4321    //
4322    // A load failure is warned about rather than silently read as "not
4323    // resumable": the alternative is exactly what let a schema mismatch on
4324    // run `eba2` fall through to a full re-competition with nobody told why.
4325    // `crate::conduct` is what actually offers a better answer than
4326    // `Runner::start` here (see `Recovery::Review`), once this task's next
4327    // failure shows it up as `held`/`failed` with the run state unreadable.
4328    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4329    // branch survived, and this reopens exactly that branch as a
4330    // review-only pass rather than resuming or competing again. Consumed
4331    // (cleared) here whichever way this goes, so it never outlives this one
4332    // attempt - see `queue::Task::review_branch`.
4333    let review_branch = take_review_branch(task, previous.as_ref());
4334    let branch_exists = match &review_branch {
4335        Some(branch) => crate::git::branch_exists(&repo, branch)
4336            .await
4337            .unwrap_or(false),
4338        None => false,
4339    };
4340    // An explicit `magi review <branch>` is reviewed whatever happens to the
4341    // branch unless an explicit implementer change requires fresh work. An
4342    // unfinished run of the same task still wins, so a retry resumes.
4343    let proposed = review_retry_starter(
4344        task,
4345        previous.as_ref(),
4346        review_branch.as_deref(),
4347        branch_exists,
4348        unfinished.as_deref(),
4349    );
4350    let retry_selected = task.replacement.is_some()
4351        && task.resumption.is_some()
4352        && !task.fresh_start
4353        && previous.as_ref().is_some_and(|run| {
4354            run.replaces.is_some()
4355                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4356                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4357        });
4358    let stop_pin = task
4359        .resume_override
4360        .as_ref()
4361        .filter(|pin| {
4362            Questions::open().get(&pin.question_id).is_ok_and(|q| {
4363                q.node == land::APPROVAL_NODE
4364                    && q.resolution()
4365                        .as_deref()
4366                        .is_some_and(crate::merge_decision::stops)
4367            })
4368        })
4369        .and_then(|pin| pin.pinned_run.clone());
4370    let starter = if let Some(owner) = &public_owner {
4371        Starter::Resume(owner.id.clone())
4372    } else if let Some(run) = stop_pin {
4373        // Stop actions resume their exact owner even after seat-count edits;
4374        // they must never fall through to implementation or a takeover.
4375        Starter::Resume(run)
4376    } else if retry_selected {
4377        Starter::Resume(previous.as_ref().unwrap().id.clone())
4378    } else if let Some(selected) = &task.pr_recovery {
4379        if selected.check_task(&task.id, &task.instruction).is_ok() {
4380            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4381        } else {
4382            Starter::Review(selected.branch.clone())
4383        }
4384    } else {
4385        starter_with_implementers(task, previous.as_ref(), proposed)
4386    };
4387    // An explicit resume pin must never degrade into a new competition or
4388    // takeover, including when its run stops being eligible after the answer.
4389    if let Some(pin) = &task.resume_override
4390        && let Some(run) = &pin.pinned_run
4391        && starter != Starter::Resume(run.clone())
4392    {
4393        let run = run.clone();
4394        task.notice_cause("resume-owner", Some(&run), None);
4395        task.hold_machine(Some(format!(
4396            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4397            task.id
4398        )));
4399        record(queue, task);
4400        return Vec::new();
4401    }
4402    if task.replacement.is_some()
4403        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4404        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4405    {
4406        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()));
4407        record(queue, task);
4408        return Vec::new();
4409    }
4410    if let Some(reason) = retained_attempt_hold(
4411        task,
4412        &starter,
4413        config.disk.retained_attempt_limit,
4414        RunState::load,
4415    ) {
4416        // The review choice was consumed above. Preserve it across this hold
4417        // so a later release cannot silently become a fresh implementation.
4418        if let Starter::Review(branch) = &starter {
4419            task.review_branch = Some(branch.clone());
4420        }
4421        task.hold_unrequested_retry(Some(reason));
4422        record(queue, task);
4423        return Vec::new();
4424    }
4425    // Absolute paths of the files the task was filed with, re-read from the
4426    // task now so a file attached while it was held reaches a resumed run
4427    // too. A stored name whose file has gone is an error before any agent is
4428    // paid for, never a silent omission the implementer cannot notice.
4429    let attachments = match task_attachments(queue, task) {
4430        Ok(a) => a,
4431        Err(e) => {
4432            task.attempts += 1;
4433            task.fail_startup_target(
4434                "startup-attachments",
4435                e.name.clone(),
4436                format!("{start_failed}{e:#}"),
4437                opts.max_attempts,
4438            );
4439            record(queue, task);
4440            return Vec::new();
4441        }
4442    };
4443    let startup_pause = stop.pause();
4444    let startup_interrupt = interrupt_pause.clone();
4445    let wait = crate::repo_lock::WaitPolicy::new(
4446        Duration::from_secs(config.graph.timeout_resource_wait),
4447        move || startup_pause.parked() || startup_interrupt.parked(),
4448    );
4449    // Startup includes review takeover and recovery. Do not embed its large
4450    // future in both the wait scope and the surrounding attempt stack frame.
4451    let started = wait.scope(Box::pin(async { match &starter {
4452        Starter::Review(_) if task.pr_recovery.is_some() => {
4453            let selected = task.pr_recovery.clone().expect("selected recovery");
4454            match selected.check_task(&task.id, &task.instruction) {
4455                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4456                    .await
4457                    .map(|mut r| {
4458                        r.state.attachments = attachments.clone();
4459                        r
4460                    }),
4461                Err(e) => Err(e),
4462            }
4463        }
4464        Starter::Review(branch) => {
4465            tracing::info!(
4466                "task {} reopens `{branch}` as a review-only pass",
4467                task.short()
4468            );
4469            // Every earlier attempt is superseded by the one being minted
4470            // now, so a branch one of them still holds may be taken over.
4471            let takeover = crate::handover::Takeover {
4472                earlier: task.earlier_attempts().to_vec(),
4473                home: crate::run::home(),
4474                choice: take_divergence_answer(branch, &config.merge.remote, task),
4475                task_instruction: Some(instruction_for(task)),
4476            };
4477            Runner::review_taking_over(
4478                &repo,
4479                branch,
4480                config,
4481                Some(takeover),
4482                crate::run::Origin::queue(&task.id),
4483            )
4484            .await
4485        }
4486        Starter::Resume(id) => {
4487            tracing::info!("resuming run {id} rather than competing again");
4488            Runner::resume(id).and_then(|mut r| {
4489                if retry_selected {
4490                    // The explicit queue release retries this same pinned
4491                    // implementation, preserving the attempt and worktrees.
4492                    for candidate in &mut r.state.candidates {
4493                        candidate.failed = None;
4494                        candidate.empty = false;
4495                        candidate.commits = 0;
4496                    }
4497                    r.state.status = RunStatus::Implementing;
4498                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4499                }
4500                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4501                    r.state.sources = task.sources.clone();
4502                }
4503                if r.state.prep_failure.is_some() {
4504                    let approval = task
4505                        .resumption
4506                        .as_ref()
4507                        .context("preparation retry requires an explicit task release")?;
4508                    r.retry_preparation(approval.at)?;
4509                }
4510                if let Some(instruction) =
4511                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4512                {
4513                    r.state.instruction = instruction;
4514                }
4515                r.state.attachments = attachments.clone();
4516                if task.replacement.is_some() {
4517                    r.state.config.merge.mode = MergeMode::Pr;
4518                    r.state.config.graph.land_approval = true;
4519                }
4520                // Replacements publish a new PR and ask again. Selected PR
4521                // recoveries keep their saved disposition; ordinary runs can
4522                // retain the task's merge override.
4523                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4524                    .overrides
4525                    .as_ref()
4526                    .and_then(|o| o.merge.as_deref())
4527                    .and_then(|m| merge_mode(m).ok())
4528                {
4529                    r.state.config.merge.mode = mode;
4530                }
4531                Ok(r)
4532            })
4533        }
4534        Starter::Start => {
4535            if let Some(branch) = &review_branch {
4536                tracing::warn!(
4537                    "conductor chose review for task {} but branch `{branch}` no longer \
4538                     exists; requeuing as a fresh competition instead",
4539                    task.short()
4540                );
4541            }
4542            let instruction = prepare_instruction(&starter, None, task)
4543                .unwrap_or_else(|| task.instruction.clone());
4544            Runner::start_naming(
4545                &repo,
4546                instruction,
4547                &task.title,
4548                config,
4549                crate::run::Origin::queue(&task.id),
4550            )
4551            .await
4552            .map(|mut r| {
4553                r.state.attachments = attachments.clone();
4554                r.state.sources = task.sources.clone();
4555                r
4556            })
4557        }
4558    }})).await;
4559    let mut runner = match started {
4560        Ok(r) => r,
4561        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4562            task.last_error = Some(e.to_string());
4563            if stop.parking() || interrupt_pause.parked() {
4564                let attempts = task.attempts;
4565                task.park(e.to_string());
4566                // Startup has not spent an attempt to refund.
4567                task.attempts = attempts;
4568            } else {
4569                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4570            }
4571            record(queue, task);
4572            return Vec::new();
4573        }
4574        // A branch an earlier attempt still holds and magi will not release
4575        // by itself is the operator's call, not a failed attempt: hold the
4576        // task with the reason, spend nothing, and say so on the bell.
4577        Err(e) if task.pr_recovery.is_some() => {
4578            task.startup_notice_cause("startup-public-head");
4579            task.attempts += 1;
4580            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
4581                task.link_run(&partial.run);
4582                task.record_pass(&partial.run, 0, task.attempts, None);
4583            }
4584            task.last_error = Some(format!("{start_failed}{e:#}"));
4585            task.hold_unrequested_retry(Some(format!(
4586                "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."
4587            )));
4588            record(queue, task);
4589            return Vec::new();
4590        }
4591        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4592            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4593                Some(r) => (p.handover_refused)(r),
4594                None => format!("{e:#}"),
4595            };
4596            task.startup_notice_cause("startup-handover");
4597            let reason = format!("{start_failed}{detail}");
4598            task.last_error = Some(reason.clone());
4599            // Consumed above by `take`; keep it so the released task retries
4600            // as a review of this same branch.
4601            let branch = match &starter {
4602                Starter::Review(branch) => Some(branch.clone()),
4603                _ => None,
4604            };
4605            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4606            // one page; the guidance rides in the reason, fixed per state so a
4607            // re-put never changes the wording and relights it.
4608            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4609            record(queue, task);
4610            tracing::warn!(
4611                "holding {} for a branch it cannot take over: {e:#}",
4612                task.short()
4613            );
4614            return Vec::new();
4615        }
4616        // A branch that differs between here and the remote in ways magi
4617        // cannot prove are the same change is a decision for the owner, not a
4618        // failed attempt: ask with both sides laid out, spend no attempt, and
4619        // let the answer requeue the task.
4620        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4621            let d = e
4622                .downcast_ref::<crate::reconcile::Diverged>()
4623                .expect("checked by the guard");
4624            let mut q = ask::Question::new(
4625                task.id.clone(),
4626                crate::reconcile::NODE.to_owned(),
4627                crate::reconcile::SEAT.to_owned(),
4628                d.summary(),
4629                d.detail(),
4630                d.choices(),
4631            );
4632            match Questions::open().put(&mut q) {
4633                Ok(()) => {
4634                    task.last_error = Some(format!("{e:#}"));
4635                    // Consumed above by `take`; the answer has to reach a review
4636                    // of this same branch, so keep pointing the task at it.
4637                    task.review_branch = Some(d.branch.clone());
4638                    task.review_instruction = Some(task.instruction.clone());
4639                    task.block(vec![q.id.clone()], Some(d.summary()));
4640                }
4641                Err(put) => {
4642                    tracing::warn!("could not file the divergence question: {put:#}");
4643                    task.attempts += 1;
4644                    task.fail_startup(
4645                        "startup-question-store",
4646                        format!("{start_failed}{e:#}"),
4647                        opts.max_attempts,
4648                    );
4649                }
4650            }
4651            record(queue, task);
4652            return Vec::new();
4653        }
4654        Err(e) => {
4655            // The answer was stale and nothing was applied: keep pointing at
4656            // the branch so the next attempt asks again against its new tips.
4657            // Nothing went wrong with the task, so no attempt is spent: a
4658            // budget one short of its limit must not hold it instead of
4659            // letting the question be asked again.
4660            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4661                && let Starter::Review(branch) = &starter
4662            {
4663                task.review_branch = Some(branch.clone());
4664                task.review_instruction = Some(task.instruction.clone());
4665                task.last_error = Some(format!("{start_failed}{e:#}"));
4666                task.status = crate::queue::TaskStatus::Failed;
4667                record(queue, task);
4668                return Vec::new();
4669            }
4670            task.attempts += 1;
4671            task.last_error = Some(format!("{start_failed}{e:#}"));
4672            task.startup_notice_cause("startup-source");
4673            task.hold_unrequested_retry(Some(format!(
4674                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4675            )));
4676            record(queue, task);
4677            return Vec::new();
4678        }
4679    };
4680    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4681        runner.state.recovery_config = Some(config_evidence);
4682    }
4683    if let Some(replacement) = &task.replacement {
4684        if matches!(starter, Starter::Start) {
4685            runner.state.instruction.push_str(&format!(
4686                "\n\n# Replacement review context\n{}",
4687                replacement.context
4688            ));
4689        }
4690        runner.state.replaces = Some(replacement.clone());
4691        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4692        if let Ok(mut old) = RunState::load(&replacement.run)
4693            && let Some(d) = &mut old.merge_decision
4694        {
4695            d.replacement_run = Some(runner.state.id.clone());
4696            old.event(
4697                "replacement",
4698                format!(
4699                    "replacement run {} owns the next attempt; old PR remains closed",
4700                    runner.state.id
4701                ),
4702            );
4703            if let Err(e) = old.save() {
4704                task.hold_manual(Some(format!(
4705                    "Could not link replacement history: {e}; no agents dispatched"
4706                )));
4707                record(queue, task);
4708                return Vec::new();
4709            }
4710        }
4711    }
4712    runner.state.task_instruction = Some(task.instruction.clone());
4713    // The follow-up depth is fixed now, while the task certainly exists:
4714    // deleting it later must not reset the cap (`crate::followup`).
4715    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4716    if runner.state.origin_chat.is_none() {
4717        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4718    }
4719    // A stop that means "park" reaches the graph through this handle.
4720    runner.on_pause(stop.pause());
4721    // `poll`'s interrupt scheduler reaches this one run - and no other -
4722    // through this handle. See `Pause`'s own doc for why these are never
4723    // the same one.
4724    runner.watch_interrupt(interrupt_pause);
4725
4726    // `start` has minted the run, so the task can now point at it. Persisting
4727    // `Running` before `execute` is what makes a crash mid-run legible.
4728    let run = runner.state.id.clone();
4729    task.start(run.clone());
4730    record(queue, task);
4731    lock(status).current.push(Current {
4732        worker: None,
4733        task: task.id.clone(),
4734        run,
4735    });
4736
4737    // `RunState::quota` is the run's whole history across every resume, so
4738    // only what this execution added may arm the cooldown or earn a refund.
4739    let quota_before = runner.state.quota.clone();
4740    runner.state.next_pass_task_entry = true;
4741    let result = runner.execute().await;
4742    finish_attempt(
4743        opts.max_attempts,
4744        queue,
4745        task,
4746        &runner.state,
4747        &quota_before,
4748        result,
4749    )
4750}
4751
4752/// Settle `task` after its run executed: the verdict, the diagnosis, the
4753/// supersession of earlier attempts and the save. Shared by the loop and by
4754/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4755/// Returns the quota losses this execution added to the run.
4756pub fn finish_attempt(
4757    max_attempts: usize,
4758    queue: &Queue,
4759    task: &mut Task,
4760    state: &RunState,
4761    quota_before: &[QuotaLoss],
4762    result: Result<()>,
4763) -> Vec<QuotaLoss> {
4764    let detail = match result {
4765        Ok(()) => describe(state),
4766        Err(e) => format!("{e:#}"),
4767    };
4768    let fresh = losses_this_attempt(quota_before, &state.quota);
4769    let verdict = Verdict {
4770        status: state.status,
4771        // A run that opened a pull request handed its work over, whatever the
4772        // gate then decided about merging it.
4773        left_pr: state.pr.is_some(),
4774        // Only a rate limit earns the task its attempt back - and only one
4775        // suffered now: a refund justified by a previous session's loss is
4776        // the same mistake as re-arming the cooldown from it. A stalled run
4777        // resumed without hitting quota again therefore spends its attempt,
4778        // like any other failure of the task's own.
4779        quota_hit: !fresh.is_empty(),
4780        // A run that parked was asked to stop; that is not a failure and must
4781        // not spend an attempt, or replacing the binary a few times would
4782        // exhaust a task's budget without an agent ever misbehaving.
4783        parked: state.parked,
4784        // A quota loss that left nothing viable is the same machine fact as a
4785        // `Stalled` quota loss; see `settle`'s doc table.
4786        no_viable_candidates: state.viable().is_empty(),
4787    };
4788    if let Some(replacement) = &state.replaces
4789        && let Some(pr) = &state.pr
4790        && let Ok(mut old) = RunState::load(&replacement.run)
4791        && let Some(d) = &mut old.merge_decision
4792    {
4793        d.replacement_pr = Some(pr.url.clone());
4794        let _ = old.save();
4795    }
4796    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4797    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4798        task.hold_unrequested_retry(Some(format!(
4799            "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.",
4800            task.short()
4801        )));
4802    }
4803    if task.status == TaskStatus::Done {
4804        supersede_prior_runs(task, &crate::run::home());
4805    }
4806    record(queue, task);
4807    tracing::info!(
4808        "task {} is {} after run {} ({})",
4809        task.short(),
4810        task.status.as_str(),
4811        state.short(),
4812        label(state.status)
4813    );
4814    fresh
4815}
4816
4817/// A task a hand-started run leaves runnable (failed with attempts to spare,
4818/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4819/// later must not spend agent calls on it. `magi task release` retries.
4820pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4821    // Parked work (including legacy Failed records with a parked run) is a
4822    // checkpoint or owner handoff, not an unrequested retry.
4823    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4824        && !awaiting_resume_with(task, RunState::load)
4825        // A run parked on the owner's word about a withheld PR title/body
4826        // resumes via `land_resume_state`, including review-only tasks that
4827        // `awaiting_resume_with` does not consider.
4828        && withheld_text_wait(task).is_none()
4829        && !(task.fresh_start && task.replacement.is_some())
4830    {
4831        let why = task.last_error.clone().map_or_else(
4832            || "the run did not finish".to_owned(),
4833            |e| format!("the run did not finish: {e}"),
4834        );
4835        task.hold_unrequested_retry(Some(format!(
4836            "{why}. It was started by hand, so it is not retried \
4837             automatically; `magi task release` retries it."
4838        )));
4839        record(queue, task);
4840    }
4841}
4842
4843/// Whether an attempt at a task whose newest run is `run` would resume that
4844/// run rather than start a fresh competition. `magi run --resume` hands a run
4845/// to a live loop only when this holds.
4846#[must_use]
4847pub fn loop_would_resume(run: &str) -> bool {
4848    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4849}
4850
4851/// A loop in another process that is alive right now: a fresh heartbeat in
4852/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4853/// carries the pid it published (`None` inside when it published none - a
4854/// fresh heartbeat is still evidence of a live loop).
4855///
4856/// The one judgement of "is somebody else serving this queue", shared by the
4857/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4858/// deciding whether to hand a task to the loop. A claim file proves nothing
4859/// here: whether a claim succeeds says nothing about whether its owner lives.
4860#[must_use]
4861pub fn foreign_loop(
4862    reading: Option<&Reading>,
4863    now: Timestamp,
4864    own_pid: u32,
4865) -> Option<Option<u32>> {
4866    let reading = reading.filter(|r| r.running(now))?;
4867    match reading.pid {
4868        Some(pid) if pid == own_pid => None,
4869        pid => Some(pid),
4870    }
4871}
4872
4873fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4874    reading.worker_protocol != Some(1)
4875        && (foreign_loop(Some(reading), now, own_pid).is_some()
4876            || reading
4877                .pid
4878                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4879}
4880
4881/// Low-level claimed-task execution shared by the detached standalone worker
4882/// and focused lifecycle fixtures. The caller must retain the queue claim for
4883/// this entire call. CLI callers transfer ownership through
4884/// [`run_detached_claimed`] instead of executing inside their own runtime.
4885///
4886/// The one deliberate difference from the loop: a task the attempt leaves
4887/// runnable (failed with attempts to spare, or requeued) is **held** instead.
4888/// Nobody asked for a retry, and a daemon starting later must not spend agent
4889/// calls re-running a hand-started task behind the operator's back;
4890/// `magi task release` is the explicit retry.
4891pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4892    run_claimed_until(opts, queue, task, &Stop::new()).await;
4893}
4894
4895async fn run_claimed_until(
4896    opts: &Opts,
4897    queue: &Queue,
4898    task: &mut Task,
4899    stop: &Stop,
4900) -> Vec<QuotaLoss> {
4901    let status = Arc::new(Mutex::new(Status::new()));
4902    // An attempt embeds startup and graph futures. Keep it off the standalone
4903    // caller's stack, on both the initial execution and withheld-text resume.
4904    let mut quota = Box::pin(attempt(
4905        opts,
4906        queue,
4907        &status,
4908        stop,
4909        crate::graph::Pause::new(),
4910        task,
4911    ))
4912    .await;
4913    // A run parked on the owner's word about a withheld PR title/body has no
4914    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
4915    // here with the claim still held, and resume once the question is settled
4916    // (answered, or abandoned at its deadline -> the neutral text).
4917    // A rejected reply files one more question (the gate asks at most twice),
4918    // so after a resume the run may be waiting again: keep going, with a fresh
4919    // limit for the new question. `resumes` bounds it even if a resume parks
4920    // without asking anything new.
4921    let mut resumes = 0;
4922    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
4923        let Some(timeout) = withheld_text_wait(task) else {
4924            break;
4925        };
4926        eprintln!(
4927            "waiting for the owner's answer on a withheld pull request text \
4928             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4929        );
4930        // The deadline abandons the question itself; the extra margin only
4931        // covers an abandon that could not be saved.
4932        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4933        let ready = loop {
4934            match land_resume_state(task) {
4935                LandResume::StillWaiting
4936                    if !stop.parking() && std::time::Instant::now() < limit =>
4937                {
4938                    tokio::time::sleep(WITHHELD_POLL).await;
4939                }
4940                LandResume::Ready => break true,
4941                _ => break false,
4942            }
4943        };
4944        if !ready || stop.parking() {
4945            break;
4946        }
4947        resumes += 1;
4948        quota.extend(
4949            Box::pin(attempt(
4950                opts,
4951                queue,
4952                &status,
4953                stop,
4954                crate::graph::Pause::new(),
4955                task,
4956            ))
4957            .await,
4958        );
4959    }
4960    hold_if_runnable(queue, task);
4961    quota
4962}
4963
4964/// Resumes an in-process run makes for withheld-text questions: the gate asks
4965/// at most twice, plus one for a resume that asks nothing new.
4966const MAX_WITHHELD_RESUMES: u32 = 3;
4967
4968/// How often an in-process run rechecks its withheld-text question.
4969const WITHHELD_POLL: Duration = Duration::from_secs(15);
4970
4971/// The `answer_timeout` (seconds) of the task's last run when that run is
4972/// parked on an unresolved withheld-text question; `None` otherwise.
4973fn withheld_text_wait(task: &Task) -> Option<u64> {
4974    let id = task.runs.last()?;
4975    let s = RunState::load(id).ok()?;
4976    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
4977        .then_some(s.config.graph.answer_timeout)
4978}
4979
4980/// The quota losses `after` holds that `before` did not: what one execution
4981/// suffered, as opposed to the run's history.
4982///
4983/// Compared by value rather than by length or position because
4984/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
4985/// the vector can shrink and shift under a resume. A retried seat that hits
4986/// quota again is a `push` with a new `at`, so it shows up as new here.
4987/// `reclaim` deliberately keeps reading the whole history: after a crash there
4988/// is no attempt boundary to diff against.
4989fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
4990    after
4991        .iter()
4992        .filter(|q| !before.contains(q))
4993        .cloned()
4994        .collect()
4995}
4996
4997/// When the loop-wide quota cooldown should end, given this attempt's losses;
4998/// `None` when there were none. Reset-hint parsing and the cap live here.
4999fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5000    if quota.is_empty() {
5001        return None;
5002    }
5003    let with_hint = quota.iter().find(|q| q.reset.is_some());
5004    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5005    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5006    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5007    Some(
5008        now.checked_add(jiff::SignedDuration::from_secs(secs))
5009            .unwrap_or(Timestamp::MAX),
5010    )
5011}
5012
5013/// An explicit task count must agree with a run before any resume.
5014fn implementers_match(task: &Task, state: &RunState) -> bool {
5015    task.replacement.as_ref().map_or_else(
5016        || {
5017            task.implementers()
5018                .is_none_or(|n| n == state.config.graph.implementers)
5019        },
5020        |replacement| {
5021            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5022                && state.config.graph.implementers == 1
5023        },
5024    )
5025}
5026
5027/// Never resume or take over candidate work built for a different seat count.
5028fn starter_with_implementers(
5029    task: &Task,
5030    previous: Option<&RunState>,
5031    proposed: Starter,
5032) -> Starter {
5033    if previous.is_some_and(|s| !implementers_match(task, s)) {
5034        task.review_of
5035            .as_ref()
5036            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5037    } else {
5038        proposed
5039    }
5040}
5041
5042/// Apply this task's explicit count to the new attempt, without changing defaults.
5043fn apply_task_implementers(config: &mut Config, task: &Task) {
5044    if let Some(n) = task.implementers() {
5045        config.graph.implementers = n;
5046    }
5047}
5048
5049/// [`prepare`] for one task: its own `--config` and command-line overrides
5050/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5051/// over the loop's, so handing a hand-started task to a daemon changes nothing
5052/// about what it does.
5053#[cfg(test)]
5054fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5055    let explicit = match &task.overrides {
5056        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5057        _ => opts.config.as_deref(),
5058    };
5059    let (mut config, _) = Config::discover(repo, explicit)?;
5060    apply_options(&mut config, opts, task)?;
5061    Ok(config)
5062}
5063
5064fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5065    if task
5066        .overrides
5067        .as_ref()
5068        .is_none_or(|o| o.inherit_daemon_options)
5069        && let Some(mode) = opts.merge.as_deref()
5070    {
5071        config.merge.mode = merge_mode(mode)?;
5072    }
5073    if let Some(o) = &task.overrides {
5074        o.apply(config);
5075    }
5076    Ok(())
5077}
5078
5079/// Load the config for a task's repository, with the merge override applied.
5080fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5081    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5082    if let Some(mode) = &opts.merge {
5083        config.merge.mode = merge_mode(mode)?;
5084    }
5085    Ok(config)
5086}
5087
5088/// Prune the shared build cache at a between-runs boundary. The detached cache
5089/// service checks authoritative task jobs first; dispatch waits for that finite
5090/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5091/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5092async fn maybe_prune_cache_between_runs(
5093    repo: &Path,
5094    opts: &Opts,
5095    home: &Path,
5096    stop: &Stop,
5097    last_checked: &mut Option<Timestamp>,
5098    now: Timestamp,
5099) {
5100    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5101        return;
5102    }
5103    *last_checked = Some(now);
5104    let cfg = match prepare(repo, opts) {
5105        Ok(cfg) => cfg,
5106        Err(e) => {
5107            tracing::warn!("cache check: no config: {e:#}");
5108            return;
5109        }
5110    };
5111    match clean::prune_cache_if_over_limit(&cfg, home) {
5112        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5113            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5114            pruned.files,
5115            pruned.freed
5116        ),
5117        Ok(_) => {}
5118        Err(e) => {
5119            tracing::warn!("housekeep: prune cache: {e:#}");
5120            notices::raise_in(
5121                home,
5122                Notice::warn(
5123                    "housekeep:cache",
5124                    format!(
5125                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5126                        e.to_string()
5127                            .lines()
5128                            .next()
5129                            .unwrap_or("unknown cleanup error")
5130                    ),
5131                ),
5132            );
5133        }
5134    }
5135}
5136
5137/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5138/// now, given when it last did (if ever). Pure, so the cadence is asserted
5139/// directly rather than by waiting out real minutes in a test.
5140fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5141    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5142}
5143
5144/// The disk janitor, with its housekeeping logged rather than fatal.
5145///
5146/// Called only at the loop's idle points, for the reason the caller documents:
5147/// a prune racing a live compile would delete files mid-build. The config is
5148/// re-read on every call because the repository that just ran may not be the
5149/// daemon's own default, and the cache directory is a repository fact.
5150///
5151/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5152/// and [`crate::run::default_worktree_root`] read here, for the same reason
5153/// [`drive`] takes its queue and status file rather than resolving them: a
5154/// test driving the loop must not reach through to the operator's real home
5155/// or worktree bay just because the janitor runs on every idle tick.
5156/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5157/// to get wrong silently - a test's `home` was already isolated, but nothing
5158/// exercised the parameter next to it, so a real worktree bay stayed wired in
5159/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5160/// it for real, every test in this file that drives the loop at all started
5161/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5162async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5163    let cfg = match prepare(repo, opts) {
5164        Ok(cfg) => cfg,
5165        Err(e) => {
5166            tracing::warn!("housekeep: no config: {e:#}");
5167            return;
5168        }
5169    };
5170    // A run's own worktree lives under `config.graph.worktree_root` when the
5171    // repository sets one - the same precedence `RunState::worktree_root`
5172    // uses - and `worktrees_root` only stands in for the *default* an
5173    // unconfigured repository resolves to (see this function's own
5174    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5175    // that always swept the default regardless of this override would never
5176    // see, and so never reclaim, a single worktree for a repository that
5177    // relocated them elsewhere.
5178    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5179    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5180    // Reported whenever there is anything to say, not only when `folded > 0`:
5181    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5182    // folded, on every single pass, for months - a report gated on `folded`
5183    // would have stayed silent through every one of them.
5184    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5185        let mut extra = Vec::new();
5186        if out.unreadable > 0 {
5187            extra.push(format!("{} unreadable", out.unreadable));
5188        }
5189        if out.orphaned_worktrees > 0 {
5190            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5191        }
5192        let detail = if extra.is_empty() {
5193            String::new()
5194        } else {
5195            format!(" ({})", extra.join(", "))
5196        };
5197        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5198    }
5199    if out.external_merges_recorded > 0 {
5200        tracing::info!(
5201            "housekeep: recorded {} run(s) as merged externally",
5202            out.external_merges_recorded
5203        );
5204    }
5205    if out.stale_pr_states_repaired > 0 {
5206        tracing::info!(
5207            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5208            out.stale_pr_states_repaired
5209        );
5210    }
5211    if out.cache_files > 0 {
5212        tracing::info!(
5213            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5214            out.cache_files,
5215            out.cache_freed
5216        );
5217    }
5218    if out.questions_abandoned > 0 {
5219        tracing::info!(
5220            "housekeep: abandoned {} question(s) left open by a finished run",
5221            out.questions_abandoned
5222        );
5223    }
5224}
5225
5226/// Run [`triage::run_once`] and log whatever it did, the same "only when
5227/// there is something to say" rule [`janitor`] follows for its own report.
5228///
5229/// Called at the same idle points as [`janitor`] - once per full poll
5230/// interval, never mid-attempt - for the same reason: it is not liveness
5231/// critical, and a task's own `hold_reason` string is the one thing this
5232/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5233/// tick for no benefit.
5234async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5235    let questions = Questions::at(home.join("questions"));
5236    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5237    if report.is_empty() {
5238        return;
5239    }
5240    if !report.quarantined.is_empty() {
5241        tracing::info!(
5242            "triage: held {} blocked task(s) whose blocked-on task or \
5243             question no longer exists: {}",
5244            report.quarantined.len(),
5245            report.quarantined.join(", ")
5246        );
5247    }
5248    if !report.resumed.is_empty() {
5249        tracing::info!(
5250            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5251            report.resumed.len(),
5252            report.resumed.join(", ")
5253        );
5254    }
5255    if !report.asked.is_empty() {
5256        tracing::info!(
5257            "triage: asked about {} held task(s): {}",
5258            report.asked.len(),
5259            report.asked.join(", ")
5260        );
5261    }
5262    if !report.answered.is_empty() {
5263        tracing::info!(
5264            "triage: applied {} operator answer(s): {}",
5265            report.answered.len(),
5266            report.answered.join(", ")
5267        );
5268    }
5269}
5270
5271/// The free-space gate: what stands between this task and a new run, if
5272/// anything. `Some(reason)` holds the task; `None` lets it start.
5273///
5274/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5275/// the operator opted out. A measurement failure is a gate, not a pass: both
5276/// sides of "cannot tell" are served by not starting.
5277pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5278    disk_gate_with(repo, config, crate::disk::free_bytes)
5279}
5280
5281/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5282/// test can assert the exact wiring `attempt` runs - config's threshold in,
5283/// task-holding reason out - without asking the real machine's disk anything.
5284fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5285    repo: &Path,
5286    config: &Config,
5287    free_bytes: F,
5288) -> Option<String> {
5289    let min = config.disk.min_free_bytes;
5290    if min == 0 {
5291        return None;
5292    }
5293    let mut paths = vec![repo.to_owned()];
5294    if let Some(cache) = config.cache_dir() {
5295        paths.push(cache);
5296    }
5297    if let Some(root) = &config.graph.worktree_root {
5298        paths.push(root.clone());
5299    }
5300    for path in paths {
5301        let probe = if path == repo {
5302            path.as_path()
5303        } else {
5304            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5305        };
5306        let reason = match free_bytes(probe) {
5307            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5308            Err(e) => Some(crate::disk::unmeasured_in(
5309                probe,
5310                &e,
5311                &config.graph.language,
5312            )),
5313        };
5314        if reason.is_some() {
5315            return reason;
5316        }
5317    }
5318    None
5319}
5320
5321/// How long to wait before offering another task when a run lost a seat to a
5322/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5323/// could read, or carried nothing at all. Long enough that a quota outage
5324/// cannot burn through a whole backlog in the few seconds each doomed attempt
5325/// takes to fail; short enough that a quota which clears early is not left
5326/// idle for the fallback's sake.
5327const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5328
5329/// Longest a parsed reset hint may push the wait out to. The hint comes from
5330/// the CLI's own words, not a contract, so a parsing slip that lands a day
5331/// away must not leave the loop asleep for a day.
5332const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5333
5334/// How long [`poll`] should wait before offering the next task, after a run
5335/// lost at least one seat to a rate limit.
5336///
5337/// Pure and separate from the loop so the policy can be exercised without a
5338/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5339/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5340/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5341/// far a parsed hint is trusted to push the wait out.
5342fn quota_wait(
5343    reset_at: Option<Timestamp>,
5344    now: Timestamp,
5345    fallback: Duration,
5346    cap: Duration,
5347) -> Duration {
5348    match reset_at {
5349        Some(at) if at > now => {
5350            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5351            Duration::from_secs(secs).min(cap)
5352        }
5353        _ => fallback,
5354    }
5355}
5356
5357/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5358///
5359/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5360/// explains why parsing it exactly "would be a bug factory" — so this only
5361/// recognises the shapes actually observed in the wild, and returns `None`
5362/// for anything else rather than guess at a format nobody has seen.
5363///
5364/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5365/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5366/// said it, not from whenever this loop happens to read it: anchoring on `now`
5367/// would push the reset later on every read and would read an already-elapsed
5368/// reset as still in the future. (A long hint is still clamped by
5369/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5370fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5371    parse_reset_hint_zoned(text, now)
5372        .or_else(|| parse_reset_hint_dated(text))
5373        .or_else(|| parse_reset_hint_relative(text, recorded))
5374}
5375
5376/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5377/// optional but at least one required, in that order. A bare number or any
5378/// unknown unit is refused.
5379fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5380    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5381    let mut rest = rest.trim();
5382    if rest.is_empty() {
5383        return None;
5384    }
5385    let mut total: i64 = 0;
5386    let mut matched = false;
5387    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5388        if let Some((digits, tail)) = rest.split_once(unit)
5389            && !digits.is_empty()
5390            && digits.bytes().all(|b| b.is_ascii_digit())
5391        {
5392            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5393            rest = tail;
5394            matched = true;
5395        }
5396    }
5397    if !rest.is_empty() || !matched {
5398        return None;
5399    }
5400    recorded
5401        .checked_add(jiff::SignedDuration::from_secs(total))
5402        .ok()
5403}
5404
5405/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5406/// case-insensitive) into a 24-hour hour and minute. Shared by every
5407/// reset-hint shape below.
5408fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5409    let clock = clock.trim().to_lowercase();
5410    let (digits, pm) = clock
5411        .strip_suffix("am")
5412        .map(|d| (d, false))
5413        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5414    let (h, m) = digits.trim().split_once(':')?;
5415    let mut hour: i8 = h.trim().parse().ok()?;
5416    let minute: i8 = m.trim().parse().ok()?;
5417    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5418        return None;
5419    }
5420    if pm && hour != 12 {
5421        hour += 12;
5422    } else if !pm && hour == 12 {
5423        hour = 0;
5424    }
5425    Some((hour, minute))
5426}
5427
5428/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5429/// and a zone, never a date. A clock reading already past today is read as
5430/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5431/// the window rolled over while nothing was watching.
5432fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5433    let open = text.find('(')?;
5434    let close = text.rfind(')')?;
5435    if close <= open {
5436        return None;
5437    }
5438    let zone = text[open + 1..close].trim();
5439    let (hour, minute) = parse_12h_clock(&text[..open])?;
5440    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5441    let candidate = now
5442        .to_zoned(tz)
5443        .with()
5444        .hour(hour)
5445        .minute(minute)
5446        .second(0)
5447        .millisecond(0)
5448        .microsecond(0)
5449        .nanosecond(0)
5450        .build()
5451        .ok()?;
5452    let mut at = candidate.timestamp();
5453    if at <= now {
5454        at += jiff::SignedDuration::from_hours(24);
5455    }
5456    Some(at)
5457}
5458
5459/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5460/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5461/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5462/// "already past today" correction to make: the year already disambiguates
5463/// it. Scanned as a five-word window so it can be pulled out of the middle
5464/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5465/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5466/// any other timestamp with no zone attached.
5467fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5468    let words: Vec<&str> = text.split_whitespace().collect();
5469    if words.len() < 5 {
5470        return None;
5471    }
5472    (0..=words.len() - 5)
5473        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5474}
5475
5476/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5477/// parenthesis right after the window is refused rather than ignored — it
5478/// reads as an explicit zone annotation on a shape that otherwise carries
5479/// none, and guessing UTC anyway would be exactly the silent misread this
5480/// module's parsing otherwise avoids.
5481fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5482    if trailing.is_some_and(|next| next.starts_with('(')) {
5483        return None;
5484    }
5485    let month = month_number(window[0])?;
5486    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5487    let day_digits = ["st", "nd", "rd", "th"]
5488        .iter()
5489        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5490    let day: i8 = day_digits.parse().ok()?;
5491    let year_token = window[2];
5492    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5493        return None;
5494    }
5495    let year: i16 = year_token.parse().ok()?;
5496    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5497    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5498    // reusing the same 12-hour clock reader the bracketed shape uses.
5499    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5500    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5501    let date = jiff::civil::Date::new(year, month, day).ok()?;
5502    let candidate = date
5503        .at(hour, minute, 0, 0)
5504        .to_zoned(jiff::tz::TimeZone::UTC)
5505        .ok()?;
5506    Some(candidate.timestamp())
5507}
5508
5509/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5510/// case-insensitively, into a 1-based month number.
5511fn month_number(name: &str) -> Option<i8> {
5512    const NAMES: [&str; 12] = [
5513        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5514    ];
5515    let lower = name.to_lowercase();
5516    NAMES
5517        .iter()
5518        .position(|n| *n == lower.as_str())
5519        .map(|i| i as i8 + 1)
5520}
5521
5522/// Test probe for the shared resume policy's review-budget exclusion.
5523#[cfg(test)]
5524fn exhausted_review_budget(state: &RunState) -> bool {
5525    // A run whose task-head publication failed has nothing left to review:
5526    // resuming it only retries the publication, so it is never "exhausted".
5527    !crate::handover::can_resume(state)
5528        && state.status == RunStatus::Blocked
5529        && !state.released()
5530        && state.retired_to.is_none()
5531}
5532
5533/// This task's *most recent* run, if resuming it would actually make
5534/// progress. `short` is only for the warning's own message.
5535///
5536/// Only ever `runs.last()` — never a search back through older history.
5537/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5538/// mint, oldest first, and every entry before the last one was already
5539/// superseded at the moment it was minted: the daemon only ever starts a new
5540/// run when the previous one was not worth resuming (unresumable, exhausted,
5541/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5542/// opens a fresh review-only run alongside an older, already-failed
5543/// competition. Searching further back would let an old run that merely
5544/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5545/// behind, say — get resumed instead of the fresh competition
5546/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5547/// nothing asked to revisit.
5548///
5549/// Two runs paid for the "prefer resuming over restarting" half of this
5550/// lesson, which is why this still checks `runs.last()` rather than always
5551/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5552/// task a moment later, duplicating two and a half hours of agent work. Then
5553/// b25f stalled on a judge that timed out and one that answered with no JSON
5554/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5555/// **one second** later, buying three fresh implementations to reach the
5556/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5557/// the second case: a stall is terminal, and its cheap recovery re-asks only
5558/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5559/// that is technically `resumable()` but provably cannot progress must not
5560/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5561/// no-op instead of the fresh competition it promises.
5562///
5563/// A load failure is warned about rather than silently read as "not
5564/// resumable": the alternative is exactly what let a schema mismatch on run
5565/// `eba2` fall through to a full re-competition with nobody told why.
5566/// `crate::conduct` is what actually offers a better answer than
5567/// `Runner::start` here (see `Recovery::Review`), once this task's next
5568/// failure shows it up as `held`/`failed` with the run state unreadable.
5569fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5570    unfinished_run_with(runs, short, RunState::load)
5571}
5572
5573/// [`unfinished_run`] with an injected state reader. Tests provide their
5574/// fixtures directly rather than touching the process-global run home.
5575pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5576where
5577    F: FnMut(&str) -> Result<RunState>,
5578{
5579    let mut id = runs.last()?.clone();
5580    let mut visited = std::collections::BTreeSet::new();
5581    let mut repo = None;
5582    loop {
5583        if !runs.contains(&id) || !visited.insert(id.clone()) {
5584            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5585            return None;
5586        }
5587        let state = match load(&id) {
5588            Ok(state) if state.id == id => state,
5589            Ok(_) => return None,
5590            Err(e) => {
5591                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5592                return None;
5593            }
5594        };
5595        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5596            return None;
5597        }
5598        repo = Some(state.repo.clone());
5599        if let Some(authority) = state.retired_to {
5600            id = authority;
5601            continue;
5602        }
5603        return (crate::handover::can_resume(&state)
5604            && state.liveness(false) != crate::run::Liveness::Live)
5605            .then_some(id);
5606    }
5607}
5608
5609/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5610/// that [`attempt`] will resume it on its own?
5611///
5612/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5613/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5614/// injected reader like its sibling. An unreadable run is not awaiting
5615/// anything: it keeps going to the conductor as before.
5616fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5617where
5618    F: FnOnce(&str) -> Result<RunState>,
5619{
5620    // `Failed` stays: a record an older build wrote for a parked run.
5621    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5622        || task.fresh_start
5623        || task.review_branch.is_some()
5624    {
5625        return false;
5626    }
5627    let Some(id) = task.runs.last() else {
5628        return false;
5629    };
5630    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5631}
5632
5633/// Which of the three ways [`attempt`] can mint or continue a run this task
5634/// should use.
5635#[derive(Debug, Clone, PartialEq, Eq)]
5636enum Starter {
5637    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5638    /// and that still exists.
5639    Review(String),
5640    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5641    Resume(String),
5642    /// `crate::graph::Runner::start`: a fresh competition.
5643    Start,
5644}
5645
5646/// A second bound independent of inputs and the resettable failure counter.
5647/// Count recovery records, not history entries: resuming appends the same id.
5648/// Unknown history is not evidence that a new set of worktrees is affordable.
5649fn retained_attempt_hold(
5650    task: &Task,
5651    starter: &Starter,
5652    limit: usize,
5653    mut load: impl FnMut(&str) -> Result<RunState>,
5654) -> Option<String> {
5655    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5656        return None;
5657    }
5658    let mut retained = 0;
5659    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5660        let state = match load(id) {
5661            Ok(state) if state.id == *id => state,
5662            _ => {
5663                return Some(format!(
5664                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5665                ));
5666            }
5667        };
5668        if state.retired_to.is_some() || state.released() {
5669            continue;
5670        }
5671        // Neither a completed status nor an empty candidate array proves that
5672        // all recovery sources (including unrecorded preparation) were retired.
5673        retained += 1;
5674    }
5675    (retained >= limit).then(|| format!(
5676        "[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."
5677    ))
5678}
5679
5680/// A selected public implementation overrides every historical candidate and pin.
5681fn selected_starter(
5682    selected: &crate::pr_recovery::Selection,
5683    previous: Option<&RunState>,
5684    unfinished: Option<&str>,
5685) -> Starter {
5686    if let Some(id) = unfinished
5687        && previous.is_some_and(|r| {
5688            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5689        })
5690    {
5691        Starter::Resume(id.to_owned())
5692    } else {
5693        Starter::Review(selected.branch.clone())
5694    }
5695}
5696
5697/// The owner's answer to this branch's divergence question, consumed from the
5698/// task so a later, different divergence asks again. The runner applies it
5699/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5700fn take_divergence_answer(
5701    branch: &str,
5702    remote: &str,
5703    task: &mut Task,
5704) -> Option<crate::reconcile::Choice> {
5705    let summary = crate::reconcile::summary_for(branch, remote);
5706    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5707        (a.question == summary)
5708            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5709            .flatten()
5710            .map(|c| (i, c))
5711    })?;
5712    task.answers.remove(idx);
5713    Some(choice)
5714}
5715
5716/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5717/// this attempt should use. Pure, and separate from [`attempt`], so the
5718/// routing itself is assertable without spawning a real graph or a git
5719/// process: `attempt`'s own `crate::git::branch_exists` call has already
5720/// happened by the time this is called.
5721///
5722/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5723/// whose branch is gone falls all the way through to [`Starter::Start`], not
5724/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5725/// old (likely `Blocked`) run in the first place, and a branch that vanished
5726/// out from under that choice is not evidence resuming it would fare better.
5727fn choose_starter(
5728    review_branch: Option<&str>,
5729    branch_exists: bool,
5730    unfinished: Option<&str>,
5731) -> Starter {
5732    match review_branch {
5733        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5734        Some(_) => Starter::Start,
5735        None => match unfinished {
5736            Some(id) => Starter::Resume(id.to_owned()),
5737            None => Starter::Start,
5738        },
5739    }
5740}
5741
5742/// Reuse a compatible latest review owner instead of taking its checked-out
5743/// branch into a new run. Different branches and changed criteria still use
5744/// the ordinary review/takeover policy.
5745fn review_retry_starter(
5746    task: &Task,
5747    previous: Option<&RunState>,
5748    branch: Option<&str>,
5749    exists: bool,
5750    unfinished: Option<&str>,
5751) -> Starter {
5752    if let Some(run) = previous
5753        && unfinished == Some(run.id.as_str())
5754        && run.reviewed_commits.is_some()
5755        && branch.is_some_and(|branch| {
5756            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5757        })
5758        && may_resume_run(run, task)
5759    {
5760        return Starter::Resume(run.id.clone());
5761    }
5762    match (branch, unfinished, &task.review_of) {
5763        (None, None, Some(branch)) => Starter::Review(branch.clone()),
5764        _ => choose_starter(branch, exists, unfinished),
5765    }
5766}
5767
5768/// Consume a retained review only while its authored criteria still match.
5769fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5770    let branch = task.review_branch.take();
5771    let instruction = task.review_instruction.take();
5772    branch.filter(|branch| match &instruction {
5773        Some(authored) => *authored == task.instruction,
5774        // Legacy retained branches must agree with their prior run; only an
5775        // explicitly pinned review can proceed without recoverable provenance.
5776        None => previous.map_or_else(
5777            || task.review_of.as_ref() == Some(branch),
5778            |run| compatible_run_instruction(run, task),
5779        ),
5780    })
5781}
5782
5783/// A current explicit pin can select an otherwise incompatible run. Edits
5784/// and subsequent approvals invalidate pins selected for earlier criteria.
5785fn may_resume_run(run: &RunState, task: &Task) -> bool {
5786    task.resume_override
5787        .as_ref()
5788        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5789        || compatible_run_instruction(run, task)
5790}
5791
5792/// Review scaffolding is execution context, not evidence of an operator edit.
5793pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5794    if let Some(authored) = &run.task_instruction {
5795        return compatible_instruction(authored, task);
5796    }
5797    if compatible_instruction(&run.instruction, task) {
5798        return true;
5799    }
5800    // Recognize only the existing generated review shapes on legacy runs.
5801    // Ordinary authored text with a similar heading is left intact.
5802    if run.reviewed_commits.is_some() {
5803        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5804            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5805        }
5806        if let Some(branch) = &task.review_of {
5807            let canonical = format!(
5808                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5809            );
5810            let generated = format!(
5811                "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"
5812            );
5813            return task.instruction == canonical && run.instruction.starts_with(&generated);
5814        }
5815    }
5816    false
5817}
5818
5819/// Compare authored instructions, excluding answer blocks appended by the daemon.
5820pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5821    strip_answers_block(old, task) == task.instruction
5822}
5823
5824/// Which repository a task runs in. A task that names none — the normal case
5825/// for one filed from a phone — runs in the daemon's own default.
5826fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5827    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5828        return fallback.to_path_buf();
5829    }
5830    task.repo.clone()
5831}
5832
5833/// The header [`append_answers`] appends operator answers under. Shared with
5834/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5835/// rather than grown a new block on every resume.
5836const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5837
5838/// Render the first `count` answers in the block appended to an instruction.
5839fn answers_block(task: &Task, count: usize) -> String {
5840    let mut s = ANSWERS_HEADER.to_owned();
5841    for a in &task.answers[..count] {
5842        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5843    }
5844    s
5845}
5846
5847/// Render the approval independently of transient task state, so historical
5848/// suffixes remain recognizable after another explicit release.
5849fn resumption_block(r: &crate::queue::Resumption) -> String {
5850    format!(
5851        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5852         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5853        r.generation, r.at, r.instruction, r.answers_through,
5854    )
5855}
5856
5857/// Append audit answers and the latest explicit approval to the instruction.
5858fn append_answers(base: &str, task: &Task) -> String {
5859    let mut s = base.to_owned();
5860    if !task.answers.is_empty() {
5861        s.push_str(&answers_block(task, task.answers.len()));
5862    }
5863    if let Some(r) = &task.resumption {
5864        s.push_str(&resumption_block(r));
5865    }
5866    s
5867}
5868
5869/// Drop the prior answer block only when it is exactly the suffix this task
5870/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5871/// the task author is ordinary instruction text, not a block to remove.
5872fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5873    let mut instruction = instruction;
5874    for approval in task
5875        .resumption
5876        .iter()
5877        .chain(task.resumption_history.iter().rev())
5878    {
5879        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5880            instruction = base;
5881            break;
5882        }
5883    }
5884    for count in (1..=task.answers.len()).rev() {
5885        let block = answers_block(task, count);
5886        if let Some(base) = instruction.strip_suffix(&block) {
5887            return base;
5888        }
5889    }
5890    instruction
5891}
5892
5893/// The instruction handed to `Runner::start`: the task's own text, plus any
5894/// operator answers `crate::conduct` collected for it (see
5895/// [`Task::answers`]), so a decision the operator actually made reaches the
5896/// implementers rather than only clearing the block that was waiting on it.
5897///
5898/// Appended rather than merged into [`Task::instruction`] itself, so the
5899/// task's own record stays exactly what its author wrote.
5900fn instruction_for(task: &Task) -> String {
5901    append_answers(&task.instruction, task)
5902}
5903
5904/// The instruction a resumed run should carry on with: whatever it already
5905/// had, refreshed with the task's *current* operator answers.
5906///
5907/// A resumable run's own `RunState::instruction` predates any answer
5908/// `crate::conduct` collects after the run parks, so resuming it unchanged —
5909/// the behaviour before this function existed — silently drops the very
5910/// decision the operator made to unblock it. Re-stripping any block this
5911/// function appended on an earlier resume before re-appending the current
5912/// list (rather than blindly appending again) is what keeps a task resumed
5913/// three times over three answered questions from carrying the same answer
5914/// three times.
5915fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5916    append_answers(strip_answers_block(old_instruction, task), task)
5917}
5918
5919/// Preserve the producer's verified boundary and target, independent of prose.
5920fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5921    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5922    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5923    if let Some(cause) = task.hold_notice_cause.as_mut() {
5924        cause.target = failure.map(|f| f.target.clone());
5925    }
5926}
5927
5928#[derive(Debug, thiserror::Error)]
5929#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5930struct MissingAttachment {
5931    name: String,
5932    path: PathBuf,
5933}
5934
5935/// The task's attachments as absolute paths, each checked to still exist.
5936fn task_attachments(
5937    queue: &Queue,
5938    task: &Task,
5939) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5940    let paths = queue.attachment_paths(task);
5941    for (name, path) in task.attachments.iter().zip(&paths) {
5942        if !path.is_file() {
5943            return Err(MissingAttachment {
5944                name: name.clone(),
5945                path: path.clone(),
5946            });
5947        }
5948    }
5949    Ok(paths)
5950}
5951
5952/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
5953/// answers before handing it to `Runner` — the actual boundary between
5954/// [`choose_starter`]'s routing and the graph, factored out so it is
5955/// assertable without a real repository, git branch, or agent CLI.
5956///
5957/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
5958/// instruction from the reviewed branch's own commit log because there is no
5959/// task statement to speak of for hand-written work, and splicing operator
5960/// answers into that text would contradict the very message it sends
5961/// reviewers ("there is no task statement").
5962fn prepare_instruction(
5963    starter: &Starter,
5964    old_instruction: Option<&str>,
5965    task: &Task,
5966) -> Option<String> {
5967    match starter {
5968        Starter::Start => Some(instruction_for(task)),
5969        Starter::Resume(_) => Some(resumed_instruction(
5970            old_instruction.expect("a resumed run always has a prior instruction"),
5971            task,
5972        )),
5973        Starter::Review(_) => None,
5974    }
5975}
5976
5977/// Persist a transition. A queue write failure is logged rather than fatal: the
5978/// run already happened, and taking the daemon down would only add a lost
5979/// backlog to a full disk.
5980fn record(queue: &Queue, task: &mut Task) {
5981    if let Err(e) = queue.put(task) {
5982        tracing::error!("could not record task {}: {e:#}", task.short());
5983        let notice = Notice::error(
5984            "loop:record",
5985            format!(
5986                "Task {} state could not be saved: {}. Check the disk.",
5987                task.id,
5988                e.to_string().lines().next().unwrap_or("unknown save error")
5989            ),
5990        )
5991        .link(Link::Task {
5992            id: task.id.clone(),
5993        });
5994        // The queue lives at `<home>/queue`, so its parent is the home.
5995        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
5996            Some(home) => notices::raise_in(home, notice),
5997            None => notices::raise(notice),
5998        }
5999    }
6000}
6001
6002/// Every runnable task, in the order the loop should try them.
6003///
6004/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6005/// tail exists so that a claim somebody else holds costs the loop the next
6006/// candidate rather than a whole poll interval of idleness.
6007fn runnable(queue: &Queue) -> Vec<Task> {
6008    let mut tasks: Vec<Task> = queue
6009        .list()
6010        .into_iter()
6011        .filter(|t| t.status.runnable())
6012        .collect();
6013    tasks.sort_unstable_by(crate::queue::dispatch_order);
6014    tasks
6015}
6016
6017/// Why a run ended where it did, in one line, for [`Task::last_error`].
6018///
6019/// A stalled run names the seats the quota took out: "out of quota" is not
6020/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6021/// agent to replace or which plan to top up.
6022///
6023/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6024/// purpose: unlike `label`'s other callers (an internal log line, an
6025/// already-a-bug fallback message), this string becomes `Task::last_error`
6026/// verbatim, which the phone renders in the same alarm-styled box an
6027/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6028/// `.err` styling. A bare `verified_noop` there would read exactly like the
6029/// failure this whole feature exists to tell apart from one.
6030fn describe(state: &RunState) -> String {
6031    let p = phrases(&state.config.graph.language);
6032    let mut detail = if state.status == RunStatus::Stalled {
6033        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6034        seats.sort_unstable();
6035        seats.dedup();
6036        if seats.is_empty() {
6037            p.quorum_lost.to_owned()
6038        } else {
6039            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6040        }
6041    } else {
6042        format!("{}{}", p.run_ended, state.status.display_label())
6043    };
6044    if let Some(last) = state.events.last() {
6045        // The review loop's "never answered" stop is the one event worth
6046        // translating; it is recognised from structured state, not by
6047        // matching the English event text (which stays as recorded).
6048        let unanswered = state
6049            .reviews
6050            .last()
6051            .filter(|r| {
6052                state.status == RunStatus::Blocked
6053                    && last.node == "review"
6054                    && r.incomplete()
6055                    && r.blocking == 0
6056                    && r.round == state.config.graph.review_rounds
6057                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6058            })
6059            .map(|r| (r.expected - r.answered, r.round));
6060        match unanswered {
6061            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6062                detail.push_str(&format!(
6063                    " ({}: {})",
6064                    last.node,
6065                    (p.reviewers_never_answered)(missing, rounds)
6066                ));
6067            }
6068            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6069        }
6070    }
6071    detail.push_str(&format!(" [run {}]", state.id));
6072    detail
6073}
6074
6075/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6076///
6077/// The task file lives in the backlog indefinitely; a diagnostic is an
6078/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6079/// stay small regardless of how much a gate command or a candidate printed.
6080const DIAGNOSTIC_MAX: usize = 4_000;
6081
6082/// Tail kept from a single failing command's output inside a diagnostic.
6083/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6084/// pointer for a human deciding whether to go read the full artifact by hand,
6085/// not a replacement for reading it.
6086const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6087
6088/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6089/// `magi task show` says more than the one-line reason in [`describe`].
6090///
6091/// The one-liner answers "where did the run stop"; this answers "what would a
6092/// human have found opening `artifacts/` by hand" — the point of the whole
6093/// feature is the case that one-liner actively misleads on: a run held as "no
6094/// candidate produced a change" can mean the implementer actually finished
6095/// the task (opened a PR, merged it, tagged a release) and only left a clean
6096/// local worktree behind, which reads as "nothing happened" unless someone
6097/// goes and reads what the agent actually said. `None` when the run carries
6098/// none of the three shapes this recognises — an ordinary run held for
6099/// something not diagnosable from `RunState` alone still explains itself
6100/// through `Task::last_error`.
6101fn diagnostic(state: &RunState) -> Option<String> {
6102    let mut parts: Vec<String> = Vec::new();
6103
6104    // Gate failure: which check(s), and the tail of what each printed.
6105    for o in state.gate.iter().filter(|o| !o.ok()) {
6106        parts.push(format!(
6107            "gate `{}` failed ({}):\n{}",
6108            o.command,
6109            notices::exit_status(o.code),
6110            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6111        ));
6112    }
6113
6114    // The land loop gave up because the fixer declined while checks were
6115    // still red: the message already names them (see `land::run`).
6116    if let Some(last) = state
6117        .events
6118        .iter()
6119        .rev()
6120        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6121    {
6122        parts.push(last.message.clone());
6123    }
6124
6125    // No viable candidate: every implementer's own final word, sanitized the
6126    // same way a judge would have read it, so a run that actually finished
6127    // the job does not read as an unexplained failure. A verified no-op is
6128    // called out ahead of its own summary and apart from an ordinary
6129    // failure's `why` — this is the one candidate shape whose diagnostic a
6130    // human is expected to actually judge, not just skim.
6131    if state.viable().is_empty() {
6132        for c in &state.candidates {
6133            if let Some(evidence) = &c.verified_noop {
6134                parts.push(format!(
6135                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6136                    c.label
6137                ));
6138            } else if !c.summary.trim().is_empty() {
6139                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6140            } else if let Some(why) = &c.failed {
6141                parts.push(format!("candidate {}: {why}", c.label));
6142            }
6143        }
6144    }
6145
6146    if parts.is_empty() {
6147        return None;
6148    }
6149    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6150    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6151    // back slightly over. Leave it enough room to always land under the
6152    // limit.
6153    Some(crate::run::tail(
6154        &parts.join("\n\n"),
6155        DIAGNOSTIC_MAX.saturating_sub(100),
6156    ))
6157}
6158
6159/// Stable lower-case name for a run status, for an internal log line and the
6160/// "graph stopped without reaching a terminal status" bug message in
6161/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6162/// doc for why that one reads [`RunStatus::display_label`] instead. One
6163/// definition of a status's name, on the type that owns it: this table used
6164/// to live here as a second copy, and a status renamed in one place would
6165/// have gone on reading correctly in the other.
6166fn label(status: RunStatus) -> &'static str {
6167    status.as_str()
6168}
6169
6170/// Parse a merge mode override.
6171pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6172    match mode {
6173        "none" => Ok(MergeMode::None),
6174        "local" => Ok(MergeMode::Local),
6175        "pr" => Ok(MergeMode::Pr),
6176        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6177    }
6178}
6179
6180/// Take the status lock, recovering from a poisoned one.
6181///
6182/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6183/// data, and the worst a poisoned lock can hold is a stale timestamp.
6184fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6185    mutex
6186        .lock()
6187        .unwrap_or_else(std::sync::PoisonError::into_inner)
6188}
6189
6190#[cfg(test)]
6191mod tests {
6192    use super::*;
6193    use crate::queue::{Source, TaskStatus};
6194    use crate::run::{Candidate, CommandOutcome};
6195    use pretty_assertions::assert_eq;
6196
6197    fn task() -> Task {
6198        Task::new(
6199            "add retries".to_owned(),
6200            "add retries".to_owned(),
6201            PathBuf::from("/repo"),
6202            Source::Human,
6203        )
6204    }
6205
6206    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6207        let job = crate::worker::Job {
6208            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6209            sequence: 1,
6210            kind: "task".into(),
6211            key: format!("task:{}", request.task),
6212            payload: serde_json::to_value(request).unwrap(),
6213            generation: "a".repeat(64),
6214            version: None,
6215            status: crate::worker::Status::Starting,
6216            result: None,
6217            pid: None,
6218            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6219            finished_at: None,
6220        };
6221        let dir = home.join("workers/jobs").join(&job.id);
6222        std::fs::create_dir_all(&dir).unwrap();
6223        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6224        job
6225    }
6226
6227    #[test]
6228    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6229        let home = tempfile::tempdir().unwrap();
6230        let request = TaskWorker {
6231            opts: Opts::default(),
6232            queue: home.path().join("queue"),
6233            task: "startup".into(),
6234            lane: PermitKind::Ordinary,
6235            standalone: false,
6236        };
6237        let job = starting_task_reservation(home.path(), &request);
6238        let error = task_worker_spawn_error(
6239            home.path(),
6240            &request,
6241            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6242        )
6243        .expect_err("our own reservation must not turn a failed spawn into a resync");
6244        let active = crate::worker::active(home.path()).unwrap();
6245        assert_eq!(active.len(), 1);
6246        assert_eq!(active[0].id, job.id);
6247        assert_eq!(active[0].status, crate::worker::Status::Starting);
6248        assert!(
6249            crate::worker::control(home.path(), &job.key)
6250                .unwrap()
6251                .is_none()
6252        );
6253        let notices = notices::Notices::at(home.path().join("notifications")).list();
6254        assert_eq!(notices.len(), 1);
6255        assert_eq!(notices[0].key, "loop:worker-startup");
6256        assert!(!notices[0].message.contains("private-error-detail"));
6257        assert!(notices[0].message.contains(&request.task));
6258        assert!(
6259            notices[0]
6260                .message
6261                .contains("could not be started or acknowledged")
6262        );
6263        assert!(notices[0].message.contains("worker.log"));
6264        assert_eq!(
6265            notices[0].link,
6266            Some(Link::Task {
6267                id: request.task.clone()
6268            })
6269        );
6270        assert!(format!("{error:#}").contains("private-error-detail"));
6271    }
6272
6273    #[test]
6274    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6275        let home = tempfile::tempdir().unwrap();
6276        let mut request = TaskWorker {
6277            opts: Opts::default(),
6278            queue: home.path().join("queue"),
6279            task: "handoff".into(),
6280            lane: PermitKind::Ordinary,
6281            standalone: true,
6282        };
6283        let job = starting_task_reservation(home.path(), &request);
6284        request.standalone = false;
6285        task_worker_spawn_error(
6286            home.path(),
6287            &request,
6288            anyhow::anyhow!("operation key is already reserved for a different request"),
6289        )
6290        .expect("a different standalone request is the handoff race, not our startup failure");
6291        let active = crate::worker::active(home.path()).unwrap();
6292        assert_eq!(active.len(), 1);
6293        assert_eq!(active[0].id, job.id);
6294        assert_eq!(active[0].payload, job.payload);
6295        assert!(
6296            notices::Notices::at(home.path().join("notifications"))
6297                .list()
6298                .is_empty()
6299        );
6300    }
6301
6302    #[test]
6303    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6304        let home = tempfile::tempdir().unwrap();
6305        let queue = Queue::at(home.path().join("queue"));
6306        let mut task = task();
6307        task.runs = vec!["previous".into()];
6308        queue.put(&mut task).unwrap();
6309        let request = TaskWorker {
6310            opts: Opts::default(),
6311            queue: home.path().join("queue"),
6312            task: task.id.clone(),
6313            lane: PermitKind::Ordinary,
6314            standalone: false,
6315        };
6316        let job = starting_task_reservation(home.path(), &request);
6317        let claims = current_work(home.path(), Timestamp::now());
6318        assert_eq!(claims.len(), 1);
6319        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6320        assert_eq!(claims[0].run, "previous");
6321        assert!(other_claims_run(&claims, "previous", None));
6322        // Only after confirming the executing caller may admission ignore
6323        // this exact projection. Cleanup continues to observe it as live.
6324        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6325        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6326    }
6327
6328    #[test]
6329    fn admission_excludes_only_the_callers_exact_reservation() {
6330        let own = Current {
6331            worker: Some("own".into()),
6332            task: "same-task".into(),
6333            run: "previous".into(),
6334        };
6335        assert!(!other_claims_run(
6336            std::slice::from_ref(&own),
6337            "previous",
6338            Some("own")
6339        ));
6340        assert!(other_claims_run(
6341            std::slice::from_ref(&own),
6342            "previous",
6343            None
6344        ));
6345        for worker in [None, Some("other".into())] {
6346            let other = Current {
6347                worker,
6348                ..own.clone()
6349            };
6350            assert!(other_claims_run(
6351                &[own.clone(), other],
6352                "previous",
6353                Some("own")
6354            ));
6355        }
6356        let legacy: Current =
6357            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6358        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6359    }
6360
6361    #[test]
6362    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6363        let mut task = task();
6364        let mut run = run_state(RunStatus::Reviewing);
6365        run.task_instruction = Some(task.instruction.clone());
6366        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6367        let branch = "magi/test/B";
6368        run.candidates.push(crate::run::Candidate {
6369            branch: branch.into(),
6370            ..candidate('B', "preserved work", false, None)
6371        });
6372        task.runs = vec![run.id.clone()];
6373        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6374        assert_eq!(
6375            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6376            Starter::Resume(run.id.clone())
6377        );
6378        assert!(matches!(
6379            review_retry_starter(
6380                &task,
6381                Some(&run),
6382                Some("different"),
6383                true,
6384                unfinished.as_deref()
6385            ),
6386            Starter::Review(_)
6387        ));
6388        assert_eq!(
6389            review_retry_starter(
6390                &task,
6391                Some(&run),
6392                Some(branch),
6393                false,
6394                unfinished.as_deref()
6395            ),
6396            Starter::Start
6397        );
6398        task.instruction.push_str(" changed criteria");
6399        assert!(matches!(
6400            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6401            Starter::Review(_)
6402        ));
6403        assert!(matches!(
6404            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6405            Starter::Review(_)
6406        ));
6407    }
6408
6409    #[test]
6410    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6411        let dir = tempfile::tempdir().unwrap();
6412        let queue = Queue::at(dir.path().join("queue"));
6413        let mut task = task();
6414        task.status = TaskStatus::Running;
6415        task.attempts = 1;
6416        queue.put(&mut task).unwrap();
6417        let live = std::collections::BTreeSet::from([task.id.clone()]);
6418        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6419        drop(queue.claim(&task.id).unwrap());
6420        let saved = queue.get(&task.id).unwrap();
6421        assert_eq!(saved.status, TaskStatus::Running);
6422        assert_eq!(saved.attempts, 1);
6423        assert!(saved.last_error.is_none());
6424    }
6425
6426    #[test]
6427    fn standalone_workers_do_not_consume_scheduler_lanes() {
6428        let request = |task: &str, lane, standalone| TaskWorker {
6429            opts: Opts::default(),
6430            queue: PathBuf::from("/queue"),
6431            task: task.to_owned(),
6432            lane,
6433            standalone,
6434        };
6435        let mut jobs = vec![
6436            request("ordinary", PermitKind::Ordinary, false),
6437            request("standalone-urgent", PermitKind::Urgent, true),
6438            request("standalone-ordinary", PermitKind::Ordinary, true),
6439            request("decision", PermitKind::None, false),
6440        ];
6441        assert_eq!(available_slots(&jobs, 2), (1, 1));
6442        jobs.push(request("urgent", PermitKind::Urgent, false));
6443        assert_eq!(available_slots(&jobs, 2), (1, 0));
6444        assert_eq!(available_slots(&jobs, 0), (0, 0));
6445    }
6446
6447    #[test]
6448    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6449        let now = Timestamp::now();
6450        let mut reading = Reading {
6451            pid: Some(std::process::id()),
6452            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6453            ..Reading::default()
6454        };
6455        assert!(!reading.running(now));
6456        assert!(legacy_scheduler_running(&reading, now, 0));
6457        reading.worker_protocol = Some(1);
6458        assert!(!legacy_scheduler_running(&reading, now, 0));
6459    }
6460
6461    #[test]
6462    fn selected_public_head_overrides_historical_resume_and_pin() {
6463        let mut t = task();
6464        let mut old = run_state(RunStatus::Blocked);
6465        let selection = crate::pr_recovery::Selection {
6466            url: "url".into(),
6467            branch: format!("magi/task-{}", t.id),
6468            head: "a".repeat(40),
6469            source_head: None,
6470            source_run: None,
6471            source_proof: None,
6472            disposition: Some(crate::pr_recovery::Disposition::Review),
6473            instruction: t.instruction.clone(),
6474            approved_at: Timestamp::now(),
6475        };
6476        t.resume_override = Some(crate::queue::OperatorResume {
6477            pinned_run: Some(old.id.clone()),
6478            question_id: "choice".into(),
6479            at: Timestamp::now(),
6480            conductor_rehold: None,
6481            forced: false,
6482        });
6483        assert_eq!(
6484            selected_starter(&selection, Some(&old), Some(&old.id)),
6485            Starter::Review(selection.branch.clone())
6486        );
6487        old.pr_recovery = Some(selection.clone());
6488        assert_eq!(
6489            selected_starter(&selection, Some(&old), Some(&old.id)),
6490            Starter::Review(selection.branch.clone())
6491        );
6492        old.reviewed_commits = Some(vec!["implementation".into()]);
6493        assert_eq!(
6494            selected_starter(&selection, Some(&old), Some(&old.id)),
6495            Starter::Resume(old.id.clone())
6496        );
6497        let mut changed = selection.clone();
6498        changed.head = "b".repeat(40);
6499        assert_eq!(
6500            selected_starter(&changed, Some(&old), Some(&old.id)),
6501            Starter::Review(changed.branch)
6502        );
6503    }
6504
6505    #[test]
6506    fn candidate_transplant_failure_is_one_actionable_hold() {
6507        let dir = tempfile::tempdir().unwrap();
6508        let q = Queue::at(dir.path().join("queue"));
6509        let mut t = task();
6510        let mut state = run_state(RunStatus::Blocked);
6511        state.event("prep", "cannot apply referenced commit: conflict");
6512        state.prep_failure = Some("conflict".into());
6513        t.start(state.id.clone());
6514        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6515        assert_eq!(t.attempts, 1);
6516        assert_eq!(t.status, TaskStatus::Held);
6517        assert!(t.operator_held());
6518        assert!(!t.status.runnable());
6519        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6520        let first = t.chat_notice_key().unwrap();
6521        t.chat_notices.push(first.clone());
6522        t.release_operator("test", None);
6523        state.id = "another-unprepared-run".into();
6524        t.start(state.id.clone());
6525        finish_attempt(
6526            3,
6527            &q,
6528            &mut t,
6529            &state,
6530            &[],
6531            Err(anyhow::anyhow!("still conflicts")),
6532        );
6533        assert_eq!(
6534            t.chat_notice_key().as_ref(),
6535            Some(&first),
6536            "no work happened"
6537        );
6538        t.release_operator("test", None);
6539        state.prep_failure = None;
6540        state.status = RunStatus::Failed;
6541        state.begin_pass();
6542        t.start(state.id.clone());
6543        finish_attempt(
6544            1,
6545            &q,
6546            &mut t,
6547            &state,
6548            &[],
6549            Err(anyhow::anyhow!("new gate failure")),
6550        );
6551        let failure = t.chat_notice_key().unwrap();
6552        assert_ne!(failure, first, "approved recovery reached a real failure");
6553        t.release_operator("test", None);
6554        state.begin_pass();
6555        t.start(state.id.clone());
6556        finish_attempt(
6557            1,
6558            &q,
6559            &mut t,
6560            &state,
6561            &[],
6562            Err(anyhow::anyhow!("new failure on resume")),
6563        );
6564        assert_ne!(
6565            t.chat_notice_key().as_ref(),
6566            Some(&failure),
6567            "a new settled pass"
6568        );
6569    }
6570
6571    #[test]
6572    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6573        for source in ["cli", "web"] {
6574            let mut t = task();
6575            let mut run = run_state(RunStatus::Blocked);
6576            run.instruction = "Run A original criteria".into();
6577            run.task_instruction = Some(run.instruction.clone());
6578            t.start(run.id.clone());
6579            t.release_operator("choice", Some("resume-question"));
6580            t.resume_override = Some(crate::queue::OperatorResume {
6581                question_id: "resume-question".into(),
6582                at: Timestamp::now(),
6583                conductor_rehold: None,
6584                forced: true,
6585                pinned_run: Some(run.id.clone()),
6586            });
6587            t.hold_machine(Some("not enough free space to start a run".into()));
6588            let mut unchanged = t.clone();
6589            unchanged
6590                .edit("title changed".into(), unchanged.instruction.clone())
6591                .unwrap();
6592            unchanged.release_operator(source, None);
6593            assert_eq!(
6594                unchanged
6595                    .resume_override
6596                    .as_ref()
6597                    .unwrap()
6598                    .pinned_run
6599                    .as_deref(),
6600                Some(run.id.as_str())
6601            );
6602            assert!(!compatible_run_instruction(&run, &unchanged));
6603            assert!(may_resume_run(&run, &unchanged));
6604
6605            t.edit(
6606                "approved recovery".into(),
6607                "Reuse measured PR head B; fix Clippy; review".into(),
6608            )
6609            .unwrap();
6610            assert!(t.resume_override.is_none());
6611            t.release_operator(source, None);
6612            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6613            assert!(reloaded.resume_override.is_none());
6614            assert!(!may_resume_run(&run, &reloaded));
6615            let unfinished =
6616                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6617                    .filter(|_| may_resume_run(&run, &reloaded));
6618            assert_eq!(
6619                choose_starter(None, false, unfinished.as_deref()),
6620                Starter::Start
6621            );
6622            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6623            assert_eq!(
6624                reloaded.resumption_history[0].question_id.as_deref(),
6625                Some("resume-question")
6626            );
6627
6628            // A revision already persisted with the old approval/pin is also
6629            // invalidated when the new operator release is recorded.
6630            unchanged.instruction = "Reuse measured PR head B".into();
6631            unchanged.hold_machine(Some("disk hold".into()));
6632            unchanged.release_operator(source, None);
6633            assert!(unchanged.resume_override.is_none());
6634            assert!(!may_resume_run(&run, &unchanged));
6635        }
6636    }
6637
6638    #[test]
6639    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6640        let mut t = task();
6641        let mut run = run_state(RunStatus::Blocked);
6642        t.review_of = Some("approved-head".into());
6643        t.instruction =
6644            "Review the branch `approved-head` (review-only: no implementation, no judging)."
6645                .into();
6646        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();
6647        run.reviewed_commits = Some(vec!["Commit log".into()]);
6648        t.start(run.id.clone());
6649        t.hold_machine(Some("interrupted review".into()));
6650        t.release_operator("cli", None);
6651        assert!(
6652            compatible_run_instruction(&run, &t),
6653            "legacy explicit review remains resumable"
6654        );
6655        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6656            .filter(|_| compatible_run_instruction(&run, &t));
6657        assert_eq!(
6658            choose_starter(None, false, unfinished.as_deref()),
6659            Starter::Resume(run.id.clone())
6660        );
6661        run.task_instruction = Some(t.instruction.clone());
6662        assert!(compatible_run_instruction(&run, &t));
6663        let reloaded: RunState =
6664            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6665        assert!(compatible_run_instruction(&reloaded, &t));
6666        t.edit(
6667            "new approved head".into(),
6668            "Reuse measured PR head B".into(),
6669        )
6670        .unwrap();
6671        assert!(!compatible_run_instruction(&run, &t));
6672
6673        // Legacy recovery reviews retain the task criteria ahead of the log.
6674        t.review_of = None;
6675        t.instruction = "Fix Clippy on approved head".into();
6676        run.task_instruction = None;
6677        run.instruction = format!(
6678            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6679            t.instruction
6680        );
6681        assert!(compatible_run_instruction(&run, &t));
6682        t.instruction.push('\n');
6683        assert!(
6684            compatible_run_instruction(&run, &t),
6685            "legacy generated review trimmed the original criteria"
6686        );
6687        t.hold_for_handover(Some("approved-head".into()), "refused".into());
6688        let mut unchanged = t.clone();
6689        assert_eq!(
6690            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6691            Some("approved-head")
6692        );
6693        t.edit("new plan".into(), "Reuse measured PR head B".into())
6694            .unwrap();
6695        assert!(take_review_branch(&mut t, Some(&run)).is_none());
6696        assert!(!compatible_run_instruction(&run, &t));
6697        t.review_branch = Some("approved-head".into());
6698        t.review_instruction = None;
6699        assert!(
6700            take_review_branch(&mut t, Some(&run)).is_none(),
6701            "legacy retained candidate cannot replace a revised approved head"
6702        );
6703    }
6704
6705    #[test]
6706    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6707        crate::run::pin_test_home();
6708        let dir = tempfile::tempdir().unwrap();
6709        let queue = Queue::at(dir.path().join("queue"));
6710        for resume in [true, false] {
6711            let state = run_state(RunStatus::Blocked);
6712            let mut t = task();
6713            t.start(state.id.clone());
6714            let action = if resume {
6715                ask::ChoiceAction::Resume {
6716                    run: state.id.clone(),
6717                }
6718            } else {
6719                ask::ChoiceAction::Requeue
6720            };
6721            let mut q = action_question(&state.id, action);
6722            q.status = ask::QuestionStatus::Open;
6723            q.answer = None;
6724            q.answered_at = None;
6725            t.fail("run stopped with a question", 3);
6726            hold_if_runnable(&queue, &mut t);
6727            assert!(t.operator_decided_at.is_none());
6728            assert!(t.operator_held());
6729            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6730            let expected = if resume {
6731                ActionDecision::Resume(state.id.clone())
6732            } else {
6733                ActionDecision::Requeue
6734            };
6735            assert_eq!(
6736                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6737                expected
6738            );
6739            t.hold_manual(Some("later explicit hold".into()));
6740            assert_eq!(
6741                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6742                ActionDecision::Stale
6743            );
6744        }
6745    }
6746
6747    #[test]
6748    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6749        let mut t = task();
6750        t.answers.push(crate::queue::AnsweredQuestion {
6751            question: "Inspect the remote?".into(),
6752            answer: "Inspect then wait".into(),
6753        });
6754        let old = instruction_for(&t);
6755        assert!(compatible_instruction(&old, &t));
6756        t.instruction = "Reuse approved PR head and review".into();
6757        t.release_operator("cli", None);
6758        assert!(!compatible_instruction(&old, &t));
6759        let approved = instruction_for(&t);
6760        assert!(approved.contains("waiting premises are superseded"));
6761        assert!(compatible_instruction(&approved, &t));
6762        assert_eq!(resumed_instruction(&approved, &t), approved);
6763        t.release_operator("web", None);
6764        assert!(compatible_instruction(&approved, &t));
6765        assert_eq!(t.resumption_history.len(), 1);
6766        t.start("run".into());
6767        assert!(instruction_for(&t).contains("Explicit operator resumption"));
6768    }
6769
6770    /// A run that stopped on an infrastructure wait asked no agent anything:
6771    /// the task is held by the machine under a `[resource]` reason (resumable,
6772    /// re-checked by triage), and the attempt it started is given back.
6773    #[test]
6774    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6775        let mut state = RunState::new(
6776            PathBuf::from("/repo"),
6777            "main".into(),
6778            "base".into(),
6779            "task".into(),
6780            Config::default(),
6781        );
6782        state.status = RunStatus::Landing;
6783        state.parked = true;
6784        state.pr_pushed_head = Some("head".into());
6785        state.land_unrelated = Some(
6786            serde_json::from_value(serde_json::json!({
6787                "head": "head", "question": "ci-question",
6788                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6789            }))
6790            .unwrap(),
6791        );
6792        let mut t = task();
6793        t.start(state.id.clone());
6794        let verdict = Verdict {
6795            status: RunStatus::Landing,
6796            left_pr: true,
6797            quota_hit: false,
6798            parked: true,
6799            no_viable_candidates: false,
6800        };
6801        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6802        assert_eq!(t.attempts, 0);
6803        assert_eq!(t.status, TaskStatus::Held);
6804        assert!(!t.operator_held());
6805        assert!(
6806            t.hold_reason
6807                .as_deref()
6808                .unwrap()
6809                .starts_with("[ci-unrelated]")
6810        );
6811        // A second settlement must not refund an earlier task attempt.
6812        t.attempts = 1;
6813        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6814        assert_eq!(t.attempts, 1);
6815        assert_eq!(t.passes.len(), 1);
6816        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6817        state.pr_pushed_head = Some("new-head".into());
6818        state.parked = false;
6819        state.status = RunStatus::Blocked;
6820        let stale = Verdict {
6821            status: RunStatus::Blocked,
6822            parked: false,
6823            ..verdict
6824        };
6825        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6826        assert_eq!(t.attempts, 1);
6827        // A new execution pass can refund its own newly charged attempt.
6828        state.begin_pass();
6829        state.begin_pass();
6830        state.status = RunStatus::Landing;
6831        state.parked = true;
6832        state.pr_pushed_head = Some("head".into());
6833        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6834        assert_eq!(t.attempts, 0);
6835        assert_eq!(t.passes.len(), 2);
6836    }
6837
6838    #[test]
6839    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
6840        let mut state = RunState::new(
6841            PathBuf::from("/repo"),
6842            "main".to_owned(),
6843            "abc1234".to_owned(),
6844            "task".to_owned(),
6845            Config::default(),
6846        );
6847        state.status = RunStatus::Blocked;
6848        state.resource_block = Some(crate::run::ResourceBlock {
6849            cause: crate::run::ResourceBlockCause::Other,
6850            node: "graft".to_owned(),
6851            kind: "shared build cache".to_owned(),
6852            detail: "timed out".to_owned(),
6853            at: jiff::Timestamp::now(),
6854        });
6855        let mut t = task();
6856        t.start("20260902-000000-aaaa".to_owned());
6857        assert_eq!(t.attempts, 1);
6858        let verdict = Verdict {
6859            status: RunStatus::Blocked,
6860            left_pr: false,
6861            quota_hit: false,
6862            parked: false,
6863            no_viable_candidates: false,
6864        };
6865        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
6866        assert_eq!(t.status, TaskStatus::Held);
6867        assert_eq!(t.attempts, 0, "the attempt is refunded");
6868        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
6869        assert!(
6870            !t.operator_held(),
6871            "a machine hold, released without a human"
6872        );
6873
6874        let mut selected = task();
6875        selected.start("20260902-000000-cccc".into());
6876        selected.replacement = Some(crate::merge_decision::Replacement {
6877            question: "fixture".into(),
6878            run: "earlier".into(),
6879            pr: "https://example.invalid/pr/1".into(),
6880            agent: "selected".into(),
6881            context: "fixture".into(),
6882        });
6883        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
6884        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
6885        assert_eq!(selected.attempts, 0);
6886        assert!(
6887            !selected.operator_held(),
6888            "a selected agent also retains a machine resource hold"
6889        );
6890        assert!(
6891            selected
6892                .hold_reason
6893                .as_deref()
6894                .unwrap()
6895                .starts_with("[resource] ")
6896        );
6897
6898        // A park request outranks it: still the operator's doing.
6899        let mut p = task();
6900        p.start("20260902-000000-bbbb".to_owned());
6901        settle_and_diagnose(
6902            &mut p,
6903            Verdict {
6904                parked: true,
6905                ..verdict
6906            },
6907            "parked",
6908            2,
6909            &state,
6910        );
6911        assert_eq!(p.status, TaskStatus::Parked);
6912        assert_eq!(
6913            p.attempts, 0,
6914            "parking refunds once rather than also settling the resource hold"
6915        );
6916    }
6917
6918    #[test]
6919    fn record_failure_notice_links_the_task() {
6920        let dir = tempfile::tempdir().unwrap();
6921        // A regular file where the queue directory should be makes every
6922        // `put` fail, on every platform and whoever runs the test.
6923        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
6924        let queue = Queue::at(dir.path().join("queue"));
6925        let mut t = interrupt_task("rec-fail-1");
6926        record(&queue, &mut t);
6927
6928        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
6929        assert_eq!(found.len(), 1);
6930        assert_eq!(found[0].key, "loop:record");
6931        assert_eq!(
6932            found[0].link,
6933            Some(Link::Task {
6934                id: "rec-fail-1".to_owned()
6935            })
6936        );
6937    }
6938
6939    /// A runnable task marked to interrupt, with an id fixed for assertions
6940    /// rather than the random one [`Task::new`] mints.
6941    fn interrupt_task(id: &str) -> Task {
6942        let mut t = task();
6943        t.id = id.to_owned();
6944        t.interrupt = true;
6945        t
6946    }
6947
6948    /// An ordinary runnable task with an id fixed for assertions.
6949    fn task_with_id(id: &str) -> Task {
6950        let mut t = task();
6951        t.id = id.to_owned();
6952        t
6953    }
6954
6955    /// A runnable task marked `--urgent`, with an id fixed for assertions.
6956    fn urgent_task(id: &str) -> Task {
6957        let mut t = task();
6958        t.id = id.to_owned();
6959        t.urgent = true;
6960        t
6961    }
6962
6963    #[test]
6964    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
6965        let dir = tempfile::tempdir().unwrap();
6966        let queue = Queue::at(dir.path().join("queue"));
6967        let mut parked = task_with_id("parked");
6968        parked.start("run".into());
6969        parked.park("upgrade");
6970        parked.record_pass_at(
6971            "run",
6972            0,
6973            Some(Timestamp::now()),
6974            1,
6975            Some(crate::run::ParkCause::Upgrade {
6976                from: "old".into(),
6977                to: None,
6978            }),
6979        );
6980        let mut fresh = task_with_id("fresh");
6981        fresh.priority = 100;
6982        let mut urgent_task = urgent_task("urgent");
6983        for t in [&mut parked, &mut fresh, &mut urgent_task] {
6984            queue.put(t).unwrap();
6985        }
6986        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6987        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6988        let candidates = runnable(&queue);
6989        assert_eq!(candidates[0].id, parked.id);
6990        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
6991        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
6992        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
6993        drop(first);
6994        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
6995        let next = runnable(&queue)
6996            .into_iter()
6997            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
6998            .unwrap();
6999        assert_eq!(next.task.id, fresh.id);
7000        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7001        drop(claimed_elsewhere);
7002        drop(next);
7003        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7004    }
7005
7006    #[test]
7007    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7008        let dir = tempfile::tempdir().unwrap();
7009        let queue = Queue::at(dir.path().join("queue"));
7010        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7011        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7012        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7013        let mut first = task();
7014        queue.put(&mut first).unwrap();
7015        let stale_plain = queue.get(&first.id).unwrap();
7016        first.set_urgent(true).unwrap();
7017        queue.put(&mut first).unwrap();
7018        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7019        let mut second = urgent_task("second");
7020        queue.put(&mut second).unwrap();
7021        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7022        drop(queue.claim(&second.id).unwrap());
7023        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7024        drop(dispatched);
7025        let stale_urgent = queue.get(&first.id).unwrap();
7026        first.set_urgent(false).unwrap();
7027        queue.put(&mut first).unwrap();
7028        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7029        assert_eq!(urgent.available_permits(), 1);
7030        drop(queue.claim(&first.id).unwrap());
7031        drop(occupied);
7032    }
7033
7034    #[test]
7035    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7036        let dir = tempfile::tempdir().unwrap();
7037        let queue = Queue::at(dir.path().join("queue"));
7038        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7039        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7040        let mut t = task();
7041        queue.put(&mut t).unwrap();
7042        for enabled in [true, false] {
7043            let stale = queue.get(&t.id).unwrap();
7044            t.set_urgent(enabled).unwrap();
7045            queue.put(&mut t).unwrap();
7046            assert_ne!(stale.urgent, enabled);
7047            let DispatchClaim {
7048                task: fresh,
7049                claim,
7050                permit,
7051            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7052            assert_eq!(fresh.urgent, enabled);
7053            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7054            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7055            assert!(queue.claim(&t.id).is_err());
7056            assert_eq!(fresh.attempts, stale.attempts);
7057            drop((claim, permit));
7058            assert_eq!(ordinary.available_permits(), 1);
7059            assert_eq!(urgent.available_permits(), 1);
7060        }
7061        t.set_urgent(true).unwrap();
7062        queue.put(&mut t).unwrap();
7063        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7064        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7065        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7066        drop(queue.claim(&t.id).unwrap());
7067        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7068        drop(occupied);
7069        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7070        drop(queue.claim(&t.id).unwrap());
7071        let held = queue.claim(&t.id).unwrap();
7072        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7073        drop(held);
7074        t.status = TaskStatus::Held;
7075        queue.put(&mut t).unwrap();
7076        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7077        drop(queue.claim(&t.id).unwrap());
7078        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7079        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7080        drop(queue.claim(&t.id).unwrap());
7081        assert_eq!(urgent.available_permits(), 1);
7082    }
7083
7084    /// The land-resume exemption wins outright, whether or not the candidate
7085    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7086    /// queue behind anything" guarantee cannot be weaker just because the
7087    /// same task was also filed with `--urgent`.
7088    #[test]
7089    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7090        assert_eq!(permit_kind(true, false), PermitKind::None);
7091        assert_eq!(permit_kind(true, true), PermitKind::None);
7092    }
7093
7094    /// The one property this whole feature exists for: `--urgent` draws from
7095    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7096    /// ordinary candidate draws from the ordinary pool exactly as before,
7097    /// untouched by the urgent slot's existence.
7098    #[test]
7099    fn permit_kind_separates_urgent_from_ordinary() {
7100        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7101        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7102    }
7103
7104    /// The exact wiring `attempt` runs before minting anything: a config's
7105    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7106    /// Free space is injected rather than asked of the real disk - the point
7107    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7108    /// is deterministic on every machine this test runs on, never dependent
7109    /// on how full the CI runner's own disk happens to be.
7110    #[test]
7111    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7112        let cfg = Config::default();
7113        let repo = Path::new("/any/repo/path");
7114
7115        let reason =
7116            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7117        assert!(reason.contains("1024"), "{reason}");
7118        assert!(
7119            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7120            "{reason}"
7121        );
7122
7123        assert_eq!(
7124            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7125            None,
7126            "exactly at the floor is open"
7127        );
7128        assert_eq!(
7129            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7130            None,
7131            "comfortably above the floor is open"
7132        );
7133    }
7134
7135    #[test]
7136    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7137        let mut cfg = Config::default();
7138        cfg.disk.min_free_bytes = 0;
7139        let repo = Path::new("/any/repo/path");
7140        assert_eq!(
7141            disk_gate_with(repo, &cfg, |_| Ok(0)),
7142            None,
7143            "a zero floor never measures at all"
7144        );
7145    }
7146
7147    #[test]
7148    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7149        let cfg = Config::default();
7150        let repo = Path::new("/any/repo/path");
7151        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7152            .expect("a measurement failure must close the gate, not open it");
7153        assert!(reason.contains("could not measure"), "{reason}");
7154    }
7155
7156    #[test]
7157    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7158        let ordinary = task();
7159        let next = advance_interrupt(
7160            Interrupt::Idle,
7161            std::slice::from_ref(&ordinary.id),
7162            std::slice::from_ref(&ordinary),
7163        );
7164        assert_eq!(next, Interrupt::Idle);
7165    }
7166
7167    #[test]
7168    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7169        // Nothing to interrupt - this is just an ordinary candidate, and the
7170        // loop's normal dispatch will pick it up like any other.
7171        let marked = interrupt_task("marked");
7172        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7173        assert_eq!(next, Interrupt::Idle);
7174    }
7175
7176    #[test]
7177    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7178        let marked = interrupt_task("marked");
7179        let next = advance_interrupt(
7180            Interrupt::Idle,
7181            &["running".to_owned()],
7182            std::slice::from_ref(&marked),
7183        );
7184        assert_eq!(
7185            next,
7186            Interrupt::Parking {
7187                parked: vec!["running".to_owned()],
7188                interrupt_task: "marked".to_owned(),
7189            }
7190        );
7191    }
7192
7193    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7194    /// one run can be in flight when a task becomes runnable and marked.
7195    /// Parking all of them would mean `Resuming` later has more than one id
7196    /// to release back to ordinary dispatch, which cannot be made safe
7197    /// against that same setting's own extra concurrency slots letting two
7198    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7199    /// The simplification the task's own constraints ask for: do not begin
7200    /// a sequence at all until the herd settles back to exactly one.
7201    #[test]
7202    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7203        let marked = interrupt_task("marked");
7204
7205        let two = advance_interrupt(
7206            Interrupt::Idle,
7207            &["a".to_owned(), "b".to_owned()],
7208            std::slice::from_ref(&marked),
7209        );
7210        assert_eq!(two, Interrupt::Idle);
7211
7212        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7213        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7214    }
7215
7216    #[test]
7217    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7218        let state = Interrupt::Parking {
7219            parked: vec!["running".to_owned()],
7220            interrupt_task: "marked".to_owned(),
7221        };
7222        // Still in flight: no change.
7223        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7224        assert_eq!(still_going, state);
7225
7226        // Left flight, but the interrupt task has not been dispatched yet on
7227        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7228        // as long as it is still runnable.
7229        let stopped_but_not_yet_dispatched =
7230            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7231        assert_eq!(stopped_but_not_yet_dispatched, state);
7232
7233        // Left flight, and the interrupt task is now in flight itself.
7234        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7235        assert_eq!(
7236            dispatched,
7237            Interrupt::Running {
7238                parked: vec!["running".to_owned()],
7239                interrupt_task: "marked".to_owned(),
7240            }
7241        );
7242    }
7243
7244    #[test]
7245    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7246        let state = Interrupt::Running {
7247            parked: vec!["running".to_owned()],
7248            interrupt_task: "marked".to_owned(),
7249        };
7250        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7251        assert_eq!(still_running, state);
7252
7253        // Whatever it ended as - merged, failed, held - is not this
7254        // function's concern: leaving flight is the only trigger, driven
7255        // straight off the same in-flight list `poll` already reaps. It does
7256        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7257        // why that would let an unrelated task start ahead of, or alongside,
7258        // the guaranteed resume.
7259        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7260        assert_eq!(
7261            ended,
7262            Interrupt::Resuming {
7263                parked: vec!["running".to_owned()]
7264            }
7265        );
7266    }
7267
7268    #[test]
7269    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7270        let state = Interrupt::Resuming {
7271            parked: vec!["running".to_owned()],
7272        };
7273        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7274        assert_eq!(still_waiting, state);
7275
7276        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7277        assert_eq!(dispatched, Interrupt::Idle);
7278    }
7279
7280    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7281    /// or otherwise moved on by an operator with no claim standing in the
7282    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7283    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7284    /// come. The parked run still gets its resume.
7285    #[test]
7286    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7287    {
7288        let state = Interrupt::Parking {
7289            parked: vec!["running".to_owned()],
7290            interrupt_task: "marked".to_owned(),
7291        };
7292        // `marked` has been held/blocked/deleted since the sequence began:
7293        // it no longer appears in `runnable` at all.
7294        let next = advance_interrupt(state, &[], &[]);
7295        assert_eq!(
7296            next,
7297            Interrupt::Resuming {
7298                parked: vec!["running".to_owned()]
7299            },
7300            "abandoning the interrupt must not abandon the resume it owes"
7301        );
7302    }
7303
7304    /// The same abandonment, one step later: `Resuming` itself must not wait
7305    /// forever for a parked task that has since become unrunnable.
7306    #[test]
7307    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7308        let state = Interrupt::Resuming {
7309            parked: vec!["running".to_owned()],
7310        };
7311        let next = advance_interrupt(state, &[], &[]);
7312        assert_eq!(
7313            next,
7314            Interrupt::Idle,
7315            "nothing is left to wait for; the loop must not stay wedged"
7316        );
7317    }
7318
7319    #[test]
7320    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7321        let marked = interrupt_task("marked");
7322        let next = advance_interrupt_tick(
7323            false,
7324            Interrupt::Idle,
7325            &["running".to_owned()],
7326            std::slice::from_ref(&marked),
7327        );
7328        assert_eq!(
7329            next,
7330            Interrupt::Idle,
7331            "an unmarked, unconfigured daemon must behave exactly as before"
7332        );
7333    }
7334
7335    #[test]
7336    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7337        let state = Interrupt::Parking {
7338            parked: vec!["running".to_owned()],
7339            interrupt_task: "marked".to_owned(),
7340        };
7341        let candidates = vec![interrupt_task("marked"), task()];
7342        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7343        assert!(
7344            allowed.is_empty(),
7345            "nothing may dispatch - not even the interrupt task itself - \
7346             until the parked run has actually stopped"
7347        );
7348    }
7349
7350    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7351    /// grow a special case for it: an urgent candidate that is not the
7352    /// interrupt task withholds exactly like an ordinary one for as long as
7353    /// the parked run it is racing has not actually left flight. A version
7354    /// of this feature once bypassed the gate for urgent candidates, on the
7355    /// theory that a genuinely separate concurrency lane could not collide
7356    /// with 75dd's own; it could, and did - the bypassed task dispatched
7357    /// alongside a run 75dd's own state machine had only *asked* to park,
7358    /// not yet confirmed gone, which is exactly the second run
7359    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7360    /// tick during Parking/Running/Resuming where letting an extra
7361    /// candidate through is safe, urgent or not - the parked run may still
7362    /// be genuinely mid-call.
7363    #[test]
7364    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7365        for state in [
7366            Interrupt::Parking {
7367                parked: vec!["running".to_owned()],
7368                interrupt_task: "marked".to_owned(),
7369            },
7370            Interrupt::Running {
7371                parked: vec!["running".to_owned()],
7372                interrupt_task: "marked".to_owned(),
7373            },
7374            Interrupt::Resuming {
7375                parked: vec!["running".to_owned()],
7376            },
7377        ] {
7378            let candidates = vec![
7379                interrupt_task("marked"),
7380                urgent_task("hot"),
7381                task_with_id("ordinary"),
7382            ];
7383            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7384            assert!(
7385                !allowed.iter().any(|t| t.id == "hot"),
7386                "an urgent candidate must wait out the same gate as anything \
7387                 else while the run it would run alongside has not actually \
7388                 left flight, for state {state:?}: {allowed:?}"
7389            );
7390        }
7391    }
7392
7393    /// The one case where marking a task `--urgent` and `interrupt` at once
7394    /// is not redundant: once the interrupt sequence's own guaranteed
7395    /// resume/dispatch actually admits the task, it is unaffected by also
7396    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7397    /// never on the urgent flag.
7398    #[test]
7399    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7400        let state = Interrupt::Resuming {
7401            parked: vec!["hot".to_owned()],
7402        };
7403        let candidates = vec![urgent_task("hot"), task()];
7404        let allowed = interrupt_gate(&state, &[], candidates);
7405        assert_eq!(
7406            allowed.iter().filter(|t| t.id == "hot").count(),
7407            1,
7408            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7409        );
7410    }
7411
7412    #[test]
7413    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7414        let state = Interrupt::Parking {
7415            parked: vec!["running".to_owned()],
7416            interrupt_task: "marked".to_owned(),
7417        };
7418        let other = task();
7419        let candidates = vec![interrupt_task("marked"), other.clone()];
7420        let allowed = interrupt_gate(&state, &[], candidates);
7421        assert_eq!(allowed.len(), 1);
7422        assert_eq!(allowed[0].id, "marked");
7423    }
7424
7425    #[test]
7426    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7427        let state = Interrupt::Running {
7428            parked: vec!["running".to_owned()],
7429            interrupt_task: "marked".to_owned(),
7430        };
7431        let candidates = vec![task(), task()];
7432        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7433        assert!(allowed.is_empty());
7434    }
7435
7436    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7437    /// sequence began (only reachable above the default
7438    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7439    /// never both in the same tick, which is what "exactly one resume, no
7440    /// simultaneous run" actually requires structurally rather than by
7441    /// coincidence of how many ordinary slots happen to be free.
7442    #[test]
7443    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7444        let state = Interrupt::Resuming {
7445            parked: vec!["a".to_owned(), "c".to_owned()],
7446        };
7447        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7448        let allowed = interrupt_gate(&state, &[], candidates);
7449        assert_eq!(
7450            allowed.len(),
7451            1,
7452            "at most one candidate may be offered while resuming: {allowed:?}"
7453        );
7454        assert_eq!(allowed[0].id, "a");
7455    }
7456
7457    #[test]
7458    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7459        let state = Interrupt::Resuming {
7460            parked: vec!["a".to_owned()],
7461        };
7462        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7463        assert!(allowed.is_empty());
7464    }
7465
7466    /// The invariant the completion criteria ask for by name: across a whole
7467    /// simulated sequence, there is never a tick where the gate would let
7468    /// through both the parked run's resume and the interrupt task, and
7469    /// exactly one candidate resumes the instant the interrupt task's run
7470    /// ends - never zero, never more than one.
7471    #[test]
7472    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7473        let running = task(); // id: whatever `Task::new` minted
7474        let marked = interrupt_task("marked");
7475
7476        let mut state = Interrupt::Idle;
7477        // Tick 1: `running` is in flight, `marked` becomes runnable.
7478        let in_flight = vec![running.id.clone()];
7479        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7480        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7481        assert!(gated.is_empty(), "still waiting on `running` to park");
7482
7483        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7484        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7485        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7486        assert_eq!(
7487            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7488            vec!["marked"],
7489            "only the interrupt task may be offered to the dispatcher now"
7490        );
7491
7492        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7493        state = advance_interrupt_tick(
7494            true,
7495            state,
7496            &["marked".to_owned()],
7497            std::slice::from_ref(&running),
7498        );
7499        let gated = interrupt_gate(
7500            &state,
7501            &["marked".to_owned()],
7502            vec![marked.clone(), running.clone()],
7503        );
7504        assert!(
7505            gated.is_empty(),
7506            "the parked run must not be offered back while the interrupt \
7507             task is still running"
7508        );
7509
7510        // Tick 4: `marked`'s run reached a terminal status and left flight.
7511        // A higher-priority ordinary task `other` is also runnable now - it
7512        // must not be let through instead of, or alongside, `running`.
7513        let other = task_with_id("other");
7514        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7515        assert_eq!(
7516            state,
7517            Interrupt::Resuming {
7518                parked: vec![running.id.clone()]
7519            }
7520        );
7521        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7522        assert_eq!(
7523            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7524            vec![running.id.as_str()],
7525            "exactly the parked run resumes - not the unrelated task, even \
7526             though it was offered first"
7527        );
7528
7529        // Tick 5: `running` is now in flight (dispatched from tick 4's
7530        // gate). Only now does the sequence end and ordinary dispatch fully
7531        // resume.
7532        state = advance_interrupt_tick(
7533            true,
7534            state,
7535            std::slice::from_ref(&running.id),
7536            std::slice::from_ref(&other),
7537        );
7538        assert_eq!(state, Interrupt::Idle);
7539        let gated = interrupt_gate(
7540            &state,
7541            std::slice::from_ref(&running.id),
7542            vec![other.clone()],
7543        );
7544        assert_eq!(
7545            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7546            vec![other.id.as_str()],
7547            "ordinary dispatch is unrestricted again"
7548        );
7549    }
7550
7551    #[test]
7552    fn every_run_status_settles_the_task_it_came_from() {
7553        // run status, resulting task status, attempts still standing after one
7554        let table = [
7555            (RunStatus::Merged, TaskStatus::Done, 1),
7556            (RunStatus::Ready, TaskStatus::Done, 1),
7557            (RunStatus::Stalled, TaskStatus::Failed, 0),
7558            (RunStatus::Blocked, TaskStatus::Failed, 1),
7559            (RunStatus::Failed, TaskStatus::Failed, 1),
7560            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7561            (RunStatus::Prep, TaskStatus::Failed, 1),
7562            (RunStatus::Implementing, TaskStatus::Failed, 1),
7563            (RunStatus::Judging, TaskStatus::Failed, 1),
7564            (RunStatus::Deliberating, TaskStatus::Failed, 1),
7565            (RunStatus::Voting, TaskStatus::Failed, 1),
7566            (RunStatus::Reviewing, TaskStatus::Failed, 1),
7567            (RunStatus::Gating, TaskStatus::Failed, 1),
7568        ];
7569        for (run, want, attempts) in table {
7570            let mut t = task();
7571            t.start("20260902-000000-aaaa".to_owned());
7572            settle(
7573                &mut t,
7574                Verdict {
7575                    status: run,
7576                    left_pr: false,
7577                    parked: false,
7578                    quota_hit: matches!(run, RunStatus::Stalled),
7579                    no_viable_candidates: false,
7580                },
7581                "why",
7582                2,
7583            );
7584            assert_eq!(t.status, want, "task status after {}", label(run));
7585            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7586        }
7587    }
7588
7589    #[test]
7590    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7591        let mut stalled = task();
7592        stalled.start("20260902-000000-aaaa".to_owned());
7593        settle(
7594            &mut stalled,
7595            Verdict {
7596                status: RunStatus::Stalled,
7597                left_pr: false,
7598                parked: false,
7599                quota_hit: true,
7600                no_viable_candidates: false,
7601            },
7602            "quota",
7603            1,
7604        );
7605        assert_eq!(stalled.attempts, 0);
7606        assert!(
7607            stalled.status.runnable(),
7608            "a machine problem must leave the task in line"
7609        );
7610
7611        let mut blocked = task();
7612        blocked.start("20260902-000000-aaaa".to_owned());
7613        settle(
7614            &mut blocked,
7615            Verdict {
7616                status: RunStatus::Blocked,
7617                left_pr: false,
7618                parked: false,
7619                quota_hit: false,
7620                no_viable_candidates: false,
7621            },
7622            "findings open",
7623            1,
7624        );
7625        assert_eq!(blocked.attempts, 1);
7626        assert_eq!(
7627            blocked.status,
7628            TaskStatus::Held,
7629            "the last attempt hands the task to a human"
7630        );
7631    }
7632
7633    #[test]
7634    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7635        // Attempts to spare: without the pull request this task would go
7636        // straight back in line and run the whole competition again.
7637        let mut delivered = task();
7638        delivered.start("20260903-080619-01c2".to_owned());
7639        settle(
7640            &mut delivered,
7641            Verdict {
7642                status: RunStatus::Blocked,
7643                left_pr: true,
7644                parked: false,
7645                quota_hit: false,
7646                no_viable_candidates: false,
7647            },
7648            "no check status",
7649            4,
7650        );
7651        assert_eq!(
7652            delivered.status,
7653            TaskStatus::Held,
7654            "a pull request waiting on CI or a person is not a retryable failure"
7655        );
7656        assert!(
7657            !delivered.status.runnable(),
7658            "the loop must not pick this task up again"
7659        );
7660        assert_eq!(
7661            delivered.last_error.as_deref(),
7662            Some("no check status"),
7663            "the operator needs to be told what the gate was waiting for"
7664        );
7665
7666        // The same status without a pull request is a plain failure, and with
7667        // attempts left it is retried.
7668        let mut empty_handed = task();
7669        empty_handed.start("20260903-080619-01c2".to_owned());
7670        settle(
7671            &mut empty_handed,
7672            Verdict {
7673                status: RunStatus::Blocked,
7674                left_pr: false,
7675                parked: false,
7676                quota_hit: false,
7677                no_viable_candidates: false,
7678            },
7679            "findings open",
7680            4,
7681        );
7682        assert_eq!(empty_handed.status, TaskStatus::Failed);
7683        assert!(empty_handed.status.runnable());
7684    }
7685
7686    #[test]
7687    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7688        // Every candidate agreed, with evidence, that nothing belonged in the
7689        // worktree. That is not a confirmed success to close automatically -
7690        // a human still has to check the claim - and it is not an ordinary
7691        // failure either, so this settles exactly like a pull request nobody
7692        // merged yet: `Held`, same as `Blocked` with a PR.
7693        let mut noop = task();
7694        noop.start("20260912-131304-391f".to_owned());
7695        settle(
7696            &mut noop,
7697            Verdict {
7698                status: RunStatus::VerifiedNoop,
7699                left_pr: false,
7700                parked: false,
7701                quota_hit: false,
7702                no_viable_candidates: true,
7703            },
7704            "candidate A: already fixed by b32cfc4, on main",
7705            4,
7706        );
7707        assert_eq!(
7708            noop.status,
7709            TaskStatus::Held,
7710            "an unverified claim is a request for a human, not a failure"
7711        );
7712        assert!(
7713            !noop.status.runnable(),
7714            "the loop must not requeue this on the same unverified claim"
7715        );
7716        // `Task::release` resets attempts to zero the moment a human looks at
7717        // the evidence and lets it run again, so it does not matter here
7718        // whether the one attempt already spent stays spent - what matters is
7719        // that nothing retries this task unattended in the meantime.
7720        assert_eq!(noop.attempts, 1);
7721    }
7722
7723    #[test]
7724    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7725        // Parking is the operator asking for the process back - to replace the
7726        // binary, most of all. The run's work is intact on disk, so this is
7727        // not a failed attempt, and charging for it would mean a few upgrades
7728        // could exhaust a budget meant for agents that misbehaved.
7729        let mut parked = task();
7730        parked.start("20260903-183634-2d98".to_owned());
7731        settle(
7732            &mut parked,
7733            Verdict {
7734                status: RunStatus::Implementing,
7735                left_pr: false,
7736                quota_hit: false,
7737                parked: true,
7738                no_viable_candidates: false,
7739            },
7740            "parked after `implementing`",
7741            2,
7742        );
7743        assert_eq!(parked.attempts, 0, "a park is refunded");
7744        assert!(
7745            parked.status.runnable(),
7746            "and the task stays in line so the next loop resumes its run"
7747        );
7748        assert_eq!(parked.status, TaskStatus::Parked);
7749        assert_eq!(
7750            parked.park_reason.as_deref(),
7751            Some("parked after `implementing`"),
7752            "the card says where it stopped"
7753        );
7754        assert_eq!(parked.last_error, None, "nothing failed");
7755
7756        // Without the park flag the same non-terminal status is what it always
7757        // was: `execute` returning mid-flight, which is a bug and spends an
7758        // attempt so a task cannot loop on it forever.
7759        let mut broken = task();
7760        broken.start("20260903-183634-2d98".to_owned());
7761        settle(
7762            &mut broken,
7763            Verdict {
7764                status: RunStatus::Implementing,
7765                left_pr: false,
7766                quota_hit: false,
7767                parked: false,
7768                no_viable_candidates: false,
7769            },
7770            "returned mid-flight",
7771            2,
7772        );
7773        assert_eq!(broken.attempts, 1);
7774    }
7775
7776    #[test]
7777    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7778        // Run e633: quorum lost because two judges answered with the wrong
7779        // JSON shape, `quota: []`. Refunding that takes the bound off the
7780        // retry loop, and each retry pays for a fresh hour-long implement
7781        // wave before it can fail the same way.
7782        let mut flaky = task();
7783        flaky.start("20260903-123023-e633".to_owned());
7784        settle(
7785            &mut flaky,
7786            Verdict {
7787                status: RunStatus::Stalled,
7788                left_pr: false,
7789                parked: false,
7790                quota_hit: false,
7791                no_viable_candidates: false,
7792            },
7793            "verdict rests on 1 of 3 judges",
7794            2,
7795        );
7796        assert_eq!(
7797            flaky.attempts, 1,
7798            "flakiness spends an attempt, so `max_attempts` still bounds it"
7799        );
7800        assert!(flaky.status.runnable(), "and it is still worth retrying");
7801
7802        // The same status, lost to a rate limit, is the machine's fault.
7803        let mut limited = task();
7804        limited.start("20260903-123023-e633".to_owned());
7805        settle(
7806            &mut limited,
7807            Verdict {
7808                status: RunStatus::Stalled,
7809                left_pr: false,
7810                parked: false,
7811                quota_hit: true,
7812                no_viable_candidates: false,
7813            },
7814            "judge-2, judge-3 out of quota",
7815            2,
7816        );
7817        assert_eq!(limited.attempts, 0, "a quota window is refunded");
7818        assert!(limited.status.runnable());
7819
7820        // And the bound really binds: a task that keeps stalling on flakiness
7821        // reaches a human instead of running the roster forever.
7822        let mut worn = task();
7823        for _ in 0..2 {
7824            worn.release();
7825        }
7826        worn.start("20260903-123023-e633".to_owned());
7827        worn.attempts = 2;
7828        settle(
7829            &mut worn,
7830            Verdict {
7831                status: RunStatus::Stalled,
7832                left_pr: false,
7833                parked: false,
7834                quota_hit: false,
7835                no_viable_candidates: false,
7836            },
7837            "no quorum again",
7838            2,
7839        );
7840        assert_eq!(worn.status, TaskStatus::Held);
7841        assert!(!worn.status.runnable());
7842    }
7843
7844    #[test]
7845    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
7846        // The implement wave loses every seat to the same rate limit and
7847        // `after_implement` bails with nothing viable, which surfaces as
7848        // `Failed` rather than `Stalled`. That is the same machine fact the
7849        // `Stalled`-quota row already refunds, and must be refunded the same
7850        // way, or a quota outage quietly holds every task it touches instead
7851        // of leaving them in line for the reset.
7852        let mut wiped_out = task();
7853        wiped_out.start("20260907-025000-a1b2".to_owned());
7854        settle(
7855            &mut wiped_out,
7856            Verdict {
7857                status: RunStatus::Failed,
7858                left_pr: false,
7859                parked: false,
7860                quota_hit: true,
7861                no_viable_candidates: true,
7862            },
7863            "no candidate produced a change; nothing to judge",
7864            2,
7865        );
7866        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
7867        assert!(
7868            wiped_out.status.runnable(),
7869            "a machine problem must leave the task in line"
7870        );
7871
7872        // This is the exemption that must stay narrow: a candidate that did
7873        // produce a change, and then failed for some other reason, still
7874        // spends the attempt even though a seat elsewhere hit its quota.
7875        // Otherwise every ordinary failure that happens to share a run with
7876        // an unrelated rate limit would be refunded for free.
7877        let mut partial_progress = task();
7878        partial_progress.start("20260907-025500-c3d4".to_owned());
7879        settle(
7880            &mut partial_progress,
7881            Verdict {
7882                status: RunStatus::Failed,
7883                left_pr: false,
7884                parked: false,
7885                quota_hit: true,
7886                no_viable_candidates: false,
7887            },
7888            "gate failed on the winning candidate",
7889            2,
7890        );
7891        assert_eq!(
7892            partial_progress.attempts, 1,
7893            "a candidate that actually produced a change spends the attempt \
7894             even though some other seat hit its quota"
7895        );
7896        assert!(partial_progress.status.runnable());
7897    }
7898
7899    #[test]
7900    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
7901        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
7902        // disk, and that construction must reach the same conclusion as the
7903        // one `attempt` builds from a live run, or a crash at exactly the
7904        // wrong moment gives a recovered task a different policy than one a
7905        // daemon finished settling itself.
7906        let mut t = task();
7907        t.start("20260907-025000-a1b2".to_owned());
7908        let mut state = run_state(RunStatus::Failed);
7909        state.quota.push(QuotaLoss {
7910            seat: "cand-a".to_owned(),
7911            node: "implement".to_owned(),
7912            at: Timestamp::now(),
7913            reset: None,
7914        });
7915        assert!(
7916            state.viable().is_empty(),
7917            "no candidate was added, so nothing is viable"
7918        );
7919        reclaim(&mut t, Some(state), 2, "en");
7920        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
7921        assert!(t.status.runnable());
7922    }
7923
7924    #[test]
7925    fn a_held_task_is_never_offered_to_the_loop() {
7926        let dir = tempfile::tempdir().unwrap();
7927        let queue = Queue::at(dir.path().to_path_buf());
7928        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
7929            let mut t = task();
7930            t.id = format!("2026090{n}-000000-000{n}");
7931            t.priority = priority;
7932            queue.put(&mut t).unwrap();
7933        }
7934        let mut held = task();
7935        held.id = "20260909-000000-9999".to_owned();
7936        held.priority = 99;
7937        held.hold_machine(None);
7938        queue.put(&mut held).unwrap();
7939
7940        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
7941        assert_eq!(order.len(), 3);
7942        assert!(!order.contains(&held.id));
7943        assert_eq!(
7944            order.first().cloned(),
7945            queue.next_runnable().map(|t| t.id),
7946            "the loop's first candidate is exactly what the queue offers"
7947        );
7948        assert_eq!(
7949            order,
7950            vec![
7951                "20260902-000000-0002".to_owned(),
7952                "20260903-000000-0003".to_owned(),
7953                "20260901-000000-0001".to_owned(),
7954            ],
7955            "priority first, then oldest, so nothing starves"
7956        );
7957    }
7958
7959    #[test]
7960    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
7961        let dir = tempfile::tempdir().unwrap();
7962        let queue = Queue::at(dir.path().to_path_buf());
7963        let mut old = task();
7964        old.id = "20260101-000000-old0".to_owned();
7965        queue.put(&mut old).unwrap();
7966        let mut fresh = task();
7967        fresh.id = "20260101-000000-new0".to_owned();
7968        queue.put(&mut fresh).unwrap();
7969
7970        // No parseable pid at all, so age is the only signal there is to
7971        // check - unlike a real `Queue::claim`, which always names a real,
7972        // and therefore alive, pid this test cannot fake as dead.
7973        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
7974        std::thread::sleep(Duration::from_millis(60));
7975        let live = queue.claim(&fresh.id).unwrap();
7976
7977        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7978        assert_eq!(swept, vec![old.id.clone()]);
7979        assert!(
7980            queue.claim(&old.id).is_ok(),
7981            "an unparseable lock older than the threshold is swept"
7982        );
7983        assert!(
7984            queue.claim(&fresh.id).is_err(),
7985            "a live pid protects its lock regardless of age"
7986        );
7987        drop(live);
7988    }
7989
7990    #[test]
7991    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
7992        // A live worker's claim remains authoritative even beyond the sweep's
7993        // age limit. Sweeping it would permit a second competing attempt.
7994        let dir = tempfile::tempdir().unwrap();
7995        let queue = Queue::at(dir.path().to_path_buf());
7996        let mut t = task();
7997        t.id = "20260101-000000-live".to_owned();
7998        queue.put(&mut t).unwrap();
7999
8000        let claim = queue.claim(&t.id).unwrap();
8001        std::thread::sleep(Duration::from_millis(60));
8002
8003        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8004        assert!(
8005            swept.is_empty(),
8006            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8007        );
8008        assert!(
8009            queue.claim(&t.id).is_err(),
8010            "the lock still protects its task"
8011        );
8012        drop(claim);
8013    }
8014
8015    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8016    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8017    fn injected_dead_pid() -> u32 {
8018        std::process::id().checked_add(1).unwrap_or(1)
8019    }
8020
8021    #[test]
8022    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8023        let dir = tempfile::tempdir().unwrap();
8024        let queue = Queue::at(dir.path().to_path_buf());
8025        let mut t = task();
8026        t.id = "20260101-000000-dead".to_owned();
8027        queue.put(&mut t).unwrap();
8028        let dead_pid = injected_dead_pid();
8029
8030        // Written directly rather than through `Queue::claim`, which would
8031        // stamp this test process's own very much alive pid and defeat the
8032        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8033        // like moments after it died, not six hours later.
8034        std::fs::write(
8035            dir.path().join(format!("{}.lock", t.id)),
8036            dead_pid.to_string(),
8037        )
8038        .unwrap();
8039
8040        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8041            pid != dead_pid
8042        });
8043        assert_eq!(
8044            swept,
8045            vec![t.id.clone()],
8046            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8047        );
8048        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8049    }
8050
8051    #[test]
8052    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8053        let dir = tempfile::tempdir().unwrap();
8054        let queue = Queue::at(dir.path().to_path_buf());
8055        let mut t = task();
8056        t.id = "20260101-000000-late".to_owned();
8057        queue.put(&mut t).unwrap();
8058        let dead_pid = injected_dead_pid();
8059
8060        // Tick one, standing in for the sweep `poll` already runs at
8061        // startup: nothing to find yet.
8062        assert!(
8063            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8064            "nothing has claimed the task yet"
8065        );
8066
8067        // A second daemon claims the task and dies before it ever writes
8068        // `running`, well after this loop's own startup sweep already ran.
8069        std::fs::write(
8070            dir.path().join(format!("{}.lock", t.id)),
8071            dead_pid.to_string(),
8072        )
8073        .unwrap();
8074
8075        // Tick two, standing in for a poll long into this daemon's uptime:
8076        // the same function, called again, notices what only just appeared -
8077        // proving the sweep is not a one-shot startup check.
8078        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8079            pid != dead_pid
8080        });
8081        assert_eq!(swept, vec![t.id.clone()]);
8082    }
8083
8084    #[test]
8085    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8086        // `reclaim_orphaned_running` looks up the task's last run, which
8087        // touches `run::home()`; the first call anywhere in this binary wins,
8088        // so this is a no-op if another test already pinned one, and either
8089        // way the run id below is never written under it.
8090        crate::run::pin_test_home();
8091        let dir = tempfile::tempdir().unwrap();
8092        let queue = Queue::at(dir.path().to_path_buf());
8093        let mut t = task();
8094        t.id = "20260101-000000-crsh".to_owned();
8095        t.status = TaskStatus::Running;
8096        t.attempts = 1;
8097        // No `run.json` behind this id: standing in for a run this test does
8098        // not need to make readable, since the point is the lock, not the
8099        // recovery table `reclaim` already has its own tests for.
8100        t.runs.push("20260904-000000-4043".to_owned());
8101        queue.put(&mut t).unwrap();
8102        let dead_pid = injected_dead_pid();
8103
8104        // The crashed daemon's own claim, naming a pid nothing on the
8105        // machine holds anymore.
8106        std::fs::write(
8107            dir.path().join(format!("{}.lock", t.id)),
8108            dead_pid.to_string(),
8109        )
8110        .unwrap();
8111
8112        // Before the lock is swept the task looks claimed, and
8113        // `reclaim_orphaned_running` must leave it alone - this is exactly
8114        // the bug: a `running` task stranded behind a dead daemon's lock,
8115        // invisible to the claim-as-proof check because the lock outlived
8116        // the process that wrote it.
8117        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8118        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8119
8120        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8121            pid != dead_pid
8122        });
8123        assert_eq!(swept, vec![t.id.clone()]);
8124
8125        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8126        assert_eq!(reclaimed, vec![t.id.clone()]);
8127        let after = queue.get(&t.id).unwrap();
8128        assert_eq!(
8129            after.status,
8130            TaskStatus::Held,
8131            "no run.json to recover from, so a human is asked"
8132        );
8133        assert_eq!(
8134            after.runs,
8135            vec!["20260904-000000-4043".to_owned()],
8136            "the crashed run's id is kept as evidence, not discarded"
8137        );
8138    }
8139
8140    #[test]
8141    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8142        let dir = tempfile::tempdir().unwrap();
8143        let queue = Queue::at(dir.path().to_path_buf());
8144        let mut t = task();
8145        t.id = "20260101-000000-unknown".to_owned();
8146        queue.put(&mut t).unwrap();
8147        let dead_pid = injected_dead_pid();
8148        std::fs::write(
8149            dir.path().join(format!("{}.lock", t.id)),
8150            dead_pid.to_string(),
8151        )
8152        .unwrap();
8153
8154        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8155        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8156        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8157    }
8158
8159    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8160        let mut s = run_state(status);
8161        s.config.graph.language = language.to_owned();
8162        s
8163    }
8164
8165    fn unstarted_verdict(status: RunStatus) -> Verdict {
8166        Verdict {
8167            status,
8168            left_pr: false,
8169            quota_hit: false,
8170            parked: false,
8171            no_viable_candidates: false,
8172        }
8173    }
8174
8175    #[test]
8176    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8177        let mut t = task();
8178        t.attempts = 1;
8179        settle_in(
8180            &mut t,
8181            unstarted_verdict(RunStatus::AlreadyInBase),
8182            "already in main",
8183            1,
8184            phrases("en"),
8185        );
8186        assert_eq!(t.status, TaskStatus::Done);
8187        assert_eq!(t.attempts, 0);
8188    }
8189
8190    #[test]
8191    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8192        let reason = |language: &str| {
8193            let mut t = task();
8194            settle_in(
8195                &mut t,
8196                unstarted_verdict(RunStatus::Judging),
8197                "boom",
8198                1,
8199                phrases(language),
8200            );
8201            t.last_error.or(t.hold_reason).unwrap_or_default()
8202        };
8203        assert!(
8204            reason("en").starts_with("the graph stopped at `"),
8205            "{}",
8206            reason("en")
8207        );
8208        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8209        assert!(reason("日本語").contains("boom"));
8210        assert_eq!(reason("fr"), reason("en"));
8211    }
8212
8213    #[test]
8214    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8215        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8216        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8217        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8218        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8219        assert!(ja.contains("[run "), "{ja}");
8220        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8221        assert!(ended.starts_with("run 終了: "), "{ended}");
8222        let mut de = run_state_in(RunStatus::Failed, "de");
8223        let mut en = run_state_in(RunStatus::Failed, "en");
8224        de.id = "same".to_owned();
8225        en.id = "same".to_owned();
8226        assert_eq!(describe(&de), describe(&en));
8227    }
8228
8229    #[test]
8230    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8231        use crate::handover::Refused;
8232        let cases = [
8233            Refused::Foreign {
8234                branch: "b".into(),
8235                path: "/w/x".into(),
8236                why: "made by hand".into(),
8237            },
8238            Refused::Unsafe {
8239                branch: "b".into(),
8240                path: "/w/x".into(),
8241                why: "its worktree has uncommitted changes (a.rs)".into(),
8242            },
8243            Refused::ReleaseFailed {
8244                branch: "b".into(),
8245                path: "/w/x".into(),
8246                run: "ab12".into(),
8247            },
8248        ];
8249        for r in &cases {
8250            let en = (phrases("en").handover_refused)(r);
8251            assert_eq!(en, r.to_string());
8252            let ja = (phrases("ja").handover_refused)(r);
8253            assert!(
8254                !ja.contains("is checked out") && !ja.contains("try again"),
8255                "{ja}"
8256            );
8257            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8258            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8259                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8260            }
8261        }
8262        assert!(phrases("en").handover_hint.contains("release the task"));
8263        assert!(phrases("ja").handover_hint.contains("解放"));
8264    }
8265
8266    #[test]
8267    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8268        let build = |lang: &str| {
8269            let mut s = run_state_in(RunStatus::Blocked, lang);
8270            s.id = "same".to_owned();
8271            s.config.graph.review_rounds = 3;
8272            let mut r = review_round(3);
8273            r.expected = 3;
8274            r.answered = 1;
8275            s.reviews.push(r);
8276            s.event(
8277                "review",
8278                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8279            );
8280            s
8281        };
8282        let en = describe(&build("en"));
8283        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8284        let ja = describe(&build("ja"));
8285        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8286        assert!(!ja.contains("never answered"), "{ja}");
8287        assert!(ja.contains("[run "), "{ja}");
8288
8289        // An incomplete panel whose verification failed is a different stop:
8290        // the real event must survive in ja too.
8291        let mut failed = build("ja");
8292        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8293            command: "cargo test".to_owned(),
8294            code: Some(1),
8295            output_tail: String::new(),
8296            duration_ms: 0,
8297            resource_blocked: false,
8298        });
8299        failed.event("review", "stopped; e2e failed: cargo test");
8300        let ja = describe(&failed);
8301        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8302        assert!(!ja.contains("席のレビュアー"), "{ja}");
8303    }
8304
8305    #[test]
8306    fn refusals_and_recovery_prose_follow_the_language() {
8307        let t = held_task_with("r1");
8308        let q = action_question(
8309            "r1",
8310            ask::ChoiceAction::Resume {
8311                run: "r1".to_owned(),
8312            },
8313        );
8314        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
8315            ActionDecision::Refuse(s) => s,
8316            other => panic!("{other:?}"),
8317        };
8318        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8319        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8320        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8321
8322        let mut held = task();
8323        reclaim(&mut held, None, 2, "ja");
8324        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8325        let mut held = task();
8326        reclaim(&mut held, None, 2, "xx");
8327        assert!(held.hold_reason.unwrap().contains("held for a human"));
8328    }
8329
8330    fn run_state(status: RunStatus) -> RunState {
8331        let mut state = RunState::new(
8332            PathBuf::from("/repo"),
8333            "main".to_owned(),
8334            "abc1234def".to_owned(),
8335            "add retries".to_owned(),
8336            Config::default(),
8337        );
8338        state.status = status;
8339        state
8340    }
8341
8342    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8343        Candidate {
8344            index: 0,
8345            label,
8346            agent: "claude".to_owned(),
8347            branch: format!("magi/x/{label}"),
8348            worktree: PathBuf::from("/repo"),
8349            summary: summary.to_owned(),
8350            stat: String::new(),
8351            files: 0,
8352            commits: usize::from(!empty),
8353            empty,
8354            failed: failed.map(str::to_owned),
8355            verified_noop: None,
8356            duration_ms: 0,
8357            folded: false,
8358        }
8359    }
8360
8361    #[test]
8362    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8363        let mut state = run_state(RunStatus::Blocked);
8364        state.gate = vec![
8365            CommandOutcome {
8366                command: "cargo make check".to_owned(),
8367                code: Some(0),
8368                output_tail: "ok".to_owned(),
8369                duration_ms: 0,
8370                resource_blocked: false,
8371            },
8372            CommandOutcome {
8373                command: "cargo test".to_owned(),
8374                code: Some(101),
8375                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8376                duration_ms: 0,
8377                resource_blocked: false,
8378            },
8379        ];
8380        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8381        assert!(d.contains("cargo test"), "{d}");
8382        assert!(
8383            !d.contains("cargo make check"),
8384            "a passing check is not a diagnostic: {d}"
8385        );
8386        assert!(d.contains("assertion failed"), "{d}");
8387    }
8388
8389    #[test]
8390    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8391        let mut state = run_state(RunStatus::Blocked);
8392        state.event(
8393            "land",
8394            "stopped: the fixer produced no commit while 2 check(s) were failing \
8395             (build, lint); stopping instead of looping on an unchanged tree",
8396        );
8397        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8398        assert!(d.contains("build"), "{d}");
8399        assert!(d.contains("lint"), "{d}");
8400        assert!(d.contains("fixer produced no commit"), "{d}");
8401    }
8402
8403    #[test]
8404    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8405        // `describe`'s output becomes `Task::last_error` verbatim, and the
8406        // phone renders that in the same alarm-styled box an ordinary
8407        // failure gets. A bare `verified_noop` there would read exactly like
8408        // the failure this status exists to be told apart from.
8409        let state = run_state(RunStatus::VerifiedNoop);
8410        let d = describe(&state);
8411        assert!(
8412            d.contains("agent-verified no-op"),
8413            "expected the display label, not the wire spelling: {d}"
8414        );
8415        assert!(!d.contains("verified_noop"), "{d}");
8416    }
8417
8418    #[test]
8419    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8420        // The whole point of the feature: a run held as "no candidate produced
8421        // a change" can mean the implementer actually finished the task and
8422        // only left a clean local tree behind - see AGENTS.md on this exact
8423        // failure mode. The diagnostic has to carry what the agent actually
8424        // said, not just the fact that nothing was there to judge.
8425        let mut state = run_state(RunStatus::Failed);
8426        state.candidates = vec![candidate(
8427            'A',
8428            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8429            true,
8430            None,
8431        )];
8432        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8433        assert!(d.contains("candidate A"), "{d}");
8434        assert!(d.contains("tagged v1.2.3"), "{d}");
8435    }
8436
8437    #[test]
8438    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8439        let mut state = run_state(RunStatus::Failed);
8440        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8441        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8442        assert!(d.contains("candidate A"), "{d}");
8443        assert!(d.contains("agent timed out"), "{d}");
8444    }
8445
8446    #[test]
8447    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8448        // A viable candidate existed, the gate never ran, and nothing land
8449        // said matches - `Task::last_error` is left to explain this one alone.
8450        let mut state = run_state(RunStatus::Failed);
8451        state.candidates = vec![candidate('A', "did the work", false, None)];
8452        assert!(diagnostic(&state).is_none());
8453    }
8454
8455    #[test]
8456    fn diagnostic_is_bounded_however_much_a_run_printed() {
8457        let mut state = run_state(RunStatus::Blocked);
8458        state.gate = vec![
8459            CommandOutcome {
8460                command: "cargo test".to_owned(),
8461                code: Some(101),
8462                output_tail: "x".repeat(50_000),
8463                duration_ms: 0,
8464                resource_blocked: false,
8465            },
8466            CommandOutcome {
8467                command: "cargo clippy".to_owned(),
8468                code: Some(1),
8469                output_tail: "y".repeat(50_000),
8470                duration_ms: 0,
8471                resource_blocked: false,
8472            },
8473        ];
8474        state.candidates = vec![
8475            candidate('A', &"z".repeat(50_000), true, None),
8476            candidate('B', &"w".repeat(50_000), true, None),
8477        ];
8478        let d = diagnostic(&state).expect("plenty here to diagnose");
8479        assert!(
8480            d.len() <= DIAGNOSTIC_MAX,
8481            "diagnostic grew to {} bytes, unbounded",
8482            d.len()
8483        );
8484    }
8485
8486    #[test]
8487    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8488        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8489            let mut t = task();
8490            let mut state = run_state(status);
8491            t.pr_recovery = Some(crate::pr_recovery::Selection {
8492                url: "url".into(),
8493                branch: format!("magi/task-{}", t.id),
8494                head: "a".repeat(40),
8495                source_head: None,
8496                source_run: None,
8497                source_proof: None,
8498                disposition: Some(crate::pr_recovery::Disposition::Land),
8499                instruction: t.instruction.clone(),
8500                approved_at: Timestamp::now(),
8501            });
8502            state.pr_recovery = t.pr_recovery.clone();
8503            t.start(state.id.clone());
8504            settle_and_diagnose(
8505                &mut t,
8506                Verdict {
8507                    status,
8508                    left_pr: false,
8509                    quota_hit: false,
8510                    parked: false,
8511                    no_viable_candidates: false,
8512                },
8513                "delivery stopped",
8514                5,
8515                &state,
8516            );
8517            assert_eq!(t.status, TaskStatus::Held);
8518            let reason = t.hold_reason.as_deref().unwrap();
8519            if status == RunStatus::Ready {
8520                assert!(reason.contains("Selected PR delivery is incomplete"));
8521                assert!(t.recovery_budget.is_none());
8522            } else {
8523                assert!(reason.contains("Selected recovery stopped"));
8524                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8525            }
8526            assert!(t.pr_recovery.is_some());
8527        }
8528    }
8529
8530    #[test]
8531    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8532        let mut state = run_state(RunStatus::Blocked);
8533        state.gate = vec![CommandOutcome {
8534            command: "cargo test".to_owned(),
8535            code: Some(101),
8536            output_tail: "assertion failed".to_owned(),
8537            duration_ms: 0,
8538            resource_blocked: false,
8539        }];
8540        let verdict = Verdict {
8541            status: RunStatus::Blocked,
8542            left_pr: false,
8543            quota_hit: false,
8544            parked: false,
8545            no_viable_candidates: false,
8546        };
8547
8548        // Attempt one of two still has a retry coming: no diagnostic yet, the
8549        // task is going to run again and this run's evidence would go stale.
8550        let mut t = task();
8551        t.start("run-1".to_owned());
8552        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8553        assert_eq!(t.status, TaskStatus::Failed);
8554        assert!(t.diagnostic.is_none());
8555
8556        // Attempt two exhausts the budget: now it is held, and the
8557        // diagnostic is what `magi task show` has to say more than one line.
8558        t.start("run-2".to_owned());
8559        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8560        assert_eq!(t.status, TaskStatus::Held);
8561        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8562        assert!(d.contains("cargo test"), "{d}");
8563    }
8564
8565    #[test]
8566    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8567        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8568        // `magi ask` question settled Held with `hold_reason: null`, so the
8569        // notification said nothing actionable. `note_open_question` should
8570        // append the question id to whatever `handed_off` already wrote.
8571        crate::run::pin_test_home();
8572        let home = crate::run::home();
8573        let state = run_state(RunStatus::VerifiedNoop);
8574        let mut q = ask::Question::new(
8575            state.id.clone(),
8576            "implement".to_owned(),
8577            "impl-A".to_owned(),
8578            "is this really a no-op?".to_owned(),
8579            String::new(),
8580            Vec::new(),
8581        );
8582        Questions::at(home.join("questions")).put(&mut q).unwrap();
8583
8584        let verdict = Verdict {
8585            status: RunStatus::VerifiedNoop,
8586            left_pr: false,
8587            quota_hit: false,
8588            parked: false,
8589            no_viable_candidates: false,
8590        };
8591        let mut t = task();
8592        t.start(state.id.clone());
8593        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8594
8595        assert_eq!(t.status, TaskStatus::Held);
8596        let reason = t.hold_reason.expect("a held task must record why");
8597        assert!(
8598            reason.starts_with("run ended agent-verified no-op"),
8599            "the original settle reason must survive unchanged: {reason}"
8600        );
8601        assert!(
8602            reason.contains(q.short()),
8603            "the open question's id must be named so the notice is actionable: {reason}"
8604        );
8605    }
8606
8607    #[test]
8608    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8609        crate::run::pin_test_home();
8610        let state = run_state(RunStatus::VerifiedNoop);
8611
8612        let verdict = Verdict {
8613            status: RunStatus::VerifiedNoop,
8614            left_pr: false,
8615            quota_hit: false,
8616            parked: false,
8617            no_viable_candidates: false,
8618        };
8619        let mut t = task();
8620        t.start(state.id.clone());
8621        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8622
8623        assert_eq!(t.status, TaskStatus::Held);
8624        assert_eq!(
8625            t.hold_reason.as_deref(),
8626            Some("run ended agent-verified no-op"),
8627            "nothing to append when the question was already answered or never asked"
8628        );
8629    }
8630
8631    #[test]
8632    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8633        crate::run::pin_test_home();
8634        let mut first = run_state(RunStatus::Blocked);
8635        first.id = "20260101-000000-sup1".to_owned();
8636        first.save().unwrap();
8637        let mut second = run_state(RunStatus::Merged);
8638        second.id = "20260101-000000-sup2".to_owned();
8639        second.save().unwrap();
8640
8641        let mut t = task();
8642        t.runs = vec![first.id.clone(), second.id.clone()];
8643        t.status = TaskStatus::Done;
8644
8645        supersede_prior_runs(&t, &crate::run::home());
8646
8647        assert_eq!(
8648            RunState::load(&first.id).unwrap().status,
8649            RunStatus::Superseded,
8650            "the first attempt's Blocked no longer needs anyone's attention"
8651        );
8652        assert_eq!(
8653            RunState::load(&second.id).unwrap().status,
8654            RunStatus::Merged,
8655            "the run that actually succeeded is left exactly as it was"
8656        );
8657    }
8658
8659    #[test]
8660    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8661        // `is_working_on` alone only proves a *daemon* claim; a `magi run
8662        // --resume` invoked by hand outside the daemon never touches
8663        // `daemon.json` at all, so it would look identical to a genuinely
8664        // idle run without also consulting `RunState::liveness`, which reads
8665        // this run's own recorded `driver_pid` instead.
8666        crate::run::pin_test_home();
8667        let mut first = run_state(RunStatus::Blocked);
8668        first.id = "20260101-000000-sup9".to_owned();
8669        // This test process's own pid: guaranteed alive without needing a
8670        // real second process or daemon.
8671        first.driver_pid = Some(std::process::id());
8672        first.driver_started_at = Some(
8673            crate::proc::process_started_at(std::process::id())
8674                .expect("this test process's own start time must be queryable"),
8675        );
8676        first.save().unwrap();
8677        let mut second = run_state(RunStatus::Merged);
8678        second.id = "20260101-000000-supa".to_owned();
8679        second.save().unwrap();
8680
8681        let mut t = task();
8682        t.runs = vec![first.id.clone(), second.id.clone()];
8683        t.status = TaskStatus::Done;
8684
8685        supersede_prior_runs(&t, &crate::run::home());
8686
8687        assert_eq!(
8688            RunState::load(&first.id).unwrap().status,
8689            RunStatus::Blocked,
8690            "a live driver_pid means something is still actually working this run, \
8691             even though no daemon claims it - rewriting under it would just be \
8692             undone the next time that process saves"
8693        );
8694    }
8695
8696    #[test]
8697    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8698        // The first resweep must skip a still-live attempt exactly like
8699        // `supersede_prior_runs` itself does; a later resweep, once that
8700        // process is no longer actually driving it, is what closes the gap
8701        // `supersede_prior_runs` alone leaves - a task only ever reaches
8702        // `Done` once, so nothing else would ever look at this run again.
8703        let dir = tempfile::tempdir().unwrap();
8704        let home = dir.path().to_path_buf();
8705        let queue = Queue::at(dir.path().join("queue"));
8706
8707        let mut first = run_state(RunStatus::Blocked);
8708        first.id = "20260101-000000-supd".to_owned();
8709        first.driver_pid = Some(std::process::id());
8710        first.driver_started_at = Some(
8711            crate::proc::process_started_at(std::process::id())
8712                .expect("this test process's own start time must be queryable"),
8713        );
8714        first.save_under(&home).unwrap();
8715        let mut second = run_state(RunStatus::Merged);
8716        second.id = "20260101-000000-supe".to_owned();
8717        second.save_under(&home).unwrap();
8718
8719        let mut t = task();
8720        t.runs = vec![first.id.clone(), second.id.clone()];
8721        t.status = TaskStatus::Done;
8722        queue.put(&mut t).unwrap();
8723
8724        resweep_superseded_attempts(&queue, &home);
8725        assert_eq!(
8726            RunState::load_under(&first.id, &home).unwrap().status,
8727            RunStatus::Blocked,
8728            "still live on the first pass, so still untouched"
8729        );
8730
8731        // Stand in for the manual process no longer being the one driving
8732        // this run: same pid (this test process really is still alive), but
8733        // an identity marker that no longer matches it - see
8734        // `RunState::liveness`'s own doc for why a mismatched
8735        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
8736        let mut stale = RunState::load_under(&first.id, &home).unwrap();
8737        stale.driver_started_at = Some("1".to_owned());
8738        stale.save_under(&home).unwrap();
8739
8740        resweep_superseded_attempts(&queue, &home);
8741        assert_eq!(
8742            RunState::load_under(&first.id, &home).unwrap().status,
8743            RunStatus::Superseded,
8744            "the second pass catches up what the first one correctly skipped"
8745        );
8746    }
8747
8748    #[test]
8749    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8750        crate::run::pin_test_home();
8751        let mut first = run_state(RunStatus::Blocked);
8752        first.id = "20260101-000000-sup3".to_owned();
8753        first.save().unwrap();
8754        let mut second = run_state(RunStatus::Blocked);
8755        second.id = "20260101-000000-sup4".to_owned();
8756        second.save().unwrap();
8757
8758        let mut t = task();
8759        t.runs = vec![first.id.clone(), second.id.clone()];
8760        // Still retrying: nothing about this task's story is settled yet, so
8761        // neither Blocked run may be relabelled, even though a later attempt
8762        // already exists.
8763        t.status = TaskStatus::Failed;
8764
8765        supersede_prior_runs(&t, &crate::run::home());
8766
8767        assert_eq!(
8768            RunState::load(&first.id).unwrap().status,
8769            RunStatus::Blocked
8770        );
8771        assert_eq!(
8772            RunState::load(&second.id).unwrap().status,
8773            RunStatus::Blocked
8774        );
8775    }
8776
8777    #[test]
8778    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
8779        // `magi task done` (or the API's equivalent) can close a task with no
8780        // run of its own ever having succeeded - there is nothing here that
8781        // counts as "the attempt that finished it", so nothing is rewritten.
8782        crate::run::pin_test_home();
8783        let mut first = run_state(RunStatus::Blocked);
8784        first.id = "20260101-000000-sup5".to_owned();
8785        first.save().unwrap();
8786
8787        let mut t = task();
8788        t.runs = vec![first.id.clone()];
8789        t.status = TaskStatus::Done;
8790
8791        supersede_prior_runs(&t, &crate::run::home());
8792
8793        assert_eq!(
8794            RunState::load(&first.id).unwrap().status,
8795            RunStatus::Blocked,
8796            "a single-attempt task has no earlier run to supersede"
8797        );
8798    }
8799
8800    #[test]
8801    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
8802        // `magi task done` (or the web/conductor equivalents) can close a
8803        // task in any status, including one whose *last* recorded attempt is
8804        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
8805        // never watched, say. `runs.last()` being `Done`-adjacent is not
8806        // proof it actually succeeded, so nothing earlier may be relabelled
8807        // on its say-so alone.
8808        crate::run::pin_test_home();
8809        let mut first = run_state(RunStatus::Blocked);
8810        first.id = "20260101-000000-supb".to_owned();
8811        first.save().unwrap();
8812        let mut second = run_state(RunStatus::Failed);
8813        second.id = "20260101-000000-supc".to_owned();
8814        second.save().unwrap();
8815
8816        let mut t = task();
8817        t.runs = vec![first.id.clone(), second.id.clone()];
8818        t.status = TaskStatus::Done;
8819
8820        supersede_prior_runs(&t, &crate::run::home());
8821
8822        assert_eq!(
8823            RunState::load(&first.id).unwrap().status,
8824            RunStatus::Blocked,
8825            "the task's last attempt never landed, so there is nothing here \
8826             actually superseding it"
8827        );
8828    }
8829
8830    #[test]
8831    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
8832        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
8833        // to look" - `Failed` and `VerifiedNoop` are already their own
8834        // terminal answers and must not be relabelled into a third one.
8835        crate::run::pin_test_home();
8836        let mut failed = run_state(RunStatus::Failed);
8837        failed.id = "20260101-000000-sup6".to_owned();
8838        failed.save().unwrap();
8839        let mut noop = run_state(RunStatus::VerifiedNoop);
8840        noop.id = "20260101-000000-sup7".to_owned();
8841        noop.save().unwrap();
8842        let mut winner = run_state(RunStatus::Ready);
8843        winner.id = "20260101-000000-sup8".to_owned();
8844        winner.save().unwrap();
8845
8846        let mut t = task();
8847        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
8848        t.status = TaskStatus::Done;
8849
8850        supersede_prior_runs(&t, &crate::run::home());
8851
8852        assert_eq!(
8853            RunState::load(&failed.id).unwrap().status,
8854            RunStatus::Failed
8855        );
8856        assert_eq!(
8857            RunState::load(&noop.id).unwrap().status,
8858            RunStatus::VerifiedNoop
8859        );
8860    }
8861
8862    fn approval_question(run: &str) -> ask::Question {
8863        ask::Question::new(
8864            run.to_owned(),
8865            land::APPROVAL_NODE.to_owned(),
8866            "land".to_owned(),
8867            "merge?".to_owned(),
8868            String::new(),
8869            vec!["merge".to_owned(), "hold".to_owned()],
8870        )
8871    }
8872
8873    #[test]
8874    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
8875        crate::run::pin_test_home();
8876        let mut state = run_state(RunStatus::Landing);
8877        state.id = "20260101-000000-fre1".to_owned();
8878        state.parked = true;
8879        state.save().unwrap();
8880        ask::Questions::open()
8881            .put(&mut approval_question(&state.id))
8882            .unwrap();
8883
8884        let mut t = task();
8885        t.runs.push(state.id.clone());
8886        assert_eq!(
8887            land_resume_state(&t),
8888            LandResume::StillWaiting,
8889            "nobody has answered and the timeout has not passed"
8890        );
8891    }
8892
8893    #[test]
8894    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
8895        crate::run::pin_test_home();
8896        let mut state = run_state(RunStatus::Gating);
8897        state.id = "20260101-000000-gt01".to_owned();
8898        state.parked = true;
8899        state.config.graph.answer_timeout = 60;
8900        state.github_text = Some(crate::run::GithubTextAsk {
8901            rewrite: None,
8902            fingerprint: "f".into(),
8903            title: true,
8904            body: false,
8905            categories: vec!["title-language".into()],
8906            question: None,
8907            asks: 1,
8908            resolved: false,
8909            chosen_title: None,
8910            choice: None,
8911        });
8912        state.save().unwrap();
8913        let store = ask::Questions::open();
8914        let mut q = ask::Question::new(
8915            state.id.clone(),
8916            crate::github_text::ASK_NODE.to_owned(),
8917            crate::github_text::ASK_SEAT.to_owned(),
8918            "s".into(),
8919            String::new(),
8920            vec!["use fallback".into()],
8921        );
8922        store.put(&mut q).unwrap();
8923        let mut t = task();
8924        t.runs.push(state.id.clone());
8925        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
8926        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
8927        store.put(&mut q).unwrap();
8928        assert_eq!(land_resume_state(&t), LandResume::Ready);
8929        assert!(!store.get(&q.id).unwrap().status.open());
8930        // Once decided, a parked run is an ordinary candidate again.
8931        state.github_text.as_mut().unwrap().resolved = true;
8932        state.save().unwrap();
8933        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
8934    }
8935
8936    #[test]
8937    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
8938        // `ask::ask_and_wait`'s own deadline used to retire a question
8939        // nobody answered; land's approval bypasses that wait (see
8940        // `land::approval_gate`), so this is now the only place
8941        // `graph.answer_timeout` is enforced for a land approval at all.
8942        crate::run::pin_test_home();
8943        let mut state = run_state(RunStatus::Landing);
8944        state.id = "20260101-000000-exp1".to_owned();
8945        state.parked = true;
8946        state.config.graph.answer_timeout = 60;
8947        state.save().unwrap();
8948
8949        let store = ask::Questions::open();
8950        let mut q = approval_question(&state.id);
8951        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
8952        store.put(&mut q).unwrap();
8953
8954        let mut t = task();
8955        t.runs.push(state.id.clone());
8956        assert_eq!(
8957            land_resume_state(&t),
8958            LandResume::Ready,
8959            "an expired question must not be waited on forever"
8960        );
8961
8962        let after = store.get(&q.id).unwrap();
8963        assert!(
8964            !after.status.open(),
8965            "the question is abandoned, not silently ignored"
8966        );
8967        assert!(
8968            after.resolution().is_none(),
8969            "an abandoned question is not read as a decision"
8970        );
8971    }
8972
8973    #[test]
8974    fn reclaim_settles_a_running_task_against_its_last_run() {
8975        let mut t = task();
8976        t.start("20260904-000000-4043".to_owned());
8977        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
8978        assert_eq!(
8979            t.status,
8980            TaskStatus::Done,
8981            "a run that actually finished must not stay `running` forever"
8982        );
8983    }
8984
8985    #[test]
8986    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
8987        let mut t = task();
8988        t.start("20260904-000000-4043".to_owned());
8989        t.last_error = Some("earlier trouble".to_owned());
8990        let mut state = run_state(RunStatus::Judging);
8991        state.parked = true;
8992        reclaim(&mut t, Some(state), 1, "en");
8993        assert_eq!(t.status, TaskStatus::Parked);
8994        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
8995        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8996        assert!(t.park_reason.is_some());
8997        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
8998        assert!(!t.fresh_start);
8999        assert!(t.status.runnable());
9000    }
9001
9002    #[test]
9003    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9004        let mut t = task();
9005        t.start("20260904-000000-4043".to_owned());
9006        t.last_error = Some("earlier trouble".to_owned());
9007        settle(
9008            &mut t,
9009            Verdict {
9010                status: RunStatus::Judging,
9011                left_pr: false,
9012                quota_hit: false,
9013                parked: true,
9014                no_viable_candidates: false,
9015            },
9016            "parked after `judging`",
9017            1,
9018        );
9019        assert_eq!(t.status, TaskStatus::Parked);
9020        assert_eq!(t.attempts, 0);
9021        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9022        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9023        assert_eq!(t.schema, crate::queue::SCHEMA);
9024        assert!(
9025            crate::notices::task_held(&t).is_none(),
9026            "a park is not news"
9027        );
9028        t.start("20260904-000000-4043".to_owned());
9029        assert_eq!(t.park_reason, None);
9030    }
9031
9032    #[test]
9033    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9034        // A blocked run with attempts left goes back to `Failed`, exactly as
9035        // it would from `attempt` itself - `reclaim` must not invent a second
9036        // policy for a task a daemon merely stopped without reporting.
9037        let mut t = task();
9038        t.start("20260904-000000-4043".to_owned());
9039        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9040        assert_eq!(t.status, TaskStatus::Failed);
9041        assert!(t.status.runnable());
9042    }
9043
9044    #[test]
9045    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9046        let mut t = task();
9047        t.start("20260904-000000-4043".to_owned());
9048        assert_eq!(t.attempts, 1);
9049        let mut run = run_state(RunStatus::Implementing);
9050        run.id = "20260904-000000-4043".to_owned();
9051        run.begin_pass();
9052        let cause = crate::run::ParkCause::Upgrade {
9053            from: "0.121.0".to_owned(),
9054            to: Some("0.121.1".to_owned()),
9055        };
9056        run.end_pass_parked(cause.clone());
9057        run.parked = true;
9058        let verdict = Verdict {
9059            status: run.status,
9060            left_pr: false,
9061            quota_hit: false,
9062            parked: true,
9063            no_viable_candidates: false,
9064        };
9065        // A crash after the checkpoint but before queue settlement must
9066        // recover exactly the same scheduling evidence and refund.
9067        let mut orphan = t.clone();
9068        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9069        assert_eq!(orphan.status, TaskStatus::Parked);
9070        assert_eq!(orphan.attempts, 0);
9071        assert_eq!(
9072            orphan.upgrade_resume_key(),
9073            Some((run.passes[0].started_at, orphan.id.as_str()))
9074        );
9075        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9076        assert_eq!(t.attempts, 0);
9077        assert_eq!(t.passes.len(), 1);
9078        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9079        assert_eq!(t.passes[0].parked, Some(cause));
9080        assert_eq!(t.passes[0].pass_index, 0);
9081        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9082        assert!(t.upgrade_resume_key().is_some());
9083
9084        // A resumed pass that then fails spends its attempt, and the earlier
9085        // pass's entry is untouched.
9086        t.start("20260904-000000-4043".to_owned());
9087        run.begin_pass();
9088        run.status = RunStatus::Failed;
9089        let verdict = Verdict {
9090            status: RunStatus::Failed,
9091            left_pr: false,
9092            quota_hit: false,
9093            parked: false,
9094            no_viable_candidates: false,
9095        };
9096        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9097        assert_eq!(t.passes.len(), 2);
9098        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9099        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9100        assert_eq!(t.passes[1].pass_index, 1);
9101        assert_eq!(t.attempts, 1);
9102    }
9103
9104    #[test]
9105    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9106        let mut t = task();
9107        t.start("20260904-000000-4043".to_owned());
9108        reclaim(&mut t, None, 2, "en");
9109        assert_eq!(t.status, TaskStatus::Held);
9110        assert!(
9111            t.last_error
9112                .as_deref()
9113                .is_some_and(|e| e.contains("running")),
9114            "the operator needs to know why this task was held"
9115        );
9116    }
9117
9118    #[test]
9119    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9120        let dir = tempfile::tempdir().unwrap();
9121        let queue = Queue::at(dir.path().to_path_buf());
9122
9123        // No run recorded, so this never has to touch `RunState::load`.
9124        let mut orphaned = task();
9125        orphaned.id = "20260904-000000-orph".to_owned();
9126        orphaned.status = TaskStatus::Running;
9127        orphaned.attempts = 1;
9128        queue.put(&mut orphaned).unwrap();
9129
9130        let mut alive = task();
9131        alive.id = "20260904-000000-live".to_owned();
9132        alive.status = TaskStatus::Running;
9133        alive.attempts = 1;
9134        queue.put(&mut alive).unwrap();
9135        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9136
9137        let mut queued = task();
9138        queued.id = "20260904-000000-wait".to_owned();
9139        queue.put(&mut queued).unwrap();
9140
9141        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9142        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9143
9144        assert_eq!(
9145            queue.get(&orphaned.id).unwrap().status,
9146            TaskStatus::Held,
9147            "nothing was driving it and there was no run to recover"
9148        );
9149        assert_eq!(
9150            queue.get(&alive.id).unwrap().status,
9151            TaskStatus::Running,
9152            "a live claim must protect the task it belongs to"
9153        );
9154        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9155    }
9156
9157    /// Read a run.json back from an explicit `home`, the same way
9158    /// `reclaim_abandoned_runs` itself does - never through the
9159    /// process-global `RunState::load`, which this test's own `home` (an
9160    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9161    /// use at all.
9162    fn read_run_under(home: &Path, id: &str) -> RunState {
9163        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9164        serde_json::from_str(&body).unwrap()
9165    }
9166
9167    #[test]
9168    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9169        let dir = tempfile::tempdir().unwrap();
9170        let home = dir.path().to_path_buf();
9171        let now = Timestamp::now();
9172        let overrun_seat = || crate::run::ActiveSeat {
9173            node: "implement".to_owned(),
9174            started_at: now - jiff::SignedDuration::new(21_000, 0),
9175            timeout_secs: 3_600,
9176            attempt: 0,
9177            task: None,
9178            command: None,
9179            index: None,
9180            total: None,
9181        };
9182
9183        let mut dead = run_state(RunStatus::Implementing);
9184        dead.id = "20260101-000000-dead".to_owned();
9185        dead.active.insert("impl-A".to_owned(), overrun_seat());
9186        // A `driver_pid` the injected query below confirms gone outright —
9187        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9188        dead.driver_pid = Some(4242);
9189        dead.save_under(&home).unwrap();
9190
9191        // Same shape, but a live daemon's heartbeat names it: must be left
9192        // exactly alone, however far past its own timeout the seat sits.
9193        let mut alive = run_state(RunStatus::Implementing);
9194        alive.id = "20260101-000000-aliv".to_owned();
9195        alive.active.insert("impl-A".to_owned(), overrun_seat());
9196        alive.save_under(&home).unwrap();
9197        let mut status = Status::new();
9198        status.current = vec![Current {
9199            worker: None,
9200            task: "20260101-000000-task".to_owned(),
9201            run: alive.id.clone(),
9202        }];
9203        write_status_to(&home.join("daemon.json"), &status).unwrap();
9204
9205        // The abandoned seat left an open question behind: nobody is left to
9206        // read an answer once the run is failed, and this must not wait for
9207        // some later daemon startup's own sweep to notice that.
9208        let questions = Questions::at(home.join("questions"));
9209        let mut q = ask::Question::new(
9210            dead.id.clone(),
9211            "implement".to_owned(),
9212            "impl-A".to_owned(),
9213            "Which storage backend?".to_owned(),
9214            String::new(),
9215            vec!["SQLite".to_owned(), "Redis".to_owned()],
9216        );
9217        questions.put(&mut q).unwrap();
9218
9219        let abandoned = reclaim_abandoned_runs_with(
9220            &home,
9221            now,
9222            |pid| if pid == 4242 { Some(false) } else { None },
9223            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9224        );
9225        assert_eq!(abandoned, vec![dead.id.clone()]);
9226
9227        let reloaded = read_run_under(&home, &dead.id);
9228        assert_eq!(reloaded.status, RunStatus::Failed);
9229        assert!(reloaded.active.is_empty());
9230        assert!(
9231            !questions.get(&q.id).unwrap().status.open(),
9232            "the failed run's own open question must be settled in the same pass"
9233        );
9234
9235        let still_alive = read_run_under(&home, &alive.id);
9236        assert_eq!(
9237            still_alive.status,
9238            RunStatus::Implementing,
9239            "a live daemon's claim protects it"
9240        );
9241        assert!(!still_alive.active.is_empty());
9242    }
9243
9244    /// The exact shape a review round flagged as broken: `magi serve` running
9245    /// in this same `home` scans *every* run on disk, including a manual
9246    /// `magi review` / `magi run` this daemon never started and that
9247    /// therefore claims no heartbeat of its own. Before this scan asked
9248    /// `liveness` rather than just `is_working_on`, a manual run whose active
9249    /// seat merely ran a little past its own timeout — the CLI finishing up,
9250    /// its result still being collected — got wiped and failed by a daemon
9251    /// that had nothing to do with it, out from under a process that was
9252    /// still very much running.
9253    #[test]
9254    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9255        let dir = tempfile::tempdir().unwrap();
9256        let home = dir.path().to_path_buf();
9257        let now = Timestamp::now();
9258
9259        let mut manual = run_state(RunStatus::Reviewing);
9260        manual.id = "20260101-000000-manl".to_owned();
9261        manual.active.insert(
9262            "review-1".to_owned(),
9263            crate::run::ActiveSeat {
9264                node: "review".to_owned(),
9265                started_at: now - jiff::SignedDuration::new(21_000, 0),
9266                timeout_secs: 3_600,
9267                attempt: 0,
9268                task: None,
9269                command: None,
9270                index: None,
9271                total: None,
9272            },
9273        );
9274        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9275        // but a real, still-running process: `liveness` must corroborate this
9276        // as `Live`, not read the missing daemon claim as death.
9277        manual.driver_pid = Some(4242);
9278        manual.driver_started_at = Some("1790000000".to_owned());
9279        manual.save_under(&home).unwrap();
9280
9281        let abandoned = reclaim_abandoned_runs_with(
9282            &home,
9283            now,
9284            |pid| if pid == 4242 { Some(true) } else { None },
9285            |pid| {
9286                if pid == 4242 {
9287                    Some("1790000000".to_owned())
9288                } else {
9289                    None
9290                }
9291            },
9292        );
9293        assert!(
9294            abandoned.is_empty(),
9295            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9296        );
9297
9298        let reloaded = read_run_under(&home, &manual.id);
9299        assert_eq!(reloaded.status, RunStatus::Reviewing);
9300        assert!(!reloaded.active.is_empty());
9301    }
9302
9303    #[test]
9304    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9305        let dir = tempfile::tempdir().unwrap();
9306        let queue = Queue::at(dir.path().to_path_buf());
9307        let mut only = task();
9308        queue.put(&mut only).unwrap();
9309
9310        let _elsewhere = queue.claim(&only.id).unwrap();
9311        let candidates = runnable(&queue);
9312        assert_eq!(candidates.len(), 1, "the task is still runnable");
9313        assert!(
9314            queue.claim(&candidates[0].id).is_err(),
9315            "the loop cannot take a claim somebody else holds"
9316        );
9317
9318        let after = queue.get(&only.id).unwrap();
9319        assert_eq!(after.status, TaskStatus::Queued);
9320        assert_eq!(
9321            after.attempts, 0,
9322            "losing the race is not an attempt at the task"
9323        );
9324        assert_eq!(after.last_error, None);
9325    }
9326
9327    #[test]
9328    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9329        let dir = tempfile::tempdir().unwrap();
9330        let path = dir.path().join("daemon.json");
9331
9332        let mut status = Status::new();
9333        status.idle = false;
9334        status.completed = 7;
9335        status.current = vec![Current {
9336            worker: None,
9337            task: "20260902-000000-t111".to_owned(),
9338            run: "20260902-000001-r111".to_owned(),
9339        }];
9340        write_status_to(&path, &status).unwrap();
9341        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9342        assert_eq!(first.schema, SCHEMA);
9343        assert_eq!(first.pid, std::process::id());
9344        assert!(!first.idle);
9345        assert_eq!(first.completed, 7);
9346        assert_eq!(first.current, status.current);
9347        assert!(
9348            !path.with_extension("json.tmp").exists(),
9349            "the temp file is renamed, not left behind"
9350        );
9351
9352        std::thread::sleep(Duration::from_millis(5));
9353        status.updated_at = Timestamp::now();
9354        status.polls = 3;
9355        write_status_to(&path, &status).unwrap();
9356        let second: Status =
9357            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9358        assert!(
9359            second.updated_at > first.updated_at,
9360            "a reader can only detect staleness if the heartbeat moves"
9361        );
9362        assert_eq!(
9363            second.started_at, first.started_at,
9364            "the start time is not a heartbeat"
9365        );
9366        assert_eq!(second.polls, 3);
9367    }
9368
9369    #[test]
9370    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9371        let dir = tempfile::tempdir().unwrap();
9372
9373        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9374
9375        let mut status = Status::new();
9376        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9377        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9378        let stale = read_status(dir.path()).unwrap();
9379        assert!(
9380            !stale.running(Timestamp::now()),
9381            "a minute without a heartbeat is a dead daemon, not a busy one"
9382        );
9383        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9384
9385        status.updated_at = Timestamp::now();
9386        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9387        let fresh = read_status(dir.path()).unwrap();
9388        assert!(fresh.running(Timestamp::now()));
9389    }
9390
9391    #[test]
9392    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9393        let dir = tempfile::tempdir().unwrap();
9394        let now = Timestamp::now();
9395        let mine = "20260903-080619-01c2";
9396
9397        assert!(
9398            !is_working_on(dir.path(), mine, now),
9399            "no status file means nobody is working on anything"
9400        );
9401
9402        let mut status = Status::new();
9403        status.current = vec![Current {
9404            worker: None,
9405            task: "20260903-080340-0167".to_owned(),
9406            run: mine.to_owned(),
9407        }];
9408        status.updated_at = now;
9409        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9410        assert!(is_working_on(dir.path(), mine, now));
9411        assert!(
9412            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9413            "a daemon busy with one run is not working on another"
9414        );
9415
9416        // A killed daemon stops writing heartbeats but leaves the file behind
9417        // naming the run it died in. That run must not be undeletable forever.
9418        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9419        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9420        assert!(
9421            !is_working_on(dir.path(), mine, now),
9422            "a stale heartbeat is a dead daemon, so its run is a leftover"
9423        );
9424    }
9425
9426    #[test]
9427    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9428        let dir = tempfile::tempdir().unwrap();
9429        let now = Timestamp::now();
9430
9431        assert!(
9432            !is_working_on_short(dir.path(), "01c2", now),
9433            "no status file means nobody is working on anything"
9434        );
9435
9436        let mut status = Status::new();
9437        status.current = vec![Current {
9438            worker: None,
9439            task: "20260903-080340-0167".to_owned(),
9440            run: "20260903-080619-01c2".to_owned(),
9441        }];
9442        status.updated_at = now;
9443        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9444        assert!(
9445            is_working_on_short(dir.path(), "01c2", now),
9446            "the run's short id is the last block of its full id"
9447        );
9448        assert!(
9449            !is_working_on_short(dir.path(), "3cbf", now),
9450            "a daemon busy with one worktree bay is not working on another"
9451        );
9452    }
9453
9454    #[test]
9455    fn a_newer_status_file_still_yields_a_reading() {
9456        let dir = tempfile::tempdir().unwrap();
9457        // A field this build has never heard of must not turn the reading into
9458        // nothing at all; that is the whole reason the reader is permissive.
9459        std::fs::write(
9460            dir.path().join("daemon.json"),
9461            serde_json::json!({
9462                "schema": 2,
9463                "updated_at": Timestamp::now().to_string(),
9464                "idle": true,
9465                "surprise": { "nested": [1, 2, 3] },
9466            })
9467            .to_string(),
9468        )
9469        .unwrap();
9470
9471        let reading = read_status(dir.path()).expect("a forward-compatible read");
9472        assert!(reading.running(Timestamp::now()));
9473        assert!(reading.idle);
9474        assert!(reading.current.is_empty());
9475    }
9476
9477    #[test]
9478    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9479        // A daemon started before `current` became a list keeps writing this
9480        // shape on every heartbeat until it is restarted. A rolling upgrade
9481        // - a newer `magi web` or `magi doctor` reading an older `magi
9482        // serve`'s heartbeat - must still see the run it is on, not "no
9483        // daemon" from a type mismatch failing the whole struct.
9484        let dir = tempfile::tempdir().unwrap();
9485        std::fs::write(
9486            dir.path().join("daemon.json"),
9487            serde_json::json!({
9488                "schema": 1,
9489                "pid": 4242,
9490                "updated_at": Timestamp::now().to_string(),
9491                "idle": false,
9492                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9493                "completed": 3,
9494                "polls": 9,
9495            })
9496            .to_string(),
9497        )
9498        .unwrap();
9499
9500        let reading = read_status(dir.path()).expect("an older shape must still parse");
9501        assert!(reading.running(Timestamp::now()));
9502        assert_eq!(
9503            reading.current,
9504            vec![Current {
9505                worker: None,
9506                task: "20260902-140501-aaaa".to_owned(),
9507                run: "20260902-140502-bbbb".to_owned(),
9508            }]
9509        );
9510    }
9511
9512    #[test]
9513    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9514        let dir = tempfile::tempdir().unwrap();
9515        std::fs::write(
9516            dir.path().join("daemon.json"),
9517            serde_json::json!({
9518                "schema": 1,
9519                "updated_at": Timestamp::now().to_string(),
9520                "idle": true,
9521                "current": null,
9522            })
9523            .to_string(),
9524        )
9525        .unwrap();
9526        let with_null = read_status(dir.path()).expect("null must still parse");
9527        assert!(with_null.current.is_empty());
9528
9529        std::fs::write(
9530            dir.path().join("daemon.json"),
9531            serde_json::json!({
9532                "schema": 1,
9533                "updated_at": Timestamp::now().to_string(),
9534                "idle": true,
9535            })
9536            .to_string(),
9537        )
9538        .unwrap();
9539        let absent = read_status(dir.path()).expect("a missing field must still parse");
9540        assert!(absent.current.is_empty());
9541    }
9542
9543    #[test]
9544    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9545        let fallback = Path::new("/default");
9546        let mut blank = task();
9547        blank.repo = PathBuf::new();
9548        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9549        let mut dot = task();
9550        dot.repo = PathBuf::from(".");
9551        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9552        assert_eq!(
9553            repo_for(&task(), fallback),
9554            PathBuf::from("/repo"),
9555            "a task that names a repository keeps it"
9556        );
9557    }
9558
9559    #[test]
9560    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9561        let dir = tempfile::tempdir().unwrap();
9562        let path = dir.path().join("explicit.toml");
9563        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9564        let opts = Opts {
9565            config: Some(path),
9566            merge: Some("none".into()),
9567            ..Default::default()
9568        };
9569        let mut t = task();
9570        t.set_implementers(
9571            2,
9572            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9573                .unwrap(),
9574        )
9575        .unwrap();
9576        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9577        assert_eq!(cfg.graph.implementers, 2);
9578        assert_eq!(cfg.graph.judges, 1);
9579        assert_eq!(cfg.merge.mode, MergeMode::None);
9580        t.set_implementers(1, &cfg).unwrap();
9581        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9582        apply_task_implementers(&mut cfg, &t);
9583        assert_eq!(cfg.graph.implementers, 1);
9584        assert_eq!(cfg.graph.judges, 1);
9585        assert_eq!(cfg.merge.mode, MergeMode::None);
9586    }
9587
9588    #[test]
9589    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9590        let dir = tempfile::tempdir().unwrap();
9591        let repo = dir.path().join("repo");
9592        std::fs::create_dir(&repo).unwrap();
9593        std::fs::write(
9594            repo.join("magi.toml"),
9595            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9596        )
9597        .unwrap();
9598        let daemon_config = dir.path().join("daemon.toml");
9599        std::fs::write(
9600            &daemon_config,
9601            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9602        )
9603        .unwrap();
9604        let opts = Opts {
9605            config: Some(daemon_config),
9606            merge: Some("pr".into()),
9607            ..Default::default()
9608        };
9609        let q = Queue::at(dir.path().join("queue"));
9610        let validation: Config =
9611            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9612                .unwrap();
9613        // No provenance field on legacy direct tasks: both shapes stay isolated.
9614        for record in ["{}", r#"{"candidates":2}"#] {
9615            let overrides = serde_json::from_str(record).unwrap();
9616            let filing = crate::direct::Filing {
9617                instruction: "work".into(),
9618                title: "direct".into(),
9619                repo: repo.clone(),
9620                source: crate::queue::Source::Human,
9621                solo: false,
9622                overrides,
9623                review_of: None,
9624                sources: Default::default(),
9625            };
9626            let filed =
9627                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9628            let crate::direct::Filed::Standalone {
9629                mut task,
9630                claim: _claim,
9631            } = filed
9632            else {
9633                panic!("local filing")
9634            };
9635            let before = prepare_for(&repo, &opts, &task).unwrap();
9636            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9637            assert_eq!(
9638                before.merge.mode,
9639                MergeMode::None,
9640                "daemon --merge must not leak"
9641            );
9642            for n in [2, 1, 2] {
9643                task.set_implementers(n, &validation).unwrap();
9644                q.put(&mut task).unwrap();
9645                task = q.get(&task.id).unwrap();
9646                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9647                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9648                apply_task_implementers(&mut cfg, &task);
9649                assert_eq!(cfg.graph.implementers, usize::from(n));
9650                assert_eq!(cfg.graph.judges, 2);
9651                assert_eq!(cfg.merge.mode, MergeMode::None);
9652            }
9653        }
9654    }
9655
9656    #[test]
9657    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9658        let cfg: Config =
9659            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9660                .unwrap();
9661        let mut t = task();
9662        t.review_of = Some("review-target".into());
9663        t.hold_manual(Some("retry".into()));
9664        let mut previous = RunState::new(
9665            PathBuf::from("/repo"),
9666            "main".into(),
9667            "abc1234".into(),
9668            "review".into(),
9669            cfg.clone(),
9670        );
9671        previous.config.graph.implementers = 2;
9672        for count in [1, 3] {
9673            t.set_implementers(count, &cfg).unwrap();
9674            t.release();
9675            assert_eq!(t.review_of.as_deref(), Some("review-target"));
9676            for proposed in [
9677                Starter::Resume(previous.id.clone()),
9678                Starter::Review("recovery-target".into()),
9679            ] {
9680                assert_eq!(
9681                    starter_with_implementers(&t, Some(&previous), proposed),
9682                    Starter::Review("review-target".into())
9683                );
9684            }
9685            let mut configured = cfg.clone();
9686            apply_task_implementers(&mut configured, &t);
9687            assert_eq!(configured.graph.implementers, usize::from(count));
9688            assert_eq!(previous.config.graph.implementers, 2);
9689        }
9690    }
9691
9692    #[test]
9693    fn task_implementers_dispatch_and_resume_agree() {
9694        let mut t = task();
9695        let cfg: crate::config::Config =
9696            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9697                .unwrap();
9698        let mut run = RunState::new(
9699            PathBuf::from("/repo"),
9700            "main".into(),
9701            "abc1234".into(),
9702            "work".into(),
9703            cfg.clone(),
9704        );
9705        run.config.graph.implementers = 2;
9706        for n in [2, 1, 3, 2] {
9707            t.set_implementers(n, &cfg).unwrap();
9708            let mut dispatched = cfg.clone();
9709            apply_task_implementers(&mut dispatched, &t);
9710            assert_eq!(dispatched.graph.implementers, usize::from(n));
9711            assert_eq!(implementers_match(&t, &run), n == 2);
9712            for proposed in [
9713                Starter::Resume(run.id.clone()),
9714                Starter::Review("old-branch".into()),
9715            ] {
9716                let expected = if n == 2 {
9717                    proposed.clone()
9718                } else {
9719                    Starter::Start
9720                };
9721                assert_eq!(
9722                    starter_with_implementers(&t, Some(&run), proposed),
9723                    expected
9724                );
9725            }
9726            assert_eq!(
9727                run.config.graph.implementers, 2,
9728                "history must not be rewritten"
9729            );
9730        }
9731        t.solo = false;
9732        t.overrides = None;
9733        assert!(implementers_match(&t, &run));
9734    }
9735
9736    #[test]
9737    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9738        // Three seats said out loud. What `solo` promises is one candidate
9739        // *whatever the config asks for*, so the contrast has to be a number
9740        // this test owns - it used to be `Config::default()`'s, which became
9741        // 1 when one implementation became the default and left the two
9742        // halves of this test asserting the same thing.
9743        let mut solo_cfg = Config::default();
9744        solo_cfg.graph.implementers = 3;
9745        let mut solo_task = task();
9746        solo_task.solo = true;
9747        apply_task_implementers(&mut solo_cfg, &solo_task);
9748        assert_eq!(solo_cfg.graph.implementers, 1);
9749
9750        let mut plain_cfg = Config::default();
9751        plain_cfg.graph.implementers = 3;
9752        let plain_task = task();
9753        assert!(!plain_task.solo);
9754        apply_task_implementers(&mut plain_cfg, &plain_task);
9755        assert_eq!(
9756            plain_cfg.graph.implementers, 3,
9757            "a task that did not ask to run alone keeps the config's candidates"
9758        );
9759    }
9760
9761    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9762        QuotaLoss {
9763            seat: seat.into(),
9764            node: "judge".into(),
9765            at: at.parse().unwrap(),
9766            reset: reset.map(str::to_string),
9767        }
9768    }
9769
9770    #[test]
9771    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
9772        let old: Vec<QuotaLoss> = (1..=4)
9773            .map(|i| {
9774                loss(
9775                    &format!("judge-{i}"),
9776                    "2026-09-23T05:23:00Z",
9777                    Some("2:40pm (Asia/Tokyo)"),
9778                )
9779            })
9780            .collect();
9781        let fresh = losses_this_attempt(&old, &old);
9782        assert!(fresh.is_empty());
9783        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
9784        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
9785    }
9786
9787    #[test]
9788    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
9789        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
9790        let now = Timestamp::now();
9791        let mut after = old.clone();
9792        after.push(loss("judge-2", &now.to_string(), None));
9793        let fresh = losses_this_attempt(&old, &after);
9794        assert_eq!(fresh, vec![after[1].clone()]);
9795        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
9796        assert_eq!(
9797            until,
9798            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
9799        );
9800    }
9801
9802    #[test]
9803    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
9804        // `recover_stall` removes judge-1's loss and the retry then hits quota
9805        // again: the vector is the same length, so an index diff sees nothing.
9806        let before = vec![
9807            loss("judge-1", "2026-09-23T05:23:00Z", None),
9808            loss("judge-2", "2026-09-23T05:24:00Z", None),
9809        ];
9810        let after = vec![
9811            loss("judge-2", "2026-09-23T05:24:00Z", None),
9812            loss("judge-1", "2026-09-24T01:00:00Z", None),
9813        ];
9814        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
9815    }
9816
9817    #[test]
9818    fn merge_overrides_are_parsed_or_refused() {
9819        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
9820        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
9821        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
9822        assert!(merge_mode("squash").is_err());
9823    }
9824
9825    #[test]
9826    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
9827        let now = Timestamp::now();
9828        let fallback = Duration::from_secs(300);
9829        let cap = Duration::from_secs(1800);
9830
9831        // No reset hint at all: the fallback.
9832        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
9833
9834        // A reset ten minutes out, well inside the cap: waited for exactly.
9835        let soon = now + jiff::SignedDuration::from_secs(600);
9836        assert_eq!(
9837            quota_wait(Some(soon), now, fallback, cap),
9838            Duration::from_secs(600)
9839        );
9840
9841        // A reset already in the past is not trusted: the fallback, not a
9842        // zero or negative wait that would spin the loop right back around.
9843        let past = now - jiff::SignedDuration::from_secs(60);
9844        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
9845
9846        // A reset further out than the cap is trusted for direction but not
9847        // for magnitude: a parsing slip must not sleep the loop for a day.
9848        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
9849        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
9850    }
9851
9852    #[test]
9853    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
9854        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9855
9856        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
9857        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
9858
9859        // Same clock reading, but it has already gone by today: read as
9860        // tomorrow's, since the CLI would not still be reporting a limit past
9861        // its own stated reset.
9862        let already_past =
9863            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
9864        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
9865
9866        assert!(
9867            parse_reset_hint("session limit reached", now, now).is_none(),
9868            "free text with no recognised shape is not guessed at"
9869        );
9870        assert!(
9871            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
9872            "an unresolvable zone name is not guessed at either"
9873        );
9874    }
9875
9876    #[test]
9877    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
9878        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9879
9880        let at = parse_reset_hint(
9881            "You've hit your usage limit. Visit \
9882             https://chatgpt.com/codex/settings/usage to purchase more \
9883             credits or try again at Sep 19th, 2026 5:10 PM.",
9884            now,
9885            now,
9886        )
9887        .expect("the codex reset wording is a recognised shape");
9888        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
9889
9890        // The month is explicit, so a date already earlier in the same
9891        // sentence-implied year than `now` is trusted as written rather than
9892        // rolled forward a year the way the bracketed shape rolls a
9893        // same-day clock reading to tomorrow.
9894        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
9895            .expect("an explicit year needs no rollover");
9896        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
9897
9898        assert!(
9899            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
9900            "a two-digit year is not the documented shape and is not guessed at"
9901        );
9902        assert!(
9903            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
9904            "a four-letter month name is not the documented three-letter abbreviation"
9905        );
9906        assert!(
9907            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
9908            "an explicit zone on the dated shape is a format nobody has \
9909             documented, and is refused rather than guessed at as UTC"
9910        );
9911    }
9912
9913    #[test]
9914    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
9915        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
9916        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
9917
9918        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
9919        assert_eq!(at.as_second() - recorded.as_second(), 3769);
9920
9921        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
9922        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
9923
9924        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
9925            assert!(
9926                parse_reset_hint(bad, now, recorded).is_none(),
9927                "{bad:?} must not be guessed at"
9928            );
9929        }
9930    }
9931
9932    /// A loop whose queue lives in a temp tree and whose poll interval is far
9933    /// longer than the test's patience, so anything that waits out a poll
9934    /// instead of noticing the stop fails rather than merely being slow.
9935    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
9936        let config = dir.join("magi.toml");
9937        std::fs::write(
9938            &config,
9939            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
9940        )
9941        .unwrap();
9942        let opts = Opts {
9943            poll: Duration::from_secs(30),
9944            config: Some(config),
9945            // The explicit fixture config keeps startup cleanup from reading
9946            // machine configuration. This fictional repository likewise
9947            // keeps any best-effort git cleanup away from this checkout.
9948            repo: dir.join("repo"),
9949            ..Opts::default()
9950        };
9951        // The status file goes in a directory that does not exist yet, so its
9952        // creation is itself evidence the loop published one. `worktrees`
9953        // must be just as fictional: the janitor reclaims worktrees under it
9954        // for real, and a test that let it fall through to
9955        // `crate::run::default_worktree_root()` would have it reclaim
9956        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
9957        // which is exactly what happened before this function took the
9958        // parameter at all.
9959        let home = dir.join("home");
9960        // These control-only fixtures do not launch native workers. Give the
9961        // independently tested maintenance services a fresh cadence receipt.
9962        let stamps = home.join("service-ticks");
9963        std::fs::create_dir_all(&stamps).unwrap();
9964        for service in ["waiter", "deputies", "release-watch"] {
9965            std::fs::write(
9966                stamps.join(service),
9967                Timestamp::now().as_second().to_string(),
9968            )
9969            .unwrap();
9970        }
9971        for operation in [
9972            "conductor",
9973            "maintenance",
9974            "housekeeping",
9975            "disk-pressure",
9976            "cache",
9977            "fetch",
9978        ] {
9979            std::fs::write(
9980                stamps.join(format!("daemon-{operation}")),
9981                serde_json::to_vec(&Timestamp::now()).unwrap(),
9982            )
9983            .unwrap();
9984        }
9985        let worktrees = dir.join("wt");
9986        (
9987            opts,
9988            Queue::at(dir.join("queue")),
9989            home.join("daemon.json"),
9990            home,
9991            worktrees,
9992        )
9993    }
9994
9995    #[test]
9996    fn a_stop_is_idempotent_and_once_set_stays_set() {
9997        let stop = Stop::new();
9998        assert!(!stop.stopped());
9999
10000        stop.stop();
10001        assert!(stop.stopped());
10002        stop.stop();
10003        assert!(stop.stopped(), "a second stop is not a toggle");
10004
10005        let shared = stop.clone();
10006        assert!(
10007            shared.stopped(),
10008            "a clone is the same stop; that is how the loop and its caller share one"
10009        );
10010    }
10011
10012    #[tokio::test]
10013    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10014        for operation in ["conductor", "maintenance", "housekeeping"] {
10015            let dir = tempfile::tempdir().unwrap();
10016            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10017            opts.once = true;
10018            opts.poll = Duration::from_millis(1);
10019            let mut task = task();
10020            task.runs.push("fixture-run".into());
10021            queue.put(&mut task).unwrap();
10022            let claim = queue.claim(&task.id).unwrap();
10023
10024            // Model a live service holding the task's claim across the
10025            // scheduler's dispatch scan. No real subprocess or timed race.
10026            let directory = home.join("workers/jobs/abcdef");
10027            std::fs::create_dir_all(&directory).unwrap();
10028            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10029            crate::pr_head::try_lock_file(&lease).unwrap();
10030            let mut job = crate::worker::Job {
10031                id: "abcdef".into(),
10032                sequence: 1,
10033                kind: "daemon-service".into(),
10034                key: format!("service:daemon-{operation}"),
10035                payload: serde_json::Value::Null,
10036                generation: "fixture".into(),
10037                version: None,
10038                status: crate::worker::Status::Running,
10039                result: None,
10040                pid: Some(std::process::id()),
10041                created_at: Timestamp::now().as_second() as u64,
10042                finished_at: None,
10043            };
10044            let record = directory.join("job.json");
10045            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10046
10047            let status = Arc::new(Mutex::new(Status::new()));
10048            let stop = Stop::new();
10049            let mut drain = Box::pin(poll(
10050                &opts,
10051                &queue,
10052                &status,
10053                &home,
10054                &worktrees,
10055                &stop,
10056                DispatchLimits {
10057                    max_concurrent: 1,
10058                    pause_for_interrupts: false,
10059                    recovery_cfg: None,
10060                },
10061            ));
10062            std::future::poll_fn(|cx| {
10063                use std::future::Future;
10064                assert!(
10065                    drain.as_mut().poll(cx).is_pending(),
10066                    "--once must wait for {operation} to release its queue claim"
10067                );
10068                std::task::Poll::Ready(())
10069            })
10070            .await;
10071            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10072
10073            // An answer arrives while the service still owns the claim. A
10074            // fresh scheduling pass must apply it before declaring idle.
10075            let questions = Questions::at(home.join("questions"));
10076            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10077            questions.put(&mut q).unwrap();
10078            drop(claim);
10079            // Model services that took longer than their cadence, without a
10080            // wall-clock sleep. The final scans must not respawn them even
10081            // though their receipts now permit another periodic invocation.
10082            let expired =
10083                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10084            for service in [operation, "housekeeping"] {
10085                std::fs::write(
10086                    home.join("service-ticks").join(format!("daemon-{service}")),
10087                    &expired,
10088                )
10089                .unwrap();
10090            }
10091            job.status = crate::worker::Status::Finished;
10092            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10093            drop(lease);
10094            tokio::time::timeout(Duration::from_secs(2), drain)
10095                .await
10096                .expect("the settled service must allow the drain to finish")
10097                .unwrap();
10098            let after = queue.get(&task.id).unwrap();
10099            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10100            assert!(after.action_applied(&q.id));
10101            for service in [operation, "housekeeping"] {
10102                assert_eq!(
10103                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10104                        .unwrap(),
10105                    expired,
10106                    "the final once rescan must not restart {service}"
10107                );
10108            }
10109        }
10110    }
10111
10112    #[test]
10113    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10114        let stop = Stop::new();
10115        stop.busy.store(1, Ordering::SeqCst);
10116        assert!(
10117            !stop.finishing(),
10118            "a busy loop nobody has asked to stop is just running"
10119        );
10120
10121        stop.stop();
10122        assert!(
10123            stop.finishing(),
10124            "a stop asked for mid-run has not landed until the run is settled"
10125        );
10126
10127        stop.busy.store(0, Ordering::SeqCst);
10128        assert!(
10129            !stop.finishing(),
10130            "once the run is settled the stop has landed and there is nothing to finish"
10131        );
10132    }
10133
10134    #[test]
10135    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10136        let stop = Stop::new();
10137        stop.busy.store(2, Ordering::SeqCst);
10138        stop.stop();
10139        assert!(stop.finishing(), "two runs still in flight");
10140
10141        stop.busy.store(1, Ordering::SeqCst);
10142        assert!(
10143            stop.finishing(),
10144            "one run finished, but a sibling is still working"
10145        );
10146
10147        stop.busy.store(0, Ordering::SeqCst);
10148        assert!(
10149            !stop.finishing(),
10150            "the last run out is what actually lands the stop"
10151        );
10152    }
10153
10154    #[tokio::test]
10155    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10156        let dir = tempfile::tempdir().unwrap();
10157        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10158        let stop = Stop::new();
10159        stop.stop();
10160
10161        let began = std::time::Instant::now();
10162        tokio::time::timeout(
10163            Duration::from_secs(2),
10164            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10165        )
10166        .await
10167        .expect("a stopped loop must return, not sit out its poll interval")
10168        .expect("the loop's own setup and teardown must not fail");
10169        assert!(
10170            began.elapsed() < opts.poll,
10171            "returned only after {:?}, which is a poll interval, not a stop",
10172            began.elapsed()
10173        );
10174    }
10175
10176    #[tokio::test]
10177    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10178        let dir = tempfile::tempdir().unwrap();
10179        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10180        let stop = Stop::new();
10181
10182        // Asked for after the loop is already parked on its empty queue, which
10183        // is the case an operator tapping stop on a phone actually hits.
10184        let asker = {
10185            let stop = stop.clone();
10186            tokio::spawn(async move {
10187                tokio::time::sleep(Duration::from_millis(20)).await;
10188                stop.stop();
10189            })
10190        };
10191
10192        let began = std::time::Instant::now();
10193        tokio::time::timeout(
10194            Duration::from_secs(2),
10195            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10196        )
10197        .await
10198        .expect("a stop asked for while idle must wake the wait")
10199        .expect("the loop's own setup and teardown must not fail");
10200        asker.await.unwrap();
10201        assert!(
10202            began.elapsed() < opts.poll,
10203            "returned only after {:?}, so the stop waited on the sleep",
10204            began.elapsed()
10205        );
10206    }
10207
10208    #[tokio::test]
10209    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10210        let dir = tempfile::tempdir().unwrap();
10211        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10212        let stop = Stop::new();
10213        stop.stop();
10214
10215        tokio::time::timeout(
10216            Duration::from_secs(2),
10217            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10218        )
10219        .await
10220        .expect("a stopped loop must return")
10221        .expect("the loop's own setup and teardown must not fail");
10222
10223        assert!(
10224            home.is_dir(),
10225            "the loop did publish a status file, so its removal is the teardown and not an absence"
10226        );
10227        assert!(
10228            !status_file.exists(),
10229            "a stopped loop clears its status file"
10230        );
10231        assert!(
10232            read_status(&home).is_none(),
10233            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10234        );
10235    }
10236
10237    #[tokio::test]
10238    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10239        let dir = tempfile::tempdir().unwrap();
10240        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10241
10242        let mut settled = RunState::new(
10243            dir.path().join("repo"),
10244            "main".to_owned(),
10245            "abc1234".to_owned(),
10246            "fixture".to_owned(),
10247            Config::default(),
10248        );
10249        settled.status = RunStatus::Ready;
10250        let run_dir = home.join("runs").join(&settled.id);
10251        std::fs::create_dir_all(&run_dir).unwrap();
10252        std::fs::write(
10253            run_dir.join("run.json"),
10254            serde_json::to_string_pretty(&settled).unwrap(),
10255        )
10256        .unwrap();
10257        let questions = Questions::at(home.join("questions"));
10258        let mut question = ask::Question::new(
10259            settled.id.clone(),
10260            "review".to_owned(),
10261            "reviewer-1".to_owned(),
10262            "Continue?".to_owned(),
10263            String::new(),
10264            Vec::new(),
10265        );
10266        questions.put(&mut question).unwrap();
10267
10268        run_service_worker(
10269            &home,
10270            serde_json::to_value(ServiceWorker {
10271                opts,
10272                queue: queue.root().to_path_buf(),
10273                worktrees_root: worktrees,
10274                operation: "housekeeping".to_owned(),
10275            })
10276            .unwrap(),
10277        )
10278        .await
10279        .unwrap();
10280
10281        assert_eq!(
10282            questions.get(&question.id).unwrap().status,
10283            ask::QuestionStatus::Abandoned,
10284            "the independent housekeeping worker settles ended-run questions"
10285        );
10286    }
10287
10288    #[test]
10289    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10290        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10291
10292        assert!(
10293            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10294            "never checked before: due at once"
10295        );
10296
10297        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10298        assert!(
10299            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10300            "well inside the interval: not due yet"
10301        );
10302
10303        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10304        assert!(
10305            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10306            "exactly at the edge: not yet due, same convention as `clean::due`"
10307        );
10308
10309        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10310        assert!(
10311            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10312            "past the interval: due again"
10313        );
10314    }
10315
10316    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10317    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10318    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10319    /// and the congestion test below both need, and must not drift apart.
10320    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10321        let config = dir.join("magi.toml");
10322        // A literal (single-quoted) TOML string, not a basic one: the cache
10323        // path is a Windows path full of backslashes, and a basic string
10324        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10325        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10326        // `{{ vars.cache }}` rendering documents.
10327        std::fs::write(
10328            &config,
10329            format!(
10330                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10331                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10332                cache_dir.display()
10333            ),
10334        )
10335        .unwrap();
10336        Opts {
10337            config: Some(config),
10338            repo: dir.join("repo"),
10339            ..Opts::default()
10340        }
10341    }
10342
10343    #[tokio::test]
10344    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10345        let dir = tempfile::tempdir().unwrap();
10346        let home = dir.path().join("home");
10347        let cache_dir = dir.path().join("cache");
10348        std::fs::create_dir_all(&cache_dir).unwrap();
10349        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10350        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10351
10352        // Nobody has asked this daemon to stop, which is the ordinary case;
10353        // the skip that a stop buys is asserted by its own test below.
10354        let running = Stop::new();
10355        let mut last_checked = None;
10356        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10357        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10358            .await;
10359        assert_eq!(
10360            crate::disk::dir_size(&cache_dir),
10361            0,
10362            "over the cap on the first check ever: pruned at once, no idle queue required"
10363        );
10364        assert_eq!(last_checked, Some(t0));
10365
10366        // A fresh oversized file lands, but the next check is not due yet.
10367        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10368        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10369        maybe_prune_cache_between_runs(
10370            &opts.repo,
10371            &opts,
10372            &home,
10373            &running,
10374            &mut last_checked,
10375            too_soon,
10376        )
10377        .await;
10378        assert_eq!(
10379            crate::disk::dir_size(&cache_dir),
10380            10,
10381            "too soon since the last check: left alone rather than rescanned every call"
10382        );
10383        assert_eq!(
10384            last_checked,
10385            Some(t0),
10386            "an idle check does not reset the clock"
10387        );
10388
10389        // Once the interval elapses, the same oversized cache is caught again.
10390        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10391        maybe_prune_cache_between_runs(
10392            &opts.repo,
10393            &opts,
10394            &home,
10395            &running,
10396            &mut last_checked,
10397            due_again,
10398        )
10399        .await;
10400        assert_eq!(
10401            crate::disk::dir_size(&cache_dir),
10402            0,
10403            "due again: pruned back under the cap"
10404        );
10405    }
10406
10407    /// A stop must not queue behind housekeeping. The prune below is a
10408    /// synchronous walk of the whole cache with no await point in it, so a
10409    /// loop that entered it could not get back to its own `stopped()` test
10410    /// until the walk finished - and because no run is in flight at this
10411    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10412    /// the stop had already landed. The idle branch has always made this same
10413    /// check before reaching `janitor`; the between-runs path makes it too.
10414    #[tokio::test]
10415    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10416        let dir = tempfile::tempdir().unwrap();
10417        let home = dir.path().join("home");
10418        let cache_dir = dir.path().join("cache");
10419        std::fs::create_dir_all(&cache_dir).unwrap();
10420        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10421        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10422
10423        let stop = Stop::new();
10424        stop.stop();
10425        assert!(
10426            !stop.finishing(),
10427            "no run is in flight at a between-runs boundary, so nothing else \
10428             would tell the operator this stop had not taken effect yet"
10429        );
10430
10431        let mut last_checked = None;
10432        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10433        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10434            .await;
10435        assert_eq!(
10436            crate::disk::dir_size(&cache_dir),
10437            10,
10438            "over its cap, and due for the first check ever, but a stop outranks \
10439             it: the cap is a standing policy the next start measures again"
10440        );
10441        assert_eq!(
10442            last_checked, None,
10443            "a check that never happened must not claim the interval"
10444        );
10445    }
10446
10447    /// A backlog must not starve cache pruning. The finite cache worker runs
10448    /// independently of queue drain and must not consume any task attempts.
10449    #[tokio::test]
10450    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10451        let dir = tempfile::tempdir().unwrap();
10452        let cache_dir = dir.path().join("cache");
10453        std::fs::create_dir_all(&cache_dir).unwrap();
10454        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10455
10456        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10457        opts.poll = Duration::from_millis(20);
10458        opts.max_attempts = 1_000;
10459
10460        let queue = Queue::at(dir.path().join("queue"));
10461        for i in 0..128 {
10462            let mut task = Task::new(
10463                format!("queued work {i}"),
10464                format!("queued work {i}"),
10465                opts.repo.clone(),
10466                Source::Human,
10467            );
10468            queue.put(&mut task).unwrap();
10469        }
10470
10471        let home = dir.path().join("home");
10472        let worktrees = dir.path().join("wt");
10473        run_service_worker(
10474            &home,
10475            serde_json::to_value(ServiceWorker {
10476                opts,
10477                queue: queue.root().to_path_buf(),
10478                worktrees_root: worktrees,
10479                operation: "cache".to_owned(),
10480            })
10481            .unwrap(),
10482        )
10483        .await
10484        .unwrap();
10485        let after = queue.list();
10486        assert_eq!(after.len(), 128);
10487        assert!(
10488            after
10489                .iter()
10490                .all(|task| task.status.runnable() && task.attempts == 0)
10491        );
10492
10493        assert_eq!(
10494            crate::disk::dir_size(&cache_dir),
10495            0,
10496            "an oversized cache must not be left to grow unboundedly just because the \
10497             queue kept the loop busy the whole time"
10498        );
10499    }
10500
10501    #[test]
10502    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10503        let dir = tempfile::tempdir().unwrap();
10504        let queue = Queue::at(dir.path().join("queue"));
10505        let questions = Questions::at(dir.path().join("questions"));
10506        let mut task = task();
10507        queue.put(&mut task).unwrap();
10508
10509        let mut task_question = ask::Question::new(
10510            task.id.clone(),
10511            crate::conduct::NODE.to_owned(),
10512            "conduct".to_owned(),
10513            "Which backend?".to_owned(),
10514            String::new(),
10515            Vec::new(),
10516        );
10517        questions.put(&mut task_question).unwrap();
10518        task.block(vec![task_question.id.clone()], None);
10519        queue.put(&mut task).unwrap();
10520
10521        let mut run_question = ask::Question::new(
10522            "20260101-000000-run1".to_owned(),
10523            "review".to_owned(),
10524            "reviewer-1".to_owned(),
10525            "Run question".to_owned(),
10526            String::new(),
10527            Vec::new(),
10528        );
10529        questions.put(&mut run_question).unwrap();
10530
10531        // A question from another node whose `run` happens to equal this
10532        // task's id — the same field, filled in for an unrelated reason. Only
10533        // `crate::conduct::NODE` questions use `run` as a task id; this one
10534        // must never be touched by this reconciliation, even after release.
10535        let mut coincidental = ask::Question::new(
10536            task.id.clone(),
10537            "review".to_owned(),
10538            "reviewer-1".to_owned(),
10539            "Unrelated review question".to_owned(),
10540            String::new(),
10541            Vec::new(),
10542        );
10543        questions.put(&mut coincidental).unwrap();
10544
10545        reconcile_task_questions(&queue, &questions);
10546        assert!(questions.get(&task_question.id).unwrap().status.open());
10547        assert!(questions.get(&run_question.id).unwrap().status.open());
10548        assert!(questions.get(&coincidental.id).unwrap().status.open());
10549
10550        task.release();
10551        queue.put(&mut task).unwrap();
10552        reconcile_task_questions(&queue, &questions);
10553        assert_eq!(
10554            questions.get(&task_question.id).unwrap().status,
10555            ask::QuestionStatus::Abandoned
10556        );
10557        assert!(
10558            questions.get(&run_question.id).unwrap().status.open(),
10559            "run questions remain the run janitor's responsibility"
10560        );
10561        assert!(
10562            questions.get(&coincidental.id).unwrap().status.open(),
10563            "a non-conductor question must not be abandoned just because its \
10564             run id coincides with a task id"
10565        );
10566    }
10567
10568    #[test]
10569    fn a_freshly_started_running_task_is_never_stalled() {
10570        let dir = tempfile::tempdir().unwrap();
10571        let mut t = task();
10572        t.start("run-1".to_owned());
10573        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10574        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10575        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10576    }
10577
10578    #[test]
10579    fn a_long_running_task_with_no_live_daemon_is_stalled() {
10580        let dir = tempfile::tempdir().unwrap();
10581        let mut t = task();
10582        t.start("run-1".to_owned());
10583        t.updated_at = Timestamp::now()
10584            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10585        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10586        assert_eq!(
10587            stalled_tasks(
10588                &Queue::at(dir.path().join("q")),
10589                dir.path(),
10590                Timestamp::now()
10591            )
10592            .len(),
10593            0,
10594            "the task was never written to this queue"
10595        );
10596    }
10597
10598    #[test]
10599    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10600        let dir = tempfile::tempdir().unwrap();
10601        let mut t = task();
10602        t.id = "20260903-080340-0167".to_owned();
10603        t.start("20260903-080619-01c2".to_owned());
10604        t.updated_at = Timestamp::now()
10605            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10606
10607        let mut status = Status::new();
10608        status.current = vec![Current {
10609            worker: None,
10610            task: t.id.clone(),
10611            run: "20260903-080619-01c2".to_owned(),
10612        }];
10613        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10614
10615        assert!(
10616            !is_stalled(&t, dir.path(), Timestamp::now()),
10617            "a live daemon's own heartbeat rules out stalled, however long the task has run"
10618        );
10619    }
10620
10621    /// Rewrite a task's `updated_at` on disk directly, bypassing
10622    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
10623    /// a fixture look like it has genuinely been `running` for a while.
10624    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10625        let path = queue.path_of(id);
10626        let body = std::fs::read_to_string(&path).unwrap();
10627        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10628        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10629        v["updated_at"] = serde_json::Value::String(old.to_string());
10630        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10631    }
10632
10633    #[test]
10634    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10635        // The realistic `poll()` ordering, not `is_stalled` in isolation:
10636        // `reclaim_orphaned_running` runs first, on every poll, and settles
10637        // any `running` task whose claim it can actually take. For most
10638        // crashes that is immediate - a dead pid is proof enough for
10639        // `sweep_stale_claims` to drop the lock the same tick, and the very
10640        // next claim attempt succeeds. But a lock whose pid cannot be parsed
10641        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
10642        // `sweep_stale_claims`'s own doc), so the lock - and the claim
10643        // failure behind it - can legitimately outlive many polls. This is
10644        // exactly the gap `stalled_tasks` exists to surface well before that
10645        // six-hour sweep would: reclaim leaves the task `running`, and it
10646        // must still reach the conductor as stalled.
10647        let dir = tempfile::tempdir().unwrap();
10648        let queue = Queue::at(dir.path().join("queue"));
10649        let home = dir.path().join("home");
10650
10651        let mut t = task();
10652        t.id = "20260101-000001-lock".to_owned();
10653        t.start("run-1".to_owned());
10654        queue.put(&mut t).unwrap();
10655        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10656        std::fs::write(
10657            dir.path().join("queue").join(format!("{}.lock", t.id)),
10658            "not a pid",
10659        )
10660        .unwrap();
10661
10662        let now = Timestamp::now();
10663        assert!(
10664            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10665            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10666             and reclaim must leave the task alone"
10667        );
10668        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10669
10670        let stalled = stalled_tasks(&queue, &home, now);
10671        assert_eq!(
10672            stalled.len(),
10673            1,
10674            "reclaim's inability to claim it yet must not hide it from the conductor"
10675        );
10676        assert_eq!(stalled[0].id, t.id);
10677    }
10678
10679    #[test]
10680    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10681        let dir = tempfile::tempdir().unwrap();
10682        crate::run::set_home(dir.path().join("run-home"));
10683        let queue = Queue::at(dir.path().join("queue"));
10684        let home = dir.path().join("home");
10685        let questions = Questions::at(dir.path().join("questions"));
10686
10687        let mut t = task();
10688        t.id = "20260101-000003-dead".to_owned();
10689        t.start("missing-run".to_owned());
10690        queue.put(&mut t).unwrap();
10691        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10692
10693        // This is the real poll ordering: retain the deterministic stalled
10694        // input before a claim proves the owner is gone and reclaims it.
10695        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10696        assert_eq!(
10697            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10698            [&t.id]
10699        );
10700        assert_eq!(
10701            reclaim_orphaned_running(&queue, 2, &Default::default()),
10702            [t.id.clone()]
10703        );
10704        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10705
10706        // Reclaim drops its guard before conductor decisions are applied, so
10707        // the decision for the captured stalled input has a real write path.
10708        crate::conduct::apply(
10709            &queue,
10710            &questions,
10711            &crate::conduct::Verdict {
10712                decisions: vec![crate::conduct::Decision {
10713                    id: t.id.clone(),
10714                    recovery: Some(crate::conduct::Recovery::Requeue),
10715                    ..crate::conduct::Decision::default()
10716                }],
10717            },
10718        )
10719        .unwrap();
10720        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10721    }
10722
10723    #[test]
10724    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10725        let dir = tempfile::tempdir().unwrap();
10726        let queue = Queue::at(dir.path().join("queue"));
10727        let home = dir.path().join("home");
10728
10729        let mut fresh = task();
10730        fresh.id = "20260101-000001-aaaa".to_owned();
10731        fresh.start("run-1".to_owned());
10732        queue.put(&mut fresh).unwrap();
10733
10734        let mut old = task();
10735        old.id = "20260101-000002-bbbb".to_owned();
10736        old.start("run-2".to_owned());
10737        queue.put(&mut old).unwrap();
10738        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10739
10740        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10741        assert_eq!(stalled.len(), 1);
10742        assert_eq!(stalled[0].id, old.id);
10743    }
10744
10745    #[test]
10746    fn queued_and_finished_task_views_partition_by_status() {
10747        let dir = tempfile::tempdir().unwrap();
10748        let queue = Queue::at(dir.path().join("queue"));
10749
10750        let mut queued = task();
10751        queued.id = "20260101-000001-aaaa".to_owned();
10752        queue.put(&mut queued).unwrap();
10753
10754        let mut failed = task();
10755        failed.id = "20260101-000002-bbbb".to_owned();
10756        failed.start("run-1".to_owned());
10757        failed.fail("gate red", 5);
10758        queue.put(&mut failed).unwrap();
10759
10760        let mut held = task();
10761        held.id = "20260101-000003-cccc".to_owned();
10762        held.hold_machine(None);
10763        queue.put(&mut held).unwrap();
10764
10765        let mut running = task();
10766        running.id = "20260101-000004-dddd".to_owned();
10767        running.start("run-2".to_owned());
10768        queue.put(&mut running).unwrap();
10769
10770        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
10771        assert_eq!(queued_ids, [queued.id.clone()]);
10772
10773        let mut finished_ids: Vec<String> =
10774            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
10775        finished_ids.sort_unstable();
10776        let mut want = vec![failed.id.clone(), held.id.clone()];
10777        want.sort_unstable();
10778        assert_eq!(finished_ids, want);
10779    }
10780
10781    #[test]
10782    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
10783        for short in [false, true] {
10784            let dir = tempfile::tempdir().unwrap();
10785            let queue = Queue::at(dir.path().join("queue"));
10786            let questions = ask::Questions::at(dir.path().join("questions"));
10787            let mut running = task();
10788            running.id = "20261013-192213-feb2".into();
10789            running.start("existing-run".into());
10790            queue.put(&mut running).unwrap();
10791            let mut middle = task();
10792            middle.id = "20261013-193611-ca5b".into();
10793            middle.block(
10794                vec![if short {
10795                    "feb2".into()
10796                } else {
10797                    running.id.clone()
10798                }],
10799                None,
10800            );
10801            queue.put(&mut middle).unwrap();
10802            let mut waiting = task();
10803            waiting.id = "20261013-202849-ee37".into();
10804            waiting.block(
10805                vec![if short {
10806                    "ca5b".into()
10807                } else {
10808                    middle.id.clone()
10809                }],
10810                Some("wait for implementation".into()),
10811            );
10812            queue.put(&mut waiting).unwrap();
10813            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
10814            let inv = crate::blockers::Inventory::load(&queue, &questions);
10815            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
10816            assert!(inv.stuck().is_empty());
10817            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10818            assert!(report.quarantined.is_empty());
10819            assert!(report.asked.is_empty());
10820            resolve_blockers(&queue, &questions);
10821            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10822            assert!(questions.list().is_empty());
10823            // Finishing the transitive prerequisite alone does not satisfy
10824            // the task's direct dependency.
10825            running.succeed();
10826            queue.put(&mut running).unwrap();
10827            resolve_blockers(&queue, &questions);
10828            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
10829            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10830            middle = queue.get(&middle.id).unwrap();
10831            middle.succeed();
10832            queue.put(&mut middle).unwrap();
10833            resolve_blockers(&queue, &questions);
10834            let after = queue.get(&waiting.id).unwrap();
10835            assert_eq!(after.status, TaskStatus::Queued);
10836            assert!(after.blocked_by.is_empty());
10837            assert_eq!(after.instruction, waiting.instruction);
10838        }
10839    }
10840
10841    #[test]
10842    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
10843        for future_schema in [false, true] {
10844            let name = "20261013-193611-ca5b";
10845            let mut future = task();
10846            future.id = name.into();
10847            future.schema = crate::queue::SCHEMA + 1;
10848            let contents = if future_schema {
10849                serde_json::to_string(&future).unwrap()
10850            } else {
10851                "corrupt".into()
10852            };
10853            let dir = tempfile::tempdir().unwrap();
10854            let queue = Queue::at(dir.path().join("queue"));
10855            let questions = ask::Questions::at(dir.path().join("questions"));
10856            let mut waiting = task();
10857            waiting.id = "20261013-202849-ee37".into();
10858            waiting.block(vec!["ca5b".into()], None);
10859            queue.put(&mut waiting).unwrap();
10860            std::fs::write(queue.path_of(name), contents).unwrap();
10861            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
10862            assert!(
10863                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
10864            );
10865            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10866            assert!(report.asked.is_empty());
10867            resolve_blockers(&queue, &questions);
10868            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10869            assert!(questions.list().is_empty());
10870        }
10871        let dir = tempfile::tempdir().unwrap();
10872        let queue = Queue::at(dir.path().join("queue"));
10873        let questions = ask::Questions::at(dir.path().join("questions"));
10874        let mut waiting = task();
10875        waiting.id = "20261013-202849-ee37".into();
10876        waiting.block(vec!["ca5b".into()], None);
10877        queue.put(&mut waiting).unwrap();
10878        let mut done = task();
10879        done.id = "20261013-193611-ca5b".into();
10880        done.succeed();
10881        queue.put(&mut done).unwrap();
10882        // An unreadable second match must not disappear from uniqueness
10883        // checks just because Queue::list skips it.
10884        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
10885        assert!(queue.get("ca5b").is_err());
10886        assert_eq!(
10887            crate::queue::dependency(&queue, &questions, "ca5b"),
10888            crate::queue::Dependency::Ambiguous
10889        );
10890        resolve_blockers(&queue, &questions);
10891        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10892        assert!(report.asked.is_empty());
10893        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10894        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
10895    }
10896
10897    #[test]
10898    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
10899        for held in [false, true] {
10900            for question in [false, true] {
10901                for reference in ["ca5b", "20261013-193611-ca5b"] {
10902                    let dir = tempfile::tempdir().unwrap();
10903                    let queue = Queue::at(dir.path().join("queue"));
10904                    let questions = ask::Questions::at(dir.path().join("questions"));
10905                    let mut prerequisite = task();
10906                    prerequisite.id = "20261013-193611-ca5b".into();
10907                    prerequisite.start("existing-run".into());
10908                    queue.put(&mut prerequisite).unwrap();
10909                    let mut waiting = task();
10910                    waiting.id = "20261013-202849-ee37".into();
10911                    if held {
10912                        waiting.hold_machine(Some("waiting for separate consent".into()));
10913                    }
10914                    queue.put(&mut waiting).unwrap();
10915                    let reason = "Deleting saved data requires separate owner consent";
10916                    crate::conduct::apply(
10917                        &queue,
10918                        &questions,
10919                        &crate::conduct::Verdict {
10920                            decisions: vec![crate::conduct::Decision {
10921                                id: waiting.id.clone(),
10922                                blocked_by: vec![reference.into()],
10923                                question: question.then(|| "May the saved data be deleted?".into()),
10924                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
10925                                reason: Some(reason.into()),
10926                                ..crate::conduct::Decision::default()
10927                            }],
10928                        },
10929                    )
10930                    .unwrap();
10931                    let before = queue.get(&waiting.id).unwrap();
10932                    if question {
10933                        assert_eq!(before.status, TaskStatus::Blocked);
10934                        let q = questions.get(&before.blocked_by[0]).unwrap();
10935                        assert_eq!(q.summary, "May the saved data be deleted?");
10936                        assert!(q.status.open());
10937                    } else {
10938                        assert_eq!(before.status, TaskStatus::Held);
10939                        let recorded_reason = before.hold_reason.as_deref().unwrap();
10940                        assert!(recorded_reason.starts_with(reason));
10941                        if held {
10942                            assert!(recorded_reason.contains("waiting for separate consent"));
10943                        }
10944                    }
10945                    prerequisite.succeed();
10946                    queue.put(&mut prerequisite).unwrap();
10947                    resolve_blockers(&queue, &questions);
10948                    let after = queue.get(&waiting.id).unwrap();
10949                    assert_eq!(after.status, before.status);
10950                    assert_eq!(after.blocked_by, before.blocked_by);
10951                    assert_eq!(after.hold_reason, before.hold_reason);
10952                    assert_eq!(after.instruction, waiting.instruction);
10953                    if question {
10954                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
10955                    }
10956                    assert!(
10957                        queue.next_runnable().is_none(),
10958                        "dependency completion is not consent"
10959                    );
10960                }
10961            }
10962        }
10963    }
10964
10965    #[test]
10966    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
10967        let dir = tempfile::tempdir().unwrap();
10968        let queue = Queue::at(dir.path().join("queue"));
10969        let questions = ask::Questions::at(dir.path().join("questions"));
10970
10971        let mut dep = task();
10972        dep.id = "20260101-000001-dep0".to_owned();
10973        dep.succeed();
10974        queue.put(&mut dep).unwrap();
10975
10976        let mut still_going = task();
10977        still_going.id = "20260101-000002-dep1".to_owned();
10978        queue.put(&mut still_going).unwrap();
10979
10980        let mut blocked = task();
10981        blocked.id = "20260101-000003-main".to_owned();
10982        blocked.block(
10983            vec![dep.id.clone(), still_going.id.clone()],
10984            Some("waits on both".to_owned()),
10985        );
10986        queue.put(&mut blocked).unwrap();
10987
10988        resolve_blockers(&queue, &questions);
10989
10990        let after = queue.get(&blocked.id).unwrap();
10991        assert_eq!(
10992            after.status,
10993            TaskStatus::Blocked,
10994            "one dependency is still outstanding"
10995        );
10996        assert_eq!(after.blocked_by, [still_going.id.clone()]);
10997    }
10998
10999    #[test]
11000    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11001        let dir = tempfile::tempdir().unwrap();
11002        let queue = Queue::at(dir.path().join("queue"));
11003        let questions = ask::Questions::at(dir.path().join("questions"));
11004
11005        let mut q = crate::ask::Question::new(
11006            "20260101-000001-main".to_owned(),
11007            crate::conduct::NODE.to_owned(),
11008            "conduct".to_owned(),
11009            "Which backend?".to_owned(),
11010            String::new(),
11011            Vec::new(),
11012        );
11013        questions.put(&mut q).unwrap();
11014        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11015            .unwrap();
11016        questions.put(&mut q).unwrap();
11017
11018        let mut blocked = task();
11019        blocked.id = "20260101-000001-main".to_owned();
11020        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11021        queue.put(&mut blocked).unwrap();
11022
11023        resolve_blockers(&queue, &questions);
11024
11025        let after = queue.get(&blocked.id).unwrap();
11026        assert_eq!(
11027            after.status,
11028            TaskStatus::Queued,
11029            "the only blocker resolved"
11030        );
11031        assert_eq!(after.answers.len(), 1);
11032        assert_eq!(after.answers[0].question, "Which backend?");
11033        assert_eq!(after.answers[0].answer, "SQLite");
11034
11035        // And the run this task starts next is told about it.
11036        let instruction = instruction_for(&after);
11037        assert!(instruction.contains("Which backend?"));
11038        assert!(instruction.contains("SQLite"));
11039    }
11040
11041    #[test]
11042    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11043        let dir = tempfile::tempdir().unwrap();
11044        let queue = Queue::at(dir.path().join("queue"));
11045        let questions = ask::Questions::at(dir.path().join("questions"));
11046
11047        let mut q = crate::ask::Question::new(
11048            "20260101-000001-main".to_owned(),
11049            crate::conduct::NODE.to_owned(),
11050            "conduct".to_owned(),
11051            "Is the setup done?".to_owned(),
11052            String::new(),
11053            Vec::new(),
11054        );
11055        q.abandon("no answer within 60s of asking");
11056        questions.put(&mut q).unwrap();
11057
11058        let mut blocked = task();
11059        blocked.id = "20260101-000001-main".to_owned();
11060        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11061        queue.put(&mut blocked).unwrap();
11062
11063        resolve_blockers(&queue, &questions);
11064
11065        let after = queue.get(&blocked.id).unwrap();
11066        assert_eq!(
11067            after.status,
11068            TaskStatus::Held,
11069            "never left blocked on nothing"
11070        );
11071        assert!(!after.operator_held(), "a machine hold, for triage");
11072        assert!(
11073            after
11074                .hold_reason
11075                .as_deref()
11076                .unwrap_or_default()
11077                .contains("went unanswered")
11078        );
11079    }
11080
11081    #[test]
11082    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11083        // Reproduces the reported bug (task 3958): a task held out of
11084        // attempts, blocked on a `crate::conduct` follow-up question, must
11085        // come back `held` once that question is answered - never `queued`,
11086        // whatever the answer said - or it silently re-enters the
11087        // competition queue with its attempts already exhausted.
11088        let dir = tempfile::tempdir().unwrap();
11089        let queue = Queue::at(dir.path().join("queue"));
11090        let questions = ask::Questions::at(dir.path().join("questions"));
11091
11092        let mut q = crate::ask::Question::new(
11093            "20260101-000001-main".to_owned(),
11094            crate::conduct::NODE.to_owned(),
11095            "conduct".to_owned(),
11096            "How should this be handled?".to_owned(),
11097            String::new(),
11098            Vec::new(),
11099        );
11100        questions.put(&mut q).unwrap();
11101        q.answer(crate::ask::Answer::Text(
11102            "leave it held, a human will look at it later".to_owned(),
11103        ))
11104        .unwrap();
11105        questions.put(&mut q).unwrap();
11106
11107        let mut held = task();
11108        held.id = "20260101-000001-main".to_owned();
11109        held.hold_machine(Some("out of attempts".to_owned()));
11110        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11111        queue.put(&mut held).unwrap();
11112
11113        resolve_blockers(&queue, &questions);
11114
11115        let after = queue.get(&held.id).unwrap();
11116        assert_eq!(after.status, TaskStatus::Held);
11117        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11118        assert_eq!(
11119            after.answers[0].answer,
11120            "leave it held, a human will look at it later"
11121        );
11122    }
11123
11124    #[test]
11125    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11126        let dir = tempfile::tempdir().unwrap();
11127        let queue = Queue::at(dir.path().join("queue"));
11128        let questions = ask::Questions::at(dir.path().join("questions"));
11129        let mut dep = task();
11130        dep.id = "20260101-000001-gone".to_owned();
11131        queue.put(&mut dep).unwrap();
11132        let mut blocked = task();
11133        blocked.id = "20260101-000003-main".to_owned();
11134        blocked.block(vec![dep.id.clone()], None);
11135        queue.put(&mut blocked).unwrap();
11136
11137        // Claimed, so `remove` cannot rewrite it and the resolver must.
11138        let claim = queue.claim(&blocked.id).unwrap();
11139        queue.remove(&dep.id, false, &questions).unwrap();
11140        drop(claim);
11141        resolve_blockers(&queue, &questions);
11142
11143        let after = queue.get(&blocked.id).unwrap();
11144        assert_eq!(after.status, TaskStatus::Queued);
11145        assert!(after.blocked_by.is_empty());
11146    }
11147
11148    #[test]
11149    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11150        // Reproduces the reported bug: a task blocked on a task id that was
11151        // removed (`magi task rm`, or deleted by hand) can never see that id
11152        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11153        // would otherwise leave the task `blocked` forever with no way for an
11154        // operator to find out why.
11155        let dir = tempfile::tempdir().unwrap();
11156        let queue = Queue::at(dir.path().join("queue"));
11157        let questions = ask::Questions::at(dir.path().join("questions"));
11158
11159        let mut still_going = task();
11160        still_going.id = "20260101-000002-dep1".to_owned();
11161        queue.put(&mut still_going).unwrap();
11162
11163        let mut blocked = task();
11164        blocked.id = "20260101-000003-main".to_owned();
11165        blocked.block(
11166            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11167            Some("waits on both".to_owned()),
11168        );
11169        queue.put(&mut blocked).unwrap();
11170
11171        resolve_blockers(&queue, &questions);
11172
11173        let after = queue.get(&blocked.id).unwrap();
11174        assert_eq!(
11175            after.status,
11176            TaskStatus::Held,
11177            "a missing dependency must not leave the task blocked forever"
11178        );
11179        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11180        assert!(after.blocked_by.is_empty());
11181        let reason = after.hold_reason.as_deref().unwrap_or_default();
11182        assert!(
11183            reason.contains("20260101-000001-gone"),
11184            "the missing id must be named so an operator can tell what happened: {reason}"
11185        );
11186        assert!(
11187            reason.contains(&still_going.id),
11188            "the still-valid dependency must not silently vanish from the record: {reason}"
11189        );
11190    }
11191
11192    #[test]
11193    fn instruction_for_is_unchanged_without_any_answers() {
11194        let t = task();
11195        assert_eq!(instruction_for(&t), t.instruction);
11196    }
11197
11198    #[test]
11199    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11200        let dir = tempfile::tempdir().unwrap();
11201        let q = Queue::at(dir.path().join("queue"));
11202        let src = dir.path().join("shot.png");
11203        std::fs::write(&src, "x").unwrap();
11204        let mut t = task();
11205        q.attach(&mut t, &[src]).unwrap();
11206        let paths = task_attachments(&q, &t).unwrap();
11207        assert_eq!(paths.len(), 1);
11208        assert!(paths[0].is_absolute() && paths[0].is_file());
11209        std::fs::remove_file(&paths[0]).unwrap();
11210        let err = task_attachments(&q, &t).unwrap_err().to_string();
11211        assert!(err.contains("shot.png"), "{err}");
11212    }
11213
11214    #[tokio::test]
11215    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11216        let dir = tempfile::tempdir().unwrap();
11217        let queue_path = dir.path().join("queue");
11218        let queue = Queue::at(queue_path.clone());
11219        let mut t = task();
11220        t.source = Source::Agent {
11221            run: "originating-chat".into(),
11222            node: crate::queue::CHAT_NODE.into(),
11223        };
11224        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11225            stage: "config-fetch",
11226            target: "origin/main".into(),
11227        });
11228        record_config_failure(&mut t, &fetch);
11229        t.hold_machine(Some(format!("{fetch:#}")));
11230        let fetch_key = t.chat_notice_due().unwrap();
11231        t.chat_notices.push(fetch_key.clone());
11232        queue.put(&mut t).unwrap();
11233
11234        let queue = Queue::at(queue_path);
11235        let mut t = queue.get(&t.id).unwrap();
11236        let a = dir.path().join("a.toml");
11237        let b = dir.path().join("b.toml");
11238        for (path, text, new_cause) in [
11239            (&a, "[graph", true),
11240            (&a, "[verify", false),
11241            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11242            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11243        ] {
11244            t.release_operator("test", None);
11245            std::fs::write(path, text).unwrap();
11246            let error = Config::discover_fetched(dir.path(), Some(path))
11247                .await
11248                .unwrap_err();
11249            record_config_failure(&mut t, &error);
11250            t.hold_machine(Some(format!("{error:#}")));
11251            let due = t.chat_notice_due();
11252            assert_eq!(due.is_some(), new_cause, "{error:#}");
11253            if let Some(key) = due {
11254                assert_ne!(key, fetch_key);
11255                t.chat_notices.push(key);
11256            }
11257        }
11258        t.succeed();
11259        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11260    }
11261
11262    #[test]
11263    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11264        let dir = tempfile::tempdir().unwrap();
11265        let queue_path = dir.path().join("queue");
11266        let queue = Queue::at(queue_path.clone());
11267        let mut t = task();
11268        t.source = crate::queue::Source::Agent {
11269            run: "originating-chat".into(),
11270            node: crate::queue::CHAT_NODE.into(),
11271        };
11272        let a = dir.path().join("a.png");
11273        let b = dir.path().join("b.png");
11274        std::fs::write(&a, "a").unwrap();
11275        std::fs::write(&b, "b").unwrap();
11276        queue.attach(&mut t, &[a, b]).unwrap();
11277        let paths = task_attachments(&queue, &t).unwrap();
11278        for path in &paths {
11279            std::fs::remove_file(path).unwrap();
11280        }
11281        let missing = task_attachments(&queue, &t).unwrap_err();
11282        t.attempts += 1;
11283        let reason = missing.to_string();
11284        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11285        let first = t.chat_notice_due().expect("first attachment notice");
11286        t.chat_notices.push(first.clone());
11287        queue.put(&mut t).unwrap();
11288
11289        let queue = Queue::at(queue_path.clone());
11290        let mut t = queue.get(&t.id).unwrap();
11291        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11292        t.release_operator("test", None);
11293        t.attempts += 1;
11294        let missing = task_attachments(&queue, &t).unwrap_err();
11295        t.fail_startup_target(
11296            "startup-attachments",
11297            missing.name,
11298            "same missing attachment with regenerated wording",
11299            1,
11300        );
11301        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11302
11303        std::fs::write(&paths[0], "restored").unwrap();
11304        t.release_operator("test", None);
11305        t.attempts += 1;
11306        let missing = task_attachments(&queue, &t).unwrap_err();
11307        let reason = missing.to_string();
11308        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11309        let second = t
11310            .chat_notice_due()
11311            .expect("different attachment must notify");
11312        assert_ne!(first, second);
11313        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11314    }
11315
11316    #[test]
11317    fn resumed_instruction_is_unchanged_without_any_answers() {
11318        let t = task();
11319        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11320    }
11321
11322    #[test]
11323    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11324        let mut t = task();
11325        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11326        // The run's own instruction on disk predates the answer: it is the
11327        // plain original text `Runner::start` saved before the operator was
11328        // ever asked anything.
11329        let old = t.instruction.clone();
11330
11331        let refreshed = resumed_instruction(&old, &t);
11332        assert!(refreshed.starts_with(&old), "the original text is kept");
11333        assert!(refreshed.contains("Which backend?"));
11334        assert!(refreshed.contains("SQLite"));
11335    }
11336
11337    #[test]
11338    fn resumed_instruction_keeps_an_original_answers_heading() {
11339        let mut t = task();
11340        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11341        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11342
11343        let refreshed = resumed_instruction(&t.instruction, &t);
11344
11345        assert!(
11346            refreshed.starts_with(&t.instruction),
11347            "an answers heading in the original instruction is not the appended block"
11348        );
11349        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11350        assert!(refreshed.contains("Which backend?"));
11351        assert!(refreshed.contains("SQLite"));
11352
11353        let repeated = resumed_instruction(&refreshed, &t);
11354        assert_eq!(
11355            repeated, refreshed,
11356            "only the final appended block is refreshed"
11357        );
11358    }
11359
11360    #[test]
11361    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11362        let mut t = task();
11363        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11364
11365        // A first resume appends the block; a second resume of the same run,
11366        // with no new answer in between, must reproduce exactly the same
11367        // text rather than appending the block a second time.
11368        let once = resumed_instruction(&t.instruction, &t);
11369        let twice = resumed_instruction(&once, &t);
11370        assert_eq!(once, twice);
11371        assert_eq!(once.matches("Which backend?").count(), 1);
11372
11373        // A later answer replaces the block wholesale rather than growing it.
11374        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11375        let refreshed = resumed_instruction(&once, &t);
11376        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11377        assert!(refreshed.contains("Which backend?"));
11378        assert!(refreshed.contains("Which cache?"));
11379    }
11380
11381    #[test]
11382    fn prepare_instruction_covers_all_three_starters() {
11383        let mut t = task();
11384        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11385
11386        // Start: a fresh run gets the task text plus every answer so far —
11387        // exactly `instruction_for`.
11388        assert_eq!(
11389            prepare_instruction(&Starter::Start, None, &t),
11390            Some(instruction_for(&t))
11391        );
11392
11393        // Resume: the run's prior instruction is refreshed with the answer,
11394        // not discarded and not left stale.
11395        let old = t.instruction.clone();
11396        assert_eq!(
11397            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11398            Some(resumed_instruction(&old, &t))
11399        );
11400
11401        // Review: a review-only pass builds its own instruction from the
11402        // branch's history in `crate::graph`, with no task statement at all -
11403        // this boundary must leave it alone.
11404        assert_eq!(
11405            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11406            None
11407        );
11408    }
11409
11410    #[test]
11411    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11412        assert_eq!(
11413            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11414            Starter::Review("magi/eba2/A".to_owned())
11415        );
11416    }
11417
11418    #[test]
11419    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11420        assert_eq!(
11421            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11422            Starter::Start,
11423            "a vanished review branch must not fall back to resuming the old run either"
11424        );
11425    }
11426
11427    #[test]
11428    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11429        let mut t = task();
11430        t.start("old-run".to_owned());
11431        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11432        t.release();
11433        let branch = t.review_branch.take();
11434        assert_eq!(
11435            choose_starter(branch.as_deref(), true, Some("old-run")),
11436            Starter::Review("magi/eba2/A".to_owned()),
11437            "a review wins over resuming the old run"
11438        );
11439    }
11440
11441    #[test]
11442    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11443        assert_eq!(
11444            choose_starter(None, false, Some("some-run")),
11445            Starter::Resume("some-run".to_owned())
11446        );
11447        assert_eq!(choose_starter(None, false, None), Starter::Start);
11448    }
11449
11450    #[test]
11451    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11452        let mut released = task();
11453        released.start("stalled-run".to_owned());
11454        released.requeue();
11455        let unfinished = (!released.fresh_start)
11456            .then(|| Some("stalled-run".to_owned()))
11457            .flatten();
11458        assert_eq!(
11459            choose_starter(None, false, unfinished.as_deref()),
11460            Starter::Start,
11461            "release keeps run history but must not resume it"
11462        );
11463        assert_eq!(released.runs, ["stalled-run"]);
11464    }
11465
11466    fn stopped_public_run(status: RunStatus) -> RunState {
11467        let mut state = run_state(status);
11468        state.driver_exited = true;
11469        state.config.graph.land = true;
11470        state.config.graph.review_rounds = 1;
11471        state.reviews = vec![review_round(1)];
11472        state.merge = Some(crate::run::MergeOutcome {
11473            mode: MergeMode::Pr,
11474            ok: false,
11475            detail: "landing stopped".into(),
11476            empty: false,
11477        });
11478        state.pr = Some(crate::run::PrRecord {
11479            url: "https://example.test/pull/1".into(),
11480            number: 1,
11481            state: "open".into(),
11482            checks: "red".into(),
11483            round: 1,
11484            rounds: 1,
11485            red_at_merge: Vec::new(),
11486        });
11487        state
11488    }
11489
11490    #[test]
11491    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11492        for status in [RunStatus::Blocked, RunStatus::Gating] {
11493            let home = tempfile::tempdir().unwrap();
11494            let mut state = stopped_public_run(status);
11495            state.save_under(home.path()).unwrap();
11496            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11497            assert!(!exhausted_review_budget(&state));
11498            let mut task = held_task_with(&state.id);
11499            task.release();
11500            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11501            assert_eq!(
11502                choose_starter(None, false, unfinished.as_deref()),
11503                Starter::Resume(state.id.clone())
11504            );
11505            let question = action_question(&state.id, resume_action(&state.id));
11506            assert_eq!(
11507                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11508                ActionDecision::Resume(state.id.clone())
11509            );
11510            // The control-plane command uses this same preflight before pinning.
11511            assert_eq!(
11512                crate::resume::validate(home.path(), &state.id).unwrap().id,
11513                state.id
11514            );
11515            let queue = Queue::at(home.path().join("queue"));
11516            let mut controlled = Task::new(
11517                "resume land".into(),
11518                state.instruction.clone(),
11519                state.repo.clone(),
11520                Source::Agent {
11521                    run: "talk".into(),
11522                    node: crate::queue::CHAT_NODE.into(),
11523                },
11524            );
11525            controlled.runs.push(state.id.clone());
11526            controlled.hold_machine(Some("land stopped".into()));
11527            queue.put(&mut controlled).unwrap();
11528            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11529            assert_eq!(resumed.status, TaskStatus::Queued);
11530            assert_eq!(
11531                resumed.resume_override.unwrap().pinned_run,
11532                Some(state.id.clone())
11533            );
11534            assert_eq!(resumed.attempts, 0);
11535        }
11536    }
11537
11538    #[test]
11539    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11540        for review_rounds in [0, 1] {
11541            let home = tempfile::tempdir().unwrap();
11542            let mut state = run_state(RunStatus::Blocked);
11543            state.config.graph.review_rounds = review_rounds;
11544            if review_rounds > 0 {
11545                let mut review = review_round(1);
11546                review.clean = true;
11547                state.reviews = vec![review];
11548            }
11549            state.gate_ran = true;
11550            state.gate = vec![crate::run::CommandOutcome {
11551                command: "verify".into(),
11552                code: Some(1),
11553                output_tail: "gate failed after repair budget exhausted".into(),
11554                duration_ms: 0,
11555                resource_blocked: false,
11556            }];
11557            state.save_under(home.path()).unwrap();
11558            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11559            assert!(exhausted_review_budget(&state));
11560            let mut task = held_task_with(&state.id);
11561            task.release();
11562            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11563            let question = action_question(&state.id, resume_action(&state.id));
11564            assert_ne!(
11565                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11566                ActionDecision::Resume(state.id.clone())
11567            );
11568            let error = crate::resume::validate(home.path(), &state.id)
11569                .unwrap_err()
11570                .to_string();
11571            assert!(!error.contains("review budget exhausted"), "{error}");
11572            assert!(
11573                error.contains(if review_rounds == 0 {
11574                    "review is disabled"
11575                } else {
11576                    "gate already ran"
11577                }),
11578                "{error}"
11579            );
11580
11581            // An unexecuted gate still has work to do with or without reviews.
11582            state.gate_ran = false;
11583            state.gate.clear();
11584            assert!(!exhausted_review_budget(&state));
11585            assert_eq!(
11586                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11587                Some(state.id)
11588            );
11589        }
11590    }
11591
11592    #[test]
11593    fn resource_blocked_verification_resumes_the_same_run() {
11594        for (kind, stage) in [
11595            ("cache", "clean"),
11596            ("coordination", "clean"),
11597            ("cache", "review-e2e"),
11598            ("coordination", "no-reviews"),
11599            ("coordination", "handoff"),
11600        ] {
11601            let home = tempfile::tempdir().unwrap();
11602            let mut state = run_state(RunStatus::Blocked);
11603            state.config.graph.review_rounds = 1;
11604            let mut review = review_round(1);
11605            review.clean = true;
11606            state.reviews = vec![review];
11607            if stage == "review-e2e" {
11608                let review = &mut state.reviews[0];
11609                review.clean = false;
11610                review.blocking = 1;
11611                review.e2e = vec![crate::run::CommandOutcome {
11612                    command: "verify".into(),
11613                    code: None,
11614                    output_tail: "resource wait expired".into(),
11615                    duration_ms: 0,
11616                    resource_blocked: true,
11617                }];
11618            } else if stage == "no-reviews" {
11619                state.config.graph.review_rounds = 0;
11620                state.reviews.clear();
11621            } else if stage == "handoff" {
11622                // A completed final verification can hand off to the gate
11623                // even when the review still carries contested findings.
11624                let review = &mut state.reviews[0];
11625                review.clean = false;
11626                review.blocking = 1;
11627                review.e2e = vec![crate::run::CommandOutcome {
11628                    command: "verify".into(),
11629                    code: Some(0),
11630                    output_tail: String::new(),
11631                    duration_ms: 0,
11632                    resource_blocked: false,
11633                }];
11634            }
11635            state.gate_ran = false;
11636            state.resource_block = Some(crate::run::ResourceBlock {
11637                cause: crate::run::ResourceBlockCause::Other,
11638                node: if stage == "review-e2e" {
11639                    "review"
11640                } else {
11641                    "gate"
11642                }
11643                .into(),
11644                kind: kind.into(),
11645                detail: "resource wait expired".into(),
11646                at: jiff::Timestamp::now(),
11647            });
11648            state.save_under(home.path()).unwrap();
11649            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11650            assert!(!exhausted_review_budget(&state));
11651            let mut task = held_task_with(&state.id);
11652            task.release();
11653            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11654            assert_eq!(
11655                choose_starter(None, false, unfinished.as_deref()),
11656                Starter::Resume(state.id.clone())
11657            );
11658            let question = action_question(&state.id, resume_action(&state.id));
11659            assert_eq!(
11660                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11661                ActionDecision::Resume(state.id.clone())
11662            );
11663            assert_eq!(
11664                crate::resume::validate(home.path(), &state.id).unwrap().id,
11665                state.id
11666            );
11667            let queue = Queue::at(home.path().join("queue"));
11668            let mut controlled = Task::new(
11669                "resume verification".into(),
11670                state.instruction.clone(),
11671                state.repo.clone(),
11672                Source::Agent {
11673                    run: "talk".into(),
11674                    node: crate::queue::CHAT_NODE.into(),
11675                },
11676            );
11677            controlled.runs.push(state.id.clone());
11678            controlled.hold_machine(Some("verification resource unavailable".into()));
11679            queue.put(&mut controlled).unwrap();
11680            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11681            assert_eq!(resumed.status, TaskStatus::Queued);
11682            assert_eq!(
11683                resumed.resume_override.unwrap().pinned_run,
11684                Some(state.id.clone())
11685            );
11686            assert_eq!(resumed.attempts, 0);
11687
11688            // A genuinely unresolved final review still exhausts the budget.
11689            state.config.graph.review_rounds = 1;
11690            let mut unresolved = review_round(1);
11691            unresolved.blocking = 1;
11692            state.reviews = vec![unresolved];
11693            state.resource_block = None;
11694            state.save_under(home.path()).unwrap();
11695            assert!(exhausted_review_budget(&state));
11696            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11697        }
11698    }
11699
11700    #[tokio::test]
11701    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11702        if !crate::standalone_test(
11703            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11704        ) {
11705            return;
11706        }
11707        let home = tempfile::tempdir().unwrap();
11708        let mut owner = stopped_public_run(RunStatus::Blocked);
11709        owner.save_under(home.path()).unwrap();
11710        let history = vec![owner.id.clone()];
11711        let repo = owner.repo.clone();
11712        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11713        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11714        let initial =
11715            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11716        assert!(
11717            initial.is_pending(),
11718            "a busy record must not hold or resume the task"
11719        );
11720        owner.retired_to = Some("20260101-000001-bbbb".into());
11721        owner.save_under(home.path()).unwrap();
11722        drop(lock);
11723        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11724            .await
11725            .expect("ownership lock released")
11726            .expect("read settled owner");
11727        assert!(
11728            result.is_none(),
11729            "the retired owner must not be resumed from a stale read"
11730        );
11731    }
11732
11733    #[tokio::test]
11734    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11735        if !crate::standalone_test(
11736            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11737        ) {
11738            return;
11739        }
11740        let home = tempfile::tempdir().unwrap();
11741        let mut owner = stopped_public_run(RunStatus::Blocked);
11742        let repo = tempfile::tempdir().unwrap();
11743        crate::git::git(repo.path(), &["init"]).await.unwrap();
11744        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
11745        owner.id = "20260101-000000-aaaa".into();
11746        owner.save_under(home.path()).unwrap();
11747        let mut successor = run_state(RunStatus::Blocked);
11748        successor.id = "20260101-000001-bbbb".into();
11749        successor.save_under(home.path()).unwrap();
11750        let runs = vec![owner.id.clone(), successor.id.clone()];
11751        assert_eq!(
11752            public_resume_owner(home.path(), &runs, &owner.repo)
11753                .await
11754                .unwrap()
11755                .unwrap()
11756                .id,
11757            owner.id
11758        );
11759        let subdir = owner.repo.join("nested");
11760        std::fs::create_dir(&subdir).unwrap();
11761        assert_eq!(
11762            public_resume_owner(home.path(), &runs, &subdir)
11763                .await
11764                .unwrap()
11765                .unwrap()
11766                .id,
11767            owner.id
11768        );
11769        #[cfg(unix)]
11770        {
11771            let alias = home.path().join("repo-alias");
11772            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
11773            assert_eq!(
11774                public_resume_owner(home.path(), &runs, &alias.join("nested"))
11775                    .await
11776                    .unwrap()
11777                    .unwrap()
11778                    .id,
11779                owner.id
11780            );
11781        }
11782        let different = tempfile::tempdir().unwrap();
11783        crate::git::git(different.path(), &["init"]).await.unwrap();
11784        assert!(
11785            public_resume_owner(home.path(), &runs, different.path())
11786                .await
11787                .is_err()
11788        );
11789        std::fs::remove_file(
11790            home.path()
11791                .join("runs")
11792                .join(&successor.id)
11793                .join("run.json"),
11794        )
11795        .unwrap();
11796        assert!(
11797            public_resume_owner(home.path(), &runs, &owner.repo)
11798                .await
11799                .is_err()
11800        );
11801    }
11802
11803    #[test]
11804    fn an_ordinary_release_keeps_a_resumable_run_available() {
11805        let mut released = task();
11806        released.start("stalled-run".to_owned());
11807        released.release();
11808        let unfinished = (!released.fresh_start)
11809            .then(|| Some("stalled-run".to_owned()))
11810            .flatten();
11811        assert_eq!(
11812            choose_starter(None, false, unfinished.as_deref()),
11813            Starter::Resume("stalled-run".to_owned()),
11814            "manual release must preserve the normal resume path"
11815        );
11816    }
11817
11818    #[test]
11819    fn resume_refusals_explain_admission_without_changing_task_or_run() {
11820        crate::run::pin_test_home();
11821        use crate::handover::{ResumeRefusal, resume_refusal_under};
11822        let home = tempfile::tempdir().unwrap();
11823        let mut exhausted = run_state(RunStatus::Blocked);
11824        exhausted.driver_exited = true;
11825        exhausted.config.graph.review_rounds = 3;
11826        exhausted.reviews = (1..=3).map(review_round).collect();
11827        for refusal in [
11828            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
11829            ResumeRefusal::Status(RunStatus::Ready),
11830            ResumeRefusal::Released("20261022-000000-aaaa".into()),
11831            ResumeRefusal::Retired("retirement-successor".into()),
11832            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
11833        ] {
11834            let mut state = exhausted.clone();
11835            let expected = match refusal {
11836                ResumeRefusal::Status(_) => {
11837                    state.status = RunStatus::Ready;
11838                    "status `ready`"
11839                }
11840                ResumeRefusal::Released(ref target) => {
11841                    state.released_to = Some(target.clone());
11842                    "execution was released"
11843                }
11844                ResumeRefusal::Retired(ref target) => {
11845                    state.retired_to = Some(target.clone());
11846                    "execution was retired"
11847                }
11848                ResumeRefusal::OwnershipTransferred(ref target) => {
11849                    state.pr_taken_over_by = Some(target.clone());
11850                    "PR ownership was transferred"
11851                }
11852                _ => "review budget exhausted (3/3 rounds used)",
11853            };
11854            assert_eq!(
11855                resume_refusal_under(&state, Some(home.path())),
11856                Some(refusal.clone())
11857            );
11858            assert_eq!(
11859                refusal.successor(),
11860                state
11861                    .released_to
11862                    .as_deref()
11863                    .or(state.retired_to.as_deref())
11864                    .or(state.pr_taken_over_by.as_deref())
11865            );
11866            state.save_under(home.path()).unwrap();
11867            let queue = Queue::at(home.path().join("queue"));
11868            let mut task = Task::new(
11869                "retained implementation".into(),
11870                state.instruction.clone(),
11871                state.repo.clone(),
11872                Source::Agent {
11873                    run: "talk".into(),
11874                    node: crate::queue::CHAT_NODE.into(),
11875                },
11876            );
11877            task.runs.push(state.id.clone());
11878            task.hold_machine(Some("stopped".into()));
11879            queue.put(&mut task).unwrap();
11880            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
11881            let before_run = serde_json::to_value(&state).unwrap();
11882            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
11883                .unwrap_err()
11884                .to_string();
11885            assert!(error.contains(expected), "{error}");
11886            assert!(!error.contains("only a stalled or blocked"), "{error}");
11887            if matches!(refusal, ResumeRefusal::Status(_)) {
11888                assert!(
11889                    error.contains("is final; there is nothing left to resume"),
11890                    "{error}"
11891                );
11892            }
11893            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
11894                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
11895                assert!(error.contains("review-only successor with a new review budget"));
11896                assert!(error.contains("does not resume this run"));
11897            }
11898            for target in [
11899                &state.released_to,
11900                &state.retired_to,
11901                &state.pr_taken_over_by,
11902            ]
11903            .into_iter()
11904            .flatten()
11905            {
11906                let short = if state.retired_to.as_ref() == Some(target) {
11907                    target.as_str()
11908                } else {
11909                    crate::run::short_of(target)
11910                };
11911                assert!(
11912                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
11913                    "{error}"
11914                );
11915                if short != target {
11916                    assert!(!error.contains(target), "full successor id leaked: {error}");
11917                }
11918            }
11919            assert_eq!(
11920                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
11921                before_task
11922            );
11923            assert_eq!(
11924                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
11925                    .unwrap(),
11926                before_run
11927            );
11928            let question = action_question(&state.id, resume_action(&state.id));
11929            for phrases in [&PHRASES_EN, &PHRASES_JA] {
11930                let ActionDecision::Refuse(detail) =
11931                    decide_action(&task, &question, phrases, |_| Ok(state.clone()))
11932                else {
11933                    panic!("refusal expected");
11934                };
11935                assert!(detail.contains(expected), "{detail}");
11936            }
11937        }
11938        // Preserve predicate ordering, while keeping every recorded destination visible.
11939        exhausted.status = RunStatus::Ready;
11940        exhausted.released_to = Some("released".into());
11941        exhausted.retired_to = Some("retired".into());
11942        exhausted.pr_taken_over_by = Some("owner".into());
11943        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
11944        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
11945        let detail = reason.diagnostic(&exhausted);
11946        for target in ["released", "retired", "owner"] {
11947            assert!(detail.contains(&format!("magi show {target}")));
11948        }
11949    }
11950
11951    #[test]
11952    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
11953        let home = tempfile::tempdir().unwrap();
11954        let mut state = run_state(RunStatus::Blocked);
11955        state.driver_exited = true;
11956        state.config.graph.review_rounds = 1;
11957        state.reviews = vec![review_round(1)];
11958        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
11959        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
11960            let mut saved = state.clone();
11961            match checkpoint {
11962                "publication" => saved.pr_publication_pending = true,
11963                "approval" => {
11964                    saved.land_approval = Some(crate::run::LandApproval {
11965                        question: "approval".into(),
11966                        head: "head".into(),
11967                    })
11968                }
11969                "armed" => saved.land_armed_head = Some("head".into()),
11970                "landing" => saved.status = RunStatus::Landing,
11971                _ => {
11972                    let mut question = ask::Question::new(
11973                        saved.id.clone(),
11974                        "review".into(),
11975                        "review-1".into(),
11976                        "continue?".into(),
11977                        String::new(),
11978                        vec!["continue".into()],
11979                    );
11980                    ask::Questions::at(home.path().join("questions"))
11981                        .put(&mut question)
11982                        .unwrap();
11983                }
11984            }
11985            saved.save_under(home.path()).unwrap();
11986            assert!(
11987                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
11988                "{checkpoint}"
11989            );
11990            assert!(
11991                crate::resume::validate(home.path(), &saved.id).is_ok(),
11992                "{checkpoint}"
11993            );
11994        }
11995    }
11996
11997    #[test]
11998    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
11999        let mut state = run_state(RunStatus::Blocked);
12000        state.config.graph.review_rounds = 3;
12001        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12002        assert!(exhausted_review_budget(&state));
12003
12004        // One round still unused: resuming can still ask a reviewer something.
12005        state.reviews.pop();
12006        assert!(!exhausted_review_budget(&state));
12007
12008        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12009        // count: only a `Blocked` run re-enters the review loop on resume.
12010        let mut stalled = run_state(RunStatus::Stalled);
12011        stalled.config.graph.review_rounds = 1;
12012        stalled.reviews = vec![review_round(1)];
12013        assert!(!exhausted_review_budget(&stalled));
12014    }
12015
12016    fn review_round(round: usize) -> crate::run::ReviewRound {
12017        crate::run::ReviewRound {
12018            round,
12019            head: "deadbeef".to_owned(),
12020            verified_head: None,
12021            verified_at: None,
12022            reviews: Vec::new(),
12023            e2e: Vec::new(),
12024            verify_retried: false,
12025            e2e_deferred: false,
12026            e2e_defer_reason: None,
12027            fix: None,
12028            blocking: 0,
12029            answered: 1,
12030            expected: 1,
12031            clean: false,
12032            progressed: true,
12033            vote_split: false,
12034            reconsideration: Vec::new(),
12035            verdict: None,
12036        }
12037    }
12038
12039    #[test]
12040    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12041        let mut run = RunState::new(
12042            PathBuf::from("/repo"),
12043            "main".to_owned(),
12044            "abc1234def".to_owned(),
12045            "add retries".to_owned(),
12046            Config::default(),
12047        );
12048        run.status = RunStatus::Judging;
12049        run.parked = true;
12050        let mut task = Task::new(
12051            "add retries".to_owned(),
12052            "add retries".to_owned(),
12053            PathBuf::from("/repo"),
12054            crate::queue::Source::Human,
12055        );
12056        task.status = TaskStatus::Failed;
12057        task.runs = vec![run.id.clone()];
12058        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12059        assert!(with(&task, &run), "parked after judging is the case");
12060        let mut parked_task = task.clone();
12061        parked_task.status = TaskStatus::Parked;
12062        assert!(with(&parked_task, &run), "the Parked status is the case");
12063
12064        let mut not_parked = run.clone();
12065        not_parked.parked = false;
12066        not_parked.status = RunStatus::Stalled;
12067        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12068
12069        let mut fresh = task.clone();
12070        fresh.fresh_start = true;
12071        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12072
12073        let mut review = task.clone();
12074        review.review_branch = Some("magi/x/A".to_owned());
12075        assert!(!with(&review, &run), "review is ranked before resume");
12076
12077        let mut held = task.clone();
12078        held.status = TaskStatus::Held;
12079        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12080
12081        let mut released = run.clone();
12082        released.released_to = Some("20260901-000000-new1".to_owned());
12083        assert!(!with(&task, &released), "nothing left to resume into");
12084
12085        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12086            "unreadable"
12087        )));
12088    }
12089
12090    #[test]
12091    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12092        let mut released = RunState::new(
12093            PathBuf::from("/repo"),
12094            "main".to_owned(),
12095            "abc1234def".to_owned(),
12096            "add retries".to_owned(),
12097            Config::default(),
12098        );
12099        released.status = RunStatus::Blocked;
12100        assert_eq!(
12101            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12102            Some(released.id.clone())
12103        );
12104        released.released_to = Some("20260901-000000-new1".to_owned());
12105        assert_eq!(
12106            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12107            None,
12108            "there is nothing left to resume it into"
12109        );
12110    }
12111
12112    #[test]
12113    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12114        // Mirrors the failure this exists to close: a task's last run ended
12115        // `Blocked` with the review budget spent, `crate::conduct` chose
12116        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12117        // evidence), and without this check `attempt` would go on treating
12118        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12119        // review loop iterates zero times over an already-spent budget, so
12120        // the resumed run settles right back to `Blocked` having asked nobody
12121        // anything, and `Requeue`'s promised fresh competition never happens.
12122        let mut exhausted = RunState::new(
12123            PathBuf::from("/repo"),
12124            "main".to_owned(),
12125            "abc1234def".to_owned(),
12126            "add retries".to_owned(),
12127            Config::default(),
12128        );
12129        exhausted.status = RunStatus::Blocked;
12130        exhausted.config.graph.review_rounds = 1;
12131        exhausted.reviews = vec![review_round(1)];
12132
12133        assert_eq!(
12134            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12135            None,
12136            "an exhausted `Blocked` run must not be offered as resumable"
12137        );
12138
12139        // A `Blocked` run with rounds still unused is genuinely worth
12140        // resuming, and must still be found.
12141        let mut has_budget_left = RunState::new(
12142            PathBuf::from("/repo"),
12143            "main".to_owned(),
12144            "abc1234def".to_owned(),
12145            "add retries".to_owned(),
12146            Config::default(),
12147        );
12148        has_budget_left.status = RunStatus::Blocked;
12149        has_budget_left.config.graph.review_rounds = 3;
12150        has_budget_left.reviews = vec![review_round(1)];
12151
12152        assert_eq!(
12153            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12154                Ok(has_budget_left.clone())
12155            }),
12156            Some(has_budget_left.id.clone())
12157        );
12158    }
12159
12160    #[test]
12161    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12162        let mut run = RunState::new(
12163            PathBuf::from("/repo"),
12164            "main".to_owned(),
12165            "abc1234def".to_owned(),
12166            "add retries".to_owned(),
12167            Config::default(),
12168        );
12169        run.status = RunStatus::Blocked;
12170        run.config.graph.review_rounds = 1;
12171        run.reviews = vec![review_round(1)];
12172        run.pr_publication_pending = true;
12173        assert_eq!(
12174            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12175            Some(run.id.clone()),
12176            "a spent review budget must not turn a failed publication into a re-competition"
12177        );
12178    }
12179
12180    #[test]
12181    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12182        let mut task = Task::new(
12183            "recover work".into(),
12184            "recover work".into(),
12185            PathBuf::from("/repo"),
12186            crate::queue::Source::Human,
12187        );
12188        let mut history = std::collections::BTreeMap::new();
12189        for index in 0..8 {
12190            let mut run = run_state(RunStatus::Blocked);
12191            run.id = format!("20260101-000000-{index:04}");
12192            run.base_commit = format!("upstream-{index}");
12193            // Seven empty newer attempts must not erase the old recovery owner.
12194            if index > 0 {
12195                run.candidates.clear();
12196            }
12197            task.runs.extend([run.id.clone(), run.id.clone()]);
12198            history.insert(run.id.clone(), run);
12199            task.requeue();
12200        }
12201        let check = |task: &Task, starter: &Starter, limit| {
12202            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12203        };
12204        assert!(
12205            check(&task, &Starter::Start, 8)
12206                .unwrap()
12207                .contains("8 unretired")
12208        );
12209        assert!(check(&task, &Starter::Start, 9).is_none());
12210        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12211        task.release_operator("owner", None);
12212        assert_eq!(task.attempts, 0);
12213        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12214        assert!(check(&restored, &Starter::Start, 8).is_some());
12215        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12216        assert!(check(&restored, &Starter::Start, 0).is_none());
12217    }
12218
12219    #[test]
12220    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12221        let mut task = Task::new(
12222            "recover work".into(),
12223            "recover work".into(),
12224            PathBuf::from("/repo"),
12225            crate::queue::Source::Human,
12226        );
12227        let mut run = run_state(RunStatus::Superseded);
12228        run.candidates.clear();
12229        task.runs.push(run.id.clone());
12230        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12231        run.retired_to = Some("authority".into());
12232        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12233        run.retired_to = None;
12234        run.released_to = Some("authority".into());
12235        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12236        assert!(
12237            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12238                .unwrap()
12239                .contains("Cannot verify")
12240        );
12241        // Resuming an existing owner needs no new inventory or worktree budget.
12242        assert!(
12243            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12244                panic!("resume must not load historical attempts")
12245            })
12246            .is_none()
12247        );
12248    }
12249
12250    #[test]
12251    fn retired_resume_requires_a_valid_same_repository_authority() {
12252        let mut source = run_state(RunStatus::Blocked);
12253        let mut empty = run_state(RunStatus::Blocked);
12254        empty.retired_to = Some(source.id.clone());
12255        let runs = vec![source.id.clone(), empty.id.clone()];
12256        let resolve = |source: &RunState, empty: &RunState| {
12257            unfinished_run_with(&runs, "fixture", |id| {
12258                if id == source.id {
12259                    Ok(source.clone())
12260                } else if id == empty.id {
12261                    Ok(empty.clone())
12262                } else {
12263                    bail!("unreadable authority")
12264                }
12265            })
12266        };
12267        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12268        assert_eq!(
12269            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12270            Starter::Resume(source.id.clone())
12271        );
12272        source.retired_to = Some(empty.id.clone());
12273        assert!(
12274            resolve(&source, &empty).is_none(),
12275            "cycles do not revive obsolete runs"
12276        );
12277        source.retired_to = None;
12278        source.repo = PathBuf::from("/another-repository");
12279        assert!(resolve(&source, &empty).is_none());
12280        source.repo = empty.repo.clone();
12281        source.released_to = Some("later".into());
12282        assert!(resolve(&source, &empty).is_none());
12283        empty.retired_to = Some("unlisted-run".into());
12284        assert!(resolve(&source, &empty).is_none());
12285    }
12286
12287    #[test]
12288    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12289        // A task whose history holds an *older* run that still looks
12290        // resumable (say, a competition `Runner::review` was started
12291        // alongside after that older run went `Stalled`) and a *newest* run
12292        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12293        // on this task must mean a fresh competition — falling back to the
12294        // stale, superseded `Stalled` run instead would resurrect history
12295        // nothing asked to revisit and silently defeat the requeue.
12296        let mut older_stalled = RunState::new(
12297            PathBuf::from("/repo"),
12298            "main".to_owned(),
12299            "abc1234def".to_owned(),
12300            "add retries".to_owned(),
12301            Config::default(),
12302        );
12303        older_stalled.status = RunStatus::Stalled;
12304
12305        let mut newest_exhausted = RunState::new(
12306            PathBuf::from("/repo"),
12307            "main".to_owned(),
12308            "abc1234def".to_owned(),
12309            "add retries".to_owned(),
12310            Config::default(),
12311        );
12312        newest_exhausted.status = RunStatus::Blocked;
12313        newest_exhausted.config.graph.review_rounds = 1;
12314        newest_exhausted.reviews = vec![review_round(1)];
12315
12316        assert_eq!(
12317            unfinished_run_with(
12318                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12319                "t",
12320                |_| Ok(newest_exhausted.clone())
12321            ),
12322            None,
12323            "the newest run is exhausted, so nothing here is worth resuming - \
12324             least of all the older, already-superseded run"
12325        );
12326    }
12327
12328    #[test]
12329    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12330        assert_eq!(
12331            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12332                Err(anyhow::anyhow!("fixture is absent"))
12333            }),
12334            None
12335        );
12336    }
12337
12338    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12339        let mut q = ask::Question::new(
12340            run.to_owned(),
12341            "implement".to_owned(),
12342            "impl-A".to_owned(),
12343            "continue?".to_owned(),
12344            String::new(),
12345            vec!["resume で続行する".to_owned(), "other".to_owned()],
12346        );
12347        q.actions.insert("resume で続行する".to_owned(), action);
12348        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12349            .unwrap();
12350        q
12351    }
12352
12353    fn held_task_with(run: &str) -> Task {
12354        let mut t = task();
12355        t.runs = vec![run.to_owned()];
12356        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12357        t
12358    }
12359
12360    fn resume_action(run: &str) -> ask::ChoiceAction {
12361        ask::ChoiceAction::Resume { run: run.into() }
12362    }
12363
12364    #[test]
12365    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12366        for parked in [false, true] {
12367            let mut t = task();
12368            t.start("A".into());
12369            t.start("B".into());
12370            assert_eq!(t.runs, vec!["A", "B"]);
12371            t.start("A".into());
12372            let mut resumed = run_state(RunStatus::Blocked);
12373            resumed.id = "A".into();
12374            resumed.parked = parked;
12375            resumed.driver_exited = true;
12376            t.hold_machine(Some("resumed run stopped".into()));
12377            let q = action_question("A", resume_action("A"));
12378            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12379            assert_eq!(
12380                decide_action(&t, &q, &PHRASES_EN, |id| {
12381                    assert_eq!(id, "A");
12382                    Ok(resumed.clone())
12383                }),
12384                ActionDecision::Resume("A".into())
12385            );
12386            assert_eq!(
12387                action_standing(&t, &action_question("B", resume_action("B"))),
12388                ActionStanding::Stale
12389            );
12390            t.release_operator("cli", None);
12391            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12392                assert_eq!(id, "A");
12393                Ok(resumed.clone())
12394            });
12395            assert_eq!(
12396                choose_starter(None, false, unfinished.as_deref()),
12397                Starter::Resume("A".into())
12398            );
12399            assert_eq!(t.runs, vec!["B", "A"]);
12400        }
12401    }
12402
12403    #[test]
12404    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12405        let mut state = crate::land::tests::repair_state(true, true);
12406        state.status = RunStatus::Landing;
12407        state.parked = true;
12408        state.driver_exited = true;
12409        let mut q = ask::Question::new(
12410            state.id.clone(),
12411            land::APPROVAL_NODE.into(),
12412            "land".into(),
12413            "Merge?".into(),
12414            String::new(),
12415            vec![land::APPROVE.into(), land::HOLD.into()],
12416        );
12417        q.id = state.id.clone();
12418        state.land_approval = Some(crate::run::LandApproval {
12419            question: q.id.clone(),
12420            head: "current-head".into(),
12421        });
12422        assert!(land::upgrade_repair_choice(&mut q, &state));
12423        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12424        let mut task = held_task_with(&state.id);
12425        task.status = TaskStatus::Parked;
12426        assert_eq!(
12427            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12428            ActionDecision::Resume(state.id.clone())
12429        );
12430        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12431        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12432        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12433        assert_eq!(
12434            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12435            ActionDecision::Resume(state.id.clone()),
12436            "a repair answer newer than the manual hold resumes the existing owner"
12437        );
12438        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12439        for answered_at in [q.answered_at, None] {
12440            let mut older = q.clone();
12441            older.answered_at = answered_at;
12442            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
12443                panic!("a later manual hold must prevent dispatch")
12444            });
12445            let ActionDecision::Refuse(reason) = refused else {
12446                panic!("expected an actionable refusal, got {refused:?}");
12447            };
12448            assert!(reason.contains("later operator decision"));
12449            assert!(reason.contains(&format!("magi task release {}", task.id)));
12450        }
12451        task.operator_decided_at = None;
12452        let mut superseded = state.clone();
12453        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12454        assert_eq!(
12455            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
12456            ActionDecision::Stale
12457        );
12458        for case in 1..4 {
12459            let mut changed = state.clone();
12460            match case {
12461                1 => changed.status = RunStatus::Blocked,
12462                2 => changed.released_to = Some("new-owner".into()),
12463                _ => changed.land_approval.as_mut().unwrap().head.clear(),
12464            }
12465            assert!(matches!(
12466                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
12467                ActionDecision::Refuse(_)
12468            ));
12469        }
12470        assert!(matches!(
12471            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
12472            ActionDecision::Refuse(_)
12473        ));
12474        task.runs.push("replacement".into());
12475        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12476        assert_eq!(
12477            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
12478                "old owner must not load"
12479            )),
12480            ActionDecision::Stale
12481        );
12482    }
12483
12484    #[test]
12485    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12486        let mut state = crate::land::tests::repair_state(true, true);
12487        state.status = RunStatus::Landing;
12488        state.parked = true;
12489        state.driver_exited = true;
12490        let mut q = ask::Question::new(
12491            state.id.clone(),
12492            land::APPROVAL_NODE.into(),
12493            "land".into(),
12494            "Merge?".into(),
12495            String::new(),
12496            vec![land::APPROVE.into(), land::HOLD.into()],
12497        );
12498        q.id = state.id.clone();
12499        state.land_approval = Some(crate::run::LandApproval {
12500            question: q.id.clone(),
12501            head: "current-head".into(),
12502        });
12503        state.save().unwrap();
12504        land::upgrade_repair_choice(&mut q, &state);
12505        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12506        Questions::open().put(&mut q).unwrap();
12507        let tmp = tempfile::tempdir().unwrap();
12508        let queue = Queue::at(tmp.path().join("queue"));
12509        let mut task = held_task_with(&state.id);
12510        task.status = TaskStatus::Parked;
12511        queue.put(&mut task).unwrap();
12512        let empty = Arc::new(tokio::sync::Semaphore::new(0));
12513        let free = Arc::new(tokio::sync::Semaphore::new(1));
12514        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12515        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12516        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12517        assert!(claim.permit.is_some());
12518        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12519        drop(claim);
12520        Questions::open()
12521            .update(&q.id, |q| {
12522                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12523                Ok(())
12524            })
12525            .unwrap();
12526        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12527        assert!(claim.permit.is_none());
12528        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12529    }
12530
12531    #[test]
12532    fn decide_action_resumes_only_the_latest_resumable_run() {
12533        let t = held_task_with("r1");
12534        let q = action_question("r1", resume_action("r1"));
12535        let load = |s: RunState| move |_: &str| Ok(s);
12536        assert_eq!(
12537            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
12538            ActionDecision::Resume("r1".into())
12539        );
12540        // Not the latest run of the task.
12541        let q_other = action_question("r1", resume_action("r0"));
12542        assert!(matches!(
12543            decide_action(
12544                &t,
12545                &q_other,
12546                &PHRASES_EN,
12547                load(run_state(RunStatus::Blocked))
12548            ),
12549            ActionDecision::Refuse(_)
12550        ));
12551        // A finished run cannot make progress.
12552        assert!(matches!(
12553            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
12554            ActionDecision::Refuse(_)
12555        ));
12556        // A released one either.
12557        let mut released = run_state(RunStatus::Blocked);
12558        released.released_to = Some("elsewhere".into());
12559        assert!(matches!(
12560            decide_action(&t, &q, &PHRASES_EN, load(released)),
12561            ActionDecision::Refuse(_)
12562        ));
12563        // Unreadable state is a refusal, never a fresh competition.
12564        assert!(matches!(
12565            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
12566            ActionDecision::Refuse(_)
12567        ));
12568    }
12569
12570    #[test]
12571    fn decide_action_ignores_a_question_about_an_earlier_run() {
12572        let mut t = held_task_with("r1");
12573        t.runs.push("r2".to_owned());
12574        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12575        assert_eq!(
12576            decide_action(
12577                &t,
12578                &action_question("r1", ask::ChoiceAction::Done),
12579                &PHRASES_EN,
12580                never
12581            ),
12582            ActionDecision::Stale
12583        );
12584    }
12585
12586    #[test]
12587    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
12588        let mut t = held_task_with("r1");
12589        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12590        assert_eq!(
12591            decide_action(
12592                &t,
12593                &action_question("r1", ask::ChoiceAction::Requeue),
12594                &PHRASES_EN,
12595                never
12596            ),
12597            ActionDecision::Requeue
12598        );
12599        let done_q = action_question("r1", ask::ChoiceAction::Done);
12600        assert_eq!(
12601            decide_action(&t, &done_q, &PHRASES_EN, never),
12602            ActionDecision::Done
12603        );
12604        t.mark_action_applied(&done_q.id);
12605        assert_eq!(
12606            decide_action(&t, &done_q, &PHRASES_EN, never),
12607            ActionDecision::Skip
12608        );
12609
12610        // A plain answer (no action for that label) does nothing.
12611        let mut plain = action_question("r1", ask::ChoiceAction::Done);
12612        plain.actions.clear();
12613        assert_eq!(
12614            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
12615            ActionDecision::Skip
12616        );
12617        // A running task is left alone.
12618        let mut running = held_task_with("r1");
12619        running.status = TaskStatus::Running;
12620        assert_eq!(
12621            decide_action(
12622                &running,
12623                &action_question("r1", ask::ChoiceAction::Done),
12624                &PHRASES_EN,
12625                never
12626            ),
12627            ActionDecision::Skip
12628        );
12629    }
12630
12631    #[test]
12632    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
12633        crate::run::pin_test_home();
12634        for legacy in [false, true] {
12635            let dir = tempfile::tempdir().unwrap();
12636            let queue = Queue::at(dir.path().join("queue"));
12637            let questions = Questions::at(dir.path().join("questions"));
12638            let run = "20260101-000000-hold";
12639            let mut task = held_task_with(run);
12640            task.status = TaskStatus::Parked;
12641            let mut q = ask::Question::new(
12642                run.into(),
12643                land::APPROVAL_NODE.into(),
12644                "land".into(),
12645                "Repair?".into(),
12646                String::new(),
12647                vec![land::REPAIR.into()],
12648            );
12649            q.actions.insert(land::REPAIR.into(), resume_action(run));
12650            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12651            // Deterministically order the answer before the actual manual hold.
12652            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12653            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
12654            questions.put(&mut q).unwrap();
12655            task.hold_manual(Some("Keep this PR paused".into()));
12656            if legacy {
12657                task.hold_source = None;
12658            }
12659            queue.put(&mut task).unwrap();
12660
12661            apply_task_choice_actions(&queue, &questions, dir.path());
12662            let after = queue.get(&task.id).unwrap();
12663            assert!(after.operator_held());
12664            assert_eq!(after.hold_source, task.hold_source);
12665            assert_eq!(after.operator_decided_at, task.operator_decided_at);
12666            assert_eq!(after.runs, task.runs);
12667            assert_eq!(after.instruction, task.instruction);
12668            assert!(after.resume_override.is_none());
12669            assert!(after.action_applied(&q.id));
12670            let reason = after.hold_reason.as_deref().unwrap();
12671            assert!(reason.starts_with("Keep this PR paused"));
12672            assert!(reason.contains("later operator decision"));
12673            assert!(reason.contains(&format!("magi task release {}", task.id)));
12674
12675            for recovery in [
12676                crate::conduct::Recovery::Review,
12677                crate::conduct::Recovery::Requeue,
12678            ] {
12679                crate::conduct::apply(
12680                    &queue,
12681                    &questions,
12682                    &crate::conduct::Verdict {
12683                        decisions: vec![crate::conduct::Decision {
12684                            id: task.id.clone(),
12685                            recovery: Some(recovery),
12686                            ..Default::default()
12687                        }],
12688                    },
12689                )
12690                .unwrap();
12691            }
12692            // Reconciliation is idempotent, and automatic recovery cannot
12693            // reopen this owner after it observes the rejected repair answer.
12694            apply_task_choice_actions(&queue, &questions, dir.path());
12695            let still_held = queue.get(&task.id).unwrap();
12696            assert!(still_held.operator_held());
12697            assert_eq!(still_held.hold_reason, after.hold_reason);
12698            assert_eq!(still_held.runs, task.runs);
12699            assert!(still_held.review_branch.is_none());
12700            assert!(!still_held.fresh_start);
12701            assert!(queue.next_runnable().is_none());
12702        }
12703    }
12704
12705    #[test]
12706    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
12707        for held in [false, true] {
12708            for retry in [false, true] {
12709                let dir = tempfile::tempdir().unwrap();
12710                let queue = Queue::at(dir.path().join("queue"));
12711                let questions = Questions::at(dir.path().join("questions"));
12712                let home = dir.path().join("home");
12713                let mut t = task();
12714                if held {
12715                    t.hold_machine(Some("driver state unknown".into()));
12716                }
12717                queue.put(&mut t).unwrap();
12718                let verdict = serde_json::from_value(serde_json::json!({
12719                    "decisions": [{
12720                        "id": t.id,
12721                        "question": "Driver state unknown; retry the checks or hold?",
12722                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
12723                        "actions": {
12724                            "daemon: recheck and retry": {"do": "requeue"},
12725                            "daemon: hold the task": {"do": "hold"}
12726                        }
12727                    }]
12728                }))
12729                .unwrap();
12730                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
12731                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12732                let mut q = questions.list().pop().unwrap();
12733                let choice = if retry {
12734                    "daemon: recheck and retry"
12735                } else {
12736                    "daemon: hold the task"
12737                };
12738                assert_eq!(q.actions.len(), 2);
12739                q.answer(ask::Answer::Choice(choice.into())).unwrap();
12740                questions.put(&mut q).unwrap();
12741
12742                // A Web answer does not remove the deputy's fresh lease.
12743                questions.beat(&q.id, ask::WaiterKind::Deputy);
12744                for _ in 0..2 {
12745                    resolve_blockers(&queue, &questions);
12746                    apply_task_choice_actions(&queue, &questions, &home);
12747                    let waiting = queue.get(&t.id).unwrap();
12748                    assert_eq!(waiting.status, TaskStatus::Blocked);
12749                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
12750                    assert!(waiting.answers.is_empty());
12751                    assert!(!waiting.action_applied(&q.id));
12752                    assert!(runnable(&queue).is_empty());
12753                    let free = Arc::new(tokio::sync::Semaphore::new(1));
12754                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
12755                }
12756                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12757
12758                // Releasing the blocker and applying the operation share one save.
12759                resolve_blockers(&queue, &questions);
12760                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12761                apply_task_choice_actions(&queue, &questions, &home);
12762                let after = queue.get(&t.id).unwrap();
12763                assert_eq!(
12764                    after.status,
12765                    if retry {
12766                        TaskStatus::Queued
12767                    } else {
12768                        TaskStatus::Held
12769                    }
12770                );
12771                assert!(after.action_applied(&q.id));
12772                assert_eq!(after.operator_held(), !retry);
12773                assert_eq!(after.answers.len(), 1);
12774
12775                // A later operator decision must not replay this answer.
12776                let mut changed = after;
12777                if retry {
12778                    changed.hold_manual(Some("later hold".into()));
12779                } else {
12780                    changed.release_operator("test", None);
12781                }
12782                let expected = changed.status;
12783                queue.put(&mut changed).unwrap();
12784                apply_task_choice_actions(&queue, &questions, &home);
12785                assert_eq!(queue.get(&t.id).unwrap().status, expected);
12786            }
12787        }
12788    }
12789
12790    #[test]
12791    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
12792        let dir = tempfile::tempdir().unwrap();
12793        let queue = Queue::at(dir.path().join("queue"));
12794        let questions = Questions::at(dir.path().join("questions"));
12795        let home = dir.path().join("home");
12796        let mut state = run_state(RunStatus::Blocked);
12797        state.id = "20260101-000000-act1".to_owned();
12798        state.save_under(&home).unwrap();
12799
12800        let mut t = held_task_with(&state.id);
12801        queue.put(&mut t).unwrap();
12802        let mut q = action_question(&state.id, resume_action(&state.id));
12803        questions.put(&mut q).unwrap();
12804
12805        apply_task_choice_actions(&queue, &questions, &home);
12806        let after = queue.get(&t.id).unwrap();
12807        assert_eq!(after.status, TaskStatus::Queued);
12808        assert!(!after.fresh_start);
12809        assert!(after.action_applied(&q.id));
12810        let pin = after.resume_override.clone().unwrap();
12811        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
12812        assert!(pin.forced);
12813
12814        // Held again later: the same answer does not release it a second time.
12815        let mut again = queue.get(&t.id).unwrap();
12816        again.hold_machine(Some("later".into()));
12817        queue.put(&mut again).unwrap();
12818        apply_task_choice_actions(&queue, &questions, &home);
12819        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12820    }
12821
12822    #[test]
12823    fn a_delivered_answer_is_still_acted_on_exactly_once() {
12824        let dir = tempfile::tempdir().unwrap();
12825        let queue = Queue::at(dir.path().join("queue"));
12826        let questions = Questions::at(dir.path().join("questions"));
12827        let home = dir.path().join("home");
12828        let mut state = run_state(RunStatus::Blocked);
12829        state.id = "20260101-000000-act2".to_owned();
12830        state.save_under(&home).unwrap();
12831
12832        let mut t = held_task_with(&state.id);
12833        queue.put(&mut t).unwrap();
12834        let mut q = action_question(&state.id, resume_action(&state.id));
12835        q.answer_delivered = true;
12836        questions.put(&mut q).unwrap();
12837
12838        // Delivered, and the agent then died: the task is still held, so the
12839        // chosen action applies.
12840        apply_task_choice_actions(&queue, &questions, &home);
12841        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12842        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
12843
12844        // Held again: the same answer does nothing a second time.
12845        let mut again = queue.get(&t.id).unwrap();
12846        again.hold_machine(Some("later".into()));
12847        queue.put(&mut again).unwrap();
12848        apply_task_choice_actions(&queue, &questions, &home);
12849        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12850    }
12851
12852    #[test]
12853    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
12854        let dir = tempfile::tempdir().unwrap();
12855        let queue = Queue::at(dir.path().join("queue"));
12856        let questions = Questions::at(dir.path().join("questions"));
12857        let home = dir.path().join("home");
12858        let mut state = run_state(RunStatus::Blocked);
12859        state.id = "20260101-000000-act3".to_owned();
12860        state.save_under(&home).unwrap();
12861        let mut t = held_task_with(&state.id);
12862        queue.put(&mut t).unwrap();
12863        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
12864        questions.put(&mut q).unwrap();
12865
12866        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
12867        apply_task_choice_actions(&queue, &questions, &home);
12868        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12869
12870        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12871        apply_task_choice_actions(&queue, &questions, &home);
12872        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12873    }
12874
12875    #[test]
12876    fn action_standing_tells_the_reasons_apart() {
12877        let mut t = held_task_with("r1");
12878        let q = action_question("r1", ask::ChoiceAction::Requeue);
12879        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12880        let mut plain = q.clone();
12881        plain.actions.clear();
12882        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
12883
12884        // Applied wins over everything, even a running task.
12885        t.mark_action_applied(&q.id);
12886        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
12887
12888        // A newer attempt running: the old question is Stale, not Busy.
12889        let mut t = held_task_with("r1");
12890        t.start("r2".to_owned());
12891        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
12892        // The same question about the latest run just waits.
12893        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
12894        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12895        t.status = TaskStatus::Blocked;
12896        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12897
12898        // A conductor question is keyed by the task, never stale.
12899        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
12900        c.node = crate::conduct::NODE.to_owned();
12901        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
12902        assert!(!ActionStanding::Busy.daemon_owns());
12903    }
12904
12905    #[test]
12906    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
12907        let dir = tempfile::tempdir().unwrap();
12908        let queue = Queue::at(dir.path().join("queue"));
12909        let questions = Questions::at(dir.path().join("questions"));
12910        let home = dir.path().join("home");
12911        let mut state = run_state(RunStatus::Blocked);
12912        state.id = "20260101-000000-act4".to_owned();
12913        state.save_under(&home).unwrap();
12914        let mut t = held_task_with(&state.id);
12915        t.status = TaskStatus::Running;
12916        queue.put(&mut t).unwrap();
12917        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
12918        q.cwd = Some(dir.path().display().to_string());
12919        questions.put(&mut q).unwrap();
12920
12921        // While the task runs the daemon will not act, so the waiter still
12922        // delivers the word to the dead asker's seat ...
12923        let running = queue.get(&t.id).unwrap();
12924        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
12925        assert!(matches!(
12926            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
12927            crate::waiter::Action::Deliver(_)
12928        ));
12929        // ... and the daemon waits while the task runs, then applies once.
12930        apply_task_choice_actions(&queue, &questions, &home);
12931        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12932        let mut back = queue.get(&t.id).unwrap();
12933        back.hold_machine(Some("later".into()));
12934        queue.put(&mut back).unwrap();
12935        apply_task_choice_actions(&queue, &questions, &home);
12936        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
12937        let mut again = queue.get(&t.id).unwrap();
12938        again.hold_machine(Some("again".into()));
12939        queue.put(&mut again).unwrap();
12940        apply_task_choice_actions(&queue, &questions, &home);
12941        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12942    }
12943}