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`. `load` reads a
924/// run's state, as with [`unfinished_run_with`]. `home` must name that same
925/// store for driver leases and question checkpoints.
926///
927/// `Resume` only fires on the task's *latest* run, and only while that run
928/// could actually make progress ([`RunStatus::resumable`], not released, review
929/// budget left); an answer naming anything else is refused rather than
930/// reinterpreted as a fresh competition.
931fn decide_action<F>(
932    home: &Path,
933    task: &Task,
934    q: &ask::Question,
935    p: &Phrases,
936    load: F,
937) -> ActionDecision
938where
939    F: FnOnce(&str) -> Result<RunState>,
940{
941    let Some(action) = q.chosen_action() else {
942        return ActionDecision::Skip;
943    };
944    if task.action_applied(&q.id)
945        || matches!(
946            task.status,
947            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
948        )
949    {
950        return ActionDecision::Skip;
951    }
952    // A question about an earlier attempt must not act on a newer one. A
953    // conductor question is keyed by the task id, not a run, so it is exempt.
954    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
955        return ActionDecision::Stale;
956    }
957    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
958    let stopping = q.node == land::APPROVAL_NODE
959        && q.resolution()
960            .as_deref()
961            .is_some_and(crate::merge_decision::stops);
962    // An answer is the owner's decision as of when it was given: a manual hold
963    // placed before it (even after the question was asked) was seen and
964    // overruled by it, while a hold or release after it supersedes it.
965    let decision_at = q.answered_at.unwrap_or(q.asked_at);
966    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
967        return if repair || stopping {
968            ActionDecision::Refuse(format!(
969                "{} 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 {}`",
970                if repair { "repair" } else { "stop" },
971                q.id,
972                q.run,
973                task.id
974            ))
975        } else {
976            ActionDecision::Stale
977        };
978    }
979    match action {
980        a if a.maintenance() => ActionDecision::Skip,
981        ask::ChoiceAction::ResumeRun { .. }
982        | ask::ChoiceAction::ReleaseTask { .. }
983        | ask::ChoiceAction::RerunChecks { .. }
984        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
985        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
986        ask::ChoiceAction::Hold => ActionDecision::Hold,
987        ask::ChoiceAction::Done => ActionDecision::Done,
988        ask::ChoiceAction::Resume { run } => {
989            if task.runs.last() != Some(run) {
990                return ActionDecision::Refuse((p.resume_not_latest)(
991                    q.short(),
992                    ask::short_id(run),
993                ));
994            }
995            match load(run) {
996                Ok(s) if stopping => {
997                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
998                        || !s
999                            .land_approval
1000                            .as_ref()
1001                            .is_some_and(|binding| binding.question == q.id)
1002                    {
1003                        ActionDecision::Stale
1004                    } else if s.liveness_under(home, false) == Liveness::Live {
1005                        ActionDecision::Skip
1006                    } else if s.status == RunStatus::Landing
1007                        && !s.released()
1008                        && s.retired_to.is_none()
1009                    {
1010                        ActionDecision::Resume(run.clone())
1011                    } else {
1012                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1013                    }
1014                }
1015                Ok(s)
1016                    if q.node == land::APPROVAL_NODE
1017                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1018                {
1019                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1020                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1021                    {
1022                        // A live/manual driver already consumed or superseded
1023                        // this answer. Do not hold its fresh approval wait.
1024                        ActionDecision::Stale
1025                    } else if s.liveness_under(home, false) == Liveness::Live {
1026                        ActionDecision::Skip
1027                    } else if s.status != RunStatus::Landing
1028                        || s.released()
1029                        || s.reviews.is_empty()
1030                        || !implementers_match(task, &s)
1031                        || !s
1032                            .land_approval
1033                            .as_ref()
1034                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1035                    {
1036                        ActionDecision::Refuse(format!(
1037                            "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",
1038                            q.id, run, run
1039                        ))
1040                    } else {
1041                        ActionDecision::Resume(run.clone())
1042                    }
1043                }
1044                Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1045                    ActionDecision::Refuse("run already has a live driver".into())
1046                }
1047                Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1048                    None => ActionDecision::Resume(run.clone()),
1049                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1050                        q.short(),
1051                        ask::short_id(run),
1052                        &reason.diagnostic(&s),
1053                    )),
1054                },
1055                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1056                    q.short(),
1057                    ask::short_id(run),
1058                    &format!("{e:#}"),
1059                )),
1060            }
1061        }
1062    }
1063}
1064
1065/// The fixed prose the daemon writes into [`Task::last_error`] and
1066/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1067/// `triage::Wording` and `land::Words`: only English and Japanese are
1068/// translated, anything else falls back to English.
1069///
1070/// Rendered when the reason is *generated*, so a reason keeps the language it
1071/// was written in if the setting changes later. The notification frame
1072/// (`Task <id> is held:`) is not here and stays English.
1073///
1074/// Deliberately **not** translated, because other code reads them back by
1075/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1076/// and `gate red`. IDs, node names, paths and external error text are embedded
1077/// as they are.
1078struct Phrases {
1079    /// `{}` = status label, then the detail.
1080    graph_stopped: fn(&str, &str) -> String,
1081    quorum_lost: &'static str,
1082    /// Followed by the seats' names.
1083    quota_took_out: &'static str,
1084    /// Followed by the status label.
1085    run_ended: &'static str,
1086    /// Followed by the question's short id.
1087    waiting_for_answer: &'static str,
1088    recovered_running: &'static str,
1089    no_run_to_recover: &'static str,
1090    could_not_start: &'static str,
1091    resume_not_latest: fn(&str, &str) -> String,
1092    resume_cannot_progress: fn(&str, &str, &str) -> String,
1093    resume_unreadable: fn(&str, &str, &str) -> String,
1094    /// A takeover refusal: the operator-facing text. English is the error's own
1095    /// `Display`; a translation keeps the machine detail apart in parentheses.
1096    handover_refused: fn(&crate::handover::Refused) -> String,
1097    /// Appended to a refused handover's hold reason (leading space included).
1098    handover_hint: &'static str,
1099    /// (seats that never answered, review rounds) for the review loop's
1100    /// "refusing to call it clean" stop.
1101    reviewers_never_answered: fn(usize, usize) -> String,
1102}
1103
1104const PHRASES_EN: Phrases = Phrases {
1105    graph_stopped: |status, detail| {
1106        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1107    },
1108    quorum_lost: "the judging panel lost its quorum",
1109    quota_took_out: "; quota took out ",
1110    run_ended: "run ended ",
1111    waiting_for_answer: " - waiting for operator answer to question ",
1112    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1113    no_run_to_recover: "task was `running` with no live daemon and no readable \
1114                        run to recover; held for a human to check what happened",
1115    could_not_start: "could not start the run: ",
1116    resume_not_latest: |q, run| {
1117        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1118    },
1119    resume_cannot_progress: |q, run, reason| {
1120        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1121    },
1122    resume_unreadable: |q, run, e| {
1123        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1124    },
1125    handover_refused: |r| r.to_string(),
1126    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1127    reviewers_never_answered: |missing, rounds| {
1128        format!(
1129            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1130             refusing to call it clean"
1131        )
1132    },
1133};
1134
1135const PHRASES_JA: Phrases = Phrases {
1136    graph_stopped: |status, detail| {
1137        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1138    },
1139    quorum_lost: "審査パネルが定足数を失いました",
1140    quota_took_out: "。クォータで脱落: ",
1141    run_ended: "run 終了: ",
1142    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1143    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1144    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1145                        何が起きたか人が確認するため保留にしました",
1146    could_not_start: "run を開始できませんでした: ",
1147    resume_not_latest: |q, run| {
1148        format!(
1149            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1150        )
1151    },
1152    resume_cannot_progress: |q, run, reason| {
1153        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1154    },
1155    resume_unreadable: |q, run, e| {
1156        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1157    },
1158    handover_refused: |r| {
1159        use crate::handover::Refused;
1160        match r {
1161            Refused::Foreign { branch, path, why } => format!(
1162                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1163                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1164                 から、やり直してください(詳細: {why})"
1165            ),
1166            Refused::Unsafe { branch, path, why } => format!(
1167                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1168                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1169                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1170            ),
1171            Refused::ReleaseFailed { branch, path, run } => format!(
1172                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1173                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1174                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1175            ),
1176        }
1177    },
1178    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1179    reviewers_never_answered: |missing, rounds| {
1180        format!(
1181            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1182             クリーンとは認めません"
1183        )
1184    },
1185};
1186
1187fn phrases(language: &str) -> &'static Phrases {
1188    if crate::lang::is_japanese(language) {
1189        &PHRASES_JA
1190    } else {
1191        &PHRASES_EN
1192    }
1193}
1194
1195/// The language of the repository a task belongs to, read best-effort for the
1196/// paths that have no run (and so no config of their own) to ask. An unreadable
1197/// config is English, not an error: a hold reason must still get written.
1198fn language_of(task: &Task, fallback: &Path) -> String {
1199    crate::lang::of_repo(&repo_for(task, fallback))
1200}
1201
1202/// The task an answered question speaks for: the one whose runs include the
1203/// question's run, or - for a conductor question, filed under the task's own
1204/// id - the task with that id.
1205pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1206    if q.node == crate::conduct::NODE {
1207        return tasks.iter().find(|t| t.id == q.run);
1208    }
1209    tasks.iter().find(|t| t.runs.contains(&q.run))
1210}
1211
1212/// Legacy conductor prose never becomes a maintenance command by inference.
1213/// Replace unsupported open labels under the question lock before dispatch.
1214fn repair_choice_offers(questions: &Questions) {
1215    for q in questions.list().into_iter().filter(|q| {
1216        q.status.open()
1217            && q.node == crate::conduct::NODE
1218            && q.choices
1219                .iter()
1220                .any(|c| crate::choice_effect::describe(q, c).is_none())
1221    }) {
1222        let _ = questions.update(&q.id, |current| {
1223            if current.status.open() {
1224                crate::choice_effect::executable_conductor(current);
1225                if let Some(deputy) = &mut current.deputy {
1226                    deputy.brief = crate::deputy::brief(
1227                        &current.run,
1228                        &current.detail,
1229                        &current.choices,
1230                        &current.actions,
1231                    );
1232                }
1233            }
1234            Ok(())
1235        });
1236    }
1237}
1238
1239/// Apply answered typed choices. Only the daemon calls this in production;
1240/// deputies settle the question and never execute its actions.
1241pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1242    apply_maintenance_choices(queue, questions, home).await;
1243    apply_task_choice_actions(queue, questions, home);
1244}
1245
1246/// Apply bounded maintenance effects independently of question ownership: a
1247/// release watcher need not have a queue task, and a predecessor is another run.
1248async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1249    for q in questions.list() {
1250        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1251            continue;
1252        };
1253        // Receipt paths use question IDs, whose format is independent of run
1254        // IDs. Apply the question store's filename safety rule to both eras.
1255        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1256            continue;
1257        }
1258        let dir = home.join("choice-actions");
1259        if std::fs::create_dir_all(&dir).is_err() {
1260            continue;
1261        }
1262        let Ok(lock) = std::fs::OpenOptions::new()
1263            .create(true)
1264            .truncate(false)
1265            .write(true)
1266            .open(dir.join(format!("{}.lock", q.id)))
1267        else {
1268            continue;
1269        };
1270        if crate::pr_head::try_lock_file(&lock).is_err() {
1271            continue;
1272        }
1273        let fresh = !home
1274            .join("choice-actions")
1275            .join(format!("{}.json", q.id))
1276            .exists();
1277        let result = async {
1278            let receipt = dir.join(format!("{}.json", q.id));
1279            if receipt.exists() {
1280                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1281                anyhow::ensure!(
1282                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1283                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1284                );
1285                return Ok::<_, anyhow::Error>(());
1286            }
1287            // Never retry an uncertain external effect. The receipt is written
1288            // before calling gh, exactly like release_watch's rerun record.
1289            let record = |status: &str| -> anyhow::Result<()> {
1290                let tmp = receipt.with_extension("tmp");
1291                std::fs::write(
1292                    &tmp,
1293                    serde_json::to_vec(&serde_json::json!({
1294                        "action": action, "status": status,
1295                    }))?,
1296                )?;
1297                std::fs::rename(tmp, &receipt)?;
1298                Ok(())
1299            };
1300            let applied = async {
1301                match action {
1302                    ask::ChoiceAction::ResumeRun { run } => {
1303                        crate::resume::validate(home, run)?;
1304                        record("started")?;
1305                        let decided = q.answered_at.unwrap_or(q.asked_at);
1306                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1307                            crate::resume::validate_unqueued(home, run)?;
1308                            crate::resume::start(home, run.clone()).await?;
1309                        }
1310                    }
1311                    ask::ChoiceAction::ReleaseTask {
1312                        task,
1313                        held_at,
1314                        reason,
1315                    } => {
1316                        anyhow::ensure!(
1317                            queue.resolve_id(task)? == *task,
1318                            "task action requires an exact task ID"
1319                        );
1320                        let _claim = queue.claim(task)?;
1321                        let mut task = queue.get(task)?;
1322                        if task.action_applied(&q.id) {
1323                            return Ok(());
1324                        }
1325                        // Filing this conductor question temporarily wraps the
1326                        // original hold in a Blocked state. Restore only that
1327                        // exact blocker on the local copy before checking the
1328                        // hold binding; unrelated waits never authorize release.
1329                        if q.node == crate::conduct::NODE
1330                            && q.run == task.id
1331                            && task.status == TaskStatus::Blocked
1332                            && task.blocked_from == Some(TaskStatus::Held)
1333                            && task.blocked_by.as_slice() == [q.id.as_str()]
1334                        {
1335                            task.unblock(&q.id);
1336                        }
1337                        anyhow::ensure!(
1338                            task.status == TaskStatus::Held
1339                                && task.held_at == Some(*held_at)
1340                                && task.hold_reason.as_deref() == reason.as_deref()
1341                                && task
1342                                    .operator_decided_at
1343                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1344                            "task no longer has the hold this question names"
1345                        );
1346                        task.release_operator("choice", Some(&q.id));
1347                        task.mark_action_applied(&q.id);
1348                        queue.put(&mut task)?;
1349                    }
1350                    ask::ChoiceAction::AbandonRun { run } => {
1351                        record("started")?;
1352                        crate::driver::abandon_proven_dead(home, run)?;
1353                    }
1354                    ask::ChoiceAction::RerunChecks {
1355                        repo,
1356                        pr,
1357                        head,
1358                        runs,
1359                    } => {
1360                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1361                            .await?;
1362                    }
1363                    _ => unreachable!(),
1364                }
1365                Ok::<_, anyhow::Error>(())
1366            }
1367            .await;
1368            match applied {
1369                Ok(()) => record("applied"),
1370                Err(e) => {
1371                    record(&format!("refused or failed: {e:#}"))?;
1372                    Err(e)
1373                }
1374            }
1375        }
1376        .await;
1377        // Retire the originating blocker as well as the target operation.
1378        // A foreign resume leaves its issuer held instead of competing beside
1379        // the execution just started. Other successful maintenance lets the
1380        // original task retry its normal, guarded path.
1381        if home
1382            .join("choice-actions")
1383            .join(format!("{}.json", q.id))
1384            .exists()
1385            && let Some(listed) = task_of_question(&queue.list(), &q)
1386            && !listed.action_applied(&q.id)
1387            && let Ok(_claim) = queue.claim(&listed.id)
1388            && let Ok(mut origin) = queue.get(&listed.id)
1389        {
1390            if !origin.operator_held()
1391                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1392                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1393            {
1394                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1395                    origin.hold_machine(Some(format!(
1396                        "Maintenance choice {} settled; inspect its target before releasing this task",
1397                        q.id
1398                    )));
1399                } else {
1400                    origin.unblock(&q.id);
1401                }
1402            }
1403            origin.mark_action_applied(&q.id);
1404            let _ = queue.put(&mut origin);
1405        }
1406        if let Err(e) = result
1407            && fresh
1408        {
1409            notices::raise_in(
1410                home,
1411                Notice::warn(
1412                    &format!("action:{}", q.id),
1413                    format!("Choice action {} was not completed: {e:#}", q.id),
1414                )
1415                .link(if q.run_names_task() {
1416                    Link::Task { id: q.run.clone() }
1417                } else {
1418                    Link::Run { id: q.run.clone() }
1419                }),
1420            );
1421        }
1422    }
1423}
1424
1425/// Rerun the named failed workflow runs of a pull request, each at most once
1426/// per `request` (a question id, or a chat operation identity). The head,
1427/// lifecycle and failed state are re-read from the forge first; `started` is
1428/// called once those checks pass and before the first external call, and the
1429/// ledger entry is written before every `gh` call, so an uncertain result is
1430/// never repeated automatically.
1431pub(crate) async fn rerun_checks_once(
1432    home: &Path,
1433    request: &str,
1434    repo: &Path,
1435    pr: &str,
1436    head: &str,
1437    runs: &[String],
1438    started: impl FnOnce() -> anyhow::Result<()>,
1439) -> anyhow::Result<()> {
1440    use crate::release_watch::{GhForge, ReleaseForge};
1441    anyhow::ensure!(
1442        !runs.is_empty()
1443            && runs.len() <= 20
1444            && runs
1445                .iter()
1446                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1447            && !pr.starts_with('-'),
1448        "invalid rerun targets"
1449    );
1450    let snap = GhForge.snapshot(repo, pr).await?;
1451    anyhow::ensure!(
1452        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1453        "pull request head or lifecycle changed"
1454    );
1455    anyhow::ensure!(
1456        runs.iter().all(|r| snap
1457            .checks
1458            .iter()
1459            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1460        "named workflow is no longer failed on this pull request"
1461    );
1462    started()?;
1463    let dir = home.join("choice-actions");
1464    std::fs::create_dir_all(&dir)?;
1465    let rerun_lock = std::fs::OpenOptions::new()
1466        .create(true)
1467        .truncate(false)
1468        .write(true)
1469        .open(dir.join("reruns.lock"))?;
1470    crate::pr_head::try_lock_file(&rerun_lock)?;
1471    let ledger = dir.join("reruns.json");
1472    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1473        serde_json::from_slice(&std::fs::read(&ledger)?)?
1474    } else {
1475        Default::default()
1476    };
1477    for run in runs {
1478        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1479        if !recorded.insert(key) {
1480            continue;
1481        }
1482        let tmp = ledger.with_extension("tmp");
1483        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1484        std::fs::rename(tmp, &ledger)?;
1485        GhForge.rerun(repo, run).await?;
1486    }
1487    Ok(())
1488}
1489
1490/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1491///
1492/// Runs on every poll before the conductor looks at the queue. The task is
1493/// re-read under its claim, so a task somebody completed or held by hand in
1494/// the meantime is judged on what it is now. `Resume` releases the task and
1495/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1496/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1497/// ordinary `unfinished_run` logic resumes that same run.
1498pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1499    let tasks = queue.list();
1500    for q in questions.list() {
1501        // Dismissal is committed by the question writer, never a resume.
1502        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1503            continue;
1504        }
1505        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1506            continue;
1507        }
1508        let Some(listed) = task_of_question(&tasks, &q) else {
1509            if q.node == land::APPROVAL_NODE
1510                && q.resolution().as_deref().is_some_and(|choice| {
1511                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1512                })
1513            {
1514                notices::raise_in(
1515                    home,
1516                    Notice::warn(
1517                        &format!("repair-owner:{}", q.id),
1518                        format!(
1519                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1520                            q.run, q.run
1521                        ),
1522                    ).link(Link::Run { id: q.run.clone() }),
1523                );
1524            }
1525            continue;
1526        };
1527        if listed.action_applied(&q.id) {
1528            continue;
1529        }
1530        let Ok(_claim) = queue.claim(&listed.id) else {
1531            continue;
1532        };
1533        let Ok(mut task) = queue.get(&listed.id) else {
1534            continue;
1535        };
1536        // Work only on this local copy until the action can be committed.
1537        // In particular, a fresh lease below leaves the persisted task blocked.
1538        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1539            let blockers: Vec<_> = task
1540                .blocked_by
1541                .iter()
1542                .filter(|id| {
1543                    crate::queue::dependency(queue, questions, id)
1544                        == crate::queue::Dependency::Question(q.id.clone())
1545                })
1546                .cloned()
1547                .collect();
1548            if !blockers.is_empty() {
1549                for id in blockers {
1550                    task.unblock(&id);
1551                }
1552                let answer = match &q.answer {
1553                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1554                    None => String::new(),
1555                };
1556                task.record_answer(q.summary.clone(), answer);
1557            }
1558        }
1559        let language = language_of(&task, Path::new("."));
1560        let decision = decide_action(home, &task, &q, phrases(&language), |id| {
1561            RunState::load_under(id, home)
1562        });
1563        let ran = matches!(
1564            decision,
1565            ActionDecision::Resume(_)
1566                | ActionDecision::Requeue
1567                | ActionDecision::Hold
1568                | ActionDecision::Done
1569        );
1570        if ran && asker_may_still_read(questions, &q, home) {
1571            // The asking process or its seat can still take the word; act
1572            // once it has gone quiet. Bound on the remaining window: the
1573            // check is not atomic with the write below, so an asker that
1574            // takes the word in between (at most one poll, never more than
1575            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1576            // and `Task::actions_applied` under the claim keeps the action to
1577            // one application. The waiter does not deliver an answer that
1578            // carries an action (`waiter::decide_owned`), so it cannot race.
1579            continue;
1580        }
1581        let done = matches!(decision, ActionDecision::Done);
1582        match decision {
1583            ActionDecision::Skip => continue,
1584            ActionDecision::Resume(run) => {
1585                task.release_operator("choice", Some(&q.id));
1586                task.resume_override = Some(crate::queue::OperatorResume {
1587                    question_id: q.id.clone(),
1588                    at: Timestamp::now(),
1589                    conductor_rehold: None,
1590                    forced: true,
1591                    pinned_run: Some(run),
1592                });
1593            }
1594            ActionDecision::Stale => {}
1595            ActionDecision::Requeue => {
1596                task.release_operator("choice-requeue", Some(&q.id));
1597                task.requeue();
1598            }
1599            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1600            ActionDecision::Done => task.succeed(),
1601            ActionDecision::Refuse(why) => {
1602                if task.operator_held() {
1603                    // A rejected answer does not release the operator's hold
1604                    // or reclassify it as recoverable by the conductor.
1605                    task.hold_reason = Some(match task.hold_reason.take() {
1606                        Some(reason) => format!("{reason}\n\n{why}"),
1607                        None => why,
1608                    });
1609                } else {
1610                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1611                    task.hold_machine(Some(why));
1612                }
1613                notices::raise(
1614                    Notice::warn(
1615                        &format!("action:{}", q.id),
1616                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1617                    )
1618                    .link(Link::Task {
1619                        id: task.id.clone(),
1620                    }),
1621                );
1622            }
1623        }
1624        task.mark_action_applied(&q.id);
1625        // The applied id travels with the transition, so a failed save loses
1626        // neither and the answer is acted on at the next poll.
1627        record(queue, &mut task);
1628        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1629            supersede_prior_runs(&task, home);
1630        }
1631        // Delivery is only a note of who has read the answer; the task's own
1632        // mark above is the authority. Best effort.
1633        let _ = questions.update(&q.id, |r| {
1634            r.answer_delivered = true;
1635            Ok(())
1636        });
1637    }
1638}
1639
1640/// Whether something may still read the answer to `q`: a fresh lease, or the
1641/// asking seat still listed as active in its run (its CLI can outlive the
1642/// `magi ask` that was killed).
1643fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1644    let now = Timestamp::now();
1645    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1646        return true;
1647    }
1648    q.node != crate::conduct::NODE
1649        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1650            s.seats_active()
1651                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1652        })
1653}
1654
1655/// Retire an unanswered conductor question after its task no longer refers to
1656/// it. Conductor questions use the task id in `Question::run`, so run-based
1657/// cleanup cannot observe a manual release or completion.
1658///
1659/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1660/// own question also carries a `run`, and a run id that happens to collide
1661/// with some task's id is not this loop's business — only a conductor
1662/// question actually uses the task id that way. One `Questions::list()` scan
1663/// is taken up front and matched against the in-memory task set, rather than
1664/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1665fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1666    let tasks = queue.list();
1667    let by_id: std::collections::BTreeMap<&str, &Task> =
1668        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1669    let referenced: Vec<&str> = tasks
1670        .iter()
1671        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1672        .collect();
1673
1674    for mut question in questions.list() {
1675        if !question.status.open() || question.node != crate::conduct::NODE {
1676            continue;
1677        }
1678        // Keep questions a task still names, including when the reference
1679        // moved to a dependent task.
1680        // Preserve even ambiguous references: retiring a possibly referenced
1681        // question is unsafe until the operator disambiguates it.
1682        if referenced
1683            .iter()
1684            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1685        {
1686            continue;
1687        }
1688        let Some(task) = by_id.get(question.run.as_str()) else {
1689            continue;
1690        };
1691        question.abandon(format!(
1692            "task {} no longer waits for this answer",
1693            task.short()
1694        ));
1695        if let Err(e) = questions.put(&mut question) {
1696            tracing::warn!(
1697                "could not retire question {} for task {}: {e:#}",
1698                question.short(),
1699                task.short()
1700            );
1701        }
1702    }
1703}
1704
1705/// What a finished run tells the queue about the task it came from.
1706///
1707/// A struct rather than a fourth and fifth boolean argument: the two flags
1708/// answer different questions about the same run, and a call site passing
1709/// `(…, true, false)` is one transposition away from refunding attempts
1710/// forever.
1711#[derive(Debug, Clone, Copy)]
1712pub struct Verdict {
1713    /// Where the graph stopped.
1714    pub status: RunStatus,
1715    /// The run opened a pull request.
1716    pub left_pr: bool,
1717    /// At least one seat was lost to a rate limit.
1718    pub quota_hit: bool,
1719    /// The run parked at a node boundary because it was asked to.
1720    pub parked: bool,
1721    /// The run never produced a single candidate a judge could look at.
1722    ///
1723    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1724    /// still have another candidate worth judging, in which case the loss was
1725    /// not the reason nothing came of the run. This is `true` only when the
1726    /// implement wave ended with nothing viable at all.
1727    pub no_viable_candidates: bool,
1728}
1729
1730/// Record a finished run against the task it came from.
1731///
1732/// Kept pure and separate from the loop because this mapping *is* the retry
1733/// policy, and a policy that can only be exercised by spawning a graph is a
1734/// policy nobody checks. The table:
1735///
1736/// | run status                           | task becomes        | attempt spent |
1737/// |---------------------------------------|---------------------|---------------|
1738/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1739/// | `Merged`, `Ready`                      | `Done`               | yes          |
1740/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1741/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1742/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1743/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1744/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1745/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1746/// | `Blocked` with a PR                    | `Held`               | yes          |
1747/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1748/// | `VerifiedNoop`                          | `Held`               | yes          |
1749/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1750///
1751/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1752/// deliberately: every candidate agreeing there is nothing to write is not a
1753/// machine fact about a rate limit, it is an unverified claim about the
1754/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1755/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1756/// claim could be wrong (a misread instruction, a stale check), and closing
1757/// the task automatically on an implementer's say-so would be the exact
1758/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1759/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1760/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1761/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1762/// claim regardless of whether the one already-spent attempt is refunded, and
1763/// [`Task::release`] resets the count to zero anyway the moment a human looks
1764/// at the evidence and lets it run again.
1765///
1766/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1767/// twice, together. A quorum lost to rate limits is a property of the machine
1768/// and not of the task, so the attempt is refunded and a reset quota picks
1769/// the work up where it stopped — and that is just as true when every
1770/// implement seat lost the same race and `after_implement` bails with nothing
1771/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1772/// machine fact. The `no_viable_candidates` guard is what keeps that row
1773/// narrow: a `Failed` run that produced a real candidate which then lost for
1774/// some other reason still spends the attempt, exactly like the quorum lost
1775/// to judges that answered with the wrong shape is ordinary flakiness, and
1776/// refunding *that* takes the bound off the retry loop entirely: run e633
1777/// stalled with `quota: []` after two judges wrote unusable JSON, was
1778/// refunded, and the next attempt paid for a fresh hour-long implement wave
1779/// before it could fail the same way. `max_attempts` exists precisely so
1780/// that cannot repeat forever.
1781///
1782/// A non-terminal status means `execute` returned while the graph was still
1783/// mid-flight, which is a bug rather than a verdict; it is treated as a
1784/// failure so that a task cannot loop on it either.
1785///
1786/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1787/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1788pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1789    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1790}
1791
1792/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1793fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1794    // A parked run is the operator's own doing, and its work is intact on
1795    // disk. The task goes back in line with its attempt refunded so the next
1796    // loop resumes the same run - which `one_task` prefers over competing
1797    // again - and so that swapping the binary a few times cannot exhaust a
1798    // budget meant for agents that actually misbehaved.
1799    if verdict.parked {
1800        task.park(detail);
1801        return;
1802    }
1803    match verdict.status {
1804        RunStatus::Merged | RunStatus::Ready
1805            if task.pr_recovery.as_ref().is_some_and(|s| {
1806                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1807            }) =>
1808        {
1809            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()));
1810        }
1811        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1812        RunStatus::AlreadyInBase => task.already_landed(detail),
1813        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1814        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1815            task.stall(detail)
1816        }
1817        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1818        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1819        RunStatus::Blocked => task.fail(detail, max_attempts),
1820        RunStatus::VerifiedNoop => task.handed_off(detail),
1821        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1822    }
1823}
1824
1825/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1826/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1827/// itself has actually finished *and* its own last attempt is provably why:
1828/// this loads that run and requires `Merged`/`Ready` before touching
1829/// anything earlier in `runs`, since `Task::succeed` can also be called
1830/// directly on a task whose last attempt never landed at all.
1831///
1832/// Called right after whatever call set `task.status` to
1833/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1834/// `reclaim`'s, but also every other place a task can be closed by hand
1835/// without the loop ever settling it itself: `magi task done`
1836/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1837/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1838/// GitHub merge, say, exactly the workflow this repository's own
1839/// "Landing a run's winner by hand" documents — is just as much "this task's
1840/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1841/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1842/// forever, which is the exact backlog this status exists to clear. `pub`
1843/// for those two out-of-module callers; everything else about this stays
1844/// internal bookkeeping.
1845///
1846/// A run something is still actually driving is left alone: a
1847/// task cannot be `Done` while one of its *own* attempts is still in flight,
1848/// so a live one at this point can only be an unrelated process — a manual
1849/// `--resume` of this old, now-moot run — and rewriting under it would just
1850/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1851/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1852/// pair `run_report`/`run_detail` use for the same question elsewhere:
1853/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1854/// --resume` invoked by hand outside it, which `liveness` also checks via
1855/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1856/// (already terminal in some other way, or itself mid-run) is left untouched
1857/// too.
1858///
1859/// Best-effort, like the rest of this module's bookkeeping: a load or save
1860/// failure here is a `tracing::warn`, not a failed settle, and the next time
1861/// this same task's completion is recorded — or a daemon restart replays
1862/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1863/// separate reconciliation pass; if that gap ever matters in practice, one
1864/// can be added then.
1865///
1866/// `home` is a parameter, not the process-global [`crate::run::home`], for
1867/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1868/// calls this with `ui.home`, which is `crate::run::home()` in a real
1869/// process but a fixture's own directory under test — falling through to
1870/// the global there would read and write through whichever home some other
1871/// test in the same binary happened to pin into that `OnceLock` first, not
1872/// the run this call actually means.
1873pub fn supersede_prior_runs(task: &Task, home: &Path) {
1874    let now = Timestamp::now();
1875    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1876    // right behind a `Merged`/`Ready` verdict) from one set directly by
1877    // `magi task done`/its web equivalent/the conductor on a task whose last
1878    // recorded attempt never actually landed - that requires reading the
1879    // run itself, which is exactly what this does before trusting anything
1880    // in `runs` is safe to relabel.
1881    let last_run_succeeded = task
1882        .runs
1883        .last()
1884        .and_then(|id| RunState::load_under(id, home).ok())
1885        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1886    for id in task.superseded_attempts(last_run_succeeded) {
1887        let mut state = match RunState::load_under(id, home) {
1888            Ok(s) => s,
1889            Err(e) => {
1890                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1891                continue;
1892            }
1893        };
1894        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1895            continue;
1896        }
1897        let daemon_claims = is_working_on(home, id, now);
1898        if state.liveness(daemon_claims) == Liveness::Live {
1899            continue;
1900        }
1901        state.status = RunStatus::Superseded;
1902        if let Err(e) = state.save_under(home) {
1903            tracing::warn!("could not mark run {id} superseded: {e:#}");
1904        }
1905    }
1906}
1907
1908/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1909/// finish the moment it was called, because one of its earlier attempts was
1910/// still live then - a `magi run --resume` invoked by hand on an old run,
1911/// most likely.
1912///
1913/// That skip is correct at the time (rewriting under a run something is
1914/// still actively saving would just be undone), but a task only ever
1915/// reaches `Done` once, so without this nothing would ever look at it
1916/// again: if that manual process later ends anywhere other than
1917/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1918/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1919/// backlog this status exists to clear. Called on the same idle-only
1920/// cadence as [`janitor`], next to it rather than folded into it: this
1921/// walks `queue` and `janitor` never otherwise needs one.
1922///
1923/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1924/// more than one attempt, every pass: each call is a handful of local file
1925/// reads bounded by that task's own attempt count, the same order of cost
1926/// [`clean::fold_due`] already pays scanning every run on disk on the same
1927/// cadence, and a task already fully resolved costs one failed liveness
1928/// check turned no-op the moment its lingering attempt is no longer live.
1929fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1930    for task in queue.list() {
1931        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1932            continue;
1933        }
1934        supersede_prior_runs(&task, home);
1935    }
1936}
1937
1938/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1939/// task ends up held.
1940///
1941/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1942/// dead daemon never got back to) share this, so the two cannot drift into
1943/// disagreeing about which held tasks get a diagnostic.
1944fn settle_and_diagnose(
1945    task: &mut Task,
1946    verdict: Verdict,
1947    detail: &str,
1948    max_attempts: usize,
1949    state: &RunState,
1950) {
1951    let p = phrases(&state.config.graph.language);
1952    // Shared by normal completion and crash recovery, under the task claim.
1953    // No new attempt can own the task until the old driver has exited.
1954    if let Some(d) = &state.merge_decision {
1955        use crate::merge_decision as md;
1956        if task.runs.last().is_some_and(|id| id != &state.id) {
1957            return;
1958        }
1959        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1960            task.succeed();
1961        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1962            if state.liveness(false) != Liveness::Dead {
1963                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1964                return;
1965            }
1966            let replacement = md::Replacement {
1967                question: d.question.clone(),
1968                run: state.id.clone(),
1969                pr: d.target.pr.clone(),
1970                agent: agent.to_owned(),
1971                context: format!(
1972                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1973                    d.target.pr,
1974                    state.id,
1975                    serde_json::to_string(&state.reviews).unwrap_or_default()
1976                ),
1977            };
1978            task.requeue();
1979            task.pr_recovery = None;
1980            task.review_of = None;
1981            task.replacement = Some(replacement);
1982        } else {
1983            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1984                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1985            } 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())) }));
1986        }
1987        task.mark_action_applied(&d.question);
1988        if let Some(pass) = state.passes.last() {
1989            task.record_pass_at(
1990                &state.id,
1991                pass.index,
1992                Some(pass.started_at),
1993                task.attempts,
1994                None,
1995            );
1996        }
1997        return;
1998    }
1999    if let Some(replacement) = &task.replacement
2000        && !state.parked
2001        && state.resource_block.is_none()
2002        && (state.viable().is_empty()
2003            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2004    {
2005        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)));
2006        return;
2007    }
2008    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2009        let mut agents: Vec<_> = state
2010            .quota
2011            .iter()
2012            .filter(|q| {
2013                q.cause == crate::agent::QuotaCause::Authentication
2014                    && state
2015                        .passes
2016                        .last()
2017                        .is_none_or(|pass| q.at >= pass.started_at)
2018            })
2019            .map(|q| q.agent.as_str())
2020            .collect();
2021        agents.sort_unstable();
2022        agents.dedup();
2023        if !agents.is_empty() {
2024            task.stall(detail);
2025            task.notice_cause("agent-authentication", None, None);
2026            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2027            return;
2028        }
2029    }
2030    let attempts_before = task.attempts;
2031    // A run that stopped because a shared resource stayed busy was never a
2032    // failure of the task or of an agent. Earlier nodes may have run; only
2033    // the blocked operation lacks a result. The attempt is
2034    // refunded and the task is held by the machine, under a reason `triage`
2035    // can re-check, so the same run resumes with the same agents once the
2036    // resource is free. A park request still wins (it is the operator's).
2037    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2038        task.notice_cause(
2039            &format!("resource:{}:{}", block.kind, block.node),
2040            None,
2041            None,
2042        );
2043        task.last_error = Some(detail.to_owned());
2044        task.diagnostic = None;
2045        task.attempts = task.attempts.saturating_sub(1);
2046        if block.kind == "agent authentication" {
2047            task.hold_machine(Some(format!(
2048                "[authentication] {}; no attempt was spent",
2049                block.detail
2050            )));
2051        } else if block.kind == "agent usage limit" {
2052            // Usage limits keep the existing cooldown-and-resume policy.
2053            if let Some(agent) = &state.config.graph.selected_implementer {
2054                task.hold_machine(Some(format!("[agent usage limit] Selected implementer `{agent}` is unavailable. No other implementer was dispatched; resume after usage is available. No attempt was spent.")));
2055            } else {
2056                task.status = TaskStatus::Failed;
2057                task.last_error = Some(block.detail.clone());
2058            }
2059        } else if block.kind == "disk pressure" {
2060            task.hold_machine(Some(format!(
2061                "{}{}",
2062                crate::disk::RUNNING_PRESSURE,
2063                block.detail
2064            )));
2065        } else {
2066            task.hold_machine(Some(format!(
2067                "{}{}; no attempt was spent; resume to retry the affected operation",
2068                crate::cache::RESOURCE_HOLD,
2069                block.description()
2070            )));
2071        }
2072        if let Some(pass) = state.passes.last() {
2073            task.record_pass_at(
2074                &state.id,
2075                pass.index,
2076                Some(pass.started_at),
2077                attempts_before,
2078                None,
2079            );
2080        }
2081        return;
2082    }
2083    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2084        state.parked
2085            && state.status == RunStatus::Landing
2086            && state
2087                .pr_pushed_head
2088                .as_ref()
2089                .is_none_or(|h| h == &hold.head)
2090            && task.runs.last() == Some(&state.id)
2091    }) {
2092        // Settlement and crash recovery share this idempotency key. A later
2093        // explicit resume is a new pass and may refund its own attempt once.
2094        let pass = state.passes.last().map_or(0, |p| p.index);
2095        if !task
2096            .passes
2097            .iter()
2098            .any(|p| p.run == state.id && p.pass_index == pass)
2099        {
2100            task.attempts = task.attempts.saturating_sub(1);
2101        }
2102        task.hold_machine(Some(format!(
2103            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2104            hold.question
2105        )));
2106        task.last_error = Some(detail.to_owned());
2107        task.diagnostic = None;
2108        task.record_pass_at(
2109            &state.id,
2110            pass,
2111            state.passes.last().map(|p| p.started_at),
2112            attempts_before,
2113            Some(crate::run::ParkCause::Question),
2114        );
2115        return;
2116    }
2117    let unresolved = task.hold_notice_cause.clone();
2118    if state.base_sync_blocked() {
2119        // No automatic retry may turn a retained sync stop into a new competition.
2120        task.hold_machine(Some(detail.to_owned()));
2121        task.last_error = Some(detail.to_owned());
2122    } else if !verdict.parked
2123        && task
2124            .pr_recovery
2125            .as_ref()
2126            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2127        && matches!(
2128            verdict.status,
2129            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2130        )
2131    {
2132        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2133            task.succeed();
2134        } else {
2135            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()));
2136        }
2137    } else if !verdict.parked
2138        && task.pr_recovery.is_some()
2139        && matches!(
2140            verdict.status,
2141            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2142        )
2143        && !verdict.quota_hit
2144    {
2145        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.")));
2146    } else {
2147        settle_in(task, verdict, detail, max_attempts, p);
2148    }
2149    if !verdict.parked
2150        && !verdict.quota_hit
2151        && matches!(
2152            verdict.status,
2153            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2154        )
2155    {
2156        task.recovery_failed(state);
2157    }
2158    if state.prep_failure.is_some() {
2159        // Minting a run whose candidates could not be prepared is not work
2160        // on a newly approved attempt. Keep the unresolved outcome anchor.
2161        task.hold_notice_cause = unresolved;
2162        task.startup_notice_cause("startup-candidates");
2163    }
2164    // Written here, where the refund (or not) is decided, so the history is a
2165    // fact and not a later guess from the run's status.
2166    if let Some(pass) = state.passes.last() {
2167        let parked = match &pass.end {
2168            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2169            _ => None,
2170        };
2171        task.record_pass_at(
2172            &state.id,
2173            pass.index,
2174            Some(pass.started_at),
2175            attempts_before,
2176            parked,
2177        );
2178    }
2179    if task.status == TaskStatus::Held {
2180        if state.base_sync_blocked() {
2181            task.base_sync_notice(state);
2182        } else if state.prep_failure.is_none() {
2183            task.notice_cause(
2184                label(verdict.status),
2185                Some(&state.id),
2186                state.passes.last().map(|p| p.index),
2187            );
2188        }
2189        task.diagnostic = diagnostic(state);
2190        note_open_question(task, &state.id, p);
2191    }
2192}
2193
2194/// If `task` is held with a `magi ask` question still open on `run`, name the
2195/// question in [`Task::hold_reason`] rather than leaving the hold reading
2196/// only [`describe`]'s run summary.
2197///
2198/// This is the shape task 20260928-191407-05fd left underspecified: an
2199/// implementer settled a verified no-op and filed a question for the
2200/// operator, and the hold that followed said nothing about the question
2201/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2202/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2203/// marker) and must keep seeing it unchanged.
2204///
2205/// Best-effort: an unreadable question store must not stop a run from
2206/// settling, so this is a no-op rather than a propagated error when
2207/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2208fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2209    let Some(home) = crate::run::try_home() else {
2210        return;
2211    };
2212    let open = Questions::at(home.join("questions")).open_for(run);
2213    let Some(q) = open.first() else {
2214        return;
2215    };
2216    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2217    decisions.sort_unstable();
2218    task.notice_cause(
2219        &format!("questions:{}", decisions.join(",")),
2220        Some(run),
2221        None,
2222    );
2223    let base = task.hold_reason.clone().unwrap_or_default();
2224    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2225}
2226
2227/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2228/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2229/// by some other means entirely, like a manual `magi run` resume that
2230/// finishes the graph outside the queue's bookkeeping.
2231///
2232/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2233/// `settle` is separate from `attempt`: a task recovered this way must land
2234/// exactly where a live daemon would have put it — the same policy table,
2235/// not a second one that quietly drifts from it — and that is only checkable
2236/// without spawning a real run.
2237fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2238    match last_run {
2239        Some(state) => {
2240            let verdict = Verdict {
2241                status: state.status,
2242                left_pr: state.pr.is_some(),
2243                quota_hit: state.quota.iter().any(|loss| {
2244                    state
2245                        .passes
2246                        .last()
2247                        .is_none_or(|pass| loss.at >= pass.started_at)
2248                }),
2249                parked: state.parked,
2250                no_viable_candidates: state.viable().is_empty(),
2251            };
2252            let detail = format!(
2253                "{}{}",
2254                phrases(&state.config.graph.language).recovered_running,
2255                describe(&state)
2256            );
2257            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2258        }
2259        None => {
2260            // No run, so no config of its own: `language` is the task's
2261            // repository's setting, read by the caller.
2262            let why = phrases(language).no_run_to_recover;
2263            task.last_error = Some(why.to_owned());
2264            // The phone shows `hold_reason`, so a task held by the machine
2265            // says why there too and not only in `last_error`.
2266            task.notice_cause("missing-run", None, None);
2267            task.hold_machine(Some(why.to_owned()));
2268        }
2269    }
2270}
2271
2272/// Find every task left at `running` that no live process is actually
2273/// driving, and settle each one against whatever its last run became.
2274///
2275/// # Why a claim is proof, not a guess
2276///
2277/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2278/// `running`, and the guard is held for the task's whole time in that status:
2279/// `attempt` does not return, and the loop does not move past the scope
2280/// holding the claim, until the run has settled. So a `running` task whose
2281/// lock is gone cannot have a live owner — this process or any other —
2282/// without needing a staleness threshold or a pid check the way
2283/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2284/// task that never got as far as `running` at all. Taking the claim here is
2285/// the whole test: it either fails, because something really does hold it
2286/// and the task is left alone, or it succeeds, which is the proof — and it is
2287/// kept for the rest of the decision so nothing else can start a competing
2288/// run while this one is being written.
2289///
2290/// Called on every poll, not only at startup, for the reason
2291/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2292/// keep noticing this, not only on the one morning it happened to restart.
2293fn reclaim_orphaned_running(
2294    queue: &Queue,
2295    max_attempts: usize,
2296    live_workers: &std::collections::BTreeSet<String>,
2297) -> Vec<String> {
2298    let mut reclaimed = Vec::new();
2299    for listed in queue.list() {
2300        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2301            continue;
2302        }
2303        let Ok(_claim) = queue.claim(&listed.id) else {
2304            continue;
2305        };
2306        // Re-read under the claim: a release or an edit landed by a human
2307        // between the listing above and the claim just taken must not be
2308        // clobbered by a decision based on the stale copy.
2309        let Ok(mut task) = queue.get(&listed.id) else {
2310            continue;
2311        };
2312        if task.status != TaskStatus::Running {
2313            continue;
2314        }
2315        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2316        // `execute` normally abandons a run's own open questions the moment
2317        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2318        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2319        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2320        // with the question still `open`, because the process died before
2321        // reaching that call. `reclaim` itself stays pure on purpose (see its
2322        // own doc), so the same cleanup runs here instead, against the run
2323        // this reclaim is already reading. `settle_run` costs nothing when
2324        // `execute` already got there first.
2325        if let Some(state) = &last_run
2326            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2327        {
2328            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2329        }
2330        let language = if last_run.is_none() {
2331            language_of(&task, Path::new("."))
2332        } else {
2333            String::new()
2334        };
2335        reclaim(&mut task, last_run, max_attempts, &language);
2336        if task.status == TaskStatus::Done {
2337            supersede_prior_runs(&task, &crate::run::home());
2338        }
2339        record(queue, &mut task);
2340        reclaimed.push(task.id.clone());
2341    }
2342    reclaimed
2343}
2344
2345/// Find every run whose `run.json` is provably dead — every seat it still
2346/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2347/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2348/// not merely "no daemon claims it" — and fail it, clearing the leftover
2349/// active seats so the run stops reading as `implementing` (or whichever
2350/// node) forever.
2351///
2352/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2353/// `running`, using whatever `run.json` already says — but nothing in that
2354/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2355/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2356/// never got back to sits exactly where it was left: `active` full of seats
2357/// nobody will ever answer for, `status` stuck on whatever node was in
2358/// flight. `magi show` already tells an operator this in prose (`no live
2359/// daemon claims this run right now`); this is what makes that fact durable
2360/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2361/// stay stuck once nothing is driving it.
2362///
2363/// Runs on every poll, not only at startup, for the reason
2364/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2365/// daemon up for days must keep noticing a run some other, now-dead, daemon
2366/// left behind just as readily as one it trips over on the way up.
2367///
2368/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2369/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2370/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2371/// `runs` directory instead: `home` here is a parameter precisely so a test
2372/// can point it away from the operator's real history (see [`drive`]'s own
2373/// doc), and a scan that fell through to the global home anyway would walk
2374/// whichever directory some *other* process or test pinned into that
2375/// `OnceLock` first — mutating runs this call was never handed.
2376fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2377    reclaim_abandoned_runs_with(
2378        home,
2379        now,
2380        crate::proc::pid_status,
2381        crate::proc::process_started_at,
2382    )
2383}
2384
2385/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2386/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2387/// for the identical reason: this sweep's real damage (wiping a run's active
2388/// seats and failing it) has to be provable against an injected answer in a
2389/// test, not just the real process table.
2390fn reclaim_abandoned_runs_with<F, G>(
2391    home: &Path,
2392    now: Timestamp,
2393    query: F,
2394    identity: G,
2395) -> Vec<String>
2396where
2397    F: Fn(u32) -> Option<bool>,
2398    G: Fn(u32) -> Option<String>,
2399{
2400    let mut abandoned = Vec::new();
2401    for entry in std::fs::read_dir(home.join("runs"))
2402        .into_iter()
2403        .flatten()
2404        .flatten()
2405    {
2406        let id = entry.file_name().to_string_lossy().into_owned();
2407        if !crate::run::is_run_id(&id) {
2408            continue;
2409        }
2410        // Serialize the proof and save with claims and takeover: a new
2411        // execution must not be overwritten after the liveness observation.
2412        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2413            continue;
2414        };
2415        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2416        // that module's docs for why a run this cannot parse is left alone
2417        // rather than guessed at. A different schema number is not that: this
2418        // touches only `status` and `active`, never a field whose meaning a
2419        // schema bump changed, so an old record's values serve this exactly
2420        // as well as a current one's (see `clean::read_state`'s own doc for
2421        // the same reasoning applied to folding).
2422        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2423            continue;
2424        };
2425        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2426            continue;
2427        };
2428        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2429            continue;
2430        }
2431        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2432        // it", which is also the normal, healthy shape of a manual `magi
2433        // run` / `magi review` sharing this same home — this scan walks
2434        // every run on disk, not only ones this daemon itself started. Such
2435        // a run's active seats can legitimately sit past their own timeout
2436        // for a little while (the CLI finishing up, its result still being
2437        // collected) without the process driving it having died. `liveness`
2438        // is what actually tells the two apart, by corroborating
2439        // `driver_pid` against the process it names — see its own doc. Only
2440        // its strongest, provable answer licenses wiping this run's active
2441        // seats and failing it out from under whatever is still running it.
2442        let daemon_claims = is_working_on(home, &id, now);
2443        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2444            != crate::run::Liveness::Dead
2445        {
2446            continue;
2447        }
2448        state.abandon("daemon");
2449        if let Err(e) = state.save_under(home) {
2450            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2451            continue;
2452        }
2453        // This run never passes through `Runner::execute` again, so its end
2454        // is announced here.
2455        if let Some(notice) = notices::run_ended(&state) {
2456            notices::raise_in(home, notice);
2457        }
2458        // The seat that asked is gone for good now, exactly like any other
2459        // door `graph::Runner::settle_questions` closes the moment `status`
2460        // lands somewhere non-resumable - see that method's own doc. Nothing
2461        // else reaches this one before the next `janitor()` startup pass
2462        // (`clean::abandon_settled_questions`), and a daemon that stays up
2463        // for days must not leave an open question badging the operator
2464        // until it happens to restart.
2465        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2466            tracing::warn!("abandon questions for {id}: {e:#}");
2467        }
2468        abandoned.push(id);
2469    }
2470    abandoned
2471}
2472
2473#[derive(Debug, Clone, Serialize, Deserialize)]
2474struct TaskWorker {
2475    opts: Opts,
2476    queue: PathBuf,
2477    task: String,
2478    #[serde(default)]
2479    lane: PermitKind,
2480    #[serde(default)]
2481    standalone: bool,
2482}
2483
2484fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2485    Ok(crate::worker::active(home)?
2486        .into_iter()
2487        .filter(|job| job.kind == "task")
2488        .collect())
2489}
2490
2491fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2492    task_jobs(home)?
2493        .into_iter()
2494        .filter_map(
2495            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2496                Ok(request) if !request.standalone => Some(Ok(job)),
2497                Ok(_) => None,
2498                Err(error) => Some(Err(error.into())),
2499            },
2500        )
2501        .collect()
2502}
2503
2504/// Whether an independent scheduler can be controlled without its web parent.
2505#[must_use]
2506pub fn managed(home: &Path) -> bool {
2507    match crate::worker::active(home) {
2508        Err(error) => {
2509            tracing::error!("cannot determine scheduler ownership: {error:#}");
2510            true
2511        }
2512        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2513        Ok(_) => {
2514            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2515                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2516        }
2517    }
2518}
2519
2520/// Start a detached, singleton scheduler using this executable generation.
2521pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2522    anyhow::ensure!(
2523        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2524        "the scheduler is stopping; wait for retirement before starting it again"
2525    );
2526    crate::worker::spawn(
2527        home,
2528        "scheduler",
2529        "scheduler",
2530        serde_json::to_value(opts.absolute()?)?,
2531    )
2532    .await
2533}
2534
2535fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2536    home.join("worker-parks").join(format!("{}.json", job.id))
2537}
2538
2539fn request_task_park(
2540    home: &Path,
2541    job: &crate::worker::Job,
2542    cause: crate::run::ParkCause,
2543) -> Result<()> {
2544    let path = park_request_path(home, job);
2545    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2546    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2547    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2548}
2549
2550/// Stop dispatch immediately; only an explicit park reaches existing workers.
2551pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2552    if control == crate::worker::Control::Park {
2553        for job in owned_task_jobs(home)? {
2554            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2555        }
2556    }
2557    crate::worker::request(home, "scheduler", control)
2558}
2559
2560/// Replace the scheduler, leaving all active task and conversation jobs alone.
2561pub async fn restart_detached(home: &Path) -> Result<()> {
2562    let active = crate::worker::active(home)?;
2563    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2564    if prior.is_none() && !managed(home) {
2565        return Ok(());
2566    }
2567    let opts: Opts = match prior {
2568        Some(job) => serde_json::from_value(job.payload)?,
2569        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2570    };
2571    request_control(home, crate::worker::Control::Stop)?;
2572    loop {
2573        let reserved = crate::worker::active(home)?
2574            .iter()
2575            .any(|job| job.kind == "scheduler");
2576        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2577            break;
2578        }
2579        tokio::time::sleep(Duration::from_millis(100)).await;
2580    }
2581    spawn_detached(home, &opts).await?;
2582    Ok(())
2583}
2584
2585/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2586pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2587    let opts: Opts = serde_json::from_value(payload)?;
2588    let _ = home;
2589    serve_until(opts, Stop::new()).await
2590}
2591
2592/// Execute and settle one task with the queue claim owned by this process.
2593pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2594    let request: TaskWorker = serde_json::from_value(payload)?;
2595    let queue = Queue::at(request.queue);
2596    let key = format!("task:{}", request.task);
2597    let job = task_jobs(home)?
2598        .into_iter()
2599        .find(|job| job.key == key)
2600        .context("task worker reservation is missing")?;
2601    let park_path = park_request_path(home, &job);
2602    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2603    // our durable reservation. Never execute before that ownership hand-off.
2604    let _claim = loop {
2605        match queue.claim(&request.task) {
2606            Ok(claim) => break claim,
2607            // Only contention (the claim file exists) is worth waiting out; an
2608            // I/O failure must end this worker instead of pinning its lane.
2609            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2610                return Err(e.context("claim the task for its worker"));
2611            }
2612            Err(_) => {
2613                sweep_stale_claims(&queue, STALE_CLAIM);
2614                tokio::time::sleep(Duration::from_millis(50)).await;
2615            }
2616        }
2617    };
2618    let mut task = queue.get(&request.task)?;
2619    if !task.status.runnable()
2620        || (!request.standalone
2621            && request.lane
2622                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2623    {
2624        return Ok(());
2625    }
2626    let stop = Stop::new();
2627    let watcher = {
2628        let home = home.to_path_buf();
2629        let stop = stop.clone();
2630        let park_path = park_path.clone();
2631        tokio::spawn(async move {
2632            loop {
2633                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2634                    let cause = std::fs::read(&park_path)
2635                        .ok()
2636                        .and_then(|body| serde_json::from_slice(&body).ok())
2637                        .unwrap_or(crate::run::ParkCause::Operator);
2638                    stop.park(cause);
2639                    return;
2640                }
2641                tokio::time::sleep(Duration::from_millis(200)).await;
2642            }
2643        })
2644    };
2645    let quota = if request.standalone {
2646        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2647    } else {
2648        let status = Arc::new(Mutex::new(Status::new()));
2649        Box::pin(attempt(
2650            &request.opts,
2651            &queue,
2652            &status,
2653            &stop,
2654            crate::graph::Pause::new(),
2655            &mut task,
2656        ))
2657        .await
2658    };
2659    watcher.abort();
2660    let _ = std::fs::remove_file(park_path);
2661    persist_cooldown(home, &quota).await?;
2662    Ok(())
2663}
2664
2665/// Launch the standalone task worker with a claim-to-reservation handoff.
2666/// Returns only after the worker owns a durable execution reservation.
2667pub async fn spawn_claimed(
2668    home: &Path,
2669    opts: &Opts,
2670    queue: &Queue,
2671    task: &Task,
2672    claim: crate::queue::Claim,
2673) -> Result<crate::worker::Job> {
2674    let request = TaskWorker {
2675        opts: opts.absolute()?,
2676        queue: std::path::absolute(queue.root())?,
2677        task: task.id.clone(),
2678        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2679        standalone: true,
2680    };
2681    let job = crate::worker::spawn(
2682        home,
2683        "task",
2684        &format!("task:{}", task.id),
2685        serde_json::to_value(request)?,
2686    )
2687    .await?;
2688    drop(claim);
2689    Ok(job)
2690}
2691
2692/// Transfer a standalone caller's claim only after the detached worker is live,
2693/// then follow that worker to its final (non-automatically-retrying) outcome.
2694pub async fn run_detached_claimed(
2695    opts: &Opts,
2696    queue: &Queue,
2697    task: &mut Task,
2698    claim: crate::queue::Claim,
2699) -> Result<()> {
2700    let home = crate::run::home();
2701    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2702    loop {
2703        // Reconcile execution leases even without a scheduler. A dead worker
2704        // must become a reported failure, never an infinite persisted wait.
2705        crate::worker::active(&home)?;
2706        let current = crate::worker::get(&home, &job.id)?;
2707        if matches!(
2708            current.status,
2709            crate::worker::Status::Finished | crate::worker::Status::Failed
2710        ) {
2711            *task = queue.get(&task.id)?;
2712            anyhow::ensure!(
2713                current.status != crate::worker::Status::Failed,
2714                "task worker failed: {}",
2715                current.result.as_deref().unwrap_or("unknown failure")
2716            );
2717            return Ok(());
2718        }
2719        tokio::time::sleep(Duration::from_millis(200)).await;
2720    }
2721}
2722
2723async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2724    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2725        let _lease = loop {
2726            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2727                break lease;
2728            }
2729            tokio::time::sleep(Duration::from_millis(10)).await;
2730        };
2731        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2732            let path = home.join("task-quota-cooldown.json");
2733            let temporary = path.with_extension("json.tmp");
2734            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2735            std::fs::rename(temporary, path)?;
2736        }
2737    }
2738    Ok(())
2739}
2740
2741fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2742    match std::fs::read(home.join("task-quota-cooldown.json")) {
2743        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2744        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2745        Err(error) => Err(error.into()),
2746    }
2747}
2748
2749/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2750///
2751/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2752/// sets, so there is one loop body rather than two that drift apart the first
2753/// time the retry policy changes on only one of them.
2754pub async fn serve(opts: Opts) -> Result<()> {
2755    tracing::info!(
2756        "automatic update and restart requires magi web; standalone serve does not restart"
2757    );
2758    serve_until(opts, Stop::new()).await
2759}
2760
2761/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2762///
2763/// A stop retires dispatch promptly, including while a worker launch is being
2764/// acknowledged. Already reserved workers own their attempts independently and
2765/// finish with their started executable. Explicit park additionally forwards
2766/// durable park requests; neither scheduler retirement nor update does so.
2767///
2768/// While the queue is empty the stop is honoured within one wakeup rather than
2769/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2770/// caller that taps stop does not sit through the remainder of a sleep.
2771pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2772    let opts = opts.absolute()?;
2773    let home = crate::run::home();
2774    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2775        .context("another scheduler already owns this home")?;
2776    if let Some(reading) = read_status(&home)
2777        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2778    {
2779        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2780    }
2781    if !crate::worker::active(&home)?
2782        .iter()
2783        .any(|job| job.kind == "scheduler")
2784    {
2785        crate::worker::clear_control(&home, "scheduler")?;
2786    }
2787    std::fs::write(
2788        home.join("scheduler-options.json"),
2789        serde_json::to_vec(&opts)?,
2790    )?;
2791    let control = {
2792        let home = home.clone();
2793        let stop = stop.clone();
2794        tokio::spawn(async move {
2795            loop {
2796                match crate::worker::control(&home, "scheduler").ok().flatten() {
2797                    Some(crate::worker::Control::Park) => {
2798                        let _ = request_control(&home, crate::worker::Control::Park);
2799                        stop.park(crate::run::ParkCause::Operator);
2800                        break;
2801                    }
2802                    Some(crate::worker::Control::Stop) => {
2803                        stop.stop();
2804                        break;
2805                    }
2806                    None => {}
2807                }
2808                tokio::time::sleep(Duration::from_millis(100)).await;
2809            }
2810        })
2811    };
2812    let signal = {
2813        let stop = stop.clone();
2814        tokio::spawn(async move {
2815            if tokio::signal::ctrl_c().await.is_ok() {
2816                stop.stop();
2817                tracing::info!("scheduler shutdown requested; independent workers continue");
2818            }
2819        })
2820    };
2821
2822    let worktrees_root = opts
2823        .worktrees_root
2824        .clone()
2825        .unwrap_or_else(crate::run::default_worktree_root);
2826    let outcome = drive(
2827        &opts,
2828        &Queue::open(),
2829        &status_path(),
2830        &crate::run::home(),
2831        &worktrees_root,
2832        &stop,
2833    )
2834    .await;
2835
2836    signal.abort();
2837    control.abort();
2838    outcome
2839}
2840
2841/// The loop proper: setup, poll, teardown, with the queue and the status file
2842/// supplied rather than discovered.
2843///
2844/// All three of `home`, `worktrees_root` and the queue/status paths are
2845/// parameters rather than resolved here, for the same reason:
2846/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2847/// so a unit test that pinned it would fight every other test in the binary,
2848/// and a loop that resolved its own worktree bay could only be exercised
2849/// against the operator's real `~/wt/<repo>` - publishing over a live
2850/// daemon's status file, claiming tasks out of a live backlog, and, since
2851/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2852/// whatever the operator actually has on disk.
2853async fn drive(
2854    opts: &Opts,
2855    queue: &Queue,
2856    status_file: &Path,
2857    home: &Path,
2858    worktrees_root: &Path,
2859    stop: &Stop,
2860) -> Result<()> {
2861    // The status file is a *snapshot*, not a stream of events: a reader only
2862    // ever wants the latest values, and every tick rewrites the whole file
2863    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2864    // while an mpsc channel would force the loop to re-send unchanged fields on
2865    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2866    // for no gain. The lock is only ever held across a field assignment, never
2867    // across an await.
2868    let recovery_cfg = prepare(&opts.repo, opts).ok();
2869    let daemon_cfg = recovery_cfg
2870        .as_ref()
2871        .map(|c| c.daemon.clone())
2872        .unwrap_or_default();
2873    let reconciled = crate::driver::reconcile(home);
2874    if !reconciled.is_empty() {
2875        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2876    }
2877    let mut initial_status = Status::new();
2878    let owned = owned_task_jobs(home)?;
2879    initial_status.current = current_work(home, Timestamp::now())
2880        .into_iter()
2881        .filter(|current| {
2882            owned
2883                .iter()
2884                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2885        })
2886        .collect();
2887    initial_status.idle = initial_status.current.is_empty();
2888    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2889        recovery_cfg.as_ref(),
2890        daemon_cfg.max_deputies,
2891    ));
2892    let status = Arc::new(Mutex::new(initial_status));
2893    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2894    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2895
2896    // Read once at startup, not per task: how many runs this loop drives at
2897    // once is a property of the machine running it, not of whichever
2898    // repository a given task happens to name - see
2899    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2900    // fact in the same sense the agent roster is.
2901    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2902
2903    tracing::info!(
2904        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2905        queue.root().display(),
2906        opts.poll.as_secs(),
2907        opts.max_attempts,
2908        concurrency,
2909        if daemon_cfg.pause_for_interrupts {
2910            ", interrupts enabled"
2911        } else {
2912            ""
2913        }
2914    );
2915
2916    let outcome = tokio::select! {
2917        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2918            max_concurrent: concurrency,
2919            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2920            recovery_cfg,
2921        }) => outcome,
2922        () = async {
2923            while !stop.stopped() {
2924                tokio::time::sleep(Duration::from_millis(25)).await;
2925            }
2926        } => {
2927            if stop.parking() {
2928                request_control(home, crate::worker::Control::Park)?;
2929            }
2930            Ok(())
2931        }
2932    };
2933
2934    stop.busy.store(0, Ordering::SeqCst);
2935    beat.abort();
2936    clear_status_at(status_file);
2937    outcome
2938}
2939
2940/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2941/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2942pub(crate) fn release_watch_settings_from_config(
2943    home: &Path,
2944    repo: &Path,
2945    cfg: &Config,
2946) -> (Vec<PathBuf>, u64) {
2947    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2948        .into_iter()
2949        .map(|r| r.path)
2950        .collect();
2951    // Repositories the daemon has worked in, wherever they live: a task may
2952    // name one outside `[repos] roots`, and its release PR must be watched too.
2953    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
2954        .list()
2955        .into_iter()
2956        .map(|t| t.repo)
2957        .collect();
2958    let runs = home.join("runs");
2959    for id in crate::run::list_ids_in(&runs) {
2960        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2961            .ok()
2962            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2963            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2964        known.extend(repo);
2965    }
2966    for k in known {
2967        let k = k.canonicalize().unwrap_or(k);
2968        if k.join(".git").exists() && !paths.contains(&k) {
2969            paths.push(k);
2970        }
2971    }
2972    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2973    if !paths.contains(&own) {
2974        paths.push(own);
2975    }
2976    (paths, cfg.daemon.release_stall_minutes)
2977}
2978
2979/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2980const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2981
2982/// Refresh the status file on a fixed tick.
2983///
2984/// Separate from the loop because a run takes tens of minutes: a status file
2985/// written only between tasks would look stale for the whole of every run, and
2986/// a reader would report the daemon dead exactly while it was busiest.
2987async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2988    loop {
2989        tokio::time::sleep(HEARTBEAT).await;
2990        let snapshot = {
2991            let mut guard = lock(&status);
2992            guard.updated_at = Timestamp::now();
2993            guard.clone()
2994        };
2995        if let Err(e) = write_status_to(&path, &snapshot) {
2996            // A failed heartbeat must not take the daemon down: the loop is the
2997            // product, the status file is only the window onto it.
2998            tracing::warn!("could not refresh the daemon status file: {e:#}");
2999        }
3000    }
3001}
3002
3003/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3004/// if so, whether that wait is over.
3005#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3006enum LandResume {
3007    /// The task's last run is not parked on a land approval; schedule it
3008    /// like any other candidate.
3009    NotLanding,
3010    /// Parked in `land`, waiting on a question nobody has answered yet.
3011    /// Left alone: attempting it now would only re-observe the same pull
3012    /// request and park again, spending a `gh` call on a decision that has
3013    /// not changed since the last time this was checked.
3014    StillWaiting,
3015    /// Parked in `land`, and the question is settled - answered or
3016    /// abandoned. Resuming this is the one kind of candidate that must not
3017    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3018    Ready,
3019}
3020
3021/// Classify a runnable candidate by whether it is parked on a land-merge
3022/// approval. Read-only - no claim taken, nothing written - so it is cheap
3023/// enough to call on every candidate, every poll.
3024fn land_resume_state(task: &Task) -> LandResume {
3025    let Some(run_id) = task.runs.last() else {
3026        return LandResume::NotLanding;
3027    };
3028    let Ok(state) = RunState::load(run_id) else {
3029        return LandResume::NotLanding;
3030    };
3031    if !state.parked {
3032        return LandResume::NotLanding;
3033    }
3034    if state.status == RunStatus::Landing
3035        && state.land_approval.as_ref().is_some_and(|binding| {
3036            ask::Questions::open()
3037                .get(&binding.question)
3038                .is_ok_and(|q| {
3039                    q.run == state.id
3040                        && q.resolution()
3041                            .as_deref()
3042                            .is_some_and(crate::merge_decision::stops)
3043                })
3044        })
3045    {
3046        return LandResume::Ready;
3047    }
3048    if !implementers_match(task, &state) {
3049        return LandResume::NotLanding;
3050    }
3051    // Parked in `land` on the merge approval, or at `merge` on the owner's
3052    // word about a title/body the posting gate withheld. Told apart by the
3053    // run's own record, not by a status both can share.
3054    let node = if state.status == RunStatus::Landing {
3055        land::APPROVAL_NODE
3056    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3057        crate::github_text::ASK_NODE
3058    } else {
3059        return LandResume::NotLanding;
3060    };
3061    let store = ask::Questions::open();
3062    let waiting = store
3063        .list()
3064        .into_iter()
3065        .filter(|q| &q.run == run_id && q.node == node)
3066        .max_by(|a, b| a.id.cmp(&b.id));
3067    let Some(mut q) = waiting else {
3068        return LandResume::Ready;
3069    };
3070    if !q.status.open() {
3071        // Repair spends agent resources and must obey concurrency and quota
3072        // waits; only a merge/hold decision may use the decision-only lane.
3073        if q.resolution().as_deref() == Some(land::REPAIR) {
3074            return if state.liveness(false) == Liveness::Live {
3075                LandResume::StillWaiting
3076            } else {
3077                LandResume::NotLanding
3078            };
3079        }
3080        return LandResume::Ready;
3081    }
3082    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3083    // nobody ever answered; land's approval bypasses that wait entirely (see
3084    // `land::approval_gate`), so the same deadline has to be enforced here
3085    // instead, or `graph.answer_timeout` silently stops meaning anything for
3086    // a land approval and a run can sit `StillWaiting` forever with nobody
3087    // told to look at it.
3088    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3089    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3090    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3091        q.abandon(format!(
3092            "no answer within {}s of asking",
3093            timeout.as_secs().max(1)
3094        ));
3095        // If this can't be persisted, do not treat the wait as settled on a
3096        // guess: fall through and try again next poll.
3097        if store.put(&mut q).is_ok() {
3098            return LandResume::Ready;
3099        }
3100    }
3101    LandResume::StillWaiting
3102}
3103
3104/// How often the loop rechecks for new work while something it already
3105/// started is still running, rather than sleeping out the whole
3106/// [`Opts::poll`] interval.
3107///
3108/// Short on purpose: this is what lets a land-merge approval that comes back
3109/// while another task is mid-competition be noticed and resumed within a
3110/// fraction of a second, not within the next multi-second poll.
3111const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3112
3113/// How often [`poll`] rechecks the shared build cache against its cap at a
3114/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3115/// waiting for the queue to run dry.
3116///
3117/// A queue that never empties means the `janitor` call at the bottom of this
3118/// loop's fully-idle branch can go unreached for as long as the backlog
3119/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3120/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3121/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3122/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3123/// backlog of short tasks does not pay for that walk on every poll.
3124const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3125
3126/// State of [`poll`]'s own interrupt-scheduling sequence - see
3127/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3128/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3129/// both kept free of `Task`'s non-identity fields on purpose: every decision
3130/// here turns only on task ids and which ones are in flight, so the "never
3131/// more than one run at once" and "exactly one resume" invariants can be
3132/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3133/// queue - which is exactly the coverage this feature's first two attempts
3134/// were missing.
3135///
3136/// Persisted after every transition, so scheduler replacement preserves the
3137/// interrupt's exclusive turn and the interrupted task's priority resume.
3138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3139enum Interrupt {
3140    /// No interrupt sequence in progress. Ordinary dispatch applies.
3141    Idle,
3142    /// `interrupt_task` is runnable and exactly one other run is in flight;
3143    /// `parked` names that one task's id. Dispatch is withheld from
3144    /// everyone, including `interrupt_task` itself, until it has left
3145    /// flight - only then is `interrupt_task` let through.
3146    ///
3147    /// `parked` is a `Vec` rather than a bare id for symmetry with
3148    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3149    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3150    /// when exactly one run is in flight, so it is guaranteed to hold
3151    /// exactly one entry in practice - see that branch's own doc for why
3152    /// more than one is deliberately never attempted.
3153    Parking {
3154        parked: Vec<String>,
3155        interrupt_task: String,
3156    },
3157    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3158    /// withheld from everyone until it leaves flight - merged, failed, held,
3159    /// it makes no difference - at which point the sequence moves to
3160    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3161    /// going straight to `Idle` would hand `parked` back to ordinary
3162    /// priority-order dispatch, where a higher-priority task filed in the
3163    /// meantime could start ahead of it.
3164    Running {
3165        parked: Vec<String>,
3166        interrupt_task: String,
3167    },
3168    /// `interrupt_task` left flight; `parked` still names the one run this
3169    /// sequence owes a resume. Dispatch is withheld from everyone except
3170    /// that task - see [`interrupt_gate`] - so the resume this feature
3171    /// promises is never raced by, or run alongside, an unrelated candidate.
3172    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3173    /// own doc on abandonment - the moment it is no longer runnable at all.
3174    Resuming { parked: Vec<String> },
3175}
3176
3177/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3178/// and `runnable` are read-only snapshots of this tick's reality, and the
3179/// only side effect the caller still owes the world is asking whichever
3180/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3181/// site.
3182///
3183/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3184/// accepted rather than a narrower type because that is what [`poll`] already
3185/// has on hand from [`runnable`], and building a second, smaller list on
3186/// every tick just to satisfy this signature would cost more than it proves.
3187///
3188/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3189/// back to a task they are waiting on no longer being [`runnable`] - held,
3190/// blocked, deleted, or finished by some other means entirely, all of which
3191/// an operator can do to a task sitting in the queue with no claim on it at
3192/// all, at any moment, interrupt sequence or not. Without this check the
3193/// sequence would wait forever for a dispatch that can never come, and
3194/// `interrupt_gate` would withhold every other task in the queue right along
3195/// with it - a single `magi task hold` on the wrong id turning into a
3196/// daemon that never dispatches anything again.
3197fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3198    match state {
3199        Interrupt::Idle => {
3200            // Not just "something to interrupt": exactly one thing. More
3201            // than one run in flight only happens above the default
3202            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3203            // one resume, never run alongside anything else" only because
3204            // it is only ever seeded with exactly one id - see
3205            // `Interrupt::Resuming`'s own doc on why releasing more than one
3206            // parked id back to ordinary dispatch cannot be made safe
3207            // against that same setting's own extra concurrency slots.
3208            // Waiting here for the herd to settle to one is the
3209            // simplification this feature's own constraints ask for rather
3210            // than a second concurrency model to reconcile with the first.
3211            if in_flight.len() != 1 {
3212                return Interrupt::Idle;
3213            }
3214            match runnable.iter().find(|t| t.interrupt) {
3215                Some(t) => Interrupt::Parking {
3216                    parked: in_flight.to_vec(),
3217                    interrupt_task: t.id.clone(),
3218                },
3219                None => Interrupt::Idle,
3220            }
3221        }
3222        Interrupt::Parking {
3223            parked,
3224            interrupt_task,
3225        } => {
3226            if in_flight.iter().any(|id| parked.contains(id)) {
3227                // Still waiting for what was in flight to actually stop.
3228                Interrupt::Parking {
3229                    parked,
3230                    interrupt_task,
3231                }
3232            } else if in_flight.contains(&interrupt_task) {
3233                Interrupt::Running {
3234                    parked,
3235                    interrupt_task,
3236                }
3237            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3238                // The parked run(s) are gone, but the interrupt task has not
3239                // been dispatched yet on this tick - `interrupt_gate` is
3240                // what lets it through next.
3241                Interrupt::Parking {
3242                    parked,
3243                    interrupt_task,
3244                }
3245            } else {
3246                // The interrupt task itself is no longer runnable - see this
3247                // function's own doc on abandonment. The parked run(s) still
3248                // get their guaranteed resume; there is simply no interrupt
3249                // to run ahead of them any longer.
3250                Interrupt::Resuming { parked }
3251            }
3252        }
3253        Interrupt::Running {
3254            parked,
3255            interrupt_task,
3256        } => {
3257            if in_flight.contains(&interrupt_task) {
3258                Interrupt::Running {
3259                    parked,
3260                    interrupt_task,
3261                }
3262            } else {
3263                // The interrupt task's own run reached a terminal status,
3264                // whichever one - this is the *only* trigger that moves the
3265                // sequence on, driven straight off the same in-flight
3266                // bookkeeping `poll` already reaps every tick, not a second,
3267                // independent poll of anything.
3268                Interrupt::Resuming { parked }
3269            }
3270        }
3271        Interrupt::Resuming { parked } => {
3272            if in_flight.iter().any(|id| parked.contains(id)) {
3273                // One of the parked runs has been dispatched - the resume
3274                // this sequence owed is fulfilled. Whatever else is left in
3275                // `parked` (ordinarily nothing, at the default concurrency
3276                // of one) rejoins ordinary priority-order dispatch, same as
3277                // any other runnable task.
3278                Interrupt::Idle
3279            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3280                Interrupt::Resuming { parked }
3281            } else {
3282                // Abandonment (see this function's own doc): nothing left in
3283                // `parked` is even runnable any longer.
3284                Interrupt::Idle
3285            }
3286        }
3287    }
3288}
3289
3290/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3291/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3292/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3293/// indistinguishable from any other runnable task - exactly the "off does
3294/// nothing" this feature promises.
3295fn advance_interrupt_tick(
3296    enabled: bool,
3297    state: Interrupt,
3298    in_flight: &[String],
3299    runnable: &[Task],
3300) -> Interrupt {
3301    if !enabled {
3302        return Interrupt::Idle;
3303    }
3304    advance_interrupt(state, in_flight, runnable)
3305}
3306
3307/// Which of this tick's runnable candidates the interrupt sequence actually
3308/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3309/// each half is assertable on its own: this is the half that keeps a
3310/// competition and an interrupt from ever running at the same moment.
3311fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3312    match state {
3313        Interrupt::Idle => candidates,
3314        Interrupt::Parking {
3315            parked,
3316            interrupt_task,
3317        } => {
3318            if in_flight.iter().any(|id| parked.contains(id)) {
3319                Vec::new()
3320            } else {
3321                candidates
3322                    .into_iter()
3323                    .filter(|t| &t.id == interrupt_task)
3324                    .collect()
3325            }
3326        }
3327        Interrupt::Running { .. } => Vec::new(),
3328        // At most one: even if `parked` names more than one id (more than
3329        // one run was in flight when the sequence began, only possible
3330        // above the default `max_concurrent_runs = 1`), only the first match
3331        // is offered. Capping this to a single candidate - not merely to
3332        // `parked`'s own ids - is what makes "exactly one resume, never two
3333        // dispatched together" true regardless of how many ordinary slots
3334        // happen to be free this tick.
3335        Interrupt::Resuming { parked } => candidates
3336            .into_iter()
3337            .find(|t| parked.contains(&t.id))
3338            .into_iter()
3339            .collect(),
3340    }
3341}
3342
3343/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3344/// bundled into one parameter so `poll`'s own signature stays readable -
3345/// see [`drive`]'s call site for where these are actually read.
3346struct DispatchLimits {
3347    /// How many *ordinary* candidates run at once. See
3348    /// [`crate::config::Daemon::max_concurrent_runs`].
3349    max_concurrent: usize,
3350    /// See [`crate::config::Daemon::pause_for_interrupts`].
3351    pause_for_interrupts: bool,
3352    recovery_cfg: Option<Config>,
3353}
3354
3355/// Which semaphore, if any, dispatching a candidate should draw its permit
3356/// from.
3357///
3358/// Pure and separate from [`poll`]'s loop body for the same reason
3359/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3360/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3361/// exactly the policy this feature adds, and a policy only exercisable by
3362/// running the whole loop is a policy nobody checks.
3363#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3364enum PermitKind {
3365    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3366    /// Checked first - a task can be both a land resume and marked
3367    /// [`Task::urgent`], and the resume's own "must not queue behind
3368    /// anything" guarantee takes precedence.
3369    None,
3370    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3371    /// (never in addition to trying) the ordinary pool. This is what lets
3372    /// an urgent task dispatch while every ordinary slot is already checked
3373    /// out, and what stops a second urgent task from opening a third run: it
3374    /// waits on this same one-slot semaphore rather than falling through to
3375    /// the ordinary one.
3376    Urgent,
3377    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3378    /// above.
3379    #[default]
3380    Ordinary,
3381}
3382
3383/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3384/// own boolean, already computed by the caller from [`land_resume_state`].
3385fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3386    if priority {
3387        PermitKind::None
3388    } else if urgent {
3389        PermitKind::Urgent
3390    } else {
3391        PermitKind::Ordinary
3392    }
3393}
3394
3395fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3396    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3397        (0usize, 0usize),
3398        |(ordinary, urgent), request| match request.lane {
3399            PermitKind::Ordinary => (ordinary + 1, urgent),
3400            PermitKind::Urgent => (ordinary, urgent + 1),
3401            PermitKind::None => (ordinary, urgent),
3402        },
3403    );
3404    (
3405        limit.saturating_sub(ordinary),
3406        1usize.saturating_sub(urgent),
3407    )
3408}
3409
3410struct DispatchClaim {
3411    task: Task,
3412    claim: crate::queue::Claim,
3413    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3414}
3415
3416/// Claim and re-read before choosing a lane: a queue listing may predate an
3417/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3418fn claim_dispatch(
3419    queue: &Queue,
3420    candidate: &Task,
3421    cooling_down: bool,
3422    ordinary: &Arc<tokio::sync::Semaphore>,
3423    urgent: &Arc<tokio::sync::Semaphore>,
3424) -> Option<DispatchClaim> {
3425    let Ok(claim) = queue.claim(&candidate.id) else {
3426        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3427        return None;
3428    };
3429    let task = match queue.get(&candidate.id) {
3430        Ok(t) if t.status.runnable() => t,
3431        Ok(_) => return None,
3432        Err(e) => {
3433            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3434            return None;
3435        }
3436    };
3437    let resume = land_resume_state(&task);
3438    if resume == LandResume::StillWaiting {
3439        return None;
3440    }
3441    let priority = resume == LandResume::Ready;
3442    if !priority && cooling_down {
3443        return None;
3444    }
3445    // Never borrow an ordinary slot when the single urgent slot is busy.
3446    // Keep scanning other candidates when either pool has no free slot.
3447    let permit = match permit_kind(priority, task.urgent) {
3448        PermitKind::None => None,
3449        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3450        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3451    };
3452    // Persist the dispatch order under the claim, before config discovery or
3453    // coordination waits can reorder concurrent starts.
3454    let stamp = Timestamp::now();
3455    let mut task = task;
3456    task.dispatched_at = Some(stamp);
3457    if let Err(e) = queue.modify(&task.id, |t| {
3458        t.dispatched_at = Some(stamp);
3459        true
3460    }) {
3461        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3462    }
3463    Some(DispatchClaim {
3464        task,
3465        claim,
3466        permit,
3467    })
3468}
3469
3470/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3471/// teardown and cannot skip the teardown on an early return.
3472///
3473/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3474/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3475/// land approval that has since been answered is dispatched outside that
3476/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3477/// the whole point of parking there is that it must not queue behind
3478/// whatever else the loop happens to be running, even at the default of one.
3479/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3480/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3481/// these exemptions is still subject to the interrupt gate below, urgent
3482/// included: a land-resume or urgent candidate is exactly as much "something
3483/// else running" as an ordinary one from the interrupt sequence's point of
3484/// view, and letting either slip through while a run is being parked, or
3485/// while the interrupt task itself has the floor, is precisely the second
3486/// run 75dd's own "at most one run, ever, at once" guarantee must never
3487/// allow - see [`Interrupt`]'s own doc.
3488#[derive(Serialize, Deserialize)]
3489struct ServiceWorker {
3490    opts: Opts,
3491    queue: PathBuf,
3492    worktrees_root: PathBuf,
3493    operation: String,
3494}
3495
3496fn load_conductor(home: &Path) -> Result<Conductor> {
3497    match std::fs::read(home.join("conductor-state.json")) {
3498        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3499        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3500        Err(error) => Err(error.into()),
3501    }
3502}
3503
3504fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3505    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3506        .into_iter()
3507        .map(|c| c.task)
3508        .collect();
3509    let stalled = stalled_tasks(queue, home, Timestamp::now());
3510    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3511    let finished = finished_tasks(queue)
3512        .into_iter()
3513        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3514        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3515        .collect();
3516    let queued = queued_tasks(queue)
3517        .into_iter()
3518        .filter(|t| !live.contains(&t.id))
3519        .collect();
3520    (queued, stalled, finished)
3521}
3522
3523async fn start_service(
3524    home: &Path,
3525    opts: &Opts,
3526    queue: &Queue,
3527    worktrees_root: &Path,
3528    operation: &str,
3529    cfg: Option<&Config>,
3530    busy: bool,
3531) -> Result<()> {
3532    // Fetch policy is live configuration, unlike question recovery capacity.
3533    // Reload before both cadence and eligibility, including disabled -> enabled.
3534    let fetch_cfg = if operation == "fetch" {
3535        match prepare(&opts.repo, opts) {
3536            Ok(cfg) => Some(cfg),
3537            Err(error) => {
3538                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3539                return Ok(());
3540            }
3541        }
3542    } else {
3543        None
3544    };
3545    let cfg = fetch_cfg.as_ref().or(cfg);
3546    let ticks = home.join("service-ticks");
3547    std::fs::create_dir_all(&ticks)?;
3548    let receipt = ticks.join(format!("daemon-{operation}"));
3549    let last = std::fs::read(&receipt)
3550        .ok()
3551        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3552    let interval = match operation {
3553        "disk-pressure" => 30,
3554        "cache" => CACHE_CHECK_INTERVAL_SECS,
3555        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3556        _ => opts.poll.as_secs().max(1),
3557    };
3558    let now = Timestamp::now();
3559    if !cache_check_due(last, now, interval) {
3560        return Ok(());
3561    }
3562    let key = format!("service:daemon-{operation}");
3563    if crate::worker::active(home)?
3564        .iter()
3565        .any(|job| job.key == key)
3566    {
3567        return Ok(());
3568    }
3569    let eligible = match operation {
3570        "conductor" => {
3571            let (queued, stalled, finished) = conductor_work(queue, home);
3572            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3573                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3574        }
3575        "maintenance" => Questions::at(home.join("questions"))
3576            .list()
3577            .iter()
3578            .any(|q| {
3579                q.chosen_action().is_some_and(|action| action.maintenance())
3580                    && !home
3581                        .join("choice-actions")
3582                        .join(format!("{}.json", q.id))
3583                        .exists()
3584            }),
3585        "housekeeping" => !busy && runnable(queue).is_empty(),
3586        "cache" => {
3587            !busy
3588                && !runnable(queue).is_empty()
3589                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3590        }
3591        "disk-pressure" => busy,
3592        "fetch" => {
3593            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3594        }
3595        _ => false,
3596    };
3597    if !eligible {
3598        return Ok(());
3599    }
3600    let request = ServiceWorker {
3601        opts: opts.absolute()?,
3602        queue: std::path::absolute(queue.root())?,
3603        worktrees_root: std::path::absolute(worktrees_root)?,
3604        operation: operation.to_owned(),
3605    };
3606    if let Err(error) =
3607        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3608    {
3609        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3610    }
3611    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3612    Ok(())
3613}
3614
3615/// Finite maintenance jobs survive scheduler replacement without duplicating
3616/// agent calls or cancelling an operation between its effect and receipt.
3617pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3618    let request: ServiceWorker = serde_json::from_value(payload)?;
3619    let opts = &request.opts;
3620    let queue = Queue::at(request.queue);
3621    let questions = Questions::at(home.join("questions"));
3622    match request.operation.as_str() {
3623        "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3624        "conductor" => {
3625            let path = home.join("conductor-state.json");
3626            let mut conductor = load_conductor(home)?;
3627            let (queued, stalled, finished) = conductor_work(&queue, home);
3628            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3629                && conductor.worth_a_look(&queue, &stalled, &finished)
3630            {
3631                let cfg = prepare(&opts.repo, opts)?;
3632                conductor
3633                    .maybe_run(
3634                        &cfg,
3635                        &opts.repo,
3636                        &queue,
3637                        &questions,
3638                        home,
3639                        &queued,
3640                        &stalled,
3641                        &finished,
3642                        opts.max_attempts,
3643                    )
3644                    .await;
3645                let temporary = path.with_extension("json.tmp");
3646                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3647                std::fs::rename(temporary, path)?;
3648            }
3649        }
3650        "fetch" => {
3651            let cfg = prepare(&opts.repo, opts)?;
3652            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3653                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3654                tracing::debug!("fetch origins: {outcome:?}");
3655            }
3656        }
3657        "cache" => {
3658            if task_jobs(home)?.is_empty() {
3659                let mut checked = None;
3660                maybe_prune_cache_between_runs(
3661                    &opts.repo,
3662                    opts,
3663                    home,
3664                    &Stop::new(),
3665                    &mut checked,
3666                    Timestamp::now(),
3667                )
3668                .await;
3669            }
3670        }
3671        "disk-pressure" => {
3672            if let Ok(cfg) = prepare(&opts.repo, opts) {
3673                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3674                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3675                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3676                }
3677                for current in current_work(home, Timestamp::now()) {
3678                    if let Ok(state) = RunState::load_under(&current.run, home)
3679                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3680                    {
3681                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3682                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3683                        }) {
3684                            request_task_park(
3685                                home,
3686                                &job,
3687                                crate::run::ParkCause::Interrupt {
3688                                    reason: reason.clone(),
3689                                },
3690                            )?;
3691                        }
3692                        notices::raise_in(
3693                            home,
3694                            Notice::warn(
3695                                "disk:pressure",
3696                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3697                            ),
3698                        );
3699                    }
3700                }
3701            }
3702        }
3703        "housekeeping" => {
3704            if task_jobs(home)?.is_empty() {
3705                if let Ok(cfg) = prepare(&opts.repo, opts) {
3706                    crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3707                }
3708                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3709                resweep_superseded_attempts(&queue, home);
3710                triage_held(&queue, home, opts).await;
3711            }
3712        }
3713        operation => bail!("unknown daemon service {operation}"),
3714    }
3715    Ok(())
3716}
3717
3718/// Only a different request under the same key is a dispatch handoff race.
3719/// Our own unacknowledged reservation is a startup failure, not competing work:
3720/// stop dispatch without fencing it, so an already detached child may still run.
3721fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3722    let key = format!("task:{}", request.task);
3723    let payload = serde_json::to_value(request)?;
3724    if crate::worker::active(home)?
3725        .iter()
3726        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3727    {
3728        tracing::warn!(
3729            "task {} acquired a competing worker reservation: {error:#}",
3730            crate::run::short_of(&request.task)
3731        );
3732        return Ok(());
3733    }
3734    tracing::error!("task worker startup stopped dispatch: {error:#}");
3735    notices::raise_in(
3736        home,
3737        Notice::error(
3738            "loop:worker-startup",
3739            // Startup diagnostics may contain private child-process details;
3740            // keep them in the local error/log rather than the chat or notifier.
3741            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),
3742        ).link(Link::Task { id: request.task.clone() }),
3743    );
3744    Err(error).with_context(|| {
3745        format!(
3746            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3747            crate::run::short_of(&request.task)
3748        )
3749    })
3750}
3751
3752async fn poll(
3753    opts: &Opts,
3754    queue: &Queue,
3755    status: &Arc<Mutex<Status>>,
3756    home: &Path,
3757    worktrees_root: &Path,
3758    stop: &Stop,
3759    limits: DispatchLimits,
3760) -> Result<()> {
3761    let mut attempted = Vec::new();
3762    let mut settling_once_services = false;
3763    let interrupt_path = home.join("scheduler-interrupt.json");
3764    let mut interrupt = match std::fs::read(&interrupt_path) {
3765        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3766        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3767        Err(error) => return Err(error.into()),
3768    };
3769    let mut previous = std::collections::BTreeSet::<String>::new();
3770    while !stop.stopped() {
3771        let jobs: Vec<_> = crate::worker::active(home)?
3772            .into_iter()
3773            .filter(|job| job.kind == "task")
3774            .collect();
3775        let requests: Vec<_> = jobs
3776            .iter()
3777            .map(|job| {
3778                serde_json::from_value::<TaskWorker>(job.payload.clone())
3779                    .with_context(|| format!("read live task worker {}", job.id))
3780            })
3781            .collect::<Result<_>>()?;
3782        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3783        let owned: std::collections::BTreeSet<_> = requests
3784            .iter()
3785            .filter(|r| !r.standalone)
3786            .map(|r| r.task.clone())
3787            .collect();
3788        let current: Vec<_> = requests
3789            .iter()
3790            .zip(&jobs)
3791            .filter(|(request, _)| !request.standalone)
3792            .map(|(request, job)| Current {
3793                worker: Some(job.id.clone()),
3794                task: request.task.clone(),
3795                run: queue
3796                    .get(&request.task)
3797                    .ok()
3798                    .and_then(|task| task.runs.last().cloned())
3799                    .unwrap_or_default(),
3800            })
3801            .collect();
3802        {
3803            let mut snapshot = lock(status);
3804            snapshot.polls += 1;
3805            snapshot.completed += previous.difference(&owned).count();
3806            snapshot.current = current;
3807            snapshot.idle = owned.is_empty();
3808        }
3809        previous = owned.clone();
3810        stop.busy.store(owned.len(), Ordering::SeqCst);
3811
3812        // Slots are reconstructed from durable reservations and OS-held worker
3813        // leases, not this scheduler's lifetime or mutable task urgency.
3814        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3815        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3816        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3817        let mut permits = Vec::new();
3818        sweep_stale_claims(queue, STALE_CLAIM);
3819        reclaim_orphaned_running(queue, opts.max_attempts, &live);
3820        reclaim_abandoned_runs(home, Timestamp::now());
3821        let questions = Questions::at(home.join("questions"));
3822
3823        // Deterministic: no model, run before the conductor sees anything so
3824        // its input reflects the queue's current, already-resolved state.
3825        crate::task_chat::sweep(
3826            queue,
3827            &crate::talk::Talks::at(home.join("talks")),
3828            &questions,
3829            home,
3830        );
3831        repair_choice_offers(&questions);
3832        resolve_blockers(queue, &questions);
3833        apply_task_choice_actions(queue, &questions, home);
3834        triage::apply_answers(queue, &questions);
3835        reconcile_task_questions(queue, &questions);
3836        let talks = crate::talk::Talks::at(home.join("talks"));
3837        crate::chat_notify::sweep(queue, &talks, home);
3838        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3839        crate::chat_watch::sweep(home, &talks);
3840        let mut turns = tokio::task::JoinSet::new();
3841        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3842        // start_turns dispatches detached turns; no paid work lives in this set.
3843        while turns.join_next().await.is_some() {}
3844
3845        crate::consult::start_services(
3846            home,
3847            &opts.repo,
3848            limits.recovery_cfg.as_ref(),
3849            opts.config.as_deref(),
3850        )
3851        .await?;
3852        for operation in [
3853            "conductor",
3854            "maintenance",
3855            "housekeeping",
3856            "disk-pressure",
3857            "cache",
3858            "fetch",
3859        ] {
3860            // Once an idle --once drain starts settling services, subsequent
3861            // scans only consume their effects. An expired cadence receipt
3862            // must not start another service and keep the drain alive.
3863            if settling_once_services {
3864                break;
3865            }
3866            start_service(
3867                home,
3868                opts,
3869                queue,
3870                worktrees_root,
3871                operation,
3872                limits.recovery_cfg.as_ref(),
3873                !live.is_empty(),
3874            )
3875            .await?;
3876        }
3877        let latest = crate::worker::active(home)?;
3878        if latest.iter().any(|job| job.key == "service:daemon-cache")
3879            || latest
3880                .iter()
3881                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3882        {
3883            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3884            continue;
3885        }
3886        let candidates: Vec<Task> = runnable(queue)
3887            .into_iter()
3888            .filter(|task| !live.contains(&task.id))
3889            .filter(|task| !opts.once || !attempted.contains(&task.id))
3890            .collect();
3891        let in_flight: Vec<_> = owned.iter().cloned().collect();
3892        let prior_interrupt = std::mem::discriminant(&interrupt);
3893        interrupt = advance_interrupt_tick(
3894            limits.pause_for_interrupts,
3895            interrupt,
3896            &in_flight,
3897            &candidates,
3898        );
3899        // Same-variant transitions preserve their identities. Only an actual
3900        // transition needs a durable write, atomically before sending controls.
3901        if prior_interrupt != std::mem::discriminant(&interrupt) {
3902            let temporary = interrupt_path.with_extension("json.tmp");
3903            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3904            std::fs::rename(temporary, &interrupt_path)?;
3905        }
3906        if let Interrupt::Parking {
3907            parked,
3908            interrupt_task,
3909        } = &interrupt
3910        {
3911            for job in jobs.iter().filter(|job| {
3912                parked
3913                    .iter()
3914                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3915            }) {
3916                if crate::worker::control(home, &job.key)?.is_none() {
3917                    request_task_park(
3918                        home,
3919                        job,
3920                        crate::run::ParkCause::Interrupt {
3921                            reason: format!(
3922                                "task {} asked to run first",
3923                                crate::run::short_of(interrupt_task)
3924                            ),
3925                        },
3926                    )?;
3927                }
3928            }
3929        }
3930        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3931        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3932        let mut started = false;
3933        let mut resync = false;
3934        for candidate in candidates {
3935            if stop.stopped() {
3936                break;
3937            }
3938            let Some(DispatchClaim {
3939                task,
3940                claim,
3941                permit,
3942            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
3943            else {
3944                continue;
3945            };
3946            if crate::worker::active(home)?
3947                .iter()
3948                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3949            {
3950                drop(claim);
3951                resync = true;
3952                break;
3953            }
3954            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
3955            let request = TaskWorker {
3956                opts: opts.absolute()?,
3957                queue: std::path::absolute(queue.root())?,
3958                task: task.id.clone(),
3959                lane,
3960                standalone: false,
3961            };
3962            // Keep the claim until spawn acknowledges the worker's durable
3963            // reservation. The worker then claims and re-reads before attempt.
3964            if let Err(error) = crate::worker::spawn(
3965                home,
3966                "task",
3967                &format!("task:{}", task.id),
3968                serde_json::to_value(&request)?,
3969            )
3970            .await
3971            {
3972                task_worker_spawn_error(home, &request, error)?;
3973                drop(claim);
3974                resync = true;
3975                break;
3976            }
3977            drop(claim);
3978            permits.extend(permit);
3979            attempted.push(task.id);
3980            started = true;
3981        }
3982        if started || resync {
3983            continue;
3984        }
3985        if owned.is_empty() && opts.once {
3986            settling_once_services = true;
3987            // These finite services can own queue claims or publish answers.
3988            // A skipped claim is not an idle queue until they have finished;
3989            // scan again afterwards so their changes are actually scheduled.
3990            if crate::worker::active(home)?.iter().any(|job| {
3991                job.kind == "daemon-service"
3992                    && matches!(
3993                        job.key.as_str(),
3994                        "service:daemon-housekeeping"
3995                            | "service:daemon-conductor"
3996                            | "service:daemon-maintenance"
3997                    )
3998            }) {
3999                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4000                continue;
4001            }
4002            break;
4003        }
4004        stop.idle(if live.is_empty() {
4005            opts.poll
4006        } else {
4007            RECHECK_WHILE_BUSY.min(opts.poll)
4008        })
4009        .await;
4010    }
4011    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4012    // every queue claim and Runner driver lease through outcome settlement.
4013    stop.busy.store(0, Ordering::SeqCst);
4014    Ok(())
4015}
4016
4017/// A maintenance pass may briefly own the same record while a worker starts.
4018/// Wait without blocking the executor or charging an agent attempt, then read
4019/// ownership again under the acquired lock. Other I/O failures still fail closed.
4020async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4021    let busy = |error: &anyhow::Error| {
4022        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4023            error.kind() == std::io::ErrorKind::WouldBlock
4024                || cfg!(windows) && error.raw_os_error() == Some(33)
4025        })
4026    };
4027    match crate::pr_head::owner_lock(home, id) {
4028        Ok(lock) => return Ok(lock),
4029        Err(error) if busy(&error) => {}
4030        Err(error) => return Err(error),
4031    }
4032    let wait = RunState::load_under(id, home)?
4033        .config
4034        .graph
4035        .timeout_resource_wait;
4036    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4037}
4038
4039/// Historical successors do not revoke a still-resumable public owner. Scan
4040/// under the same lock as publication/driver claims, and fail closed on unknown
4041/// history before spending another attempt.
4042async fn public_resume_owner(
4043    home: &Path,
4044    runs: &[String],
4045    repo: &Path,
4046) -> Result<Option<RunState>> {
4047    let mut owner = None;
4048    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4049        let _lock = resume_owner_lock(home, id).await?;
4050        let state = RunState::load_under(id, home)?;
4051        if state.released()
4052            || state.retired_to.is_some()
4053            || state.pr_taken_over_by.is_some()
4054            || !crate::handover::landing_checkpoint(&state)
4055        {
4056            continue;
4057        }
4058        anyhow::ensure!(
4059            crate::git::toplevel(&state.repo).await?.canonicalize()?
4060                == crate::git::toplevel(repo).await?.canonicalize()?,
4061            "public owner repository differs; inspect run lineage"
4062        );
4063        anyhow::ensure!(
4064            owner.is_none(),
4065            "multiple retained public owners; inspect run lineage"
4066        );
4067        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4068            anyhow::bail!(reason.diagnostic(&state));
4069        }
4070        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4071        anyhow::ensure!(
4072            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4073            "public owner's driver is live or unknown; wait before retrying"
4074        );
4075        owner = Some(state);
4076    }
4077    Ok(owner)
4078}
4079
4080/// Run one claimed task to a terminal status and record the outcome.
4081///
4082/// Every transition is flushed to the queue as it happens, so the state on disk
4083/// is what actually occurred rather than what this process still intends to
4084/// write.
4085async fn attempt(
4086    opts: &Opts,
4087    queue: &Queue,
4088    status: &Arc<Mutex<Status>>,
4089    stop: &Stop,
4090    interrupt_pause: crate::graph::Pause,
4091    task: &mut Task,
4092) -> Vec<QuotaLoss> {
4093    let repo = repo_for(task, &opts.repo);
4094    tracing::info!(
4095        "task {} — {} (repo {})",
4096        task.short(),
4097        task.title,
4098        repo.display()
4099    );
4100
4101    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4102        Ok(owner) => owner,
4103        Err(e) => {
4104            task.hold_machine(Some(format!(
4105                "Cannot verify existing public owner: {e:#}; no attempt started."
4106            )));
4107            record(queue, task);
4108            return Vec::new();
4109        }
4110    };
4111    let resume_runs = public_owner
4112        .as_ref()
4113        .map(|s| vec![s.id.clone()])
4114        .unwrap_or_else(|| task.runs.clone());
4115
4116    // A stop spends no agent resources and uses the saved landing owner.
4117    // Current roster edits, missing attachments or a failed config fetch must
4118    // never turn it into a new implementation, or prevent a PR from closing.
4119    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4120        && previous
4121            .merge_decision
4122            .as_ref()
4123            .is_some_and(|decision| !decision.closed)
4124        && previous.status != RunStatus::Landing
4125        && !crate::merge_decision::resumable_hold(&previous)
4126    {
4127        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)));
4128        record(queue, task);
4129        return Vec::new();
4130    }
4131    let stop_owner = resume_runs
4132        .last()
4133        .and_then(|id| RunState::load(id).ok())
4134        .filter(|state| {
4135            crate::merge_decision::resumable_hold(state)
4136                || state.status == RunStatus::Landing
4137                    && state.land_approval.as_ref().is_some_and(|binding| {
4138                        Questions::open().get(&binding.question).is_ok_and(|q| {
4139                            q.run == state.id
4140                                && q.resolution()
4141                                    .as_deref()
4142                                    .is_some_and(crate::merge_decision::stops)
4143                        })
4144                    })
4145        });
4146    if let Some(owner) = stop_owner {
4147        let mut runner = match Runner::resume(&owner.id) {
4148            Ok(runner) => runner,
4149            Err(e) => {
4150                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4151                record(queue, task);
4152                return Vec::new();
4153            }
4154        };
4155        runner.on_pause(stop.pause());
4156        runner.watch_interrupt(interrupt_pause);
4157        let quota_before = runner.state.quota.clone();
4158        task.start(owner.id.clone());
4159        record(queue, task);
4160        lock(status).current.push(Current {
4161            worker: None,
4162            task: task.id.clone(),
4163            run: owner.id,
4164        });
4165        runner.state.next_pass_task_entry = true;
4166        let result = runner.execute().await;
4167        return finish_attempt(
4168            opts.max_attempts,
4169            queue,
4170            task,
4171            &runner.state,
4172            &quota_before,
4173            result,
4174        );
4175    }
4176
4177    if let Some(owner) = &public_owner
4178        && (task.fresh_start || !may_resume_run(owner, task))
4179    {
4180        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)));
4181        record(queue, task);
4182        return Vec::new();
4183    }
4184
4185    if let Some(state) = task.runs.last().and_then(|id| RunState::load(id).ok())
4186        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4187    {
4188        task.hold_machine(Some(reason));
4189        record(queue, task);
4190        return Vec::new();
4191    }
4192
4193    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4194        && !task.fresh_start
4195        && task.pr_recovery.is_none()
4196    {
4197        // Authorization still takes the owner lock and execution lease and
4198        // rechecks liveness, retained HEAD and ownership before saving.
4199        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4200            true
4201        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4202            let home = queue.root().parent().expect("queue has a home");
4203            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4204                Ok(()) => true,
4205                Err(error) => {
4206                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4207                    false
4208                }
4209            }
4210        } else {
4211            false
4212        };
4213        if !authorized {
4214            task.hold_machine(Some(format!("Base synchronization remains stopped. {} A release without a new owner approval grants no additional synchronization budget and starts no replacement competition.", held.base_sync_next_action())));
4215            // Retain the existing stop identity when an old release reached the queue.
4216            task.base_sync_notice(&held);
4217            task.resume_override = None;
4218            record(queue, task);
4219            return Vec::new();
4220        }
4221    }
4222    let unfinished = (!task.fresh_start)
4223        .then(|| unfinished_run(&resume_runs, task.short()))
4224        .flatten()
4225        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4226    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4227    if !task.fresh_start
4228        && task.pr_recovery.is_none()
4229        && task.review_branch.is_none()
4230        && task.resume_override.is_none()
4231        && previous
4232            .as_ref()
4233            .is_some_and(|run| run.retired_to.is_some())
4234        && unfinished.is_none()
4235    {
4236        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()));
4237        record(queue, task);
4238        return Vec::new();
4239    }
4240
4241    let saved_recovery = previous.as_ref().filter(|run| {
4242        task.replacement.is_none()
4243            && task.pr_recovery.as_ref().is_some_and(|selected| {
4244                selected.check_task(&task.id, &task.instruction).is_ok()
4245                    && selected_starter(selected, Some(run), unfinished.as_deref())
4246                        == Starter::Resume(run.id.clone())
4247            })
4248    });
4249
4250    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4251    // failure here is the network's or the operator's, not the task's: hold
4252    // without spending an attempt, never fall back to a possibly stale copy.
4253    let explicit = match &task.overrides {
4254        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4255        Some(_) => opts.config.as_deref(),
4256        None => opts.config.as_deref(),
4257    };
4258    let (mut config, layers) = if let Some(run) = saved_recovery {
4259        // A matching resume owns its resolved configuration and evidence;
4260        // current layers and inherited overrides only configure new work.
4261        let mut saved = run.clone();
4262        if let Err(e) = saved.configure_recovery_resume() {
4263            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4264            record(queue, task);
4265            return Vec::new();
4266        }
4267        (saved.config, Vec::new())
4268    } else {
4269        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4270            Ok(loaded) => loaded,
4271            Err(e) => {
4272                let reason = format!("[config] {e:#}");
4273                record_config_failure(task, &e);
4274                task.last_error = Some(reason.clone());
4275                task.hold_machine(Some(reason));
4276                record(queue, task);
4277                return Vec::new();
4278            }
4279        };
4280        if let Err(e) = apply_options(&mut config, opts, task) {
4281            task.hold_manual(Some(format!(
4282                "[config] {e:#}; correct the merge override before releasing the task"
4283            )));
4284            record(queue, task);
4285            return Vec::new();
4286        }
4287        if let Some(selected) = &task.pr_recovery
4288            && let Err(e) = selected.configure(&mut config)
4289        {
4290            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4291            record(queue, task);
4292            return Vec::new();
4293        }
4294        (config, layers)
4295    };
4296    let config_evidence = crate::pr_recovery::ConfigEvidence {
4297        layers,
4298        overrides: task.overrides.clone(),
4299        daemon_merge: task
4300            .overrides
4301            .as_ref()
4302            .is_none_or(|o| o.inherit_daemon_options)
4303            .then(|| opts.merge.clone())
4304            .flatten(),
4305    };
4306    apply_task_implementers(&mut config, task);
4307    if let Some(replacement) = &task.replacement {
4308        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4309            old.liveness(false) == Liveness::Dead
4310                && old.merge_decision.as_ref().is_some_and(|d| {
4311                    d.closed
4312                        && d.question == replacement.question
4313                        && d.replacement_run.as_ref().is_none_or(|run| {
4314                            task.runs.last() == Some(run)
4315                                && RunState::load(run).is_ok_and(|current| {
4316                                    current.replaces.as_ref().is_some_and(|pin| {
4317                                        pin.question == replacement.question
4318                                            && pin.agent == replacement.agent
4319                                    })
4320                                })
4321                        })
4322                })
4323        });
4324        if !safe {
4325            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()));
4326            record(queue, task);
4327            return Vec::new();
4328        }
4329        match config.agent(&replacement.agent) {
4330            Ok(agent) if crate::agent::installed(agent) => {}
4331            _ => {
4332                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)));
4333                record(queue, task);
4334                return Vec::new();
4335            }
4336        }
4337        config.graph.implementers = 1;
4338        config.graph.land_approval = true;
4339        config.merge.mode = MergeMode::Pr;
4340        config.graph.selected_implementer = Some(replacement.agent.clone());
4341    }
4342    let p = phrases(&config.graph.language);
4343    let start_failed = p.could_not_start;
4344    // Resolve once for both admission and settlement. The inputs are the
4345    // task's explicit sources (never prose), plus an explicit review source's
4346    // current head; review-only runs may rebase later, and neither fact can
4347    // refund a failed automatic generation.
4348    if let Ok(base) =
4349        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4350            .await
4351        && let Ok(head) =
4352            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4353    {
4354        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4355        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4356            let source = crate::git::rev_parse(&repo, branch)
4357                .await
4358                .unwrap_or_default();
4359            inputs.push_str(&format!(";review:{branch}:{source}"));
4360        }
4361        if let Some(reason) = task
4362            .recovery_exhausted(
4363                &head,
4364                &inputs,
4365                task.attempt_limit
4366                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4367            )
4368            .filter(|_| {
4369                !task.repair_grants.last().is_some_and(|receipt| {
4370                    RunState::load(&receipt.request.run)
4371                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4372                })
4373            })
4374        {
4375            task.hold_unrequested_retry(Some(reason));
4376            record(queue, task);
4377            return Vec::new();
4378        }
4379        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4380    }
4381
4382    // The free-space gate, checked *before* anything is minted: a task that
4383    // waits out a full disk costs nothing yet, and must not spend an attempt
4384    // or start a run the machine cannot finish. Held tasks stay in the list
4385    // for the human to see, and `magi task release` re-queues them when space
4386    // comes back - the same recovery as any other hold. A volume whose free
4387    // space cannot be measured closes the gate too: starting a run blind on a
4388    // disk that may be full is how the machine ends up with 6.7 GB free.
4389    if let Some(reason) = disk_gate(&repo, &config) {
4390        task.notice_cause("disk-space", None, None);
4391        task.last_error = Some(reason.clone());
4392        task.hold_machine(Some(reason.clone()));
4393        record(queue, task);
4394        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4395        // Stable wording - the free-space figures live in the task's hold
4396        // reason, and changing numbers would relight the bell every poll.
4397        notices::raise(
4398            Notice::warn(
4399                &format!("disk:{}", repo.display()),
4400                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4401            )
4402            .link(Link::Task {
4403                id: task.id.clone(),
4404            }),
4405        );
4406        return Vec::new();
4407    }
4408
4409    // A resumable run of this task is carried on, never re-competed. The
4410    // candidates are built and paid for, and a fresh competition races a
4411    // second implementation against them.
4412    //
4413    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4414    // started 3cbf on the same task a moment later, duplicating two and a
4415    // half hours of agent work. Then b25f stalled on a judge that timed out
4416    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4417    // was to blame for - and 4043 started **one second** later, buying three
4418    // fresh implementations to reach the same panel. `RunStatus::resumable`
4419    // rather than `!done()` is what catches the second case: a stall is
4420    // terminal, and its cheap recovery re-asks only the absent seats.
4421    //
4422    // A load failure is warned about rather than silently read as "not
4423    // resumable": the alternative is exactly what let a schema mismatch on
4424    // run `eba2` fall through to a full re-competition with nobody told why.
4425    // `crate::conduct` is what actually offers a better answer than
4426    // `Runner::start` here (see `Recovery::Review`), once this task's next
4427    // failure shows it up as `held`/`failed` with the run state unreadable.
4428    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4429    // branch survived, and this reopens exactly that branch as a
4430    // review-only pass rather than resuming or competing again. Consumed
4431    // (cleared) here whichever way this goes, so it never outlives this one
4432    // attempt - see `queue::Task::review_branch`.
4433    let review_branch = if previous
4434        .as_ref()
4435        .is_some_and(|state| crate::repair_budget::pending(task, state))
4436    {
4437        None
4438    } else {
4439        take_review_branch(task, previous.as_ref())
4440    };
4441    let branch_exists = match &review_branch {
4442        Some(branch) => crate::git::branch_exists(&repo, branch)
4443            .await
4444            .unwrap_or(false),
4445        None => false,
4446    };
4447    // An explicit `magi review <branch>` is reviewed whatever happens to the
4448    // branch unless an explicit implementer change requires fresh work. An
4449    // unfinished run of the same task still wins, so a retry resumes.
4450    let proposed = review_retry_starter(
4451        task,
4452        previous.as_ref(),
4453        review_branch.as_deref(),
4454        branch_exists,
4455        unfinished.as_deref(),
4456    );
4457    let retry_selected = task.replacement.is_some()
4458        && task.resumption.is_some()
4459        && !task.fresh_start
4460        && previous.as_ref().is_some_and(|run| {
4461            run.replaces.is_some()
4462                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4463                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4464        });
4465    let stop_pin = task
4466        .resume_override
4467        .as_ref()
4468        .filter(|pin| {
4469            Questions::open().get(&pin.question_id).is_ok_and(|q| {
4470                q.node == land::APPROVAL_NODE
4471                    && q.resolution()
4472                        .as_deref()
4473                        .is_some_and(crate::merge_decision::stops)
4474            })
4475        })
4476        .and_then(|pin| pin.pinned_run.clone());
4477    let granted_run = task.repair_grants.last().and_then(|receipt| {
4478        let state = RunState::load(&receipt.request.run).ok()?;
4479        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4480    });
4481    let starter = if let Some(run) = granted_run {
4482        Starter::Resume(run)
4483    } else if let Some(owner) = &public_owner {
4484        Starter::Resume(owner.id.clone())
4485    } else if let Some(run) = stop_pin {
4486        // Stop actions resume their exact owner even after seat-count edits;
4487        // they must never fall through to implementation or a takeover.
4488        Starter::Resume(run)
4489    } else if retry_selected {
4490        Starter::Resume(previous.as_ref().unwrap().id.clone())
4491    } else if let Some(selected) = &task.pr_recovery {
4492        if selected.check_task(&task.id, &task.instruction).is_ok() {
4493            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4494        } else {
4495            Starter::Review(selected.branch.clone())
4496        }
4497    } else {
4498        starter_with_implementers(task, previous.as_ref(), proposed)
4499    };
4500    // An explicit resume pin must never degrade into a new competition or
4501    // takeover, including when its run stops being eligible after the answer.
4502    if let Some(pin) = &task.resume_override
4503        && let Some(run) = &pin.pinned_run
4504        && starter != Starter::Resume(run.clone())
4505    {
4506        let run = run.clone();
4507        task.notice_cause("resume-owner", Some(&run), None);
4508        task.hold_machine(Some(format!(
4509            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4510            task.id
4511        )));
4512        record(queue, task);
4513        return Vec::new();
4514    }
4515    if task.replacement.is_some()
4516        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4517        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4518    {
4519        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()));
4520        record(queue, task);
4521        return Vec::new();
4522    }
4523    if let Some(reason) = retained_attempt_hold(
4524        task,
4525        &starter,
4526        config.disk.retained_attempt_limit,
4527        RunState::load,
4528    ) {
4529        // The review choice was consumed above. Preserve it across this hold
4530        // so a later release cannot silently become a fresh implementation.
4531        if let Starter::Review(branch) = &starter {
4532            task.review_branch = Some(branch.clone());
4533        }
4534        task.hold_unrequested_retry(Some(reason));
4535        record(queue, task);
4536        return Vec::new();
4537    }
4538    // Absolute paths of the files the task was filed with, re-read from the
4539    // task now so a file attached while it was held reaches a resumed run
4540    // too. A stored name whose file has gone is an error before any agent is
4541    // paid for, never a silent omission the implementer cannot notice.
4542    let attachments = match task_attachments(queue, task) {
4543        Ok(a) => a,
4544        Err(e) => {
4545            task.attempts += 1;
4546            task.fail_startup_target(
4547                "startup-attachments",
4548                e.name.clone(),
4549                format!("{start_failed}{e:#}"),
4550                opts.max_attempts,
4551            );
4552            record(queue, task);
4553            return Vec::new();
4554        }
4555    };
4556    let startup_pause = stop.pause();
4557    let startup_interrupt = interrupt_pause.clone();
4558    let wait = crate::repo_lock::WaitPolicy::new(
4559        Duration::from_secs(config.graph.timeout_resource_wait),
4560        move || startup_pause.parked() || startup_interrupt.parked(),
4561    );
4562    // Startup includes review takeover and recovery. Do not embed its large
4563    // future in both the wait scope and the surrounding attempt stack frame.
4564    let started = wait.scope(Box::pin(async { match &starter {
4565        Starter::Review(_) if task.pr_recovery.is_some() => {
4566            let selected = task.pr_recovery.clone().expect("selected recovery");
4567            match selected.check_task(&task.id, &task.instruction) {
4568                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4569                    .await
4570                    .map(|mut r| {
4571                        r.state.attachments = attachments.clone();
4572                        r
4573                    }),
4574                Err(e) => Err(e),
4575            }
4576        }
4577        Starter::Review(branch) => {
4578            tracing::info!(
4579                "task {} reopens `{branch}` as a review-only pass",
4580                task.short()
4581            );
4582            // Every earlier attempt is superseded by the one being minted
4583            // now, so a branch one of them still holds may be taken over.
4584            let takeover = crate::handover::Takeover {
4585                earlier: task.earlier_attempts().to_vec(),
4586                home: crate::run::home(),
4587                choice: take_divergence_answer(branch, &config.merge.remote, task),
4588                task_instruction: Some(instruction_for(task)),
4589            };
4590            Runner::review_taking_over(
4591                &repo,
4592                branch,
4593                config,
4594                Some(takeover),
4595                crate::run::Origin::queue(&task.id),
4596            )
4597            .await
4598        }
4599        Starter::Resume(id) => {
4600            tracing::info!("resuming run {id} rather than competing again");
4601            Runner::resume(id).and_then(|mut r| {
4602                if retry_selected {
4603                    // The explicit queue release retries this same pinned
4604                    // implementation, preserving the attempt and worktrees.
4605                    for candidate in &mut r.state.candidates {
4606                        candidate.failed = None;
4607                        candidate.empty = false;
4608                        candidate.commits = 0;
4609                    }
4610                    r.state.status = RunStatus::Implementing;
4611                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4612                }
4613                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4614                    r.state.sources = task.sources.clone();
4615                }
4616                if r.state.prep_failure.is_some() {
4617                    let approval = task
4618                        .resumption
4619                        .as_ref()
4620                        .context("preparation retry requires an explicit task release")?;
4621                    r.retry_preparation(approval.at)?;
4622                }
4623                if let Some(instruction) =
4624                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4625                {
4626                    r.state.instruction = instruction;
4627                }
4628                r.state.attachments = attachments.clone();
4629                if task.replacement.is_some() {
4630                    r.state.config.merge.mode = MergeMode::Pr;
4631                    r.state.config.graph.land_approval = true;
4632                }
4633                // Replacements publish a new PR and ask again. Selected PR
4634                // recoveries keep their saved disposition; ordinary runs can
4635                // retain the task's merge override.
4636                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4637                    .overrides
4638                    .as_ref()
4639                    .and_then(|o| o.merge.as_deref())
4640                    .and_then(|m| merge_mode(m).ok())
4641                {
4642                    r.state.config.merge.mode = mode;
4643                }
4644                Ok(r)
4645            })
4646        }
4647        Starter::Start => {
4648            if let Some(branch) = &review_branch {
4649                tracing::warn!(
4650                    "conductor chose review for task {} but branch `{branch}` no longer \
4651                     exists; requeuing as a fresh competition instead",
4652                    task.short()
4653                );
4654            }
4655            let instruction = prepare_instruction(&starter, None, task)
4656                .unwrap_or_else(|| task.instruction.clone());
4657            Runner::start_naming(
4658                &repo,
4659                instruction,
4660                &task.title,
4661                config,
4662                crate::run::Origin::queue(&task.id),
4663            )
4664            .await
4665            .map(|mut r| {
4666                r.state.attachments = attachments.clone();
4667                r.state.sources = task.sources.clone();
4668                r
4669            })
4670        }
4671    }})).await;
4672    if let Err(error) = &started
4673        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
4674    {
4675        task.record_startup_failure(failure.clone());
4676    }
4677    let mut runner = match started {
4678        Ok(r) => r,
4679        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4680            task.last_error = Some(e.to_string());
4681            if stop.parking() || interrupt_pause.parked() {
4682                let attempts = task.attempts;
4683                task.park(e.to_string());
4684                // Startup has not spent an attempt to refund.
4685                task.attempts = attempts;
4686            } else {
4687                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4688            }
4689            record(queue, task);
4690            return Vec::new();
4691        }
4692        // A branch an earlier attempt still holds and magi will not release
4693        // by itself is the operator's call, not a failed attempt: hold the
4694        // task with the reason, spend nothing, and say so on the bell.
4695        Err(e) if task.pr_recovery.is_some() => {
4696            task.startup_notice_cause("startup-public-head");
4697            task.attempts += 1;
4698            task.last_error = Some(format!("{start_failed}{e:#}"));
4699            task.hold_unrequested_retry(Some(format!(
4700                "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."
4701            )));
4702            record(queue, task);
4703            return Vec::new();
4704        }
4705        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4706            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4707                Some(r) => (p.handover_refused)(r),
4708                None => format!("{e:#}"),
4709            };
4710            task.startup_notice_cause("startup-handover");
4711            let reason = format!("{start_failed}{detail}");
4712            task.last_error = Some(reason.clone());
4713            // Consumed above by `take`; keep it so the released task retries
4714            // as a review of this same branch.
4715            let branch = match &starter {
4716                Starter::Review(branch) => Some(branch.clone()),
4717                _ => None,
4718            };
4719            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4720            // one page; the guidance rides in the reason, fixed per state so a
4721            // re-put never changes the wording and relights it.
4722            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4723            record(queue, task);
4724            tracing::warn!(
4725                "holding {} for a branch it cannot take over: {e:#}",
4726                task.short()
4727            );
4728            return Vec::new();
4729        }
4730        // A branch that differs between here and the remote in ways magi
4731        // cannot prove are the same change is a decision for the owner, not a
4732        // failed attempt: ask with both sides laid out, spend no attempt, and
4733        // let the answer requeue the task.
4734        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4735            let d = e
4736                .downcast_ref::<crate::reconcile::Diverged>()
4737                .expect("checked by the guard");
4738            let mut q = ask::Question::new(
4739                task.id.clone(),
4740                crate::reconcile::NODE.to_owned(),
4741                crate::reconcile::SEAT.to_owned(),
4742                d.summary(),
4743                d.detail(),
4744                d.choices(),
4745            );
4746            match Questions::open().put(&mut q) {
4747                Ok(()) => {
4748                    task.last_error = Some(format!("{e:#}"));
4749                    // Consumed above by `take`; the answer has to reach a review
4750                    // of this same branch, so keep pointing the task at it.
4751                    task.review_branch = Some(d.branch.clone());
4752                    task.review_instruction = Some(task.instruction.clone());
4753                    task.block(vec![q.id.clone()], Some(d.summary()));
4754                }
4755                Err(put) => {
4756                    tracing::warn!("could not file the divergence question: {put:#}");
4757                    task.attempts += 1;
4758                    task.fail_startup(
4759                        "startup-question-store",
4760                        format!("{start_failed}{e:#}"),
4761                        opts.max_attempts,
4762                    );
4763                }
4764            }
4765            record(queue, task);
4766            return Vec::new();
4767        }
4768        Err(e) => {
4769            // The answer was stale and nothing was applied: keep pointing at
4770            // the branch so the next attempt asks again against its new tips.
4771            // Nothing went wrong with the task, so no attempt is spent: a
4772            // budget one short of its limit must not hold it instead of
4773            // letting the question be asked again.
4774            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4775                && let Starter::Review(branch) = &starter
4776            {
4777                task.review_branch = Some(branch.clone());
4778                task.review_instruction = Some(task.instruction.clone());
4779                task.last_error = Some(format!("{start_failed}{e:#}"));
4780                task.status = crate::queue::TaskStatus::Failed;
4781                record(queue, task);
4782                return Vec::new();
4783            }
4784            task.attempts += 1;
4785            task.last_error = Some(format!("{start_failed}{e:#}"));
4786            task.startup_notice_cause("startup-source");
4787            task.hold_unrequested_retry(Some(format!(
4788                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4789            )));
4790            record(queue, task);
4791            return Vec::new();
4792        }
4793    };
4794    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4795        runner.state.recovery_config = Some(config_evidence);
4796    }
4797    if let Some(replacement) = &task.replacement {
4798        if matches!(starter, Starter::Start) {
4799            runner.state.instruction.push_str(&format!(
4800                "\n\n# Replacement review context\n{}",
4801                replacement.context
4802            ));
4803        }
4804        runner.state.replaces = Some(replacement.clone());
4805        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4806        if let Ok(mut old) = RunState::load(&replacement.run)
4807            && let Some(d) = &mut old.merge_decision
4808        {
4809            d.replacement_run = Some(runner.state.id.clone());
4810            old.event(
4811                "replacement",
4812                format!(
4813                    "replacement run {} owns the next attempt; old PR remains closed",
4814                    runner.state.id
4815                ),
4816            );
4817            if let Err(e) = old.save() {
4818                let error = runner.fail_startup("replacement-history", e);
4819                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4820                    task.record_startup_failure(failure.clone());
4821                }
4822                task.hold_manual(Some(format!(
4823                    "Could not link replacement history: {error:#}; no agents dispatched"
4824                )));
4825                record(queue, task);
4826                return Vec::new();
4827            }
4828        }
4829    }
4830    runner.state.task_instruction = Some(task.instruction.clone());
4831    // The follow-up depth is fixed now, while the task certainly exists:
4832    // deleting it later must not reset the cap (`crate::followup`).
4833    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4834    if runner.state.origin_chat.is_none() {
4835        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4836    }
4837    // A stop that means "park" reaches the graph through this handle.
4838    runner.on_pause(stop.pause());
4839    // `poll`'s interrupt scheduler reaches this one run - and no other -
4840    // through this handle. See `Pause`'s own doc for why these are never
4841    // the same one.
4842    runner.watch_interrupt(interrupt_pause);
4843
4844    // `start` has minted the run, so the task can now point at it. Persisting
4845    // `Running` before `execute` is what makes a crash mid-run legible.
4846    let run = runner.state.id.clone();
4847    let before_start = task.clone();
4848    task.start(run.clone());
4849    if let Err(error) = queue.put(task) {
4850        *task = before_start;
4851        let error = runner.fail_startup("task-start", error);
4852        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4853            task.record_startup_failure(failure.clone());
4854        }
4855        task.hold_manual(Some(format!(
4856            "Could not persist task start; no agents dispatched: {error:#}"
4857        )));
4858        record(queue, task);
4859        return Vec::new();
4860    }
4861    lock(status).current.push(Current {
4862        worker: None,
4863        task: task.id.clone(),
4864        run,
4865    });
4866
4867    // `RunState::quota` is the run's whole history across every resume, so
4868    // only what this execution added may arm the cooldown or earn a refund.
4869    let quota_before = runner.state.quota.clone();
4870    runner.state.next_pass_task_entry = true;
4871    let result = runner.execute().await;
4872    finish_attempt(
4873        opts.max_attempts,
4874        queue,
4875        task,
4876        &runner.state,
4877        &quota_before,
4878        result,
4879    )
4880}
4881
4882/// Settle `task` after its run executed: the verdict, the diagnosis, the
4883/// supersession of earlier attempts and the save. Shared by the loop and by
4884/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4885/// Returns the quota losses this execution added to the run.
4886pub fn finish_attempt(
4887    max_attempts: usize,
4888    queue: &Queue,
4889    task: &mut Task,
4890    state: &RunState,
4891    quota_before: &[QuotaLoss],
4892    result: Result<()>,
4893) -> Vec<QuotaLoss> {
4894    let detail = match result {
4895        Ok(()) => describe(state),
4896        Err(e) => format!("{e:#}"),
4897    };
4898    let fresh = losses_this_attempt(quota_before, &state.quota);
4899    let verdict = Verdict {
4900        status: state.status,
4901        // A run that opened a pull request handed its work over, whatever the
4902        // gate then decided about merging it.
4903        left_pr: state.pr.is_some(),
4904        // Only a rate limit earns the task its attempt back - and only one
4905        // suffered now: a refund justified by a previous session's loss is
4906        // the same mistake as re-arming the cooldown from it. A stalled run
4907        // resumed without hitting quota again therefore spends its attempt,
4908        // like any other failure of the task's own.
4909        quota_hit: !fresh.is_empty(),
4910        // A run that parked was asked to stop; that is not a failure and must
4911        // not spend an attempt, or replacing the binary a few times would
4912        // exhaust a task's budget without an agent ever misbehaving.
4913        parked: state.parked,
4914        // A quota loss that left nothing viable is the same machine fact as a
4915        // `Stalled` quota loss; see `settle`'s doc table.
4916        no_viable_candidates: state.viable().is_empty(),
4917    };
4918    if let Some(replacement) = &state.replaces
4919        && let Some(pr) = &state.pr
4920        && let Ok(mut old) = RunState::load(&replacement.run)
4921        && let Some(d) = &mut old.merge_decision
4922    {
4923        d.replacement_pr = Some(pr.url.clone());
4924        let _ = old.save();
4925    }
4926    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4927    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4928        task.hold_unrequested_retry(Some(format!(
4929            "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.",
4930            task.short()
4931        )));
4932    }
4933    if task.status == TaskStatus::Done {
4934        supersede_prior_runs(task, &crate::run::home());
4935    }
4936    record(queue, task);
4937    tracing::info!(
4938        "task {} is {} after run {} ({})",
4939        task.short(),
4940        task.status.as_str(),
4941        state.short(),
4942        label(state.status)
4943    );
4944    fresh
4945}
4946
4947/// A task a hand-started run leaves runnable (failed with attempts to spare,
4948/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4949/// later must not spend agent calls on it. `magi task release` retries.
4950pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4951    // Parked work (including legacy Failed records with a parked run) is a
4952    // checkpoint or owner handoff, not an unrequested retry.
4953    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4954        && !awaiting_resume_with(task, RunState::load)
4955        // A run parked on the owner's word about a withheld PR title/body
4956        // resumes via `land_resume_state`, including review-only tasks that
4957        // `awaiting_resume_with` does not consider.
4958        && withheld_text_wait(task).is_none()
4959        && !(task.fresh_start && task.replacement.is_some())
4960    {
4961        let why = task.last_error.clone().map_or_else(
4962            || "the run did not finish".to_owned(),
4963            |e| format!("the run did not finish: {e}"),
4964        );
4965        task.hold_unrequested_retry(Some(format!(
4966            "{why}. It was started by hand, so it is not retried \
4967             automatically; `magi task release` retries it."
4968        )));
4969        record(queue, task);
4970    }
4971}
4972
4973/// Whether an attempt at a task whose newest run is `run` would resume that
4974/// run rather than start a fresh competition. `magi run --resume` hands a run
4975/// to a live loop only when this holds.
4976#[must_use]
4977pub fn loop_would_resume(run: &str) -> bool {
4978    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4979}
4980
4981/// A loop in another process that is alive right now: a fresh heartbeat in
4982/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4983/// carries the pid it published (`None` inside when it published none - a
4984/// fresh heartbeat is still evidence of a live loop).
4985///
4986/// The one judgement of "is somebody else serving this queue", shared by the
4987/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4988/// deciding whether to hand a task to the loop. A claim file proves nothing
4989/// here: whether a claim succeeds says nothing about whether its owner lives.
4990#[must_use]
4991pub fn foreign_loop(
4992    reading: Option<&Reading>,
4993    now: Timestamp,
4994    own_pid: u32,
4995) -> Option<Option<u32>> {
4996    let reading = reading.filter(|r| r.running(now))?;
4997    match reading.pid {
4998        Some(pid) if pid == own_pid => None,
4999        pid => Some(pid),
5000    }
5001}
5002
5003fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5004    reading.worker_protocol != Some(1)
5005        && (foreign_loop(Some(reading), now, own_pid).is_some()
5006            || reading
5007                .pid
5008                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5009}
5010
5011/// Low-level claimed-task execution shared by the detached standalone worker
5012/// and focused lifecycle fixtures. The caller must retain the queue claim for
5013/// this entire call. CLI callers transfer ownership through
5014/// [`run_detached_claimed`] instead of executing inside their own runtime.
5015///
5016/// The one deliberate difference from the loop: a task the attempt leaves
5017/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5018/// Nobody asked for a retry, and a daemon starting later must not spend agent
5019/// calls re-running a hand-started task behind the operator's back;
5020/// `magi task release` is the explicit retry.
5021pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5022    run_claimed_until(opts, queue, task, &Stop::new()).await;
5023}
5024
5025async fn run_claimed_until(
5026    opts: &Opts,
5027    queue: &Queue,
5028    task: &mut Task,
5029    stop: &Stop,
5030) -> Vec<QuotaLoss> {
5031    let status = Arc::new(Mutex::new(Status::new()));
5032    // An attempt embeds startup and graph futures. Keep it off the standalone
5033    // caller's stack, on both the initial execution and withheld-text resume.
5034    let mut quota = Box::pin(attempt(
5035        opts,
5036        queue,
5037        &status,
5038        stop,
5039        crate::graph::Pause::new(),
5040        task,
5041    ))
5042    .await;
5043    // A run parked on the owner's word about a withheld PR title/body has no
5044    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5045    // here with the claim still held, and resume once the question is settled
5046    // (answered, or abandoned at its deadline -> the neutral text).
5047    // A rejected reply files one more question (the gate asks at most twice),
5048    // so after a resume the run may be waiting again: keep going, with a fresh
5049    // limit for the new question. `resumes` bounds it even if a resume parks
5050    // without asking anything new.
5051    let mut resumes = 0;
5052    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5053        let Some(timeout) = withheld_text_wait(task) else {
5054            break;
5055        };
5056        eprintln!(
5057            "waiting for the owner's answer on a withheld pull request text \
5058             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5059        );
5060        // The deadline abandons the question itself; the extra margin only
5061        // covers an abandon that could not be saved.
5062        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5063        let ready = loop {
5064            match land_resume_state(task) {
5065                LandResume::StillWaiting
5066                    if !stop.parking() && std::time::Instant::now() < limit =>
5067                {
5068                    tokio::time::sleep(WITHHELD_POLL).await;
5069                }
5070                LandResume::Ready => break true,
5071                _ => break false,
5072            }
5073        };
5074        if !ready || stop.parking() {
5075            break;
5076        }
5077        resumes += 1;
5078        quota.extend(
5079            Box::pin(attempt(
5080                opts,
5081                queue,
5082                &status,
5083                stop,
5084                crate::graph::Pause::new(),
5085                task,
5086            ))
5087            .await,
5088        );
5089    }
5090    hold_if_runnable(queue, task);
5091    quota
5092}
5093
5094/// Resumes an in-process run makes for withheld-text questions: the gate asks
5095/// at most twice, plus one for a resume that asks nothing new.
5096const MAX_WITHHELD_RESUMES: u32 = 3;
5097
5098/// How often an in-process run rechecks its withheld-text question.
5099const WITHHELD_POLL: Duration = Duration::from_secs(15);
5100
5101/// The `answer_timeout` (seconds) of the task's last run when that run is
5102/// parked on an unresolved withheld-text question; `None` otherwise.
5103fn withheld_text_wait(task: &Task) -> Option<u64> {
5104    let id = task.runs.last()?;
5105    let s = RunState::load(id).ok()?;
5106    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5107        .then_some(s.config.graph.answer_timeout)
5108}
5109
5110/// The quota losses `after` holds that `before` did not: what one execution
5111/// suffered, as opposed to the run's history.
5112///
5113/// Compared by value rather than by length or position because
5114/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5115/// the vector can shrink and shift under a resume. A retried seat that hits
5116/// quota again is a `push` with a new `at`, so it shows up as new here.
5117/// Crash recovery uses the recorded pass start as its boundary when available;
5118/// legacy records without passes retain their original history-based policy.
5119fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5120    after
5121        .iter()
5122        .filter(|q| !before.contains(q))
5123        .cloned()
5124        .collect()
5125}
5126
5127/// When the loop-wide quota cooldown should end, given this attempt's losses;
5128/// `None` when there were none. Reset-hint parsing and the cap live here.
5129fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5130    let quota: Vec<_> = quota
5131        .iter()
5132        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5133        .collect();
5134    if quota.is_empty() {
5135        return None;
5136    }
5137    let with_hint = quota.iter().find(|q| q.reset.is_some());
5138    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5139    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5140    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5141    Some(
5142        now.checked_add(jiff::SignedDuration::from_secs(secs))
5143            .unwrap_or(Timestamp::MAX),
5144    )
5145}
5146
5147/// An explicit task count must agree with a run before any resume.
5148fn implementers_match(task: &Task, state: &RunState) -> bool {
5149    task.replacement.as_ref().map_or_else(
5150        || {
5151            task.implementers()
5152                .is_none_or(|n| n == state.config.graph.implementers)
5153        },
5154        |replacement| {
5155            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5156                && state.config.graph.implementers == 1
5157        },
5158    )
5159}
5160
5161/// Never resume or take over candidate work built for a different seat count.
5162fn starter_with_implementers(
5163    task: &Task,
5164    previous: Option<&RunState>,
5165    proposed: Starter,
5166) -> Starter {
5167    if previous.is_some_and(|s| !implementers_match(task, s)) {
5168        task.review_of
5169            .as_ref()
5170            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5171    } else {
5172        proposed
5173    }
5174}
5175
5176/// Apply this task's explicit count to the new attempt, without changing defaults.
5177fn apply_task_implementers(config: &mut Config, task: &Task) {
5178    if let Some(n) = task.implementers() {
5179        config.graph.implementers = n;
5180    }
5181}
5182
5183/// [`prepare`] for one task: its own `--config` and command-line overrides
5184/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5185/// over the loop's, so handing a hand-started task to a daemon changes nothing
5186/// about what it does.
5187#[cfg(test)]
5188fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5189    let explicit = match &task.overrides {
5190        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5191        _ => opts.config.as_deref(),
5192    };
5193    let (mut config, _) = Config::discover(repo, explicit)?;
5194    apply_options(&mut config, opts, task)?;
5195    Ok(config)
5196}
5197
5198fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5199    if task
5200        .overrides
5201        .as_ref()
5202        .is_none_or(|o| o.inherit_daemon_options)
5203        && let Some(mode) = opts.merge.as_deref()
5204    {
5205        config.merge.mode = merge_mode(mode)?;
5206    }
5207    if let Some(o) = &task.overrides {
5208        o.apply(config);
5209    }
5210    Ok(())
5211}
5212
5213/// Load the config for a task's repository, with the merge override applied.
5214fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5215    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5216    if let Some(mode) = &opts.merge {
5217        config.merge.mode = merge_mode(mode)?;
5218    }
5219    Ok(config)
5220}
5221
5222/// Prune the shared build cache at a between-runs boundary. The detached cache
5223/// service checks authoritative task jobs first; dispatch waits for that finite
5224/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5225/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5226async fn maybe_prune_cache_between_runs(
5227    repo: &Path,
5228    opts: &Opts,
5229    home: &Path,
5230    stop: &Stop,
5231    last_checked: &mut Option<Timestamp>,
5232    now: Timestamp,
5233) {
5234    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5235        return;
5236    }
5237    *last_checked = Some(now);
5238    let cfg = match prepare(repo, opts) {
5239        Ok(cfg) => cfg,
5240        Err(e) => {
5241            tracing::warn!("cache check: no config: {e:#}");
5242            return;
5243        }
5244    };
5245    match clean::prune_cache_if_over_limit(&cfg, home) {
5246        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5247            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5248            pruned.files,
5249            pruned.freed
5250        ),
5251        Ok(_) => {}
5252        Err(e) => {
5253            tracing::warn!("housekeep: prune cache: {e:#}");
5254            notices::raise_in(
5255                home,
5256                Notice::warn(
5257                    "housekeep:cache",
5258                    format!(
5259                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5260                        e.to_string()
5261                            .lines()
5262                            .next()
5263                            .unwrap_or("unknown cleanup error")
5264                    ),
5265                ),
5266            );
5267        }
5268    }
5269}
5270
5271/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5272/// now, given when it last did (if ever). Pure, so the cadence is asserted
5273/// directly rather than by waiting out real minutes in a test.
5274fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5275    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5276}
5277
5278/// The disk janitor, with its housekeeping logged rather than fatal.
5279///
5280/// Called only at the loop's idle points, for the reason the caller documents:
5281/// a prune racing a live compile would delete files mid-build. The config is
5282/// re-read on every call because the repository that just ran may not be the
5283/// daemon's own default, and the cache directory is a repository fact.
5284///
5285/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5286/// and [`crate::run::default_worktree_root`] read here, for the same reason
5287/// [`drive`] takes its queue and status file rather than resolving them: a
5288/// test driving the loop must not reach through to the operator's real home
5289/// or worktree bay just because the janitor runs on every idle tick.
5290/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5291/// to get wrong silently - a test's `home` was already isolated, but nothing
5292/// exercised the parameter next to it, so a real worktree bay stayed wired in
5293/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5294/// it for real, every test in this file that drives the loop at all started
5295/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5296async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5297    let cfg = match prepare(repo, opts) {
5298        Ok(cfg) => cfg,
5299        Err(e) => {
5300            tracing::warn!("housekeep: no config: {e:#}");
5301            return;
5302        }
5303    };
5304    // A run's own worktree lives under `config.graph.worktree_root` when the
5305    // repository sets one - the same precedence `RunState::worktree_root`
5306    // uses - and `worktrees_root` only stands in for the *default* an
5307    // unconfigured repository resolves to (see this function's own
5308    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5309    // that always swept the default regardless of this override would never
5310    // see, and so never reclaim, a single worktree for a repository that
5311    // relocated them elsewhere.
5312    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5313    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5314    // Reported whenever there is anything to say, not only when `folded > 0`:
5315    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5316    // folded, on every single pass, for months - a report gated on `folded`
5317    // would have stayed silent through every one of them.
5318    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5319        let mut extra = Vec::new();
5320        if out.unreadable > 0 {
5321            extra.push(format!("{} unreadable", out.unreadable));
5322        }
5323        if out.orphaned_worktrees > 0 {
5324            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5325        }
5326        let detail = if extra.is_empty() {
5327            String::new()
5328        } else {
5329            format!(" ({})", extra.join(", "))
5330        };
5331        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5332    }
5333    if out.external_merges_recorded > 0 {
5334        tracing::info!(
5335            "housekeep: recorded {} run(s) as merged externally",
5336            out.external_merges_recorded
5337        );
5338    }
5339    if out.stale_pr_states_repaired > 0 {
5340        tracing::info!(
5341            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5342            out.stale_pr_states_repaired
5343        );
5344    }
5345    if out.cache_files > 0 {
5346        tracing::info!(
5347            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5348            out.cache_files,
5349            out.cache_freed
5350        );
5351    }
5352    if out.questions_abandoned > 0 {
5353        tracing::info!(
5354            "housekeep: abandoned {} question(s) left open by a finished run",
5355            out.questions_abandoned
5356        );
5357    }
5358}
5359
5360/// Run [`triage::run_once`] and log whatever it did, the same "only when
5361/// there is something to say" rule [`janitor`] follows for its own report.
5362///
5363/// Called at the same idle points as [`janitor`] - once per full poll
5364/// interval, never mid-attempt - for the same reason: it is not liveness
5365/// critical, and a task's own `hold_reason` string is the one thing this
5366/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5367/// tick for no benefit.
5368async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5369    let questions = Questions::at(home.join("questions"));
5370    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5371    if report.is_empty() {
5372        return;
5373    }
5374    if !report.quarantined.is_empty() {
5375        tracing::info!(
5376            "triage: held {} blocked task(s) whose blocked-on task or \
5377             question no longer exists: {}",
5378            report.quarantined.len(),
5379            report.quarantined.join(", ")
5380        );
5381    }
5382    if !report.resumed.is_empty() {
5383        tracing::info!(
5384            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5385            report.resumed.len(),
5386            report.resumed.join(", ")
5387        );
5388    }
5389    if !report.asked.is_empty() {
5390        tracing::info!(
5391            "triage: asked about {} held task(s): {}",
5392            report.asked.len(),
5393            report.asked.join(", ")
5394        );
5395    }
5396    if !report.answered.is_empty() {
5397        tracing::info!(
5398            "triage: applied {} operator answer(s): {}",
5399            report.answered.len(),
5400            report.answered.join(", ")
5401        );
5402    }
5403}
5404
5405/// The free-space gate: what stands between this task and a new run, if
5406/// anything. `Some(reason)` holds the task; `None` lets it start.
5407///
5408/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5409/// the operator opted out. A measurement failure is a gate, not a pass: both
5410/// sides of "cannot tell" are served by not starting.
5411pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5412    disk_gate_with(repo, config, crate::disk::free_bytes)
5413}
5414
5415/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5416/// test can assert the exact wiring `attempt` runs - config's threshold in,
5417/// task-holding reason out - without asking the real machine's disk anything.
5418fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5419    repo: &Path,
5420    config: &Config,
5421    free_bytes: F,
5422) -> Option<String> {
5423    let min = config.disk.min_free_bytes;
5424    if min == 0 {
5425        return None;
5426    }
5427    let mut paths = vec![repo.to_owned()];
5428    if let Some(cache) = config.cache_dir() {
5429        paths.push(cache);
5430    }
5431    if let Some(root) = &config.graph.worktree_root {
5432        paths.push(root.clone());
5433    }
5434    for path in paths {
5435        let probe = if path == repo {
5436            path.as_path()
5437        } else {
5438            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5439        };
5440        let reason = match free_bytes(probe) {
5441            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5442            Err(e) => Some(crate::disk::unmeasured_in(
5443                probe,
5444                &e,
5445                &config.graph.language,
5446            )),
5447        };
5448        if reason.is_some() {
5449            return reason;
5450        }
5451    }
5452    None
5453}
5454
5455/// How long to wait before offering another task when a run lost a seat to a
5456/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5457/// could read, or carried nothing at all. Long enough that a quota outage
5458/// cannot burn through a whole backlog in the few seconds each doomed attempt
5459/// takes to fail; short enough that a quota which clears early is not left
5460/// idle for the fallback's sake.
5461const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5462
5463/// Longest a parsed reset hint may push the wait out to. The hint comes from
5464/// the CLI's own words, not a contract, so a parsing slip that lands a day
5465/// away must not leave the loop asleep for a day.
5466const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5467
5468/// How long [`poll`] should wait before offering the next task, after a run
5469/// lost at least one seat to a rate limit.
5470///
5471/// Pure and separate from the loop so the policy can be exercised without a
5472/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5473/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5474/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5475/// far a parsed hint is trusted to push the wait out.
5476fn quota_wait(
5477    reset_at: Option<Timestamp>,
5478    now: Timestamp,
5479    fallback: Duration,
5480    cap: Duration,
5481) -> Duration {
5482    match reset_at {
5483        Some(at) if at > now => {
5484            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5485            Duration::from_secs(secs).min(cap)
5486        }
5487        _ => fallback,
5488    }
5489}
5490
5491/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5492///
5493/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5494/// explains why parsing it exactly "would be a bug factory" — so this only
5495/// recognises the shapes actually observed in the wild, and returns `None`
5496/// for anything else rather than guess at a format nobody has seen.
5497///
5498/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5499/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5500/// said it, not from whenever this loop happens to read it: anchoring on `now`
5501/// would push the reset later on every read and would read an already-elapsed
5502/// reset as still in the future. (A long hint is still clamped by
5503/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5504fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5505    parse_reset_hint_zoned(text, now)
5506        .or_else(|| parse_reset_hint_dated(text))
5507        .or_else(|| parse_reset_hint_relative(text, recorded))
5508}
5509
5510/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5511/// optional but at least one required, in that order. A bare number or any
5512/// unknown unit is refused.
5513fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5514    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5515    let mut rest = rest.trim();
5516    if rest.is_empty() {
5517        return None;
5518    }
5519    let mut total: i64 = 0;
5520    let mut matched = false;
5521    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5522        if let Some((digits, tail)) = rest.split_once(unit)
5523            && !digits.is_empty()
5524            && digits.bytes().all(|b| b.is_ascii_digit())
5525        {
5526            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5527            rest = tail;
5528            matched = true;
5529        }
5530    }
5531    if !rest.is_empty() || !matched {
5532        return None;
5533    }
5534    recorded
5535        .checked_add(jiff::SignedDuration::from_secs(total))
5536        .ok()
5537}
5538
5539/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5540/// case-insensitive) into a 24-hour hour and minute. Shared by every
5541/// reset-hint shape below.
5542fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5543    let clock = clock.trim().to_lowercase();
5544    let (digits, pm) = clock
5545        .strip_suffix("am")
5546        .map(|d| (d, false))
5547        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5548    let (h, m) = digits.trim().split_once(':')?;
5549    let mut hour: i8 = h.trim().parse().ok()?;
5550    let minute: i8 = m.trim().parse().ok()?;
5551    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5552        return None;
5553    }
5554    if pm && hour != 12 {
5555        hour += 12;
5556    } else if !pm && hour == 12 {
5557        hour = 0;
5558    }
5559    Some((hour, minute))
5560}
5561
5562/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5563/// and a zone, never a date. A clock reading already past today is read as
5564/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5565/// the window rolled over while nothing was watching.
5566fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5567    let open = text.find('(')?;
5568    let close = text.rfind(')')?;
5569    if close <= open {
5570        return None;
5571    }
5572    let zone = text[open + 1..close].trim();
5573    let (hour, minute) = parse_12h_clock(&text[..open])?;
5574    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5575    let candidate = now
5576        .to_zoned(tz)
5577        .with()
5578        .hour(hour)
5579        .minute(minute)
5580        .second(0)
5581        .millisecond(0)
5582        .microsecond(0)
5583        .nanosecond(0)
5584        .build()
5585        .ok()?;
5586    let mut at = candidate.timestamp();
5587    if at <= now {
5588        at += jiff::SignedDuration::from_hours(24);
5589    }
5590    Some(at)
5591}
5592
5593/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5594/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5595/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5596/// "already past today" correction to make: the year already disambiguates
5597/// it. Scanned as a five-word window so it can be pulled out of the middle
5598/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5599/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5600/// any other timestamp with no zone attached.
5601fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5602    let words: Vec<&str> = text.split_whitespace().collect();
5603    if words.len() < 5 {
5604        return None;
5605    }
5606    (0..=words.len() - 5)
5607        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5608}
5609
5610/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5611/// parenthesis right after the window is refused rather than ignored — it
5612/// reads as an explicit zone annotation on a shape that otherwise carries
5613/// none, and guessing UTC anyway would be exactly the silent misread this
5614/// module's parsing otherwise avoids.
5615fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5616    if trailing.is_some_and(|next| next.starts_with('(')) {
5617        return None;
5618    }
5619    let month = month_number(window[0])?;
5620    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5621    let day_digits = ["st", "nd", "rd", "th"]
5622        .iter()
5623        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5624    let day: i8 = day_digits.parse().ok()?;
5625    let year_token = window[2];
5626    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5627        return None;
5628    }
5629    let year: i16 = year_token.parse().ok()?;
5630    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5631    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5632    // reusing the same 12-hour clock reader the bracketed shape uses.
5633    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5634    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5635    let date = jiff::civil::Date::new(year, month, day).ok()?;
5636    let candidate = date
5637        .at(hour, minute, 0, 0)
5638        .to_zoned(jiff::tz::TimeZone::UTC)
5639        .ok()?;
5640    Some(candidate.timestamp())
5641}
5642
5643/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5644/// case-insensitively, into a 1-based month number.
5645fn month_number(name: &str) -> Option<i8> {
5646    const NAMES: [&str; 12] = [
5647        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5648    ];
5649    let lower = name.to_lowercase();
5650    NAMES
5651        .iter()
5652        .position(|n| *n == lower.as_str())
5653        .map(|i| i as i8 + 1)
5654}
5655
5656/// Test probe for the shared resume policy's review-budget exclusion.
5657#[cfg(test)]
5658fn exhausted_review_budget(state: &RunState) -> bool {
5659    // A run whose task-head publication failed has nothing left to review:
5660    // resuming it only retries the publication, so it is never "exhausted".
5661    !crate::handover::can_resume(state)
5662        && state.status == RunStatus::Blocked
5663        && !state.released()
5664        && state.retired_to.is_none()
5665}
5666
5667/// This task's *most recent* run, if resuming it would actually make
5668/// progress. `short` is only for the warning's own message.
5669///
5670/// Only ever `runs.last()` — never a search back through older history.
5671/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5672/// mint, oldest first, and every entry before the last one was already
5673/// superseded at the moment it was minted: the daemon only ever starts a new
5674/// run when the previous one was not worth resuming (unresumable, exhausted,
5675/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5676/// opens a fresh review-only run alongside an older, already-failed
5677/// competition. Searching further back would let an old run that merely
5678/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5679/// behind, say — get resumed instead of the fresh competition
5680/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5681/// nothing asked to revisit.
5682///
5683/// Two runs paid for the "prefer resuming over restarting" half of this
5684/// lesson, which is why this still checks `runs.last()` rather than always
5685/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5686/// task a moment later, duplicating two and a half hours of agent work. Then
5687/// b25f stalled on a judge that timed out and one that answered with no JSON
5688/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5689/// **one second** later, buying three fresh implementations to reach the
5690/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5691/// the second case: a stall is terminal, and its cheap recovery re-asks only
5692/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5693/// that is technically `resumable()` but provably cannot progress must not
5694/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5695/// no-op instead of the fresh competition it promises.
5696///
5697/// A load failure is warned about rather than silently read as "not
5698/// resumable": the alternative is exactly what let a schema mismatch on run
5699/// `eba2` fall through to a full re-competition with nobody told why.
5700/// `crate::conduct` is what actually offers a better answer than
5701/// `Runner::start` here (see `Recovery::Review`), once this task's next
5702/// failure shows it up as `held`/`failed` with the run state unreadable.
5703fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5704    unfinished_run_with(runs, short, RunState::load)
5705}
5706
5707/// [`unfinished_run`] with an injected state reader. Tests provide their
5708/// fixtures directly rather than touching the process-global run home.
5709pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5710where
5711    F: FnMut(&str) -> Result<RunState>,
5712{
5713    let mut id = runs.last()?.clone();
5714    let mut visited = std::collections::BTreeSet::new();
5715    let mut repo = None;
5716    loop {
5717        if !runs.contains(&id) || !visited.insert(id.clone()) {
5718            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5719            return None;
5720        }
5721        let state = match load(&id) {
5722            Ok(state) if state.id == id => state,
5723            Ok(_) => return None,
5724            Err(e) => {
5725                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5726                return None;
5727            }
5728        };
5729        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5730            return None;
5731        }
5732        repo = Some(state.repo.clone());
5733        if let Some(authority) = state.retired_to {
5734            id = authority;
5735            continue;
5736        }
5737        return (crate::handover::can_resume(&state)
5738            && state.liveness(false) != crate::run::Liveness::Live)
5739            .then_some(id);
5740    }
5741}
5742
5743/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5744/// that [`attempt`] will resume it on its own?
5745///
5746/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5747/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5748/// injected reader like its sibling. An unreadable run is not awaiting
5749/// anything: it keeps going to the conductor as before.
5750fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5751where
5752    F: FnOnce(&str) -> Result<RunState>,
5753{
5754    // `Failed` stays: a record an older build wrote for a parked run.
5755    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5756        || task.fresh_start
5757        || task.review_branch.is_some()
5758    {
5759        return false;
5760    }
5761    let Some(id) = task.runs.last() else {
5762        return false;
5763    };
5764    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5765}
5766
5767/// Which of the three ways [`attempt`] can mint or continue a run this task
5768/// should use.
5769#[derive(Debug, Clone, PartialEq, Eq)]
5770enum Starter {
5771    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5772    /// and that still exists.
5773    Review(String),
5774    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5775    Resume(String),
5776    /// `crate::graph::Runner::start`: a fresh competition.
5777    Start,
5778}
5779
5780/// A second bound independent of inputs and the resettable failure counter.
5781/// Count execution and failed-startup recovery records once per run. Startup
5782/// failures can retain unrecorded preparation assets without an execution pass.
5783/// Unknown history is not evidence that a new set of worktrees is affordable.
5784fn retained_attempt_hold(
5785    task: &Task,
5786    starter: &Starter,
5787    limit: usize,
5788    mut load: impl FnMut(&str) -> Result<RunState>,
5789) -> Option<String> {
5790    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5791        return None;
5792    }
5793    let mut retained = 0;
5794    for id in task
5795        .runs
5796        .iter()
5797        .chain(task.startup_failures.iter().map(|failure| &failure.run))
5798        .collect::<std::collections::BTreeSet<_>>()
5799    {
5800        let state = match load(id) {
5801            Ok(state) if state.id == *id => state,
5802            _ => {
5803                return Some(format!(
5804                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5805                ));
5806            }
5807        };
5808        if state.retired_to.is_some() || state.released() {
5809            continue;
5810        }
5811        // Neither a completed status nor an empty candidate array proves that
5812        // all recovery sources (including unrecorded preparation) were retired.
5813        retained += 1;
5814    }
5815    (retained >= limit).then(|| format!(
5816        "[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."
5817    ))
5818}
5819
5820/// A selected public implementation overrides every historical candidate and pin.
5821fn selected_starter(
5822    selected: &crate::pr_recovery::Selection,
5823    previous: Option<&RunState>,
5824    unfinished: Option<&str>,
5825) -> Starter {
5826    if let Some(id) = unfinished
5827        && previous.is_some_and(|r| {
5828            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5829        })
5830    {
5831        Starter::Resume(id.to_owned())
5832    } else {
5833        Starter::Review(selected.branch.clone())
5834    }
5835}
5836
5837/// The owner's answer to this branch's divergence question, consumed from the
5838/// task so a later, different divergence asks again. The runner applies it
5839/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5840fn take_divergence_answer(
5841    branch: &str,
5842    remote: &str,
5843    task: &mut Task,
5844) -> Option<crate::reconcile::Choice> {
5845    let summary = crate::reconcile::summary_for(branch, remote);
5846    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5847        (a.question == summary)
5848            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5849            .flatten()
5850            .map(|c| (i, c))
5851    })?;
5852    task.answers.remove(idx);
5853    Some(choice)
5854}
5855
5856/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5857/// this attempt should use. Pure, and separate from [`attempt`], so the
5858/// routing itself is assertable without spawning a real graph or a git
5859/// process: `attempt`'s own `crate::git::branch_exists` call has already
5860/// happened by the time this is called.
5861///
5862/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5863/// whose branch is gone falls all the way through to [`Starter::Start`], not
5864/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5865/// old (likely `Blocked`) run in the first place, and a branch that vanished
5866/// out from under that choice is not evidence resuming it would fare better.
5867fn choose_starter(
5868    review_branch: Option<&str>,
5869    branch_exists: bool,
5870    unfinished: Option<&str>,
5871) -> Starter {
5872    match review_branch {
5873        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5874        Some(_) => Starter::Start,
5875        None => match unfinished {
5876            Some(id) => Starter::Resume(id.to_owned()),
5877            None => Starter::Start,
5878        },
5879    }
5880}
5881
5882/// Reuse a compatible latest review owner instead of taking its checked-out
5883/// branch into a new run. Different branches and changed criteria still use
5884/// the ordinary review/takeover policy.
5885fn review_retry_starter(
5886    task: &Task,
5887    previous: Option<&RunState>,
5888    branch: Option<&str>,
5889    exists: bool,
5890    unfinished: Option<&str>,
5891) -> Starter {
5892    if let Some(run) = previous
5893        && unfinished == Some(run.id.as_str())
5894        && run.reviewed_commits.is_some()
5895        && branch.is_some_and(|branch| {
5896            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5897        })
5898        && may_resume_run(run, task)
5899    {
5900        return Starter::Resume(run.id.clone());
5901    }
5902    match (branch, unfinished, &task.review_of) {
5903        (None, None, Some(branch)) => Starter::Review(branch.clone()),
5904        _ => choose_starter(branch, exists, unfinished),
5905    }
5906}
5907
5908/// Consume a retained review only while its authored criteria still match.
5909fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5910    let branch = task.review_branch.take();
5911    let instruction = task.review_instruction.take();
5912    branch.filter(|branch| match &instruction {
5913        Some(authored) => *authored == task.instruction,
5914        // Legacy retained branches must agree with their prior run; only an
5915        // explicitly pinned review can proceed without recoverable provenance.
5916        None => previous.map_or_else(
5917            || task.review_of.as_ref() == Some(branch),
5918            |run| compatible_run_instruction(run, task),
5919        ),
5920    })
5921}
5922
5923/// A current explicit pin can select an otherwise incompatible run. Edits
5924/// and subsequent approvals invalidate pins selected for earlier criteria.
5925fn may_resume_run(run: &RunState, task: &Task) -> bool {
5926    task.resume_override
5927        .as_ref()
5928        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5929        || compatible_run_instruction(run, task)
5930}
5931
5932/// Review scaffolding is execution context, not evidence of an operator edit.
5933pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5934    if let Some(authored) = &run.task_instruction {
5935        return compatible_instruction(authored, task);
5936    }
5937    if compatible_instruction(&run.instruction, task) {
5938        return true;
5939    }
5940    // Recognize only the existing generated review shapes on legacy runs.
5941    // Ordinary authored text with a similar heading is left intact.
5942    if run.reviewed_commits.is_some() {
5943        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5944            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5945        }
5946        if let Some(branch) = &task.review_of {
5947            let canonical = format!(
5948                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5949            );
5950            let generated = format!(
5951                "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"
5952            );
5953            return task.instruction == canonical && run.instruction.starts_with(&generated);
5954        }
5955    }
5956    false
5957}
5958
5959/// Compare authored instructions, excluding answer blocks appended by the daemon.
5960pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5961    strip_answers_block(old, task) == task.instruction
5962}
5963
5964/// Which repository a task runs in. A task that names none — the normal case
5965/// for one filed from a phone — runs in the daemon's own default.
5966fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5967    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5968        return fallback.to_path_buf();
5969    }
5970    task.repo.clone()
5971}
5972
5973/// The header [`append_answers`] appends operator answers under. Shared with
5974/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5975/// rather than grown a new block on every resume.
5976const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5977
5978/// Render the first `count` answers in the block appended to an instruction.
5979fn answers_block(task: &Task, count: usize) -> String {
5980    let mut s = ANSWERS_HEADER.to_owned();
5981    for a in &task.answers[..count] {
5982        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5983    }
5984    s
5985}
5986
5987/// Render the approval independently of transient task state, so historical
5988/// suffixes remain recognizable after another explicit release.
5989fn resumption_block(r: &crate::queue::Resumption) -> String {
5990    format!(
5991        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5992         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5993        r.generation, r.at, r.instruction, r.answers_through,
5994    )
5995}
5996
5997/// Append audit answers and the latest explicit approval to the instruction.
5998fn append_answers(base: &str, task: &Task) -> String {
5999    let mut s = base.to_owned();
6000    if !task.answers.is_empty() {
6001        s.push_str(&answers_block(task, task.answers.len()));
6002    }
6003    if let Some(r) = &task.resumption {
6004        s.push_str(&resumption_block(r));
6005    }
6006    s
6007}
6008
6009/// Drop the prior answer block only when it is exactly the suffix this task
6010/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6011/// the task author is ordinary instruction text, not a block to remove.
6012fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6013    let mut instruction = instruction;
6014    for approval in task
6015        .resumption
6016        .iter()
6017        .chain(task.resumption_history.iter().rev())
6018    {
6019        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6020            instruction = base;
6021            break;
6022        }
6023    }
6024    for count in (1..=task.answers.len()).rev() {
6025        let block = answers_block(task, count);
6026        if let Some(base) = instruction.strip_suffix(&block) {
6027            return base;
6028        }
6029    }
6030    instruction
6031}
6032
6033/// The instruction handed to `Runner::start`: the task's own text, plus any
6034/// operator answers `crate::conduct` collected for it (see
6035/// [`Task::answers`]), so a decision the operator actually made reaches the
6036/// implementers rather than only clearing the block that was waiting on it.
6037///
6038/// Appended rather than merged into [`Task::instruction`] itself, so the
6039/// task's own record stays exactly what its author wrote.
6040fn instruction_for(task: &Task) -> String {
6041    append_answers(&task.instruction, task)
6042}
6043
6044/// The instruction a resumed run should carry on with: whatever it already
6045/// had, refreshed with the task's *current* operator answers.
6046///
6047/// A resumable run's own `RunState::instruction` predates any answer
6048/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6049/// the behaviour before this function existed — silently drops the very
6050/// decision the operator made to unblock it. Re-stripping any block this
6051/// function appended on an earlier resume before re-appending the current
6052/// list (rather than blindly appending again) is what keeps a task resumed
6053/// three times over three answered questions from carrying the same answer
6054/// three times.
6055fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6056    append_answers(strip_answers_block(old_instruction, task), task)
6057}
6058
6059/// Preserve the producer's verified boundary and target, independent of prose.
6060fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6061    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6062    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6063    if let Some(cause) = task.hold_notice_cause.as_mut() {
6064        cause.target = failure.map(|f| f.target.clone());
6065    }
6066}
6067
6068#[derive(Debug, thiserror::Error)]
6069#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6070struct MissingAttachment {
6071    name: String,
6072    path: PathBuf,
6073}
6074
6075/// The task's attachments as absolute paths, each checked to still exist.
6076fn task_attachments(
6077    queue: &Queue,
6078    task: &Task,
6079) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6080    let paths = queue.attachment_paths(task);
6081    for (name, path) in task.attachments.iter().zip(&paths) {
6082        if !path.is_file() {
6083            return Err(MissingAttachment {
6084                name: name.clone(),
6085                path: path.clone(),
6086            });
6087        }
6088    }
6089    Ok(paths)
6090}
6091
6092/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6093/// answers before handing it to `Runner` — the actual boundary between
6094/// [`choose_starter`]'s routing and the graph, factored out so it is
6095/// assertable without a real repository, git branch, or agent CLI.
6096///
6097/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6098/// instruction from the reviewed branch's own commit log because there is no
6099/// task statement to speak of for hand-written work, and splicing operator
6100/// answers into that text would contradict the very message it sends
6101/// reviewers ("there is no task statement").
6102fn prepare_instruction(
6103    starter: &Starter,
6104    old_instruction: Option<&str>,
6105    task: &Task,
6106) -> Option<String> {
6107    match starter {
6108        Starter::Start => Some(instruction_for(task)),
6109        Starter::Resume(_) => Some(resumed_instruction(
6110            old_instruction.expect("a resumed run always has a prior instruction"),
6111            task,
6112        )),
6113        Starter::Review(_) => None,
6114    }
6115}
6116
6117/// Persist a transition. A queue write failure is logged rather than fatal: the
6118/// run already happened, and taking the daemon down would only add a lost
6119/// backlog to a full disk.
6120fn record(queue: &Queue, task: &mut Task) {
6121    if let Err(e) = queue.put(task) {
6122        tracing::error!("could not record task {}: {e:#}", task.short());
6123        let notice = Notice::error(
6124            "loop:record",
6125            format!(
6126                "Task {} state could not be saved: {}. Check the disk.",
6127                task.id,
6128                e.to_string().lines().next().unwrap_or("unknown save error")
6129            ),
6130        )
6131        .link(Link::Task {
6132            id: task.id.clone(),
6133        });
6134        // The queue lives at `<home>/queue`, so its parent is the home.
6135        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6136            Some(home) => notices::raise_in(home, notice),
6137            None => notices::raise(notice),
6138        }
6139    }
6140}
6141
6142/// Every runnable task, in the order the loop should try them.
6143///
6144/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6145/// tail exists so that a claim somebody else holds costs the loop the next
6146/// candidate rather than a whole poll interval of idleness.
6147fn runnable(queue: &Queue) -> Vec<Task> {
6148    let mut tasks: Vec<Task> = queue
6149        .list()
6150        .into_iter()
6151        .filter(|t| t.status.runnable())
6152        .collect();
6153    tasks.sort_unstable_by(crate::queue::dispatch_order);
6154    tasks
6155}
6156
6157/// Why a run ended where it did, in one line, for [`Task::last_error`].
6158///
6159/// A stalled run names the seats the quota took out: "out of quota" is not
6160/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6161/// agent to replace or which plan to top up.
6162///
6163/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6164/// purpose: unlike `label`'s other callers (an internal log line, an
6165/// already-a-bug fallback message), this string becomes `Task::last_error`
6166/// verbatim, which the phone renders in the same alarm-styled box an
6167/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6168/// `.err` styling. A bare `verified_noop` there would read exactly like the
6169/// failure this whole feature exists to tell apart from one.
6170fn describe(state: &RunState) -> String {
6171    let p = phrases(&state.config.graph.language);
6172    let mut detail = if state.status == RunStatus::Stalled {
6173        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6174        seats.sort_unstable();
6175        seats.dedup();
6176        if seats.is_empty() {
6177            p.quorum_lost.to_owned()
6178        } else {
6179            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6180        }
6181    } else {
6182        format!("{}{}", p.run_ended, state.status.display_label())
6183    };
6184    if let Some(cause) = state.verification_blocking_cause() {
6185        detail.push_str(&format!(" ({cause})"));
6186    } else if let Some(last) = state.events.last() {
6187        // The review loop's "never answered" stop is the one event worth
6188        // translating; it is recognised from structured state, not by
6189        // matching the English event text (which stays as recorded).
6190        let unanswered = state
6191            .reviews
6192            .last()
6193            .filter(|r| {
6194                state.status == RunStatus::Blocked
6195                    && last.node == "review"
6196                    && r.incomplete()
6197                    && r.blocking == 0
6198                    && r.round == state.config.graph.review_rounds
6199                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6200            })
6201            .map(|r| (r.expected - r.answered, r.round));
6202        match unanswered {
6203            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6204                detail.push_str(&format!(
6205                    " ({}: {})",
6206                    last.node,
6207                    (p.reviewers_never_answered)(missing, rounds)
6208                ));
6209            }
6210            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6211        }
6212    }
6213    detail.push_str(&format!(" [run {}]", state.id));
6214    detail
6215}
6216
6217/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6218///
6219/// The task file lives in the backlog indefinitely; a diagnostic is an
6220/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6221/// stay small regardless of how much a gate command or a candidate printed.
6222const DIAGNOSTIC_MAX: usize = 4_000;
6223
6224/// Tail kept from a single failing command's output inside a diagnostic.
6225/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6226/// pointer for a human deciding whether to go read the full artifact by hand,
6227/// not a replacement for reading it.
6228const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6229
6230/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6231/// `magi task show` says more than the one-line reason in [`describe`].
6232///
6233/// The one-liner answers "where did the run stop"; this answers "what would a
6234/// human have found opening `artifacts/` by hand" — the point of the whole
6235/// feature is the case that one-liner actively misleads on: a run held as "no
6236/// candidate produced a change" can mean the implementer actually finished
6237/// the task (opened a PR, merged it, tagged a release) and only left a clean
6238/// local worktree behind, which reads as "nothing happened" unless someone
6239/// goes and reads what the agent actually said. `None` when the run carries
6240/// none of the three shapes this recognises — an ordinary run held for
6241/// something not diagnosable from `RunState` alone still explains itself
6242/// through `Task::last_error`.
6243fn diagnostic(state: &RunState) -> Option<String> {
6244    let mut parts: Vec<String> = Vec::new();
6245
6246    // Gate failure: which check(s), and the tail of what each printed.
6247    for o in state.gate.iter().filter(|o| !o.ok()) {
6248        parts.push(format!(
6249            "gate `{}` failed ({}):\n{}",
6250            o.command,
6251            notices::exit_status(o.code),
6252            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6253        ));
6254    }
6255
6256    // The land loop gave up because the fixer declined while checks were
6257    // still red: the message already names them (see `land::run`).
6258    if let Some(last) = state
6259        .events
6260        .iter()
6261        .rev()
6262        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6263    {
6264        parts.push(last.message.clone());
6265    }
6266
6267    // No viable candidate: every implementer's own final word, sanitized the
6268    // same way a judge would have read it, so a run that actually finished
6269    // the job does not read as an unexplained failure. A verified no-op is
6270    // called out ahead of its own summary and apart from an ordinary
6271    // failure's `why` — this is the one candidate shape whose diagnostic a
6272    // human is expected to actually judge, not just skim.
6273    if state.viable().is_empty() {
6274        for c in &state.candidates {
6275            if let Some(evidence) = &c.verified_noop {
6276                parts.push(format!(
6277                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6278                    c.label
6279                ));
6280            } else if !c.summary.trim().is_empty() {
6281                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6282            } else if let Some(why) = &c.failed {
6283                parts.push(format!("candidate {}: {why}", c.label));
6284            }
6285        }
6286    }
6287
6288    if parts.is_empty() {
6289        return None;
6290    }
6291    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6292    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6293    // back slightly over. Leave it enough room to always land under the
6294    // limit.
6295    Some(crate::run::tail(
6296        &parts.join("\n\n"),
6297        DIAGNOSTIC_MAX.saturating_sub(100),
6298    ))
6299}
6300
6301/// Stable lower-case name for a run status, for an internal log line and the
6302/// "graph stopped without reaching a terminal status" bug message in
6303/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6304/// doc for why that one reads [`RunStatus::display_label`] instead. One
6305/// definition of a status's name, on the type that owns it: this table used
6306/// to live here as a second copy, and a status renamed in one place would
6307/// have gone on reading correctly in the other.
6308fn label(status: RunStatus) -> &'static str {
6309    status.as_str()
6310}
6311
6312/// Parse a merge mode override.
6313pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6314    match mode {
6315        "none" => Ok(MergeMode::None),
6316        "local" => Ok(MergeMode::Local),
6317        "pr" => Ok(MergeMode::Pr),
6318        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6319    }
6320}
6321
6322/// Take the status lock, recovering from a poisoned one.
6323///
6324/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6325/// data, and the worst a poisoned lock can hold is a stale timestamp.
6326fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6327    mutex
6328        .lock()
6329        .unwrap_or_else(std::sync::PoisonError::into_inner)
6330}
6331
6332#[cfg(test)]
6333mod tests {
6334    use super::*;
6335    use crate::queue::{Source, TaskStatus};
6336    use crate::run::{Candidate, CommandOutcome};
6337    use pretty_assertions::assert_eq;
6338
6339    fn task() -> Task {
6340        Task::new(
6341            "add retries".to_owned(),
6342            "add retries".to_owned(),
6343            PathBuf::from("/repo"),
6344            Source::Human,
6345        )
6346    }
6347
6348    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6349        let job = crate::worker::Job {
6350            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6351            sequence: 1,
6352            kind: "task".into(),
6353            key: format!("task:{}", request.task),
6354            payload: serde_json::to_value(request).unwrap(),
6355            generation: "a".repeat(64),
6356            version: None,
6357            status: crate::worker::Status::Starting,
6358            result: None,
6359            pid: None,
6360            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6361            finished_at: None,
6362        };
6363        let dir = home.join("workers/jobs").join(&job.id);
6364        std::fs::create_dir_all(&dir).unwrap();
6365        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6366        job
6367    }
6368
6369    #[test]
6370    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6371        let home = tempfile::tempdir().unwrap();
6372        let request = TaskWorker {
6373            opts: Opts::default(),
6374            queue: home.path().join("queue"),
6375            task: "startup".into(),
6376            lane: PermitKind::Ordinary,
6377            standalone: false,
6378        };
6379        let job = starting_task_reservation(home.path(), &request);
6380        let error = task_worker_spawn_error(
6381            home.path(),
6382            &request,
6383            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6384        )
6385        .expect_err("our own reservation must not turn a failed spawn into a resync");
6386        let active = crate::worker::active(home.path()).unwrap();
6387        assert_eq!(active.len(), 1);
6388        assert_eq!(active[0].id, job.id);
6389        assert_eq!(active[0].status, crate::worker::Status::Starting);
6390        assert!(
6391            crate::worker::control(home.path(), &job.key)
6392                .unwrap()
6393                .is_none()
6394        );
6395        let notices = notices::Notices::at(home.path().join("notifications")).list();
6396        assert_eq!(notices.len(), 1);
6397        assert_eq!(notices[0].key, "loop:worker-startup");
6398        assert!(!notices[0].message.contains("private-error-detail"));
6399        assert!(notices[0].message.contains(&request.task));
6400        assert!(
6401            notices[0]
6402                .message
6403                .contains("could not be started or acknowledged")
6404        );
6405        assert!(notices[0].message.contains("worker.log"));
6406        assert_eq!(
6407            notices[0].link,
6408            Some(Link::Task {
6409                id: request.task.clone()
6410            })
6411        );
6412        assert!(format!("{error:#}").contains("private-error-detail"));
6413    }
6414
6415    #[test]
6416    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6417        let home = tempfile::tempdir().unwrap();
6418        let mut request = TaskWorker {
6419            opts: Opts::default(),
6420            queue: home.path().join("queue"),
6421            task: "handoff".into(),
6422            lane: PermitKind::Ordinary,
6423            standalone: true,
6424        };
6425        let job = starting_task_reservation(home.path(), &request);
6426        request.standalone = false;
6427        task_worker_spawn_error(
6428            home.path(),
6429            &request,
6430            anyhow::anyhow!("operation key is already reserved for a different request"),
6431        )
6432        .expect("a different standalone request is the handoff race, not our startup failure");
6433        let active = crate::worker::active(home.path()).unwrap();
6434        assert_eq!(active.len(), 1);
6435        assert_eq!(active[0].id, job.id);
6436        assert_eq!(active[0].payload, job.payload);
6437        assert!(
6438            notices::Notices::at(home.path().join("notifications"))
6439                .list()
6440                .is_empty()
6441        );
6442    }
6443
6444    #[test]
6445    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6446        let home = tempfile::tempdir().unwrap();
6447        let queue = Queue::at(home.path().join("queue"));
6448        let mut task = task();
6449        task.runs = vec!["previous".into()];
6450        queue.put(&mut task).unwrap();
6451        let request = TaskWorker {
6452            opts: Opts::default(),
6453            queue: home.path().join("queue"),
6454            task: task.id.clone(),
6455            lane: PermitKind::Ordinary,
6456            standalone: false,
6457        };
6458        let job = starting_task_reservation(home.path(), &request);
6459        let claims = current_work(home.path(), Timestamp::now());
6460        assert_eq!(claims.len(), 1);
6461        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6462        assert_eq!(claims[0].run, "previous");
6463        assert!(other_claims_run(&claims, "previous", None));
6464        // Only after confirming the executing caller may admission ignore
6465        // this exact projection. Cleanup continues to observe it as live.
6466        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6467        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6468    }
6469
6470    #[test]
6471    fn admission_excludes_only_the_callers_exact_reservation() {
6472        let own = Current {
6473            worker: Some("own".into()),
6474            task: "same-task".into(),
6475            run: "previous".into(),
6476        };
6477        assert!(!other_claims_run(
6478            std::slice::from_ref(&own),
6479            "previous",
6480            Some("own")
6481        ));
6482        assert!(other_claims_run(
6483            std::slice::from_ref(&own),
6484            "previous",
6485            None
6486        ));
6487        for worker in [None, Some("other".into())] {
6488            let other = Current {
6489                worker,
6490                ..own.clone()
6491            };
6492            assert!(other_claims_run(
6493                &[own.clone(), other],
6494                "previous",
6495                Some("own")
6496            ));
6497        }
6498        let legacy: Current =
6499            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6500        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6501    }
6502
6503    #[test]
6504    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6505        let mut task = task();
6506        let mut run = run_state(RunStatus::Reviewing);
6507        run.task_instruction = Some(task.instruction.clone());
6508        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6509        let branch = "magi/test/B";
6510        run.candidates.push(crate::run::Candidate {
6511            branch: branch.into(),
6512            ..candidate('B', "preserved work", false, None)
6513        });
6514        task.runs = vec![run.id.clone()];
6515        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6516        assert_eq!(
6517            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6518            Starter::Resume(run.id.clone())
6519        );
6520        assert!(matches!(
6521            review_retry_starter(
6522                &task,
6523                Some(&run),
6524                Some("different"),
6525                true,
6526                unfinished.as_deref()
6527            ),
6528            Starter::Review(_)
6529        ));
6530        assert_eq!(
6531            review_retry_starter(
6532                &task,
6533                Some(&run),
6534                Some(branch),
6535                false,
6536                unfinished.as_deref()
6537            ),
6538            Starter::Start
6539        );
6540        task.instruction.push_str(" changed criteria");
6541        assert!(matches!(
6542            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6543            Starter::Review(_)
6544        ));
6545        assert!(matches!(
6546            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6547            Starter::Review(_)
6548        ));
6549    }
6550
6551    #[test]
6552    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6553        let dir = tempfile::tempdir().unwrap();
6554        let queue = Queue::at(dir.path().join("queue"));
6555        let mut task = task();
6556        task.status = TaskStatus::Running;
6557        task.attempts = 1;
6558        queue.put(&mut task).unwrap();
6559        let live = std::collections::BTreeSet::from([task.id.clone()]);
6560        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6561        drop(queue.claim(&task.id).unwrap());
6562        let saved = queue.get(&task.id).unwrap();
6563        assert_eq!(saved.status, TaskStatus::Running);
6564        assert_eq!(saved.attempts, 1);
6565        assert!(saved.last_error.is_none());
6566    }
6567
6568    #[test]
6569    fn standalone_workers_do_not_consume_scheduler_lanes() {
6570        let request = |task: &str, lane, standalone| TaskWorker {
6571            opts: Opts::default(),
6572            queue: PathBuf::from("/queue"),
6573            task: task.to_owned(),
6574            lane,
6575            standalone,
6576        };
6577        let mut jobs = vec![
6578            request("ordinary", PermitKind::Ordinary, false),
6579            request("standalone-urgent", PermitKind::Urgent, true),
6580            request("standalone-ordinary", PermitKind::Ordinary, true),
6581            request("decision", PermitKind::None, false),
6582        ];
6583        assert_eq!(available_slots(&jobs, 2), (1, 1));
6584        jobs.push(request("urgent", PermitKind::Urgent, false));
6585        assert_eq!(available_slots(&jobs, 2), (1, 0));
6586        assert_eq!(available_slots(&jobs, 0), (0, 0));
6587    }
6588
6589    #[test]
6590    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6591        let now = Timestamp::now();
6592        let mut reading = Reading {
6593            pid: Some(std::process::id()),
6594            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6595            ..Reading::default()
6596        };
6597        assert!(!reading.running(now));
6598        assert!(legacy_scheduler_running(&reading, now, 0));
6599        reading.worker_protocol = Some(1);
6600        assert!(!legacy_scheduler_running(&reading, now, 0));
6601    }
6602
6603    #[test]
6604    fn selected_public_head_overrides_historical_resume_and_pin() {
6605        let mut t = task();
6606        let mut old = run_state(RunStatus::Blocked);
6607        let selection = crate::pr_recovery::Selection {
6608            url: "url".into(),
6609            branch: format!("magi/task-{}", t.id),
6610            head: "a".repeat(40),
6611            source_head: None,
6612            source_run: None,
6613            source_proof: None,
6614            disposition: Some(crate::pr_recovery::Disposition::Review),
6615            instruction: t.instruction.clone(),
6616            approved_at: Timestamp::now(),
6617        };
6618        t.resume_override = Some(crate::queue::OperatorResume {
6619            pinned_run: Some(old.id.clone()),
6620            question_id: "choice".into(),
6621            at: Timestamp::now(),
6622            conductor_rehold: None,
6623            forced: false,
6624        });
6625        assert_eq!(
6626            selected_starter(&selection, Some(&old), Some(&old.id)),
6627            Starter::Review(selection.branch.clone())
6628        );
6629        old.pr_recovery = Some(selection.clone());
6630        assert_eq!(
6631            selected_starter(&selection, Some(&old), Some(&old.id)),
6632            Starter::Review(selection.branch.clone())
6633        );
6634        old.reviewed_commits = Some(vec!["implementation".into()]);
6635        assert_eq!(
6636            selected_starter(&selection, Some(&old), Some(&old.id)),
6637            Starter::Resume(old.id.clone())
6638        );
6639        let mut changed = selection.clone();
6640        changed.head = "b".repeat(40);
6641        assert_eq!(
6642            selected_starter(&changed, Some(&old), Some(&old.id)),
6643            Starter::Review(changed.branch)
6644        );
6645    }
6646
6647    #[test]
6648    fn candidate_transplant_failure_is_one_actionable_hold() {
6649        let dir = tempfile::tempdir().unwrap();
6650        let q = Queue::at(dir.path().join("queue"));
6651        let mut t = task();
6652        let mut state = run_state(RunStatus::Blocked);
6653        state.event("prep", "cannot apply referenced commit: conflict");
6654        state.prep_failure = Some("conflict".into());
6655        t.start(state.id.clone());
6656        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6657        assert_eq!(t.attempts, 1);
6658        assert_eq!(t.status, TaskStatus::Held);
6659        assert!(t.operator_held());
6660        assert!(!t.status.runnable());
6661        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6662        let first = t.chat_notice_key().unwrap();
6663        t.chat_notices.push(first.clone());
6664        t.release_operator("test", None);
6665        state.id = "another-unprepared-run".into();
6666        t.start(state.id.clone());
6667        finish_attempt(
6668            3,
6669            &q,
6670            &mut t,
6671            &state,
6672            &[],
6673            Err(anyhow::anyhow!("still conflicts")),
6674        );
6675        assert_eq!(
6676            t.chat_notice_key().as_ref(),
6677            Some(&first),
6678            "no work happened"
6679        );
6680        t.release_operator("test", None);
6681        state.prep_failure = None;
6682        state.status = RunStatus::Failed;
6683        state.begin_pass();
6684        t.start(state.id.clone());
6685        finish_attempt(
6686            1,
6687            &q,
6688            &mut t,
6689            &state,
6690            &[],
6691            Err(anyhow::anyhow!("new gate failure")),
6692        );
6693        let failure = t.chat_notice_key().unwrap();
6694        assert_ne!(failure, first, "approved recovery reached a real failure");
6695        t.release_operator("test", None);
6696        state.begin_pass();
6697        t.start(state.id.clone());
6698        finish_attempt(
6699            1,
6700            &q,
6701            &mut t,
6702            &state,
6703            &[],
6704            Err(anyhow::anyhow!("new failure on resume")),
6705        );
6706        assert_ne!(
6707            t.chat_notice_key().as_ref(),
6708            Some(&failure),
6709            "a new settled pass"
6710        );
6711    }
6712
6713    #[test]
6714    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6715        for source in ["cli", "web"] {
6716            let mut t = task();
6717            let mut run = run_state(RunStatus::Blocked);
6718            run.instruction = "Run A original criteria".into();
6719            run.task_instruction = Some(run.instruction.clone());
6720            t.start(run.id.clone());
6721            t.release_operator("choice", Some("resume-question"));
6722            t.resume_override = Some(crate::queue::OperatorResume {
6723                question_id: "resume-question".into(),
6724                at: Timestamp::now(),
6725                conductor_rehold: None,
6726                forced: true,
6727                pinned_run: Some(run.id.clone()),
6728            });
6729            t.hold_machine(Some("not enough free space to start a run".into()));
6730            let mut unchanged = t.clone();
6731            unchanged
6732                .edit("title changed".into(), unchanged.instruction.clone())
6733                .unwrap();
6734            unchanged.release_operator(source, None);
6735            assert_eq!(
6736                unchanged
6737                    .resume_override
6738                    .as_ref()
6739                    .unwrap()
6740                    .pinned_run
6741                    .as_deref(),
6742                Some(run.id.as_str())
6743            );
6744            assert!(!compatible_run_instruction(&run, &unchanged));
6745            assert!(may_resume_run(&run, &unchanged));
6746
6747            t.edit(
6748                "approved recovery".into(),
6749                "Reuse measured PR head B; fix Clippy; review".into(),
6750            )
6751            .unwrap();
6752            assert!(t.resume_override.is_none());
6753            t.release_operator(source, None);
6754            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6755            assert!(reloaded.resume_override.is_none());
6756            assert!(!may_resume_run(&run, &reloaded));
6757            let unfinished =
6758                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6759                    .filter(|_| may_resume_run(&run, &reloaded));
6760            assert_eq!(
6761                choose_starter(None, false, unfinished.as_deref()),
6762                Starter::Start
6763            );
6764            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6765            assert_eq!(
6766                reloaded.resumption_history[0].question_id.as_deref(),
6767                Some("resume-question")
6768            );
6769
6770            // A revision already persisted with the old approval/pin is also
6771            // invalidated when the new operator release is recorded.
6772            unchanged.instruction = "Reuse measured PR head B".into();
6773            unchanged.hold_machine(Some("disk hold".into()));
6774            unchanged.release_operator(source, None);
6775            assert!(unchanged.resume_override.is_none());
6776            assert!(!may_resume_run(&run, &unchanged));
6777        }
6778    }
6779
6780    #[test]
6781    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6782        let mut t = task();
6783        let mut run = run_state(RunStatus::Blocked);
6784        t.review_of = Some("approved-head".into());
6785        t.instruction =
6786            "Review the branch `approved-head` (review-only: no implementation, no judging)."
6787                .into();
6788        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();
6789        run.reviewed_commits = Some(vec!["Commit log".into()]);
6790        t.start(run.id.clone());
6791        t.hold_machine(Some("interrupted review".into()));
6792        t.release_operator("cli", None);
6793        assert!(
6794            compatible_run_instruction(&run, &t),
6795            "legacy explicit review remains resumable"
6796        );
6797        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6798            .filter(|_| compatible_run_instruction(&run, &t));
6799        assert_eq!(
6800            choose_starter(None, false, unfinished.as_deref()),
6801            Starter::Resume(run.id.clone())
6802        );
6803        run.task_instruction = Some(t.instruction.clone());
6804        assert!(compatible_run_instruction(&run, &t));
6805        let reloaded: RunState =
6806            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6807        assert!(compatible_run_instruction(&reloaded, &t));
6808        t.edit(
6809            "new approved head".into(),
6810            "Reuse measured PR head B".into(),
6811        )
6812        .unwrap();
6813        assert!(!compatible_run_instruction(&run, &t));
6814
6815        // Legacy recovery reviews retain the task criteria ahead of the log.
6816        t.review_of = None;
6817        t.instruction = "Fix Clippy on approved head".into();
6818        run.task_instruction = None;
6819        run.instruction = format!(
6820            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6821            t.instruction
6822        );
6823        assert!(compatible_run_instruction(&run, &t));
6824        t.instruction.push('\n');
6825        assert!(
6826            compatible_run_instruction(&run, &t),
6827            "legacy generated review trimmed the original criteria"
6828        );
6829        t.hold_for_handover(Some("approved-head".into()), "refused".into());
6830        let mut unchanged = t.clone();
6831        assert_eq!(
6832            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6833            Some("approved-head")
6834        );
6835        t.edit("new plan".into(), "Reuse measured PR head B".into())
6836            .unwrap();
6837        assert!(take_review_branch(&mut t, Some(&run)).is_none());
6838        assert!(!compatible_run_instruction(&run, &t));
6839        t.review_branch = Some("approved-head".into());
6840        t.review_instruction = None;
6841        assert!(
6842            take_review_branch(&mut t, Some(&run)).is_none(),
6843            "legacy retained candidate cannot replace a revised approved head"
6844        );
6845    }
6846
6847    #[test]
6848    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6849        let home = crate::run::test_home();
6850        crate::run::pin_test_home();
6851        let dir = tempfile::tempdir().unwrap();
6852        let queue = Queue::at(dir.path().join("queue"));
6853        for resume in [true, false] {
6854            let state = run_state(RunStatus::Blocked);
6855            let mut t = task();
6856            t.start(state.id.clone());
6857            let action = if resume {
6858                ask::ChoiceAction::Resume {
6859                    run: state.id.clone(),
6860                }
6861            } else {
6862                ask::ChoiceAction::Requeue
6863            };
6864            let mut q = action_question(&state.id, action);
6865            q.status = ask::QuestionStatus::Open;
6866            q.answer = None;
6867            q.answered_at = None;
6868            t.fail("run stopped with a question", 3);
6869            hold_if_runnable(&queue, &mut t);
6870            assert!(t.operator_decided_at.is_none());
6871            assert!(t.operator_held());
6872            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6873            let expected = if resume {
6874                ActionDecision::Resume(state.id.clone())
6875            } else {
6876                ActionDecision::Requeue
6877            };
6878            assert_eq!(
6879                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6880                expected
6881            );
6882            t.hold_manual(Some("later explicit hold".into()));
6883            assert_eq!(
6884                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6885                ActionDecision::Stale
6886            );
6887        }
6888    }
6889
6890    #[test]
6891    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6892        let mut t = task();
6893        t.answers.push(crate::queue::AnsweredQuestion {
6894            question: "Inspect the remote?".into(),
6895            answer: "Inspect then wait".into(),
6896        });
6897        let old = instruction_for(&t);
6898        assert!(compatible_instruction(&old, &t));
6899        t.instruction = "Reuse approved PR head and review".into();
6900        t.release_operator("cli", None);
6901        assert!(!compatible_instruction(&old, &t));
6902        let approved = instruction_for(&t);
6903        assert!(approved.contains("waiting premises are superseded"));
6904        assert!(compatible_instruction(&approved, &t));
6905        assert_eq!(resumed_instruction(&approved, &t), approved);
6906        t.release_operator("web", None);
6907        assert!(compatible_instruction(&approved, &t));
6908        assert_eq!(t.resumption_history.len(), 1);
6909        t.start("run".into());
6910        assert!(instruction_for(&t).contains("Explicit operator resumption"));
6911    }
6912
6913    /// A run that stopped on an infrastructure wait asked no agent anything:
6914    /// the task is held by the machine under a `[resource]` reason (resumable,
6915    /// re-checked by triage), and the attempt it started is given back.
6916    #[test]
6917    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6918        let mut state = RunState::new(
6919            PathBuf::from("/repo"),
6920            "main".into(),
6921            "base".into(),
6922            "task".into(),
6923            Config::default(),
6924        );
6925        state.status = RunStatus::Landing;
6926        state.parked = true;
6927        state.pr_pushed_head = Some("head".into());
6928        state.land_unrelated = Some(
6929            serde_json::from_value(serde_json::json!({
6930                "head": "head", "question": "ci-question",
6931                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6932            }))
6933            .unwrap(),
6934        );
6935        let mut t = task();
6936        t.start(state.id.clone());
6937        let verdict = Verdict {
6938            status: RunStatus::Landing,
6939            left_pr: true,
6940            quota_hit: false,
6941            parked: true,
6942            no_viable_candidates: false,
6943        };
6944        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6945        assert_eq!(t.attempts, 0);
6946        assert_eq!(t.status, TaskStatus::Held);
6947        assert!(!t.operator_held());
6948        assert!(
6949            t.hold_reason
6950                .as_deref()
6951                .unwrap()
6952                .starts_with("[ci-unrelated]")
6953        );
6954        // A second settlement must not refund an earlier task attempt.
6955        t.attempts = 1;
6956        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6957        assert_eq!(t.attempts, 1);
6958        assert_eq!(t.passes.len(), 1);
6959        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6960        state.pr_pushed_head = Some("new-head".into());
6961        state.parked = false;
6962        state.status = RunStatus::Blocked;
6963        let stale = Verdict {
6964            status: RunStatus::Blocked,
6965            parked: false,
6966            ..verdict
6967        };
6968        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6969        assert_eq!(t.attempts, 1);
6970        // A new execution pass can refund its own newly charged attempt.
6971        state.begin_pass();
6972        state.begin_pass();
6973        state.status = RunStatus::Landing;
6974        state.parked = true;
6975        state.pr_pushed_head = Some("head".into());
6976        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6977        assert_eq!(t.attempts, 0);
6978        assert_eq!(t.passes.len(), 2);
6979    }
6980
6981    #[test]
6982    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
6983        let mut state = run_state(RunStatus::Failed);
6984        state
6985            .quota
6986            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
6987        state.begin_pass();
6988        let mut t = task();
6989        t.start(state.id.clone());
6990        reclaim(&mut t, Some(state), 2, "en");
6991        assert_eq!(t.attempts, 1);
6992    }
6993
6994    #[test]
6995    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
6996        let mut state = run_state(RunStatus::Blocked);
6997        let losses: Vec<_> = ["alpha", "beta"]
6998            .into_iter()
6999            .enumerate()
7000            .map(|(i, agent)| {
7001                QuotaLoss::from_report(
7002                    format!("advisor-{i}"),
7003                    "advise",
7004                    Some(&crate::agent::Quota {
7005                        cause: crate::agent::QuotaCause::Authentication,
7006                        agent: agent.to_owned(),
7007                        reset: None,
7008                    }),
7009                )
7010            })
7011            .collect();
7012        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7013        state.quota = losses;
7014        let mut t = task();
7015        t.start(state.id.clone());
7016        let verdict = Verdict {
7017            status: state.status,
7018            left_pr: false,
7019            quota_hit: true,
7020            parked: false,
7021            no_viable_candidates: true,
7022        };
7023        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7024        assert_eq!(t.attempts, 0);
7025        assert_eq!(t.status, TaskStatus::Held);
7026        assert!(!t.operator_held());
7027        let reason = t.hold_reason.as_deref().unwrap();
7028        assert!(reason.starts_with("[authentication]"));
7029        assert!(
7030            reason.contains("alpha")
7031                && reason.contains("beta")
7032                && reason.contains("re-authenticate")
7033        );
7034        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7035        // Orphan recovery uses the same settlement and cannot spend an attempt.
7036        let mut orphan = task();
7037        orphan.start(state.id.clone());
7038        reclaim(&mut orphan, Some(state), 2, "en");
7039        assert_eq!(orphan.attempts, 0);
7040        assert_eq!(orphan.status, TaskStatus::Held);
7041    }
7042
7043    #[test]
7044    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7045        let mut state = RunState::new(
7046            PathBuf::from("/repo"),
7047            "main".to_owned(),
7048            "abc1234".to_owned(),
7049            "task".to_owned(),
7050            Config::default(),
7051        );
7052        state.status = RunStatus::Blocked;
7053        state.resource_block = Some(crate::run::ResourceBlock {
7054            cause: crate::run::ResourceBlockCause::Other,
7055            node: "graft".to_owned(),
7056            kind: "shared build cache".to_owned(),
7057            detail: "timed out".to_owned(),
7058            at: jiff::Timestamp::now(),
7059        });
7060        let mut t = task();
7061        t.start("20260902-000000-aaaa".to_owned());
7062        assert_eq!(t.attempts, 1);
7063        let verdict = Verdict {
7064            status: RunStatus::Blocked,
7065            left_pr: false,
7066            quota_hit: false,
7067            parked: false,
7068            no_viable_candidates: false,
7069        };
7070        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7071        assert_eq!(t.status, TaskStatus::Held);
7072        assert_eq!(t.attempts, 0, "the attempt is refunded");
7073        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7074        assert!(
7075            !t.operator_held(),
7076            "a machine hold, released without a human"
7077        );
7078
7079        let mut selected = task();
7080        selected.start("20260902-000000-cccc".into());
7081        selected.replacement = Some(crate::merge_decision::Replacement {
7082            question: "fixture".into(),
7083            run: "earlier".into(),
7084            pr: "https://example.invalid/pr/1".into(),
7085            agent: "selected".into(),
7086            context: "fixture".into(),
7087        });
7088        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7089        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7090        assert_eq!(selected.attempts, 0);
7091        assert!(
7092            !selected.operator_held(),
7093            "a selected agent also retains a machine resource hold"
7094        );
7095        assert!(
7096            selected
7097                .hold_reason
7098                .as_deref()
7099                .unwrap()
7100                .starts_with("[resource] ")
7101        );
7102
7103        // A park request outranks it: still the operator's doing.
7104        let mut p = task();
7105        p.start("20260902-000000-bbbb".to_owned());
7106        settle_and_diagnose(
7107            &mut p,
7108            Verdict {
7109                parked: true,
7110                ..verdict
7111            },
7112            "parked",
7113            2,
7114            &state,
7115        );
7116        assert_eq!(p.status, TaskStatus::Parked);
7117        assert_eq!(
7118            p.attempts, 0,
7119            "parking refunds once rather than also settling the resource hold"
7120        );
7121    }
7122
7123    #[test]
7124    fn record_failure_notice_links_the_task() {
7125        let dir = tempfile::tempdir().unwrap();
7126        // A regular file where the queue directory should be makes every
7127        // `put` fail, on every platform and whoever runs the test.
7128        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7129        let queue = Queue::at(dir.path().join("queue"));
7130        let mut t = interrupt_task("rec-fail-1");
7131        record(&queue, &mut t);
7132
7133        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7134        assert_eq!(found.len(), 1);
7135        assert_eq!(found[0].key, "loop:record");
7136        assert_eq!(
7137            found[0].link,
7138            Some(Link::Task {
7139                id: "rec-fail-1".to_owned()
7140            })
7141        );
7142    }
7143
7144    /// A runnable task marked to interrupt, with an id fixed for assertions
7145    /// rather than the random one [`Task::new`] mints.
7146    fn interrupt_task(id: &str) -> Task {
7147        let mut t = task();
7148        t.id = id.to_owned();
7149        t.interrupt = true;
7150        t
7151    }
7152
7153    /// An ordinary runnable task with an id fixed for assertions.
7154    fn task_with_id(id: &str) -> Task {
7155        let mut t = task();
7156        t.id = id.to_owned();
7157        t
7158    }
7159
7160    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7161    fn urgent_task(id: &str) -> Task {
7162        let mut t = task();
7163        t.id = id.to_owned();
7164        t.urgent = true;
7165        t
7166    }
7167
7168    #[test]
7169    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7170        let dir = tempfile::tempdir().unwrap();
7171        let queue = Queue::at(dir.path().join("queue"));
7172        let mut parked = task_with_id("parked");
7173        parked.start("run".into());
7174        parked.park("upgrade");
7175        parked.record_pass_at(
7176            "run",
7177            0,
7178            Some(Timestamp::now()),
7179            1,
7180            Some(crate::run::ParkCause::Upgrade {
7181                from: "old".into(),
7182                to: None,
7183            }),
7184        );
7185        let mut fresh = task_with_id("fresh");
7186        fresh.priority = 100;
7187        let mut urgent_task = urgent_task("urgent");
7188        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7189            queue.put(t).unwrap();
7190        }
7191        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7192        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7193        let candidates = runnable(&queue);
7194        assert_eq!(candidates[0].id, parked.id);
7195        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7196        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7197        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7198        drop(first);
7199        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7200        let next = runnable(&queue)
7201            .into_iter()
7202            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7203            .unwrap();
7204        assert_eq!(next.task.id, fresh.id);
7205        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7206        drop(claimed_elsewhere);
7207        drop(next);
7208        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7209    }
7210
7211    #[test]
7212    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7213        let dir = tempfile::tempdir().unwrap();
7214        let queue = Queue::at(dir.path().join("queue"));
7215        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7216        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7217        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7218        let mut first = task();
7219        queue.put(&mut first).unwrap();
7220        let stale_plain = queue.get(&first.id).unwrap();
7221        first.set_urgent(true).unwrap();
7222        queue.put(&mut first).unwrap();
7223        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7224        let mut second = urgent_task("second");
7225        queue.put(&mut second).unwrap();
7226        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7227        drop(queue.claim(&second.id).unwrap());
7228        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7229        drop(dispatched);
7230        let stale_urgent = queue.get(&first.id).unwrap();
7231        first.set_urgent(false).unwrap();
7232        queue.put(&mut first).unwrap();
7233        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7234        assert_eq!(urgent.available_permits(), 1);
7235        drop(queue.claim(&first.id).unwrap());
7236        drop(occupied);
7237    }
7238
7239    #[test]
7240    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7241        let dir = tempfile::tempdir().unwrap();
7242        let queue = Queue::at(dir.path().join("queue"));
7243        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7244        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7245        let mut t = task();
7246        queue.put(&mut t).unwrap();
7247        for enabled in [true, false] {
7248            let stale = queue.get(&t.id).unwrap();
7249            t.set_urgent(enabled).unwrap();
7250            queue.put(&mut t).unwrap();
7251            assert_ne!(stale.urgent, enabled);
7252            let DispatchClaim {
7253                task: fresh,
7254                claim,
7255                permit,
7256            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7257            assert_eq!(fresh.urgent, enabled);
7258            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7259            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7260            assert!(queue.claim(&t.id).is_err());
7261            assert_eq!(fresh.attempts, stale.attempts);
7262            drop((claim, permit));
7263            assert_eq!(ordinary.available_permits(), 1);
7264            assert_eq!(urgent.available_permits(), 1);
7265        }
7266        t.set_urgent(true).unwrap();
7267        queue.put(&mut t).unwrap();
7268        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7269        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7270        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7271        drop(queue.claim(&t.id).unwrap());
7272        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7273        drop(occupied);
7274        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7275        drop(queue.claim(&t.id).unwrap());
7276        let held = queue.claim(&t.id).unwrap();
7277        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7278        drop(held);
7279        t.status = TaskStatus::Held;
7280        queue.put(&mut t).unwrap();
7281        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7282        drop(queue.claim(&t.id).unwrap());
7283        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7284        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7285        drop(queue.claim(&t.id).unwrap());
7286        assert_eq!(urgent.available_permits(), 1);
7287    }
7288
7289    /// The land-resume exemption wins outright, whether or not the candidate
7290    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7291    /// queue behind anything" guarantee cannot be weaker just because the
7292    /// same task was also filed with `--urgent`.
7293    #[test]
7294    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7295        assert_eq!(permit_kind(true, false), PermitKind::None);
7296        assert_eq!(permit_kind(true, true), PermitKind::None);
7297    }
7298
7299    /// The one property this whole feature exists for: `--urgent` draws from
7300    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7301    /// ordinary candidate draws from the ordinary pool exactly as before,
7302    /// untouched by the urgent slot's existence.
7303    #[test]
7304    fn permit_kind_separates_urgent_from_ordinary() {
7305        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7306        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7307    }
7308
7309    /// The exact wiring `attempt` runs before minting anything: a config's
7310    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7311    /// Free space is injected rather than asked of the real disk - the point
7312    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7313    /// is deterministic on every machine this test runs on, never dependent
7314    /// on how full the CI runner's own disk happens to be.
7315    #[test]
7316    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7317        let cfg = Config::default();
7318        let repo = Path::new("/any/repo/path");
7319
7320        let reason =
7321            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7322        assert!(reason.contains("1024"), "{reason}");
7323        assert!(
7324            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7325            "{reason}"
7326        );
7327
7328        assert_eq!(
7329            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7330            None,
7331            "exactly at the floor is open"
7332        );
7333        assert_eq!(
7334            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7335            None,
7336            "comfortably above the floor is open"
7337        );
7338    }
7339
7340    #[test]
7341    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7342        let mut cfg = Config::default();
7343        cfg.disk.min_free_bytes = 0;
7344        let repo = Path::new("/any/repo/path");
7345        assert_eq!(
7346            disk_gate_with(repo, &cfg, |_| Ok(0)),
7347            None,
7348            "a zero floor never measures at all"
7349        );
7350    }
7351
7352    #[test]
7353    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7354        let cfg = Config::default();
7355        let repo = Path::new("/any/repo/path");
7356        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7357            .expect("a measurement failure must close the gate, not open it");
7358        assert!(reason.contains("could not measure"), "{reason}");
7359    }
7360
7361    #[test]
7362    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7363        let ordinary = task();
7364        let next = advance_interrupt(
7365            Interrupt::Idle,
7366            std::slice::from_ref(&ordinary.id),
7367            std::slice::from_ref(&ordinary),
7368        );
7369        assert_eq!(next, Interrupt::Idle);
7370    }
7371
7372    #[test]
7373    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7374        // Nothing to interrupt - this is just an ordinary candidate, and the
7375        // loop's normal dispatch will pick it up like any other.
7376        let marked = interrupt_task("marked");
7377        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7378        assert_eq!(next, Interrupt::Idle);
7379    }
7380
7381    #[test]
7382    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7383        let marked = interrupt_task("marked");
7384        let next = advance_interrupt(
7385            Interrupt::Idle,
7386            &["running".to_owned()],
7387            std::slice::from_ref(&marked),
7388        );
7389        assert_eq!(
7390            next,
7391            Interrupt::Parking {
7392                parked: vec!["running".to_owned()],
7393                interrupt_task: "marked".to_owned(),
7394            }
7395        );
7396    }
7397
7398    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7399    /// one run can be in flight when a task becomes runnable and marked.
7400    /// Parking all of them would mean `Resuming` later has more than one id
7401    /// to release back to ordinary dispatch, which cannot be made safe
7402    /// against that same setting's own extra concurrency slots letting two
7403    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7404    /// The simplification the task's own constraints ask for: do not begin
7405    /// a sequence at all until the herd settles back to exactly one.
7406    #[test]
7407    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7408        let marked = interrupt_task("marked");
7409
7410        let two = advance_interrupt(
7411            Interrupt::Idle,
7412            &["a".to_owned(), "b".to_owned()],
7413            std::slice::from_ref(&marked),
7414        );
7415        assert_eq!(two, Interrupt::Idle);
7416
7417        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7418        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7419    }
7420
7421    #[test]
7422    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7423        let state = Interrupt::Parking {
7424            parked: vec!["running".to_owned()],
7425            interrupt_task: "marked".to_owned(),
7426        };
7427        // Still in flight: no change.
7428        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7429        assert_eq!(still_going, state);
7430
7431        // Left flight, but the interrupt task has not been dispatched yet on
7432        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7433        // as long as it is still runnable.
7434        let stopped_but_not_yet_dispatched =
7435            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7436        assert_eq!(stopped_but_not_yet_dispatched, state);
7437
7438        // Left flight, and the interrupt task is now in flight itself.
7439        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7440        assert_eq!(
7441            dispatched,
7442            Interrupt::Running {
7443                parked: vec!["running".to_owned()],
7444                interrupt_task: "marked".to_owned(),
7445            }
7446        );
7447    }
7448
7449    #[test]
7450    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7451        let state = Interrupt::Running {
7452            parked: vec!["running".to_owned()],
7453            interrupt_task: "marked".to_owned(),
7454        };
7455        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7456        assert_eq!(still_running, state);
7457
7458        // Whatever it ended as - merged, failed, held - is not this
7459        // function's concern: leaving flight is the only trigger, driven
7460        // straight off the same in-flight list `poll` already reaps. It does
7461        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7462        // why that would let an unrelated task start ahead of, or alongside,
7463        // the guaranteed resume.
7464        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7465        assert_eq!(
7466            ended,
7467            Interrupt::Resuming {
7468                parked: vec!["running".to_owned()]
7469            }
7470        );
7471    }
7472
7473    #[test]
7474    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7475        let state = Interrupt::Resuming {
7476            parked: vec!["running".to_owned()],
7477        };
7478        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7479        assert_eq!(still_waiting, state);
7480
7481        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7482        assert_eq!(dispatched, Interrupt::Idle);
7483    }
7484
7485    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7486    /// or otherwise moved on by an operator with no claim standing in the
7487    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7488    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7489    /// come. The parked run still gets its resume.
7490    #[test]
7491    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7492    {
7493        let state = Interrupt::Parking {
7494            parked: vec!["running".to_owned()],
7495            interrupt_task: "marked".to_owned(),
7496        };
7497        // `marked` has been held/blocked/deleted since the sequence began:
7498        // it no longer appears in `runnable` at all.
7499        let next = advance_interrupt(state, &[], &[]);
7500        assert_eq!(
7501            next,
7502            Interrupt::Resuming {
7503                parked: vec!["running".to_owned()]
7504            },
7505            "abandoning the interrupt must not abandon the resume it owes"
7506        );
7507    }
7508
7509    /// The same abandonment, one step later: `Resuming` itself must not wait
7510    /// forever for a parked task that has since become unrunnable.
7511    #[test]
7512    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7513        let state = Interrupt::Resuming {
7514            parked: vec!["running".to_owned()],
7515        };
7516        let next = advance_interrupt(state, &[], &[]);
7517        assert_eq!(
7518            next,
7519            Interrupt::Idle,
7520            "nothing is left to wait for; the loop must not stay wedged"
7521        );
7522    }
7523
7524    #[test]
7525    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7526        let marked = interrupt_task("marked");
7527        let next = advance_interrupt_tick(
7528            false,
7529            Interrupt::Idle,
7530            &["running".to_owned()],
7531            std::slice::from_ref(&marked),
7532        );
7533        assert_eq!(
7534            next,
7535            Interrupt::Idle,
7536            "an unmarked, unconfigured daemon must behave exactly as before"
7537        );
7538    }
7539
7540    #[test]
7541    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7542        let state = Interrupt::Parking {
7543            parked: vec!["running".to_owned()],
7544            interrupt_task: "marked".to_owned(),
7545        };
7546        let candidates = vec![interrupt_task("marked"), task()];
7547        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7548        assert!(
7549            allowed.is_empty(),
7550            "nothing may dispatch - not even the interrupt task itself - \
7551             until the parked run has actually stopped"
7552        );
7553    }
7554
7555    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7556    /// grow a special case for it: an urgent candidate that is not the
7557    /// interrupt task withholds exactly like an ordinary one for as long as
7558    /// the parked run it is racing has not actually left flight. A version
7559    /// of this feature once bypassed the gate for urgent candidates, on the
7560    /// theory that a genuinely separate concurrency lane could not collide
7561    /// with 75dd's own; it could, and did - the bypassed task dispatched
7562    /// alongside a run 75dd's own state machine had only *asked* to park,
7563    /// not yet confirmed gone, which is exactly the second run
7564    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7565    /// tick during Parking/Running/Resuming where letting an extra
7566    /// candidate through is safe, urgent or not - the parked run may still
7567    /// be genuinely mid-call.
7568    #[test]
7569    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7570        for state in [
7571            Interrupt::Parking {
7572                parked: vec!["running".to_owned()],
7573                interrupt_task: "marked".to_owned(),
7574            },
7575            Interrupt::Running {
7576                parked: vec!["running".to_owned()],
7577                interrupt_task: "marked".to_owned(),
7578            },
7579            Interrupt::Resuming {
7580                parked: vec!["running".to_owned()],
7581            },
7582        ] {
7583            let candidates = vec![
7584                interrupt_task("marked"),
7585                urgent_task("hot"),
7586                task_with_id("ordinary"),
7587            ];
7588            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7589            assert!(
7590                !allowed.iter().any(|t| t.id == "hot"),
7591                "an urgent candidate must wait out the same gate as anything \
7592                 else while the run it would run alongside has not actually \
7593                 left flight, for state {state:?}: {allowed:?}"
7594            );
7595        }
7596    }
7597
7598    /// The one case where marking a task `--urgent` and `interrupt` at once
7599    /// is not redundant: once the interrupt sequence's own guaranteed
7600    /// resume/dispatch actually admits the task, it is unaffected by also
7601    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7602    /// never on the urgent flag.
7603    #[test]
7604    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7605        let state = Interrupt::Resuming {
7606            parked: vec!["hot".to_owned()],
7607        };
7608        let candidates = vec![urgent_task("hot"), task()];
7609        let allowed = interrupt_gate(&state, &[], candidates);
7610        assert_eq!(
7611            allowed.iter().filter(|t| t.id == "hot").count(),
7612            1,
7613            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7614        );
7615    }
7616
7617    #[test]
7618    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7619        let state = Interrupt::Parking {
7620            parked: vec!["running".to_owned()],
7621            interrupt_task: "marked".to_owned(),
7622        };
7623        let other = task();
7624        let candidates = vec![interrupt_task("marked"), other.clone()];
7625        let allowed = interrupt_gate(&state, &[], candidates);
7626        assert_eq!(allowed.len(), 1);
7627        assert_eq!(allowed[0].id, "marked");
7628    }
7629
7630    #[test]
7631    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7632        let state = Interrupt::Running {
7633            parked: vec!["running".to_owned()],
7634            interrupt_task: "marked".to_owned(),
7635        };
7636        let candidates = vec![task(), task()];
7637        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7638        assert!(allowed.is_empty());
7639    }
7640
7641    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7642    /// sequence began (only reachable above the default
7643    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7644    /// never both in the same tick, which is what "exactly one resume, no
7645    /// simultaneous run" actually requires structurally rather than by
7646    /// coincidence of how many ordinary slots happen to be free.
7647    #[test]
7648    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7649        let state = Interrupt::Resuming {
7650            parked: vec!["a".to_owned(), "c".to_owned()],
7651        };
7652        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7653        let allowed = interrupt_gate(&state, &[], candidates);
7654        assert_eq!(
7655            allowed.len(),
7656            1,
7657            "at most one candidate may be offered while resuming: {allowed:?}"
7658        );
7659        assert_eq!(allowed[0].id, "a");
7660    }
7661
7662    #[test]
7663    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7664        let state = Interrupt::Resuming {
7665            parked: vec!["a".to_owned()],
7666        };
7667        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7668        assert!(allowed.is_empty());
7669    }
7670
7671    /// The invariant the completion criteria ask for by name: across a whole
7672    /// simulated sequence, there is never a tick where the gate would let
7673    /// through both the parked run's resume and the interrupt task, and
7674    /// exactly one candidate resumes the instant the interrupt task's run
7675    /// ends - never zero, never more than one.
7676    #[test]
7677    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7678        let running = task(); // id: whatever `Task::new` minted
7679        let marked = interrupt_task("marked");
7680
7681        let mut state = Interrupt::Idle;
7682        // Tick 1: `running` is in flight, `marked` becomes runnable.
7683        let in_flight = vec![running.id.clone()];
7684        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7685        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7686        assert!(gated.is_empty(), "still waiting on `running` to park");
7687
7688        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7689        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7690        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7691        assert_eq!(
7692            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7693            vec!["marked"],
7694            "only the interrupt task may be offered to the dispatcher now"
7695        );
7696
7697        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7698        state = advance_interrupt_tick(
7699            true,
7700            state,
7701            &["marked".to_owned()],
7702            std::slice::from_ref(&running),
7703        );
7704        let gated = interrupt_gate(
7705            &state,
7706            &["marked".to_owned()],
7707            vec![marked.clone(), running.clone()],
7708        );
7709        assert!(
7710            gated.is_empty(),
7711            "the parked run must not be offered back while the interrupt \
7712             task is still running"
7713        );
7714
7715        // Tick 4: `marked`'s run reached a terminal status and left flight.
7716        // A higher-priority ordinary task `other` is also runnable now - it
7717        // must not be let through instead of, or alongside, `running`.
7718        let other = task_with_id("other");
7719        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7720        assert_eq!(
7721            state,
7722            Interrupt::Resuming {
7723                parked: vec![running.id.clone()]
7724            }
7725        );
7726        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7727        assert_eq!(
7728            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7729            vec![running.id.as_str()],
7730            "exactly the parked run resumes - not the unrelated task, even \
7731             though it was offered first"
7732        );
7733
7734        // Tick 5: `running` is now in flight (dispatched from tick 4's
7735        // gate). Only now does the sequence end and ordinary dispatch fully
7736        // resume.
7737        state = advance_interrupt_tick(
7738            true,
7739            state,
7740            std::slice::from_ref(&running.id),
7741            std::slice::from_ref(&other),
7742        );
7743        assert_eq!(state, Interrupt::Idle);
7744        let gated = interrupt_gate(
7745            &state,
7746            std::slice::from_ref(&running.id),
7747            vec![other.clone()],
7748        );
7749        assert_eq!(
7750            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7751            vec![other.id.as_str()],
7752            "ordinary dispatch is unrestricted again"
7753        );
7754    }
7755
7756    #[test]
7757    fn every_run_status_settles_the_task_it_came_from() {
7758        // run status, resulting task status, attempts still standing after one
7759        let table = [
7760            (RunStatus::Merged, TaskStatus::Done, 1),
7761            (RunStatus::Ready, TaskStatus::Done, 1),
7762            (RunStatus::Stalled, TaskStatus::Failed, 0),
7763            (RunStatus::Blocked, TaskStatus::Failed, 1),
7764            (RunStatus::Failed, TaskStatus::Failed, 1),
7765            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7766            (RunStatus::Prep, TaskStatus::Failed, 1),
7767            (RunStatus::Implementing, TaskStatus::Failed, 1),
7768            (RunStatus::Judging, TaskStatus::Failed, 1),
7769            (RunStatus::Deliberating, TaskStatus::Failed, 1),
7770            (RunStatus::Voting, TaskStatus::Failed, 1),
7771            (RunStatus::Reviewing, TaskStatus::Failed, 1),
7772            (RunStatus::Gating, TaskStatus::Failed, 1),
7773        ];
7774        for (run, want, attempts) in table {
7775            let mut t = task();
7776            t.start("20260902-000000-aaaa".to_owned());
7777            settle(
7778                &mut t,
7779                Verdict {
7780                    status: run,
7781                    left_pr: false,
7782                    parked: false,
7783                    quota_hit: matches!(run, RunStatus::Stalled),
7784                    no_viable_candidates: false,
7785                },
7786                "why",
7787                2,
7788            );
7789            assert_eq!(t.status, want, "task status after {}", label(run));
7790            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7791        }
7792    }
7793
7794    #[test]
7795    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7796        let mut stalled = task();
7797        stalled.start("20260902-000000-aaaa".to_owned());
7798        settle(
7799            &mut stalled,
7800            Verdict {
7801                status: RunStatus::Stalled,
7802                left_pr: false,
7803                parked: false,
7804                quota_hit: true,
7805                no_viable_candidates: false,
7806            },
7807            "quota",
7808            1,
7809        );
7810        assert_eq!(stalled.attempts, 0);
7811        assert!(
7812            stalled.status.runnable(),
7813            "a machine problem must leave the task in line"
7814        );
7815
7816        let mut blocked = task();
7817        blocked.start("20260902-000000-aaaa".to_owned());
7818        settle(
7819            &mut blocked,
7820            Verdict {
7821                status: RunStatus::Blocked,
7822                left_pr: false,
7823                parked: false,
7824                quota_hit: false,
7825                no_viable_candidates: false,
7826            },
7827            "findings open",
7828            1,
7829        );
7830        assert_eq!(blocked.attempts, 1);
7831        assert_eq!(
7832            blocked.status,
7833            TaskStatus::Held,
7834            "the last attempt hands the task to a human"
7835        );
7836    }
7837
7838    #[test]
7839    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7840        // Attempts to spare: without the pull request this task would go
7841        // straight back in line and run the whole competition again.
7842        let mut delivered = task();
7843        delivered.start("20260903-080619-01c2".to_owned());
7844        settle(
7845            &mut delivered,
7846            Verdict {
7847                status: RunStatus::Blocked,
7848                left_pr: true,
7849                parked: false,
7850                quota_hit: false,
7851                no_viable_candidates: false,
7852            },
7853            "no check status",
7854            4,
7855        );
7856        assert_eq!(
7857            delivered.status,
7858            TaskStatus::Held,
7859            "a pull request waiting on CI or a person is not a retryable failure"
7860        );
7861        assert!(
7862            !delivered.status.runnable(),
7863            "the loop must not pick this task up again"
7864        );
7865        assert_eq!(
7866            delivered.last_error.as_deref(),
7867            Some("no check status"),
7868            "the operator needs to be told what the gate was waiting for"
7869        );
7870
7871        // The same status without a pull request is a plain failure, and with
7872        // attempts left it is retried.
7873        let mut empty_handed = task();
7874        empty_handed.start("20260903-080619-01c2".to_owned());
7875        settle(
7876            &mut empty_handed,
7877            Verdict {
7878                status: RunStatus::Blocked,
7879                left_pr: false,
7880                parked: false,
7881                quota_hit: false,
7882                no_viable_candidates: false,
7883            },
7884            "findings open",
7885            4,
7886        );
7887        assert_eq!(empty_handed.status, TaskStatus::Failed);
7888        assert!(empty_handed.status.runnable());
7889    }
7890
7891    #[test]
7892    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7893        // Every candidate agreed, with evidence, that nothing belonged in the
7894        // worktree. That is not a confirmed success to close automatically -
7895        // a human still has to check the claim - and it is not an ordinary
7896        // failure either, so this settles exactly like a pull request nobody
7897        // merged yet: `Held`, same as `Blocked` with a PR.
7898        let mut noop = task();
7899        noop.start("20260912-131304-391f".to_owned());
7900        settle(
7901            &mut noop,
7902            Verdict {
7903                status: RunStatus::VerifiedNoop,
7904                left_pr: false,
7905                parked: false,
7906                quota_hit: false,
7907                no_viable_candidates: true,
7908            },
7909            "candidate A: already fixed by b32cfc4, on main",
7910            4,
7911        );
7912        assert_eq!(
7913            noop.status,
7914            TaskStatus::Held,
7915            "an unverified claim is a request for a human, not a failure"
7916        );
7917        assert!(
7918            !noop.status.runnable(),
7919            "the loop must not requeue this on the same unverified claim"
7920        );
7921        // `Task::release` resets attempts to zero the moment a human looks at
7922        // the evidence and lets it run again, so it does not matter here
7923        // whether the one attempt already spent stays spent - what matters is
7924        // that nothing retries this task unattended in the meantime.
7925        assert_eq!(noop.attempts, 1);
7926    }
7927
7928    #[test]
7929    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7930        // Parking is the operator asking for the process back - to replace the
7931        // binary, most of all. The run's work is intact on disk, so this is
7932        // not a failed attempt, and charging for it would mean a few upgrades
7933        // could exhaust a budget meant for agents that misbehaved.
7934        let mut parked = task();
7935        parked.start("20260903-183634-2d98".to_owned());
7936        settle(
7937            &mut parked,
7938            Verdict {
7939                status: RunStatus::Implementing,
7940                left_pr: false,
7941                quota_hit: false,
7942                parked: true,
7943                no_viable_candidates: false,
7944            },
7945            "parked after `implementing`",
7946            2,
7947        );
7948        assert_eq!(parked.attempts, 0, "a park is refunded");
7949        assert!(
7950            parked.status.runnable(),
7951            "and the task stays in line so the next loop resumes its run"
7952        );
7953        assert_eq!(parked.status, TaskStatus::Parked);
7954        assert_eq!(
7955            parked.park_reason.as_deref(),
7956            Some("parked after `implementing`"),
7957            "the card says where it stopped"
7958        );
7959        assert_eq!(parked.last_error, None, "nothing failed");
7960
7961        // Without the park flag the same non-terminal status is what it always
7962        // was: `execute` returning mid-flight, which is a bug and spends an
7963        // attempt so a task cannot loop on it forever.
7964        let mut broken = task();
7965        broken.start("20260903-183634-2d98".to_owned());
7966        settle(
7967            &mut broken,
7968            Verdict {
7969                status: RunStatus::Implementing,
7970                left_pr: false,
7971                quota_hit: false,
7972                parked: false,
7973                no_viable_candidates: false,
7974            },
7975            "returned mid-flight",
7976            2,
7977        );
7978        assert_eq!(broken.attempts, 1);
7979    }
7980
7981    #[test]
7982    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7983        // Run e633: quorum lost because two judges answered with the wrong
7984        // JSON shape, `quota: []`. Refunding that takes the bound off the
7985        // retry loop, and each retry pays for a fresh hour-long implement
7986        // wave before it can fail the same way.
7987        let mut flaky = task();
7988        flaky.start("20260903-123023-e633".to_owned());
7989        settle(
7990            &mut flaky,
7991            Verdict {
7992                status: RunStatus::Stalled,
7993                left_pr: false,
7994                parked: false,
7995                quota_hit: false,
7996                no_viable_candidates: false,
7997            },
7998            "verdict rests on 1 of 3 judges",
7999            2,
8000        );
8001        assert_eq!(
8002            flaky.attempts, 1,
8003            "flakiness spends an attempt, so `max_attempts` still bounds it"
8004        );
8005        assert!(flaky.status.runnable(), "and it is still worth retrying");
8006
8007        // The same status, lost to a rate limit, is the machine's fault.
8008        let mut limited = task();
8009        limited.start("20260903-123023-e633".to_owned());
8010        settle(
8011            &mut limited,
8012            Verdict {
8013                status: RunStatus::Stalled,
8014                left_pr: false,
8015                parked: false,
8016                quota_hit: true,
8017                no_viable_candidates: false,
8018            },
8019            "judge-2, judge-3 out of quota",
8020            2,
8021        );
8022        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8023        assert!(limited.status.runnable());
8024
8025        // And the bound really binds: a task that keeps stalling on flakiness
8026        // reaches a human instead of running the roster forever.
8027        let mut worn = task();
8028        for _ in 0..2 {
8029            worn.release();
8030        }
8031        worn.start("20260903-123023-e633".to_owned());
8032        worn.attempts = 2;
8033        settle(
8034            &mut worn,
8035            Verdict {
8036                status: RunStatus::Stalled,
8037                left_pr: false,
8038                parked: false,
8039                quota_hit: false,
8040                no_viable_candidates: false,
8041            },
8042            "no quorum again",
8043            2,
8044        );
8045        assert_eq!(worn.status, TaskStatus::Held);
8046        assert!(!worn.status.runnable());
8047    }
8048
8049    #[test]
8050    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8051        // The implement wave loses every seat to the same rate limit and
8052        // `after_implement` bails with nothing viable, which surfaces as
8053        // `Failed` rather than `Stalled`. That is the same machine fact the
8054        // `Stalled`-quota row already refunds, and must be refunded the same
8055        // way, or a quota outage quietly holds every task it touches instead
8056        // of leaving them in line for the reset.
8057        let mut wiped_out = task();
8058        wiped_out.start("20260907-025000-a1b2".to_owned());
8059        settle(
8060            &mut wiped_out,
8061            Verdict {
8062                status: RunStatus::Failed,
8063                left_pr: false,
8064                parked: false,
8065                quota_hit: true,
8066                no_viable_candidates: true,
8067            },
8068            "no candidate produced a change; nothing to judge",
8069            2,
8070        );
8071        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8072        assert!(
8073            wiped_out.status.runnable(),
8074            "a machine problem must leave the task in line"
8075        );
8076
8077        // This is the exemption that must stay narrow: a candidate that did
8078        // produce a change, and then failed for some other reason, still
8079        // spends the attempt even though a seat elsewhere hit its quota.
8080        // Otherwise every ordinary failure that happens to share a run with
8081        // an unrelated rate limit would be refunded for free.
8082        let mut partial_progress = task();
8083        partial_progress.start("20260907-025500-c3d4".to_owned());
8084        settle(
8085            &mut partial_progress,
8086            Verdict {
8087                status: RunStatus::Failed,
8088                left_pr: false,
8089                parked: false,
8090                quota_hit: true,
8091                no_viable_candidates: false,
8092            },
8093            "gate failed on the winning candidate",
8094            2,
8095        );
8096        assert_eq!(
8097            partial_progress.attempts, 1,
8098            "a candidate that actually produced a change spends the attempt \
8099             even though some other seat hit its quota"
8100        );
8101        assert!(partial_progress.status.runnable());
8102    }
8103
8104    #[test]
8105    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8106        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8107        // disk, and that construction must reach the same conclusion as the
8108        // one `attempt` builds from a live run, or a crash at exactly the
8109        // wrong moment gives a recovered task a different policy than one a
8110        // daemon finished settling itself.
8111        let mut t = task();
8112        t.start("20260907-025000-a1b2".to_owned());
8113        let mut state = run_state(RunStatus::Failed);
8114        state.quota.push(QuotaLoss {
8115            cause: crate::agent::QuotaCause::UsageLimit,
8116            agent: String::new(),
8117            seat: "cand-a".to_owned(),
8118            node: "implement".to_owned(),
8119            at: Timestamp::now(),
8120            reset: None,
8121        });
8122        assert!(
8123            state.viable().is_empty(),
8124            "no candidate was added, so nothing is viable"
8125        );
8126        reclaim(&mut t, Some(state), 2, "en");
8127        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8128        assert!(t.status.runnable());
8129    }
8130
8131    #[test]
8132    fn a_held_task_is_never_offered_to_the_loop() {
8133        let dir = tempfile::tempdir().unwrap();
8134        let queue = Queue::at(dir.path().to_path_buf());
8135        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8136            let mut t = task();
8137            t.id = format!("2026090{n}-000000-000{n}");
8138            t.priority = priority;
8139            queue.put(&mut t).unwrap();
8140        }
8141        let mut held = task();
8142        held.id = "20260909-000000-9999".to_owned();
8143        held.priority = 99;
8144        held.hold_machine(None);
8145        queue.put(&mut held).unwrap();
8146
8147        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8148        assert_eq!(order.len(), 3);
8149        assert!(!order.contains(&held.id));
8150        assert_eq!(
8151            order.first().cloned(),
8152            queue.next_runnable().map(|t| t.id),
8153            "the loop's first candidate is exactly what the queue offers"
8154        );
8155        assert_eq!(
8156            order,
8157            vec![
8158                "20260902-000000-0002".to_owned(),
8159                "20260903-000000-0003".to_owned(),
8160                "20260901-000000-0001".to_owned(),
8161            ],
8162            "priority first, then oldest, so nothing starves"
8163        );
8164    }
8165
8166    #[test]
8167    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8168        let dir = tempfile::tempdir().unwrap();
8169        let queue = Queue::at(dir.path().to_path_buf());
8170        let mut old = task();
8171        old.id = "20260101-000000-old0".to_owned();
8172        queue.put(&mut old).unwrap();
8173        let mut fresh = task();
8174        fresh.id = "20260101-000000-new0".to_owned();
8175        queue.put(&mut fresh).unwrap();
8176
8177        // No parseable pid at all, so age is the only signal there is to
8178        // check - unlike a real `Queue::claim`, which always names a real,
8179        // and therefore alive, pid this test cannot fake as dead.
8180        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8181        std::thread::sleep(Duration::from_millis(60));
8182        let live = queue.claim(&fresh.id).unwrap();
8183
8184        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8185        assert_eq!(swept, vec![old.id.clone()]);
8186        assert!(
8187            queue.claim(&old.id).is_ok(),
8188            "an unparseable lock older than the threshold is swept"
8189        );
8190        assert!(
8191            queue.claim(&fresh.id).is_err(),
8192            "a live pid protects its lock regardless of age"
8193        );
8194        drop(live);
8195    }
8196
8197    #[test]
8198    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8199        // A live worker's claim remains authoritative even beyond the sweep's
8200        // age limit. Sweeping it would permit a second competing attempt.
8201        let dir = tempfile::tempdir().unwrap();
8202        let queue = Queue::at(dir.path().to_path_buf());
8203        let mut t = task();
8204        t.id = "20260101-000000-live".to_owned();
8205        queue.put(&mut t).unwrap();
8206
8207        let claim = queue.claim(&t.id).unwrap();
8208        std::thread::sleep(Duration::from_millis(60));
8209
8210        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8211        assert!(
8212            swept.is_empty(),
8213            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8214        );
8215        assert!(
8216            queue.claim(&t.id).is_err(),
8217            "the lock still protects its task"
8218        );
8219        drop(claim);
8220    }
8221
8222    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8223    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8224    fn injected_dead_pid() -> u32 {
8225        std::process::id().checked_add(1).unwrap_or(1)
8226    }
8227
8228    #[test]
8229    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8230        let dir = tempfile::tempdir().unwrap();
8231        let queue = Queue::at(dir.path().to_path_buf());
8232        let mut t = task();
8233        t.id = "20260101-000000-dead".to_owned();
8234        queue.put(&mut t).unwrap();
8235        let dead_pid = injected_dead_pid();
8236
8237        // Written directly rather than through `Queue::claim`, which would
8238        // stamp this test process's own very much alive pid and defeat the
8239        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8240        // like moments after it died, not six hours later.
8241        std::fs::write(
8242            dir.path().join(format!("{}.lock", t.id)),
8243            dead_pid.to_string(),
8244        )
8245        .unwrap();
8246
8247        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8248            pid != dead_pid
8249        });
8250        assert_eq!(
8251            swept,
8252            vec![t.id.clone()],
8253            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8254        );
8255        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8256    }
8257
8258    #[test]
8259    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8260        let dir = tempfile::tempdir().unwrap();
8261        let queue = Queue::at(dir.path().to_path_buf());
8262        let mut t = task();
8263        t.id = "20260101-000000-late".to_owned();
8264        queue.put(&mut t).unwrap();
8265        let dead_pid = injected_dead_pid();
8266
8267        // Tick one, standing in for the sweep `poll` already runs at
8268        // startup: nothing to find yet.
8269        assert!(
8270            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8271            "nothing has claimed the task yet"
8272        );
8273
8274        // A second daemon claims the task and dies before it ever writes
8275        // `running`, well after this loop's own startup sweep already ran.
8276        std::fs::write(
8277            dir.path().join(format!("{}.lock", t.id)),
8278            dead_pid.to_string(),
8279        )
8280        .unwrap();
8281
8282        // Tick two, standing in for a poll long into this daemon's uptime:
8283        // the same function, called again, notices what only just appeared -
8284        // proving the sweep is not a one-shot startup check.
8285        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8286            pid != dead_pid
8287        });
8288        assert_eq!(swept, vec![t.id.clone()]);
8289    }
8290
8291    #[test]
8292    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8293        // `reclaim_orphaned_running` looks up the task's last run, which
8294        // touches `run::home()`; the first call anywhere in this binary wins,
8295        // so this is a no-op if another test already pinned one, and either
8296        // way the run id below is never written under it.
8297        crate::run::pin_test_home();
8298        let dir = tempfile::tempdir().unwrap();
8299        let queue = Queue::at(dir.path().to_path_buf());
8300        let mut t = task();
8301        t.id = "20260101-000000-crsh".to_owned();
8302        t.status = TaskStatus::Running;
8303        t.attempts = 1;
8304        // No `run.json` behind this id: standing in for a run this test does
8305        // not need to make readable, since the point is the lock, not the
8306        // recovery table `reclaim` already has its own tests for.
8307        t.runs.push("20260904-000000-4043".to_owned());
8308        queue.put(&mut t).unwrap();
8309        let dead_pid = injected_dead_pid();
8310
8311        // The crashed daemon's own claim, naming a pid nothing on the
8312        // machine holds anymore.
8313        std::fs::write(
8314            dir.path().join(format!("{}.lock", t.id)),
8315            dead_pid.to_string(),
8316        )
8317        .unwrap();
8318
8319        // Before the lock is swept the task looks claimed, and
8320        // `reclaim_orphaned_running` must leave it alone - this is exactly
8321        // the bug: a `running` task stranded behind a dead daemon's lock,
8322        // invisible to the claim-as-proof check because the lock outlived
8323        // the process that wrote it.
8324        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8325        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8326
8327        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8328            pid != dead_pid
8329        });
8330        assert_eq!(swept, vec![t.id.clone()]);
8331
8332        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8333        assert_eq!(reclaimed, vec![t.id.clone()]);
8334        let after = queue.get(&t.id).unwrap();
8335        assert_eq!(
8336            after.status,
8337            TaskStatus::Held,
8338            "no run.json to recover from, so a human is asked"
8339        );
8340        assert_eq!(
8341            after.runs,
8342            vec!["20260904-000000-4043".to_owned()],
8343            "the crashed run's id is kept as evidence, not discarded"
8344        );
8345    }
8346
8347    #[test]
8348    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8349        let dir = tempfile::tempdir().unwrap();
8350        let queue = Queue::at(dir.path().to_path_buf());
8351        let mut t = task();
8352        t.id = "20260101-000000-unknown".to_owned();
8353        queue.put(&mut t).unwrap();
8354        let dead_pid = injected_dead_pid();
8355        std::fs::write(
8356            dir.path().join(format!("{}.lock", t.id)),
8357            dead_pid.to_string(),
8358        )
8359        .unwrap();
8360
8361        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8362        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8363        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8364    }
8365
8366    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8367        let mut s = run_state(status);
8368        s.config.graph.language = language.to_owned();
8369        s
8370    }
8371
8372    fn unstarted_verdict(status: RunStatus) -> Verdict {
8373        Verdict {
8374            status,
8375            left_pr: false,
8376            quota_hit: false,
8377            parked: false,
8378            no_viable_candidates: false,
8379        }
8380    }
8381
8382    #[test]
8383    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8384        let mut t = task();
8385        t.attempts = 1;
8386        settle_in(
8387            &mut t,
8388            unstarted_verdict(RunStatus::AlreadyInBase),
8389            "already in main",
8390            1,
8391            phrases("en"),
8392        );
8393        assert_eq!(t.status, TaskStatus::Done);
8394        assert_eq!(t.attempts, 0);
8395    }
8396
8397    #[test]
8398    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8399        let reason = |language: &str| {
8400            let mut t = task();
8401            settle_in(
8402                &mut t,
8403                unstarted_verdict(RunStatus::Judging),
8404                "boom",
8405                1,
8406                phrases(language),
8407            );
8408            t.last_error.or(t.hold_reason).unwrap_or_default()
8409        };
8410        assert!(
8411            reason("en").starts_with("the graph stopped at `"),
8412            "{}",
8413            reason("en")
8414        );
8415        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8416        assert!(reason("日本語").contains("boom"));
8417        assert_eq!(reason("fr"), reason("en"));
8418    }
8419
8420    #[test]
8421    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8422        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8423        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8424        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8425        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8426        assert!(ja.contains("[run "), "{ja}");
8427        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8428        assert!(ended.starts_with("run 終了: "), "{ended}");
8429        let mut de = run_state_in(RunStatus::Failed, "de");
8430        let mut en = run_state_in(RunStatus::Failed, "en");
8431        de.id = "same".to_owned();
8432        en.id = "same".to_owned();
8433        assert_eq!(describe(&de), describe(&en));
8434    }
8435
8436    #[test]
8437    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8438        use crate::handover::Refused;
8439        let cases = [
8440            Refused::Foreign {
8441                branch: "b".into(),
8442                path: "/w/x".into(),
8443                why: "made by hand".into(),
8444            },
8445            Refused::Unsafe {
8446                branch: "b".into(),
8447                path: "/w/x".into(),
8448                why: "its worktree has uncommitted changes (a.rs)".into(),
8449            },
8450            Refused::ReleaseFailed {
8451                branch: "b".into(),
8452                path: "/w/x".into(),
8453                run: "ab12".into(),
8454            },
8455        ];
8456        for r in &cases {
8457            let en = (phrases("en").handover_refused)(r);
8458            assert_eq!(en, r.to_string());
8459            let ja = (phrases("ja").handover_refused)(r);
8460            assert!(
8461                !ja.contains("is checked out") && !ja.contains("try again"),
8462                "{ja}"
8463            );
8464            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8465            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8466                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8467            }
8468        }
8469        assert!(phrases("en").handover_hint.contains("release the task"));
8470        assert!(phrases("ja").handover_hint.contains("解放"));
8471    }
8472
8473    #[test]
8474    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8475        let build = |lang: &str| {
8476            let mut s = run_state_in(RunStatus::Blocked, lang);
8477            s.id = "same".to_owned();
8478            s.config.graph.review_rounds = 3;
8479            let mut r = review_round(3);
8480            r.expected = 3;
8481            r.answered = 1;
8482            s.reviews.push(r);
8483            s.event(
8484                "review",
8485                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8486            );
8487            s
8488        };
8489        let en = describe(&build("en"));
8490        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8491        let ja = describe(&build("ja"));
8492        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8493        assert!(!ja.contains("never answered"), "{ja}");
8494        assert!(ja.contains("[run "), "{ja}");
8495
8496        // An incomplete panel whose verification failed is a different stop:
8497        // the real event must survive in ja too.
8498        let mut failed = build("ja");
8499        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8500            command: "cargo test".to_owned(),
8501            code: Some(1),
8502            output_tail: String::new(),
8503            duration_ms: 0,
8504            resource_blocked: false,
8505        });
8506        failed.event("review", "stopped; e2e failed: cargo test");
8507        let ja = describe(&failed);
8508        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8509        assert!(!ja.contains("席のレビュアー"), "{ja}");
8510    }
8511
8512    #[test]
8513    fn refusals_and_recovery_prose_follow_the_language() {
8514        let home = crate::run::test_home();
8515        let t = held_task_with("r1");
8516        let q = action_question(
8517            "r1",
8518            ask::ChoiceAction::Resume {
8519                run: "r1".to_owned(),
8520            },
8521        );
8522        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
8523            ActionDecision::Refuse(s) => s,
8524            other => panic!("{other:?}"),
8525        };
8526        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8527        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8528        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8529
8530        let mut held = task();
8531        reclaim(&mut held, None, 2, "ja");
8532        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8533        let mut held = task();
8534        reclaim(&mut held, None, 2, "xx");
8535        assert!(held.hold_reason.unwrap().contains("held for a human"));
8536    }
8537
8538    fn run_state(status: RunStatus) -> RunState {
8539        let mut state = RunState::new(
8540            PathBuf::from("/repo"),
8541            "main".to_owned(),
8542            "abc1234def".to_owned(),
8543            "add retries".to_owned(),
8544            Config::default(),
8545        );
8546        state.status = status;
8547        state
8548    }
8549
8550    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8551        Candidate {
8552            index: 0,
8553            label,
8554            agent: "claude".to_owned(),
8555            branch: format!("magi/x/{label}"),
8556            worktree: PathBuf::from("/repo"),
8557            summary: summary.to_owned(),
8558            stat: String::new(),
8559            files: 0,
8560            commits: usize::from(!empty),
8561            empty,
8562            failed: failed.map(str::to_owned),
8563            verified_noop: None,
8564            duration_ms: 0,
8565            folded: false,
8566        }
8567    }
8568
8569    #[test]
8570    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8571        let mut state = run_state(RunStatus::Blocked);
8572        state.gate = vec![
8573            CommandOutcome {
8574                command: "cargo make check".to_owned(),
8575                code: Some(0),
8576                output_tail: "ok".to_owned(),
8577                duration_ms: 0,
8578                resource_blocked: false,
8579            },
8580            CommandOutcome {
8581                command: "cargo test".to_owned(),
8582                code: Some(101),
8583                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8584                duration_ms: 0,
8585                resource_blocked: false,
8586            },
8587        ];
8588        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8589        assert!(d.contains("cargo test"), "{d}");
8590        assert!(
8591            !d.contains("cargo make check"),
8592            "a passing check is not a diagnostic: {d}"
8593        );
8594        assert!(d.contains("assertion failed"), "{d}");
8595    }
8596
8597    #[test]
8598    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8599        let mut state = run_state(RunStatus::Blocked);
8600        state.event(
8601            "land",
8602            "stopped: the fixer produced no commit while 2 check(s) were failing \
8603             (build, lint); stopping instead of looping on an unchanged tree",
8604        );
8605        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8606        assert!(d.contains("build"), "{d}");
8607        assert!(d.contains("lint"), "{d}");
8608        assert!(d.contains("fixer produced no commit"), "{d}");
8609    }
8610
8611    #[test]
8612    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8613        // `describe`'s output becomes `Task::last_error` verbatim, and the
8614        // phone renders that in the same alarm-styled box an ordinary
8615        // failure gets. A bare `verified_noop` there would read exactly like
8616        // the failure this status exists to be told apart from.
8617        let state = run_state(RunStatus::VerifiedNoop);
8618        let d = describe(&state);
8619        assert!(
8620            d.contains("agent-verified no-op"),
8621            "expected the display label, not the wire spelling: {d}"
8622        );
8623        assert!(!d.contains("verified_noop"), "{d}");
8624    }
8625
8626    #[test]
8627    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8628        let mut state = run_state(RunStatus::Failed);
8629        state.gate.push(crate::run::CommandOutcome {
8630            command: "cargo test".into(),
8631            code: Some(101),
8632            output_tail: format!(
8633                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8634                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8635            ),
8636            duration_ms: 1,
8637            resource_blocked: false,
8638        });
8639        let d = diagnostic(&state).unwrap();
8640        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8641        assert!(d.contains("assertion failed: widget missing"));
8642        assert!(d.contains("widget log"));
8643    }
8644
8645    #[test]
8646    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8647        // The whole point of the feature: a run held as "no candidate produced
8648        // a change" can mean the implementer actually finished the task and
8649        // only left a clean local tree behind - see AGENTS.md on this exact
8650        // failure mode. The diagnostic has to carry what the agent actually
8651        // said, not just the fact that nothing was there to judge.
8652        let mut state = run_state(RunStatus::Failed);
8653        state.candidates = vec![candidate(
8654            'A',
8655            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8656            true,
8657            None,
8658        )];
8659        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8660        assert!(d.contains("candidate A"), "{d}");
8661        assert!(d.contains("tagged v1.2.3"), "{d}");
8662    }
8663
8664    #[test]
8665    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8666        let mut state = run_state(RunStatus::Failed);
8667        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8668        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8669        assert!(d.contains("candidate A"), "{d}");
8670        assert!(d.contains("agent timed out"), "{d}");
8671    }
8672
8673    #[test]
8674    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8675        // A viable candidate existed, the gate never ran, and nothing land
8676        // said matches - `Task::last_error` is left to explain this one alone.
8677        let mut state = run_state(RunStatus::Failed);
8678        state.candidates = vec![candidate('A', "did the work", false, None)];
8679        assert!(diagnostic(&state).is_none());
8680    }
8681
8682    #[test]
8683    fn diagnostic_is_bounded_however_much_a_run_printed() {
8684        let mut state = run_state(RunStatus::Blocked);
8685        state.gate = vec![
8686            CommandOutcome {
8687                command: "cargo test".to_owned(),
8688                code: Some(101),
8689                output_tail: "x".repeat(50_000),
8690                duration_ms: 0,
8691                resource_blocked: false,
8692            },
8693            CommandOutcome {
8694                command: "cargo clippy".to_owned(),
8695                code: Some(1),
8696                output_tail: "y".repeat(50_000),
8697                duration_ms: 0,
8698                resource_blocked: false,
8699            },
8700        ];
8701        state.candidates = vec![
8702            candidate('A', &"z".repeat(50_000), true, None),
8703            candidate('B', &"w".repeat(50_000), true, None),
8704        ];
8705        let d = diagnostic(&state).expect("plenty here to diagnose");
8706        assert!(
8707            d.len() <= DIAGNOSTIC_MAX,
8708            "diagnostic grew to {} bytes, unbounded",
8709            d.len()
8710        );
8711    }
8712
8713    #[test]
8714    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8715        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8716            let mut t = task();
8717            let mut state = run_state(status);
8718            t.pr_recovery = Some(crate::pr_recovery::Selection {
8719                url: "url".into(),
8720                branch: format!("magi/task-{}", t.id),
8721                head: "a".repeat(40),
8722                source_head: None,
8723                source_run: None,
8724                source_proof: None,
8725                disposition: Some(crate::pr_recovery::Disposition::Land),
8726                instruction: t.instruction.clone(),
8727                approved_at: Timestamp::now(),
8728            });
8729            state.pr_recovery = t.pr_recovery.clone();
8730            t.start(state.id.clone());
8731            settle_and_diagnose(
8732                &mut t,
8733                Verdict {
8734                    status,
8735                    left_pr: false,
8736                    quota_hit: false,
8737                    parked: false,
8738                    no_viable_candidates: false,
8739                },
8740                "delivery stopped",
8741                5,
8742                &state,
8743            );
8744            assert_eq!(t.status, TaskStatus::Held);
8745            let reason = t.hold_reason.as_deref().unwrap();
8746            if status == RunStatus::Ready {
8747                assert!(reason.contains("Selected PR delivery is incomplete"));
8748                assert!(t.recovery_budget.is_none());
8749            } else {
8750                assert!(reason.contains("Selected recovery stopped"));
8751                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8752            }
8753            assert!(t.pr_recovery.is_some());
8754        }
8755    }
8756
8757    #[test]
8758    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8759        let mut state = run_state(RunStatus::Voting);
8760        state.base_sync = Some(crate::run::BaseSync {
8761            tip: "base-tip".into(),
8762            behind: 3,
8763            attempts: 4,
8764            conflict: Some("base stopped".into()),
8765            already_in: None,
8766        });
8767        state.record_base_sync_stop("candidate-head");
8768        let mut t = task();
8769        t.start(state.id.clone());
8770        let verdict = Verdict {
8771            status: RunStatus::Blocked,
8772            left_pr: false,
8773            quota_hit: false,
8774            parked: false,
8775            no_viable_candidates: false,
8776        };
8777        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8778        assert_eq!(
8779            t.status,
8780            TaskStatus::Held,
8781            "unspent task attempts cannot start another competition"
8782        );
8783        let at = t.held_at;
8784        let cause = t.hold_notice_cause.clone();
8785        state.begin_pass();
8786        t.release_operator("test-resume", None);
8787        t.start(state.id.clone());
8788        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8789        assert_eq!(t.status, TaskStatus::Held);
8790        assert_eq!(t.held_at, at);
8791        assert_eq!(t.hold_notice_cause, cause);
8792    }
8793
8794    #[test]
8795    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8796        let mut state = run_state(RunStatus::Blocked);
8797        state.gate = vec![CommandOutcome {
8798            command: "cargo test".to_owned(),
8799            code: Some(101),
8800            output_tail: "assertion failed".to_owned(),
8801            duration_ms: 0,
8802            resource_blocked: false,
8803        }];
8804        let verdict = Verdict {
8805            status: RunStatus::Blocked,
8806            left_pr: false,
8807            quota_hit: false,
8808            parked: false,
8809            no_viable_candidates: false,
8810        };
8811
8812        // Attempt one of two still has a retry coming: no diagnostic yet, the
8813        // task is going to run again and this run's evidence would go stale.
8814        let mut t = task();
8815        t.start("run-1".to_owned());
8816        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8817        assert_eq!(t.status, TaskStatus::Failed);
8818        assert!(t.diagnostic.is_none());
8819
8820        // Attempt two exhausts the budget: now it is held, and the
8821        // diagnostic is what `magi task show` has to say more than one line.
8822        t.start("run-2".to_owned());
8823        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8824        assert_eq!(t.status, TaskStatus::Held);
8825        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8826        assert!(d.contains("cargo test"), "{d}");
8827    }
8828
8829    #[test]
8830    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8831        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8832        // `magi ask` question settled Held with `hold_reason: null`, so the
8833        // notification said nothing actionable. `note_open_question` should
8834        // append the question id to whatever `handed_off` already wrote.
8835        crate::run::pin_test_home();
8836        let home = crate::run::home();
8837        let state = run_state(RunStatus::VerifiedNoop);
8838        let mut q = ask::Question::new(
8839            state.id.clone(),
8840            "implement".to_owned(),
8841            "impl-A".to_owned(),
8842            "is this really a no-op?".to_owned(),
8843            String::new(),
8844            Vec::new(),
8845        );
8846        Questions::at(home.join("questions")).put(&mut q).unwrap();
8847
8848        let verdict = Verdict {
8849            status: RunStatus::VerifiedNoop,
8850            left_pr: false,
8851            quota_hit: false,
8852            parked: false,
8853            no_viable_candidates: false,
8854        };
8855        let mut t = task();
8856        t.start(state.id.clone());
8857        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8858
8859        assert_eq!(t.status, TaskStatus::Held);
8860        let reason = t.hold_reason.expect("a held task must record why");
8861        assert!(
8862            reason.starts_with("run ended agent-verified no-op"),
8863            "the original settle reason must survive unchanged: {reason}"
8864        );
8865        assert!(
8866            reason.contains(q.short()),
8867            "the open question's id must be named so the notice is actionable: {reason}"
8868        );
8869    }
8870
8871    #[test]
8872    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8873        crate::run::pin_test_home();
8874        let state = run_state(RunStatus::VerifiedNoop);
8875
8876        let verdict = Verdict {
8877            status: RunStatus::VerifiedNoop,
8878            left_pr: false,
8879            quota_hit: false,
8880            parked: false,
8881            no_viable_candidates: false,
8882        };
8883        let mut t = task();
8884        t.start(state.id.clone());
8885        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8886
8887        assert_eq!(t.status, TaskStatus::Held);
8888        assert_eq!(
8889            t.hold_reason.as_deref(),
8890            Some("run ended agent-verified no-op"),
8891            "nothing to append when the question was already answered or never asked"
8892        );
8893    }
8894
8895    #[test]
8896    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8897        crate::run::pin_test_home();
8898        let mut first = run_state(RunStatus::Blocked);
8899        first.id = "20260101-000000-sup1".to_owned();
8900        first.save().unwrap();
8901        let mut second = run_state(RunStatus::Merged);
8902        second.id = "20260101-000000-sup2".to_owned();
8903        second.save().unwrap();
8904
8905        let mut t = task();
8906        t.runs = vec![first.id.clone(), second.id.clone()];
8907        t.status = TaskStatus::Done;
8908
8909        supersede_prior_runs(&t, &crate::run::home());
8910
8911        assert_eq!(
8912            RunState::load(&first.id).unwrap().status,
8913            RunStatus::Superseded,
8914            "the first attempt's Blocked no longer needs anyone's attention"
8915        );
8916        assert_eq!(
8917            RunState::load(&second.id).unwrap().status,
8918            RunStatus::Merged,
8919            "the run that actually succeeded is left exactly as it was"
8920        );
8921    }
8922
8923    #[test]
8924    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8925        // `is_working_on` alone only proves a *daemon* claim; a `magi run
8926        // --resume` invoked by hand outside the daemon never touches
8927        // `daemon.json` at all, so it would look identical to a genuinely
8928        // idle run without also consulting `RunState::liveness`, which reads
8929        // this run's own recorded `driver_pid` instead.
8930        crate::run::pin_test_home();
8931        let mut first = run_state(RunStatus::Blocked);
8932        first.id = "20260101-000000-sup9".to_owned();
8933        // This test process's own pid: guaranteed alive without needing a
8934        // real second process or daemon.
8935        first.driver_pid = Some(std::process::id());
8936        first.driver_started_at = Some(
8937            crate::proc::process_started_at(std::process::id())
8938                .expect("this test process's own start time must be queryable"),
8939        );
8940        first.save().unwrap();
8941        let mut second = run_state(RunStatus::Merged);
8942        second.id = "20260101-000000-supa".to_owned();
8943        second.save().unwrap();
8944
8945        let mut t = task();
8946        t.runs = vec![first.id.clone(), second.id.clone()];
8947        t.status = TaskStatus::Done;
8948
8949        supersede_prior_runs(&t, &crate::run::home());
8950
8951        assert_eq!(
8952            RunState::load(&first.id).unwrap().status,
8953            RunStatus::Blocked,
8954            "a live driver_pid means something is still actually working this run, \
8955             even though no daemon claims it - rewriting under it would just be \
8956             undone the next time that process saves"
8957        );
8958    }
8959
8960    #[test]
8961    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8962        // The first resweep must skip a still-live attempt exactly like
8963        // `supersede_prior_runs` itself does; a later resweep, once that
8964        // process is no longer actually driving it, is what closes the gap
8965        // `supersede_prior_runs` alone leaves - a task only ever reaches
8966        // `Done` once, so nothing else would ever look at this run again.
8967        let dir = tempfile::tempdir().unwrap();
8968        let home = dir.path().to_path_buf();
8969        let queue = Queue::at(dir.path().join("queue"));
8970
8971        let mut first = run_state(RunStatus::Blocked);
8972        first.id = "20260101-000000-supd".to_owned();
8973        first.driver_pid = Some(std::process::id());
8974        first.driver_started_at = Some(
8975            crate::proc::process_started_at(std::process::id())
8976                .expect("this test process's own start time must be queryable"),
8977        );
8978        first.save_under(&home).unwrap();
8979        let mut second = run_state(RunStatus::Merged);
8980        second.id = "20260101-000000-supe".to_owned();
8981        second.save_under(&home).unwrap();
8982
8983        let mut t = task();
8984        t.runs = vec![first.id.clone(), second.id.clone()];
8985        t.status = TaskStatus::Done;
8986        queue.put(&mut t).unwrap();
8987
8988        resweep_superseded_attempts(&queue, &home);
8989        assert_eq!(
8990            RunState::load_under(&first.id, &home).unwrap().status,
8991            RunStatus::Blocked,
8992            "still live on the first pass, so still untouched"
8993        );
8994
8995        // Stand in for the manual process no longer being the one driving
8996        // this run: same pid (this test process really is still alive), but
8997        // an identity marker that no longer matches it - see
8998        // `RunState::liveness`'s own doc for why a mismatched
8999        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9000        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9001        stale.driver_started_at = Some("1".to_owned());
9002        stale.save_under(&home).unwrap();
9003
9004        resweep_superseded_attempts(&queue, &home);
9005        assert_eq!(
9006            RunState::load_under(&first.id, &home).unwrap().status,
9007            RunStatus::Superseded,
9008            "the second pass catches up what the first one correctly skipped"
9009        );
9010    }
9011
9012    #[test]
9013    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9014        crate::run::pin_test_home();
9015        let mut first = run_state(RunStatus::Blocked);
9016        first.id = "20260101-000000-sup3".to_owned();
9017        first.save().unwrap();
9018        let mut second = run_state(RunStatus::Blocked);
9019        second.id = "20260101-000000-sup4".to_owned();
9020        second.save().unwrap();
9021
9022        let mut t = task();
9023        t.runs = vec![first.id.clone(), second.id.clone()];
9024        // Still retrying: nothing about this task's story is settled yet, so
9025        // neither Blocked run may be relabelled, even though a later attempt
9026        // already exists.
9027        t.status = TaskStatus::Failed;
9028
9029        supersede_prior_runs(&t, &crate::run::home());
9030
9031        assert_eq!(
9032            RunState::load(&first.id).unwrap().status,
9033            RunStatus::Blocked
9034        );
9035        assert_eq!(
9036            RunState::load(&second.id).unwrap().status,
9037            RunStatus::Blocked
9038        );
9039    }
9040
9041    #[test]
9042    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9043        // `magi task done` (or the API's equivalent) can close a task with no
9044        // run of its own ever having succeeded - there is nothing here that
9045        // counts as "the attempt that finished it", so nothing is rewritten.
9046        crate::run::pin_test_home();
9047        let mut first = run_state(RunStatus::Blocked);
9048        first.id = "20260101-000000-sup5".to_owned();
9049        first.save().unwrap();
9050
9051        let mut t = task();
9052        t.runs = vec![first.id.clone()];
9053        t.status = TaskStatus::Done;
9054
9055        supersede_prior_runs(&t, &crate::run::home());
9056
9057        assert_eq!(
9058            RunState::load(&first.id).unwrap().status,
9059            RunStatus::Blocked,
9060            "a single-attempt task has no earlier run to supersede"
9061        );
9062    }
9063
9064    #[test]
9065    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9066        // `magi task done` (or the web/conductor equivalents) can close a
9067        // task in any status, including one whose *last* recorded attempt is
9068        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9069        // never watched, say. `runs.last()` being `Done`-adjacent is not
9070        // proof it actually succeeded, so nothing earlier may be relabelled
9071        // on its say-so alone.
9072        crate::run::pin_test_home();
9073        let mut first = run_state(RunStatus::Blocked);
9074        first.id = "20260101-000000-supb".to_owned();
9075        first.save().unwrap();
9076        let mut second = run_state(RunStatus::Failed);
9077        second.id = "20260101-000000-supc".to_owned();
9078        second.save().unwrap();
9079
9080        let mut t = task();
9081        t.runs = vec![first.id.clone(), second.id.clone()];
9082        t.status = TaskStatus::Done;
9083
9084        supersede_prior_runs(&t, &crate::run::home());
9085
9086        assert_eq!(
9087            RunState::load(&first.id).unwrap().status,
9088            RunStatus::Blocked,
9089            "the task's last attempt never landed, so there is nothing here \
9090             actually superseding it"
9091        );
9092    }
9093
9094    #[test]
9095    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9096        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9097        // to look" - `Failed` and `VerifiedNoop` are already their own
9098        // terminal answers and must not be relabelled into a third one.
9099        crate::run::pin_test_home();
9100        let mut failed = run_state(RunStatus::Failed);
9101        failed.id = "20260101-000000-sup6".to_owned();
9102        failed.save().unwrap();
9103        let mut noop = run_state(RunStatus::VerifiedNoop);
9104        noop.id = "20260101-000000-sup7".to_owned();
9105        noop.save().unwrap();
9106        let mut winner = run_state(RunStatus::Ready);
9107        winner.id = "20260101-000000-sup8".to_owned();
9108        winner.save().unwrap();
9109
9110        let mut t = task();
9111        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9112        t.status = TaskStatus::Done;
9113
9114        supersede_prior_runs(&t, &crate::run::home());
9115
9116        assert_eq!(
9117            RunState::load(&failed.id).unwrap().status,
9118            RunStatus::Failed
9119        );
9120        assert_eq!(
9121            RunState::load(&noop.id).unwrap().status,
9122            RunStatus::VerifiedNoop
9123        );
9124    }
9125
9126    fn approval_question(run: &str) -> ask::Question {
9127        ask::Question::new(
9128            run.to_owned(),
9129            land::APPROVAL_NODE.to_owned(),
9130            "land".to_owned(),
9131            "merge?".to_owned(),
9132            String::new(),
9133            vec!["merge".to_owned(), "hold".to_owned()],
9134        )
9135    }
9136
9137    #[test]
9138    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9139        crate::run::pin_test_home();
9140        let mut state = run_state(RunStatus::Landing);
9141        state.id = "20260101-000000-fre1".to_owned();
9142        state.parked = true;
9143        state.save().unwrap();
9144        ask::Questions::open()
9145            .put(&mut approval_question(&state.id))
9146            .unwrap();
9147
9148        let mut t = task();
9149        t.runs.push(state.id.clone());
9150        assert_eq!(
9151            land_resume_state(&t),
9152            LandResume::StillWaiting,
9153            "nobody has answered and the timeout has not passed"
9154        );
9155    }
9156
9157    #[test]
9158    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9159        crate::run::pin_test_home();
9160        let mut state = run_state(RunStatus::Gating);
9161        state.id = "20260101-000000-gt01".to_owned();
9162        state.parked = true;
9163        state.config.graph.answer_timeout = 60;
9164        state.github_text = Some(crate::run::GithubTextAsk {
9165            rewrite: None,
9166            fingerprint: "f".into(),
9167            title: true,
9168            body: false,
9169            categories: vec!["title-language".into()],
9170            question: None,
9171            asks: 1,
9172            resolved: false,
9173            chosen_title: None,
9174            choice: None,
9175        });
9176        state.save().unwrap();
9177        let store = ask::Questions::open();
9178        let mut q = ask::Question::new(
9179            state.id.clone(),
9180            crate::github_text::ASK_NODE.to_owned(),
9181            crate::github_text::ASK_SEAT.to_owned(),
9182            "s".into(),
9183            String::new(),
9184            vec!["use fallback".into()],
9185        );
9186        store.put(&mut q).unwrap();
9187        let mut t = task();
9188        t.runs.push(state.id.clone());
9189        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9190        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9191        store.put(&mut q).unwrap();
9192        assert_eq!(land_resume_state(&t), LandResume::Ready);
9193        assert!(!store.get(&q.id).unwrap().status.open());
9194        // Once decided, a parked run is an ordinary candidate again.
9195        state.github_text.as_mut().unwrap().resolved = true;
9196        state.save().unwrap();
9197        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9198    }
9199
9200    #[test]
9201    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9202        // `ask::ask_and_wait`'s own deadline used to retire a question
9203        // nobody answered; land's approval bypasses that wait (see
9204        // `land::approval_gate`), so this is now the only place
9205        // `graph.answer_timeout` is enforced for a land approval at all.
9206        crate::run::pin_test_home();
9207        let mut state = run_state(RunStatus::Landing);
9208        state.id = "20260101-000000-exp1".to_owned();
9209        state.parked = true;
9210        state.config.graph.answer_timeout = 60;
9211        state.save().unwrap();
9212
9213        let store = ask::Questions::open();
9214        let mut q = approval_question(&state.id);
9215        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9216        store.put(&mut q).unwrap();
9217
9218        let mut t = task();
9219        t.runs.push(state.id.clone());
9220        assert_eq!(
9221            land_resume_state(&t),
9222            LandResume::Ready,
9223            "an expired question must not be waited on forever"
9224        );
9225
9226        let after = store.get(&q.id).unwrap();
9227        assert!(
9228            !after.status.open(),
9229            "the question is abandoned, not silently ignored"
9230        );
9231        assert!(
9232            after.resolution().is_none(),
9233            "an abandoned question is not read as a decision"
9234        );
9235    }
9236
9237    #[test]
9238    fn reclaim_settles_a_running_task_against_its_last_run() {
9239        let mut t = task();
9240        t.start("20260904-000000-4043".to_owned());
9241        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9242        assert_eq!(
9243            t.status,
9244            TaskStatus::Done,
9245            "a run that actually finished must not stay `running` forever"
9246        );
9247    }
9248
9249    #[test]
9250    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9251        let mut t = task();
9252        t.start("20260904-000000-4043".to_owned());
9253        t.last_error = Some("earlier trouble".to_owned());
9254        let mut state = run_state(RunStatus::Judging);
9255        state.parked = true;
9256        reclaim(&mut t, Some(state), 1, "en");
9257        assert_eq!(t.status, TaskStatus::Parked);
9258        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9259        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9260        assert!(t.park_reason.is_some());
9261        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9262        assert!(!t.fresh_start);
9263        assert!(t.status.runnable());
9264    }
9265
9266    #[test]
9267    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9268        let mut t = task();
9269        t.start("20260904-000000-4043".to_owned());
9270        t.last_error = Some("earlier trouble".to_owned());
9271        settle(
9272            &mut t,
9273            Verdict {
9274                status: RunStatus::Judging,
9275                left_pr: false,
9276                quota_hit: false,
9277                parked: true,
9278                no_viable_candidates: false,
9279            },
9280            "parked after `judging`",
9281            1,
9282        );
9283        assert_eq!(t.status, TaskStatus::Parked);
9284        assert_eq!(t.attempts, 0);
9285        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9286        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9287        assert_eq!(t.schema, crate::queue::SCHEMA);
9288        assert!(
9289            crate::notices::task_held(&t).is_none(),
9290            "a park is not news"
9291        );
9292        t.start("20260904-000000-4043".to_owned());
9293        assert_eq!(t.park_reason, None);
9294    }
9295
9296    #[test]
9297    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9298        // A blocked run with attempts left goes back to `Failed`, exactly as
9299        // it would from `attempt` itself - `reclaim` must not invent a second
9300        // policy for a task a daemon merely stopped without reporting.
9301        let mut t = task();
9302        t.start("20260904-000000-4043".to_owned());
9303        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9304        assert_eq!(t.status, TaskStatus::Failed);
9305        assert!(t.status.runnable());
9306    }
9307
9308    #[test]
9309    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9310        let mut t = task();
9311        t.start("20260904-000000-4043".to_owned());
9312        assert_eq!(t.attempts, 1);
9313        let mut run = run_state(RunStatus::Implementing);
9314        run.id = "20260904-000000-4043".to_owned();
9315        run.begin_pass();
9316        let cause = crate::run::ParkCause::Upgrade {
9317            from: "0.121.0".to_owned(),
9318            to: Some("0.121.1".to_owned()),
9319        };
9320        run.end_pass_parked(cause.clone());
9321        run.parked = true;
9322        let verdict = Verdict {
9323            status: run.status,
9324            left_pr: false,
9325            quota_hit: false,
9326            parked: true,
9327            no_viable_candidates: false,
9328        };
9329        // A crash after the checkpoint but before queue settlement must
9330        // recover exactly the same scheduling evidence and refund.
9331        let mut orphan = t.clone();
9332        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9333        assert_eq!(orphan.status, TaskStatus::Parked);
9334        assert_eq!(orphan.attempts, 0);
9335        assert_eq!(
9336            orphan.upgrade_resume_key(),
9337            Some((run.passes[0].started_at, orphan.id.as_str()))
9338        );
9339        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9340        assert_eq!(t.attempts, 0);
9341        assert_eq!(t.passes.len(), 1);
9342        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9343        assert_eq!(t.passes[0].parked, Some(cause));
9344        assert_eq!(t.passes[0].pass_index, 0);
9345        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9346        assert!(t.upgrade_resume_key().is_some());
9347
9348        // A resumed pass that then fails spends its attempt, and the earlier
9349        // pass's entry is untouched.
9350        t.start("20260904-000000-4043".to_owned());
9351        run.begin_pass();
9352        run.status = RunStatus::Failed;
9353        let verdict = Verdict {
9354            status: RunStatus::Failed,
9355            left_pr: false,
9356            quota_hit: false,
9357            parked: false,
9358            no_viable_candidates: false,
9359        };
9360        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9361        assert_eq!(t.passes.len(), 2);
9362        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9363        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9364        assert_eq!(t.passes[1].pass_index, 1);
9365        assert_eq!(t.attempts, 1);
9366    }
9367
9368    #[test]
9369    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9370        let mut t = task();
9371        t.start("20260904-000000-4043".to_owned());
9372        reclaim(&mut t, None, 2, "en");
9373        assert_eq!(t.status, TaskStatus::Held);
9374        assert!(
9375            t.last_error
9376                .as_deref()
9377                .is_some_and(|e| e.contains("running")),
9378            "the operator needs to know why this task was held"
9379        );
9380    }
9381
9382    #[test]
9383    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9384        let dir = tempfile::tempdir().unwrap();
9385        let queue = Queue::at(dir.path().to_path_buf());
9386
9387        // No run recorded, so this never has to touch `RunState::load`.
9388        let mut orphaned = task();
9389        orphaned.id = "20260904-000000-orph".to_owned();
9390        orphaned.status = TaskStatus::Running;
9391        orphaned.attempts = 1;
9392        queue.put(&mut orphaned).unwrap();
9393
9394        let mut alive = task();
9395        alive.id = "20260904-000000-live".to_owned();
9396        alive.status = TaskStatus::Running;
9397        alive.attempts = 1;
9398        queue.put(&mut alive).unwrap();
9399        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9400
9401        let mut queued = task();
9402        queued.id = "20260904-000000-wait".to_owned();
9403        queue.put(&mut queued).unwrap();
9404
9405        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9406        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9407
9408        assert_eq!(
9409            queue.get(&orphaned.id).unwrap().status,
9410            TaskStatus::Held,
9411            "nothing was driving it and there was no run to recover"
9412        );
9413        assert_eq!(
9414            queue.get(&alive.id).unwrap().status,
9415            TaskStatus::Running,
9416            "a live claim must protect the task it belongs to"
9417        );
9418        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9419    }
9420
9421    /// Read a run.json back from an explicit `home`, the same way
9422    /// `reclaim_abandoned_runs` itself does - never through the
9423    /// process-global `RunState::load`, which this test's own `home` (an
9424    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9425    /// use at all.
9426    fn read_run_under(home: &Path, id: &str) -> RunState {
9427        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9428        serde_json::from_str(&body).unwrap()
9429    }
9430
9431    #[test]
9432    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9433        let dir = tempfile::tempdir().unwrap();
9434        let home = dir.path().to_path_buf();
9435        let now = Timestamp::now();
9436        let overrun_seat = || crate::run::ActiveSeat {
9437            node: "implement".to_owned(),
9438            started_at: now - jiff::SignedDuration::new(21_000, 0),
9439            timeout_secs: 3_600,
9440            attempt: 0,
9441            task: None,
9442            command: None,
9443            index: None,
9444            total: None,
9445        };
9446
9447        let mut dead = run_state(RunStatus::Implementing);
9448        dead.id = "20260101-000000-dead".to_owned();
9449        dead.active.insert("impl-A".to_owned(), overrun_seat());
9450        // A `driver_pid` the injected query below confirms gone outright —
9451        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9452        dead.driver_pid = Some(4242);
9453        dead.save_under(&home).unwrap();
9454
9455        // Same shape, but a live daemon's heartbeat names it: must be left
9456        // exactly alone, however far past its own timeout the seat sits.
9457        let mut alive = run_state(RunStatus::Implementing);
9458        alive.id = "20260101-000000-aliv".to_owned();
9459        alive.active.insert("impl-A".to_owned(), overrun_seat());
9460        alive.save_under(&home).unwrap();
9461        let mut status = Status::new();
9462        status.current = vec![Current {
9463            worker: None,
9464            task: "20260101-000000-task".to_owned(),
9465            run: alive.id.clone(),
9466        }];
9467        write_status_to(&home.join("daemon.json"), &status).unwrap();
9468
9469        // The abandoned seat left an open question behind: nobody is left to
9470        // read an answer once the run is failed, and this must not wait for
9471        // some later daemon startup's own sweep to notice that.
9472        let questions = Questions::at(home.join("questions"));
9473        let mut q = ask::Question::new(
9474            dead.id.clone(),
9475            "implement".to_owned(),
9476            "impl-A".to_owned(),
9477            "Which storage backend?".to_owned(),
9478            String::new(),
9479            vec!["SQLite".to_owned(), "Redis".to_owned()],
9480        );
9481        questions.put(&mut q).unwrap();
9482
9483        let abandoned = reclaim_abandoned_runs_with(
9484            &home,
9485            now,
9486            |pid| if pid == 4242 { Some(false) } else { None },
9487            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9488        );
9489        assert_eq!(abandoned, vec![dead.id.clone()]);
9490
9491        let reloaded = read_run_under(&home, &dead.id);
9492        assert_eq!(reloaded.status, RunStatus::Failed);
9493        assert!(reloaded.active.is_empty());
9494        assert!(
9495            !questions.get(&q.id).unwrap().status.open(),
9496            "the failed run's own open question must be settled in the same pass"
9497        );
9498
9499        let still_alive = read_run_under(&home, &alive.id);
9500        assert_eq!(
9501            still_alive.status,
9502            RunStatus::Implementing,
9503            "a live daemon's claim protects it"
9504        );
9505        assert!(!still_alive.active.is_empty());
9506    }
9507
9508    /// The exact shape a review round flagged as broken: `magi serve` running
9509    /// in this same `home` scans *every* run on disk, including a manual
9510    /// `magi review` / `magi run` this daemon never started and that
9511    /// therefore claims no heartbeat of its own. Before this scan asked
9512    /// `liveness` rather than just `is_working_on`, a manual run whose active
9513    /// seat merely ran a little past its own timeout — the CLI finishing up,
9514    /// its result still being collected — got wiped and failed by a daemon
9515    /// that had nothing to do with it, out from under a process that was
9516    /// still very much running.
9517    #[test]
9518    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9519        let dir = tempfile::tempdir().unwrap();
9520        let home = dir.path().to_path_buf();
9521        let now = Timestamp::now();
9522
9523        let mut manual = run_state(RunStatus::Reviewing);
9524        manual.id = "20260101-000000-manl".to_owned();
9525        manual.active.insert(
9526            "review-1".to_owned(),
9527            crate::run::ActiveSeat {
9528                node: "review".to_owned(),
9529                started_at: now - jiff::SignedDuration::new(21_000, 0),
9530                timeout_secs: 3_600,
9531                attempt: 0,
9532                task: None,
9533                command: None,
9534                index: None,
9535                total: None,
9536            },
9537        );
9538        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9539        // but a real, still-running process: `liveness` must corroborate this
9540        // as `Live`, not read the missing daemon claim as death.
9541        manual.driver_pid = Some(4242);
9542        manual.driver_started_at = Some("1790000000".to_owned());
9543        manual.save_under(&home).unwrap();
9544
9545        let abandoned = reclaim_abandoned_runs_with(
9546            &home,
9547            now,
9548            |pid| if pid == 4242 { Some(true) } else { None },
9549            |pid| {
9550                if pid == 4242 {
9551                    Some("1790000000".to_owned())
9552                } else {
9553                    None
9554                }
9555            },
9556        );
9557        assert!(
9558            abandoned.is_empty(),
9559            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9560        );
9561
9562        let reloaded = read_run_under(&home, &manual.id);
9563        assert_eq!(reloaded.status, RunStatus::Reviewing);
9564        assert!(!reloaded.active.is_empty());
9565    }
9566
9567    #[test]
9568    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9569        let dir = tempfile::tempdir().unwrap();
9570        let queue = Queue::at(dir.path().to_path_buf());
9571        let mut only = task();
9572        queue.put(&mut only).unwrap();
9573
9574        let _elsewhere = queue.claim(&only.id).unwrap();
9575        let candidates = runnable(&queue);
9576        assert_eq!(candidates.len(), 1, "the task is still runnable");
9577        assert!(
9578            queue.claim(&candidates[0].id).is_err(),
9579            "the loop cannot take a claim somebody else holds"
9580        );
9581
9582        let after = queue.get(&only.id).unwrap();
9583        assert_eq!(after.status, TaskStatus::Queued);
9584        assert_eq!(
9585            after.attempts, 0,
9586            "losing the race is not an attempt at the task"
9587        );
9588        assert_eq!(after.last_error, None);
9589    }
9590
9591    #[test]
9592    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9593        let dir = tempfile::tempdir().unwrap();
9594        let path = dir.path().join("daemon.json");
9595
9596        let mut status = Status::new();
9597        status.idle = false;
9598        status.completed = 7;
9599        status.current = vec![Current {
9600            worker: None,
9601            task: "20260902-000000-t111".to_owned(),
9602            run: "20260902-000001-r111".to_owned(),
9603        }];
9604        write_status_to(&path, &status).unwrap();
9605        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9606        assert_eq!(first.schema, SCHEMA);
9607        assert_eq!(first.pid, std::process::id());
9608        assert!(!first.idle);
9609        assert_eq!(first.completed, 7);
9610        assert_eq!(first.current, status.current);
9611        assert!(
9612            !path.with_extension("json.tmp").exists(),
9613            "the temp file is renamed, not left behind"
9614        );
9615
9616        std::thread::sleep(Duration::from_millis(5));
9617        status.updated_at = Timestamp::now();
9618        status.polls = 3;
9619        write_status_to(&path, &status).unwrap();
9620        let second: Status =
9621            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9622        assert!(
9623            second.updated_at > first.updated_at,
9624            "a reader can only detect staleness if the heartbeat moves"
9625        );
9626        assert_eq!(
9627            second.started_at, first.started_at,
9628            "the start time is not a heartbeat"
9629        );
9630        assert_eq!(second.polls, 3);
9631    }
9632
9633    #[test]
9634    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9635        let dir = tempfile::tempdir().unwrap();
9636
9637        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9638
9639        let mut status = Status::new();
9640        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9641        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9642        let stale = read_status(dir.path()).unwrap();
9643        assert!(
9644            !stale.running(Timestamp::now()),
9645            "a minute without a heartbeat is a dead daemon, not a busy one"
9646        );
9647        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9648
9649        status.updated_at = Timestamp::now();
9650        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9651        let fresh = read_status(dir.path()).unwrap();
9652        assert!(fresh.running(Timestamp::now()));
9653    }
9654
9655    #[test]
9656    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9657        let dir = tempfile::tempdir().unwrap();
9658        let now = Timestamp::now();
9659        let mine = "20260903-080619-01c2";
9660
9661        assert!(
9662            !is_working_on(dir.path(), mine, now),
9663            "no status file means nobody is working on anything"
9664        );
9665
9666        let mut status = Status::new();
9667        status.current = vec![Current {
9668            worker: None,
9669            task: "20260903-080340-0167".to_owned(),
9670            run: mine.to_owned(),
9671        }];
9672        status.updated_at = now;
9673        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9674        assert!(is_working_on(dir.path(), mine, now));
9675        assert!(
9676            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9677            "a daemon busy with one run is not working on another"
9678        );
9679
9680        // A killed daemon stops writing heartbeats but leaves the file behind
9681        // naming the run it died in. That run must not be undeletable forever.
9682        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9683        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9684        assert!(
9685            !is_working_on(dir.path(), mine, now),
9686            "a stale heartbeat is a dead daemon, so its run is a leftover"
9687        );
9688    }
9689
9690    #[test]
9691    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9692        let dir = tempfile::tempdir().unwrap();
9693        let now = Timestamp::now();
9694
9695        assert!(
9696            !is_working_on_short(dir.path(), "01c2", now),
9697            "no status file means nobody is working on anything"
9698        );
9699
9700        let mut status = Status::new();
9701        status.current = vec![Current {
9702            worker: None,
9703            task: "20260903-080340-0167".to_owned(),
9704            run: "20260903-080619-01c2".to_owned(),
9705        }];
9706        status.updated_at = now;
9707        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9708        assert!(
9709            is_working_on_short(dir.path(), "01c2", now),
9710            "the run's short id is the last block of its full id"
9711        );
9712        assert!(
9713            !is_working_on_short(dir.path(), "3cbf", now),
9714            "a daemon busy with one worktree bay is not working on another"
9715        );
9716    }
9717
9718    #[test]
9719    fn a_newer_status_file_still_yields_a_reading() {
9720        let dir = tempfile::tempdir().unwrap();
9721        // A field this build has never heard of must not turn the reading into
9722        // nothing at all; that is the whole reason the reader is permissive.
9723        std::fs::write(
9724            dir.path().join("daemon.json"),
9725            serde_json::json!({
9726                "schema": 2,
9727                "updated_at": Timestamp::now().to_string(),
9728                "idle": true,
9729                "surprise": { "nested": [1, 2, 3] },
9730            })
9731            .to_string(),
9732        )
9733        .unwrap();
9734
9735        let reading = read_status(dir.path()).expect("a forward-compatible read");
9736        assert!(reading.running(Timestamp::now()));
9737        assert!(reading.idle);
9738        assert!(reading.current.is_empty());
9739    }
9740
9741    #[test]
9742    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9743        // A daemon started before `current` became a list keeps writing this
9744        // shape on every heartbeat until it is restarted. A rolling upgrade
9745        // - a newer `magi web` or `magi doctor` reading an older `magi
9746        // serve`'s heartbeat - must still see the run it is on, not "no
9747        // daemon" from a type mismatch failing the whole struct.
9748        let dir = tempfile::tempdir().unwrap();
9749        std::fs::write(
9750            dir.path().join("daemon.json"),
9751            serde_json::json!({
9752                "schema": 1,
9753                "pid": 4242,
9754                "updated_at": Timestamp::now().to_string(),
9755                "idle": false,
9756                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9757                "completed": 3,
9758                "polls": 9,
9759            })
9760            .to_string(),
9761        )
9762        .unwrap();
9763
9764        let reading = read_status(dir.path()).expect("an older shape must still parse");
9765        assert!(reading.running(Timestamp::now()));
9766        assert_eq!(
9767            reading.current,
9768            vec![Current {
9769                worker: None,
9770                task: "20260902-140501-aaaa".to_owned(),
9771                run: "20260902-140502-bbbb".to_owned(),
9772            }]
9773        );
9774    }
9775
9776    #[test]
9777    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9778        let dir = tempfile::tempdir().unwrap();
9779        std::fs::write(
9780            dir.path().join("daemon.json"),
9781            serde_json::json!({
9782                "schema": 1,
9783                "updated_at": Timestamp::now().to_string(),
9784                "idle": true,
9785                "current": null,
9786            })
9787            .to_string(),
9788        )
9789        .unwrap();
9790        let with_null = read_status(dir.path()).expect("null must still parse");
9791        assert!(with_null.current.is_empty());
9792
9793        std::fs::write(
9794            dir.path().join("daemon.json"),
9795            serde_json::json!({
9796                "schema": 1,
9797                "updated_at": Timestamp::now().to_string(),
9798                "idle": true,
9799            })
9800            .to_string(),
9801        )
9802        .unwrap();
9803        let absent = read_status(dir.path()).expect("a missing field must still parse");
9804        assert!(absent.current.is_empty());
9805    }
9806
9807    #[test]
9808    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9809        let fallback = Path::new("/default");
9810        let mut blank = task();
9811        blank.repo = PathBuf::new();
9812        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9813        let mut dot = task();
9814        dot.repo = PathBuf::from(".");
9815        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9816        assert_eq!(
9817            repo_for(&task(), fallback),
9818            PathBuf::from("/repo"),
9819            "a task that names a repository keeps it"
9820        );
9821    }
9822
9823    #[test]
9824    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9825        let dir = tempfile::tempdir().unwrap();
9826        let path = dir.path().join("explicit.toml");
9827        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9828        let opts = Opts {
9829            config: Some(path),
9830            merge: Some("none".into()),
9831            ..Default::default()
9832        };
9833        let mut t = task();
9834        t.set_implementers(
9835            2,
9836            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9837                .unwrap(),
9838        )
9839        .unwrap();
9840        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9841        assert_eq!(cfg.graph.implementers, 2);
9842        assert_eq!(cfg.graph.judges, 1);
9843        assert_eq!(cfg.merge.mode, MergeMode::None);
9844        t.set_implementers(1, &cfg).unwrap();
9845        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9846        apply_task_implementers(&mut cfg, &t);
9847        assert_eq!(cfg.graph.implementers, 1);
9848        assert_eq!(cfg.graph.judges, 1);
9849        assert_eq!(cfg.merge.mode, MergeMode::None);
9850    }
9851
9852    #[test]
9853    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9854        let dir = tempfile::tempdir().unwrap();
9855        let repo = dir.path().join("repo");
9856        std::fs::create_dir(&repo).unwrap();
9857        std::fs::write(
9858            repo.join("magi.toml"),
9859            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9860        )
9861        .unwrap();
9862        let daemon_config = dir.path().join("daemon.toml");
9863        std::fs::write(
9864            &daemon_config,
9865            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9866        )
9867        .unwrap();
9868        let opts = Opts {
9869            config: Some(daemon_config),
9870            merge: Some("pr".into()),
9871            ..Default::default()
9872        };
9873        let q = Queue::at(dir.path().join("queue"));
9874        let validation: Config =
9875            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9876                .unwrap();
9877        // No provenance field on legacy direct tasks: both shapes stay isolated.
9878        for record in ["{}", r#"{"candidates":2}"#] {
9879            let overrides = serde_json::from_str(record).unwrap();
9880            let filing = crate::direct::Filing {
9881                instruction: "work".into(),
9882                title: "direct".into(),
9883                repo: repo.clone(),
9884                source: crate::queue::Source::Human,
9885                solo: false,
9886                overrides,
9887                review_of: None,
9888                sources: Default::default(),
9889            };
9890            let filed =
9891                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9892            let crate::direct::Filed::Standalone {
9893                mut task,
9894                claim: _claim,
9895            } = filed
9896            else {
9897                panic!("local filing")
9898            };
9899            let before = prepare_for(&repo, &opts, &task).unwrap();
9900            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9901            assert_eq!(
9902                before.merge.mode,
9903                MergeMode::None,
9904                "daemon --merge must not leak"
9905            );
9906            for n in [2, 1, 2] {
9907                task.set_implementers(n, &validation).unwrap();
9908                q.put(&mut task).unwrap();
9909                task = q.get(&task.id).unwrap();
9910                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9911                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9912                apply_task_implementers(&mut cfg, &task);
9913                assert_eq!(cfg.graph.implementers, usize::from(n));
9914                assert_eq!(cfg.graph.judges, 2);
9915                assert_eq!(cfg.merge.mode, MergeMode::None);
9916            }
9917        }
9918    }
9919
9920    #[test]
9921    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9922        let cfg: Config =
9923            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9924                .unwrap();
9925        let mut t = task();
9926        t.review_of = Some("review-target".into());
9927        t.hold_manual(Some("retry".into()));
9928        let mut previous = RunState::new(
9929            PathBuf::from("/repo"),
9930            "main".into(),
9931            "abc1234".into(),
9932            "review".into(),
9933            cfg.clone(),
9934        );
9935        previous.config.graph.implementers = 2;
9936        for count in [1, 3] {
9937            t.set_implementers(count, &cfg).unwrap();
9938            t.release();
9939            assert_eq!(t.review_of.as_deref(), Some("review-target"));
9940            for proposed in [
9941                Starter::Resume(previous.id.clone()),
9942                Starter::Review("recovery-target".into()),
9943            ] {
9944                assert_eq!(
9945                    starter_with_implementers(&t, Some(&previous), proposed),
9946                    Starter::Review("review-target".into())
9947                );
9948            }
9949            let mut configured = cfg.clone();
9950            apply_task_implementers(&mut configured, &t);
9951            assert_eq!(configured.graph.implementers, usize::from(count));
9952            assert_eq!(previous.config.graph.implementers, 2);
9953        }
9954    }
9955
9956    #[test]
9957    fn task_implementers_dispatch_and_resume_agree() {
9958        let mut t = task();
9959        let cfg: crate::config::Config =
9960            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9961                .unwrap();
9962        let mut run = RunState::new(
9963            PathBuf::from("/repo"),
9964            "main".into(),
9965            "abc1234".into(),
9966            "work".into(),
9967            cfg.clone(),
9968        );
9969        run.config.graph.implementers = 2;
9970        for n in [2, 1, 3, 2] {
9971            t.set_implementers(n, &cfg).unwrap();
9972            let mut dispatched = cfg.clone();
9973            apply_task_implementers(&mut dispatched, &t);
9974            assert_eq!(dispatched.graph.implementers, usize::from(n));
9975            assert_eq!(implementers_match(&t, &run), n == 2);
9976            for proposed in [
9977                Starter::Resume(run.id.clone()),
9978                Starter::Review("old-branch".into()),
9979            ] {
9980                let expected = if n == 2 {
9981                    proposed.clone()
9982                } else {
9983                    Starter::Start
9984                };
9985                assert_eq!(
9986                    starter_with_implementers(&t, Some(&run), proposed),
9987                    expected
9988                );
9989            }
9990            assert_eq!(
9991                run.config.graph.implementers, 2,
9992                "history must not be rewritten"
9993            );
9994        }
9995        t.solo = false;
9996        t.overrides = None;
9997        assert!(implementers_match(&t, &run));
9998    }
9999
10000    #[test]
10001    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10002        // Three seats said out loud. What `solo` promises is one candidate
10003        // *whatever the config asks for*, so the contrast has to be a number
10004        // this test owns - it used to be `Config::default()`'s, which became
10005        // 1 when one implementation became the default and left the two
10006        // halves of this test asserting the same thing.
10007        let mut solo_cfg = Config::default();
10008        solo_cfg.graph.implementers = 3;
10009        let mut solo_task = task();
10010        solo_task.solo = true;
10011        apply_task_implementers(&mut solo_cfg, &solo_task);
10012        assert_eq!(solo_cfg.graph.implementers, 1);
10013
10014        let mut plain_cfg = Config::default();
10015        plain_cfg.graph.implementers = 3;
10016        let plain_task = task();
10017        assert!(!plain_task.solo);
10018        apply_task_implementers(&mut plain_cfg, &plain_task);
10019        assert_eq!(
10020            plain_cfg.graph.implementers, 3,
10021            "a task that did not ask to run alone keeps the config's candidates"
10022        );
10023    }
10024
10025    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10026        QuotaLoss {
10027            cause: crate::agent::QuotaCause::UsageLimit,
10028            agent: String::new(),
10029            seat: seat.into(),
10030            node: "judge".into(),
10031            at: at.parse().unwrap(),
10032            reset: reset.map(str::to_string),
10033        }
10034    }
10035
10036    #[test]
10037    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10038        let now = Timestamp::now();
10039        for reset in [None, Some("in 1h")] {
10040            let auth = crate::agent::Quota {
10041                cause: crate::agent::QuotaCause::Authentication,
10042                agent: "alpha".into(),
10043                reset: reset.map(str::to_owned),
10044            };
10045            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10046            assert_eq!(cooldown_until(&[loss], now), None);
10047        }
10048    }
10049
10050    #[test]
10051    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10052        let old: Vec<QuotaLoss> = (1..=4)
10053            .map(|i| {
10054                loss(
10055                    &format!("judge-{i}"),
10056                    "2026-09-23T05:23:00Z",
10057                    Some("2:40pm (Asia/Tokyo)"),
10058                )
10059            })
10060            .collect();
10061        let fresh = losses_this_attempt(&old, &old);
10062        assert!(fresh.is_empty());
10063        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10064        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10065    }
10066
10067    #[test]
10068    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10069        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10070        let now = Timestamp::now();
10071        let mut after = old.clone();
10072        after.push(loss("judge-2", &now.to_string(), None));
10073        let fresh = losses_this_attempt(&old, &after);
10074        assert_eq!(fresh, vec![after[1].clone()]);
10075        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10076        assert_eq!(
10077            until,
10078            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10079        );
10080    }
10081
10082    #[test]
10083    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10084        // `recover_stall` removes judge-1's loss and the retry then hits quota
10085        // again: the vector is the same length, so an index diff sees nothing.
10086        let before = vec![
10087            loss("judge-1", "2026-09-23T05:23:00Z", None),
10088            loss("judge-2", "2026-09-23T05:24:00Z", None),
10089        ];
10090        let after = vec![
10091            loss("judge-2", "2026-09-23T05:24:00Z", None),
10092            loss("judge-1", "2026-09-24T01:00:00Z", None),
10093        ];
10094        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10095    }
10096
10097    #[test]
10098    fn merge_overrides_are_parsed_or_refused() {
10099        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10100        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10101        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10102        assert!(merge_mode("squash").is_err());
10103    }
10104
10105    #[test]
10106    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10107        let now = Timestamp::now();
10108        let fallback = Duration::from_secs(300);
10109        let cap = Duration::from_secs(1800);
10110
10111        // No reset hint at all: the fallback.
10112        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10113
10114        // A reset ten minutes out, well inside the cap: waited for exactly.
10115        let soon = now + jiff::SignedDuration::from_secs(600);
10116        assert_eq!(
10117            quota_wait(Some(soon), now, fallback, cap),
10118            Duration::from_secs(600)
10119        );
10120
10121        // A reset already in the past is not trusted: the fallback, not a
10122        // zero or negative wait that would spin the loop right back around.
10123        let past = now - jiff::SignedDuration::from_secs(60);
10124        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10125
10126        // A reset further out than the cap is trusted for direction but not
10127        // for magnitude: a parsing slip must not sleep the loop for a day.
10128        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10129        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10130    }
10131
10132    #[test]
10133    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10134        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10135
10136        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10137        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10138
10139        // Same clock reading, but it has already gone by today: read as
10140        // tomorrow's, since the CLI would not still be reporting a limit past
10141        // its own stated reset.
10142        let already_past =
10143            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10144        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10145
10146        assert!(
10147            parse_reset_hint("session limit reached", now, now).is_none(),
10148            "free text with no recognised shape is not guessed at"
10149        );
10150        assert!(
10151            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10152            "an unresolvable zone name is not guessed at either"
10153        );
10154    }
10155
10156    #[test]
10157    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10158        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10159
10160        let at = parse_reset_hint(
10161            "You've hit your usage limit. Visit \
10162             https://chatgpt.com/codex/settings/usage to purchase more \
10163             credits or try again at Sep 19th, 2026 5:10 PM.",
10164            now,
10165            now,
10166        )
10167        .expect("the codex reset wording is a recognised shape");
10168        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10169
10170        // The month is explicit, so a date already earlier in the same
10171        // sentence-implied year than `now` is trusted as written rather than
10172        // rolled forward a year the way the bracketed shape rolls a
10173        // same-day clock reading to tomorrow.
10174        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10175            .expect("an explicit year needs no rollover");
10176        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10177
10178        assert!(
10179            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10180            "a two-digit year is not the documented shape and is not guessed at"
10181        );
10182        assert!(
10183            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10184            "a four-letter month name is not the documented three-letter abbreviation"
10185        );
10186        assert!(
10187            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10188            "an explicit zone on the dated shape is a format nobody has \
10189             documented, and is refused rather than guessed at as UTC"
10190        );
10191    }
10192
10193    #[test]
10194    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10195        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10196        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10197
10198        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10199        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10200
10201        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10202        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10203
10204        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10205            assert!(
10206                parse_reset_hint(bad, now, recorded).is_none(),
10207                "{bad:?} must not be guessed at"
10208            );
10209        }
10210    }
10211
10212    /// A loop whose queue lives in a temp tree and whose poll interval is far
10213    /// longer than the test's patience, so anything that waits out a poll
10214    /// instead of noticing the stop fails rather than merely being slow.
10215    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10216        let config = dir.join("magi.toml");
10217        std::fs::write(
10218            &config,
10219            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10220        )
10221        .unwrap();
10222        let opts = Opts {
10223            poll: Duration::from_secs(30),
10224            config: Some(config),
10225            // The explicit fixture config keeps startup cleanup from reading
10226            // machine configuration. This fictional repository likewise
10227            // keeps any best-effort git cleanup away from this checkout.
10228            repo: dir.join("repo"),
10229            ..Opts::default()
10230        };
10231        // The status file goes in a directory that does not exist yet, so its
10232        // creation is itself evidence the loop published one. `worktrees`
10233        // must be just as fictional: the janitor reclaims worktrees under it
10234        // for real, and a test that let it fall through to
10235        // `crate::run::default_worktree_root()` would have it reclaim
10236        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10237        // which is exactly what happened before this function took the
10238        // parameter at all.
10239        let home = dir.join("home");
10240        // These control-only fixtures do not launch native workers. Give the
10241        // independently tested maintenance services a fresh cadence receipt.
10242        let stamps = home.join("service-ticks");
10243        std::fs::create_dir_all(&stamps).unwrap();
10244        for service in ["waiter", "deputies", "release-watch"] {
10245            std::fs::write(
10246                stamps.join(service),
10247                Timestamp::now().as_second().to_string(),
10248            )
10249            .unwrap();
10250        }
10251        for operation in [
10252            "conductor",
10253            "maintenance",
10254            "housekeeping",
10255            "disk-pressure",
10256            "cache",
10257            "fetch",
10258        ] {
10259            std::fs::write(
10260                stamps.join(format!("daemon-{operation}")),
10261                serde_json::to_vec(&Timestamp::now()).unwrap(),
10262            )
10263            .unwrap();
10264        }
10265        let worktrees = dir.join("wt");
10266        (
10267            opts,
10268            Queue::at(dir.join("queue")),
10269            home.join("daemon.json"),
10270            home,
10271            worktrees,
10272        )
10273    }
10274
10275    #[test]
10276    fn a_stop_is_idempotent_and_once_set_stays_set() {
10277        let stop = Stop::new();
10278        assert!(!stop.stopped());
10279
10280        stop.stop();
10281        assert!(stop.stopped());
10282        stop.stop();
10283        assert!(stop.stopped(), "a second stop is not a toggle");
10284
10285        let shared = stop.clone();
10286        assert!(
10287            shared.stopped(),
10288            "a clone is the same stop; that is how the loop and its caller share one"
10289        );
10290    }
10291
10292    #[tokio::test]
10293    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10294        for operation in ["conductor", "maintenance", "housekeeping"] {
10295            let dir = tempfile::tempdir().unwrap();
10296            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10297            opts.once = true;
10298            opts.poll = Duration::from_millis(1);
10299            let mut task = task();
10300            task.runs.push("fixture-run".into());
10301            queue.put(&mut task).unwrap();
10302            let claim = queue.claim(&task.id).unwrap();
10303
10304            // Model a live service holding the task's claim across the
10305            // scheduler's dispatch scan. No real subprocess or timed race.
10306            let directory = home.join("workers/jobs/abcdef");
10307            std::fs::create_dir_all(&directory).unwrap();
10308            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10309            crate::pr_head::try_lock_file(&lease).unwrap();
10310            let mut job = crate::worker::Job {
10311                id: "abcdef".into(),
10312                sequence: 1,
10313                kind: "daemon-service".into(),
10314                key: format!("service:daemon-{operation}"),
10315                payload: serde_json::Value::Null,
10316                generation: "fixture".into(),
10317                version: None,
10318                status: crate::worker::Status::Running,
10319                result: None,
10320                pid: Some(std::process::id()),
10321                created_at: Timestamp::now().as_second() as u64,
10322                finished_at: None,
10323            };
10324            let record = directory.join("job.json");
10325            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10326
10327            let status = Arc::new(Mutex::new(Status::new()));
10328            let stop = Stop::new();
10329            let mut drain = Box::pin(poll(
10330                &opts,
10331                &queue,
10332                &status,
10333                &home,
10334                &worktrees,
10335                &stop,
10336                DispatchLimits {
10337                    max_concurrent: 1,
10338                    pause_for_interrupts: false,
10339                    recovery_cfg: None,
10340                },
10341            ));
10342            std::future::poll_fn(|cx| {
10343                use std::future::Future;
10344                assert!(
10345                    drain.as_mut().poll(cx).is_pending(),
10346                    "--once must wait for {operation} to release its queue claim"
10347                );
10348                std::task::Poll::Ready(())
10349            })
10350            .await;
10351            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10352
10353            // An answer arrives while the service still owns the claim. A
10354            // fresh scheduling pass must apply it before declaring idle.
10355            let questions = Questions::at(home.join("questions"));
10356            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10357            questions.put(&mut q).unwrap();
10358            drop(claim);
10359            // Model services that took longer than their cadence, without a
10360            // wall-clock sleep. The final scans must not respawn them even
10361            // though their receipts now permit another periodic invocation.
10362            let expired =
10363                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10364            for service in [operation, "housekeeping"] {
10365                std::fs::write(
10366                    home.join("service-ticks").join(format!("daemon-{service}")),
10367                    &expired,
10368                )
10369                .unwrap();
10370            }
10371            job.status = crate::worker::Status::Finished;
10372            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10373            drop(lease);
10374            tokio::time::timeout(Duration::from_secs(2), drain)
10375                .await
10376                .expect("the settled service must allow the drain to finish")
10377                .unwrap();
10378            let after = queue.get(&task.id).unwrap();
10379            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10380            assert!(after.action_applied(&q.id));
10381            for service in [operation, "housekeeping"] {
10382                assert_eq!(
10383                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10384                        .unwrap(),
10385                    expired,
10386                    "the final once rescan must not restart {service}"
10387                );
10388            }
10389        }
10390    }
10391
10392    #[test]
10393    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10394        let stop = Stop::new();
10395        stop.busy.store(1, Ordering::SeqCst);
10396        assert!(
10397            !stop.finishing(),
10398            "a busy loop nobody has asked to stop is just running"
10399        );
10400
10401        stop.stop();
10402        assert!(
10403            stop.finishing(),
10404            "a stop asked for mid-run has not landed until the run is settled"
10405        );
10406
10407        stop.busy.store(0, Ordering::SeqCst);
10408        assert!(
10409            !stop.finishing(),
10410            "once the run is settled the stop has landed and there is nothing to finish"
10411        );
10412    }
10413
10414    #[test]
10415    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10416        let stop = Stop::new();
10417        stop.busy.store(2, Ordering::SeqCst);
10418        stop.stop();
10419        assert!(stop.finishing(), "two runs still in flight");
10420
10421        stop.busy.store(1, Ordering::SeqCst);
10422        assert!(
10423            stop.finishing(),
10424            "one run finished, but a sibling is still working"
10425        );
10426
10427        stop.busy.store(0, Ordering::SeqCst);
10428        assert!(
10429            !stop.finishing(),
10430            "the last run out is what actually lands the stop"
10431        );
10432    }
10433
10434    #[tokio::test]
10435    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10436        let dir = tempfile::tempdir().unwrap();
10437        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10438        let stop = Stop::new();
10439        stop.stop();
10440
10441        let began = std::time::Instant::now();
10442        tokio::time::timeout(
10443            Duration::from_secs(2),
10444            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10445        )
10446        .await
10447        .expect("a stopped loop must return, not sit out its poll interval")
10448        .expect("the loop's own setup and teardown must not fail");
10449        assert!(
10450            began.elapsed() < opts.poll,
10451            "returned only after {:?}, which is a poll interval, not a stop",
10452            began.elapsed()
10453        );
10454    }
10455
10456    #[tokio::test]
10457    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10458        let dir = tempfile::tempdir().unwrap();
10459        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10460        let stop = Stop::new();
10461
10462        // Asked for after the loop is already parked on its empty queue, which
10463        // is the case an operator tapping stop on a phone actually hits.
10464        let asker = {
10465            let stop = stop.clone();
10466            tokio::spawn(async move {
10467                tokio::time::sleep(Duration::from_millis(20)).await;
10468                stop.stop();
10469            })
10470        };
10471
10472        let began = std::time::Instant::now();
10473        tokio::time::timeout(
10474            Duration::from_secs(2),
10475            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10476        )
10477        .await
10478        .expect("a stop asked for while idle must wake the wait")
10479        .expect("the loop's own setup and teardown must not fail");
10480        asker.await.unwrap();
10481        assert!(
10482            began.elapsed() < opts.poll,
10483            "returned only after {:?}, so the stop waited on the sleep",
10484            began.elapsed()
10485        );
10486    }
10487
10488    #[tokio::test]
10489    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10490        let dir = tempfile::tempdir().unwrap();
10491        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10492        let stop = Stop::new();
10493        stop.stop();
10494
10495        tokio::time::timeout(
10496            Duration::from_secs(2),
10497            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10498        )
10499        .await
10500        .expect("a stopped loop must return")
10501        .expect("the loop's own setup and teardown must not fail");
10502
10503        assert!(
10504            home.is_dir(),
10505            "the loop did publish a status file, so its removal is the teardown and not an absence"
10506        );
10507        assert!(
10508            !status_file.exists(),
10509            "a stopped loop clears its status file"
10510        );
10511        assert!(
10512            read_status(&home).is_none(),
10513            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10514        );
10515    }
10516
10517    #[tokio::test]
10518    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10519        let dir = tempfile::tempdir().unwrap();
10520        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10521
10522        let mut settled = RunState::new(
10523            dir.path().join("repo"),
10524            "main".to_owned(),
10525            "abc1234".to_owned(),
10526            "fixture".to_owned(),
10527            Config::default(),
10528        );
10529        settled.status = RunStatus::Ready;
10530        let run_dir = home.join("runs").join(&settled.id);
10531        std::fs::create_dir_all(&run_dir).unwrap();
10532        std::fs::write(
10533            run_dir.join("run.json"),
10534            serde_json::to_string_pretty(&settled).unwrap(),
10535        )
10536        .unwrap();
10537        let questions = Questions::at(home.join("questions"));
10538        let mut question = ask::Question::new(
10539            settled.id.clone(),
10540            "review".to_owned(),
10541            "reviewer-1".to_owned(),
10542            "Continue?".to_owned(),
10543            String::new(),
10544            Vec::new(),
10545        );
10546        questions.put(&mut question).unwrap();
10547
10548        run_service_worker(
10549            &home,
10550            serde_json::to_value(ServiceWorker {
10551                opts,
10552                queue: queue.root().to_path_buf(),
10553                worktrees_root: worktrees,
10554                operation: "housekeeping".to_owned(),
10555            })
10556            .unwrap(),
10557        )
10558        .await
10559        .unwrap();
10560
10561        assert_eq!(
10562            questions.get(&question.id).unwrap().status,
10563            ask::QuestionStatus::Abandoned,
10564            "the independent housekeeping worker settles ended-run questions"
10565        );
10566    }
10567
10568    #[test]
10569    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10570        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10571
10572        assert!(
10573            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10574            "never checked before: due at once"
10575        );
10576
10577        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10578        assert!(
10579            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10580            "well inside the interval: not due yet"
10581        );
10582
10583        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10584        assert!(
10585            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10586            "exactly at the edge: not yet due, same convention as `clean::due`"
10587        );
10588
10589        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10590        assert!(
10591            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10592            "past the interval: due again"
10593        );
10594    }
10595
10596    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10597    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10598    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10599    /// and the congestion test below both need, and must not drift apart.
10600    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10601        let config = dir.join("magi.toml");
10602        // A literal (single-quoted) TOML string, not a basic one: the cache
10603        // path is a Windows path full of backslashes, and a basic string
10604        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10605        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10606        // `{{ vars.cache }}` rendering documents.
10607        std::fs::write(
10608            &config,
10609            format!(
10610                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10611                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10612                cache_dir.display()
10613            ),
10614        )
10615        .unwrap();
10616        Opts {
10617            config: Some(config),
10618            repo: dir.join("repo"),
10619            ..Opts::default()
10620        }
10621    }
10622
10623    #[tokio::test]
10624    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10625        let dir = tempfile::tempdir().unwrap();
10626        let home = dir.path().join("home");
10627        let cache_dir = dir.path().join("cache");
10628        std::fs::create_dir_all(&cache_dir).unwrap();
10629        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10630        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10631
10632        // Nobody has asked this daemon to stop, which is the ordinary case;
10633        // the skip that a stop buys is asserted by its own test below.
10634        let running = Stop::new();
10635        let mut last_checked = None;
10636        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10637        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10638            .await;
10639        assert_eq!(
10640            crate::disk::dir_size(&cache_dir),
10641            0,
10642            "over the cap on the first check ever: pruned at once, no idle queue required"
10643        );
10644        assert_eq!(last_checked, Some(t0));
10645
10646        // A fresh oversized file lands, but the next check is not due yet.
10647        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10648        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10649        maybe_prune_cache_between_runs(
10650            &opts.repo,
10651            &opts,
10652            &home,
10653            &running,
10654            &mut last_checked,
10655            too_soon,
10656        )
10657        .await;
10658        assert_eq!(
10659            crate::disk::dir_size(&cache_dir),
10660            10,
10661            "too soon since the last check: left alone rather than rescanned every call"
10662        );
10663        assert_eq!(
10664            last_checked,
10665            Some(t0),
10666            "an idle check does not reset the clock"
10667        );
10668
10669        // Once the interval elapses, the same oversized cache is caught again.
10670        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10671        maybe_prune_cache_between_runs(
10672            &opts.repo,
10673            &opts,
10674            &home,
10675            &running,
10676            &mut last_checked,
10677            due_again,
10678        )
10679        .await;
10680        assert_eq!(
10681            crate::disk::dir_size(&cache_dir),
10682            0,
10683            "due again: pruned back under the cap"
10684        );
10685    }
10686
10687    /// A stop must not queue behind housekeeping. The prune below is a
10688    /// synchronous walk of the whole cache with no await point in it, so a
10689    /// loop that entered it could not get back to its own `stopped()` test
10690    /// until the walk finished - and because no run is in flight at this
10691    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10692    /// the stop had already landed. The idle branch has always made this same
10693    /// check before reaching `janitor`; the between-runs path makes it too.
10694    #[tokio::test]
10695    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10696        let dir = tempfile::tempdir().unwrap();
10697        let home = dir.path().join("home");
10698        let cache_dir = dir.path().join("cache");
10699        std::fs::create_dir_all(&cache_dir).unwrap();
10700        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10701        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10702
10703        let stop = Stop::new();
10704        stop.stop();
10705        assert!(
10706            !stop.finishing(),
10707            "no run is in flight at a between-runs boundary, so nothing else \
10708             would tell the operator this stop had not taken effect yet"
10709        );
10710
10711        let mut last_checked = None;
10712        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10713        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10714            .await;
10715        assert_eq!(
10716            crate::disk::dir_size(&cache_dir),
10717            10,
10718            "over its cap, and due for the first check ever, but a stop outranks \
10719             it: the cap is a standing policy the next start measures again"
10720        );
10721        assert_eq!(
10722            last_checked, None,
10723            "a check that never happened must not claim the interval"
10724        );
10725    }
10726
10727    /// A backlog must not starve cache pruning. The finite cache worker runs
10728    /// independently of queue drain and must not consume any task attempts.
10729    #[tokio::test]
10730    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10731        let dir = tempfile::tempdir().unwrap();
10732        let cache_dir = dir.path().join("cache");
10733        std::fs::create_dir_all(&cache_dir).unwrap();
10734        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10735
10736        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10737        opts.poll = Duration::from_millis(20);
10738        opts.max_attempts = 1_000;
10739
10740        let queue = Queue::at(dir.path().join("queue"));
10741        for i in 0..128 {
10742            let mut task = Task::new(
10743                format!("queued work {i}"),
10744                format!("queued work {i}"),
10745                opts.repo.clone(),
10746                Source::Human,
10747            );
10748            queue.put(&mut task).unwrap();
10749        }
10750
10751        let home = dir.path().join("home");
10752        let worktrees = dir.path().join("wt");
10753        run_service_worker(
10754            &home,
10755            serde_json::to_value(ServiceWorker {
10756                opts,
10757                queue: queue.root().to_path_buf(),
10758                worktrees_root: worktrees,
10759                operation: "cache".to_owned(),
10760            })
10761            .unwrap(),
10762        )
10763        .await
10764        .unwrap();
10765        let after = queue.list();
10766        assert_eq!(after.len(), 128);
10767        assert!(
10768            after
10769                .iter()
10770                .all(|task| task.status.runnable() && task.attempts == 0)
10771        );
10772
10773        assert_eq!(
10774            crate::disk::dir_size(&cache_dir),
10775            0,
10776            "an oversized cache must not be left to grow unboundedly just because the \
10777             queue kept the loop busy the whole time"
10778        );
10779    }
10780
10781    #[test]
10782    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10783        let dir = tempfile::tempdir().unwrap();
10784        let queue = Queue::at(dir.path().join("queue"));
10785        let questions = Questions::at(dir.path().join("questions"));
10786        let mut task = task();
10787        queue.put(&mut task).unwrap();
10788
10789        let mut task_question = ask::Question::new(
10790            task.id.clone(),
10791            crate::conduct::NODE.to_owned(),
10792            "conduct".to_owned(),
10793            "Which backend?".to_owned(),
10794            String::new(),
10795            Vec::new(),
10796        );
10797        questions.put(&mut task_question).unwrap();
10798        task.block(vec![task_question.id.clone()], None);
10799        queue.put(&mut task).unwrap();
10800
10801        let mut run_question = ask::Question::new(
10802            "20260101-000000-run1".to_owned(),
10803            "review".to_owned(),
10804            "reviewer-1".to_owned(),
10805            "Run question".to_owned(),
10806            String::new(),
10807            Vec::new(),
10808        );
10809        questions.put(&mut run_question).unwrap();
10810
10811        // A question from another node whose `run` happens to equal this
10812        // task's id — the same field, filled in for an unrelated reason. Only
10813        // `crate::conduct::NODE` questions use `run` as a task id; this one
10814        // must never be touched by this reconciliation, even after release.
10815        let mut coincidental = ask::Question::new(
10816            task.id.clone(),
10817            "review".to_owned(),
10818            "reviewer-1".to_owned(),
10819            "Unrelated review question".to_owned(),
10820            String::new(),
10821            Vec::new(),
10822        );
10823        questions.put(&mut coincidental).unwrap();
10824
10825        reconcile_task_questions(&queue, &questions);
10826        assert!(questions.get(&task_question.id).unwrap().status.open());
10827        assert!(questions.get(&run_question.id).unwrap().status.open());
10828        assert!(questions.get(&coincidental.id).unwrap().status.open());
10829
10830        task.release();
10831        queue.put(&mut task).unwrap();
10832        reconcile_task_questions(&queue, &questions);
10833        assert_eq!(
10834            questions.get(&task_question.id).unwrap().status,
10835            ask::QuestionStatus::Abandoned
10836        );
10837        assert!(
10838            questions.get(&run_question.id).unwrap().status.open(),
10839            "run questions remain the run janitor's responsibility"
10840        );
10841        assert!(
10842            questions.get(&coincidental.id).unwrap().status.open(),
10843            "a non-conductor question must not be abandoned just because its \
10844             run id coincides with a task id"
10845        );
10846    }
10847
10848    #[test]
10849    fn a_freshly_started_running_task_is_never_stalled() {
10850        let dir = tempfile::tempdir().unwrap();
10851        let mut t = task();
10852        t.start("run-1".to_owned());
10853        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10854        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10855        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10856    }
10857
10858    #[test]
10859    fn a_long_running_task_with_no_live_daemon_is_stalled() {
10860        let dir = tempfile::tempdir().unwrap();
10861        let mut t = task();
10862        t.start("run-1".to_owned());
10863        t.updated_at = Timestamp::now()
10864            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10865        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10866        assert_eq!(
10867            stalled_tasks(
10868                &Queue::at(dir.path().join("q")),
10869                dir.path(),
10870                Timestamp::now()
10871            )
10872            .len(),
10873            0,
10874            "the task was never written to this queue"
10875        );
10876    }
10877
10878    #[test]
10879    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10880        let dir = tempfile::tempdir().unwrap();
10881        let mut t = task();
10882        t.id = "20260903-080340-0167".to_owned();
10883        t.start("20260903-080619-01c2".to_owned());
10884        t.updated_at = Timestamp::now()
10885            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10886
10887        let mut status = Status::new();
10888        status.current = vec![Current {
10889            worker: None,
10890            task: t.id.clone(),
10891            run: "20260903-080619-01c2".to_owned(),
10892        }];
10893        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10894
10895        assert!(
10896            !is_stalled(&t, dir.path(), Timestamp::now()),
10897            "a live daemon's own heartbeat rules out stalled, however long the task has run"
10898        );
10899    }
10900
10901    /// Rewrite a task's `updated_at` on disk directly, bypassing
10902    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
10903    /// a fixture look like it has genuinely been `running` for a while.
10904    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10905        let path = queue.path_of(id);
10906        let body = std::fs::read_to_string(&path).unwrap();
10907        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10908        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10909        v["updated_at"] = serde_json::Value::String(old.to_string());
10910        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10911    }
10912
10913    #[test]
10914    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10915        // The realistic `poll()` ordering, not `is_stalled` in isolation:
10916        // `reclaim_orphaned_running` runs first, on every poll, and settles
10917        // any `running` task whose claim it can actually take. For most
10918        // crashes that is immediate - a dead pid is proof enough for
10919        // `sweep_stale_claims` to drop the lock the same tick, and the very
10920        // next claim attempt succeeds. But a lock whose pid cannot be parsed
10921        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
10922        // `sweep_stale_claims`'s own doc), so the lock - and the claim
10923        // failure behind it - can legitimately outlive many polls. This is
10924        // exactly the gap `stalled_tasks` exists to surface well before that
10925        // six-hour sweep would: reclaim leaves the task `running`, and it
10926        // must still reach the conductor as stalled.
10927        let dir = tempfile::tempdir().unwrap();
10928        let queue = Queue::at(dir.path().join("queue"));
10929        let home = dir.path().join("home");
10930
10931        let mut t = task();
10932        t.id = "20260101-000001-lock".to_owned();
10933        t.start("run-1".to_owned());
10934        queue.put(&mut t).unwrap();
10935        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10936        std::fs::write(
10937            dir.path().join("queue").join(format!("{}.lock", t.id)),
10938            "not a pid",
10939        )
10940        .unwrap();
10941
10942        let now = Timestamp::now();
10943        assert!(
10944            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10945            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10946             and reclaim must leave the task alone"
10947        );
10948        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10949
10950        let stalled = stalled_tasks(&queue, &home, now);
10951        assert_eq!(
10952            stalled.len(),
10953            1,
10954            "reclaim's inability to claim it yet must not hide it from the conductor"
10955        );
10956        assert_eq!(stalled[0].id, t.id);
10957    }
10958
10959    #[test]
10960    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10961        let dir = tempfile::tempdir().unwrap();
10962        crate::run::set_home(dir.path().join("run-home"));
10963        let queue = Queue::at(dir.path().join("queue"));
10964        let home = dir.path().join("home");
10965        let questions = Questions::at(dir.path().join("questions"));
10966
10967        let mut t = task();
10968        t.id = "20260101-000003-dead".to_owned();
10969        t.start("missing-run".to_owned());
10970        queue.put(&mut t).unwrap();
10971        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10972
10973        // This is the real poll ordering: retain the deterministic stalled
10974        // input before a claim proves the owner is gone and reclaims it.
10975        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10976        assert_eq!(
10977            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10978            [&t.id]
10979        );
10980        assert_eq!(
10981            reclaim_orphaned_running(&queue, 2, &Default::default()),
10982            [t.id.clone()]
10983        );
10984        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10985
10986        // Reclaim drops its guard before conductor decisions are applied, so
10987        // the decision for the captured stalled input has a real write path.
10988        crate::conduct::apply(
10989            &queue,
10990            &questions,
10991            &crate::conduct::Verdict {
10992                decisions: vec![crate::conduct::Decision {
10993                    id: t.id.clone(),
10994                    recovery: Some(crate::conduct::Recovery::Requeue),
10995                    ..crate::conduct::Decision::default()
10996                }],
10997            },
10998        )
10999        .unwrap();
11000        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11001    }
11002
11003    #[test]
11004    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
11005        let dir = tempfile::tempdir().unwrap();
11006        let queue = Queue::at(dir.path().join("queue"));
11007        let home = dir.path().join("home");
11008
11009        let mut fresh = task();
11010        fresh.id = "20260101-000001-aaaa".to_owned();
11011        fresh.start("run-1".to_owned());
11012        queue.put(&mut fresh).unwrap();
11013
11014        let mut old = task();
11015        old.id = "20260101-000002-bbbb".to_owned();
11016        old.start("run-2".to_owned());
11017        queue.put(&mut old).unwrap();
11018        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
11019
11020        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11021        assert_eq!(stalled.len(), 1);
11022        assert_eq!(stalled[0].id, old.id);
11023    }
11024
11025    #[test]
11026    fn queued_and_finished_task_views_partition_by_status() {
11027        let dir = tempfile::tempdir().unwrap();
11028        let queue = Queue::at(dir.path().join("queue"));
11029
11030        let mut queued = task();
11031        queued.id = "20260101-000001-aaaa".to_owned();
11032        queue.put(&mut queued).unwrap();
11033
11034        let mut failed = task();
11035        failed.id = "20260101-000002-bbbb".to_owned();
11036        failed.start("run-1".to_owned());
11037        failed.fail("gate red", 5);
11038        queue.put(&mut failed).unwrap();
11039
11040        let mut held = task();
11041        held.id = "20260101-000003-cccc".to_owned();
11042        held.hold_machine(None);
11043        queue.put(&mut held).unwrap();
11044
11045        let mut running = task();
11046        running.id = "20260101-000004-dddd".to_owned();
11047        running.start("run-2".to_owned());
11048        queue.put(&mut running).unwrap();
11049
11050        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11051        assert_eq!(queued_ids, [queued.id.clone()]);
11052
11053        let mut finished_ids: Vec<String> =
11054            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11055        finished_ids.sort_unstable();
11056        let mut want = vec![failed.id.clone(), held.id.clone()];
11057        want.sort_unstable();
11058        assert_eq!(finished_ids, want);
11059    }
11060
11061    #[test]
11062    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11063        for short in [false, true] {
11064            let dir = tempfile::tempdir().unwrap();
11065            let queue = Queue::at(dir.path().join("queue"));
11066            let questions = ask::Questions::at(dir.path().join("questions"));
11067            let mut running = task();
11068            running.id = "20261013-192213-feb2".into();
11069            running.start("existing-run".into());
11070            queue.put(&mut running).unwrap();
11071            let mut middle = task();
11072            middle.id = "20261013-193611-ca5b".into();
11073            middle.block(
11074                vec![if short {
11075                    "feb2".into()
11076                } else {
11077                    running.id.clone()
11078                }],
11079                None,
11080            );
11081            queue.put(&mut middle).unwrap();
11082            let mut waiting = task();
11083            waiting.id = "20261013-202849-ee37".into();
11084            waiting.block(
11085                vec![if short {
11086                    "ca5b".into()
11087                } else {
11088                    middle.id.clone()
11089                }],
11090                Some("wait for implementation".into()),
11091            );
11092            queue.put(&mut waiting).unwrap();
11093            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11094            let inv = crate::blockers::Inventory::load(&queue, &questions);
11095            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11096            assert!(inv.stuck().is_empty());
11097            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11098            assert!(report.quarantined.is_empty());
11099            assert!(report.asked.is_empty());
11100            resolve_blockers(&queue, &questions);
11101            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11102            assert!(questions.list().is_empty());
11103            // Finishing the transitive prerequisite alone does not satisfy
11104            // the task's direct dependency.
11105            running.succeed();
11106            queue.put(&mut running).unwrap();
11107            resolve_blockers(&queue, &questions);
11108            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11109            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11110            middle = queue.get(&middle.id).unwrap();
11111            middle.succeed();
11112            queue.put(&mut middle).unwrap();
11113            resolve_blockers(&queue, &questions);
11114            let after = queue.get(&waiting.id).unwrap();
11115            assert_eq!(after.status, TaskStatus::Queued);
11116            assert!(after.blocked_by.is_empty());
11117            assert_eq!(after.instruction, waiting.instruction);
11118        }
11119    }
11120
11121    #[test]
11122    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11123        for future_schema in [false, true] {
11124            let name = "20261013-193611-ca5b";
11125            let mut future = task();
11126            future.id = name.into();
11127            future.schema = crate::queue::SCHEMA + 1;
11128            let contents = if future_schema {
11129                serde_json::to_string(&future).unwrap()
11130            } else {
11131                "corrupt".into()
11132            };
11133            let dir = tempfile::tempdir().unwrap();
11134            let queue = Queue::at(dir.path().join("queue"));
11135            let questions = ask::Questions::at(dir.path().join("questions"));
11136            let mut waiting = task();
11137            waiting.id = "20261013-202849-ee37".into();
11138            waiting.block(vec!["ca5b".into()], None);
11139            queue.put(&mut waiting).unwrap();
11140            std::fs::write(queue.path_of(name), contents).unwrap();
11141            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11142            assert!(
11143                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11144            );
11145            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11146            assert!(report.asked.is_empty());
11147            resolve_blockers(&queue, &questions);
11148            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11149            assert!(questions.list().is_empty());
11150        }
11151        let dir = tempfile::tempdir().unwrap();
11152        let queue = Queue::at(dir.path().join("queue"));
11153        let questions = ask::Questions::at(dir.path().join("questions"));
11154        let mut waiting = task();
11155        waiting.id = "20261013-202849-ee37".into();
11156        waiting.block(vec!["ca5b".into()], None);
11157        queue.put(&mut waiting).unwrap();
11158        let mut done = task();
11159        done.id = "20261013-193611-ca5b".into();
11160        done.succeed();
11161        queue.put(&mut done).unwrap();
11162        // An unreadable second match must not disappear from uniqueness
11163        // checks just because Queue::list skips it.
11164        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11165        assert!(queue.get("ca5b").is_err());
11166        assert_eq!(
11167            crate::queue::dependency(&queue, &questions, "ca5b"),
11168            crate::queue::Dependency::Ambiguous
11169        );
11170        resolve_blockers(&queue, &questions);
11171        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11172        assert!(report.asked.is_empty());
11173        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11174        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11175    }
11176
11177    #[test]
11178    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11179        for held in [false, true] {
11180            for question in [false, true] {
11181                for reference in ["ca5b", "20261013-193611-ca5b"] {
11182                    let dir = tempfile::tempdir().unwrap();
11183                    let queue = Queue::at(dir.path().join("queue"));
11184                    let questions = ask::Questions::at(dir.path().join("questions"));
11185                    let mut prerequisite = task();
11186                    prerequisite.id = "20261013-193611-ca5b".into();
11187                    prerequisite.start("existing-run".into());
11188                    queue.put(&mut prerequisite).unwrap();
11189                    let mut waiting = task();
11190                    waiting.id = "20261013-202849-ee37".into();
11191                    if held {
11192                        waiting.hold_machine(Some("waiting for separate consent".into()));
11193                    }
11194                    queue.put(&mut waiting).unwrap();
11195                    let reason = "Deleting saved data requires separate owner consent";
11196                    crate::conduct::apply(
11197                        &queue,
11198                        &questions,
11199                        &crate::conduct::Verdict {
11200                            decisions: vec![crate::conduct::Decision {
11201                                id: waiting.id.clone(),
11202                                blocked_by: vec![reference.into()],
11203                                question: question.then(|| "May the saved data be deleted?".into()),
11204                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11205                                reason: Some(reason.into()),
11206                                ..crate::conduct::Decision::default()
11207                            }],
11208                        },
11209                    )
11210                    .unwrap();
11211                    let before = queue.get(&waiting.id).unwrap();
11212                    if question {
11213                        assert_eq!(before.status, TaskStatus::Blocked);
11214                        let q = questions.get(&before.blocked_by[0]).unwrap();
11215                        assert_eq!(q.summary, "May the saved data be deleted?");
11216                        assert!(q.status.open());
11217                    } else {
11218                        assert_eq!(before.status, TaskStatus::Held);
11219                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11220                        assert!(recorded_reason.starts_with(reason));
11221                        if held {
11222                            assert!(recorded_reason.contains("waiting for separate consent"));
11223                        }
11224                    }
11225                    prerequisite.succeed();
11226                    queue.put(&mut prerequisite).unwrap();
11227                    resolve_blockers(&queue, &questions);
11228                    let after = queue.get(&waiting.id).unwrap();
11229                    assert_eq!(after.status, before.status);
11230                    assert_eq!(after.blocked_by, before.blocked_by);
11231                    assert_eq!(after.hold_reason, before.hold_reason);
11232                    assert_eq!(after.instruction, waiting.instruction);
11233                    if question {
11234                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11235                    }
11236                    assert!(
11237                        queue.next_runnable().is_none(),
11238                        "dependency completion is not consent"
11239                    );
11240                }
11241            }
11242        }
11243    }
11244
11245    #[test]
11246    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11247        let dir = tempfile::tempdir().unwrap();
11248        let queue = Queue::at(dir.path().join("queue"));
11249        let questions = ask::Questions::at(dir.path().join("questions"));
11250
11251        let mut dep = task();
11252        dep.id = "20260101-000001-dep0".to_owned();
11253        dep.succeed();
11254        queue.put(&mut dep).unwrap();
11255
11256        let mut still_going = task();
11257        still_going.id = "20260101-000002-dep1".to_owned();
11258        queue.put(&mut still_going).unwrap();
11259
11260        let mut blocked = task();
11261        blocked.id = "20260101-000003-main".to_owned();
11262        blocked.block(
11263            vec![dep.id.clone(), still_going.id.clone()],
11264            Some("waits on both".to_owned()),
11265        );
11266        queue.put(&mut blocked).unwrap();
11267
11268        resolve_blockers(&queue, &questions);
11269
11270        let after = queue.get(&blocked.id).unwrap();
11271        assert_eq!(
11272            after.status,
11273            TaskStatus::Blocked,
11274            "one dependency is still outstanding"
11275        );
11276        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11277    }
11278
11279    #[test]
11280    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11281        let dir = tempfile::tempdir().unwrap();
11282        let queue = Queue::at(dir.path().join("queue"));
11283        let questions = ask::Questions::at(dir.path().join("questions"));
11284
11285        let mut q = crate::ask::Question::new(
11286            "20260101-000001-main".to_owned(),
11287            crate::conduct::NODE.to_owned(),
11288            "conduct".to_owned(),
11289            "Which backend?".to_owned(),
11290            String::new(),
11291            Vec::new(),
11292        );
11293        questions.put(&mut q).unwrap();
11294        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11295            .unwrap();
11296        questions.put(&mut q).unwrap();
11297
11298        let mut blocked = task();
11299        blocked.id = "20260101-000001-main".to_owned();
11300        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11301        queue.put(&mut blocked).unwrap();
11302
11303        resolve_blockers(&queue, &questions);
11304
11305        let after = queue.get(&blocked.id).unwrap();
11306        assert_eq!(
11307            after.status,
11308            TaskStatus::Queued,
11309            "the only blocker resolved"
11310        );
11311        assert_eq!(after.answers.len(), 1);
11312        assert_eq!(after.answers[0].question, "Which backend?");
11313        assert_eq!(after.answers[0].answer, "SQLite");
11314
11315        // And the run this task starts next is told about it.
11316        let instruction = instruction_for(&after);
11317        assert!(instruction.contains("Which backend?"));
11318        assert!(instruction.contains("SQLite"));
11319    }
11320
11321    #[test]
11322    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11323        let dir = tempfile::tempdir().unwrap();
11324        let queue = Queue::at(dir.path().join("queue"));
11325        let questions = ask::Questions::at(dir.path().join("questions"));
11326
11327        let mut q = crate::ask::Question::new(
11328            "20260101-000001-main".to_owned(),
11329            crate::conduct::NODE.to_owned(),
11330            "conduct".to_owned(),
11331            "Is the setup done?".to_owned(),
11332            String::new(),
11333            Vec::new(),
11334        );
11335        q.abandon("no answer within 60s of asking");
11336        questions.put(&mut q).unwrap();
11337
11338        let mut blocked = task();
11339        blocked.id = "20260101-000001-main".to_owned();
11340        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11341        queue.put(&mut blocked).unwrap();
11342
11343        resolve_blockers(&queue, &questions);
11344
11345        let after = queue.get(&blocked.id).unwrap();
11346        assert_eq!(
11347            after.status,
11348            TaskStatus::Held,
11349            "never left blocked on nothing"
11350        );
11351        assert!(!after.operator_held(), "a machine hold, for triage");
11352        assert!(
11353            after
11354                .hold_reason
11355                .as_deref()
11356                .unwrap_or_default()
11357                .contains("went unanswered")
11358        );
11359    }
11360
11361    #[test]
11362    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11363        // Reproduces the reported bug (task 3958): a task held out of
11364        // attempts, blocked on a `crate::conduct` follow-up question, must
11365        // come back `held` once that question is answered - never `queued`,
11366        // whatever the answer said - or it silently re-enters the
11367        // competition queue with its attempts already exhausted.
11368        let dir = tempfile::tempdir().unwrap();
11369        let queue = Queue::at(dir.path().join("queue"));
11370        let questions = ask::Questions::at(dir.path().join("questions"));
11371
11372        let mut q = crate::ask::Question::new(
11373            "20260101-000001-main".to_owned(),
11374            crate::conduct::NODE.to_owned(),
11375            "conduct".to_owned(),
11376            "How should this be handled?".to_owned(),
11377            String::new(),
11378            Vec::new(),
11379        );
11380        questions.put(&mut q).unwrap();
11381        q.answer(crate::ask::Answer::Text(
11382            "leave it held, a human will look at it later".to_owned(),
11383        ))
11384        .unwrap();
11385        questions.put(&mut q).unwrap();
11386
11387        let mut held = task();
11388        held.id = "20260101-000001-main".to_owned();
11389        held.hold_machine(Some("out of attempts".to_owned()));
11390        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11391        queue.put(&mut held).unwrap();
11392
11393        resolve_blockers(&queue, &questions);
11394
11395        let after = queue.get(&held.id).unwrap();
11396        assert_eq!(after.status, TaskStatus::Held);
11397        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11398        assert_eq!(
11399            after.answers[0].answer,
11400            "leave it held, a human will look at it later"
11401        );
11402    }
11403
11404    #[test]
11405    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11406        let dir = tempfile::tempdir().unwrap();
11407        let queue = Queue::at(dir.path().join("queue"));
11408        let questions = ask::Questions::at(dir.path().join("questions"));
11409        let mut dep = task();
11410        dep.id = "20260101-000001-gone".to_owned();
11411        queue.put(&mut dep).unwrap();
11412        let mut blocked = task();
11413        blocked.id = "20260101-000003-main".to_owned();
11414        blocked.block(vec![dep.id.clone()], None);
11415        queue.put(&mut blocked).unwrap();
11416
11417        // Claimed, so `remove` cannot rewrite it and the resolver must.
11418        let claim = queue.claim(&blocked.id).unwrap();
11419        queue.remove(&dep.id, false, &questions).unwrap();
11420        drop(claim);
11421        resolve_blockers(&queue, &questions);
11422
11423        let after = queue.get(&blocked.id).unwrap();
11424        assert_eq!(after.status, TaskStatus::Queued);
11425        assert!(after.blocked_by.is_empty());
11426    }
11427
11428    #[test]
11429    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11430        // Reproduces the reported bug: a task blocked on a task id that was
11431        // removed (`magi task rm`, or deleted by hand) can never see that id
11432        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11433        // would otherwise leave the task `blocked` forever with no way for an
11434        // operator to find out why.
11435        let dir = tempfile::tempdir().unwrap();
11436        let queue = Queue::at(dir.path().join("queue"));
11437        let questions = ask::Questions::at(dir.path().join("questions"));
11438
11439        let mut still_going = task();
11440        still_going.id = "20260101-000002-dep1".to_owned();
11441        queue.put(&mut still_going).unwrap();
11442
11443        let mut blocked = task();
11444        blocked.id = "20260101-000003-main".to_owned();
11445        blocked.block(
11446            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11447            Some("waits on both".to_owned()),
11448        );
11449        queue.put(&mut blocked).unwrap();
11450
11451        resolve_blockers(&queue, &questions);
11452
11453        let after = queue.get(&blocked.id).unwrap();
11454        assert_eq!(
11455            after.status,
11456            TaskStatus::Held,
11457            "a missing dependency must not leave the task blocked forever"
11458        );
11459        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11460        assert!(after.blocked_by.is_empty());
11461        let reason = after.hold_reason.as_deref().unwrap_or_default();
11462        assert!(
11463            reason.contains("20260101-000001-gone"),
11464            "the missing id must be named so an operator can tell what happened: {reason}"
11465        );
11466        assert!(
11467            reason.contains(&still_going.id),
11468            "the still-valid dependency must not silently vanish from the record: {reason}"
11469        );
11470    }
11471
11472    #[test]
11473    fn instruction_for_is_unchanged_without_any_answers() {
11474        let t = task();
11475        assert_eq!(instruction_for(&t), t.instruction);
11476    }
11477
11478    #[test]
11479    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11480        let dir = tempfile::tempdir().unwrap();
11481        let q = Queue::at(dir.path().join("queue"));
11482        let src = dir.path().join("shot.png");
11483        std::fs::write(&src, "x").unwrap();
11484        let mut t = task();
11485        q.attach(&mut t, &[src]).unwrap();
11486        let paths = task_attachments(&q, &t).unwrap();
11487        assert_eq!(paths.len(), 1);
11488        assert!(paths[0].is_absolute() && paths[0].is_file());
11489        std::fs::remove_file(&paths[0]).unwrap();
11490        let err = task_attachments(&q, &t).unwrap_err().to_string();
11491        assert!(err.contains("shot.png"), "{err}");
11492    }
11493
11494    #[tokio::test]
11495    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11496        let dir = tempfile::tempdir().unwrap();
11497        let queue_path = dir.path().join("queue");
11498        let queue = Queue::at(queue_path.clone());
11499        let mut t = task();
11500        t.source = Source::Agent {
11501            run: "originating-chat".into(),
11502            node: crate::queue::CHAT_NODE.into(),
11503        };
11504        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11505            stage: "config-fetch",
11506            target: "origin/main".into(),
11507        });
11508        record_config_failure(&mut t, &fetch);
11509        t.hold_machine(Some(format!("{fetch:#}")));
11510        let fetch_key = t.chat_notice_due().unwrap();
11511        t.chat_notices.push(fetch_key.clone());
11512        queue.put(&mut t).unwrap();
11513
11514        let queue = Queue::at(queue_path);
11515        let mut t = queue.get(&t.id).unwrap();
11516        let a = dir.path().join("a.toml");
11517        let b = dir.path().join("b.toml");
11518        for (path, text, new_cause) in [
11519            (&a, "[graph", true),
11520            (&a, "[verify", false),
11521            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11522            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11523        ] {
11524            t.release_operator("test", None);
11525            std::fs::write(path, text).unwrap();
11526            let error = Config::discover_fetched(dir.path(), Some(path))
11527                .await
11528                .unwrap_err();
11529            record_config_failure(&mut t, &error);
11530            t.hold_machine(Some(format!("{error:#}")));
11531            let due = t.chat_notice_due();
11532            assert_eq!(due.is_some(), new_cause, "{error:#}");
11533            if let Some(key) = due {
11534                assert_ne!(key, fetch_key);
11535                t.chat_notices.push(key);
11536            }
11537        }
11538        t.succeed();
11539        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11540    }
11541
11542    #[test]
11543    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11544        let dir = tempfile::tempdir().unwrap();
11545        let queue_path = dir.path().join("queue");
11546        let queue = Queue::at(queue_path.clone());
11547        let mut t = task();
11548        t.source = crate::queue::Source::Agent {
11549            run: "originating-chat".into(),
11550            node: crate::queue::CHAT_NODE.into(),
11551        };
11552        let a = dir.path().join("a.png");
11553        let b = dir.path().join("b.png");
11554        std::fs::write(&a, "a").unwrap();
11555        std::fs::write(&b, "b").unwrap();
11556        queue.attach(&mut t, &[a, b]).unwrap();
11557        let paths = task_attachments(&queue, &t).unwrap();
11558        for path in &paths {
11559            std::fs::remove_file(path).unwrap();
11560        }
11561        let missing = task_attachments(&queue, &t).unwrap_err();
11562        t.attempts += 1;
11563        let reason = missing.to_string();
11564        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11565        let first = t.chat_notice_due().expect("first attachment notice");
11566        t.chat_notices.push(first.clone());
11567        queue.put(&mut t).unwrap();
11568
11569        let queue = Queue::at(queue_path.clone());
11570        let mut t = queue.get(&t.id).unwrap();
11571        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11572        t.release_operator("test", None);
11573        t.attempts += 1;
11574        let missing = task_attachments(&queue, &t).unwrap_err();
11575        t.fail_startup_target(
11576            "startup-attachments",
11577            missing.name,
11578            "same missing attachment with regenerated wording",
11579            1,
11580        );
11581        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11582
11583        std::fs::write(&paths[0], "restored").unwrap();
11584        t.release_operator("test", None);
11585        t.attempts += 1;
11586        let missing = task_attachments(&queue, &t).unwrap_err();
11587        let reason = missing.to_string();
11588        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11589        let second = t
11590            .chat_notice_due()
11591            .expect("different attachment must notify");
11592        assert_ne!(first, second);
11593        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11594    }
11595
11596    #[test]
11597    fn resumed_instruction_is_unchanged_without_any_answers() {
11598        let t = task();
11599        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11600    }
11601
11602    #[test]
11603    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11604        let mut t = task();
11605        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11606        // The run's own instruction on disk predates the answer: it is the
11607        // plain original text `Runner::start` saved before the operator was
11608        // ever asked anything.
11609        let old = t.instruction.clone();
11610
11611        let refreshed = resumed_instruction(&old, &t);
11612        assert!(refreshed.starts_with(&old), "the original text is kept");
11613        assert!(refreshed.contains("Which backend?"));
11614        assert!(refreshed.contains("SQLite"));
11615    }
11616
11617    #[test]
11618    fn resumed_instruction_keeps_an_original_answers_heading() {
11619        let mut t = task();
11620        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11621        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11622
11623        let refreshed = resumed_instruction(&t.instruction, &t);
11624
11625        assert!(
11626            refreshed.starts_with(&t.instruction),
11627            "an answers heading in the original instruction is not the appended block"
11628        );
11629        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11630        assert!(refreshed.contains("Which backend?"));
11631        assert!(refreshed.contains("SQLite"));
11632
11633        let repeated = resumed_instruction(&refreshed, &t);
11634        assert_eq!(
11635            repeated, refreshed,
11636            "only the final appended block is refreshed"
11637        );
11638    }
11639
11640    #[test]
11641    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11642        let mut t = task();
11643        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11644
11645        // A first resume appends the block; a second resume of the same run,
11646        // with no new answer in between, must reproduce exactly the same
11647        // text rather than appending the block a second time.
11648        let once = resumed_instruction(&t.instruction, &t);
11649        let twice = resumed_instruction(&once, &t);
11650        assert_eq!(once, twice);
11651        assert_eq!(once.matches("Which backend?").count(), 1);
11652
11653        // A later answer replaces the block wholesale rather than growing it.
11654        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11655        let refreshed = resumed_instruction(&once, &t);
11656        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11657        assert!(refreshed.contains("Which backend?"));
11658        assert!(refreshed.contains("Which cache?"));
11659    }
11660
11661    #[test]
11662    fn prepare_instruction_covers_all_three_starters() {
11663        let mut t = task();
11664        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11665
11666        // Start: a fresh run gets the task text plus every answer so far —
11667        // exactly `instruction_for`.
11668        assert_eq!(
11669            prepare_instruction(&Starter::Start, None, &t),
11670            Some(instruction_for(&t))
11671        );
11672
11673        // Resume: the run's prior instruction is refreshed with the answer,
11674        // not discarded and not left stale.
11675        let old = t.instruction.clone();
11676        assert_eq!(
11677            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11678            Some(resumed_instruction(&old, &t))
11679        );
11680
11681        // Review: a review-only pass builds its own instruction from the
11682        // branch's history in `crate::graph`, with no task statement at all -
11683        // this boundary must leave it alone.
11684        assert_eq!(
11685            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11686            None
11687        );
11688    }
11689
11690    #[test]
11691    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11692        assert_eq!(
11693            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11694            Starter::Review("magi/eba2/A".to_owned())
11695        );
11696    }
11697
11698    #[test]
11699    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11700        assert_eq!(
11701            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11702            Starter::Start,
11703            "a vanished review branch must not fall back to resuming the old run either"
11704        );
11705    }
11706
11707    #[test]
11708    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11709        let mut t = task();
11710        t.start("old-run".to_owned());
11711        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11712        t.release();
11713        let branch = t.review_branch.take();
11714        assert_eq!(
11715            choose_starter(branch.as_deref(), true, Some("old-run")),
11716            Starter::Review("magi/eba2/A".to_owned()),
11717            "a review wins over resuming the old run"
11718        );
11719    }
11720
11721    #[test]
11722    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11723        assert_eq!(
11724            choose_starter(None, false, Some("some-run")),
11725            Starter::Resume("some-run".to_owned())
11726        );
11727        assert_eq!(choose_starter(None, false, None), Starter::Start);
11728    }
11729
11730    #[test]
11731    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11732        let mut released = task();
11733        released.start("stalled-run".to_owned());
11734        released.requeue();
11735        let unfinished = (!released.fresh_start)
11736            .then(|| Some("stalled-run".to_owned()))
11737            .flatten();
11738        assert_eq!(
11739            choose_starter(None, false, unfinished.as_deref()),
11740            Starter::Start,
11741            "release keeps run history but must not resume it"
11742        );
11743        assert_eq!(released.runs, ["stalled-run"]);
11744    }
11745
11746    fn stopped_public_run(status: RunStatus) -> RunState {
11747        let mut state = run_state(status);
11748        state.driver_exited = true;
11749        state.config.graph.land = true;
11750        state.config.graph.review_rounds = 1;
11751        state.reviews = vec![review_round(1)];
11752        state.merge = Some(crate::run::MergeOutcome {
11753            mode: MergeMode::Pr,
11754            ok: false,
11755            detail: "landing stopped".into(),
11756            empty: false,
11757        });
11758        state.pr = Some(crate::run::PrRecord {
11759            url: "https://example.test/pull/1".into(),
11760            number: 1,
11761            state: "open".into(),
11762            checks: "red".into(),
11763            round: 1,
11764            rounds: 1,
11765            red_at_merge: Vec::new(),
11766        });
11767        state
11768    }
11769
11770    #[test]
11771    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11772        for status in [RunStatus::Blocked, RunStatus::Gating] {
11773            let home = tempfile::tempdir().unwrap();
11774            let mut state = stopped_public_run(status);
11775            state.save_under(home.path()).unwrap();
11776            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11777            assert!(!exhausted_review_budget(&state));
11778            let mut task = held_task_with(&state.id);
11779            task.release();
11780            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11781            assert_eq!(
11782                choose_starter(None, false, unfinished.as_deref()),
11783                Starter::Resume(state.id.clone())
11784            );
11785            let question = action_question(&state.id, resume_action(&state.id));
11786            assert_eq!(
11787                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11788                    state.clone()
11789                )),
11790                ActionDecision::Resume(state.id.clone())
11791            );
11792            // The control-plane command uses this same preflight before pinning.
11793            assert_eq!(
11794                crate::resume::validate(home.path(), &state.id).unwrap().id,
11795                state.id
11796            );
11797            let queue = Queue::at(home.path().join("queue"));
11798            let mut controlled = Task::new(
11799                "resume land".into(),
11800                state.instruction.clone(),
11801                state.repo.clone(),
11802                Source::Agent {
11803                    run: "talk".into(),
11804                    node: crate::queue::CHAT_NODE.into(),
11805                },
11806            );
11807            controlled.runs.push(state.id.clone());
11808            controlled.hold_machine(Some("land stopped".into()));
11809            queue.put(&mut controlled).unwrap();
11810            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11811            assert_eq!(resumed.status, TaskStatus::Queued);
11812            assert_eq!(
11813                resumed.resume_override.unwrap().pinned_run,
11814                Some(state.id.clone())
11815            );
11816            assert_eq!(resumed.attempts, 0);
11817        }
11818    }
11819
11820    #[test]
11821    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11822        for review_rounds in [0, 1] {
11823            let home = tempfile::tempdir().unwrap();
11824            let mut state = run_state(RunStatus::Blocked);
11825            state.config.graph.review_rounds = review_rounds;
11826            if review_rounds > 0 {
11827                let mut review = review_round(1);
11828                review.clean = true;
11829                state.reviews = vec![review];
11830            }
11831            state.gate_ran = true;
11832            state.gate = vec![crate::run::CommandOutcome {
11833                command: "verify".into(),
11834                code: Some(1),
11835                output_tail: "gate failed after repair budget exhausted".into(),
11836                duration_ms: 0,
11837                resource_blocked: false,
11838            }];
11839            state.save_under(home.path()).unwrap();
11840            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11841            assert!(exhausted_review_budget(&state));
11842            let mut task = held_task_with(&state.id);
11843            task.release();
11844            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11845            let question = action_question(&state.id, resume_action(&state.id));
11846            assert_ne!(
11847                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11848                    state.clone()
11849                )),
11850                ActionDecision::Resume(state.id.clone())
11851            );
11852            let error = crate::resume::validate(home.path(), &state.id)
11853                .unwrap_err()
11854                .to_string();
11855            assert!(!error.contains("review budget exhausted"), "{error}");
11856            assert!(
11857                error.contains(if review_rounds == 0 {
11858                    "review is disabled"
11859                } else {
11860                    "gate already ran"
11861                }),
11862                "{error}"
11863            );
11864
11865            // An unexecuted gate still has work to do with or without reviews.
11866            state.gate_ran = false;
11867            state.gate.clear();
11868            assert!(!exhausted_review_budget(&state));
11869            assert_eq!(
11870                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11871                Some(state.id)
11872            );
11873        }
11874    }
11875
11876    #[test]
11877    fn resource_blocked_verification_resumes_the_same_run() {
11878        for (kind, stage) in [
11879            ("cache", "clean"),
11880            ("coordination", "clean"),
11881            ("cache", "review-e2e"),
11882            ("coordination", "no-reviews"),
11883            ("coordination", "handoff"),
11884        ] {
11885            let home = tempfile::tempdir().unwrap();
11886            let mut state = run_state(RunStatus::Blocked);
11887            state.config.graph.review_rounds = 1;
11888            let mut review = review_round(1);
11889            review.clean = true;
11890            state.reviews = vec![review];
11891            if stage == "review-e2e" {
11892                let review = &mut state.reviews[0];
11893                review.clean = false;
11894                review.blocking = 1;
11895                review.e2e = vec![crate::run::CommandOutcome {
11896                    command: "verify".into(),
11897                    code: None,
11898                    output_tail: "resource wait expired".into(),
11899                    duration_ms: 0,
11900                    resource_blocked: true,
11901                }];
11902            } else if stage == "no-reviews" {
11903                state.config.graph.review_rounds = 0;
11904                state.reviews.clear();
11905            } else if stage == "handoff" {
11906                // A completed final verification can hand off to the gate
11907                // even when the review still carries contested findings.
11908                let review = &mut state.reviews[0];
11909                review.clean = false;
11910                review.blocking = 1;
11911                review.e2e = vec![crate::run::CommandOutcome {
11912                    command: "verify".into(),
11913                    code: Some(0),
11914                    output_tail: String::new(),
11915                    duration_ms: 0,
11916                    resource_blocked: false,
11917                }];
11918            }
11919            state.gate_ran = false;
11920            state.resource_block = Some(crate::run::ResourceBlock {
11921                cause: crate::run::ResourceBlockCause::Other,
11922                node: if stage == "review-e2e" {
11923                    "review"
11924                } else {
11925                    "gate"
11926                }
11927                .into(),
11928                kind: kind.into(),
11929                detail: "resource wait expired".into(),
11930                at: jiff::Timestamp::now(),
11931            });
11932            state.save_under(home.path()).unwrap();
11933            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11934            assert!(!exhausted_review_budget(&state));
11935            let mut task = held_task_with(&state.id);
11936            task.release();
11937            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11938            assert_eq!(
11939                choose_starter(None, false, unfinished.as_deref()),
11940                Starter::Resume(state.id.clone())
11941            );
11942            let question = action_question(&state.id, resume_action(&state.id));
11943            assert_eq!(
11944                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11945                    state.clone()
11946                )),
11947                ActionDecision::Resume(state.id.clone())
11948            );
11949            assert_eq!(
11950                crate::resume::validate(home.path(), &state.id).unwrap().id,
11951                state.id
11952            );
11953            let queue = Queue::at(home.path().join("queue"));
11954            let mut controlled = Task::new(
11955                "resume verification".into(),
11956                state.instruction.clone(),
11957                state.repo.clone(),
11958                Source::Agent {
11959                    run: "talk".into(),
11960                    node: crate::queue::CHAT_NODE.into(),
11961                },
11962            );
11963            controlled.runs.push(state.id.clone());
11964            controlled.hold_machine(Some("verification resource unavailable".into()));
11965            queue.put(&mut controlled).unwrap();
11966            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11967            assert_eq!(resumed.status, TaskStatus::Queued);
11968            assert_eq!(
11969                resumed.resume_override.unwrap().pinned_run,
11970                Some(state.id.clone())
11971            );
11972            assert_eq!(resumed.attempts, 0);
11973
11974            // A genuinely unresolved final review still exhausts the budget.
11975            state.config.graph.review_rounds = 1;
11976            let mut unresolved = review_round(1);
11977            unresolved.blocking = 1;
11978            state.reviews = vec![unresolved];
11979            state.resource_block = None;
11980            state.save_under(home.path()).unwrap();
11981            assert!(exhausted_review_budget(&state));
11982            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11983        }
11984    }
11985
11986    #[tokio::test]
11987    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11988        if !crate::standalone_test(
11989            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11990        ) {
11991            return;
11992        }
11993        let home = tempfile::tempdir().unwrap();
11994        let mut owner = stopped_public_run(RunStatus::Blocked);
11995        owner.save_under(home.path()).unwrap();
11996        let history = vec![owner.id.clone()];
11997        let repo = owner.repo.clone();
11998        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11999        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
12000        let initial =
12001            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
12002        assert!(
12003            initial.is_pending(),
12004            "a busy record must not hold or resume the task"
12005        );
12006        owner.retired_to = Some("20260101-000001-bbbb".into());
12007        owner.save_under(home.path()).unwrap();
12008        drop(lock);
12009        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
12010            .await
12011            .expect("ownership lock released")
12012            .expect("read settled owner");
12013        assert!(
12014            result.is_none(),
12015            "the retired owner must not be resumed from a stale read"
12016        );
12017    }
12018
12019    #[tokio::test]
12020    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
12021        if !crate::standalone_test(
12022            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
12023        ) {
12024            return;
12025        }
12026        let home = tempfile::tempdir().unwrap();
12027        let mut owner = stopped_public_run(RunStatus::Blocked);
12028        let repo = tempfile::tempdir().unwrap();
12029        crate::git::git(repo.path(), &["init"]).await.unwrap();
12030        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12031        owner.id = "20260101-000000-aaaa".into();
12032        owner.save_under(home.path()).unwrap();
12033        let mut successor = run_state(RunStatus::Blocked);
12034        successor.id = "20260101-000001-bbbb".into();
12035        successor.save_under(home.path()).unwrap();
12036        let runs = vec![owner.id.clone(), successor.id.clone()];
12037        assert_eq!(
12038            public_resume_owner(home.path(), &runs, &owner.repo)
12039                .await
12040                .unwrap()
12041                .unwrap()
12042                .id,
12043            owner.id
12044        );
12045        let subdir = owner.repo.join("nested");
12046        std::fs::create_dir(&subdir).unwrap();
12047        assert_eq!(
12048            public_resume_owner(home.path(), &runs, &subdir)
12049                .await
12050                .unwrap()
12051                .unwrap()
12052                .id,
12053            owner.id
12054        );
12055        #[cfg(unix)]
12056        {
12057            let alias = home.path().join("repo-alias");
12058            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12059            assert_eq!(
12060                public_resume_owner(home.path(), &runs, &alias.join("nested"))
12061                    .await
12062                    .unwrap()
12063                    .unwrap()
12064                    .id,
12065                owner.id
12066            );
12067        }
12068        let different = tempfile::tempdir().unwrap();
12069        crate::git::git(different.path(), &["init"]).await.unwrap();
12070        assert!(
12071            public_resume_owner(home.path(), &runs, different.path())
12072                .await
12073                .is_err()
12074        );
12075        std::fs::remove_file(
12076            home.path()
12077                .join("runs")
12078                .join(&successor.id)
12079                .join("run.json"),
12080        )
12081        .unwrap();
12082        assert!(
12083            public_resume_owner(home.path(), &runs, &owner.repo)
12084                .await
12085                .is_err()
12086        );
12087    }
12088
12089    #[test]
12090    fn an_ordinary_release_keeps_a_resumable_run_available() {
12091        let mut released = task();
12092        released.start("stalled-run".to_owned());
12093        released.release();
12094        let unfinished = (!released.fresh_start)
12095            .then(|| Some("stalled-run".to_owned()))
12096            .flatten();
12097        assert_eq!(
12098            choose_starter(None, false, unfinished.as_deref()),
12099            Starter::Resume("stalled-run".to_owned()),
12100            "manual release must preserve the normal resume path"
12101        );
12102    }
12103
12104    #[test]
12105    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12106        use crate::handover::{ResumeRefusal, resume_refusal_under};
12107        let home = tempfile::tempdir().unwrap();
12108        let mut exhausted = run_state(RunStatus::Blocked);
12109        exhausted.driver_exited = true;
12110        exhausted.config.graph.review_rounds = 3;
12111        exhausted.reviews = (1..=3).map(review_round).collect();
12112        for refusal in [
12113            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12114            ResumeRefusal::Status(RunStatus::Ready),
12115            ResumeRefusal::Released("20261022-000000-aaaa".into()),
12116            ResumeRefusal::Retired("retirement-successor".into()),
12117            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12118        ] {
12119            let mut state = exhausted.clone();
12120            let expected = match refusal {
12121                ResumeRefusal::Status(_) => {
12122                    state.status = RunStatus::Ready;
12123                    "status `ready`"
12124                }
12125                ResumeRefusal::Released(ref target) => {
12126                    state.released_to = Some(target.clone());
12127                    "execution was released"
12128                }
12129                ResumeRefusal::Retired(ref target) => {
12130                    state.retired_to = Some(target.clone());
12131                    "execution was retired"
12132                }
12133                ResumeRefusal::OwnershipTransferred(ref target) => {
12134                    state.pr_taken_over_by = Some(target.clone());
12135                    "PR ownership was transferred"
12136                }
12137                _ => "review budget exhausted (3/3 rounds used)",
12138            };
12139            assert_eq!(
12140                resume_refusal_under(&state, Some(home.path())),
12141                Some(refusal.clone())
12142            );
12143            assert_eq!(
12144                refusal.successor(),
12145                state
12146                    .released_to
12147                    .as_deref()
12148                    .or(state.retired_to.as_deref())
12149                    .or(state.pr_taken_over_by.as_deref())
12150            );
12151            state.save_under(home.path()).unwrap();
12152            let queue = Queue::at(home.path().join("queue"));
12153            let mut task = Task::new(
12154                "retained implementation".into(),
12155                state.instruction.clone(),
12156                state.repo.clone(),
12157                Source::Agent {
12158                    run: "talk".into(),
12159                    node: crate::queue::CHAT_NODE.into(),
12160                },
12161            );
12162            task.runs.push(state.id.clone());
12163            task.hold_machine(Some("stopped".into()));
12164            queue.put(&mut task).unwrap();
12165            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12166            let before_run = serde_json::to_value(&state).unwrap();
12167            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12168                .unwrap_err()
12169                .to_string();
12170            assert!(error.contains(expected), "{error}");
12171            assert!(!error.contains("only a stalled or blocked"), "{error}");
12172            if matches!(refusal, ResumeRefusal::Status(_)) {
12173                assert!(
12174                    error.contains("is final; there is nothing left to resume"),
12175                    "{error}"
12176                );
12177            }
12178            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12179                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12180                assert!(error.contains("review-only successor with a new review budget"));
12181                assert!(error.contains("does not resume this run"));
12182            }
12183            for target in [
12184                &state.released_to,
12185                &state.retired_to,
12186                &state.pr_taken_over_by,
12187            ]
12188            .into_iter()
12189            .flatten()
12190            {
12191                let short = if state.retired_to.as_ref() == Some(target) {
12192                    target.as_str()
12193                } else {
12194                    crate::run::short_of(target)
12195                };
12196                assert!(
12197                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12198                    "{error}"
12199                );
12200                if short != target {
12201                    assert!(!error.contains(target), "full successor id leaked: {error}");
12202                }
12203            }
12204            assert_eq!(
12205                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12206                before_task
12207            );
12208            assert_eq!(
12209                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12210                    .unwrap(),
12211                before_run
12212            );
12213            let question = action_question(&state.id, resume_action(&state.id));
12214            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12215                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12216                    RunState::load_under(id, home.path())
12217                });
12218                let ActionDecision::Refuse(detail) = decision else {
12219                    panic!(
12220                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12221                        state.id,
12222                        home.path().display()
12223                    );
12224                };
12225                assert!(detail.contains(expected), "{detail}");
12226            }
12227        }
12228        // Preserve predicate ordering, while keeping every recorded destination visible.
12229        exhausted.status = RunStatus::Ready;
12230        exhausted.released_to = Some("released".into());
12231        exhausted.retired_to = Some("retired".into());
12232        exhausted.pr_taken_over_by = Some("owner".into());
12233        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12234        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12235        let detail = reason.diagnostic(&exhausted);
12236        for target in ["released", "retired", "owner"] {
12237            assert!(detail.contains(&format!("magi show {target}")));
12238        }
12239    }
12240
12241    #[test]
12242    fn resume_action_ignores_question_checkpoints_in_another_home() {
12243        crate::run::pin_test_home();
12244        let home = tempfile::tempdir().unwrap();
12245        let mut state = run_state(RunStatus::Blocked);
12246        // The private directory reserves this fixture's identity even while
12247        // other tests write questions into the process-wide store.
12248        state.id = format!(
12249            "resume-context-{}",
12250            home.path().file_name().unwrap().to_str().unwrap()
12251        );
12252        state.driver_exited = true;
12253        state.config.graph.review_rounds = 1;
12254        state.reviews = vec![review_round(1)];
12255        state.save_under(home.path()).unwrap();
12256        let task = held_task_with(&state.id);
12257        let answer = action_question(&state.id, resume_action(&state.id));
12258        let mut checkpoint = approval_question(&state.id);
12259        let foreign = Questions::open();
12260        foreign.put(&mut checkpoint).unwrap();
12261        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
12262        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12263            RunState::load_under(id, home.path())
12264        });
12265        let matching: Vec<_> = foreign
12266            .list()
12267            .into_iter()
12268            .filter(|q| q.run == state.id && q.status.open())
12269            .collect();
12270        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
12271        assert!(
12272            matches!(decision, ActionDecision::Refuse(_)),
12273            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
12274            state.id,
12275            home.path().display(),
12276            crate::run::test_home().display()
12277        );
12278        assert_eq!(
12279            refusal,
12280            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
12281        );
12282        let local = Questions::at(home.path().join("questions"));
12283        for status in [
12284            ask::QuestionStatus::Open,
12285            ask::QuestionStatus::Answered,
12286            ask::QuestionStatus::Abandoned,
12287        ] {
12288            let mut question = checkpoint.clone();
12289            match status {
12290                ask::QuestionStatus::Open => {}
12291                ask::QuestionStatus::Answered => {
12292                    question
12293                        .answer(ask::Answer::Choice(question.choices[0].clone()))
12294                        .unwrap();
12295                }
12296                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
12297            }
12298            local.put(&mut question).unwrap();
12299            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12300                RunState::load_under(id, home.path())
12301            });
12302            if status.open() {
12303                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
12304            } else {
12305                assert!(
12306                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
12307                    "status={status:?}, decision={decision:?}"
12308                );
12309            }
12310        }
12311    }
12312
12313    #[test]
12314    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
12315        let home = tempfile::tempdir().unwrap();
12316        let mut state = run_state(RunStatus::Stalled);
12317        state.id = format!(
12318            "resume-driver-{}",
12319            home.path().file_name().unwrap().to_str().unwrap()
12320        );
12321        state.driver_claimed = Some(false);
12322        state.save_under(home.path()).unwrap();
12323        let task = held_task_with(&state.id);
12324        let question = action_question(&state.id, resume_action(&state.id));
12325        let decide = || {
12326            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
12327                RunState::load_under(id, home.path())
12328            })
12329        };
12330        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
12331        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
12332        assert_eq!(
12333            decide(),
12334            ActionDecision::Refuse("run already has a live driver".into())
12335        );
12336        drop(lease);
12337        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
12338    }
12339
12340    #[test]
12341    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12342        let home = tempfile::tempdir().unwrap();
12343        let mut state = run_state(RunStatus::Blocked);
12344        state.driver_exited = true;
12345        state.config.graph.review_rounds = 1;
12346        state.reviews = vec![review_round(1)];
12347        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12348        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12349            let mut saved = state.clone();
12350            match checkpoint {
12351                "publication" => saved.pr_publication_pending = true,
12352                "approval" => {
12353                    saved.land_approval = Some(crate::run::LandApproval {
12354                        question: "approval".into(),
12355                        head: "head".into(),
12356                    })
12357                }
12358                "armed" => saved.land_armed_head = Some("head".into()),
12359                "landing" => saved.status = RunStatus::Landing,
12360                _ => {
12361                    let mut question = ask::Question::new(
12362                        saved.id.clone(),
12363                        "review".into(),
12364                        "review-1".into(),
12365                        "continue?".into(),
12366                        String::new(),
12367                        vec!["continue".into()],
12368                    );
12369                    ask::Questions::at(home.path().join("questions"))
12370                        .put(&mut question)
12371                        .unwrap();
12372                }
12373            }
12374            saved.save_under(home.path()).unwrap();
12375            assert!(
12376                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12377                "{checkpoint}"
12378            );
12379            assert!(
12380                crate::resume::validate(home.path(), &saved.id).is_ok(),
12381                "{checkpoint}"
12382            );
12383        }
12384    }
12385
12386    #[test]
12387    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12388        let mut state = run_state(RunStatus::Blocked);
12389        state.config.graph.review_rounds = 3;
12390        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12391        assert!(exhausted_review_budget(&state));
12392
12393        // One round still unused: resuming can still ask a reviewer something.
12394        state.reviews.pop();
12395        assert!(!exhausted_review_budget(&state));
12396
12397        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12398        // count: only a `Blocked` run re-enters the review loop on resume.
12399        let mut stalled = run_state(RunStatus::Stalled);
12400        stalled.config.graph.review_rounds = 1;
12401        stalled.reviews = vec![review_round(1)];
12402        assert!(!exhausted_review_budget(&stalled));
12403    }
12404
12405    fn review_round(round: usize) -> crate::run::ReviewRound {
12406        crate::run::ReviewRound {
12407            round,
12408            head: "deadbeef".to_owned(),
12409            verified_head: None,
12410            verified_at: None,
12411            reviews: Vec::new(),
12412            e2e: Vec::new(),
12413            verify_retried: false,
12414            e2e_deferred: false,
12415            e2e_defer_reason: None,
12416            fix: None,
12417            blocking: 0,
12418            answered: 1,
12419            expected: 1,
12420            clean: false,
12421            progressed: true,
12422            vote_split: false,
12423            reconsideration: Vec::new(),
12424            verdict: None,
12425        }
12426    }
12427
12428    #[test]
12429    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12430        let mut run = RunState::new(
12431            PathBuf::from("/repo"),
12432            "main".to_owned(),
12433            "abc1234def".to_owned(),
12434            "add retries".to_owned(),
12435            Config::default(),
12436        );
12437        run.status = RunStatus::Judging;
12438        run.parked = true;
12439        let mut task = Task::new(
12440            "add retries".to_owned(),
12441            "add retries".to_owned(),
12442            PathBuf::from("/repo"),
12443            crate::queue::Source::Human,
12444        );
12445        task.status = TaskStatus::Failed;
12446        task.runs = vec![run.id.clone()];
12447        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12448        assert!(with(&task, &run), "parked after judging is the case");
12449        let mut parked_task = task.clone();
12450        parked_task.status = TaskStatus::Parked;
12451        assert!(with(&parked_task, &run), "the Parked status is the case");
12452
12453        let mut not_parked = run.clone();
12454        not_parked.parked = false;
12455        not_parked.status = RunStatus::Stalled;
12456        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12457
12458        let mut fresh = task.clone();
12459        fresh.fresh_start = true;
12460        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12461
12462        let mut review = task.clone();
12463        review.review_branch = Some("magi/x/A".to_owned());
12464        assert!(!with(&review, &run), "review is ranked before resume");
12465
12466        let mut held = task.clone();
12467        held.status = TaskStatus::Held;
12468        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12469
12470        let mut released = run.clone();
12471        released.released_to = Some("20260901-000000-new1".to_owned());
12472        assert!(!with(&task, &released), "nothing left to resume into");
12473
12474        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12475            "unreadable"
12476        )));
12477    }
12478
12479    #[test]
12480    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12481        let mut released = RunState::new(
12482            PathBuf::from("/repo"),
12483            "main".to_owned(),
12484            "abc1234def".to_owned(),
12485            "add retries".to_owned(),
12486            Config::default(),
12487        );
12488        released.status = RunStatus::Blocked;
12489        assert_eq!(
12490            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12491            Some(released.id.clone())
12492        );
12493        released.released_to = Some("20260901-000000-new1".to_owned());
12494        assert_eq!(
12495            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12496            None,
12497            "there is nothing left to resume it into"
12498        );
12499    }
12500
12501    #[test]
12502    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12503        // Mirrors the failure this exists to close: a task's last run ended
12504        // `Blocked` with the review budget spent, `crate::conduct` chose
12505        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12506        // evidence), and without this check `attempt` would go on treating
12507        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12508        // review loop iterates zero times over an already-spent budget, so
12509        // the resumed run settles right back to `Blocked` having asked nobody
12510        // anything, and `Requeue`'s promised fresh competition never happens.
12511        let mut exhausted = RunState::new(
12512            PathBuf::from("/repo"),
12513            "main".to_owned(),
12514            "abc1234def".to_owned(),
12515            "add retries".to_owned(),
12516            Config::default(),
12517        );
12518        exhausted.status = RunStatus::Blocked;
12519        exhausted.config.graph.review_rounds = 1;
12520        exhausted.reviews = vec![review_round(1)];
12521
12522        assert_eq!(
12523            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12524            None,
12525            "an exhausted `Blocked` run must not be offered as resumable"
12526        );
12527
12528        // A `Blocked` run with rounds still unused is genuinely worth
12529        // resuming, and must still be found.
12530        let mut has_budget_left = RunState::new(
12531            PathBuf::from("/repo"),
12532            "main".to_owned(),
12533            "abc1234def".to_owned(),
12534            "add retries".to_owned(),
12535            Config::default(),
12536        );
12537        has_budget_left.status = RunStatus::Blocked;
12538        has_budget_left.config.graph.review_rounds = 3;
12539        has_budget_left.reviews = vec![review_round(1)];
12540
12541        assert_eq!(
12542            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12543                Ok(has_budget_left.clone())
12544            }),
12545            Some(has_budget_left.id.clone())
12546        );
12547    }
12548
12549    #[test]
12550    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12551        let mut run = RunState::new(
12552            PathBuf::from("/repo"),
12553            "main".to_owned(),
12554            "abc1234def".to_owned(),
12555            "add retries".to_owned(),
12556            Config::default(),
12557        );
12558        run.status = RunStatus::Blocked;
12559        run.config.graph.review_rounds = 1;
12560        run.reviews = vec![review_round(1)];
12561        run.pr_publication_pending = true;
12562        assert_eq!(
12563            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12564            Some(run.id.clone()),
12565            "a spent review budget must not turn a failed publication into a re-competition"
12566        );
12567    }
12568
12569    #[test]
12570    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12571        let mut task = Task::new(
12572            "recover work".into(),
12573            "recover work".into(),
12574            PathBuf::from("/repo"),
12575            crate::queue::Source::Human,
12576        );
12577        let mut history = std::collections::BTreeMap::new();
12578        for index in 0..8 {
12579            let mut run = run_state(RunStatus::Blocked);
12580            run.id = format!("20260101-000000-{index:04}");
12581            run.base_commit = format!("upstream-{index}");
12582            // Seven empty newer attempts must not erase the old recovery owner.
12583            if index > 0 {
12584                run.candidates.clear();
12585            }
12586            task.runs.extend([run.id.clone(), run.id.clone()]);
12587            history.insert(run.id.clone(), run);
12588            task.requeue();
12589        }
12590        let check = |task: &Task, starter: &Starter, limit| {
12591            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12592        };
12593        assert!(
12594            check(&task, &Starter::Start, 8)
12595                .unwrap()
12596                .contains("8 unretired")
12597        );
12598        assert!(check(&task, &Starter::Start, 9).is_none());
12599        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12600        task.release_operator("owner", None);
12601        assert_eq!(task.attempts, 0);
12602        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12603        assert!(check(&restored, &Starter::Start, 8).is_some());
12604        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12605        assert!(check(&restored, &Starter::Start, 0).is_none());
12606    }
12607
12608    #[test]
12609    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
12610        let tmp = tempfile::tempdir().unwrap();
12611        let mut task = Task::new(
12612            "recover selected PR".into(),
12613            "preserve implementation".into(),
12614            tmp.path().join("repo"),
12615            crate::queue::Source::Human,
12616        );
12617        let mut failed = run_state(RunStatus::Failed);
12618        failed.id = "20260101-000000-fail".into();
12619        failed.candidates.clear();
12620        failed.prep_complete = Some(false);
12621        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
12622        failed.startup = Some(crate::run::Startup {
12623            kind: "pr-recovery".into(),
12624            branch: Some("selected-public-head".into()),
12625            stage: "worktree-setup".into(),
12626            complete: false,
12627            failure: Some("setup modified a tracked file and failed".into()),
12628        });
12629        // Setup may fail before a candidate is recorded; its dirty worktree
12630        // still needs protection and consumes the independent retained bound.
12631        let worktree = failed.worktree_root().join("under-review");
12632        std::fs::create_dir_all(&worktree).unwrap();
12633        let retained_edit = worktree.join("implementation");
12634        std::fs::write(&retained_edit, "retained setup edit").unwrap();
12635        task.record_startup_failure(crate::run::StartupFailure {
12636            run: failed.id.clone(),
12637            stage: "worktree-setup".into(),
12638        });
12639        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12640        assert!(task.runs.is_empty() && task.passes.is_empty());
12641        assert_eq!(task.attempts, 0);
12642        let starter = Starter::Review("selected-public-head".into());
12643        assert!(
12644            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
12645                .unwrap()
12646                .contains("1 unretired")
12647        );
12648        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
12649        assert!(
12650            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
12651                .unwrap()
12652                .contains("Cannot verify")
12653        );
12654        // Older or mixed writers can link the same reservation in both lists.
12655        let mut mixed = task.clone();
12656        mixed.runs.push(failed.id.clone());
12657        mixed
12658            .startup_failures
12659            .push(task.startup_failures[0].clone());
12660        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
12661        failed.retired_to = Some("verified-recovery-owner".into());
12662        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
12663        assert!(
12664            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
12665                panic!("resuming the existing owner must not allocate a new attempt")
12666            })
12667            .is_none()
12668        );
12669        assert_eq!(
12670            std::fs::read_to_string(retained_edit).unwrap(),
12671            "retained setup edit"
12672        );
12673        assert!(task.runs.is_empty() && task.passes.is_empty());
12674        assert_eq!(task.attempts, 0);
12675    }
12676
12677    #[test]
12678    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12679        let mut task = Task::new(
12680            "recover work".into(),
12681            "recover work".into(),
12682            PathBuf::from("/repo"),
12683            crate::queue::Source::Human,
12684        );
12685        let mut run = run_state(RunStatus::Superseded);
12686        run.candidates.clear();
12687        task.runs.push(run.id.clone());
12688        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12689        run.retired_to = Some("authority".into());
12690        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12691        run.retired_to = None;
12692        run.released_to = Some("authority".into());
12693        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12694        assert!(
12695            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12696                .unwrap()
12697                .contains("Cannot verify")
12698        );
12699        // Resuming an existing owner needs no new inventory or worktree budget.
12700        assert!(
12701            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12702                panic!("resume must not load historical attempts")
12703            })
12704            .is_none()
12705        );
12706    }
12707
12708    #[test]
12709    fn retired_resume_requires_a_valid_same_repository_authority() {
12710        let mut source = run_state(RunStatus::Blocked);
12711        let mut empty = run_state(RunStatus::Blocked);
12712        empty.retired_to = Some(source.id.clone());
12713        let runs = vec![source.id.clone(), empty.id.clone()];
12714        let resolve = |source: &RunState, empty: &RunState| {
12715            unfinished_run_with(&runs, "fixture", |id| {
12716                if id == source.id {
12717                    Ok(source.clone())
12718                } else if id == empty.id {
12719                    Ok(empty.clone())
12720                } else {
12721                    bail!("unreadable authority")
12722                }
12723            })
12724        };
12725        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12726        assert_eq!(
12727            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12728            Starter::Resume(source.id.clone())
12729        );
12730        source.retired_to = Some(empty.id.clone());
12731        assert!(
12732            resolve(&source, &empty).is_none(),
12733            "cycles do not revive obsolete runs"
12734        );
12735        source.retired_to = None;
12736        source.repo = PathBuf::from("/another-repository");
12737        assert!(resolve(&source, &empty).is_none());
12738        source.repo = empty.repo.clone();
12739        source.released_to = Some("later".into());
12740        assert!(resolve(&source, &empty).is_none());
12741        empty.retired_to = Some("unlisted-run".into());
12742        assert!(resolve(&source, &empty).is_none());
12743    }
12744
12745    #[test]
12746    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12747        // A task whose history holds an *older* run that still looks
12748        // resumable (say, a competition `Runner::review` was started
12749        // alongside after that older run went `Stalled`) and a *newest* run
12750        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12751        // on this task must mean a fresh competition — falling back to the
12752        // stale, superseded `Stalled` run instead would resurrect history
12753        // nothing asked to revisit and silently defeat the requeue.
12754        let mut older_stalled = RunState::new(
12755            PathBuf::from("/repo"),
12756            "main".to_owned(),
12757            "abc1234def".to_owned(),
12758            "add retries".to_owned(),
12759            Config::default(),
12760        );
12761        older_stalled.status = RunStatus::Stalled;
12762
12763        let mut newest_exhausted = RunState::new(
12764            PathBuf::from("/repo"),
12765            "main".to_owned(),
12766            "abc1234def".to_owned(),
12767            "add retries".to_owned(),
12768            Config::default(),
12769        );
12770        newest_exhausted.status = RunStatus::Blocked;
12771        newest_exhausted.config.graph.review_rounds = 1;
12772        newest_exhausted.reviews = vec![review_round(1)];
12773
12774        assert_eq!(
12775            unfinished_run_with(
12776                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12777                "t",
12778                |_| Ok(newest_exhausted.clone())
12779            ),
12780            None,
12781            "the newest run is exhausted, so nothing here is worth resuming - \
12782             least of all the older, already-superseded run"
12783        );
12784    }
12785
12786    #[test]
12787    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12788        assert_eq!(
12789            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12790                Err(anyhow::anyhow!("fixture is absent"))
12791            }),
12792            None
12793        );
12794    }
12795
12796    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12797        let mut q = ask::Question::new(
12798            run.to_owned(),
12799            "implement".to_owned(),
12800            "impl-A".to_owned(),
12801            "continue?".to_owned(),
12802            String::new(),
12803            vec!["resume で続行する".to_owned(), "other".to_owned()],
12804        );
12805        q.actions.insert("resume で続行する".to_owned(), action);
12806        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12807            .unwrap();
12808        q
12809    }
12810
12811    fn held_task_with(run: &str) -> Task {
12812        let mut t = task();
12813        t.runs = vec![run.to_owned()];
12814        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12815        t
12816    }
12817
12818    fn resume_action(run: &str) -> ask::ChoiceAction {
12819        ask::ChoiceAction::Resume { run: run.into() }
12820    }
12821
12822    #[test]
12823    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12824        let home = crate::run::test_home();
12825        for parked in [false, true] {
12826            let mut t = task();
12827            t.start("A".into());
12828            t.start("B".into());
12829            assert_eq!(t.runs, vec!["A", "B"]);
12830            t.start("A".into());
12831            let mut resumed = run_state(RunStatus::Blocked);
12832            resumed.id = "A".into();
12833            resumed.parked = parked;
12834            resumed.driver_exited = true;
12835            t.hold_machine(Some("resumed run stopped".into()));
12836            let q = action_question("A", resume_action("A"));
12837            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12838            assert_eq!(
12839                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
12840                    assert_eq!(id, "A");
12841                    Ok(resumed.clone())
12842                }),
12843                ActionDecision::Resume("A".into())
12844            );
12845            assert_eq!(
12846                action_standing(&t, &action_question("B", resume_action("B"))),
12847                ActionStanding::Stale
12848            );
12849            t.release_operator("cli", None);
12850            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12851                assert_eq!(id, "A");
12852                Ok(resumed.clone())
12853            });
12854            assert_eq!(
12855                choose_starter(None, false, unfinished.as_deref()),
12856                Starter::Resume("A".into())
12857            );
12858            assert_eq!(t.runs, vec!["B", "A"]);
12859        }
12860    }
12861
12862    #[test]
12863    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12864        let home = crate::run::test_home();
12865        let mut state = crate::land::tests::repair_state(true, true);
12866        state.status = RunStatus::Landing;
12867        state.parked = true;
12868        state.driver_exited = true;
12869        let mut q = ask::Question::new(
12870            state.id.clone(),
12871            land::APPROVAL_NODE.into(),
12872            "land".into(),
12873            "Merge?".into(),
12874            String::new(),
12875            vec![land::APPROVE.into(), land::HOLD.into()],
12876        );
12877        q.id = state.id.clone();
12878        state.land_approval = Some(crate::run::LandApproval {
12879            question: q.id.clone(),
12880            head: "current-head".into(),
12881        });
12882        assert!(land::upgrade_repair_choice(&mut q, &state));
12883        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12884        let mut task = held_task_with(&state.id);
12885        task.status = TaskStatus::Parked;
12886        assert_eq!(
12887            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12888            ActionDecision::Resume(state.id.clone())
12889        );
12890        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12891        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12892        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12893        assert_eq!(
12894            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12895            ActionDecision::Resume(state.id.clone()),
12896            "a repair answer newer than the manual hold resumes the existing owner"
12897        );
12898        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12899        for answered_at in [q.answered_at, None] {
12900            let mut older = q.clone();
12901            older.answered_at = answered_at;
12902            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
12903                panic!("a later manual hold must prevent dispatch")
12904            });
12905            let ActionDecision::Refuse(reason) = refused else {
12906                panic!("expected an actionable refusal, got {refused:?}");
12907            };
12908            assert!(reason.contains("later operator decision"));
12909            assert!(reason.contains(&format!("magi task release {}", task.id)));
12910        }
12911        task.operator_decided_at = None;
12912        let mut superseded = state.clone();
12913        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12914        assert_eq!(
12915            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
12916            ActionDecision::Stale
12917        );
12918        for case in 1..4 {
12919            let mut changed = state.clone();
12920            match case {
12921                1 => changed.status = RunStatus::Blocked,
12922                2 => changed.released_to = Some("new-owner".into()),
12923                _ => changed.land_approval.as_mut().unwrap().head.clear(),
12924            }
12925            assert!(matches!(
12926                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
12927                ActionDecision::Refuse(_)
12928            ));
12929        }
12930        assert!(matches!(
12931            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
12932                "missing owner"
12933            )),
12934            ActionDecision::Refuse(_)
12935        ));
12936        task.runs.push("replacement".into());
12937        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12938        assert_eq!(
12939            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
12940                "old owner must not load"
12941            )),
12942            ActionDecision::Stale
12943        );
12944    }
12945
12946    #[test]
12947    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12948        let mut state = crate::land::tests::repair_state(true, true);
12949        state.status = RunStatus::Landing;
12950        state.parked = true;
12951        state.driver_exited = true;
12952        let mut q = ask::Question::new(
12953            state.id.clone(),
12954            land::APPROVAL_NODE.into(),
12955            "land".into(),
12956            "Merge?".into(),
12957            String::new(),
12958            vec![land::APPROVE.into(), land::HOLD.into()],
12959        );
12960        q.id = state.id.clone();
12961        state.land_approval = Some(crate::run::LandApproval {
12962            question: q.id.clone(),
12963            head: "current-head".into(),
12964        });
12965        state.save().unwrap();
12966        land::upgrade_repair_choice(&mut q, &state);
12967        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12968        Questions::open().put(&mut q).unwrap();
12969        let tmp = tempfile::tempdir().unwrap();
12970        let queue = Queue::at(tmp.path().join("queue"));
12971        let mut task = held_task_with(&state.id);
12972        task.status = TaskStatus::Parked;
12973        queue.put(&mut task).unwrap();
12974        let empty = Arc::new(tokio::sync::Semaphore::new(0));
12975        let free = Arc::new(tokio::sync::Semaphore::new(1));
12976        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12977        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12978        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12979        assert!(claim.permit.is_some());
12980        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12981        drop(claim);
12982        Questions::open()
12983            .update(&q.id, |q| {
12984                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12985                Ok(())
12986            })
12987            .unwrap();
12988        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12989        assert!(claim.permit.is_none());
12990        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12991    }
12992
12993    #[test]
12994    fn decide_action_resumes_only_the_latest_resumable_run() {
12995        let home = crate::run::test_home();
12996        let t = held_task_with("r1");
12997        let q = action_question("r1", resume_action("r1"));
12998        let load = |s: RunState| move |_: &str| Ok(s);
12999        assert_eq!(
13000            decide_action(
13001                &home,
13002                &t,
13003                &q,
13004                &PHRASES_EN,
13005                load(run_state(RunStatus::Blocked))
13006            ),
13007            ActionDecision::Resume("r1".into())
13008        );
13009        // Not the latest run of the task.
13010        let q_other = action_question("r1", resume_action("r0"));
13011        assert!(matches!(
13012            decide_action(
13013                &home,
13014                &t,
13015                &q_other,
13016                &PHRASES_EN,
13017                load(run_state(RunStatus::Blocked))
13018            ),
13019            ActionDecision::Refuse(_)
13020        ));
13021        // A finished run cannot make progress.
13022        assert!(matches!(
13023            decide_action(
13024                &home,
13025                &t,
13026                &q,
13027                &PHRASES_EN,
13028                load(run_state(RunStatus::Ready))
13029            ),
13030            ActionDecision::Refuse(_)
13031        ));
13032        // A released one either.
13033        let mut released = run_state(RunStatus::Blocked);
13034        released.released_to = Some("elsewhere".into());
13035        assert!(matches!(
13036            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13037            ActionDecision::Refuse(_)
13038        ));
13039        // Unreadable state is a refusal, never a fresh competition.
13040        assert!(matches!(
13041            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13042            ActionDecision::Refuse(_)
13043        ));
13044    }
13045
13046    #[test]
13047    fn decide_action_ignores_a_question_about_an_earlier_run() {
13048        let home = crate::run::test_home();
13049        let mut t = held_task_with("r1");
13050        t.runs.push("r2".to_owned());
13051        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13052        assert_eq!(
13053            decide_action(
13054                &home,
13055                &t,
13056                &action_question("r1", ask::ChoiceAction::Done),
13057                &PHRASES_EN,
13058                never
13059            ),
13060            ActionDecision::Stale
13061        );
13062    }
13063
13064    #[test]
13065    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13066        let home = crate::run::test_home();
13067        let mut t = held_task_with("r1");
13068        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13069        assert_eq!(
13070            decide_action(
13071                &home,
13072                &t,
13073                &action_question("r1", ask::ChoiceAction::Requeue),
13074                &PHRASES_EN,
13075                never
13076            ),
13077            ActionDecision::Requeue
13078        );
13079        let done_q = action_question("r1", ask::ChoiceAction::Done);
13080        assert_eq!(
13081            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13082            ActionDecision::Done
13083        );
13084        t.mark_action_applied(&done_q.id);
13085        assert_eq!(
13086            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13087            ActionDecision::Skip
13088        );
13089
13090        // A plain answer (no action for that label) does nothing.
13091        let mut plain = action_question("r1", ask::ChoiceAction::Done);
13092        plain.actions.clear();
13093        assert_eq!(
13094            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13095            ActionDecision::Skip
13096        );
13097        // A running task is left alone.
13098        let mut running = held_task_with("r1");
13099        running.status = TaskStatus::Running;
13100        assert_eq!(
13101            decide_action(
13102                &home,
13103                &running,
13104                &action_question("r1", ask::ChoiceAction::Done),
13105                &PHRASES_EN,
13106                never
13107            ),
13108            ActionDecision::Skip
13109        );
13110    }
13111
13112    #[test]
13113    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13114        crate::run::pin_test_home();
13115        for legacy in [false, true] {
13116            let dir = tempfile::tempdir().unwrap();
13117            let queue = Queue::at(dir.path().join("queue"));
13118            let questions = Questions::at(dir.path().join("questions"));
13119            let run = "20260101-000000-hold";
13120            let mut task = held_task_with(run);
13121            task.status = TaskStatus::Parked;
13122            let mut q = ask::Question::new(
13123                run.into(),
13124                land::APPROVAL_NODE.into(),
13125                "land".into(),
13126                "Repair?".into(),
13127                String::new(),
13128                vec![land::REPAIR.into()],
13129            );
13130            q.actions.insert(land::REPAIR.into(), resume_action(run));
13131            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13132            // Deterministically order the answer before the actual manual hold.
13133            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13134            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13135            questions.put(&mut q).unwrap();
13136            task.hold_manual(Some("Keep this PR paused".into()));
13137            if legacy {
13138                task.hold_source = None;
13139            }
13140            queue.put(&mut task).unwrap();
13141
13142            apply_task_choice_actions(&queue, &questions, dir.path());
13143            let after = queue.get(&task.id).unwrap();
13144            assert!(after.operator_held());
13145            assert_eq!(after.hold_source, task.hold_source);
13146            assert_eq!(after.operator_decided_at, task.operator_decided_at);
13147            assert_eq!(after.runs, task.runs);
13148            assert_eq!(after.instruction, task.instruction);
13149            assert!(after.resume_override.is_none());
13150            assert!(after.action_applied(&q.id));
13151            let reason = after.hold_reason.as_deref().unwrap();
13152            assert!(reason.starts_with("Keep this PR paused"));
13153            assert!(reason.contains("later operator decision"));
13154            assert!(reason.contains(&format!("magi task release {}", task.id)));
13155
13156            for recovery in [
13157                crate::conduct::Recovery::Review,
13158                crate::conduct::Recovery::Requeue,
13159            ] {
13160                crate::conduct::apply(
13161                    &queue,
13162                    &questions,
13163                    &crate::conduct::Verdict {
13164                        decisions: vec![crate::conduct::Decision {
13165                            id: task.id.clone(),
13166                            recovery: Some(recovery),
13167                            ..Default::default()
13168                        }],
13169                    },
13170                )
13171                .unwrap();
13172            }
13173            // Reconciliation is idempotent, and automatic recovery cannot
13174            // reopen this owner after it observes the rejected repair answer.
13175            apply_task_choice_actions(&queue, &questions, dir.path());
13176            let still_held = queue.get(&task.id).unwrap();
13177            assert!(still_held.operator_held());
13178            assert_eq!(still_held.hold_reason, after.hold_reason);
13179            assert_eq!(still_held.runs, task.runs);
13180            assert!(still_held.review_branch.is_none());
13181            assert!(!still_held.fresh_start);
13182            assert!(queue.next_runnable().is_none());
13183        }
13184    }
13185
13186    #[test]
13187    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13188        for held in [false, true] {
13189            for retry in [false, true] {
13190                let dir = tempfile::tempdir().unwrap();
13191                let queue = Queue::at(dir.path().join("queue"));
13192                let questions = Questions::at(dir.path().join("questions"));
13193                let home = dir.path().join("home");
13194                let mut t = task();
13195                if held {
13196                    t.hold_machine(Some("driver state unknown".into()));
13197                }
13198                queue.put(&mut t).unwrap();
13199                let verdict = serde_json::from_value(serde_json::json!({
13200                    "decisions": [{
13201                        "id": t.id,
13202                        "question": "Driver state unknown; retry the checks or hold?",
13203                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13204                        "actions": {
13205                            "daemon: recheck and retry": {"do": "requeue"},
13206                            "daemon: hold the task": {"do": "hold"}
13207                        }
13208                    }]
13209                }))
13210                .unwrap();
13211                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13212                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13213                let mut q = questions.list().pop().unwrap();
13214                let choice = if retry {
13215                    "daemon: recheck and retry"
13216                } else {
13217                    "daemon: hold the task"
13218                };
13219                assert_eq!(q.actions.len(), 2);
13220                q.answer(ask::Answer::Choice(choice.into())).unwrap();
13221                questions.put(&mut q).unwrap();
13222
13223                // A Web answer does not remove the deputy's fresh lease.
13224                questions.beat(&q.id, ask::WaiterKind::Deputy);
13225                for _ in 0..2 {
13226                    resolve_blockers(&queue, &questions);
13227                    apply_task_choice_actions(&queue, &questions, &home);
13228                    let waiting = queue.get(&t.id).unwrap();
13229                    assert_eq!(waiting.status, TaskStatus::Blocked);
13230                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
13231                    assert!(waiting.answers.is_empty());
13232                    assert!(!waiting.action_applied(&q.id));
13233                    assert!(runnable(&queue).is_empty());
13234                    let free = Arc::new(tokio::sync::Semaphore::new(1));
13235                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
13236                }
13237                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13238
13239                // Releasing the blocker and applying the operation share one save.
13240                resolve_blockers(&queue, &questions);
13241                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13242                apply_task_choice_actions(&queue, &questions, &home);
13243                let after = queue.get(&t.id).unwrap();
13244                assert_eq!(
13245                    after.status,
13246                    if retry {
13247                        TaskStatus::Queued
13248                    } else {
13249                        TaskStatus::Held
13250                    }
13251                );
13252                assert!(after.action_applied(&q.id));
13253                assert_eq!(after.operator_held(), !retry);
13254                assert_eq!(after.answers.len(), 1);
13255
13256                // A later operator decision must not replay this answer.
13257                let mut changed = after;
13258                if retry {
13259                    changed.hold_manual(Some("later hold".into()));
13260                } else {
13261                    changed.release_operator("test", None);
13262                }
13263                let expected = changed.status;
13264                queue.put(&mut changed).unwrap();
13265                apply_task_choice_actions(&queue, &questions, &home);
13266                assert_eq!(queue.get(&t.id).unwrap().status, expected);
13267            }
13268        }
13269    }
13270
13271    #[test]
13272    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13273        let dir = tempfile::tempdir().unwrap();
13274        let queue = Queue::at(dir.path().join("queue"));
13275        let questions = Questions::at(dir.path().join("questions"));
13276        let home = dir.path().join("home");
13277        let mut state = run_state(RunStatus::Blocked);
13278        state.id = "20260101-000000-act1".to_owned();
13279        state.save_under(&home).unwrap();
13280
13281        let mut t = held_task_with(&state.id);
13282        queue.put(&mut t).unwrap();
13283        let mut q = action_question(&state.id, resume_action(&state.id));
13284        questions.put(&mut q).unwrap();
13285
13286        apply_task_choice_actions(&queue, &questions, &home);
13287        let after = queue.get(&t.id).unwrap();
13288        assert_eq!(after.status, TaskStatus::Queued);
13289        assert!(!after.fresh_start);
13290        assert!(after.action_applied(&q.id));
13291        let pin = after.resume_override.clone().unwrap();
13292        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13293        assert!(pin.forced);
13294
13295        // Held again later: the same answer does not release it a second time.
13296        let mut again = queue.get(&t.id).unwrap();
13297        again.hold_machine(Some("later".into()));
13298        queue.put(&mut again).unwrap();
13299        apply_task_choice_actions(&queue, &questions, &home);
13300        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13301    }
13302
13303    #[test]
13304    fn a_delivered_answer_is_still_acted_on_exactly_once() {
13305        let dir = tempfile::tempdir().unwrap();
13306        let queue = Queue::at(dir.path().join("queue"));
13307        let questions = Questions::at(dir.path().join("questions"));
13308        let home = dir.path().join("home");
13309        let mut state = run_state(RunStatus::Blocked);
13310        state.id = "20260101-000000-act2".to_owned();
13311        state.save_under(&home).unwrap();
13312
13313        let mut t = held_task_with(&state.id);
13314        queue.put(&mut t).unwrap();
13315        let mut q = action_question(&state.id, resume_action(&state.id));
13316        q.answer_delivered = true;
13317        questions.put(&mut q).unwrap();
13318
13319        // Delivered, and the agent then died: the task is still held, so the
13320        // chosen action applies.
13321        apply_task_choice_actions(&queue, &questions, &home);
13322        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13323        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13324
13325        // Held again: the same answer does nothing a second time.
13326        let mut again = queue.get(&t.id).unwrap();
13327        again.hold_machine(Some("later".into()));
13328        queue.put(&mut again).unwrap();
13329        apply_task_choice_actions(&queue, &questions, &home);
13330        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13331    }
13332
13333    #[test]
13334    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13335        let dir = tempfile::tempdir().unwrap();
13336        let queue = Queue::at(dir.path().join("queue"));
13337        let questions = Questions::at(dir.path().join("questions"));
13338        let home = dir.path().join("home");
13339        let mut state = run_state(RunStatus::Blocked);
13340        state.id = "20260101-000000-act3".to_owned();
13341        state.save_under(&home).unwrap();
13342        let mut t = held_task_with(&state.id);
13343        queue.put(&mut t).unwrap();
13344        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13345        questions.put(&mut q).unwrap();
13346
13347        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13348        apply_task_choice_actions(&queue, &questions, &home);
13349        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13350
13351        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13352        apply_task_choice_actions(&queue, &questions, &home);
13353        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13354    }
13355
13356    #[test]
13357    fn action_standing_tells_the_reasons_apart() {
13358        let mut t = held_task_with("r1");
13359        let q = action_question("r1", ask::ChoiceAction::Requeue);
13360        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13361        let mut plain = q.clone();
13362        plain.actions.clear();
13363        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13364
13365        // Applied wins over everything, even a running task.
13366        t.mark_action_applied(&q.id);
13367        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13368
13369        // A newer attempt running: the old question is Stale, not Busy.
13370        let mut t = held_task_with("r1");
13371        t.start("r2".to_owned());
13372        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13373        // The same question about the latest run just waits.
13374        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13375        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13376        t.status = TaskStatus::Blocked;
13377        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13378
13379        // A conductor question is keyed by the task, never stale.
13380        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13381        c.node = crate::conduct::NODE.to_owned();
13382        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13383        assert!(!ActionStanding::Busy.daemon_owns());
13384    }
13385
13386    #[test]
13387    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13388        let dir = tempfile::tempdir().unwrap();
13389        let queue = Queue::at(dir.path().join("queue"));
13390        let questions = Questions::at(dir.path().join("questions"));
13391        let home = dir.path().join("home");
13392        let mut state = run_state(RunStatus::Blocked);
13393        state.id = "20260101-000000-act4".to_owned();
13394        state.save_under(&home).unwrap();
13395        let mut t = held_task_with(&state.id);
13396        t.status = TaskStatus::Running;
13397        queue.put(&mut t).unwrap();
13398        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13399        q.cwd = Some(dir.path().display().to_string());
13400        questions.put(&mut q).unwrap();
13401
13402        // While the task runs the daemon will not act, so the waiter still
13403        // delivers the word to the dead asker's seat ...
13404        let running = queue.get(&t.id).unwrap();
13405        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13406        assert!(matches!(
13407            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13408            crate::waiter::Action::Deliver(_)
13409        ));
13410        // ... and the daemon waits while the task runs, then applies once.
13411        apply_task_choice_actions(&queue, &questions, &home);
13412        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13413        let mut back = queue.get(&t.id).unwrap();
13414        back.hold_machine(Some("later".into()));
13415        queue.put(&mut back).unwrap();
13416        apply_task_choice_actions(&queue, &questions, &home);
13417        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13418        let mut again = queue.get(&t.id).unwrap();
13419        again.hold_machine(Some("again".into()));
13420        queue.put(&mut again).unwrap();
13421        apply_task_choice_actions(&queue, &questions, &home);
13422        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13423    }
13424}