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::{BuildCache, Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{CompletionActor, CompletionContext, 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    /// Last completed candidate scan that started no tasks; absent otherwise.
137    #[serde(default)]
138    pub dispatch_wait: Option<DispatchWait>,
139    /// Effective startup capabilities of the question recovery loops.
140    #[serde(default)]
141    pub question_recovery: Option<crate::question_delivery::Recovery>,
142    /// Independent-worker control protocol supported by this scheduler.
143    #[serde(default)]
144    pub worker_protocol: Option<u32>,
145}
146
147impl Status {
148    /// A fresh, idle status for this process.
149    #[must_use]
150    pub fn new() -> Self {
151        let now = Timestamp::now();
152        Self {
153            schema: SCHEMA,
154            pid: std::process::id(),
155            started_at: now,
156            updated_at: now,
157            idle: true,
158            current: Vec::new(),
159            completed: 0,
160            polls: 0,
161            dispatch_wait: None,
162            question_recovery: None,
163            worker_protocol: Some(1),
164        }
165    }
166}
167
168impl Default for Status {
169    fn default() -> Self {
170        Self::new()
171    }
172}
173
174/// How the loop should behave.
175#[derive(Debug, Clone, Serialize, Deserialize)]
176#[serde(default)]
177pub struct Opts {
178    /// Repository used by tasks that name none.
179    pub repo: PathBuf,
180    /// Explicit `magi.toml`, instead of the discovered layer stack.
181    pub config: Option<PathBuf>,
182    /// Queue poll interval.
183    pub poll: Duration,
184    /// Attempts a task gets before it is held for a human.
185    pub max_attempts: usize,
186    /// Drain what is runnable now, then return, instead of waiting for more.
187    pub once: bool,
188    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
189    pub merge: Option<String>,
190    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
191    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
192    /// `None` resolves to [`crate::run::default_worktree_root`] - the
193    /// operator's real `~/wt/<repo>` - the same way a run with no
194    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
195    /// that does not own that directory (a test, an embedding that manages
196    /// worktrees itself) must set this, or every idle tick reclaims worktrees
197    /// out from under whoever actually does.
198    pub worktrees_root: Option<PathBuf>,
199}
200
201impl Default for Opts {
202    fn default() -> Self {
203        Self {
204            repo: PathBuf::from("."),
205            config: None,
206            poll: POLL,
207            max_attempts: 2,
208            once: false,
209            merge: None,
210            worktrees_root: None,
211        }
212    }
213}
214
215impl Opts {
216    fn absolute(&self) -> Result<Self> {
217        let mut opts = self.clone();
218        opts.repo = std::path::absolute(&opts.repo)?;
219        opts.config = opts
220            .config
221            .as_deref()
222            .map(std::path::absolute)
223            .transpose()?;
224        opts.worktrees_root = opts
225            .worktrees_root
226            .as_deref()
227            .map(std::path::absolute)
228            .transpose()?;
229        Ok(opts)
230    }
231}
232
233/// How many runs a plain `usize` from config may drive concurrently, floored
234/// at one. A `0` in a config file would otherwise stall the loop entirely -
235/// no runnable task could ever start - which is never what an operator who
236/// wrote `0` meant.
237fn max_concurrent(n: usize) -> usize {
238    n.max(1)
239}
240
241/// Where the status file lives.
242#[must_use]
243pub fn status_path() -> PathBuf {
244    crate::run::home().join("daemon.json")
245}
246
247/// Publish the status file for this process.
248pub fn write_status(status: &Status) -> Result<()> {
249    write_status_to(&status_path(), status)
250}
251
252/// Publish a status to an explicit path.
253///
254/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
255/// on every health poll and must never see a half-written one.
256pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
257    if let Some(parent) = path.parent() {
258        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
259    }
260    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
261    let tmp = path.with_extension("json.tmp");
262    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
263    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
264    Ok(())
265}
266
267/// Delete the status file. Called on the way out so a clean exit reads as
268/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
269pub fn clear_status() {
270    clear_status_at(&status_path());
271}
272
273/// Delete a status file at an explicit path, so the loop's teardown and
274/// [`clear_status`] cannot drift apart: the loop is handed the path it
275/// published to, and a test can watch a temp file disappear.
276fn clear_status_at(path: &Path) {
277    let _ = std::fs::remove_file(path);
278}
279
280/// A cooperative stop, shared with whoever asked the loop to run.
281///
282/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
283/// Ctrl-C listener and the web UI keep others, and every clone points at the
284/// same flag. There is no channel because there is nothing to send — the only
285/// message is "stop", it is idempotent, and a flag cannot be missed by a
286/// receiver that was not listening yet.
287///
288/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
289/// detached task workers keep their own lifetimes and ownership after this
290/// handle's scheduler exits.
291#[derive(Debug, Clone, Default)]
292pub struct Stop {
293    /// Set once, never cleared: a stop is not something an operator takes back
294    /// half way through, and a clearable flag would let a start racing a stop
295    /// resurrect a loop that is already unwinding.
296    stopped: Arc<AtomicBool>,
297    /// Live task workers observed by the scheduler's latest dispatch snapshot.
298    busy: Arc<std::sync::atomic::AtomicUsize>,
299    /// Wakes the idle wait. Without this a stop would not be seen until the
300    /// poll interval elapsed, and an operator tapping stop on a phone would
301    /// watch a button do nothing for five seconds.
302    wake: Arc<Notify>,
303    /// Handed to the run in flight, so a stop can also mean "park at the next
304    /// node boundary" instead of "finish the whole competition first".
305    pause: crate::graph::Pause,
306}
307
308impl Stop {
309    /// A stop nobody has asked for yet.
310    #[must_use]
311    pub fn new() -> Self {
312        Self::default()
313    }
314
315    /// Ask the loop to stop. Idempotent, and safe to call before the loop
316    /// starts: the flag is checked before the first poll.
317    pub fn stop(&self) {
318        self.stopped.store(true, Ordering::SeqCst);
319        // `notify_one` rather than `notify_waiters` because the loop may not be
320        // parked yet: this stores a permit, so a wait that registers a moment
321        // later returns at once instead of sleeping out the whole interval.
322        self.wake.notify_one();
323    }
324
325    /// Has a stop been asked for?
326    #[must_use]
327    pub fn stopped(&self) -> bool {
328        self.stopped.load(Ordering::SeqCst)
329    }
330
331    /// Whether a requested scheduler retirement still has an active snapshot.
332    /// Workers continue independently after the scheduler has retired.
333    #[must_use]
334    pub fn finishing(&self) -> bool {
335        self.stopped() && self.busy_now()
336    }
337
338    /// Ask the loop to stop *and* the run in flight to park at its next node
339    /// boundary.
340    ///
341    /// Unlike plain stop, explicit park asks workers to checkpoint at their
342    /// existing safe boundaries. Binary replacement never needs a park.
343    pub fn park(&self, cause: crate::run::ParkCause) {
344        self.pause.park_for(cause);
345        self.stop();
346    }
347
348    /// Has a park been asked for?
349    #[must_use]
350    pub fn parking(&self) -> bool {
351        self.pause.parked()
352    }
353
354    /// The pause handle to give a runner.
355    #[must_use]
356    pub fn pause(&self) -> crate::graph::Pause {
357        self.pause.clone()
358    }
359
360    /// Whether the scheduler's latest snapshot contains active task workers.
361    #[must_use]
362    pub fn busy_now(&self) -> bool {
363        self.busy.load(Ordering::SeqCst) > 0
364    }
365
366    /// Wait out one poll interval, returning early once a stop is asked for.
367    async fn idle(&self, poll: Duration) {
368        tokio::select! {
369            () = tokio::time::sleep(poll) => {}
370            () = self.wake.notified() => {}
371        }
372    }
373}
374
375/// The daemon's published state, read permissively.
376///
377/// This mirrors [`Status`], but is a separate declaration on purpose: every
378/// field defaults, so a status file from an older or newer magi still yields
379/// a usable reading — one this build has never heard of — instead of a parse
380/// error that hides the daemon entirely.
381#[derive(Debug, Clone, Default, Deserialize)]
382#[serde(default)]
383pub struct Reading {
384    /// Format version the daemon claims.
385    pub schema: u32,
386    /// Daemon process id, for an operator who wants to stop it.
387    pub pid: Option<u32>,
388    /// When that process started.
389    pub started_at: Option<Timestamp>,
390    /// Last heartbeat. Absent means the file is unusable, hence not running.
391    pub updated_at: Option<Timestamp>,
392    /// True when the queue had nothing runnable at the last poll.
393    pub idle: bool,
394    /// What the daemon is working on. Empty means idle; more than one entry
395    /// means more than one run is in flight at once.
396    ///
397    /// `deserialize_with` rather than the plain derive: a daemon started
398    /// before this field became a list is still out there writing the old
399    /// shape — a single `{"task":...,"run":...}` object, or its absence —
400    /// on every heartbeat until it is restarted, and a live process reading
401    /// that file during the rollout must still see it as running rather than
402    /// as absent. A bare type change here would fail the whole struct's
403    /// deserialization on a type mismatch, defeating the permissiveness this
404    /// type exists for.
405    #[serde(deserialize_with = "de_current")]
406    pub current: Vec<Current>,
407    /// Tasks this daemon process has finished.
408    pub completed: u64,
409    /// Queue polls this daemon process has made.
410    pub polls: u64,
411    /// Last no-start scan, retaining unknown reason keys from newer writers.
412    pub dispatch_wait: Option<DispatchWait>,
413    /// Effective startup capabilities of the question recovery loops.
414    #[serde(default)]
415    pub question_recovery: Option<crate::question_delivery::Recovery>,
416    /// Independent-worker control protocol, absent on legacy embedded loops.
417    pub worker_protocol: Option<u32>,
418}
419
420/// Accept the old single-`Current`-or-absent shape as well as the current
421/// list, so a reader never has to know which build wrote the file.
422fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
423where
424    D: serde::Deserializer<'de>,
425{
426    #[derive(Deserialize)]
427    #[serde(untagged)]
428    enum Shape {
429        Many(Vec<Current>),
430        One(Current),
431    }
432    Ok(
433        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
434            Shape::Many(v) => v,
435            Shape::One(c) => vec![c],
436        }),
437    )
438}
439
440impl Reading {
441    /// Seconds since the last heartbeat, or `None` when there has never been
442    /// one.
443    #[must_use]
444    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
445        self.updated_at
446            .map(|at| (now.as_second() - at.as_second()).max(0))
447    }
448
449    /// Whether the loop counts as running: a heartbeat no older than
450    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
451    /// progress hours after the daemon that owned it was killed.
452    #[must_use]
453    pub fn running(&self, now: Timestamp) -> bool {
454        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
455    }
456}
457
458/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
459/// usable there.
460///
461/// Missing, half-written and unparseable all collapse to `None`, because the
462/// only question a reader asks is whether a daemon is alive, and a file it
463/// cannot read is not evidence that one is.
464#[must_use]
465pub fn read_status(home: &Path) -> Option<Reading> {
466    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
467    serde_json::from_str(&body).ok()
468}
469
470/// Read-only evidence of runs owned by a live daemon or independent worker.
471///
472/// CLI, sandboxed conversation controls and Web cleanup share this observation.
473/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
474/// Starting reservations and unknown worker state remain protected; observing
475/// them never creates, reconciles or archives files in the worker store.
476/// Callers interested in one identity use [`is_working_on`] or
477/// [`is_working_on_task`].
478#[must_use]
479pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
480    let mut current = read_status(home)
481        .filter(|reading| reading.running(now))
482        .map(|reading| reading.current)
483        .unwrap_or_default();
484    let workers = crate::worker::observe_active(home).and_then(|jobs| {
485        jobs.into_iter()
486            .filter(|job| job.kind == "task")
487            .map(|job| {
488                let request: TaskWorker = serde_json::from_value(job.payload)?;
489                let run = Queue::at(request.queue)
490                    .get(&request.task)
491                    .ok()
492                    .and_then(|task| task.execution_runs().last().cloned())
493                    .unwrap_or_default();
494                Ok(Current {
495                    worker: Some(job.id),
496                    task: request.task,
497                    run,
498                })
499            })
500            .collect::<Result<Vec<_>>>()
501    });
502    match workers {
503        Ok(workers) => {
504            for worker in workers {
505                if !current.iter().any(|claim| {
506                    claim.task == worker.task
507                        && claim.run == worker.run
508                        && claim.worker == worker.worker
509                }) {
510                    current.push(worker);
511                }
512            }
513        }
514        Err(error) => {
515            // This API gates destructive cleanup. Unknown worker ownership
516            // protects every known task/run instead of pretending it is idle.
517            tracing::error!("cannot determine active workers: {error:#}");
518            current.extend(
519                Queue::at(home.join("queue"))
520                    .list()
521                    .into_iter()
522                    .map(|task| Current {
523                        worker: None,
524                        task: task.id.clone(),
525                        run: task.execution_runs().last().cloned().unwrap_or_default(),
526                    }),
527            );
528            current.extend(
529                crate::run::list_ids_in(&home.join("runs"))
530                    .into_iter()
531                    .map(|run| Current {
532                        worker: None,
533                        task: String::new(),
534                        run,
535                    }),
536            );
537        }
538    }
539    current
540}
541
542/// Whether a live daemon is working on this run at this moment.
543#[must_use]
544pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
545    current_work(home, now).iter().any(|c| c.run == run)
546}
547
548/// Admission may ignore only this process's confirmed worker reservation.
549/// Keep anonymous/legacy daemon claims and every other worker, even for the
550/// same task. The run's execution lease and process identity are checked by
551/// the caller under the owner lock as well.
552pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
553    // A helper or test may inherit an identity from a different run store.
554    // That identity grants no exception here; retain all ownership evidence.
555    let same_home = std::env::var_os("MAGI_WORKER_HOME")
556        .is_some_and(|worker_home| Path::new(&worker_home) == home);
557    let caller = if same_home {
558        crate::worker::current_job(home)?
559    } else {
560        None
561    }
562    .filter(|job| {
563        job.kind == "task"
564            && job.status == crate::worker::Status::Running
565            && job.pid == Some(std::process::id())
566    });
567    Ok(other_claims_run(
568        &current_work(home, now),
569        run,
570        caller.as_ref().map(|job| job.id.as_str()),
571    ))
572}
573
574fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
575    claims
576        .iter()
577        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
578}
579
580/// Whether a live daemon is working on a run whose short id is this one.
581///
582/// For a worktree that has no run record to compare against at all -
583/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
584/// id is not available to hand to [`is_working_on`]. The short id is: a run's
585/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
586/// and it is exactly the gap between the daemon claiming a task and
587/// `RunState::new` saving the first `run.json` that this exists to protect -
588/// a run genuinely in flight but invisible to a scan of `runs/`.
589#[must_use]
590pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
591    current_work(home, now)
592        .iter()
593        .any(|c| crate::run::short_of(&c.run) == short)
594}
595
596/// Whether a live daemon is working on this task at this moment.
597#[must_use]
598pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
599    current_work(home, now).iter().any(|c| c.task == task)
600}
601
602/// Remove claim files whose owner is provably dead, or that have simply
603/// outlived `older_than`, and return the task ids swept.
604///
605/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
606/// destructor, and the orphaned `.lock` file would make its task permanently
607/// unclaimable — the backlog would stop for good at exactly the task that was
608/// in flight when the machine went down.
609///
610/// The pid recorded in the lock is the authority whenever it can be read at
611/// all; age is only a fallback for when it cannot be.
612///
613/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
614///   full stop — dead sweeps the lock immediately, regardless of age; alive
615///   protects it, regardless of age. This is what lets a lock be reclaimed in
616///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
617///   before this daemon even started, next to a `queued` task, no longer has
618///   to sit for six hours before anything notices its owner is gone.
619/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
620///   falls back to `older_than`, since there is nothing else to check.
621///
622/// Age must never override a *positive* liveness confirmation. `sweep`
623/// polls concurrently with independently running task workers. A worker may
624/// legitimately run longer than `older_than`; its live pid must still protect
625/// its claim. Age alone must never turn that claim into a second task attempt,
626/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
627/// to a second attempt — two `Runner`s writing the same `run.json` and the
628/// same worktree at once. `pid_alive` answering "alive" for anything it
629/// cannot determine (a live process, a pid this build cannot check, one
630/// under another account) is exactly what keeps that path from ever
631/// firing on a guess.
632///
633/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
634/// output unreadable must not be license to guess, and the risk of an
635/// unparseable lock outliving a genuinely dead owner is bounded by an order
636/// of magnitude above any plausible run rather than by a positive check.
637///
638/// Runs on every poll, not only at startup — a daemon up for days must keep
639/// noticing a lock some other, now-dead, daemon left behind just as readily
640/// as one it trips over on the way up.
641pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
642    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
643}
644
645/// [`sweep_stale_claims`] with its process-query boundary supplied by the
646/// caller. This keeps the lock policy testable where process listing is
647/// unavailable, while production still uses the platform query above.
648fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
649where
650    F: Fn(u32) -> bool,
651{
652    let this_process = std::process::id();
653    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
654        .into_iter()
655        .flatten()
656        .flatten()
657        .map(|e| e.path())
658        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
659        .filter(|p| {
660            match std::fs::read_to_string(p)
661                .ok()
662                .and_then(|body| body.trim().parse::<u32>().ok())
663            {
664                // This process wrote it and is asking the question right
665                // now, so it is definitionally still alive - settled without
666                // spawning a helper process at all.
667                Some(pid) if pid == this_process => false,
668                Some(pid) => !pid_alive(pid),
669                None => p
670                    .metadata()
671                    .and_then(|m| m.modified())
672                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
673                    .is_ok_and(|age| age >= older_than),
674            }
675        })
676        .filter(|p| std::fs::remove_file(p).is_ok())
677        .filter_map(|p| {
678            p.file_stem()
679                .and_then(|s| s.to_str())
680                .map(std::borrow::ToOwned::to_owned)
681        })
682        .collect();
683    swept.sort_unstable();
684    swept
685}
686
687/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
688/// no live daemon's heartbeat naming it? Deterministic — no model call, and
689/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
690/// shown.
691fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
692    task.status == TaskStatus::Running
693        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
694        && !is_working_on_task(home, &task.id, now)
695}
696
697/// Every task [`is_stalled`] right now — "止まったタスク" in
698/// `crate::conduct`'s vocabulary.
699fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
700    queue
701        .list()
702        .into_iter()
703        .filter(|t| is_stalled(t, home, now))
704        .collect()
705}
706
707/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
708/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
709/// `Failed`-and-so-also-runnable: a task that already attempted and lost
710/// belongs in [`finished_tasks`], where the question is a recovery, not a
711/// dependency.
712fn queued_tasks(queue: &Queue) -> Vec<Task> {
713    queue
714        .list()
715        .into_iter()
716        .filter(|t| t.status == TaskStatus::Queued)
717        .collect()
718}
719
720/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
721/// タスク" in `crate::conduct`'s vocabulary.
722fn finished_tasks(queue: &Queue) -> Vec<Task> {
723    queue
724        .list()
725        .into_iter()
726        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
727        .collect()
728}
729
730/// Deterministically resolve `Task::blocked_by`: a dependency task that
731/// reached `Done`, or a question that was answered, is removed — no model
732/// involved, on every poll. An answered question's content is copied onto
733/// the task ([`Task::record_answer`]) before its id is dropped, so it
734/// reaches the next `crate::conduct` prompt and the next run's instruction
735/// (see [`instruction_for`]) rather than only clearing the block.
736///
737/// A `blocked_by` id that names neither an existing task nor an existing
738/// question - `magi task rm` (or an operator by hand) deleted it while this
739/// task was still waiting - is caught before any of that: it can never
740/// become `Done` or `Answered`, so the ordinary loop below would otherwise
741/// leave the task `blocked` forever with nothing to notice. Such a task is
742/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
743/// which puts it in front of `crate::triage::run_once`'s own walk the next
744/// time it runs - see that module's doc for why the choice is "ask a human",
745/// never "assume the missing dependency was satisfied and unblock anyway".
746fn resolve_blockers(queue: &Queue, questions: &Questions) {
747    for listed in queue.list() {
748        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
749            continue;
750        }
751        let Ok(_claim) = queue.claim(&listed.id) else {
752            continue;
753        };
754        let Ok(mut task) = queue.get(&listed.id) else {
755            continue;
756        };
757        if task.status != TaskStatus::Blocked {
758            continue;
759        }
760        // A dependency deleted on purpose is released, not held - and before
761        // the missing check, so a pass that races the delete (or a claim that
762        // made `Queue::remove` skip this task) settles it quietly.
763        let deleted = queue.apply_deleted_blockers(&mut task, questions);
764        if !deleted.is_empty() {
765            record(queue, &mut task);
766            for id in &deleted {
767                queue.note_dependency_deleted(&task, id);
768            }
769            if task.status != TaskStatus::Blocked {
770                continue;
771            }
772        }
773        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
774        if !missing.is_empty() {
775            let language = language_of(&task, Path::new("."));
776            let mut cause = missing.clone();
777            cause.sort();
778            cause.dedup();
779            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
780            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
781                &task.blocked_by,
782                &missing,
783                &language,
784            )));
785            record(queue, &mut task);
786            continue;
787        }
788        // A conductor question nobody answered in time is retired by the
789        // waiter, and nothing else would ever move the task it blocks.
790        if let Some(q) = task.blocked_by.iter().find_map(|id| {
791            let crate::queue::Dependency::Question(full) =
792                crate::queue::dependency(queue, questions, id)
793            else {
794                return None;
795            };
796            questions.get_for_effects(&full).ok().filter(|q| {
797                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
798            })
799        }) {
800            let language = language_of(&task, Path::new("."));
801            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
802            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
803            record(queue, &mut task);
804            continue;
805        }
806        let mut changed = false;
807        for id in task.blocked_by.clone() {
808            let resolved = crate::queue::dependency(queue, questions, &id);
809            if let crate::queue::Dependency::Task(full) = &resolved {
810                if queue
811                    .get(full)
812                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
813                {
814                    task.unblock(&id);
815                    changed = true;
816                }
817                continue;
818            }
819            if let crate::queue::Dependency::Question(full) = resolved
820                && let Ok(q) = questions.get_for_effects(&full)
821                && q.status == ask::QuestionStatus::Answered
822            {
823                // The action sweep releases conductor blockers atomically
824                // with their selected operation. A fresh deputy lease must
825                // never leave an answered hold temporarily runnable.
826                if q.node == crate::conduct::NODE
827                    && q.chosen_action().is_some()
828                    && !task.action_applied(&q.id)
829                {
830                    continue;
831                }
832                let answer = match &q.answer {
833                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
834                    None => String::new(),
835                };
836                task.record_answer(q.summary.clone(), answer);
837                task.unblock(&id);
838                changed = true;
839            }
840        }
841        if changed {
842            record(queue, &mut task);
843        }
844    }
845}
846
847/// The `hold_reason` of a task whose conductor question went unanswered.
848fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
849    if crate::lang::is_japanese(language) {
850        format!(
851            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
852            q.short(),
853            q.summary
854        )
855    } else {
856        format!(
857            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
858            q.short(),
859            q.summary
860        )
861    }
862}
863
864/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
865/// for several unrelated reasons, and the waiter must not read them alike.
866#[derive(Debug, Clone, Copy, PartialEq, Eq)]
867pub(crate) enum ActionStanding {
868    /// The answer carries no action: the waiter delivers it as before.
869    NoAction,
870    /// The daemon will apply it (not applied, task idle, current attempt).
871    Pending,
872    /// Already applied (`Task::actions_applied`): the daemon has acted, so
873    /// delivering the word to the old seat would run it beside the new work.
874    Applied,
875    /// The question is about an earlier attempt than the task's latest.
876    Stale,
877    /// The task is running / blocked / done: the daemon defers for now.
878    Busy,
879}
880
881impl ActionStanding {
882    /// The daemon has acted or will act: the waiter must not deliver.
883    pub(crate) fn daemon_owns(self) -> bool {
884        matches!(self, Self::Pending | Self::Applied | Self::Stale)
885    }
886}
887
888/// Classify `q`'s chosen action against `task`. `Stale` is judged before
889/// `Busy`: a question about an earlier attempt must be stopped even while a
890/// newer competition is running.
891pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
892    if task.stale_question(q) {
893        ActionStanding::Stale
894    } else if q.chosen_action().is_none() {
895        ActionStanding::NoAction
896    } else if task.action_applied(&q.id) {
897        ActionStanding::Applied
898    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
899        ActionStanding::Stale
900    } else if matches!(
901        task.status,
902        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
903    ) {
904        ActionStanding::Busy
905    } else {
906        ActionStanding::Pending
907    }
908}
909
910/// What [`decide_action`] concluded about one answered question.
911#[derive(Debug, Clone, PartialEq, Eq)]
912enum ActionDecision {
913    /// Nothing to do now (no action, already applied, or the task is busy).
914    Skip,
915    /// Continue the named run instead of competing again.
916    Resume(String),
917    /// Requeue as a fresh competition.
918    Requeue,
919    /// Hold the task by explicit operator choice.
920    Hold,
921    /// Close the task as done.
922    Done,
923    /// The question is about an earlier attempt than the task's latest; it
924    /// is recorded as handled and changes nothing.
925    Stale,
926    /// The action cannot be carried out; hold the task and say why. Never
927    /// falls back to something else, because the operator chose this one.
928    Refuse(String),
929}
930
931/// Decide what the choice answered on `q` means for `task`. `load` reads a
932/// run's state, as with [`unfinished_run_with`]. `home` must name that same
933/// store for driver leases and question checkpoints.
934///
935/// `Resume` only fires on the task's *latest* run, and only while that run
936/// could actually make progress ([`RunStatus::resumable`], not released, review
937/// budget left); an answer naming anything else is refused rather than
938/// reinterpreted as a fresh competition.
939fn decide_action<F>(
940    home: &Path,
941    task: &Task,
942    q: &ask::Question,
943    p: &Phrases,
944    load: F,
945) -> ActionDecision
946where
947    F: FnOnce(&str) -> Result<RunState>,
948{
949    if task.stale_question(q) {
950        return ActionDecision::Stale;
951    }
952    let Some(action) = q.chosen_action() else {
953        return ActionDecision::Skip;
954    };
955    if task.action_applied(&q.id)
956        || matches!(
957            task.status,
958            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
959        )
960    {
961        return ActionDecision::Skip;
962    }
963    // A question about an earlier attempt must not act on a newer one. A
964    // conductor question is keyed by the task id, not a run, so it is exempt.
965    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
966        return ActionDecision::Stale;
967    }
968    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
969    let stopping = q.node == land::APPROVAL_NODE
970        && q.resolution()
971            .as_deref()
972            .is_some_and(crate::merge_decision::stops);
973    // An answer is the owner's decision as of when it was given: a manual hold
974    // placed before it (even after the question was asked) was seen and
975    // overruled by it, while a hold or release after it supersedes it.
976    let decision_at = q.answered_at.unwrap_or(q.asked_at);
977    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
978        return if repair || stopping {
979            ActionDecision::Refuse(format!(
980                "{} 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 {}`",
981                if repair { "repair" } else { "stop" },
982                q.id,
983                q.run,
984                task.id
985            ))
986        } else {
987            ActionDecision::Stale
988        };
989    }
990    match action {
991        a if a.maintenance() => ActionDecision::Skip,
992        ask::ChoiceAction::RecoverBase { .. }
993        | ask::ChoiceAction::ResumeRun { .. }
994        | ask::ChoiceAction::ReleaseTask { .. }
995        | ask::ChoiceAction::RerunChecks { .. }
996        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
997        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
998        ask::ChoiceAction::Hold => ActionDecision::Hold,
999        ask::ChoiceAction::Done => ActionDecision::Done,
1000        ask::ChoiceAction::Resume { run } => {
1001            if task.execution_runs().last() != Some(run) {
1002                return ActionDecision::Refuse((p.resume_not_latest)(
1003                    q.short(),
1004                    ask::short_id(run),
1005                ));
1006            }
1007            match load(run) {
1008                Ok(s) if stopping => {
1009                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1010                        || !s
1011                            .land_approval
1012                            .as_ref()
1013                            .is_some_and(|binding| binding.question == q.id)
1014                    {
1015                        ActionDecision::Stale
1016                    } else if s.liveness_under(home, false) == Liveness::Live {
1017                        ActionDecision::Skip
1018                    } else if s.status == RunStatus::Landing
1019                        && !s.released()
1020                        && s.retired_to.is_none()
1021                    {
1022                        ActionDecision::Resume(run.clone())
1023                    } else {
1024                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1025                    }
1026                }
1027                Ok(s)
1028                    if q.node == land::APPROVAL_NODE
1029                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1030                {
1031                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1032                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1033                    {
1034                        // A live/manual driver already consumed or superseded
1035                        // this answer. Do not hold its fresh approval wait.
1036                        ActionDecision::Stale
1037                    } else if s.liveness_under(home, false) == Liveness::Live {
1038                        ActionDecision::Skip
1039                    } else if s.status != RunStatus::Landing
1040                        || s.released()
1041                        || s.reviews.is_empty()
1042                        || !implementers_match(task, &s)
1043                        || !s
1044                            .land_approval
1045                            .as_ref()
1046                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1047                    {
1048                        ActionDecision::Refuse(format!(
1049                            "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",
1050                            q.id, run, run
1051                        ))
1052                    } else {
1053                        ActionDecision::Resume(run.clone())
1054                    }
1055                }
1056                Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1057                    ActionDecision::Refuse("run already has a live driver".into())
1058                }
1059                Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1060                    None => ActionDecision::Resume(run.clone()),
1061                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1062                        q.short(),
1063                        ask::short_id(run),
1064                        &reason.diagnostic(&s),
1065                    )),
1066                },
1067                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1068                    q.short(),
1069                    ask::short_id(run),
1070                    &format!("{e:#}"),
1071                )),
1072            }
1073        }
1074    }
1075}
1076
1077/// The fixed prose the daemon writes into [`Task::last_error`] and
1078/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1079/// `triage::Wording` and `land::Words`: only English and Japanese are
1080/// translated, anything else falls back to English.
1081///
1082/// Rendered when the reason is *generated*, so a reason keeps the language it
1083/// was written in if the setting changes later. The notification frame
1084/// (`Task <id> is held:`) is not here and stays English.
1085///
1086/// Deliberately **not** translated, because other code reads them back by
1087/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1088/// and `gate red`. IDs, node names, paths and external error text are embedded
1089/// as they are.
1090struct Phrases {
1091    /// `{}` = status label, then the detail.
1092    graph_stopped: fn(&str, &str) -> String,
1093    quorum_lost: &'static str,
1094    /// Followed by the seats' names.
1095    quota_took_out: &'static str,
1096    /// Followed by the status label.
1097    run_ended: &'static str,
1098    /// Followed by the question's short id.
1099    waiting_for_answer: &'static str,
1100    recovered_running: &'static str,
1101    no_run_to_recover: &'static str,
1102    could_not_start: &'static str,
1103    resume_not_latest: fn(&str, &str) -> String,
1104    resume_cannot_progress: fn(&str, &str, &str) -> String,
1105    resume_unreadable: fn(&str, &str, &str) -> String,
1106    /// A takeover refusal: the operator-facing text. English is the error's own
1107    /// `Display`; a translation keeps the machine detail apart in parentheses.
1108    handover_refused: fn(&crate::handover::Refused) -> String,
1109    /// Appended to a refused handover's hold reason (leading space included).
1110    handover_hint: &'static str,
1111    /// (seats that never answered, review rounds) for the review loop's
1112    /// "refusing to call it clean" stop.
1113    reviewers_never_answered: fn(usize, usize) -> String,
1114}
1115
1116const PHRASES_EN: Phrases = Phrases {
1117    graph_stopped: |status, detail| {
1118        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1119    },
1120    quorum_lost: "the judging panel lost its quorum",
1121    quota_took_out: "; quota took out ",
1122    run_ended: "run ended ",
1123    waiting_for_answer: " - waiting for operator answer to question ",
1124    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1125    no_run_to_recover: "task was `running` with no live daemon and no readable \
1126                        run to recover; held for a human to check what happened",
1127    could_not_start: "could not start the run: ",
1128    resume_not_latest: |q, run| {
1129        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1130    },
1131    resume_cannot_progress: |q, run, reason| {
1132        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1133    },
1134    resume_unreadable: |q, run, e| {
1135        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1136    },
1137    handover_refused: |r| r.to_string(),
1138    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1139    reviewers_never_answered: |missing, rounds| {
1140        format!(
1141            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1142             refusing to call it clean"
1143        )
1144    },
1145};
1146
1147const PHRASES_JA: Phrases = Phrases {
1148    graph_stopped: |status, detail| {
1149        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1150    },
1151    quorum_lost: "審査パネルが定足数を失いました",
1152    quota_took_out: "。クォータで脱落: ",
1153    run_ended: "run 終了: ",
1154    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1155    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1156    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1157                        何が起きたか人が確認するため保留にしました",
1158    could_not_start: "run を開始できませんでした: ",
1159    resume_not_latest: |q, run| {
1160        format!(
1161            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1162        )
1163    },
1164    resume_cannot_progress: |q, run, reason| {
1165        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1166    },
1167    resume_unreadable: |q, run, e| {
1168        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1169    },
1170    handover_refused: |r| {
1171        use crate::handover::Refused;
1172        match r {
1173            Refused::Foreign { branch, path, why } => format!(
1174                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1175                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1176                 から、やり直してください(詳細: {why})"
1177            ),
1178            Refused::Unsafe { branch, path, why } => format!(
1179                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1180                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1181                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1182            ),
1183            Refused::ReleaseFailed { branch, path, run } => format!(
1184                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1185                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1186                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1187            ),
1188        }
1189    },
1190    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1191    reviewers_never_answered: |missing, rounds| {
1192        format!(
1193            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1194             クリーンとは認めません"
1195        )
1196    },
1197};
1198
1199fn phrases(language: &str) -> &'static Phrases {
1200    if crate::lang::is_japanese(language) {
1201        &PHRASES_JA
1202    } else {
1203        &PHRASES_EN
1204    }
1205}
1206
1207/// The language of the repository a task belongs to, read best-effort for the
1208/// paths that have no run (and so no config of their own) to ask. An unreadable
1209/// config is English, not an error: a hold reason must still get written.
1210fn language_of(task: &Task, fallback: &Path) -> String {
1211    crate::lang::of_repo(&repo_for(task, fallback))
1212}
1213
1214/// The task an answered question speaks for: the one whose runs include the
1215/// question's run, or - for a conductor question, filed under the task's own
1216/// id - the task with that id.
1217pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1218    if q.node == crate::conduct::NODE {
1219        return tasks.iter().find(|t| t.id == q.run);
1220    }
1221    tasks.iter().find(|t| t.runs.contains(&q.run))
1222}
1223
1224/// Legacy conductor prose never becomes a maintenance command by inference.
1225/// Replace unsupported open labels under the question lock before dispatch.
1226fn repair_choice_offers(questions: &Questions) {
1227    let ownership = crate::task_chat::InquiryOwnership::default();
1228    for q in questions
1229        .list_for_effects_in(&ownership)
1230        .into_iter()
1231        .filter(|q| {
1232            q.status.open()
1233                && q.node == crate::conduct::NODE
1234                && q.choices
1235                    .iter()
1236                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1237        })
1238    {
1239        let _ = questions.update_in(&q.id, &ownership, |current| {
1240            if current.status.open() {
1241                crate::choice_effect::executable_conductor(current);
1242                if let Some(deputy) = &mut current.deputy {
1243                    deputy.brief = crate::deputy::brief(
1244                        &current.run,
1245                        &current.detail,
1246                        &current.choices,
1247                        &current.actions,
1248                    );
1249                }
1250            }
1251            Ok(())
1252        });
1253    }
1254}
1255
1256/// Apply answered typed choices. Only the daemon calls this in production;
1257/// deputies settle the question and never execute its actions.
1258pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1259    apply_maintenance_choices(queue, questions, home).await;
1260    apply_task_choice_actions(queue, questions, home);
1261}
1262
1263/// Apply bounded maintenance effects independently of question ownership: a
1264/// release watcher need not have a queue task, and a predecessor is another run.
1265async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1266    let ownership = crate::task_chat::InquiryOwnership::default();
1267    for q in questions.list_for_effects_in(&ownership) {
1268        // Read again under the same fence used by explicit settlement.
1269        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1270            continue;
1271        };
1272        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1273            continue;
1274        };
1275        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1276            continue;
1277        };
1278        // Receipt paths use question IDs, whose format is independent of run
1279        // IDs. Apply the question store's filename safety rule to both eras.
1280        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1281            continue;
1282        }
1283        if queue.list().iter().any(|task| {
1284            (task.id == q.run
1285                || task.runs.contains(&q.run)
1286                || q.routed_task.as_deref() == Some(&task.id))
1287                && task.stale_question(&q)
1288        }) {
1289            continue;
1290        }
1291        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1292            let tasks = queue.list();
1293            let owner = crate::task_chat::task_of(&q, &tasks);
1294            if let Some(owner) = owner
1295                && q.routed_task
1296                    .as_deref()
1297                    .is_none_or(|routed| routed == owner)
1298            {
1299                let result = crate::base_recovery_control::recover(
1300                    queue,
1301                    home,
1302                    crate::base_recovery_control::Request {
1303                        run: run.clone(),
1304                        head: stop.head.clone(),
1305                        actor: "decisions".into(),
1306                        request: q.id.clone(),
1307                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1308                        expected_stop: Some((stop.clone(), *episode)),
1309                    },
1310                )
1311                .await;
1312                if let Err(error) = result {
1313                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1314                    notices::raise_in(home, Notice::warn(
1315                        &format!("base-recovery:{}", q.id),
1316                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1317                    ).link(Link::Run { id: run.clone() }));
1318                }
1319            }
1320            continue;
1321        }
1322        let dir = home.join("choice-actions");
1323        if std::fs::create_dir_all(&dir).is_err() {
1324            continue;
1325        }
1326        let Ok(lock) = std::fs::OpenOptions::new()
1327            .create(true)
1328            .truncate(false)
1329            .write(true)
1330            .open(dir.join(format!("{}.lock", q.id)))
1331        else {
1332            continue;
1333        };
1334        if crate::pr_head::try_lock_file(&lock).is_err() {
1335            continue;
1336        }
1337        let fresh = !home
1338            .join("choice-actions")
1339            .join(format!("{}.json", q.id))
1340            .exists();
1341        let result = async {
1342            let receipt = dir.join(format!("{}.json", q.id));
1343            if receipt.exists() {
1344                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1345                anyhow::ensure!(
1346                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1347                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1348                );
1349                return Ok::<_, anyhow::Error>(());
1350            }
1351            // Never retry an uncertain external effect. The receipt is written
1352            // before calling gh, exactly like release_watch's rerun record.
1353            let record = |status: &str| -> anyhow::Result<()> {
1354                let tmp = receipt.with_extension("tmp");
1355                std::fs::write(
1356                    &tmp,
1357                    serde_json::to_vec(&serde_json::json!({
1358                        "action": action, "status": status,
1359                    }))?,
1360                )?;
1361                std::fs::rename(tmp, &receipt)?;
1362                Ok(())
1363            };
1364            let applied = async {
1365                match action {
1366                    ask::ChoiceAction::ResumeRun { run } => {
1367                        crate::resume::validate(home, run)?;
1368                        record("started")?;
1369                        let decided = q.answered_at.unwrap_or(q.asked_at);
1370                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1371                            crate::resume::validate_unqueued(home, run)?;
1372                            crate::resume::start(home, run.clone()).await?;
1373                        }
1374                    }
1375                    ask::ChoiceAction::ReleaseTask {
1376                        task,
1377                        held_at,
1378                        reason,
1379                    } => {
1380                        anyhow::ensure!(
1381                            queue.resolve_id(task)? == *task,
1382                            "task action requires an exact task ID"
1383                        );
1384                        let _claim = queue.claim(task)?;
1385                        let mut task = queue.get(task)?;
1386                        if task.action_applied(&q.id) {
1387                            return Ok(());
1388                        }
1389                        // Filing this conductor question temporarily wraps the
1390                        // original hold in a Blocked state. Restore only that
1391                        // exact blocker on the local copy before checking the
1392                        // hold binding; unrelated waits never authorize release.
1393                        if q.node == crate::conduct::NODE
1394                            && q.run == task.id
1395                            && task.status == TaskStatus::Blocked
1396                            && task.blocked_from == Some(TaskStatus::Held)
1397                            && task.blocked_by.as_slice() == [q.id.as_str()]
1398                        {
1399                            task.unblock(&q.id);
1400                        }
1401                        anyhow::ensure!(
1402                            task.status == TaskStatus::Held
1403                                && task.held_at == Some(*held_at)
1404                                && task.hold_reason.as_deref() == reason.as_deref()
1405                                && task
1406                                    .operator_decided_at
1407                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1408                            "task no longer has the hold this question names"
1409                        );
1410                        task.release_operator("choice", Some(&q.id));
1411                        task.mark_action_applied(&q.id);
1412                        queue.put(&mut task)?;
1413                    }
1414                    ask::ChoiceAction::AbandonRun { run } => {
1415                        record("started")?;
1416                        crate::driver::abandon_proven_dead(home, run)?;
1417                    }
1418                    ask::ChoiceAction::RerunChecks {
1419                        repo,
1420                        pr,
1421                        head,
1422                        runs,
1423                    } => {
1424                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1425                            .await?;
1426                    }
1427                    _ => unreachable!(),
1428                }
1429                Ok::<_, anyhow::Error>(())
1430            }
1431            .await;
1432            match applied {
1433                Ok(()) => record("applied"),
1434                Err(e) => {
1435                    record(&format!("refused or failed: {e:#}"))?;
1436                    Err(e)
1437                }
1438            }
1439        }
1440        .await;
1441        // Retire the originating blocker as well as the target operation.
1442        // A foreign resume leaves its issuer held instead of competing beside
1443        // the execution just started. Other successful maintenance lets the
1444        // original task retry its normal, guarded path.
1445        if home
1446            .join("choice-actions")
1447            .join(format!("{}.json", q.id))
1448            .exists()
1449            && let Some(listed) = task_of_question(&queue.list(), &q)
1450            && !listed.action_applied(&q.id)
1451            && let Ok(_claim) = queue.claim(&listed.id)
1452            && let Ok(mut origin) = queue.get(&listed.id)
1453        {
1454            if !origin.operator_held()
1455                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1456                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1457            {
1458                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1459                    origin.hold_machine(Some(format!(
1460                        "Maintenance choice {} settled; inspect its target before releasing this task",
1461                        q.id
1462                    )));
1463                } else {
1464                    origin.unblock(&q.id);
1465                }
1466            }
1467            origin.mark_action_applied(&q.id);
1468            let _ = queue.put(&mut origin);
1469        }
1470        if let Err(e) = result
1471            && fresh
1472        {
1473            notices::raise_in(
1474                home,
1475                Notice::warn(
1476                    &format!("action:{}", q.id),
1477                    format!("Choice action {} was not completed: {e:#}", q.id),
1478                )
1479                .link(if q.run_names_task() {
1480                    Link::Task { id: q.run.clone() }
1481                } else {
1482                    Link::Run { id: q.run.clone() }
1483                }),
1484            );
1485        }
1486    }
1487}
1488
1489/// Rerun the named failed workflow runs of a pull request, each at most once
1490/// per `request` (a question id, or a chat operation identity). The head,
1491/// lifecycle and failed state are re-read from the forge first; `started` is
1492/// called once those checks pass and before the first external call, and the
1493/// ledger entry is written before every `gh` call, so an uncertain result is
1494/// never repeated automatically.
1495pub(crate) async fn rerun_checks_once(
1496    home: &Path,
1497    request: &str,
1498    repo: &Path,
1499    pr: &str,
1500    head: &str,
1501    runs: &[String],
1502    started: impl FnOnce() -> anyhow::Result<()>,
1503) -> anyhow::Result<()> {
1504    use crate::release_watch::{GhForge, ReleaseForge};
1505    anyhow::ensure!(
1506        !runs.is_empty()
1507            && runs.len() <= 20
1508            && runs
1509                .iter()
1510                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1511            && !pr.starts_with('-'),
1512        "invalid rerun targets"
1513    );
1514    let snap = GhForge.snapshot(repo, pr).await?;
1515    anyhow::ensure!(
1516        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1517        "pull request head or lifecycle changed"
1518    );
1519    anyhow::ensure!(
1520        runs.iter().all(|r| snap
1521            .checks
1522            .iter()
1523            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1524        "named workflow is no longer failed on this pull request"
1525    );
1526    started()?;
1527    let dir = home.join("choice-actions");
1528    std::fs::create_dir_all(&dir)?;
1529    let rerun_lock = std::fs::OpenOptions::new()
1530        .create(true)
1531        .truncate(false)
1532        .write(true)
1533        .open(dir.join("reruns.lock"))?;
1534    crate::pr_head::try_lock_file(&rerun_lock)?;
1535    let ledger = dir.join("reruns.json");
1536    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1537        serde_json::from_slice(&std::fs::read(&ledger)?)?
1538    } else {
1539        Default::default()
1540    };
1541    for run in runs {
1542        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1543        if !recorded.insert(key) {
1544            continue;
1545        }
1546        let tmp = ledger.with_extension("tmp");
1547        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1548        std::fs::rename(tmp, &ledger)?;
1549        GhForge.rerun(repo, run).await?;
1550    }
1551    Ok(())
1552}
1553
1554/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1555///
1556/// Runs on every poll before the conductor looks at the queue. The task is
1557/// re-read under its claim, so a task somebody completed or held by hand in
1558/// the meantime is judged on what it is now. `Resume` releases the task and
1559/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1560/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1561/// ordinary `unfinished_run` logic resumes that same run.
1562pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1563    let tasks = queue.list();
1564    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1565    for q in questions.list_for_effects_in(&ownership) {
1566        // Read again under the same fence used by explicit settlement.
1567        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1568            continue;
1569        };
1570        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1571            continue;
1572        };
1573        // Dismissal is committed by the question writer, never a resume.
1574        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1575            continue;
1576        }
1577        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1578            continue;
1579        }
1580        let Some(listed) = task_of_question(&tasks, &q) else {
1581            if q.node == land::APPROVAL_NODE
1582                && q.resolution().as_deref().is_some_and(|choice| {
1583                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1584                })
1585            {
1586                notices::raise_in(
1587                    home,
1588                    Notice::warn(
1589                        &format!("repair-owner:{}", q.id),
1590                        format!(
1591                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1592                            q.run, q.run
1593                        ),
1594                    ).link(Link::Run { id: q.run.clone() }),
1595                );
1596            }
1597            continue;
1598        };
1599        if listed.action_applied(&q.id) {
1600            continue;
1601        }
1602        let Ok(_claim) = queue.claim(&listed.id) else {
1603            continue;
1604        };
1605        let Ok(mut task) = queue.get(&listed.id) else {
1606            continue;
1607        };
1608        // Work only on this local copy until the action can be committed.
1609        // In particular, a fresh lease below leaves the persisted task blocked.
1610        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1611            let blockers: Vec<_> = task
1612                .blocked_by
1613                .iter()
1614                .filter(|id| {
1615                    crate::queue::dependency(queue, questions, id)
1616                        == crate::queue::Dependency::Question(q.id.clone())
1617                })
1618                .cloned()
1619                .collect();
1620            if !blockers.is_empty() {
1621                for id in blockers {
1622                    task.unblock(&id);
1623                }
1624                let answer = match &q.answer {
1625                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1626                    None => String::new(),
1627                };
1628                task.record_answer(q.summary.clone(), answer);
1629            }
1630        }
1631        let language = language_of(&task, Path::new("."));
1632        let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1633            RunState::load_under(id, home)
1634        });
1635        let completion = if matches!(decision, ActionDecision::Done) {
1636            match crate::task_completion::prepare_close(
1637                &task,
1638                home,
1639                CompletionActor::DaemonSettle,
1640                Some(format!(
1641                    "Question {}: {} — {}",
1642                    q.id,
1643                    q.summary,
1644                    q.resolution().unwrap_or_default()
1645                )),
1646                false,
1647            ) {
1648                Ok(context) => Some(context),
1649                Err(error) => {
1650                    decision = ActionDecision::Refuse(error.to_string());
1651                    None
1652                }
1653            }
1654        } else {
1655            None
1656        };
1657        let ran = matches!(
1658            decision,
1659            ActionDecision::Resume(_)
1660                | ActionDecision::Requeue
1661                | ActionDecision::Hold
1662                | ActionDecision::Done
1663        );
1664        if ran && asker_may_still_read(questions, &q, home) {
1665            // The asking process or its seat can still take the word; act
1666            // once it has gone quiet. Bound on the remaining window: the
1667            // check is not atomic with the write below, so an asker that
1668            // takes the word in between (at most one poll, never more than
1669            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1670            // and `Task::actions_applied` under the claim keeps the action to
1671            // one application. The waiter does not deliver an answer that
1672            // carries an action (`waiter::decide_owned`), so it cannot race.
1673            continue;
1674        }
1675        let done = matches!(decision, ActionDecision::Done);
1676        // Resume owes an execution pass; only these task-local effects finish
1677        // in this write. Stale/refused actions never acquire an effect receipt.
1678        let completed = matches!(
1679            decision,
1680            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1681        );
1682        match decision {
1683            ActionDecision::Skip => continue,
1684            ActionDecision::Resume(run) => {
1685                task.release_operator("choice", Some(&q.id));
1686                task.resume_override = Some(crate::queue::OperatorResume {
1687                    question_id: q.id.clone(),
1688                    at: Timestamp::now(),
1689                    conductor_rehold: None,
1690                    forced: true,
1691                    pinned_run: Some(run),
1692                });
1693            }
1694            ActionDecision::Stale => {}
1695            ActionDecision::Requeue => {
1696                task.release_operator("choice-requeue", Some(&q.id));
1697                task.requeue();
1698            }
1699            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1700            ActionDecision::Done => {
1701                task.succeed(completion.expect("done passed completion admission"));
1702            }
1703            ActionDecision::Refuse(why) => {
1704                let _ =
1705                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1706                if task.operator_held() {
1707                    // A rejected answer does not release the operator's hold
1708                    // or reclassify it as recoverable by the conductor.
1709                    task.hold_reason = Some(match task.hold_reason.take() {
1710                        Some(reason) => format!("{reason}\n\n{why}"),
1711                        None => why,
1712                    });
1713                } else {
1714                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1715                    task.hold_machine(Some(why));
1716                }
1717                notices::raise(
1718                    Notice::warn(
1719                        &format!("action:{}", q.id),
1720                        "An answered task action could not be applied; the task stays held.",
1721                    )
1722                    .link(Link::Task {
1723                        id: task.id.clone(),
1724                    }),
1725                );
1726            }
1727        }
1728        task.mark_action_applied(&q.id);
1729        if completed {
1730            task.decision_effects.insert(
1731                q.id.clone(),
1732                format!("decision: {}", q.resolution().expect("answered action")),
1733            );
1734        }
1735        // The applied id travels with the transition, so a failed save loses
1736        // neither and the answer is acted on at the next poll.
1737        record(queue, &mut task);
1738        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1739            supersede_prior_runs(&task, home);
1740        }
1741        // Delivery is only a note of who has read the answer; the task's own
1742        // mark above is the authority. Best effort.
1743        let _ = questions.update_in(&q.id, &ownership, |r| {
1744            r.answer_delivered = true;
1745            Ok(())
1746        });
1747    }
1748}
1749
1750/// Whether something may still read the answer to `q`: a fresh lease, or the
1751/// asking seat still listed as active in its run (its CLI can outlive the
1752/// `magi ask` that was killed).
1753fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1754    let now = Timestamp::now();
1755    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1756        return true;
1757    }
1758    q.node != crate::conduct::NODE
1759        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1760            s.seats_active()
1761                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1762        })
1763}
1764
1765/// Retire an unanswered conductor question after its task no longer refers to
1766/// it. Conductor questions use the task id in `Question::run`, so run-based
1767/// cleanup cannot observe a manual release or completion.
1768///
1769/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1770/// own question also carries a `run`, and a run id that happens to collide
1771/// with some task's id is not this loop's business — only a conductor
1772/// question actually uses the task id that way. One `Questions::list()` scan
1773/// is taken up front and matched against the in-memory task set, rather than
1774/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1775fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1776    let tasks = queue.list();
1777    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1778    let by_id: std::collections::BTreeMap<&str, &Task> =
1779        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1780    let referenced: Vec<&str> = tasks
1781        .iter()
1782        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1783        .collect();
1784
1785    for mut question in questions.list_for_effects_in(&ownership) {
1786        if !question.status.open()
1787            || question.node != crate::conduct::NODE
1788            || questions.held_reply_in(&question.id, &ownership)
1789        {
1790            continue;
1791        }
1792        // Keep questions a task still names, including when the reference
1793        // moved to a dependent task.
1794        // Preserve even ambiguous references: retiring a possibly referenced
1795        // question is unsafe until the operator disambiguates it.
1796        if referenced
1797            .iter()
1798            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1799        {
1800            continue;
1801        }
1802        let Some(task) = by_id.get(question.run.as_str()) else {
1803            continue;
1804        };
1805        question.abandon(format!(
1806            "task {} no longer waits for this answer",
1807            task.short()
1808        ));
1809        if let Err(e) = questions.put_in(&mut question, &ownership) {
1810            tracing::warn!(
1811                "could not retire question {} for task {}: {e:#}",
1812                question.short(),
1813                task.short()
1814            );
1815        }
1816    }
1817}
1818
1819/// What a finished run tells the queue about the task it came from.
1820///
1821/// A struct rather than a fourth and fifth boolean argument: the two flags
1822/// answer different questions about the same run, and a call site passing
1823/// `(…, true, false)` is one transposition away from refunding attempts
1824/// forever.
1825#[derive(Debug, Clone, Copy)]
1826pub struct Verdict {
1827    /// Where the graph stopped.
1828    pub status: RunStatus,
1829    /// The run opened a pull request.
1830    pub left_pr: bool,
1831    /// At least one seat was lost to a rate limit.
1832    pub quota_hit: bool,
1833    /// The run parked at a node boundary because it was asked to.
1834    pub parked: bool,
1835    /// The run never produced a single candidate a judge could look at.
1836    ///
1837    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1838    /// still have another candidate worth judging, in which case the loss was
1839    /// not the reason nothing came of the run. This is `true` only when the
1840    /// implement wave ended with nothing viable at all.
1841    pub no_viable_candidates: bool,
1842}
1843
1844/// Record a finished run against the task it came from.
1845///
1846/// Kept pure and separate from the loop because this mapping *is* the retry
1847/// policy, and a policy that can only be exercised by spawning a graph is a
1848/// policy nobody checks. The table:
1849///
1850/// | run status                           | task becomes        | attempt spent |
1851/// |---------------------------------------|---------------------|---------------|
1852/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1853/// | `Merged`, `Ready`                      | `Done`               | yes          |
1854/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1855/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1856/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1857/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1858/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1859/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1860/// | `Blocked` with a PR                    | `Held`               | yes          |
1861/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1862/// | `VerifiedNoop`                          | `Held`               | yes          |
1863/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1864///
1865/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1866/// deliberately: every candidate agreeing there is nothing to write is not a
1867/// machine fact about a rate limit, it is an unverified claim about the
1868/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1869/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1870/// claim could be wrong (a misread instruction, a stale check), and closing
1871/// the task automatically on an implementer's say-so would be the exact
1872/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1873/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1874/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1875/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1876/// claim regardless of whether the one already-spent attempt is refunded, and
1877/// [`Task::release`] resets the count to zero anyway the moment a human looks
1878/// at the evidence and lets it run again.
1879///
1880/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1881/// twice, together. A quorum lost to rate limits is a property of the machine
1882/// and not of the task, so the attempt is refunded and a reset quota picks
1883/// the work up where it stopped — and that is just as true when every
1884/// implement seat lost the same race and `after_implement` bails with nothing
1885/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1886/// machine fact. The `no_viable_candidates` guard is what keeps that row
1887/// narrow: a `Failed` run that produced a real candidate which then lost for
1888/// some other reason still spends the attempt, exactly like the quorum lost
1889/// to judges that answered with the wrong shape is ordinary flakiness, and
1890/// refunding *that* takes the bound off the retry loop entirely: run e633
1891/// stalled with `quota: []` after two judges wrote unusable JSON, was
1892/// refunded, and the next attempt paid for a fresh hour-long implement wave
1893/// before it could fail the same way. `max_attempts` exists precisely so
1894/// that cannot repeat forever.
1895///
1896/// A non-terminal status means `execute` returned while the graph was still
1897/// mid-flight, which is a bug rather than a verdict; it is treated as a
1898/// failure so that a task cannot loop on it either.
1899///
1900/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1901/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1902pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1903    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
1904}
1905
1906/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1907fn settle_in(
1908    task: &mut Task,
1909    verdict: Verdict,
1910    detail: &str,
1911    max_attempts: usize,
1912    p: &Phrases,
1913    state: Option<&RunState>,
1914) {
1915    // A parked run is the operator's own doing, and its work is intact on
1916    // disk. The task goes back in line with its attempt refunded so the next
1917    // loop resumes the same run - which `one_task` prefers over competing
1918    // again - and so that swapping the binary a few times cannot exhaust a
1919    // budget meant for agents that actually misbehaved.
1920    if verdict.parked {
1921        task.park(detail);
1922        return;
1923    }
1924    let completion = |task: &Task| match state {
1925        Some(state) => CompletionContext::from_run(
1926            CompletionActor::DaemonSettle,
1927            Some(detail.to_owned()),
1928            task,
1929            state,
1930        ),
1931        None => CompletionContext::new(
1932            CompletionActor::DaemonSettle,
1933            Some(detail.to_owned()),
1934            &crate::run::home(),
1935            task,
1936        ),
1937    };
1938    match verdict.status {
1939        RunStatus::Merged | RunStatus::Ready
1940            if task.pr_recovery.as_ref().is_some_and(|s| {
1941                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1942            }) =>
1943        {
1944            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()));
1945        }
1946        RunStatus::Merged | RunStatus::Ready => task.succeed(completion(task)),
1947        RunStatus::AlreadyInBase => task.already_landed(detail, completion(task)),
1948        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1949        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1950            task.stall(detail)
1951        }
1952        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1953        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1954        RunStatus::Blocked => task.fail(detail, max_attempts),
1955        RunStatus::VerifiedNoop => task.handed_off(detail),
1956        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1957    }
1958}
1959
1960/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1961/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1962/// itself has actually finished *and* its own last attempt is provably why:
1963/// this loads that run and requires `Merged`/`Ready` before touching
1964/// anything earlier in `runs`, since `Task::succeed` can also be called
1965/// directly on a task whose last attempt never landed at all.
1966///
1967/// Called right after whatever call set `task.status` to
1968/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1969/// `reclaim`'s, but also every other place a task can be closed by hand
1970/// without the loop ever settling it itself: `magi task done`
1971/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1972/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1973/// GitHub merge, say, exactly the workflow this repository's own
1974/// "Landing a run's winner by hand" documents — is just as much "this task's
1975/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1976/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1977/// forever, which is the exact backlog this status exists to clear. `pub`
1978/// for those two out-of-module callers; everything else about this stays
1979/// internal bookkeeping.
1980///
1981/// A run something is still actually driving is left alone: a
1982/// task cannot be `Done` while one of its *own* attempts is still in flight,
1983/// so a live one at this point can only be an unrelated process — a manual
1984/// `--resume` of this old, now-moot run — and rewriting under it would just
1985/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1986/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1987/// pair `run_report`/`run_detail` use for the same question elsewhere:
1988/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1989/// --resume` invoked by hand outside it, which `liveness` also checks via
1990/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1991/// (already terminal in some other way, or itself mid-run) is left untouched
1992/// too.
1993///
1994/// Best-effort, like the rest of this module's bookkeeping: a load or save
1995/// failure here is a `tracing::warn`, not a failed settle, and the next time
1996/// this same task's completion is recorded — or a daemon restart replays
1997/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1998/// separate reconciliation pass; if that gap ever matters in practice, one
1999/// can be added then.
2000///
2001/// `home` is a parameter, not the process-global [`crate::run::home`], for
2002/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
2003/// calls this with `ui.home`, which is `crate::run::home()` in a real
2004/// process but a fixture's own directory under test — falling through to
2005/// the global there would read and write through whichever home some other
2006/// test in the same binary happened to pin into that `OnceLock` first, not
2007/// the run this call actually means.
2008pub fn supersede_prior_runs(task: &Task, home: &Path) {
2009    if task
2010        .completion_history
2011        .last()
2012        .is_some_and(|event| event.discard)
2013    {
2014        return;
2015    }
2016    let now = Timestamp::now();
2017    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
2018    // right behind a `Merged`/`Ready` verdict) from one set directly by
2019    // `magi task done`/its web equivalent/the conductor on a task whose last
2020    // recorded attempt never actually landed - that requires reading the
2021    // run itself, which is exactly what this does before trusting anything
2022    // in `runs` is safe to relabel.
2023    let last_run_succeeded = task
2024        .runs
2025        .last()
2026        .and_then(|id| RunState::load_under(id, home).ok())
2027        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2028    for id in task.superseded_attempts(last_run_succeeded) {
2029        let mut state = match RunState::load_under(id, home) {
2030            Ok(s) => s,
2031            Err(e) => {
2032                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2033                continue;
2034            }
2035        };
2036        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2037            continue;
2038        }
2039        let daemon_claims = is_working_on(home, id, now);
2040        if state.liveness(daemon_claims) == Liveness::Live {
2041            continue;
2042        }
2043        state.status = RunStatus::Superseded;
2044        if let Err(e) = state.save_under(home) {
2045            tracing::warn!("could not mark run {id} superseded: {e:#}");
2046        }
2047    }
2048}
2049
2050/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
2051/// finish the moment it was called, because one of its earlier attempts was
2052/// still live then - a `magi run --resume` invoked by hand on an old run,
2053/// most likely.
2054///
2055/// That skip is correct at the time (rewriting under a run something is
2056/// still actively saving would just be undone), but recording a completion
2057/// does not schedule another settlement, so without this nothing would look at it
2058/// again: if that manual process later ends anywhere other than
2059/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2060/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2061/// backlog this status exists to clear. Called on the same idle-only
2062/// cadence as [`janitor`], next to it rather than folded into it: this
2063/// walks `queue` and `janitor` never otherwise needs one.
2064///
2065/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2066/// more than one attempt, every pass: each call is a handful of local file
2067/// reads bounded by that task's own attempt count, the same order of cost
2068/// [`clean::fold_due`] already pays scanning every run on disk on the same
2069/// cadence, and a task already fully resolved costs one failed liveness
2070/// check turned no-op the moment its lingering attempt is no longer live.
2071fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2072    for task in queue.list() {
2073        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2074            continue;
2075        }
2076        supersede_prior_runs(&task, home);
2077    }
2078}
2079
2080/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2081/// task ends up held.
2082///
2083/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2084/// dead daemon never got back to) share this, so the two cannot drift into
2085/// disagreeing about which held tasks get a diagnostic.
2086fn settle_and_diagnose(
2087    task: &mut Task,
2088    verdict: Verdict,
2089    detail: &str,
2090    max_attempts: usize,
2091    state: &RunState,
2092) {
2093    let p = phrases(&state.config.graph.language);
2094    // Shared by normal completion and crash recovery, under the task claim.
2095    // No new attempt can own the task until the old driver has exited.
2096    if let Some(d) = &state.merge_decision {
2097        use crate::merge_decision as md;
2098        if task
2099            .execution_runs()
2100            .last()
2101            .is_some_and(|id| id != &state.id)
2102        {
2103            return;
2104        }
2105        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2106            task.succeed(CompletionContext::from_run(
2107                CompletionActor::DaemonSettle,
2108                Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2109                task,
2110                state,
2111            ));
2112        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2113            if state.liveness(false) != Liveness::Dead {
2114                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2115                return;
2116            }
2117            let replacement = md::Replacement {
2118                question: d.question.clone(),
2119                run: state.id.clone(),
2120                pr: d.target.pr.clone(),
2121                agent: agent.to_owned(),
2122                context: format!(
2123                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2124                    d.target.pr,
2125                    state.id,
2126                    serde_json::to_string(&state.reviews).unwrap_or_default()
2127                ),
2128            };
2129            task.requeue();
2130            task.pr_recovery = None;
2131            task.review_of = None;
2132            task.replacement = Some(replacement);
2133        } else {
2134            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2135                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2136            } 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())) }));
2137        }
2138        task.mark_action_applied(&d.question);
2139        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2140            task.decision_effects
2141                .insert(d.question.clone(), format!("decision: {}", d.choice));
2142        }
2143        if let Some(pass) = state.passes.last() {
2144            task.record_pass_at(
2145                &state.id,
2146                pass.index,
2147                Some(pass.started_at),
2148                task.attempts,
2149                None,
2150            );
2151        }
2152        return;
2153    }
2154    if let Some(replacement) = &task.replacement
2155        && !state.parked
2156        && state.resource_block.is_none()
2157        && (state.viable().is_empty()
2158            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2159    {
2160        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)));
2161        return;
2162    }
2163    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2164        let mut agents: Vec<_> = state
2165            .quota
2166            .iter()
2167            .filter(|q| {
2168                q.cause == crate::agent::QuotaCause::Authentication
2169                    && state
2170                        .passes
2171                        .last()
2172                        .is_none_or(|pass| q.at >= pass.started_at)
2173            })
2174            .map(|q| q.agent.as_str())
2175            .collect();
2176        agents.sort_unstable();
2177        agents.dedup();
2178        if !agents.is_empty() {
2179            task.stall(detail);
2180            task.notice_cause("agent-authentication", None, None);
2181            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2182            return;
2183        }
2184    }
2185    let attempts_before = task.attempts;
2186    // A run that stopped because a shared resource stayed busy was never a
2187    // failure of the task or of an agent. Earlier nodes may have run; only
2188    // the blocked operation lacks a result. The attempt is
2189    // refunded and the task is held by the machine, under a reason `triage`
2190    // can re-check, so the same run resumes with the same agents once the
2191    // resource is free. A park request still wins (it is the operator's).
2192    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2193        let disk_checked_at = task.disk_checked_at;
2194        task.notice_cause(
2195            &format!("resource:{}:{}", block.kind, block.node),
2196            None,
2197            None,
2198        );
2199        task.last_error = Some(detail.to_owned());
2200        task.diagnostic = None;
2201        task.attempts = task.attempts.saturating_sub(1);
2202        if block.kind == "agent authentication" {
2203            task.hold_machine(Some(format!(
2204                "[authentication] {}; no attempt was spent",
2205                block.detail
2206            )));
2207        } else if block.kind == "agent usage limit" {
2208            // Usage limits keep the existing cooldown-and-resume policy.
2209            if let Some(agent) = &state.config.graph.selected_implementer {
2210                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.")));
2211            } else {
2212                task.status = TaskStatus::Failed;
2213                task.last_error = Some(block.detail.clone());
2214            }
2215        } else if block.kind == "disk pressure" {
2216            task.hold_machine(Some(format!(
2217                "{}{}",
2218                crate::disk::RUNNING_PRESSURE,
2219                block.detail
2220            )));
2221        } else {
2222            task.hold_machine(Some(format!(
2223                "{}{}; no attempt was spent; resume to retry the affected operation",
2224                crate::cache::RESOURCE_HOLD,
2225                block.description()
2226            )));
2227        }
2228        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2229            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2230        {
2231            task.mark_disk_capacity();
2232            task.disk_checked_at = disk_checked_at;
2233        }
2234        if let Some(pass) = state.passes.last() {
2235            task.record_pass_at(
2236                &state.id,
2237                pass.index,
2238                Some(pass.started_at),
2239                attempts_before,
2240                None,
2241            );
2242        }
2243        return;
2244    }
2245    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2246        state.parked
2247            && state.status == RunStatus::Landing
2248            && state
2249                .pr_pushed_head
2250                .as_ref()
2251                .is_none_or(|h| h == &hold.head)
2252            && task.execution_runs().last() == Some(&state.id)
2253    }) {
2254        // Settlement and crash recovery share this idempotency key. A later
2255        // explicit resume is a new pass and may refund its own attempt once.
2256        let pass = state.passes.last().map_or(0, |p| p.index);
2257        if !task
2258            .passes
2259            .iter()
2260            .any(|p| p.run == state.id && p.pass_index == pass)
2261        {
2262            task.attempts = task.attempts.saturating_sub(1);
2263        }
2264        task.hold_machine(Some(format!(
2265            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2266            hold.question
2267        )));
2268        task.last_error = Some(detail.to_owned());
2269        task.diagnostic = None;
2270        task.record_pass_at(
2271            &state.id,
2272            pass,
2273            state.passes.last().map(|p| p.started_at),
2274            attempts_before,
2275            Some(crate::run::ParkCause::Question),
2276        );
2277        return;
2278    }
2279    let unresolved = task.hold_notice_cause.clone();
2280    let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2281        .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2282    let mut reconsumed_head_e2e = false;
2283    if state.base_sync_blocked() {
2284        // No automatic retry may turn a retained sync stop into a new competition.
2285        task.hold_machine(Some(detail.to_owned()));
2286        task.last_error = Some(detail.to_owned());
2287    } else if !verdict.parked
2288        && task
2289            .pr_recovery
2290            .as_ref()
2291            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2292        && matches!(
2293            verdict.status,
2294            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2295        )
2296    {
2297        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2298            task.succeed(CompletionContext::from_run(
2299                CompletionActor::DaemonSettle,
2300                Some(detail.to_owned()),
2301                task,
2302                state,
2303            ));
2304        } else {
2305            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()));
2306        }
2307    } else if !verdict.parked
2308        && task.pr_recovery.is_some()
2309        && matches!(
2310            verdict.status,
2311            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2312        )
2313        && !verdict.quota_hit
2314    {
2315        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.")));
2316    } else if let Some(stop) = head_e2e_stop.clone() {
2317        // Conclusive current-head E2E red settles directly to one actionable
2318        // machine hold instead of cycling through runnable `Failed` passes.
2319        // Refund only when this pass provably reconsumed an earlier stop with
2320        // no new verification events, idempotently across reclaim/re-settle.
2321        if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2322            reconsumed_head_e2e = true;
2323            let pass = state.passes.last().map_or(0, |p| p.index);
2324            if !task
2325                .passes
2326                .iter()
2327                .any(|p| p.run == state.id && p.pass_index == pass)
2328            {
2329                task.attempts = task.attempts.saturating_sub(1);
2330            }
2331        }
2332        let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2333        task.hold_head_e2e(stop, reason, detail.to_owned());
2334    } else {
2335        settle_in(task, verdict, detail, max_attempts, p, Some(state));
2336    }
2337    if !verdict.parked
2338        && !verdict.quota_hit
2339        && !reconsumed_head_e2e
2340        && matches!(
2341            verdict.status,
2342            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2343        )
2344    {
2345        task.recovery_failed(state);
2346    }
2347    if state.prep_failure.is_some() {
2348        // Minting a run whose candidates could not be prepared is not work
2349        // on a newly approved attempt. Keep the unresolved outcome anchor.
2350        task.hold_notice_cause = unresolved;
2351        task.startup_notice_cause("startup-candidates");
2352    }
2353    // Written here, where the refund (or not) is decided, so the history is a
2354    // fact and not a later guess from the run's status.
2355    if let Some(pass) = state.passes.last() {
2356        let parked = match &pass.end {
2357            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2358            _ => None,
2359        };
2360        task.record_pass_at(
2361            &state.id,
2362            pass.index,
2363            Some(pass.started_at),
2364            attempts_before,
2365            parked,
2366        );
2367    }
2368    if task.status == TaskStatus::Held {
2369        if state.base_sync_blocked() {
2370            task.base_sync_notice(state);
2371        } else if let Some(stop) = &head_e2e_stop {
2372            task.head_e2e_notice(stop);
2373        } else if state.prep_failure.is_none() {
2374            task.notice_cause(
2375                label(verdict.status),
2376                Some(&state.id),
2377                state.passes.last().map(|p| p.index),
2378            );
2379        }
2380        task.diagnostic = diagnostic(state);
2381        note_open_question(task, &state.id, p);
2382    }
2383}
2384
2385/// If `task` is held with a `magi ask` question still open on `run`, name the
2386/// question in [`Task::hold_reason`] rather than leaving the hold reading
2387/// only [`describe`]'s run summary.
2388///
2389/// This is the shape task 20260928-191407-05fd left underspecified: an
2390/// implementer settled a verified no-op and filed a question for the
2391/// operator, and the hold that followed said nothing about the question
2392/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2393/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2394/// marker) and must keep seeing it unchanged.
2395///
2396/// Best-effort: an unreadable question store must not stop a run from
2397/// settling, so this is a no-op rather than a propagated error when
2398/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2399fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2400    let Some(home) = crate::run::try_home() else {
2401        return;
2402    };
2403    let open = Questions::at(home.join("questions")).open_for(run);
2404    let Some(q) = open.first() else {
2405        return;
2406    };
2407    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2408    decisions.sort_unstable();
2409    task.notice_cause(
2410        &format!("questions:{}", decisions.join(",")),
2411        Some(run),
2412        None,
2413    );
2414    let base = task.hold_reason.clone().unwrap_or_default();
2415    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2416}
2417
2418/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2419/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2420/// by some other means entirely, like a manual `magi run` resume that
2421/// finishes the graph outside the queue's bookkeeping.
2422///
2423/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2424/// `settle` is separate from `attempt`: a task recovered this way must land
2425/// exactly where a live daemon would have put it — the same policy table,
2426/// not a second one that quietly drifts from it — and that is only checkable
2427/// without spawning a real run.
2428fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2429    if let Some(request) = task.sync_only.clone() {
2430        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2431        return;
2432    }
2433    match last_run {
2434        Some(state) => {
2435            let verdict = Verdict {
2436                status: state.status,
2437                left_pr: state.pr.is_some(),
2438                quota_hit: state.quota.iter().any(|loss| {
2439                    state
2440                        .passes
2441                        .last()
2442                        .is_none_or(|pass| loss.at >= pass.started_at)
2443                }),
2444                parked: state.parked,
2445                no_viable_candidates: state.viable().is_empty(),
2446            };
2447            let detail = format!(
2448                "{}{}",
2449                phrases(&state.config.graph.language).recovered_running,
2450                describe(&state)
2451            );
2452            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2453        }
2454        None => {
2455            // No run, so no config of its own: `language` is the task's
2456            // repository's setting, read by the caller.
2457            let why = phrases(language).no_run_to_recover;
2458            task.last_error = Some(why.to_owned());
2459            // The phone shows `hold_reason`, so a task held by the machine
2460            // says why there too and not only in `last_error`.
2461            task.notice_cause("missing-run", None, None);
2462            task.hold_machine(Some(why.to_owned()));
2463        }
2464    }
2465}
2466
2467/// Find every task left at `running` that no live process is actually
2468/// driving, and settle each one against whatever its last run became.
2469///
2470/// # Why a claim is proof, not a guess
2471///
2472/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2473/// `running`, and the guard is held for the task's whole time in that status:
2474/// `attempt` does not return, and the loop does not move past the scope
2475/// holding the claim, until the run has settled. So a `running` task whose
2476/// lock is gone cannot have a live owner — this process or any other —
2477/// without needing a staleness threshold or a pid check the way
2478/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2479/// task that never got as far as `running` at all. Taking the claim here is
2480/// the whole test: it either fails, because something really does hold it
2481/// and the task is left alone, or it succeeds, which is the proof — and it is
2482/// kept for the rest of the decision so nothing else can start a competing
2483/// run while this one is being written.
2484///
2485/// Called on every poll, not only at startup, for the reason
2486/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2487/// keep noticing this, not only on the one morning it happened to restart.
2488fn reclaim_orphaned_running(
2489    queue: &Queue,
2490    max_attempts: usize,
2491    live_workers: &std::collections::BTreeSet<String>,
2492) -> Vec<String> {
2493    let mut reclaimed = Vec::new();
2494    for listed in queue.list() {
2495        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2496            continue;
2497        }
2498        let Ok(_claim) = queue.claim(&listed.id) else {
2499            continue;
2500        };
2501        // Re-read under the claim: a release or an edit landed by a human
2502        // between the listing above and the claim just taken must not be
2503        // clobbered by a decision based on the stale copy.
2504        let Ok(mut task) = queue.get(&listed.id) else {
2505            continue;
2506        };
2507        if task.status != TaskStatus::Running {
2508            continue;
2509        }
2510        let last_run = task
2511            .execution_runs()
2512            .last()
2513            .and_then(|id| RunState::load(id).ok());
2514        // `execute` normally abandons a run's own open questions the moment
2515        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2516        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2517        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2518        // with the question still `open`, because the process died before
2519        // reaching that call. `reclaim` itself stays pure on purpose (see its
2520        // own doc), so the same cleanup runs here instead, against the run
2521        // this reclaim is already reading. `settle_run` costs nothing when
2522        // `execute` already got there first.
2523        if let Some(state) = &last_run
2524            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2525        {
2526            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2527        }
2528        let language = if last_run.is_none() {
2529            language_of(&task, Path::new("."))
2530        } else {
2531            String::new()
2532        };
2533        reclaim(&mut task, last_run, max_attempts, &language);
2534        if task.status == TaskStatus::Done {
2535            supersede_prior_runs(&task, &crate::run::home());
2536        }
2537        record(queue, &mut task);
2538        reclaimed.push(task.id.clone());
2539    }
2540    reclaimed
2541}
2542
2543/// Find every run whose `run.json` is provably dead — every seat it still
2544/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2545/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2546/// not merely "no daemon claims it" — and fail it, clearing the leftover
2547/// active seats so the run stops reading as `implementing` (or whichever
2548/// node) forever.
2549///
2550/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2551/// `running`, using whatever `run.json` already says — but nothing in that
2552/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2553/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2554/// never got back to sits exactly where it was left: `active` full of seats
2555/// nobody will ever answer for, `status` stuck on whatever node was in
2556/// flight. `magi show` already tells an operator this in prose (`no live
2557/// daemon claims this run right now`); this is what makes that fact durable
2558/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2559/// stay stuck once nothing is driving it.
2560///
2561/// Runs on every poll, not only at startup, for the reason
2562/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2563/// daemon up for days must keep noticing a run some other, now-dead, daemon
2564/// left behind just as readily as one it trips over on the way up.
2565///
2566/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2567/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2568/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2569/// `runs` directory instead: `home` here is a parameter precisely so a test
2570/// can point it away from the operator's real history (see [`drive`]'s own
2571/// doc), and a scan that fell through to the global home anyway would walk
2572/// whichever directory some *other* process or test pinned into that
2573/// `OnceLock` first — mutating runs this call was never handed.
2574fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2575    reclaim_abandoned_runs_with(
2576        home,
2577        now,
2578        crate::proc::pid_status,
2579        crate::proc::process_started_at,
2580    )
2581}
2582
2583/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2584/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2585/// for the identical reason: this sweep's real damage (wiping a run's active
2586/// seats and failing it) has to be provable against an injected answer in a
2587/// test, not just the real process table.
2588fn reclaim_abandoned_runs_with<F, G>(
2589    home: &Path,
2590    now: Timestamp,
2591    query: F,
2592    identity: G,
2593) -> Vec<String>
2594where
2595    F: Fn(u32) -> Option<bool>,
2596    G: Fn(u32) -> Option<String>,
2597{
2598    let mut abandoned = Vec::new();
2599    for entry in std::fs::read_dir(home.join("runs"))
2600        .into_iter()
2601        .flatten()
2602        .flatten()
2603    {
2604        let id = entry.file_name().to_string_lossy().into_owned();
2605        if !crate::run::is_run_id(&id) {
2606            continue;
2607        }
2608        // Serialize the proof and save with claims and takeover: a new
2609        // execution must not be overwritten after the liveness observation.
2610        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2611            continue;
2612        };
2613        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2614        // that module's docs for why a run this cannot parse is left alone
2615        // rather than guessed at. A different schema number is not that: this
2616        // touches only `status` and `active`, never a field whose meaning a
2617        // schema bump changed, so an old record's values serve this exactly
2618        // as well as a current one's (see `clean::read_state`'s own doc for
2619        // the same reasoning applied to folding).
2620        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2621            continue;
2622        };
2623        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2624            continue;
2625        };
2626        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2627            continue;
2628        }
2629        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2630        // it", which is also the normal, healthy shape of a manual `magi
2631        // run` / `magi review` sharing this same home — this scan walks
2632        // every run on disk, not only ones this daemon itself started. Such
2633        // a run's active seats can legitimately sit past their own timeout
2634        // for a little while (the CLI finishing up, its result still being
2635        // collected) without the process driving it having died. `liveness`
2636        // is what actually tells the two apart, by corroborating
2637        // `driver_pid` against the process it names — see its own doc. Only
2638        // its strongest, provable answer licenses wiping this run's active
2639        // seats and failing it out from under whatever is still running it.
2640        let daemon_claims = is_working_on(home, &id, now);
2641        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2642            != crate::run::Liveness::Dead
2643        {
2644            continue;
2645        }
2646        state.abandon("daemon");
2647        if let Err(e) = state.save_under(home) {
2648            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2649            continue;
2650        }
2651        // This run never passes through `Runner::execute` again, so its end
2652        // is announced here.
2653        if let Some(notice) = notices::run_ended(&state) {
2654            notices::raise_in(home, notice);
2655        }
2656        // The seat that asked is gone for good now, exactly like any other
2657        // door `graph::Runner::settle_questions` closes the moment `status`
2658        // lands somewhere non-resumable - see that method's own doc. Nothing
2659        // else reaches this one before the next `janitor()` startup pass
2660        // (`clean::abandon_settled_questions`), and a daemon that stays up
2661        // for days must not leave an open question badging the operator
2662        // until it happens to restart.
2663        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2664            tracing::warn!("abandon questions for {id}: {e:#}");
2665        }
2666        abandoned.push(id);
2667    }
2668    abandoned
2669}
2670
2671#[derive(Debug, Clone, Serialize, Deserialize)]
2672struct TaskWorker {
2673    opts: Opts,
2674    queue: PathBuf,
2675    task: String,
2676    #[serde(default)]
2677    lane: PermitKind,
2678    #[serde(default)]
2679    standalone: bool,
2680}
2681
2682#[doc(hidden)]
2683pub struct TaskWorkerLease {
2684    pub job: crate::worker::Job,
2685    dir: PathBuf,
2686    lease: Option<crate::worker::Lease>,
2687}
2688
2689impl TaskWorkerLease {
2690    pub fn release_lease(&mut self) {
2691        self.lease = None;
2692    }
2693}
2694
2695impl Drop for TaskWorkerLease {
2696    fn drop(&mut self) {
2697        self.release_lease();
2698        let _ = std::fs::remove_dir_all(&self.dir);
2699    }
2700}
2701
2702/// Reserve a task worker without launching a process, for integration tests.
2703#[doc(hidden)]
2704pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2705    let request = TaskWorker {
2706        opts: Opts::default(),
2707        queue: home.join("queue"),
2708        task: task.to_owned(),
2709        lane: PermitKind::default(),
2710        standalone: true,
2711    };
2712    let (job, lease) = crate::worker::running_fixture(
2713        home,
2714        &format!("task:{task}"),
2715        serde_json::to_value(request)?,
2716    )?;
2717    Ok(TaskWorkerLease {
2718        dir: home.join("workers").join("jobs").join(&job.id),
2719        job,
2720        lease: Some(lease),
2721    })
2722}
2723
2724fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2725    Ok(crate::worker::active(home)?
2726        .into_iter()
2727        .filter(|job| job.kind == "task")
2728        .collect())
2729}
2730
2731fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2732    task_jobs(home)?
2733        .into_iter()
2734        .filter_map(
2735            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2736                Ok(request) if !request.standalone => Some(Ok(job)),
2737                Ok(_) => None,
2738                Err(error) => Some(Err(error.into())),
2739            },
2740        )
2741        .collect()
2742}
2743
2744/// Whether an independent scheduler can be controlled without its web parent.
2745#[must_use]
2746pub fn managed(home: &Path) -> bool {
2747    match crate::worker::active(home) {
2748        Err(error) => {
2749            tracing::error!("cannot determine scheduler ownership: {error:#}");
2750            true
2751        }
2752        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2753        Ok(_) => {
2754            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2755                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2756        }
2757    }
2758}
2759
2760/// Start a detached, singleton scheduler using this executable generation.
2761pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2762    anyhow::ensure!(
2763        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2764        "the scheduler is stopping; wait for retirement before starting it again"
2765    );
2766    crate::worker::spawn(
2767        home,
2768        "scheduler",
2769        "scheduler",
2770        serde_json::to_value(opts.absolute()?)?,
2771    )
2772    .await
2773}
2774
2775fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2776    home.join("worker-parks").join(format!("{}.json", job.id))
2777}
2778
2779fn request_task_park(
2780    home: &Path,
2781    job: &crate::worker::Job,
2782    cause: crate::run::ParkCause,
2783) -> Result<()> {
2784    let path = park_request_path(home, job);
2785    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2786    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2787    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2788}
2789
2790/// Stop dispatch immediately; only an explicit park reaches existing workers.
2791pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2792    if control == crate::worker::Control::Park {
2793        for job in owned_task_jobs(home)? {
2794            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2795        }
2796    }
2797    crate::worker::request(home, "scheduler", control)
2798}
2799
2800/// Resolve what a restart would replace without signalling the scheduler.
2801pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2802    if let Some(job) = crate::worker::active(home)?
2803        .into_iter()
2804        .find(|job| job.kind == "scheduler")
2805    {
2806        return serde_json::from_value(job.payload)
2807            .context("read detached scheduler options")
2808            .map(Some);
2809    }
2810    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2811        && crate::worker::try_lease(home, "scheduler")?.is_none()
2812    {
2813        let path = home.join("scheduler-options.json");
2814        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2815        return serde_json::from_slice(&body)
2816            .context("decode detached scheduler options")
2817            .map(Some);
2818    }
2819    Ok(None)
2820}
2821
2822/// Replace the scheduler, leaving all active task and conversation jobs alone.
2823pub async fn restart_detached(home: &Path) -> Result<()> {
2824    let Some(opts) = scheduler_restart_options(home)? else {
2825        return Ok(());
2826    };
2827    request_control(home, crate::worker::Control::Stop)?;
2828    loop {
2829        let reserved = crate::worker::active(home)?
2830            .iter()
2831            .any(|job| job.kind == "scheduler");
2832        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2833            break;
2834        }
2835        tokio::time::sleep(Duration::from_millis(100)).await;
2836    }
2837    spawn_detached(home, &opts).await?;
2838    Ok(())
2839}
2840
2841/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2842pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2843    let opts: Opts = serde_json::from_value(payload)?;
2844    let _ = home;
2845    serve_until(opts, Stop::new()).await
2846}
2847
2848/// Execute and settle one task with the queue claim owned by this process.
2849pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2850    let request: TaskWorker = serde_json::from_value(payload)?;
2851    let queue = Queue::at(request.queue);
2852    let key = format!("task:{}", request.task);
2853    let job = task_jobs(home)?
2854        .into_iter()
2855        .find(|job| job.key == key)
2856        .context("task worker reservation is missing")?;
2857    let park_path = park_request_path(home, &job);
2858    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2859    // our durable reservation. Never execute before that ownership hand-off.
2860    let _claim = loop {
2861        match queue.claim(&request.task) {
2862            Ok(claim) => break claim,
2863            // Only contention (the claim file exists) is worth waiting out; an
2864            // I/O failure must end this worker instead of pinning its lane.
2865            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2866                return Err(e.context("claim the task for its worker"));
2867            }
2868            Err(_) => {
2869                sweep_stale_claims(&queue, STALE_CLAIM);
2870                tokio::time::sleep(Duration::from_millis(50)).await;
2871            }
2872        }
2873    };
2874    let mut task = queue.get(&request.task)?;
2875    if !task.status.runnable()
2876        || (!request.standalone
2877            && request.lane
2878                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2879    {
2880        return Ok(());
2881    }
2882    let stop = Stop::new();
2883    let watcher = {
2884        let home = home.to_path_buf();
2885        let stop = stop.clone();
2886        let park_path = park_path.clone();
2887        tokio::spawn(async move {
2888            loop {
2889                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2890                    let cause = std::fs::read(&park_path)
2891                        .ok()
2892                        .and_then(|body| serde_json::from_slice(&body).ok())
2893                        .unwrap_or(crate::run::ParkCause::Operator);
2894                    stop.park(cause);
2895                    return;
2896                }
2897                tokio::time::sleep(Duration::from_millis(200)).await;
2898            }
2899        })
2900    };
2901    let quota = if request.standalone {
2902        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2903    } else {
2904        let status = Arc::new(Mutex::new(Status::new()));
2905        Box::pin(attempt(
2906            &request.opts,
2907            &queue,
2908            &status,
2909            &stop,
2910            crate::graph::Pause::new(),
2911            &mut task,
2912        ))
2913        .await
2914    };
2915    watcher.abort();
2916    let _ = std::fs::remove_file(park_path);
2917    persist_cooldown(home, &quota).await?;
2918    Ok(())
2919}
2920
2921/// Launch the standalone task worker with a claim-to-reservation handoff.
2922/// Returns only after the worker owns a durable execution reservation.
2923pub async fn spawn_claimed(
2924    home: &Path,
2925    opts: &Opts,
2926    queue: &Queue,
2927    task: &Task,
2928    claim: crate::queue::Claim,
2929) -> Result<crate::worker::Job> {
2930    let request = TaskWorker {
2931        opts: opts.absolute()?,
2932        queue: std::path::absolute(queue.root())?,
2933        task: task.id.clone(),
2934        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2935        standalone: true,
2936    };
2937    let job = crate::worker::spawn(
2938        home,
2939        "task",
2940        &format!("task:{}", task.id),
2941        serde_json::to_value(request)?,
2942    )
2943    .await?;
2944    drop(claim);
2945    Ok(job)
2946}
2947
2948/// Transfer a standalone caller's claim only after the detached worker is live,
2949/// then follow that worker to its final (non-automatically-retrying) outcome.
2950pub async fn run_detached_claimed(
2951    opts: &Opts,
2952    queue: &Queue,
2953    task: &mut Task,
2954    claim: crate::queue::Claim,
2955) -> Result<()> {
2956    let home = crate::run::home();
2957    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2958    loop {
2959        // Reconcile execution leases even without a scheduler. A dead worker
2960        // must become a reported failure, never an infinite persisted wait.
2961        crate::worker::active(&home)?;
2962        let current = crate::worker::get(&home, &job.id)?;
2963        if matches!(
2964            current.status,
2965            crate::worker::Status::Finished | crate::worker::Status::Failed
2966        ) {
2967            *task = queue.get(&task.id)?;
2968            anyhow::ensure!(
2969                current.status != crate::worker::Status::Failed,
2970                "task worker failed: {}",
2971                current.result.as_deref().unwrap_or("unknown failure")
2972            );
2973            return Ok(());
2974        }
2975        tokio::time::sleep(Duration::from_millis(200)).await;
2976    }
2977}
2978
2979async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2980    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2981        let _lease = loop {
2982            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2983                break lease;
2984            }
2985            tokio::time::sleep(Duration::from_millis(10)).await;
2986        };
2987        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2988            let path = home.join("task-quota-cooldown.json");
2989            let temporary = path.with_extension("json.tmp");
2990            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2991            std::fs::rename(temporary, path)?;
2992        }
2993    }
2994    Ok(())
2995}
2996
2997fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2998    match std::fs::read(home.join("task-quota-cooldown.json")) {
2999        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3000        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3001        Err(error) => Err(error.into()),
3002    }
3003}
3004
3005/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
3006///
3007/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
3008/// sets, so there is one loop body rather than two that drift apart the first
3009/// time the retry policy changes on only one of them.
3010pub async fn serve(opts: Opts) -> Result<()> {
3011    tracing::info!(
3012        "automatic update and restart requires magi web; standalone serve does not restart"
3013    );
3014    serve_until(opts, Stop::new()).await
3015}
3016
3017/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
3018///
3019/// A stop retires dispatch promptly, including while a worker launch is being
3020/// acknowledged. Already reserved workers own their attempts independently and
3021/// finish with their started executable. Explicit park additionally forwards
3022/// durable park requests; neither scheduler retirement nor update does so.
3023///
3024/// While the queue is empty the stop is honoured within one wakeup rather than
3025/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
3026/// caller that taps stop does not sit through the remainder of a sleep.
3027pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3028    let opts = opts.absolute()?;
3029    let home = crate::run::home();
3030    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3031        .context("another scheduler already owns this home")?;
3032    if let Some(reading) = read_status(&home)
3033        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3034    {
3035        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3036    }
3037    if !crate::worker::active(&home)?
3038        .iter()
3039        .any(|job| job.kind == "scheduler")
3040    {
3041        crate::worker::clear_control(&home, "scheduler")?;
3042    }
3043    std::fs::write(
3044        home.join("scheduler-options.json"),
3045        serde_json::to_vec(&opts)?,
3046    )?;
3047    let control = {
3048        let home = home.clone();
3049        let stop = stop.clone();
3050        tokio::spawn(async move {
3051            loop {
3052                match crate::worker::control(&home, "scheduler").ok().flatten() {
3053                    Some(crate::worker::Control::Park) => {
3054                        let _ = request_control(&home, crate::worker::Control::Park);
3055                        stop.park(crate::run::ParkCause::Operator);
3056                        break;
3057                    }
3058                    Some(crate::worker::Control::Stop) => {
3059                        stop.stop();
3060                        break;
3061                    }
3062                    None => {}
3063                }
3064                tokio::time::sleep(Duration::from_millis(100)).await;
3065            }
3066        })
3067    };
3068    let signal = {
3069        let stop = stop.clone();
3070        tokio::spawn(async move {
3071            if tokio::signal::ctrl_c().await.is_ok() {
3072                stop.stop();
3073                tracing::info!("scheduler shutdown requested; independent workers continue");
3074            }
3075        })
3076    };
3077
3078    let worktrees_root = opts
3079        .worktrees_root
3080        .clone()
3081        .unwrap_or_else(crate::run::default_worktree_root);
3082    let outcome = drive(
3083        &opts,
3084        &Queue::open(),
3085        &status_path(),
3086        &crate::run::home(),
3087        &worktrees_root,
3088        &stop,
3089    )
3090    .await;
3091
3092    signal.abort();
3093    control.abort();
3094    outcome
3095}
3096
3097/// The loop proper: setup, poll, teardown, with the queue and the status file
3098/// supplied rather than discovered.
3099///
3100/// All three of `home`, `worktrees_root` and the queue/status paths are
3101/// parameters rather than resolved here, for the same reason:
3102/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3103/// so a unit test that pinned it would fight every other test in the binary,
3104/// and a loop that resolved its own worktree bay could only be exercised
3105/// against the operator's real `~/wt/<repo>` - publishing over a live
3106/// daemon's status file, claiming tasks out of a live backlog, and, since
3107/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3108/// whatever the operator actually has on disk.
3109async fn drive(
3110    opts: &Opts,
3111    queue: &Queue,
3112    status_file: &Path,
3113    home: &Path,
3114    worktrees_root: &Path,
3115    stop: &Stop,
3116) -> Result<()> {
3117    // The status file is a *snapshot*, not a stream of events: a reader only
3118    // ever wants the latest values, and every tick rewrites the whole file
3119    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3120    // while an mpsc channel would force the loop to re-send unchanged fields on
3121    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3122    // for no gain. The lock is only ever held across a field assignment, never
3123    // across an await.
3124    let recovery_cfg = prepare(&opts.repo, opts).ok();
3125    let daemon_cfg = recovery_cfg
3126        .as_ref()
3127        .map(|c| c.daemon.clone())
3128        .unwrap_or_default();
3129    let reconciled = crate::driver::reconcile(home);
3130    if !reconciled.is_empty() {
3131        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3132    }
3133    let mut initial_status = Status::new();
3134    let owned = owned_task_jobs(home)?;
3135    initial_status.current = current_work(home, Timestamp::now())
3136        .into_iter()
3137        .filter(|current| {
3138            owned
3139                .iter()
3140                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3141        })
3142        .collect();
3143    initial_status.idle = initial_status.current.is_empty();
3144    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3145        recovery_cfg.as_ref(),
3146        daemon_cfg.max_deputies,
3147    ));
3148    let status = Arc::new(Mutex::new(initial_status));
3149    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3150    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3151
3152    // Read once at startup, not per task: how many runs this loop drives at
3153    // once is a property of the machine running it, not of whichever
3154    // repository a given task happens to name - see
3155    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3156    // fact in the same sense the agent roster is.
3157    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3158
3159    tracing::info!(
3160        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3161        queue.root().display(),
3162        opts.poll.as_secs(),
3163        opts.max_attempts,
3164        concurrency,
3165        if daemon_cfg.pause_for_interrupts {
3166            ", interrupts enabled"
3167        } else {
3168            ""
3169        }
3170    );
3171
3172    let outcome = tokio::select! {
3173        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3174            max_concurrent: concurrency,
3175            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3176            recovery_cfg,
3177        }) => outcome,
3178        () = async {
3179            while !stop.stopped() {
3180                tokio::time::sleep(Duration::from_millis(25)).await;
3181            }
3182        } => {
3183            if stop.parking() {
3184                request_control(home, crate::worker::Control::Park)?;
3185            }
3186            Ok(())
3187        }
3188    };
3189
3190    stop.busy.store(0, Ordering::SeqCst);
3191    beat.abort();
3192    clear_status_at(status_file);
3193    outcome
3194}
3195
3196/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3197/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3198pub(crate) fn release_watch_settings_from_config(
3199    home: &Path,
3200    repo: &Path,
3201    cfg: &Config,
3202) -> (Vec<PathBuf>, u64) {
3203    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3204        .into_iter()
3205        .map(|r| r.path)
3206        .collect();
3207    // Repositories the daemon has worked in, wherever they live: a task may
3208    // name one outside `[repos] roots`, and its release PR must be watched too.
3209    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3210        .list()
3211        .into_iter()
3212        .map(|t| t.repo)
3213        .collect();
3214    let runs = home.join("runs");
3215    for id in crate::run::list_ids_in(&runs) {
3216        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3217            .ok()
3218            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3219            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3220        known.extend(repo);
3221    }
3222    for k in known {
3223        let k = k.canonicalize().unwrap_or(k);
3224        if k.join(".git").exists() && !paths.contains(&k) {
3225            paths.push(k);
3226        }
3227    }
3228    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3229    if !paths.contains(&own) {
3230        paths.push(own);
3231    }
3232    (paths, cfg.daemon.release_stall_minutes)
3233}
3234
3235/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3236const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3237
3238/// Refresh the status file on a fixed tick.
3239///
3240/// Separate from the loop because a run takes tens of minutes: a status file
3241/// written only between tasks would look stale for the whole of every run, and
3242/// a reader would report the daemon dead exactly while it was busiest.
3243async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3244    loop {
3245        tokio::time::sleep(HEARTBEAT).await;
3246        let snapshot = {
3247            let mut guard = lock(&status);
3248            guard.updated_at = Timestamp::now();
3249            guard.clone()
3250        };
3251        if let Err(e) = write_status_to(&path, &snapshot) {
3252            // A failed heartbeat must not take the daemon down: the loop is the
3253            // product, the status file is only the window onto it.
3254            tracing::warn!("could not refresh the daemon status file: {e:#}");
3255        }
3256    }
3257}
3258
3259/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3260/// if so, whether that wait is over.
3261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3262enum LandResume {
3263    /// The task's last run is not parked on a land approval; schedule it
3264    /// like any other candidate.
3265    NotLanding,
3266    /// Parked in `land`, waiting on a question nobody has answered yet.
3267    /// Left alone: attempting it now would only re-observe the same pull
3268    /// request and park again, spending a `gh` call on a decision that has
3269    /// not changed since the last time this was checked.
3270    StillWaiting,
3271    /// Parked in `land`, and the question is settled - answered or
3272    /// abandoned. Resuming this is the one kind of candidate that must not
3273    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3274    Ready,
3275}
3276
3277/// Classify a runnable candidate by whether it is parked on a land-merge
3278/// approval. Read-only - no claim taken, nothing written - so it is cheap
3279/// enough to call on every candidate, every poll.
3280fn land_resume_state(task: &Task) -> LandResume {
3281    if task.sync_only.is_some() {
3282        return LandResume::NotLanding;
3283    }
3284    let Some(run_id) = task.execution_runs().last() else {
3285        return LandResume::NotLanding;
3286    };
3287    let Ok(state) = RunState::load(run_id) else {
3288        return LandResume::NotLanding;
3289    };
3290    if !state.parked {
3291        return LandResume::NotLanding;
3292    }
3293    if state.status == RunStatus::Landing
3294        && state.land_approval.as_ref().is_some_and(|binding| {
3295            ask::Questions::open()
3296                .get_for_effects(&binding.question)
3297                .is_ok_and(|q| {
3298                    q.run == state.id
3299                        && q.resolution()
3300                            .as_deref()
3301                            .is_some_and(crate::merge_decision::stops)
3302                })
3303        })
3304    {
3305        return LandResume::Ready;
3306    }
3307    if !implementers_match(task, &state) {
3308        return LandResume::NotLanding;
3309    }
3310    // Parked in `land` on the merge approval, or at `merge` on the owner's
3311    // word about a title/body the posting gate withheld. Told apart by the
3312    // run's own record, not by a status both can share.
3313    let node = if state.status == RunStatus::Landing {
3314        land::APPROVAL_NODE
3315    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3316        crate::github_text::ASK_NODE
3317    } else {
3318        return LandResume::NotLanding;
3319    };
3320    let store = ask::Questions::open();
3321    let waiting = store
3322        .list_for_effects()
3323        .into_iter()
3324        .filter(|q| &q.run == run_id && q.node == node)
3325        .max_by(|a, b| a.id.cmp(&b.id));
3326    let Some(mut q) = waiting else {
3327        return LandResume::Ready;
3328    };
3329    if !q.status.open() {
3330        // Repair spends agent resources and must obey concurrency and quota
3331        // waits; only a merge/hold decision may use the decision-only lane.
3332        if q.resolution().as_deref() == Some(land::REPAIR) {
3333            return if state.liveness(false) == Liveness::Live {
3334                LandResume::StillWaiting
3335            } else {
3336                LandResume::NotLanding
3337            };
3338        }
3339        return LandResume::Ready;
3340    }
3341    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3342    // nobody ever answered; land's approval bypasses that wait entirely (see
3343    // `land::approval_gate`), so the same deadline has to be enforced here
3344    // instead, or `graph.answer_timeout` silently stops meaning anything for
3345    // a land approval and a run can sit `StillWaiting` forever with nobody
3346    // told to look at it.
3347    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3348    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3349    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3350        q.abandon(format!(
3351            "no answer within {}s of asking",
3352            timeout.as_secs().max(1)
3353        ));
3354        // If this can't be persisted, do not treat the wait as settled on a
3355        // guess: fall through and try again next poll.
3356        if store.put(&mut q).is_ok() {
3357            return LandResume::Ready;
3358        }
3359    }
3360    LandResume::StillWaiting
3361}
3362
3363/// How often the loop rechecks for new work while something it already
3364/// started is still running, rather than sleeping out the whole
3365/// [`Opts::poll`] interval.
3366///
3367/// Short on purpose: this is what lets a land-merge approval that comes back
3368/// while another task is mid-competition be noticed and resumed within a
3369/// fraction of a second, not within the next multi-second poll.
3370const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3371
3372/// How often [`poll`] rechecks the shared build cache against its cap at a
3373/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3374/// waiting for the queue to run dry.
3375///
3376/// A queue that never empties means the `janitor` call at the bottom of this
3377/// loop's fully-idle branch can go unreached for as long as the backlog
3378/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3379/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3380/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3381/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3382/// backlog of short tasks does not pay for that walk on every poll.
3383const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3384
3385/// State of [`poll`]'s own interrupt-scheduling sequence - see
3386/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3387/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3388/// both kept free of `Task`'s non-identity fields on purpose: every decision
3389/// here turns only on task ids and which ones are in flight, so the "never
3390/// more than one run at once" and "exactly one resume" invariants can be
3391/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3392/// queue - which is exactly the coverage this feature's first two attempts
3393/// were missing.
3394///
3395/// Persisted after every transition, so scheduler replacement preserves the
3396/// interrupt's exclusive turn and the interrupted task's priority resume.
3397#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3398enum Interrupt {
3399    /// No interrupt sequence in progress. Ordinary dispatch applies.
3400    Idle,
3401    /// `interrupt_task` is runnable and exactly one other run is in flight;
3402    /// `parked` names that one task's id. Dispatch is withheld from
3403    /// everyone, including `interrupt_task` itself, until it has left
3404    /// flight - only then is `interrupt_task` let through.
3405    ///
3406    /// `parked` is a `Vec` rather than a bare id for symmetry with
3407    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3408    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3409    /// when exactly one run is in flight, so it is guaranteed to hold
3410    /// exactly one entry in practice - see that branch's own doc for why
3411    /// more than one is deliberately never attempted.
3412    Parking {
3413        parked: Vec<String>,
3414        interrupt_task: String,
3415    },
3416    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3417    /// withheld from everyone until it leaves flight - merged, failed, held,
3418    /// it makes no difference - at which point the sequence moves to
3419    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3420    /// going straight to `Idle` would hand `parked` back to ordinary
3421    /// priority-order dispatch, where a higher-priority task filed in the
3422    /// meantime could start ahead of it.
3423    Running {
3424        parked: Vec<String>,
3425        interrupt_task: String,
3426    },
3427    /// `interrupt_task` left flight; `parked` still names the one run this
3428    /// sequence owes a resume. Dispatch is withheld from everyone except
3429    /// that task - see [`interrupt_gate`] - so the resume this feature
3430    /// promises is never raced by, or run alongside, an unrelated candidate.
3431    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3432    /// own doc on abandonment - the moment it is no longer runnable at all.
3433    Resuming { parked: Vec<String> },
3434}
3435
3436/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3437/// and `runnable` are read-only snapshots of this tick's reality, and the
3438/// only side effect the caller still owes the world is asking whichever
3439/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3440/// site.
3441///
3442/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3443/// accepted rather than a narrower type because that is what [`poll`] already
3444/// has on hand from [`runnable`], and building a second, smaller list on
3445/// every tick just to satisfy this signature would cost more than it proves.
3446///
3447/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3448/// back to a task they are waiting on no longer being [`runnable`] - held,
3449/// blocked, deleted, or finished by some other means entirely, all of which
3450/// an operator can do to a task sitting in the queue with no claim on it at
3451/// all, at any moment, interrupt sequence or not. Without this check the
3452/// sequence would wait forever for a dispatch that can never come, and
3453/// `interrupt_gate` would withhold every other task in the queue right along
3454/// with it - a single `magi task hold` on the wrong id turning into a
3455/// daemon that never dispatches anything again.
3456fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3457    match state {
3458        Interrupt::Idle => {
3459            // Not just "something to interrupt": exactly one thing. More
3460            // than one run in flight only happens above the default
3461            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3462            // one resume, never run alongside anything else" only because
3463            // it is only ever seeded with exactly one id - see
3464            // `Interrupt::Resuming`'s own doc on why releasing more than one
3465            // parked id back to ordinary dispatch cannot be made safe
3466            // against that same setting's own extra concurrency slots.
3467            // Waiting here for the herd to settle to one is the
3468            // simplification this feature's own constraints ask for rather
3469            // than a second concurrency model to reconcile with the first.
3470            if in_flight.len() != 1 {
3471                return Interrupt::Idle;
3472            }
3473            match runnable.iter().find(|t| t.interrupt) {
3474                Some(t) => Interrupt::Parking {
3475                    parked: in_flight.to_vec(),
3476                    interrupt_task: t.id.clone(),
3477                },
3478                None => Interrupt::Idle,
3479            }
3480        }
3481        Interrupt::Parking {
3482            parked,
3483            interrupt_task,
3484        } => {
3485            if in_flight.iter().any(|id| parked.contains(id)) {
3486                // Still waiting for what was in flight to actually stop.
3487                Interrupt::Parking {
3488                    parked,
3489                    interrupt_task,
3490                }
3491            } else if in_flight.contains(&interrupt_task) {
3492                Interrupt::Running {
3493                    parked,
3494                    interrupt_task,
3495                }
3496            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3497                // The parked run(s) are gone, but the interrupt task has not
3498                // been dispatched yet on this tick - `interrupt_gate` is
3499                // what lets it through next.
3500                Interrupt::Parking {
3501                    parked,
3502                    interrupt_task,
3503                }
3504            } else {
3505                // The interrupt task itself is no longer runnable - see this
3506                // function's own doc on abandonment. The parked run(s) still
3507                // get their guaranteed resume; there is simply no interrupt
3508                // to run ahead of them any longer.
3509                Interrupt::Resuming { parked }
3510            }
3511        }
3512        Interrupt::Running {
3513            parked,
3514            interrupt_task,
3515        } => {
3516            if in_flight.contains(&interrupt_task) {
3517                Interrupt::Running {
3518                    parked,
3519                    interrupt_task,
3520                }
3521            } else {
3522                // The interrupt task's own run reached a terminal status,
3523                // whichever one - this is the *only* trigger that moves the
3524                // sequence on, driven straight off the same in-flight
3525                // bookkeeping `poll` already reaps every tick, not a second,
3526                // independent poll of anything.
3527                Interrupt::Resuming { parked }
3528            }
3529        }
3530        Interrupt::Resuming { parked } => {
3531            if in_flight.iter().any(|id| parked.contains(id)) {
3532                // One of the parked runs has been dispatched - the resume
3533                // this sequence owed is fulfilled. Whatever else is left in
3534                // `parked` (ordinarily nothing, at the default concurrency
3535                // of one) rejoins ordinary priority-order dispatch, same as
3536                // any other runnable task.
3537                Interrupt::Idle
3538            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3539                Interrupt::Resuming { parked }
3540            } else {
3541                // Abandonment (see this function's own doc): nothing left in
3542                // `parked` is even runnable any longer.
3543                Interrupt::Idle
3544            }
3545        }
3546    }
3547}
3548
3549/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3550/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3551/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3552/// indistinguishable from any other runnable task - exactly the "off does
3553/// nothing" this feature promises.
3554fn advance_interrupt_tick(
3555    enabled: bool,
3556    state: Interrupt,
3557    in_flight: &[String],
3558    runnable: &[Task],
3559) -> Interrupt {
3560    if !enabled {
3561        return Interrupt::Idle;
3562    }
3563    advance_interrupt(state, in_flight, runnable)
3564}
3565
3566/// Which of this tick's runnable candidates the interrupt sequence actually
3567/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3568/// each half is assertable on its own: this is the half that keeps a
3569/// competition and an interrupt from ever running at the same moment.
3570fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3571    match state {
3572        Interrupt::Idle => candidates,
3573        Interrupt::Parking {
3574            parked,
3575            interrupt_task,
3576        } => {
3577            if in_flight.iter().any(|id| parked.contains(id)) {
3578                Vec::new()
3579            } else {
3580                candidates
3581                    .into_iter()
3582                    .filter(|t| &t.id == interrupt_task)
3583                    .collect()
3584            }
3585        }
3586        Interrupt::Running { .. } => Vec::new(),
3587        // At most one: even if `parked` names more than one id (more than
3588        // one run was in flight when the sequence began, only possible
3589        // above the default `max_concurrent_runs = 1`), only the first match
3590        // is offered. Capping this to a single candidate - not merely to
3591        // `parked`'s own ids - is what makes "exactly one resume, never two
3592        // dispatched together" true regardless of how many ordinary slots
3593        // happen to be free this tick.
3594        Interrupt::Resuming { parked } => candidates
3595            .into_iter()
3596            .find(|t| parked.contains(&t.id))
3597            .into_iter()
3598            .collect(),
3599    }
3600}
3601
3602/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3603/// bundled into one parameter so `poll`'s own signature stays readable -
3604/// see [`drive`]'s call site for where these are actually read.
3605struct DispatchLimits {
3606    /// How many *ordinary* candidates run at once. See
3607    /// [`crate::config::Daemon::max_concurrent_runs`].
3608    max_concurrent: usize,
3609    /// See [`crate::config::Daemon::pause_for_interrupts`].
3610    pause_for_interrupts: bool,
3611    recovery_cfg: Option<Config>,
3612}
3613
3614/// Which semaphore, if any, dispatching a candidate should draw its permit
3615/// from.
3616///
3617/// Pure and separate from [`poll`]'s loop body for the same reason
3618/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3619/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3620/// exactly the policy this feature adds, and a policy only exercisable by
3621/// running the whole loop is a policy nobody checks.
3622#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3623enum PermitKind {
3624    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3625    /// Checked first - a task can be both a land resume and marked
3626    /// [`Task::urgent`], and the resume's own "must not queue behind
3627    /// anything" guarantee takes precedence.
3628    None,
3629    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3630    /// (never in addition to trying) the ordinary pool. This is what lets
3631    /// an urgent task dispatch while every ordinary slot is already checked
3632    /// out, and what stops a second urgent task from opening a third run: it
3633    /// waits on this same one-slot semaphore rather than falling through to
3634    /// the ordinary one.
3635    Urgent,
3636    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3637    /// above.
3638    #[default]
3639    Ordinary,
3640}
3641
3642/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3643/// own boolean, already computed by the caller from [`land_resume_state`].
3644fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3645    if priority {
3646        PermitKind::None
3647    } else if urgent {
3648        PermitKind::Urgent
3649    } else {
3650        PermitKind::Ordinary
3651    }
3652}
3653
3654fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3655    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3656        (0usize, 0usize),
3657        |(ordinary, urgent), request| match request.lane {
3658            PermitKind::Ordinary => (ordinary + 1, urgent),
3659            PermitKind::Urgent => (ordinary, urgent + 1),
3660            PermitKind::None => (ordinary, urgent),
3661        },
3662    );
3663    (
3664        limit.saturating_sub(ordinary),
3665        1usize.saturating_sub(urgent),
3666    )
3667}
3668
3669/// Why a runnable candidate was not dispatched. This does not alter policy.
3670#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3671enum SkipReason {
3672    ClaimUnavailable,
3673    RereadFailed,
3674    NoLongerRunnable,
3675    WaitingOnLanding,
3676    CoolingDown,
3677    OrdinaryCapacity,
3678    UrgentCapacity,
3679    InterruptGate,
3680}
3681
3682impl SkipReason {
3683    fn key(self) -> &'static str {
3684        match self {
3685            Self::ClaimUnavailable => "claim_unavailable",
3686            Self::RereadFailed => "reread_failed",
3687            Self::NoLongerRunnable => "no_longer_runnable",
3688            Self::WaitingOnLanding => "waiting_on_landing",
3689            Self::CoolingDown => "cooling_down",
3690            Self::OrdinaryCapacity => "ordinary_capacity",
3691            Self::UrgentCapacity => "urgent_capacity",
3692            Self::InterruptGate => "interrupt_gate",
3693        }
3694    }
3695
3696    fn describe(self) -> &'static str {
3697        match self {
3698            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3699            Self::RereadFailed => "could not re-read it",
3700            Self::NoLongerRunnable => "no longer runnable",
3701            Self::WaitingOnLanding => "waiting on landing",
3702            Self::CoolingDown => "quota cooldown",
3703            Self::OrdinaryCapacity => "no free ordinary slot",
3704            Self::UrgentCapacity => "urgent slot busy",
3705            Self::InterruptGate => "withheld by the interrupt sequence",
3706        }
3707    }
3708}
3709
3710/// A reason count from a completed dispatch scan.
3711#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3712pub struct DispatchReasonCount {
3713    /// Stable string key, so readers can preserve future reasons.
3714    pub reason: String,
3715    /// Candidates skipped for this reason.
3716    pub count: usize,
3717}
3718
3719/// Observations from a completed scan, not a fresh queue estimate.
3720#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3721pub struct DispatchWait {
3722    /// Runnable candidates before the interrupt gate.
3723    pub runnable: usize,
3724    /// Counts in descending order, with stable reason order for ties.
3725    pub reasons: Vec<DispatchReasonCount>,
3726}
3727
3728type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3729
3730fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3731    if runnable == 0 {
3732        return None;
3733    }
3734    let mut counts = std::collections::BTreeMap::new();
3735    for (_, reason) in skips {
3736        *counts.entry(*reason).or_insert(0usize) += 1;
3737    }
3738    let mut counts: Vec<_> = counts.into_iter().collect();
3739    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3740    Some(DispatchWait {
3741        runnable,
3742        reasons: counts
3743            .into_iter()
3744            .map(|(reason, count)| DispatchReasonCount {
3745                reason: reason.key().to_owned(),
3746                count,
3747            })
3748            .collect(),
3749    })
3750}
3751
3752fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3753    before
3754        .iter()
3755        .filter(|id| !after.iter().any(|task| &task.id == *id))
3756        .map(|id| (id.clone(), SkipReason::InterruptGate))
3757        .collect()
3758}
3759
3760fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3761    if *previous == current {
3762        return false;
3763    }
3764    *previous = current;
3765    true
3766}
3767
3768struct DispatchClaim {
3769    task: Task,
3770    claim: crate::queue::Claim,
3771    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3772}
3773
3774/// Claim and re-read before choosing a lane: a queue listing may predate an
3775/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3776fn claim_dispatch(
3777    queue: &Queue,
3778    candidate: &Task,
3779    cooling_down: bool,
3780    ordinary: &Arc<tokio::sync::Semaphore>,
3781    urgent: &Arc<tokio::sync::Semaphore>,
3782) -> std::result::Result<DispatchClaim, SkipReason> {
3783    let claim = queue
3784        .claim(&candidate.id)
3785        .map_err(|_| SkipReason::ClaimUnavailable)?;
3786    let task = match queue.get(&candidate.id) {
3787        Ok(t) if t.status.runnable() => t,
3788        Ok(_) => return Err(SkipReason::NoLongerRunnable),
3789        Err(e) => {
3790            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3791            return Err(SkipReason::RereadFailed);
3792        }
3793    };
3794    if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
3795        let mut held = task;
3796        hold.apply(&mut held);
3797        record(queue, &mut held);
3798        return Err(SkipReason::NoLongerRunnable);
3799    }
3800    let resume = land_resume_state(&task);
3801    if resume == LandResume::StillWaiting {
3802        return Err(SkipReason::WaitingOnLanding);
3803    }
3804    let priority = resume == LandResume::Ready;
3805    if !priority && cooling_down {
3806        return Err(SkipReason::CoolingDown);
3807    }
3808    // Never borrow an ordinary slot when the single urgent slot is busy.
3809    // Keep scanning other candidates when either pool has no free slot.
3810    let permit = match permit_kind(priority, task.urgent) {
3811        PermitKind::None => None,
3812        PermitKind::Urgent => Some(
3813            Arc::clone(urgent)
3814                .try_acquire_owned()
3815                .map_err(|_| SkipReason::UrgentCapacity)?,
3816        ),
3817        PermitKind::Ordinary => Some(
3818            Arc::clone(ordinary)
3819                .try_acquire_owned()
3820                .map_err(|_| SkipReason::OrdinaryCapacity)?,
3821        ),
3822    };
3823    // Persist the dispatch order under the claim, before config discovery or
3824    // coordination waits can reorder concurrent starts.
3825    let stamp = Timestamp::now();
3826    let mut task = task;
3827    task.dispatched_at = Some(stamp);
3828    if let Err(e) = queue.modify(&task.id, |t| {
3829        t.dispatched_at = Some(stamp);
3830        true
3831    }) {
3832        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3833    }
3834    Ok(DispatchClaim {
3835        task,
3836        claim,
3837        permit,
3838    })
3839}
3840
3841/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3842/// teardown and cannot skip the teardown on an early return.
3843///
3844/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3845/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3846/// land approval that has since been answered is dispatched outside that
3847/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3848/// the whole point of parking there is that it must not queue behind
3849/// whatever else the loop happens to be running, even at the default of one.
3850/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3851/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3852/// these exemptions is still subject to the interrupt gate below, urgent
3853/// included: a land-resume or urgent candidate is exactly as much "something
3854/// else running" as an ordinary one from the interrupt sequence's point of
3855/// view, and letting either slip through while a run is being parked, or
3856/// while the interrupt task itself has the floor, is precisely the second
3857/// run 75dd's own "at most one run, ever, at once" guarantee must never
3858/// allow - see [`Interrupt`]'s own doc.
3859#[derive(Serialize, Deserialize)]
3860struct ServiceWorker {
3861    opts: Opts,
3862    queue: PathBuf,
3863    worktrees_root: PathBuf,
3864    operation: String,
3865}
3866
3867fn load_conductor(home: &Path) -> Result<Conductor> {
3868    match std::fs::read(home.join("conductor-state.json")) {
3869        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3870        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3871        Err(error) => Err(error.into()),
3872    }
3873}
3874
3875fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3876    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3877        .into_iter()
3878        .map(|c| c.task)
3879        .collect();
3880    let stalled = stalled_tasks(queue, home, Timestamp::now());
3881    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3882    let finished = finished_tasks(queue)
3883        .into_iter()
3884        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3885        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3886        .collect();
3887    let queued = queued_tasks(queue)
3888        .into_iter()
3889        .filter(|t| !live.contains(&t.id))
3890        .collect();
3891    (queued, stalled, finished)
3892}
3893
3894// Separate latest dispatch and worker receipts expose version handoff and skips
3895// without erasing the last completed scan or treating observations as authority.
3896fn retention_service_receipt(
3897    home: &Path,
3898    operation: &str,
3899    phase: &str,
3900    outcome: &str,
3901    detail: &str,
3902    cfg: Option<&Config>,
3903) {
3904    if !matches!(operation, "housekeeping" | "disk-pressure") {
3905        return;
3906    }
3907    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3908        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3909        "operation": operation, "outcome": outcome, "detail": detail,
3910        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3911        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3912    if let Err(error) = crate::fold_evidence::atomic_write(
3913        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3914        &serde_json::to_vec(&receipt).expect("service receipt"),
3915    ) {
3916        tracing::warn!("retention service receipt failed: {error:#}");
3917    }
3918}
3919
3920async fn start_service(
3921    home: &Path,
3922    opts: &Opts,
3923    queue: &Queue,
3924    worktrees_root: &Path,
3925    operation: &str,
3926    cfg: Option<&Config>,
3927    busy: bool,
3928) -> Result<()> {
3929    // Fetch policy is live configuration, unlike question recovery capacity.
3930    // Reload before both cadence and eligibility, including disabled -> enabled.
3931    let fetch_cfg = if operation == "fetch" {
3932        match prepare(&opts.repo, opts) {
3933            Ok(cfg) => Some(cfg),
3934            Err(error) => {
3935                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3936                return Ok(());
3937            }
3938        }
3939    } else {
3940        None
3941    };
3942    let cfg = fetch_cfg.as_ref().or(cfg);
3943    let ticks = home.join("service-ticks");
3944    std::fs::create_dir_all(&ticks)?;
3945    let receipt = ticks.join(format!("daemon-{operation}"));
3946    let last = std::fs::read(&receipt)
3947        .ok()
3948        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3949    let interval = match operation {
3950        "disk-pressure" => 30,
3951        "chat-goals" => 60,
3952        "cache" => CACHE_CHECK_INTERVAL_SECS,
3953        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3954        _ => opts.poll.as_secs().max(1),
3955    };
3956    let now = Timestamp::now();
3957    if !cache_check_due(last, now, interval) {
3958        retention_service_receipt(
3959            home,
3960            operation,
3961            "dispatch",
3962            "skipped",
3963            "cadence not due",
3964            cfg,
3965        );
3966        return Ok(());
3967    }
3968    let key = format!("service:daemon-{operation}");
3969    if crate::worker::active(home)?
3970        .iter()
3971        .any(|job| job.key == key)
3972    {
3973        retention_service_receipt(
3974            home,
3975            operation,
3976            "dispatch",
3977            "skipped",
3978            "service worker already active",
3979            cfg,
3980        );
3981        return Ok(());
3982    }
3983    let eligible = match operation {
3984        "conductor" => {
3985            let (queued, stalled, finished) = conductor_work(queue, home);
3986            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3987                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3988        }
3989        "maintenance" => {
3990            queue.list().iter().any(|task| {
3991                crate::triage::disk_wait_eligible(task)
3992                    && task
3993                        .disk_checked_at
3994                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3995            }) || Questions::at(home.join("questions"))
3996                .list_for_effects()
3997                .iter()
3998                .any(|q| {
3999                    q.chosen_action().is_some_and(|action| action.maintenance())
4000                        && !home
4001                            .join("choice-actions")
4002                            .join(format!("{}.json", q.id))
4003                            .exists()
4004                })
4005        }
4006        "housekeeping" => !busy && runnable(queue).is_empty(),
4007        "cache" => {
4008            !busy
4009                && !runnable(queue).is_empty()
4010                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4011        }
4012        "disk-pressure" => busy,
4013        "fetch" => {
4014            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4015        }
4016        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4017            .list()
4018            .iter()
4019            .any(|talk| {
4020                talk.status.open()
4021                    && talk.pending.is_empty()
4022                    && talk.pending_attachments.is_empty()
4023                    && talk.goals.iter().any(|goal| goal.active())
4024            }),
4025        _ => false,
4026    };
4027    if !eligible {
4028        retention_service_receipt(
4029            home,
4030            operation,
4031            "dispatch",
4032            "skipped",
4033            if operation == "housekeeping" {
4034                "active work or runnable task queue"
4035            } else {
4036                "no active work; idle housekeeping owns scan"
4037            },
4038            cfg,
4039        );
4040        return Ok(());
4041    }
4042    retention_service_receipt(
4043        home,
4044        operation,
4045        "dispatch",
4046        "launching",
4047        "eligible and cadence due",
4048        cfg,
4049    );
4050    let request = ServiceWorker {
4051        opts: opts.absolute()?,
4052        queue: std::path::absolute(queue.root())?,
4053        worktrees_root: std::path::absolute(worktrees_root)?,
4054        operation: operation.to_owned(),
4055    };
4056    if let Err(error) =
4057        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
4058    {
4059        retention_service_receipt(
4060            home,
4061            operation,
4062            "dispatch",
4063            "error",
4064            &format!("worker launch: {error:#}"),
4065            cfg,
4066        );
4067        tracing::warn!(operation, "could not launch daemon service: {error:#}");
4068    }
4069    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4070    Ok(())
4071}
4072
4073/// Finite maintenance jobs survive scheduler replacement without duplicating
4074/// agent calls or cancelling an operation between its effect and receipt.
4075pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
4076    let request: ServiceWorker = serde_json::from_value(payload)?;
4077    let opts = &request.opts;
4078    let queue = Queue::at(request.queue);
4079    let questions = Questions::at(home.join("questions"));
4080    match request.operation.as_str() {
4081        "chat-goals" => {
4082            let talks = crate::talk::Talks::at(home.join("talks"));
4083            crate::chat_goal_runtime::sweep(&talks, false).await;
4084        }
4085        "maintenance" => {
4086            apply_maintenance_choices(&queue, &questions, home).await;
4087            triage::monitor_disk_waits(
4088                &queue,
4089                &questions,
4090                opts.config.as_deref(),
4091                Timestamp::now(),
4092            );
4093        }
4094        "conductor" => {
4095            let path = home.join("conductor-state.json");
4096            let mut conductor = load_conductor(home)?;
4097            let (queued, stalled, finished) = conductor_work(&queue, home);
4098            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4099                && conductor.worth_a_look(&queue, &stalled, &finished)
4100            {
4101                let cfg = prepare(&opts.repo, opts)?;
4102                conductor
4103                    .maybe_run(
4104                        &cfg,
4105                        &opts.repo,
4106                        &queue,
4107                        &questions,
4108                        home,
4109                        &queued,
4110                        &stalled,
4111                        &finished,
4112                        opts.max_attempts,
4113                    )
4114                    .await;
4115                let temporary = path.with_extension("json.tmp");
4116                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
4117                std::fs::rename(temporary, path)?;
4118            }
4119        }
4120        "fetch" => {
4121            let cfg = prepare(&opts.repo, opts)?;
4122            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
4123                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
4124                tracing::debug!("fetch origins: {outcome:?}");
4125            }
4126        }
4127        "cache" => {
4128            if task_jobs(home)?.is_empty() {
4129                let mut checked = None;
4130                maybe_prune_cache_between_runs(
4131                    &opts.repo,
4132                    opts,
4133                    home,
4134                    &Stop::new(),
4135                    &mut checked,
4136                    Timestamp::now(),
4137                )
4138                .await;
4139            }
4140        }
4141        "disk-pressure" => {
4142            if let Ok(cfg) = prepare(&opts.repo, opts) {
4143                retention_service_receipt(
4144                    home,
4145                    "disk-pressure",
4146                    "worker",
4147                    "running",
4148                    "retention sweep",
4149                    Some(&cfg),
4150                );
4151                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4152                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4153                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4154                }
4155                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4156                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4157                }
4158                for current in current_work(home, Timestamp::now()) {
4159                    if let Ok(state) = RunState::load_under(&current.run, home)
4160                        && let Some(reason) = disk_gate(&state.repo, &state.config)
4161                    {
4162                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4163                            job.key.strip_prefix("task:") == Some(current.task.as_str())
4164                        }) {
4165                            request_task_park(
4166                                home,
4167                                &job,
4168                                crate::run::ParkCause::Interrupt {
4169                                    reason: reason.clone(),
4170                                },
4171                            )?;
4172                        }
4173                        notices::raise_in(
4174                            home,
4175                            Notice::warn(
4176                                "disk:pressure",
4177                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4178                            ),
4179                        );
4180                    }
4181                }
4182            } else {
4183                retention_service_receipt(
4184                    home,
4185                    "disk-pressure",
4186                    "worker",
4187                    "error",
4188                    "configuration could not be loaded",
4189                    None,
4190                );
4191            }
4192        }
4193        "housekeeping" => {
4194            if task_jobs(home)?.is_empty() {
4195                match prepare(&opts.repo, opts) {
4196                    Ok(cfg) => {
4197                        retention_service_receipt(
4198                            home,
4199                            "housekeeping",
4200                            "worker",
4201                            "running",
4202                            "retention sweep",
4203                            Some(&cfg),
4204                        );
4205                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4206                    }
4207                    Err(error) => retention_service_receipt(
4208                        home,
4209                        "housekeeping",
4210                        "worker",
4211                        "error",
4212                        &format!("configuration: {error:#}"),
4213                        None,
4214                    ),
4215                }
4216                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4217                resweep_superseded_attempts(&queue, home);
4218                triage_held(&queue, home, opts).await;
4219            } else {
4220                retention_service_receipt(
4221                    home,
4222                    "housekeeping",
4223                    "worker",
4224                    "skipped",
4225                    "task worker became active",
4226                    None,
4227                );
4228            }
4229        }
4230        operation => bail!("unknown daemon service {operation}"),
4231    }
4232    Ok(())
4233}
4234
4235/// Only a different request under the same key is a dispatch handoff race.
4236/// Our own unacknowledged reservation is a startup failure, not competing work:
4237/// stop dispatch without fencing it, so an already detached child may still run.
4238fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4239    let key = format!("task:{}", request.task);
4240    let payload = serde_json::to_value(request)?;
4241    if crate::worker::active(home)?
4242        .iter()
4243        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4244    {
4245        tracing::warn!(
4246            "task {} acquired a competing worker reservation: {error:#}",
4247            crate::run::short_of(&request.task)
4248        );
4249        return Ok(());
4250    }
4251    tracing::error!("task worker startup stopped dispatch: {error:#}");
4252    notices::raise_in(
4253        home,
4254        Notice::error(
4255            "loop:worker-startup",
4256            // Startup diagnostics may contain private child-process details;
4257            // keep them in the local error/log rather than the chat or notifier.
4258            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),
4259        ).link(Link::Task { id: request.task.clone() }),
4260    );
4261    Err(error).with_context(|| {
4262        format!(
4263            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4264            crate::run::short_of(&request.task)
4265        )
4266    })
4267}
4268
4269async fn poll(
4270    opts: &Opts,
4271    queue: &Queue,
4272    status: &Arc<Mutex<Status>>,
4273    home: &Path,
4274    worktrees_root: &Path,
4275    stop: &Stop,
4276    limits: DispatchLimits,
4277) -> Result<()> {
4278    let mut attempted = Vec::new();
4279    let mut settling_once_services = false;
4280    let interrupt_path = home.join("scheduler-interrupt.json");
4281    let mut interrupt = match std::fs::read(&interrupt_path) {
4282        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4283        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4284        Err(error) => return Err(error.into()),
4285    };
4286    let mut previous = std::collections::BTreeSet::<String>::new();
4287    let mut previous_skips = DispatchSkips::new();
4288    while !stop.stopped() {
4289        let jobs: Vec<_> = crate::worker::active(home)?
4290            .into_iter()
4291            .filter(|job| job.kind == "task")
4292            .collect();
4293        let requests: Vec<_> = jobs
4294            .iter()
4295            .map(|job| {
4296                serde_json::from_value::<TaskWorker>(job.payload.clone())
4297                    .with_context(|| format!("read live task worker {}", job.id))
4298            })
4299            .collect::<Result<_>>()?;
4300        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4301        let owned: std::collections::BTreeSet<_> = requests
4302            .iter()
4303            .filter(|r| !r.standalone)
4304            .map(|r| r.task.clone())
4305            .collect();
4306        let current: Vec<_> = requests
4307            .iter()
4308            .zip(&jobs)
4309            .filter(|(request, _)| !request.standalone)
4310            .map(|(request, job)| Current {
4311                worker: Some(job.id.clone()),
4312                task: request.task.clone(),
4313                run: queue
4314                    .get(&request.task)
4315                    .ok()
4316                    .and_then(|task| task.execution_runs().last().cloned())
4317                    .unwrap_or_default(),
4318            })
4319            .collect();
4320        {
4321            let mut snapshot = lock(status);
4322            snapshot.polls += 1;
4323            snapshot.completed += previous.difference(&owned).count();
4324            snapshot.current = current;
4325            snapshot.idle = owned.is_empty();
4326            snapshot.dispatch_wait = None;
4327        }
4328        previous = owned.clone();
4329        stop.busy.store(owned.len(), Ordering::SeqCst);
4330
4331        // Slots are reconstructed from durable reservations and OS-held worker
4332        // leases, not this scheduler's lifetime or mutable task urgency.
4333        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4334        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4335        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4336        let mut permits = Vec::new();
4337        sweep_stale_claims(queue, STALE_CLAIM);
4338        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4339        reclaim_abandoned_runs(home, Timestamp::now());
4340        let questions = Questions::at(home.join("questions"));
4341
4342        // Deterministic: no model, run before the conductor sees anything so
4343        // its input reflects the queue's current, already-resolved state.
4344        crate::task_chat::sweep(
4345            queue,
4346            &crate::talk::Talks::at(home.join("talks")),
4347            &questions,
4348            home,
4349        );
4350        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4351            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4352        {
4353            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4354        }
4355        repair_choice_offers(&questions);
4356        resolve_blockers(queue, &questions);
4357        apply_task_choice_actions(queue, &questions, home);
4358        triage::apply_answers(queue, &questions);
4359        reconcile_task_questions(queue, &questions);
4360        let talks = crate::talk::Talks::at(home.join("talks"));
4361        crate::chat_notify::sweep(queue, &talks, home);
4362        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4363        crate::chat_watch::sweep(home, &talks);
4364        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4365            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4366        }
4367        let mut turns = tokio::task::JoinSet::new();
4368        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4369        // start_turns dispatches detached turns; no paid work lives in this set.
4370        while turns.join_next().await.is_some() {}
4371
4372        crate::consult::start_services(
4373            home,
4374            &opts.repo,
4375            limits.recovery_cfg.as_ref(),
4376            opts.config.as_deref(),
4377        )
4378        .await?;
4379        for operation in [
4380            "conductor",
4381            "maintenance",
4382            "housekeeping",
4383            "disk-pressure",
4384            "cache",
4385            "fetch",
4386            "chat-goals",
4387        ] {
4388            // Once an idle --once drain starts settling services, subsequent
4389            // scans only consume their effects. An expired cadence receipt
4390            // must not start another service and keep the drain alive.
4391            if settling_once_services {
4392                break;
4393            }
4394            if operation == "chat-goals" && stop.parking() {
4395                continue;
4396            }
4397            start_service(
4398                home,
4399                opts,
4400                queue,
4401                worktrees_root,
4402                operation,
4403                limits.recovery_cfg.as_ref(),
4404                !live.is_empty(),
4405            )
4406            .await?;
4407        }
4408        let latest = crate::worker::active(home)?;
4409        if latest.iter().any(|job| job.key == "service:daemon-cache")
4410            || latest
4411                .iter()
4412                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4413        {
4414            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4415            continue;
4416        }
4417        let candidates: Vec<Task> = runnable(queue)
4418            .into_iter()
4419            .filter(|task| !live.contains(&task.id))
4420            .filter(|task| !opts.once || !attempted.contains(&task.id))
4421            .collect();
4422        let in_flight: Vec<_> = owned.iter().cloned().collect();
4423        let prior_interrupt = std::mem::discriminant(&interrupt);
4424        interrupt = advance_interrupt_tick(
4425            limits.pause_for_interrupts,
4426            interrupt,
4427            &in_flight,
4428            &candidates,
4429        );
4430        // Same-variant transitions preserve their identities. Only an actual
4431        // transition needs a durable write, atomically before sending controls.
4432        if prior_interrupt != std::mem::discriminant(&interrupt) {
4433            let temporary = interrupt_path.with_extension("json.tmp");
4434            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4435            std::fs::rename(temporary, &interrupt_path)?;
4436        }
4437        if let Interrupt::Parking {
4438            parked,
4439            interrupt_task,
4440        } = &interrupt
4441        {
4442            for job in jobs.iter().filter(|job| {
4443                parked
4444                    .iter()
4445                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4446            }) {
4447                if crate::worker::control(home, &job.key)?.is_none() {
4448                    request_task_park(
4449                        home,
4450                        job,
4451                        crate::run::ParkCause::Interrupt {
4452                            reason: format!(
4453                                "task {} asked to run first",
4454                                crate::run::short_of(interrupt_task)
4455                            ),
4456                        },
4457                    )?;
4458                }
4459            }
4460        }
4461        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4462        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4463        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4464        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4465        let mut started = false;
4466        let mut resync = false;
4467        for candidate in candidates {
4468            if stop.stopped() {
4469                break;
4470            }
4471            let DispatchClaim {
4472                task,
4473                claim,
4474                permit,
4475            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4476                Ok(claim) => claim,
4477                Err(reason) => {
4478                    skips.insert((candidate.id, reason));
4479                    continue;
4480                }
4481            };
4482            if crate::worker::active(home)?
4483                .iter()
4484                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4485            {
4486                drop(claim);
4487                resync = true;
4488                break;
4489            }
4490            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4491            let request = TaskWorker {
4492                opts: opts.absolute()?,
4493                queue: std::path::absolute(queue.root())?,
4494                task: task.id.clone(),
4495                lane,
4496                standalone: false,
4497            };
4498            // Keep the claim until spawn acknowledges the worker's durable
4499            // reservation. The worker then claims and re-reads before attempt.
4500            if let Err(error) = crate::worker::spawn(
4501                home,
4502                "task",
4503                &format!("task:{}", task.id),
4504                serde_json::to_value(&request)?,
4505            )
4506            .await
4507            {
4508                task_worker_spawn_error(home, &request, error)?;
4509                drop(claim);
4510                resync = true;
4511                break;
4512            }
4513            drop(claim);
4514            permits.extend(permit);
4515            attempted.push(task.id);
4516            started = true;
4517        }
4518        if !resync && !stop.stopped() {
4519            if !started {
4520                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4521            }
4522            if changed_dispatch_skips(&mut previous_skips, skips) {
4523                if previous_skips.is_empty() {
4524                    tracing::info!("dispatch skips cleared");
4525                }
4526                for (task, reason) in &previous_skips {
4527                    tracing::info!(
4528                        task,
4529                        reason = reason.key(),
4530                        "task {} skipped: {}",
4531                        crate::run::short_of(task),
4532                        reason.describe()
4533                    );
4534                }
4535            }
4536        }
4537        if started || resync {
4538            continue;
4539        }
4540        if owned.is_empty() && opts.once {
4541            settling_once_services = true;
4542            // These finite services can own queue claims or publish answers.
4543            // A skipped claim is not an idle queue until they have finished;
4544            // scan again afterwards so their changes are actually scheduled.
4545            if crate::worker::active(home)?.iter().any(|job| {
4546                job.kind == "daemon-service"
4547                    && matches!(
4548                        job.key.as_str(),
4549                        "service:daemon-housekeeping"
4550                            | "service:daemon-conductor"
4551                            | "service:daemon-maintenance"
4552                    )
4553            }) {
4554                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4555                continue;
4556            }
4557            break;
4558        }
4559        stop.idle(if live.is_empty() {
4560            opts.poll
4561        } else {
4562            RECHECK_WHILE_BUSY.min(opts.poll)
4563        })
4564        .await;
4565    }
4566    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4567    // every queue claim and Runner driver lease through outcome settlement.
4568    stop.busy.store(0, Ordering::SeqCst);
4569    lock(status).dispatch_wait = None;
4570    Ok(())
4571}
4572
4573/// A maintenance pass may briefly own the same record while a worker starts.
4574/// Wait without blocking the executor or charging an agent attempt, then read
4575/// ownership again under the acquired lock. Other I/O failures still fail closed.
4576async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4577    let busy = |error: &anyhow::Error| {
4578        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4579            error.kind() == std::io::ErrorKind::WouldBlock
4580                || cfg!(windows) && error.raw_os_error() == Some(33)
4581        })
4582    };
4583    match crate::pr_head::owner_lock(home, id) {
4584        Ok(lock) => return Ok(lock),
4585        Err(error) if busy(&error) => {}
4586        Err(error) => return Err(error),
4587    }
4588    let wait = RunState::load_under(id, home)?
4589        .config
4590        .graph
4591        .timeout_resource_wait;
4592    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4593}
4594
4595/// Historical successors do not revoke a still-resumable public owner. Scan
4596/// under the same lock as publication/driver claims, and fail closed on unknown
4597/// history before spending another attempt.
4598async fn public_resume_owner(
4599    home: &Path,
4600    runs: &[String],
4601    repo: &Path,
4602) -> Result<Option<RunState>> {
4603    let mut owner = None;
4604    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4605        let _lock = resume_owner_lock(home, id).await?;
4606        let state = RunState::load_under(id, home)?;
4607        if state.released()
4608            || state.retired_to.is_some()
4609            || state.pr_taken_over_by.is_some()
4610            || !crate::handover::landing_checkpoint(&state)
4611        {
4612            continue;
4613        }
4614        anyhow::ensure!(
4615            crate::git::toplevel(&state.repo).await?.canonicalize()?
4616                == crate::git::toplevel(repo).await?.canonicalize()?,
4617            "public owner repository differs; inspect run lineage"
4618        );
4619        anyhow::ensure!(
4620            owner.is_none(),
4621            "multiple retained public owners; inspect run lineage"
4622        );
4623        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4624            anyhow::bail!(reason.diagnostic(&state));
4625        }
4626        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4627        anyhow::ensure!(
4628            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4629            "public owner's driver is live or unknown; wait before retrying"
4630        );
4631        owner = Some(state);
4632    }
4633    Ok(owner)
4634}
4635
4636/// Run one claimed task to a terminal status and record the outcome.
4637///
4638/// Every transition is flushed to the queue as it happens, so the state on disk
4639/// is what actually occurred rather than what this process still intends to
4640/// write.
4641async fn attempt(
4642    opts: &Opts,
4643    queue: &Queue,
4644    status: &Arc<Mutex<Status>>,
4645    stop: &Stop,
4646    interrupt_pause: crate::graph::Pause,
4647    task: &mut Task,
4648) -> Vec<QuotaLoss> {
4649    if let Some(request) = task.sync_only.clone() {
4650        Box::pin(attempt_sync_only(
4651            queue,
4652            status,
4653            stop,
4654            interrupt_pause,
4655            task,
4656            request,
4657        ))
4658        .await;
4659        return Vec::new();
4660    }
4661    let repo = repo_for(task, &opts.repo);
4662    tracing::info!(
4663        "task {} — {} (repo {})",
4664        task.short(),
4665        task.title,
4666        repo.display()
4667    );
4668
4669    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4670        Ok(owner) => owner,
4671        Err(e) => {
4672            task.hold_machine(Some(format!(
4673                "Cannot verify existing public owner: {e:#}; no attempt started."
4674            )));
4675            record(queue, task);
4676            return Vec::new();
4677        }
4678    };
4679    let resume_runs = public_owner
4680        .as_ref()
4681        .map(|s| vec![s.id.clone()])
4682        .unwrap_or_else(|| task.execution_runs().to_vec());
4683
4684    // A stop spends no agent resources and uses the saved landing owner.
4685    // Current roster edits, missing attachments or a failed config fetch must
4686    // never turn it into a new implementation, or prevent a PR from closing.
4687    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4688        && previous
4689            .merge_decision
4690            .as_ref()
4691            .is_some_and(|decision| !decision.closed)
4692        && previous.status != RunStatus::Landing
4693        && !crate::merge_decision::resumable_hold(&previous)
4694    {
4695        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)));
4696        record(queue, task);
4697        return Vec::new();
4698    }
4699    let stop_owner = resume_runs
4700        .last()
4701        .and_then(|id| RunState::load(id).ok())
4702        .filter(|state| {
4703            crate::merge_decision::resumable_hold(state)
4704                || state.status == RunStatus::Landing
4705                    && state.land_approval.as_ref().is_some_and(|binding| {
4706                        Questions::open()
4707                            .get_for_effects(&binding.question)
4708                            .is_ok_and(|q| {
4709                                q.run == state.id
4710                                    && q.resolution()
4711                                        .as_deref()
4712                                        .is_some_and(crate::merge_decision::stops)
4713                            })
4714                    })
4715        });
4716    if let Some(owner) = stop_owner {
4717        let mut runner = match Runner::resume(&owner.id) {
4718            Ok(runner) => runner,
4719            Err(e) => {
4720                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4721                record(queue, task);
4722                return Vec::new();
4723            }
4724        };
4725        runner.on_pause(stop.pause());
4726        runner.watch_interrupt(interrupt_pause);
4727        let quota_before = runner.state.quota.clone();
4728        let before_start = task.clone();
4729        task.start(owner.id.clone());
4730        if let Err(error) = queue.put(task) {
4731            *task = before_start;
4732            let error = runner.fail_startup("task-start", error);
4733            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4734                task.record_startup_failure(failure.clone());
4735            }
4736            task.hold_manual(Some(format!(
4737                "Could not persist task start; no agents dispatched: {error:#}"
4738            )));
4739            record(queue, task);
4740            return Vec::new();
4741        }
4742        lock(status).current.push(Current {
4743            worker: None,
4744            task: task.id.clone(),
4745            run: owner.id,
4746        });
4747        runner.state.carry_dispatched_resumes(task);
4748        runner.state.next_pass_task_entry = true;
4749        let result = runner.execute().await;
4750        return finish_attempt(
4751            opts.max_attempts,
4752            queue,
4753            task,
4754            &runner.state,
4755            &quota_before,
4756            result,
4757        );
4758    }
4759
4760    if let Some(owner) = &public_owner
4761        && (task.fresh_start || !may_resume_run(owner, task))
4762    {
4763        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)));
4764        record(queue, task);
4765        return Vec::new();
4766    }
4767
4768    if let Some(state) = task
4769        .execution_runs()
4770        .last()
4771        .and_then(|id| RunState::load(id).ok())
4772        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4773    {
4774        task.hold_machine(Some(reason));
4775        record(queue, task);
4776        return Vec::new();
4777    }
4778
4779    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4780        && !task.fresh_start
4781        && task.pr_recovery.is_none()
4782    {
4783        // A pinned infrastructure resume continues the saved reservation;
4784        // it does not authorize another base-sync interval.
4785        let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
4786            && task.review_branch.is_none()
4787            && task.assignment_accepts(&held)
4788            && compatible_run_instruction(&held, task)
4789            && task
4790                .resume_override
4791                .as_ref()
4792                .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
4793        // Exhaustion authorization still takes the owner lock and execution
4794        // lease and rechecks liveness, retained HEAD and ownership.
4795        let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
4796        {
4797            true
4798        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4799            let home = queue.root().parent().expect("queue has a home");
4800            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4801                Ok(()) => true,
4802                Err(error) => {
4803                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4804                    false
4805                }
4806            }
4807        } else {
4808            false
4809        };
4810        if !authorized {
4811            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())));
4812            // Retain the existing stop identity when an old release reached the queue.
4813            task.base_sync_notice(&held);
4814            task.resume_override = None;
4815            record(queue, task);
4816            return Vec::new();
4817        }
4818    }
4819    let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
4820        Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
4821            hold.apply(task);
4822            record(queue, task);
4823            return Vec::new();
4824        }
4825        Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
4826            run,
4827            stop_id,
4828            generation,
4829            approval_at,
4830        }) => Some((run, stop_id, generation, approval_at)),
4831        None => None,
4832    };
4833    let unfinished = (!task.fresh_start)
4834        .then(|| unfinished_run(&resume_runs, task.short()))
4835        .flatten()
4836        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4837    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4838    if task.repair_grants.last().is_some_and(|receipt| {
4839        task.execution_runs().last() == Some(&receipt.request.run)
4840            && task.operator_decided_at == receipt.decision
4841            && previous
4842                .as_ref()
4843                .is_none_or(|run| run.id != receipt.request.run)
4844    }) {
4845        task.hold_unrequested_retry(Some(
4846            "The retained repair run cannot be read or no longer owns this task's recovery. Inspect the saved grant and run; no replacement was started.".into(),
4847        ));
4848        record(queue, task);
4849        return Vec::new();
4850    }
4851    if let Some(id) = &task.disk_resume_run
4852        && unfinished.as_ref() != Some(id)
4853    {
4854        task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely. Inspect its state and recovery approvals; no replacement competition was started.".into()));
4855        record(queue, task);
4856        return Vec::new();
4857    }
4858
4859    if !task.fresh_start
4860        && task.pr_recovery.is_none()
4861        && task.review_branch.is_none()
4862        && task.resume_override.is_none()
4863        && previous
4864            .as_ref()
4865            .is_some_and(|run| run.retired_to.is_some())
4866        && unfinished.is_none()
4867    {
4868        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()));
4869        record(queue, task);
4870        return Vec::new();
4871    }
4872
4873    let saved_recovery = previous.as_ref().filter(|run| {
4874        task.replacement.is_none()
4875            && task.pr_recovery.as_ref().is_some_and(|selected| {
4876                selected
4877                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4878                    .is_ok()
4879                    && selected_starter(selected, Some(run), unfinished.as_deref())
4880                        == Starter::Resume(run.id.clone())
4881            })
4882    });
4883
4884    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4885    // failure here is the network's or the operator's, not the task's: hold
4886    // without spending an attempt, never fall back to a possibly stale copy.
4887    let explicit = match &task.overrides {
4888        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4889        Some(_) => opts.config.as_deref(),
4890        None => opts.config.as_deref(),
4891    };
4892    let (mut config, layers) = if let Some(run) = saved_recovery {
4893        // A matching resume owns its resolved configuration and evidence;
4894        // current layers and inherited overrides only configure new work.
4895        let mut saved = run.clone();
4896        if let Err(e) = saved.configure_recovery_resume() {
4897            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4898            record(queue, task);
4899            return Vec::new();
4900        }
4901        (saved.config, Vec::new())
4902    } else {
4903        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4904            Ok(loaded) => loaded,
4905            Err(e) => {
4906                let reason = format!("[config] {e:#}");
4907                record_config_failure(task, &e);
4908                task.last_error = Some(reason.clone());
4909                task.hold_machine(Some(reason));
4910                record(queue, task);
4911                return Vec::new();
4912            }
4913        };
4914        if let Err(e) = apply_options(&mut config, opts, task) {
4915            task.hold_manual(Some(format!(
4916                "[config] {e:#}; correct the merge override before releasing the task"
4917            )));
4918            record(queue, task);
4919            return Vec::new();
4920        }
4921        if let Some(selected) = &task.pr_recovery
4922            && let Err(e) = selected.configure(&mut config)
4923        {
4924            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4925            record(queue, task);
4926            return Vec::new();
4927        }
4928        (config, layers)
4929    };
4930    let config_evidence = crate::pr_recovery::ConfigEvidence {
4931        layers,
4932        overrides: task.overrides.clone(),
4933        daemon_merge: task
4934            .overrides
4935            .as_ref()
4936            .is_none_or(|o| o.inherit_daemon_options)
4937            .then(|| opts.merge.clone())
4938            .flatten(),
4939    };
4940    apply_task_implementers(&mut config, task);
4941    if let Some(replacement) = &task.replacement {
4942        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4943            old.liveness(false) == Liveness::Dead
4944                && old.merge_decision.as_ref().is_some_and(|d| {
4945                    d.closed
4946                        && d.question == replacement.question
4947                        && d.replacement_run.as_ref().is_none_or(|run| {
4948                            task.execution_runs().last() == Some(run)
4949                                && RunState::load(run).is_ok_and(|current| {
4950                                    current.replaces.as_ref().is_some_and(|pin| {
4951                                        pin.question == replacement.question
4952                                            && pin.agent == replacement.agent
4953                                    })
4954                                })
4955                        })
4956                })
4957        });
4958        if !safe {
4959            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()));
4960            record(queue, task);
4961            return Vec::new();
4962        }
4963        match config.agent(&replacement.agent) {
4964            Ok(agent) if crate::agent::installed(agent) => {}
4965            _ => {
4966                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)));
4967                record(queue, task);
4968                return Vec::new();
4969            }
4970        }
4971        config.graph.implementers = 1;
4972        config.graph.land_approval = true;
4973        config.merge.mode = MergeMode::Pr;
4974        config.graph.selected_implementer = Some(replacement.agent.clone());
4975    }
4976    let p = phrases(&config.graph.language);
4977    let start_failed = p.could_not_start;
4978    // Resolve once for both admission and settlement. The inputs are the
4979    // task's explicit sources (never prose), plus an explicit review source's
4980    // current head; review-only runs may rebase later, and neither fact can
4981    // refund a failed automatic generation.
4982    if let Ok(base) =
4983        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4984            .await
4985        && let Ok(head) =
4986            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4987    {
4988        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4989        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4990            let source = crate::git::rev_parse(&repo, branch)
4991                .await
4992                .unwrap_or_default();
4993            inputs.push_str(&format!(";review:{branch}:{source}"));
4994        }
4995        if let Some(reason) = task
4996            .recovery_exhausted(
4997                &head,
4998                &inputs,
4999                task.attempt_limit
5000                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
5001            )
5002            .filter(|_| {
5003                !task.repair_grants.last().is_some_and(|receipt| {
5004                    RunState::load(&receipt.request.run)
5005                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
5006                })
5007            })
5008        {
5009            task.hold_recovery_budget(
5010                reason,
5011                crate::queue::RecoveryAdmission { base: head, inputs },
5012            );
5013            record(queue, task);
5014            return Vec::new();
5015        }
5016        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
5017    }
5018
5019    // A resumable run of this task is carried on, never re-competed. The
5020    // candidates are built and paid for, and a fresh competition races a
5021    // second implementation against them.
5022    //
5023    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
5024    // started 3cbf on the same task a moment later, duplicating two and a
5025    // half hours of agent work. Then b25f stalled on a judge that timed out
5026    // and one that answered with no JSON - `quota: 0`, so nothing the machine
5027    // was to blame for - and 4043 started **one second** later, buying three
5028    // fresh implementations to reach the same panel. `RunStatus::resumable`
5029    // rather than `!done()` is what catches the second case: a stall is
5030    // terminal, and its cheap recovery re-asks only the absent seats.
5031    //
5032    // A load failure is warned about rather than silently read as "not
5033    // resumable": the alternative is exactly what let a schema mismatch on
5034    // run `eba2` fall through to a full re-competition with nobody told why.
5035    // `crate::conduct` is what actually offers a better answer than
5036    // `Runner::start` here (see `Recovery::Review`), once this task's next
5037    // failure shows it up as `held`/`failed` with the run state unreadable.
5038    // Keep a retained review selection intact until disk admission succeeds.
5039    let consume_review = !previous
5040        .as_ref()
5041        .is_some_and(|state| crate::repair_budget::pending(task, state));
5042    let review_branch = consume_review
5043        .then(|| review_branch_for(task, previous.as_ref()))
5044        .flatten();
5045    let branch_exists = match review_branch {
5046        Some(branch) => crate::git::branch_exists(&repo, branch)
5047            .await
5048            .unwrap_or(false),
5049        None => false,
5050    };
5051    // An explicit `magi review <branch>` is reviewed whatever happens to the
5052    // branch unless an explicit implementer change requires fresh work. An
5053    // unfinished run of the same task still wins, so a retry resumes.
5054    let proposed = review_retry_starter(
5055        task,
5056        previous.as_ref(),
5057        review_branch,
5058        branch_exists,
5059        unfinished.as_deref(),
5060    );
5061    let retry_selected = task.replacement.is_some()
5062        && task.resumption.is_some()
5063        && !task.fresh_start
5064        && previous.as_ref().is_some_and(|run| {
5065            run.replaces.is_some()
5066                && ((run.status == RunStatus::Failed && run.viable().is_empty())
5067                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
5068        });
5069    let stop_pin = task
5070        .resume_override
5071        .as_ref()
5072        .filter(|pin| {
5073            Questions::open()
5074                .get_for_effects(&pin.question_id)
5075                .is_ok_and(|q| {
5076                    q.node == land::APPROVAL_NODE
5077                        && q.resolution()
5078                            .as_deref()
5079                            .is_some_and(crate::merge_decision::stops)
5080                })
5081        })
5082        .and_then(|pin| pin.pinned_run.clone());
5083    let granted_run = task.repair_grants.last().and_then(|receipt| {
5084        let state = RunState::load(&receipt.request.run).ok()?;
5085        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
5086    });
5087    let starter = if let Some(run) = granted_run {
5088        Starter::Resume(run)
5089    } else if let Some(owner) = &public_owner {
5090        Starter::Resume(owner.id.clone())
5091    } else if let Some(run) = stop_pin {
5092        // Stop actions resume their exact owner even after seat-count edits;
5093        // they must never fall through to implementation or a takeover.
5094        Starter::Resume(run)
5095    } else if retry_selected {
5096        Starter::Resume(previous.as_ref().unwrap().id.clone())
5097    } else if let Some(selected) = &task.pr_recovery {
5098        if selected
5099            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5100            .is_ok()
5101        {
5102            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
5103        } else {
5104            Starter::Review(selected.branch.clone())
5105        }
5106    } else {
5107        starter_with_implementers(task, previous.as_ref(), proposed)
5108    };
5109    // A retained execution still writes to its saved output volume. A newer
5110    // repository policy only selects the volume for a fresh run.
5111    let disk_reason = match &starter {
5112        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
5113            || {
5114                RunState::load(id)
5115                    .ok()
5116                    .and_then(|run| disk_gate(&run.repo, &run.config))
5117            },
5118            |run| disk_gate(&run.repo, &run.config),
5119        ),
5120        _ => disk_gate(&repo, &config),
5121    };
5122    if let Some(reason) = disk_reason {
5123        task.notice_cause("disk-space", None, None);
5124        task.last_error = Some(reason.clone());
5125        let disk_checked_at = task.disk_checked_at;
5126        task.hold_machine(Some(reason.clone()));
5127        if matches!(starter, Starter::Resume(_)) {
5128            task.mark_disk_capacity();
5129        } else {
5130            task.mark_startup_disk_capacity();
5131        }
5132        task.disk_checked_at = disk_checked_at;
5133        record(queue, task);
5134        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
5135        notices::raise(
5136            Notice::warn(
5137                &format!("disk:{}", repo.display()),
5138                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
5139            )
5140            .link(Link::Task {
5141                id: task.id.clone(),
5142            }),
5143        );
5144        return Vec::new();
5145    }
5146    let review_branch = if consume_review {
5147        let valid = review_branch.is_some();
5148        task.review_instruction = None;
5149        task.review_branch.take().filter(|_| valid)
5150    } else {
5151        None
5152    };
5153    // An explicit resume pin must never degrade into a new competition or
5154    // takeover, including when its run stops being eligible after the answer.
5155    if let Some(pin) = &task.resume_override
5156        && let Some(run) = &pin.pinned_run
5157        && starter != Starter::Resume(run.clone())
5158    {
5159        let run = run.clone();
5160        task.notice_cause("resume-owner", Some(&run), None);
5161        task.hold_machine(Some(format!(
5162            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5163            task.id
5164        )));
5165        record(queue, task);
5166        return Vec::new();
5167    }
5168    // Automatic disk recovery resumes its retained run or stops: a changed
5169    // seat count or review branch must not turn it into a new competition.
5170    // No attempt is spent here.
5171    if let Some(run) = &task.disk_resume_run
5172        && starter != Starter::Resume(run.clone())
5173    {
5174        task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely: the task's current settings would start a different run. Inspect its state and recovery approvals; no replacement competition was started.".into()));
5175        record(queue, task);
5176        return Vec::new();
5177    }
5178    if task.replacement.is_some()
5179        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5180        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5181    {
5182        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()));
5183        record(queue, task);
5184        return Vec::new();
5185    }
5186    if let Some((ref run, ..)) = head_e2e_approval
5187        && starter != Starter::Resume(run.clone())
5188    {
5189        task.hold_machine(Some(format!(
5190            "Conclusive head_e2e stop on run {run} cannot resume safely with current task settings; inspect `magi show {run}` before retrying. No replacement competition was started."
5191        )));
5192        record(queue, task);
5193        return Vec::new();
5194    }
5195    if let Some(reason) = retained_attempt_hold(
5196        task,
5197        &starter,
5198        config.disk.retained_attempt_limit,
5199        RunState::load,
5200    ) {
5201        // The review choice was consumed above. Preserve it across this hold
5202        // so a later release cannot silently become a fresh implementation.
5203        if let Starter::Review(branch) = &starter {
5204            task.review_branch = Some(branch.clone());
5205        }
5206        task.hold_unrequested_retry(Some(reason));
5207        record(queue, task);
5208        return Vec::new();
5209    }
5210    // Absolute paths of the files the task was filed with, re-read from the
5211    // task now so a file attached while it was held reaches a resumed run
5212    // too. A stored name whose file has gone is an error before any agent is
5213    // paid for, never a silent omission the implementer cannot notice.
5214    let attachments = match task_attachments(queue, task) {
5215        Ok(a) => a,
5216        Err(e) => {
5217            task.attempts += 1;
5218            task.fail_startup_target(
5219                "startup-attachments",
5220                e.name.clone(),
5221                format!("{start_failed}{e:#}"),
5222                opts.max_attempts,
5223            );
5224            record(queue, task);
5225            return Vec::new();
5226        }
5227    };
5228    let startup_pause = stop.pause();
5229    let startup_interrupt = interrupt_pause.clone();
5230    let wait = crate::repo_lock::WaitPolicy::new(
5231        Duration::from_secs(config.graph.timeout_resource_wait),
5232        move || startup_pause.parked() || startup_interrupt.parked(),
5233    );
5234    // Startup includes review takeover and recovery. Do not embed its large
5235    // future in both the wait scope and the surrounding attempt stack frame.
5236    let started = wait.scope(Box::pin(async { match &starter {
5237        Starter::Review(_) if task.pr_recovery.is_some() => {
5238            let selected = task.pr_recovery.clone().expect("selected recovery");
5239            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5240                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5241                    .await
5242                    .map(|mut r| {
5243                        r.state.attachments = attachments.clone();
5244                        r
5245                    }),
5246                Err(e) => Err(e),
5247            }
5248        }
5249        Starter::Review(branch) => {
5250            tracing::info!(
5251                "task {} reopens `{branch}` as a review-only pass",
5252                task.short()
5253            );
5254            // Every earlier attempt is superseded by the one being minted
5255            // now, so a branch one of them still holds may be taken over.
5256            let takeover = crate::handover::Takeover {
5257                earlier: task.earlier_attempts().to_vec(),
5258                home: crate::run::home(),
5259                choice: take_divergence_answer(branch, &config.merge.remote, task),
5260                task_instruction: Some(instruction_for(task)),
5261            };
5262            Runner::review_taking_over(
5263                &repo,
5264                branch,
5265                config,
5266                Some(takeover),
5267                crate::run::Origin::queue(&task.id),
5268            )
5269            .await
5270        }
5271        Starter::Resume(id) => {
5272            tracing::info!("resuming run {id} rather than competing again");
5273            Runner::resume(id).and_then(|mut r| {
5274                if retry_selected {
5275                    // The explicit queue release retries this same pinned
5276                    // implementation, preserving the attempt and worktrees.
5277                    for candidate in &mut r.state.candidates {
5278                        candidate.failed = None;
5279                        candidate.empty = false;
5280                        candidate.commits = 0;
5281                    }
5282                    r.state.status = RunStatus::Implementing;
5283                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5284                }
5285                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5286                    r.state.sources = task.sources.clone();
5287                }
5288                if r.state.prep_failure.is_some() {
5289                    let approval = task
5290                        .resumption
5291                        .as_ref()
5292                        .context("preparation retry requires an explicit task release")?;
5293                    r.retry_preparation(approval.at)?;
5294                }
5295                if let Some(instruction) =
5296                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5297                {
5298                    r.state.instruction = instruction;
5299                }
5300                r.state.attachments = attachments.clone();
5301                if task.replacement.is_some() {
5302                    r.state.config.merge.mode = MergeMode::Pr;
5303                    r.state.config.graph.land_approval = true;
5304                }
5305                // Replacements publish a new PR and ask again. Selected PR
5306                // recoveries keep their saved disposition; ordinary runs can
5307                // retain the task's merge override.
5308                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5309                    .overrides
5310                    .as_ref()
5311                    .and_then(|o| o.merge.as_deref())
5312                    .and_then(|m| merge_mode(m).ok())
5313                {
5314                    r.state.config.merge.mode = mode;
5315                }
5316                Ok(r)
5317            })
5318        }
5319        Starter::Start => {
5320            if let Some(branch) = &review_branch {
5321                tracing::warn!(
5322                    "conductor chose review for task {} but branch `{branch}` no longer \
5323                     exists; requeuing as a fresh competition instead",
5324                    task.short()
5325                );
5326            }
5327            let instruction = prepare_instruction(&starter, None, task)
5328                .unwrap_or_else(|| task.instruction.clone());
5329            Runner::start_naming(
5330                &repo,
5331                instruction,
5332                &task.title,
5333                config,
5334                crate::run::Origin::queue(&task.id),
5335            )
5336            .await
5337            .map(|mut r| {
5338                r.state.attachments = attachments.clone();
5339                r.state.sources = task.sources.clone();
5340                r
5341            })
5342        }
5343    }})).await;
5344    if let Err(error) = &started
5345        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5346    {
5347        task.record_startup_failure(failure.clone());
5348    }
5349    let mut runner = match started {
5350        Ok(r) => r,
5351        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5352            let detail = format!("{e:#}");
5353            task.last_error = Some(detail.clone());
5354            if e.is::<crate::build_target::AdmissionDiskWait>()
5355                && let Starter::Review(branch) = &starter
5356                && review_branch.is_some()
5357            {
5358                task.review_branch = Some(branch.clone());
5359                task.review_instruction = Some(task.instruction.clone());
5360            }
5361            if stop.parking() || interrupt_pause.parked() {
5362                let attempts = task.attempts;
5363                task.park(e.to_string());
5364                // Startup has not spent an attempt to refund.
5365                task.attempts = attempts;
5366            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5367                let disk_checked_at = task.disk_checked_at;
5368                task.hold_machine(Some(detail));
5369                task.mark_startup_disk_capacity();
5370                task.disk_checked_at = disk_checked_at;
5371            } else {
5372                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5373            }
5374            record(queue, task);
5375            return Vec::new();
5376        }
5377        // A branch an earlier attempt still holds and magi will not release
5378        // by itself is the operator's call, not a failed attempt: hold the
5379        // task with the reason, spend nothing, and say so on the bell.
5380        Err(e) if task.pr_recovery.is_some() => {
5381            task.startup_notice_cause("startup-public-head");
5382            task.attempts += 1;
5383            task.last_error = Some(format!("{start_failed}{e:#}"));
5384            task.hold_unrequested_retry(Some(format!(
5385                "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."
5386            )));
5387            record(queue, task);
5388            return Vec::new();
5389        }
5390        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5391            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5392                Some(r) => (p.handover_refused)(r),
5393                None => format!("{e:#}"),
5394            };
5395            task.startup_notice_cause("startup-handover");
5396            let reason = format!("{start_failed}{detail}");
5397            task.last_error = Some(reason.clone());
5398            // Consumed above by `take`; keep it so the released task retries
5399            // as a review of this same branch.
5400            let branch = match &starter {
5401                Starter::Review(branch) => Some(branch.clone()),
5402                _ => None,
5403            };
5404            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5405            // one page; the guidance rides in the reason, fixed per state so a
5406            // re-put never changes the wording and relights it.
5407            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5408            record(queue, task);
5409            tracing::warn!(
5410                "holding {} for a branch it cannot take over: {e:#}",
5411                task.short()
5412            );
5413            return Vec::new();
5414        }
5415        // A branch that differs between here and the remote in ways magi
5416        // cannot prove are the same change is a decision for the owner, not a
5417        // failed attempt: ask with both sides laid out, spend no attempt, and
5418        // let the answer requeue the task.
5419        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5420            let d = e
5421                .downcast_ref::<crate::reconcile::Diverged>()
5422                .expect("checked by the guard");
5423            let mut q = ask::Question::new(
5424                task.id.clone(),
5425                crate::reconcile::NODE.to_owned(),
5426                crate::reconcile::SEAT.to_owned(),
5427                d.summary(),
5428                d.detail(),
5429                d.choices(),
5430            );
5431            match Questions::open().put(&mut q) {
5432                Ok(()) => {
5433                    task.last_error = Some(format!("{e:#}"));
5434                    // Consumed above by `take`; the answer has to reach a review
5435                    // of this same branch, so keep pointing the task at it.
5436                    task.review_branch = Some(d.branch.clone());
5437                    task.review_instruction = Some(task.instruction.clone());
5438                    task.block(vec![q.id.clone()], Some(d.summary()));
5439                }
5440                Err(put) => {
5441                    tracing::warn!("could not file the divergence question: {put:#}");
5442                    task.attempts += 1;
5443                    task.fail_startup(
5444                        "startup-question-store",
5445                        format!("{start_failed}{e:#}"),
5446                        opts.max_attempts,
5447                    );
5448                }
5449            }
5450            record(queue, task);
5451            return Vec::new();
5452        }
5453        Err(e) => {
5454            // The answer was stale and nothing was applied: keep pointing at
5455            // the branch so the next attempt asks again against its new tips.
5456            // Nothing went wrong with the task, so no attempt is spent: a
5457            // budget one short of its limit must not hold it instead of
5458            // letting the question be asked again.
5459            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5460                && let Starter::Review(branch) = &starter
5461            {
5462                task.review_branch = Some(branch.clone());
5463                task.review_instruction = Some(task.instruction.clone());
5464                task.last_error = Some(format!("{start_failed}{e:#}"));
5465                task.status = crate::queue::TaskStatus::Failed;
5466                record(queue, task);
5467                return Vec::new();
5468            }
5469            task.attempts += 1;
5470            task.last_error = Some(format!("{start_failed}{e:#}"));
5471            task.startup_notice_cause("startup-source");
5472            task.hold_unrequested_retry(Some(format!(
5473                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5474            )));
5475            record(queue, task);
5476            return Vec::new();
5477        }
5478    };
5479    if !matches!(starter, Starter::Resume(_))
5480        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5481    {
5482        runner
5483            .state
5484            .event("build-cache", format!("{mode} selected by {source}"));
5485    }
5486    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5487        runner.state.recovery_config = Some(config_evidence);
5488    }
5489    if let Some(replacement) = &task.replacement {
5490        if matches!(starter, Starter::Start) {
5491            runner.state.instruction.push_str(&format!(
5492                "\n\n# Replacement review context\n{}",
5493                replacement.context
5494            ));
5495        }
5496        runner.state.replaces = Some(replacement.clone());
5497        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5498        if let Ok(mut old) = RunState::load(&replacement.run)
5499            && let Some(d) = &mut old.merge_decision
5500        {
5501            d.replacement_run = Some(runner.state.id.clone());
5502            old.event(
5503                "replacement",
5504                format!(
5505                    "replacement run {} owns the next attempt; old PR remains closed",
5506                    runner.state.id
5507                ),
5508            );
5509            if let Err(e) = old.save() {
5510                let error = runner.fail_startup("replacement-history", e);
5511                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5512                    task.record_startup_failure(failure.clone());
5513                }
5514                task.hold_manual(Some(format!(
5515                    "Could not link replacement history: {error:#}; no agents dispatched"
5516                )));
5517                record(queue, task);
5518                return Vec::new();
5519            }
5520        }
5521    }
5522    runner.state.task_instruction = Some(task.instruction.clone());
5523    // The follow-up depth is fixed now, while the task certainly exists:
5524    // deleting it later must not reset the cap (`crate::followup`).
5525    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5526    if runner.state.origin_chat.is_none() {
5527        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5528    }
5529    // A stop that means "park" reaches the graph through this handle.
5530    runner.on_pause(stop.pause());
5531    // `poll`'s interrupt scheduler reaches this one run - and no other -
5532    // through this handle. See `Pause`'s own doc for why these are never
5533    // the same one.
5534    runner.watch_interrupt(interrupt_pause);
5535
5536    // `start` has minted the run, so the task can now point at it. Persisting
5537    // `Running` before `execute` is what makes a crash mid-run legible.
5538    let run = runner.state.id.clone();
5539    let before_start = task.clone();
5540    task.start(run.clone());
5541    if let Err(error) = queue.put(task) {
5542        *task = before_start;
5543        let error = runner.fail_startup("task-start", error);
5544        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5545            task.record_startup_failure(failure.clone());
5546        }
5547        task.hold_manual(Some(format!(
5548            "Could not persist task start; no agents dispatched: {error:#}"
5549        )));
5550        record(queue, task);
5551        return Vec::new();
5552    }
5553    if task.status != TaskStatus::Running {
5554        // Queue::put kept a newer hold or continuation instead of this start.
5555        return Vec::new();
5556    }
5557    lock(status).current.push(Current {
5558        worker: None,
5559        task: task.id.clone(),
5560        run,
5561    });
5562
5563    // `RunState::quota` is the run's whole history across every resume, so
5564    // only what this execution added may arm the cooldown or earn a refund.
5565    let quota_before = runner.state.quota.clone();
5566    runner.state.carry_dispatched_resumes(task);
5567    runner.state.entry_resumption_generation =
5568        Some(task.resumption.as_ref().map_or(0, |r| r.generation));
5569    if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
5570        && runner.state.id == run
5571    {
5572        crate::head_e2e_stop::record_consumed_approval(
5573            &mut runner.state,
5574            &task.id,
5575            &stop_id,
5576            generation,
5577            approval_at,
5578        );
5579    }
5580    runner.state.next_pass_task_entry = true;
5581    let result = runner.execute().await;
5582    finish_attempt(
5583        opts.max_attempts,
5584        queue,
5585        task,
5586        &runner.state,
5587        &quota_before,
5588        result,
5589    )
5590}
5591
5592async fn attempt_sync_only(
5593    queue: &Queue,
5594    status: &Arc<Mutex<Status>>,
5595    stop: &Stop,
5596    interrupt: crate::graph::Pause,
5597    task: &mut Task,
5598    request: crate::base_sync_only::Request,
5599) {
5600    let result = async {
5601        anyhow::ensure!(
5602            task.status == TaskStatus::Queued
5603                && task.execution_runs().last() == Some(&request.run)
5604                && task.resume_override.as_ref().is_some_and(
5605                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5606                ),
5607            "sync-base-only request no longer owns the exact queued run"
5608        );
5609        let mut runner = Runner::resume(&request.run)?;
5610        anyhow::ensure!(
5611            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5612                .await?
5613                .is_none(),
5614            "the task still has a public execution owner"
5615        );
5616        anyhow::ensure!(
5617            !stop.parking() && !interrupt.parked(),
5618            "paused before base synchronization"
5619        );
5620        let original = task.clone();
5621        task.start(request.run.clone());
5622        task.attempts = original.attempts;
5623        if let Err(error) = queue.put(task) {
5624            *task = original;
5625            return Err(error);
5626        }
5627        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5628            return Ok(());
5629        }
5630        lock(status).current.push(Current {
5631            worker: None,
5632            task: task.id.clone(),
5633            run: request.run.clone(),
5634        });
5635        runner.on_pause(stop.pause());
5636        runner.watch_interrupt(interrupt);
5637        runner.execute_sync_only(request.clone()).await
5638    }
5639    .await;
5640    if task.sync_only.as_ref() == Some(&request) {
5641        let saved = RunState::load(&request.run).ok();
5642        let detail = result.err().map(|error| {
5643            format!("Base synchronization only: {error:#}; verification was not allowed")
5644        });
5645        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5646        record(queue, task);
5647    }
5648}
5649
5650/// Settle `task` after its run executed: the verdict, the diagnosis, the
5651/// supersession of earlier attempts and the save. Shared by the loop and by
5652/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5653/// Returns the quota losses this execution added to the run.
5654pub fn finish_attempt(
5655    max_attempts: usize,
5656    queue: &Queue,
5657    task: &mut Task,
5658    state: &RunState,
5659    quota_before: &[QuotaLoss],
5660    result: Result<()>,
5661) -> Vec<QuotaLoss> {
5662    let detail = match result {
5663        Ok(()) => describe(state),
5664        Err(e) => format!("{e:#}"),
5665    };
5666    let fresh = losses_this_attempt(quota_before, &state.quota);
5667    let verdict = Verdict {
5668        status: state.status,
5669        // A run that opened a pull request handed its work over, whatever the
5670        // gate then decided about merging it.
5671        left_pr: state.pr.is_some(),
5672        // Only a rate limit earns the task its attempt back - and only one
5673        // suffered now: a refund justified by a previous session's loss is
5674        // the same mistake as re-arming the cooldown from it. A stalled run
5675        // resumed without hitting quota again therefore spends its attempt,
5676        // like any other failure of the task's own.
5677        quota_hit: !fresh.is_empty(),
5678        // A run that parked was asked to stop; that is not a failure and must
5679        // not spend an attempt, or replacing the binary a few times would
5680        // exhaust a task's budget without an agent ever misbehaving.
5681        parked: state.parked,
5682        // A quota loss that left nothing viable is the same machine fact as a
5683        // `Stalled` quota loss; see `settle`'s doc table.
5684        no_viable_candidates: state.viable().is_empty(),
5685    };
5686    if let Some(replacement) = &state.replaces
5687        && let Some(pr) = &state.pr
5688        && let Ok(mut old) = RunState::load(&replacement.run)
5689        && let Some(d) = &mut old.merge_decision
5690    {
5691        d.replacement_pr = Some(pr.url.clone());
5692        let _ = old.save();
5693    }
5694    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5695    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5696        task.hold_unrequested_retry(Some(format!(
5697            "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.",
5698            task.short()
5699        )));
5700    }
5701    if task.status == TaskStatus::Done {
5702        supersede_prior_runs(task, &crate::run::home());
5703    }
5704    record(queue, task);
5705    tracing::info!(
5706        "task {} is {} after run {} ({})",
5707        task.short(),
5708        task.status.as_str(),
5709        state.short(),
5710        label(state.status)
5711    );
5712    fresh
5713}
5714
5715/// A task a hand-started run leaves runnable (failed with attempts to spare,
5716/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5717/// later must not spend agent calls on it. `magi task release` retries.
5718pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5719    // Parked work (including legacy Failed records with a parked run) is a
5720    // checkpoint or owner handoff, not an unrequested retry.
5721    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5722        && !awaiting_resume_with(task, RunState::load)
5723        // A run parked on the owner's word about a withheld PR title/body
5724        // resumes via `land_resume_state`, including review-only tasks that
5725        // `awaiting_resume_with` does not consider.
5726        && withheld_text_wait(task).is_none()
5727        && !(task.fresh_start && task.replacement.is_some())
5728    {
5729        let why = task.last_error.clone().map_or_else(
5730            || "the run did not finish".to_owned(),
5731            |e| format!("the run did not finish: {e}"),
5732        );
5733        task.hold_unrequested_retry(Some(format!(
5734            "{why}. It was started by hand, so it is not retried \
5735             automatically; `magi task release` retries it."
5736        )));
5737        record(queue, task);
5738    }
5739}
5740
5741/// Whether an attempt at a task whose newest run is `run` would resume that
5742/// run rather than start a fresh competition. `magi run --resume` hands a run
5743/// to a live loop only when this holds.
5744#[must_use]
5745pub fn loop_would_resume(run: &str) -> bool {
5746    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5747}
5748
5749/// A loop in another process that is alive right now: a fresh heartbeat in
5750/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5751/// carries the pid it published (`None` inside when it published none - a
5752/// fresh heartbeat is still evidence of a live loop).
5753///
5754/// The one judgement of "is somebody else serving this queue", shared by the
5755/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5756/// deciding whether to hand a task to the loop. A claim file proves nothing
5757/// here: whether a claim succeeds says nothing about whether its owner lives.
5758#[must_use]
5759pub fn foreign_loop(
5760    reading: Option<&Reading>,
5761    now: Timestamp,
5762    own_pid: u32,
5763) -> Option<Option<u32>> {
5764    let reading = reading.filter(|r| r.running(now))?;
5765    match reading.pid {
5766        Some(pid) if pid == own_pid => None,
5767        pid => Some(pid),
5768    }
5769}
5770
5771fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5772    reading.worker_protocol != Some(1)
5773        && (foreign_loop(Some(reading), now, own_pid).is_some()
5774            || reading
5775                .pid
5776                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5777}
5778
5779/// Low-level claimed-task execution shared by the detached standalone worker
5780/// and focused lifecycle fixtures. The caller must retain the queue claim for
5781/// this entire call. CLI callers transfer ownership through
5782/// [`run_detached_claimed`] instead of executing inside their own runtime.
5783///
5784/// The one deliberate difference from the loop: a task the attempt leaves
5785/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5786/// Nobody asked for a retry, and a daemon starting later must not spend agent
5787/// calls re-running a hand-started task behind the operator's back;
5788/// `magi task release` is the explicit retry.
5789pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5790    run_claimed_until(opts, queue, task, &Stop::new()).await;
5791}
5792
5793async fn run_claimed_until(
5794    opts: &Opts,
5795    queue: &Queue,
5796    task: &mut Task,
5797    stop: &Stop,
5798) -> Vec<QuotaLoss> {
5799    let status = Arc::new(Mutex::new(Status::new()));
5800    // An attempt embeds startup and graph futures. Keep it off the standalone
5801    // caller's stack, on both the initial execution and withheld-text resume.
5802    let mut quota = Box::pin(attempt(
5803        opts,
5804        queue,
5805        &status,
5806        stop,
5807        crate::graph::Pause::new(),
5808        task,
5809    ))
5810    .await;
5811    // A run parked on the owner's word about a withheld PR title/body has no
5812    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5813    // here with the claim still held, and resume once the question is settled
5814    // (answered, or abandoned at its deadline -> the neutral text).
5815    // A rejected reply files one more question (the gate asks at most twice),
5816    // so after a resume the run may be waiting again: keep going, with a fresh
5817    // limit for the new question. `resumes` bounds it even if a resume parks
5818    // without asking anything new.
5819    let mut resumes = 0;
5820    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5821        let Some(timeout) = withheld_text_wait(task) else {
5822            break;
5823        };
5824        eprintln!(
5825            "waiting for the owner's answer on a withheld pull request text \
5826             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5827        );
5828        // The deadline abandons the question itself; the extra margin only
5829        // covers an abandon that could not be saved.
5830        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5831        let ready = loop {
5832            match land_resume_state(task) {
5833                LandResume::StillWaiting
5834                    if !stop.parking() && std::time::Instant::now() < limit =>
5835                {
5836                    tokio::time::sleep(WITHHELD_POLL).await;
5837                }
5838                LandResume::Ready => break true,
5839                _ => break false,
5840            }
5841        };
5842        if !ready || stop.parking() {
5843            break;
5844        }
5845        resumes += 1;
5846        quota.extend(
5847            Box::pin(attempt(
5848                opts,
5849                queue,
5850                &status,
5851                stop,
5852                crate::graph::Pause::new(),
5853                task,
5854            ))
5855            .await,
5856        );
5857    }
5858    hold_if_runnable(queue, task);
5859    quota
5860}
5861
5862/// Resumes an in-process run makes for withheld-text questions: the gate asks
5863/// at most twice, plus one for a resume that asks nothing new.
5864const MAX_WITHHELD_RESUMES: u32 = 3;
5865
5866/// How often an in-process run rechecks its withheld-text question.
5867const WITHHELD_POLL: Duration = Duration::from_secs(15);
5868
5869/// The `answer_timeout` (seconds) of the task's last run when that run is
5870/// parked on an unresolved withheld-text question; `None` otherwise.
5871fn withheld_text_wait(task: &Task) -> Option<u64> {
5872    let id = task.execution_runs().last()?;
5873    let s = RunState::load(id).ok()?;
5874    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5875        .then_some(s.config.graph.answer_timeout)
5876}
5877
5878/// The quota losses `after` holds that `before` did not: what one execution
5879/// suffered, as opposed to the run's history.
5880///
5881/// Compared by value rather than by length or position because
5882/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5883/// the vector can shrink and shift under a resume. A retried seat that hits
5884/// quota again is a `push` with a new `at`, so it shows up as new here.
5885/// Crash recovery uses the recorded pass start as its boundary when available;
5886/// legacy records without passes retain their original history-based policy.
5887fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5888    after
5889        .iter()
5890        .filter(|q| !before.contains(q))
5891        .cloned()
5892        .collect()
5893}
5894
5895/// When the loop-wide quota cooldown should end, given this attempt's losses;
5896/// `None` when there were none. Reset-hint parsing and the cap live here.
5897fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5898    let quota: Vec<_> = quota
5899        .iter()
5900        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5901        .collect();
5902    if quota.is_empty() {
5903        return None;
5904    }
5905    let with_hint = quota.iter().find(|q| q.reset.is_some());
5906    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5907    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5908    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5909    Some(
5910        now.checked_add(jiff::SignedDuration::from_secs(secs))
5911            .unwrap_or(Timestamp::MAX),
5912    )
5913}
5914
5915/// An explicit task count must agree with a run before any resume.
5916fn implementers_match(task: &Task, state: &RunState) -> bool {
5917    task.replacement.as_ref().map_or_else(
5918        || {
5919            task.implementers()
5920                .is_none_or(|n| n == state.config.graph.implementers)
5921        },
5922        |replacement| {
5923            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5924                && state.config.graph.implementers == 1
5925        },
5926    )
5927}
5928
5929/// Never resume or take over candidate work built for a different seat count.
5930fn starter_with_implementers(
5931    task: &Task,
5932    previous: Option<&RunState>,
5933    proposed: Starter,
5934) -> Starter {
5935    if previous.is_some_and(|s| !implementers_match(task, s)) {
5936        task.review_of
5937            .as_ref()
5938            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5939    } else {
5940        proposed
5941    }
5942}
5943
5944/// Apply this task's explicit count to the new attempt, without changing defaults.
5945fn apply_task_implementers(config: &mut Config, task: &Task) {
5946    if let Some(n) = task.implementers() {
5947        config.graph.implementers = n;
5948    }
5949}
5950
5951/// [`prepare`] for one task: its own `--config` and command-line overrides
5952/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5953/// over the loop's, so handing a hand-started task to a daemon changes nothing
5954/// about what it does.
5955#[cfg(test)]
5956fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5957    let explicit = match &task.overrides {
5958        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5959        _ => opts.config.as_deref(),
5960    };
5961    let (mut config, _) = Config::discover(repo, explicit)?;
5962    apply_options(&mut config, opts, task)?;
5963    Ok(config)
5964}
5965
5966fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5967    if task
5968        .overrides
5969        .as_ref()
5970        .is_none_or(|o| o.inherit_daemon_options)
5971        && let Some(mode) = opts.merge.as_deref()
5972    {
5973        config.merge.mode = merge_mode(mode)?;
5974    }
5975    if let Some(o) = &task.overrides {
5976        o.apply(config);
5977    }
5978    if let Some((mode, _)) = task.build_cache_override(config) {
5979        config.verify.build_cache = mode;
5980    }
5981    Ok(())
5982}
5983
5984/// Load the config for a task's repository, with the merge override applied.
5985fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5986    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5987    if let Some(mode) = &opts.merge {
5988        config.merge.mode = merge_mode(mode)?;
5989    }
5990    Ok(config)
5991}
5992
5993/// Prune the shared build cache at a between-runs boundary. The detached cache
5994/// service checks authoritative task jobs first; dispatch waits for that finite
5995/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5996/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5997async fn maybe_prune_cache_between_runs(
5998    repo: &Path,
5999    opts: &Opts,
6000    home: &Path,
6001    stop: &Stop,
6002    last_checked: &mut Option<Timestamp>,
6003    now: Timestamp,
6004) {
6005    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
6006        return;
6007    }
6008    *last_checked = Some(now);
6009    let cfg = match prepare(repo, opts) {
6010        Ok(cfg) => cfg,
6011        Err(e) => {
6012            tracing::warn!("cache check: no config: {e:#}");
6013            return;
6014        }
6015    };
6016    match clean::prune_cache_if_over_limit(&cfg, home) {
6017        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
6018            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
6019            pruned.files,
6020            pruned.freed
6021        ),
6022        Ok(_) => {}
6023        Err(e) => {
6024            tracing::warn!("housekeep: prune cache: {e:#}");
6025            notices::raise_in(
6026                home,
6027                Notice::warn(
6028                    "housekeep:cache",
6029                    format!(
6030                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
6031                        e.to_string()
6032                            .lines()
6033                            .next()
6034                            .unwrap_or("unknown cleanup error")
6035                    ),
6036                ),
6037            );
6038        }
6039    }
6040}
6041
6042/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
6043/// now, given when it last did (if ever). Pure, so the cadence is asserted
6044/// directly rather than by waiting out real minutes in a test.
6045fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
6046    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
6047}
6048
6049/// The disk janitor, with its housekeeping logged rather than fatal.
6050///
6051/// Called only at the loop's idle points, for the reason the caller documents:
6052/// a prune racing a live compile would delete files mid-build. The config is
6053/// re-read on every call because the repository that just ran may not be the
6054/// daemon's own default, and the cache directory is a repository fact.
6055///
6056/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
6057/// and [`crate::run::default_worktree_root`] read here, for the same reason
6058/// [`drive`] takes its queue and status file rather than resolving them: a
6059/// test driving the loop must not reach through to the operator's real home
6060/// or worktree bay just because the janitor runs on every idle tick.
6061/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
6062/// to get wrong silently - a test's `home` was already isolated, but nothing
6063/// exercised the parameter next to it, so a real worktree bay stayed wired in
6064/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
6065/// it for real, every test in this file that drives the loop at all started
6066/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
6067async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
6068    let cfg = match prepare(repo, opts) {
6069        Ok(cfg) => cfg,
6070        Err(e) => {
6071            tracing::warn!("housekeep: no config: {e:#}");
6072            return;
6073        }
6074    };
6075    // A run's own worktree lives under `config.graph.worktree_root` when the
6076    // repository sets one - the same precedence `RunState::worktree_root`
6077    // uses - and `worktrees_root` only stands in for the *default* an
6078    // unconfigured repository resolves to (see this function's own
6079    // parameter, or the test fixture wiring one to a fake path). Housekeeping
6080    // that always swept the default regardless of this override would never
6081    // see, and so never reclaim, a single worktree for a repository that
6082    // relocated them elsewhere.
6083    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
6084    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
6085    // Reported whenever there is anything to say, not only when `folded > 0`:
6086    // the incident this exists to prevent was 90 of 93 runs skipped and 0
6087    // folded, on every single pass, for months - a report gated on `folded`
6088    // would have stayed silent through every one of them.
6089    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
6090        let mut extra = Vec::new();
6091        if out.unreadable > 0 {
6092            extra.push(format!("{} unreadable", out.unreadable));
6093        }
6094        if out.orphaned_worktrees > 0 {
6095            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
6096        }
6097        let detail = if extra.is_empty() {
6098            String::new()
6099        } else {
6100            format!(" ({})", extra.join(", "))
6101        };
6102        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
6103    }
6104    if out.external_merges_recorded > 0 {
6105        tracing::info!(
6106            "housekeep: recorded {} run(s) as merged externally",
6107            out.external_merges_recorded
6108        );
6109    }
6110    if out.stale_pr_states_repaired > 0 {
6111        tracing::info!(
6112            "housekeep: rewrote {} run record(s) whose pull request had already settled",
6113            out.stale_pr_states_repaired
6114        );
6115    }
6116    if out.cache_files > 0 {
6117        tracing::info!(
6118            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
6119            out.cache_files,
6120            out.cache_freed
6121        );
6122    }
6123    if out.questions_abandoned > 0 {
6124        tracing::info!(
6125            "housekeep: abandoned {} question(s) left open by a finished run",
6126            out.questions_abandoned
6127        );
6128    }
6129}
6130
6131/// Run [`triage::run_once`] and log whatever it did, the same "only when
6132/// there is something to say" rule [`janitor`] follows for its own report.
6133///
6134/// Called at the same idle points as [`janitor`] - once per full poll
6135/// interval, never mid-attempt - for the same reason: it is not liveness
6136/// critical, and a task's own `hold_reason` string is the one thing this
6137/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
6138/// tick for no benefit.
6139async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
6140    let questions = Questions::at(home.join("questions"));
6141    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
6142    if report.is_empty() {
6143        return;
6144    }
6145    if !report.quarantined.is_empty() {
6146        tracing::info!(
6147            "triage: held {} blocked task(s) whose blocked-on task or \
6148             question no longer exists: {}",
6149            report.quarantined.len(),
6150            report.quarantined.join(", ")
6151        );
6152    }
6153    if !report.resumed.is_empty() {
6154        tracing::info!(
6155            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
6156            report.resumed.len(),
6157            report.resumed.join(", ")
6158        );
6159    }
6160    if !report.asked.is_empty() {
6161        tracing::info!(
6162            "triage: asked about {} held task(s): {}",
6163            report.asked.len(),
6164            report.asked.join(", ")
6165        );
6166    }
6167    if !report.answered.is_empty() {
6168        tracing::info!(
6169            "triage: applied {} operator answer(s): {}",
6170            report.answered.len(),
6171            report.answered.join(", ")
6172        );
6173    }
6174}
6175
6176/// The free-space gate: what stands between this task and a new run, if
6177/// anything. `Some(reason)` holds the task; `None` lets it start.
6178///
6179/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
6180/// the operator opted out. A measurement failure is a gate, not a pass: both
6181/// sides of "cannot tell" are served by not starting.
6182pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6183    disk_gate_at(repo, config, crate::run::home)
6184}
6185
6186pub(crate) fn disk_gate_at(
6187    repo: &Path,
6188    config: &Config,
6189    home: impl FnOnce() -> PathBuf,
6190) -> Option<String> {
6191    let measure = if crate::build_target::isolated(config) {
6192        crate::disk::managed_free_bytes
6193    } else {
6194        crate::disk::free_bytes
6195    };
6196    disk_gate_with(repo, config, home, measure)
6197}
6198
6199/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
6200/// test can assert the exact wiring `attempt` runs - config's threshold in,
6201/// task-holding reason out - without asking the real machine's disk anything.
6202fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6203    repo: &Path,
6204    config: &Config,
6205    home: impl FnOnce() -> PathBuf,
6206    free_bytes: F,
6207) -> Option<String> {
6208    let min = config.disk.min_free_bytes;
6209    if min == 0 {
6210        return None;
6211    }
6212    let output = match config.verify.build_cache {
6213        BuildCache::Shared => config.cache_dir(),
6214        BuildCache::Isolated => Some(home()),
6215    };
6216    let default_worktree_root;
6217    let worktree_root = match config.graph.worktree_root.as_deref() {
6218        Some(root) => root,
6219        None => {
6220            default_worktree_root = crate::run::default_worktree_root();
6221            &default_worktree_root
6222        }
6223    };
6224    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6225        .into_iter()
6226        .flatten()
6227    {
6228        let probe = if path == repo {
6229            path
6230        } else {
6231            path.ancestors().find(|p| p.exists()).unwrap_or(path)
6232        };
6233        let reason = match free_bytes(probe) {
6234            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6235            Err(e) => Some(crate::disk::unmeasured_in(
6236                probe,
6237                &e,
6238                &config.graph.language,
6239            )),
6240        };
6241        if reason.is_some() {
6242            return reason;
6243        }
6244    }
6245    None
6246}
6247
6248/// How long to wait before offering another task when a run lost a seat to a
6249/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
6250/// could read, or carried nothing at all. Long enough that a quota outage
6251/// cannot burn through a whole backlog in the few seconds each doomed attempt
6252/// takes to fail; short enough that a quota which clears early is not left
6253/// idle for the fallback's sake.
6254const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6255
6256/// Longest a parsed reset hint may push the wait out to. The hint comes from
6257/// the CLI's own words, not a contract, so a parsing slip that lands a day
6258/// away must not leave the loop asleep for a day.
6259const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6260
6261/// How long [`poll`] should wait before offering the next task, after a run
6262/// lost at least one seat to a rate limit.
6263///
6264/// Pure and separate from the loop so the policy can be exercised without a
6265/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
6266/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
6267/// nothing to parse, or the parsed time has already passed; `cap` bounds how
6268/// far a parsed hint is trusted to push the wait out.
6269fn quota_wait(
6270    reset_at: Option<Timestamp>,
6271    now: Timestamp,
6272    fallback: Duration,
6273    cap: Duration,
6274) -> Duration {
6275    match reset_at {
6276        Some(at) if at > now => {
6277            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6278            Duration::from_secs(secs).min(cap)
6279        }
6280        _ => fallback,
6281    }
6282}
6283
6284/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
6285///
6286/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
6287/// explains why parsing it exactly "would be a bug factory" — so this only
6288/// recognises the shapes actually observed in the wild, and returns `None`
6289/// for anything else rather than guess at a format nobody has seen.
6290///
6291/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
6292/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
6293/// said it, not from whenever this loop happens to read it: anchoring on `now`
6294/// would push the reset later on every read and would read an already-elapsed
6295/// reset as still in the future. (A long hint is still clamped by
6296/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
6297fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6298    parse_reset_hint_zoned(text, now)
6299        .or_else(|| parse_reset_hint_dated(text))
6300        .or_else(|| parse_reset_hint_relative(text, recorded))
6301}
6302
6303/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
6304/// optional but at least one required, in that order. A bare number or any
6305/// unknown unit is refused.
6306fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6307    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6308    let mut rest = rest.trim();
6309    if rest.is_empty() {
6310        return None;
6311    }
6312    let mut total: i64 = 0;
6313    let mut matched = false;
6314    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6315        if let Some((digits, tail)) = rest.split_once(unit)
6316            && !digits.is_empty()
6317            && digits.bytes().all(|b| b.is_ascii_digit())
6318        {
6319            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6320            rest = tail;
6321            matched = true;
6322        }
6323    }
6324    if !rest.is_empty() || !matched {
6325        return None;
6326    }
6327    recorded
6328        .checked_add(jiff::SignedDuration::from_secs(total))
6329        .ok()
6330}
6331
6332/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
6333/// case-insensitive) into a 24-hour hour and minute. Shared by every
6334/// reset-hint shape below.
6335fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6336    let clock = clock.trim().to_lowercase();
6337    let (digits, pm) = clock
6338        .strip_suffix("am")
6339        .map(|d| (d, false))
6340        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6341    let (h, m) = digits.trim().split_once(':')?;
6342    let mut hour: i8 = h.trim().parse().ok()?;
6343    let minute: i8 = m.trim().parse().ok()?;
6344    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6345        return None;
6346    }
6347    if pm && hour != 12 {
6348        hour += 12;
6349    } else if !pm && hour == 12 {
6350        hour = 0;
6351    }
6352    Some((hour, minute))
6353}
6354
6355/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
6356/// and a zone, never a date. A clock reading already past today is read as
6357/// tomorrow's: a CLI naming a same-day reset that has already gone by means
6358/// the window rolled over while nothing was watching.
6359fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6360    let open = text.find('(')?;
6361    let close = text.rfind(')')?;
6362    if close <= open {
6363        return None;
6364    }
6365    let zone = text[open + 1..close].trim();
6366    let (hour, minute) = parse_12h_clock(&text[..open])?;
6367    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6368    let candidate = now
6369        .to_zoned(tz)
6370        .with()
6371        .hour(hour)
6372        .minute(minute)
6373        .second(0)
6374        .millisecond(0)
6375        .microsecond(0)
6376        .nanosecond(0)
6377        .build()
6378        .ok()?;
6379    let mut at = candidate.timestamp();
6380    if at <= now {
6381        at += jiff::SignedDuration::from_hours(24);
6382    }
6383    Some(at)
6384}
6385
6386/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6387/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6388/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6389/// "already past today" correction to make: the year already disambiguates
6390/// it. Scanned as a five-word window so it can be pulled out of the middle
6391/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6392/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6393/// any other timestamp with no zone attached.
6394fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6395    let words: Vec<&str> = text.split_whitespace().collect();
6396    if words.len() < 5 {
6397        return None;
6398    }
6399    (0..=words.len() - 5)
6400        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6401}
6402
6403/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6404/// parenthesis right after the window is refused rather than ignored — it
6405/// reads as an explicit zone annotation on a shape that otherwise carries
6406/// none, and guessing UTC anyway would be exactly the silent misread this
6407/// module's parsing otherwise avoids.
6408fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6409    if trailing.is_some_and(|next| next.starts_with('(')) {
6410        return None;
6411    }
6412    let month = month_number(window[0])?;
6413    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6414    let day_digits = ["st", "nd", "rd", "th"]
6415        .iter()
6416        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6417    let day: i8 = day_digits.parse().ok()?;
6418    let year_token = window[2];
6419    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6420        return None;
6421    }
6422    let year: i16 = year_token.parse().ok()?;
6423    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6424    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6425    // reusing the same 12-hour clock reader the bracketed shape uses.
6426    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6427    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6428    let date = jiff::civil::Date::new(year, month, day).ok()?;
6429    let candidate = date
6430        .at(hour, minute, 0, 0)
6431        .to_zoned(jiff::tz::TimeZone::UTC)
6432        .ok()?;
6433    Some(candidate.timestamp())
6434}
6435
6436/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6437/// case-insensitively, into a 1-based month number.
6438fn month_number(name: &str) -> Option<i8> {
6439    const NAMES: [&str; 12] = [
6440        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6441    ];
6442    let lower = name.to_lowercase();
6443    NAMES
6444        .iter()
6445        .position(|n| *n == lower.as_str())
6446        .map(|i| i as i8 + 1)
6447}
6448
6449/// Test probe for the shared resume policy's review-budget exclusion.
6450#[cfg(test)]
6451fn exhausted_review_budget(state: &RunState) -> bool {
6452    // A run whose task-head publication failed has nothing left to review:
6453    // resuming it only retries the publication, so it is never "exhausted".
6454    !crate::handover::can_resume(state)
6455        && state.status == RunStatus::Blocked
6456        && !state.released()
6457        && state.retired_to.is_none()
6458}
6459
6460/// This task's *most recent* run, if resuming it would actually make
6461/// progress. `short` is only for the warning's own message.
6462///
6463/// Only ever `runs.last()` — never a search back through older history.
6464/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6465/// mint, oldest first, and every entry before the last one was already
6466/// superseded at the moment it was minted: the daemon only ever starts a new
6467/// run when the previous one was not worth resuming (unresumable, exhausted,
6468/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6469/// opens a fresh review-only run alongside an older, already-failed
6470/// competition. Searching further back would let an old run that merely
6471/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6472/// behind, say — get resumed instead of the fresh competition
6473/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6474/// nothing asked to revisit.
6475///
6476/// Two runs paid for the "prefer resuming over restarting" half of this
6477/// lesson, which is why this still checks `runs.last()` rather than always
6478/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6479/// task a moment later, duplicating two and a half hours of agent work. Then
6480/// b25f stalled on a judge that timed out and one that answered with no JSON
6481/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6482/// **one second** later, buying three fresh implementations to reach the
6483/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6484/// the second case: a stall is terminal, and its cheap recovery re-asks only
6485/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6486/// that is technically `resumable()` but provably cannot progress must not
6487/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6488/// no-op instead of the fresh competition it promises.
6489///
6490/// A load failure is warned about rather than silently read as "not
6491/// resumable": the alternative is exactly what let a schema mismatch on run
6492/// `eba2` fall through to a full re-competition with nobody told why.
6493/// `crate::conduct` is what actually offers a better answer than
6494/// `Runner::start` here (see `Recovery::Review`), once this task's next
6495/// failure shows it up as `held`/`failed` with the run state unreadable.
6496fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6497    unfinished_run_with(runs, short, RunState::load)
6498}
6499
6500/// [`unfinished_run`] with an injected state reader. Tests provide their
6501/// fixtures directly rather than touching the process-global run home.
6502pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6503where
6504    F: FnMut(&str) -> Result<RunState>,
6505{
6506    let mut id = runs.last()?.clone();
6507    let mut visited = std::collections::BTreeSet::new();
6508    let mut repo = None;
6509    loop {
6510        if !runs.contains(&id) || !visited.insert(id.clone()) {
6511            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6512            return None;
6513        }
6514        let state = match load(&id) {
6515            Ok(state) if state.id == id => state,
6516            Ok(_) => return None,
6517            Err(e) => {
6518                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6519                return None;
6520            }
6521        };
6522        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6523            return None;
6524        }
6525        repo = Some(state.repo.clone());
6526        if let Some(authority) = state.retired_to {
6527            id = authority;
6528            continue;
6529        }
6530        return (crate::handover::can_resume(&state)
6531            && state.liveness(false) != crate::run::Liveness::Live)
6532            .then_some(id);
6533    }
6534}
6535
6536/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6537/// that [`attempt`] will resume it on its own?
6538///
6539/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6540/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6541/// injected reader like its sibling. An unreadable run is not awaiting
6542/// anything: it keeps going to the conductor as before.
6543fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6544where
6545    F: FnOnce(&str) -> Result<RunState>,
6546{
6547    // `Failed` stays: a record an older build wrote for a parked run.
6548    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6549        || task.fresh_start
6550        || task.review_branch.is_some()
6551    {
6552        return false;
6553    }
6554    let Some(id) = task.execution_runs().last() else {
6555        return false;
6556    };
6557    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6558}
6559
6560/// Which of the three ways [`attempt`] can mint or continue a run this task
6561/// should use.
6562#[derive(Debug, Clone, PartialEq, Eq)]
6563enum Starter {
6564    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6565    /// and that still exists.
6566    Review(String),
6567    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6568    Resume(String),
6569    /// `crate::graph::Runner::start`: a fresh competition.
6570    Start,
6571}
6572
6573/// A second bound independent of inputs and the resettable failure counter.
6574/// Count execution and failed-startup recovery records once per run. Startup
6575/// failures can retain unrecorded preparation assets without an execution pass.
6576/// Unknown history is not evidence that a new set of worktrees is affordable.
6577fn retained_attempt_hold(
6578    task: &Task,
6579    starter: &Starter,
6580    limit: usize,
6581    mut load: impl FnMut(&str) -> Result<RunState>,
6582) -> Option<String> {
6583    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6584        return None;
6585    }
6586    let mut retained = 0;
6587    for id in task
6588        .runs
6589        .iter()
6590        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6591        .collect::<std::collections::BTreeSet<_>>()
6592    {
6593        let state = match load(id) {
6594            Ok(state) if state.id == *id => state,
6595            _ => {
6596                return Some(format!(
6597                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6598                ));
6599            }
6600        };
6601        if state.retired_to.is_some() || state.released() {
6602            continue;
6603        }
6604        // Neither a completed status nor an empty candidate array proves that
6605        // all recovery sources (including unrecorded preparation) were retired.
6606        retained += 1;
6607    }
6608    (retained >= limit).then(|| format!(
6609        "[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."
6610    ))
6611}
6612
6613/// A selected public implementation overrides every historical candidate and pin.
6614fn selected_starter(
6615    selected: &crate::pr_recovery::Selection,
6616    previous: Option<&RunState>,
6617    unfinished: Option<&str>,
6618) -> Starter {
6619    if let Some(id) = unfinished
6620        && previous.is_some_and(|r| {
6621            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6622        })
6623    {
6624        Starter::Resume(id.to_owned())
6625    } else {
6626        Starter::Review(selected.branch.clone())
6627    }
6628}
6629
6630/// The owner's answer to this branch's divergence question, consumed from the
6631/// task so a later, different divergence asks again. The runner applies it
6632/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6633fn take_divergence_answer(
6634    branch: &str,
6635    remote: &str,
6636    task: &mut Task,
6637) -> Option<crate::reconcile::Choice> {
6638    let summary = crate::reconcile::summary_for(branch, remote);
6639    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6640        (a.question == summary)
6641            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6642            .flatten()
6643            .map(|c| (i, c))
6644    })?;
6645    task.answers.remove(idx);
6646    Some(choice)
6647}
6648
6649/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6650/// this attempt should use. Pure, and separate from [`attempt`], so the
6651/// routing itself is assertable without spawning a real graph or a git
6652/// process: `attempt`'s own `crate::git::branch_exists` call has already
6653/// happened by the time this is called.
6654///
6655/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6656/// whose branch is gone falls all the way through to [`Starter::Start`], not
6657/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6658/// old (likely `Blocked`) run in the first place, and a branch that vanished
6659/// out from under that choice is not evidence resuming it would fare better.
6660fn choose_starter(
6661    review_branch: Option<&str>,
6662    branch_exists: bool,
6663    unfinished: Option<&str>,
6664) -> Starter {
6665    match review_branch {
6666        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6667        Some(_) => Starter::Start,
6668        None => match unfinished {
6669            Some(id) => Starter::Resume(id.to_owned()),
6670            None => Starter::Start,
6671        },
6672    }
6673}
6674
6675/// Reuse a compatible latest review owner instead of taking its checked-out
6676/// branch into a new run. Different branches and changed criteria still use
6677/// the ordinary review/takeover policy.
6678fn review_retry_starter(
6679    task: &Task,
6680    previous: Option<&RunState>,
6681    branch: Option<&str>,
6682    exists: bool,
6683    unfinished: Option<&str>,
6684) -> Starter {
6685    if let Some(run) = previous
6686        && unfinished == Some(run.id.as_str())
6687        && run.reviewed_commits.is_some()
6688        && branch.is_some_and(|branch| {
6689            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6690        })
6691        && may_resume_run(run, task)
6692    {
6693        return Starter::Resume(run.id.clone());
6694    }
6695    match (branch, unfinished, &task.review_of) {
6696        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6697        _ => choose_starter(branch, exists, unfinished),
6698    }
6699}
6700
6701/// A retained review is valid only while its authored criteria still match.
6702fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6703    task.review_branch
6704        .as_deref()
6705        .filter(|&branch| match &task.review_instruction {
6706            Some(authored) => *authored == task.instruction,
6707            // Legacy retained branches must agree with their prior run; only an
6708            // explicitly pinned review can proceed without recoverable provenance.
6709            None => previous.map_or_else(
6710                || task.review_of.as_deref() == Some(branch),
6711                |run| compatible_run_instruction(run, task),
6712            ),
6713        })
6714}
6715
6716/// A current explicit pin can select an otherwise incompatible run. Edits
6717/// and subsequent approvals invalidate pins selected for earlier criteria.
6718fn may_resume_run(run: &RunState, task: &Task) -> bool {
6719    if !task.assignment_accepts(run) {
6720        return false;
6721    }
6722    task.resume_override
6723        .as_ref()
6724        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6725        || compatible_run_instruction(run, task)
6726}
6727
6728/// Review scaffolding is execution context, not evidence of an operator edit.
6729pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6730    if let Some(authored) = &run.task_instruction {
6731        return compatible_instruction(authored, task);
6732    }
6733    if compatible_instruction(&run.instruction, task) {
6734        return true;
6735    }
6736    // Recognize only the existing generated review shapes on legacy runs.
6737    // Ordinary authored text with a similar heading is left intact.
6738    if run.reviewed_commits.is_some() {
6739        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6740            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6741        }
6742        if let Some(branch) = &task.review_of {
6743            let canonical = format!(
6744                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6745            );
6746            let generated = format!(
6747                "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"
6748            );
6749            return task.instruction == canonical && run.instruction.starts_with(&generated);
6750        }
6751    }
6752    false
6753}
6754
6755/// Compare authored instructions, excluding answer blocks appended by the daemon.
6756pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6757    strip_answers_block(old, task) == task.instruction
6758}
6759
6760/// Which repository a task runs in. A task that names none — the normal case
6761/// for one filed from a phone — runs in the daemon's own default.
6762fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6763    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6764        return fallback.to_path_buf();
6765    }
6766    task.repo.clone()
6767}
6768
6769/// The header [`append_answers`] appends operator answers under. Shared with
6770/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6771/// rather than grown a new block on every resume.
6772const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6773
6774/// Render the first `count` answers in the block appended to an instruction.
6775fn answers_block(task: &Task, count: usize) -> String {
6776    let mut s = ANSWERS_HEADER.to_owned();
6777    for a in &task.answers[..count] {
6778        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6779    }
6780    s
6781}
6782
6783/// Render the approval independently of transient task state, so historical
6784/// suffixes remain recognizable after another explicit release.
6785fn resumption_block(r: &crate::queue::Resumption) -> String {
6786    format!(
6787        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6788         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6789        r.generation, r.at, r.instruction, r.answers_through,
6790    )
6791}
6792
6793/// Append audit answers and the latest explicit approval to the instruction.
6794fn append_answers(base: &str, task: &Task) -> String {
6795    let mut s = base.to_owned();
6796    if !task.answers.is_empty() {
6797        s.push_str(&answers_block(task, task.answers.len()));
6798    }
6799    if let Some(r) = &task.resumption {
6800        s.push_str(&resumption_block(r));
6801    }
6802    s
6803}
6804
6805/// Drop the prior answer block only when it is exactly the suffix this task
6806/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6807/// the task author is ordinary instruction text, not a block to remove.
6808fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6809    let mut instruction = instruction;
6810    for approval in task
6811        .resumption
6812        .iter()
6813        .chain(task.resumption_history.iter().rev())
6814    {
6815        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6816            instruction = base;
6817            break;
6818        }
6819    }
6820    for count in (1..=task.answers.len()).rev() {
6821        let block = answers_block(task, count);
6822        if let Some(base) = instruction.strip_suffix(&block) {
6823            return base;
6824        }
6825    }
6826    instruction
6827}
6828
6829/// The instruction handed to `Runner::start`: the task's own text, plus any
6830/// operator answers `crate::conduct` collected for it (see
6831/// [`Task::answers`]), so a decision the operator actually made reaches the
6832/// implementers rather than only clearing the block that was waiting on it.
6833///
6834/// Appended rather than merged into [`Task::instruction`] itself, so the
6835/// task's own record stays exactly what its author wrote.
6836fn instruction_for(task: &Task) -> String {
6837    append_answers(&task.instruction, task)
6838}
6839
6840/// The instruction a resumed run should carry on with: whatever it already
6841/// had, refreshed with the task's *current* operator answers.
6842///
6843/// A resumable run's own `RunState::instruction` predates any answer
6844/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6845/// the behaviour before this function existed — silently drops the very
6846/// decision the operator made to unblock it. Re-stripping any block this
6847/// function appended on an earlier resume before re-appending the current
6848/// list (rather than blindly appending again) is what keeps a task resumed
6849/// three times over three answered questions from carrying the same answer
6850/// three times.
6851fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6852    append_answers(strip_answers_block(old_instruction, task), task)
6853}
6854
6855/// Preserve the producer's verified boundary and target, independent of prose.
6856fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6857    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6858    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6859    if let Some(cause) = task.hold_notice_cause.as_mut() {
6860        cause.target = failure.map(|f| f.target.clone());
6861    }
6862}
6863
6864#[derive(Debug, thiserror::Error)]
6865#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6866struct MissingAttachment {
6867    name: String,
6868    path: PathBuf,
6869}
6870
6871/// The task's attachments as absolute paths, each checked to still exist.
6872fn task_attachments(
6873    queue: &Queue,
6874    task: &Task,
6875) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6876    let paths = queue.attachment_paths(task);
6877    for (name, path) in task.attachments.iter().zip(&paths) {
6878        if !path.is_file() {
6879            return Err(MissingAttachment {
6880                name: name.clone(),
6881                path: path.clone(),
6882            });
6883        }
6884    }
6885    Ok(paths)
6886}
6887
6888/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6889/// answers before handing it to `Runner` — the actual boundary between
6890/// [`choose_starter`]'s routing and the graph, factored out so it is
6891/// assertable without a real repository, git branch, or agent CLI.
6892///
6893/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6894/// instruction from the reviewed branch's own commit log because there is no
6895/// task statement to speak of for hand-written work, and splicing operator
6896/// answers into that text would contradict the very message it sends
6897/// reviewers ("there is no task statement").
6898fn prepare_instruction(
6899    starter: &Starter,
6900    old_instruction: Option<&str>,
6901    task: &Task,
6902) -> Option<String> {
6903    match starter {
6904        Starter::Start => Some(instruction_for(task)),
6905        Starter::Resume(_) => Some(resumed_instruction(
6906            old_instruction.expect("a resumed run always has a prior instruction"),
6907            task,
6908        )),
6909        Starter::Review(_) => None,
6910    }
6911}
6912
6913/// Persist a transition. A queue write failure is logged rather than fatal: the
6914/// run already happened, and taking the daemon down would only add a lost
6915/// backlog to a full disk.
6916fn record(queue: &Queue, task: &mut Task) {
6917    if let Err(e) = queue.put(task) {
6918        tracing::error!("could not record task {}: {e:#}", task.short());
6919        let notice = Notice::error(
6920            "loop:record",
6921            format!(
6922                "Task {} state could not be saved: {}. Check the disk.",
6923                task.id,
6924                e.to_string().lines().next().unwrap_or("unknown save error")
6925            ),
6926        )
6927        .link(Link::Task {
6928            id: task.id.clone(),
6929        });
6930        // The queue lives at `<home>/queue`, so its parent is the home.
6931        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6932            Some(home) => notices::raise_in(home, notice),
6933            None => notices::raise(notice),
6934        }
6935    }
6936}
6937
6938/// Every runnable task, in the order the loop should try them.
6939///
6940/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6941/// tail exists so that a claim somebody else holds costs the loop the next
6942/// candidate rather than a whole poll interval of idleness.
6943fn runnable(queue: &Queue) -> Vec<Task> {
6944    let mut tasks: Vec<Task> = queue
6945        .list()
6946        .into_iter()
6947        .filter(|t| t.status.runnable())
6948        .collect();
6949    tasks.sort_unstable_by(crate::queue::dispatch_order);
6950    tasks
6951}
6952
6953/// Why a run ended where it did, in one line, for [`Task::last_error`].
6954///
6955/// A stalled run names the seats the quota took out: "out of quota" is not
6956/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6957/// agent to replace or which plan to top up.
6958///
6959/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6960/// purpose: unlike `label`'s other callers (an internal log line, an
6961/// already-a-bug fallback message), this string becomes `Task::last_error`
6962/// verbatim, which the phone renders in the same alarm-styled box an
6963/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6964/// `.err` styling. A bare `verified_noop` there would read exactly like the
6965/// failure this whole feature exists to tell apart from one.
6966fn describe(state: &RunState) -> String {
6967    let p = phrases(&state.config.graph.language);
6968    let mut detail = if state.status == RunStatus::Stalled {
6969        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6970        seats.sort_unstable();
6971        seats.dedup();
6972        if seats.is_empty() {
6973            p.quorum_lost.to_owned()
6974        } else {
6975            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6976        }
6977    } else {
6978        format!("{}{}", p.run_ended, state.status.display_label())
6979    };
6980    if let Some(cause) = state.verification_blocking_cause() {
6981        detail.push_str(&format!(" ({cause})"));
6982    } else if let Some(last) = state.events.last() {
6983        // The review loop's "never answered" stop is the one event worth
6984        // translating; it is recognised from structured state, not by
6985        // matching the English event text (which stays as recorded).
6986        let unanswered = state
6987            .reviews
6988            .last()
6989            .filter(|r| {
6990                state.status == RunStatus::Blocked
6991                    && last.node == "review"
6992                    && r.incomplete()
6993                    && r.blocking == 0
6994                    && r.round == state.config.graph.review_rounds
6995                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6996            })
6997            .map(|r| (r.expected - r.answered, r.round));
6998        match unanswered {
6999            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
7000                detail.push_str(&format!(
7001                    " ({}: {})",
7002                    last.node,
7003                    (p.reviewers_never_answered)(missing, rounds)
7004                ));
7005            }
7006            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
7007        }
7008    }
7009    detail.push_str(&format!(" [run {}]", state.id));
7010    detail
7011}
7012
7013/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
7014///
7015/// The task file lives in the backlog indefinitely; a diagnostic is an
7016/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
7017/// stay small regardless of how much a gate command or a candidate printed.
7018const DIAGNOSTIC_MAX: usize = 4_000;
7019
7020/// Tail kept from a single failing command's output inside a diagnostic.
7021/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
7022/// pointer for a human deciding whether to go read the full artifact by hand,
7023/// not a replacement for reading it.
7024const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
7025
7026/// Assemble a bounded diagnostic excerpt from a held task's own run, so
7027/// `magi task show` says more than the one-line reason in [`describe`].
7028///
7029/// The one-liner answers "where did the run stop"; this answers "what would a
7030/// human have found opening `artifacts/` by hand" — the point of the whole
7031/// feature is the case that one-liner actively misleads on: a run held as "no
7032/// candidate produced a change" can mean the implementer actually finished
7033/// the task (opened a PR, merged it, tagged a release) and only left a clean
7034/// local worktree behind, which reads as "nothing happened" unless someone
7035/// goes and reads what the agent actually said. `None` when the run carries
7036/// none of the three shapes this recognises — an ordinary run held for
7037/// something not diagnosable from `RunState` alone still explains itself
7038/// through `Task::last_error`.
7039pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
7040    diagnostic(state)
7041}
7042
7043fn diagnostic(state: &RunState) -> Option<String> {
7044    let mut parts: Vec<String> = Vec::new();
7045
7046    if let Some(e2e) = &state.head_e2e
7047        && !e2e.passed
7048    {
7049        for o in e2e
7050            .outcomes
7051            .iter()
7052            .filter(|o| !o.ok() && !o.resource_blocked)
7053        {
7054            parts.push(format!(
7055                "head_e2e `{}` failed on {} ({}):\n{}",
7056                o.command,
7057                e2e.head.chars().take(7).collect::<String>(),
7058                notices::exit_status(o.code),
7059                crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7060            ));
7061        }
7062    }
7063
7064    // Gate failure: which check(s), and the tail of what each printed.
7065    for o in state.gate.iter().filter(|o| !o.ok()) {
7066        parts.push(format!(
7067            "gate `{}` failed ({}):\n{}",
7068            o.command,
7069            notices::exit_status(o.code),
7070            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7071        ));
7072    }
7073
7074    // The land loop gave up because the fixer declined while checks were
7075    // still red: the message already names them (see `land::run`).
7076    if let Some(last) = state
7077        .events
7078        .iter()
7079        .rev()
7080        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
7081    {
7082        parts.push(last.message.clone());
7083    }
7084
7085    // No viable candidate: every implementer's own final word, sanitized the
7086    // same way a judge would have read it, so a run that actually finished
7087    // the job does not read as an unexplained failure. A verified no-op is
7088    // called out ahead of its own summary and apart from an ordinary
7089    // failure's `why` — this is the one candidate shape whose diagnostic a
7090    // human is expected to actually judge, not just skim.
7091    if state.viable().is_empty() {
7092        for c in &state.candidates {
7093            if let Some(evidence) = &c.verified_noop {
7094                parts.push(format!(
7095                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
7096                    c.label
7097                ));
7098            } else if !c.summary.trim().is_empty() {
7099                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
7100            } else if let Some(why) = &c.failed {
7101                parts.push(format!("candidate {}: {why}", c.label));
7102            }
7103        }
7104    }
7105
7106    if parts.is_empty() {
7107        return None;
7108    }
7109    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
7110    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
7111    // back slightly over. Leave it enough room to always land under the
7112    // limit.
7113    Some(crate::run::tail(
7114        &parts.join("\n\n"),
7115        DIAGNOSTIC_MAX.saturating_sub(100),
7116    ))
7117}
7118
7119/// Stable lower-case name for a run status, for an internal log line and the
7120/// "graph stopped without reaching a terminal status" bug message in
7121/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
7122/// doc for why that one reads [`RunStatus::display_label`] instead. One
7123/// definition of a status's name, on the type that owns it: this table used
7124/// to live here as a second copy, and a status renamed in one place would
7125/// have gone on reading correctly in the other.
7126fn label(status: RunStatus) -> &'static str {
7127    status.as_str()
7128}
7129
7130/// Parse a merge mode override.
7131pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
7132    match mode {
7133        "none" => Ok(MergeMode::None),
7134        "local" => Ok(MergeMode::Local),
7135        "pr" => Ok(MergeMode::Pr),
7136        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
7137    }
7138}
7139
7140/// Take the status lock, recovering from a poisoned one.
7141///
7142/// A panic elsewhere must not silently stop the heartbeat: the status is plain
7143/// data, and the worst a poisoned lock can hold is a stale timestamp.
7144fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
7145    mutex
7146        .lock()
7147        .unwrap_or_else(std::sync::PoisonError::into_inner)
7148}
7149
7150#[cfg(test)]
7151mod tests {
7152    use super::*;
7153    use crate::queue::{Source, TaskStatus};
7154    use crate::run::{Candidate, CommandOutcome};
7155    use pretty_assertions::assert_eq;
7156
7157    fn task() -> Task {
7158        Task::new(
7159            "add retries".to_owned(),
7160            "add retries".to_owned(),
7161            PathBuf::from("/repo"),
7162            Source::Human,
7163        )
7164    }
7165
7166    #[test]
7167    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
7168        let skips = DispatchSkips::from([
7169            ("a".into(), SkipReason::CoolingDown),
7170            ("b".into(), SkipReason::WaitingOnLanding),
7171            ("c".into(), SkipReason::WaitingOnLanding),
7172            ("d".into(), SkipReason::OrdinaryCapacity),
7173        ]);
7174        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
7175        assert_eq!(wait.runnable, 4);
7176        assert_eq!(
7177            wait.reasons
7178                .iter()
7179                .map(|r| (r.reason.as_str(), r.count))
7180                .collect::<Vec<_>>(),
7181            [
7182                ("waiting_on_landing", 2),
7183                ("cooling_down", 1),
7184                ("ordinary_capacity", 1)
7185            ]
7186        );
7187        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
7188        assert!(
7189            aggregate_dispatch_wait(2, &DispatchSkips::new())
7190                .unwrap()
7191                .reasons
7192                .is_empty()
7193        );
7194    }
7195
7196    #[test]
7197    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
7198        let before = vec!["a".into(), "b".into(), "c".into()];
7199        let allowed = vec![task_with_id("b")];
7200        let skips = interrupt_skips(&before, &allowed);
7201        assert_eq!(
7202            skips,
7203            DispatchSkips::from([
7204                ("a".into(), SkipReason::InterruptGate),
7205                ("c".into(), SkipReason::InterruptGate),
7206            ])
7207        );
7208        let mut previous = DispatchSkips::new();
7209        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7210        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7211        assert!(!changed_dispatch_skips(&mut previous, skips));
7212        assert!(changed_dispatch_skips(
7213            &mut previous,
7214            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7215        ));
7216        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7217    }
7218
7219    #[test]
7220    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7221        let mut value = serde_json::to_value(Status::new()).unwrap();
7222        value.as_object_mut().unwrap().remove("dispatch_wait");
7223        assert!(
7224            serde_json::from_value::<Status>(value.clone())
7225                .unwrap()
7226                .dispatch_wait
7227                .is_none()
7228        );
7229        assert!(
7230            serde_json::from_value::<Reading>(value.clone())
7231                .unwrap()
7232                .dispatch_wait
7233                .is_none()
7234        );
7235        value["dispatch_wait"] = serde_json::json!({
7236            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7237        });
7238        let reading = serde_json::from_value::<Reading>(value).unwrap();
7239        assert_eq!(
7240            reading.dispatch_wait.unwrap().reasons[0].reason,
7241            "future_reason"
7242        );
7243    }
7244
7245    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7246        let job = crate::worker::Job {
7247            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7248            sequence: 1,
7249            kind: "task".into(),
7250            key: format!("task:{}", request.task),
7251            payload: serde_json::to_value(request).unwrap(),
7252            generation: "a".repeat(64),
7253            version: None,
7254            status: crate::worker::Status::Starting,
7255            result: None,
7256            pid: None,
7257            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7258            finished_at: None,
7259        };
7260        let dir = home.join("workers/jobs").join(&job.id);
7261        std::fs::create_dir_all(&dir).unwrap();
7262        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7263        job
7264    }
7265
7266    #[test]
7267    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7268        let home = tempfile::tempdir().unwrap();
7269        let request = TaskWorker {
7270            opts: Opts::default(),
7271            queue: home.path().join("queue"),
7272            task: "startup".into(),
7273            lane: PermitKind::Ordinary,
7274            standalone: false,
7275        };
7276        let job = starting_task_reservation(home.path(), &request);
7277        let error = task_worker_spawn_error(
7278            home.path(),
7279            &request,
7280            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7281        )
7282        .expect_err("our own reservation must not turn a failed spawn into a resync");
7283        let active = crate::worker::active(home.path()).unwrap();
7284        assert_eq!(active.len(), 1);
7285        assert_eq!(active[0].id, job.id);
7286        assert_eq!(active[0].status, crate::worker::Status::Starting);
7287        assert!(
7288            crate::worker::control(home.path(), &job.key)
7289                .unwrap()
7290                .is_none()
7291        );
7292        let notices = notices::Notices::at(home.path().join("notifications")).list();
7293        assert_eq!(notices.len(), 1);
7294        assert_eq!(notices[0].key, "loop:worker-startup");
7295        assert!(!notices[0].message.contains("private-error-detail"));
7296        assert!(notices[0].message.contains(&request.task));
7297        assert!(
7298            notices[0]
7299                .message
7300                .contains("could not be started or acknowledged")
7301        );
7302        assert!(notices[0].message.contains("worker.log"));
7303        assert_eq!(
7304            notices[0].link,
7305            Some(Link::Task {
7306                id: request.task.clone()
7307            })
7308        );
7309        assert!(format!("{error:#}").contains("private-error-detail"));
7310    }
7311
7312    #[test]
7313    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7314        let home = tempfile::tempdir().unwrap();
7315        let mut request = TaskWorker {
7316            opts: Opts::default(),
7317            queue: home.path().join("queue"),
7318            task: "handoff".into(),
7319            lane: PermitKind::Ordinary,
7320            standalone: true,
7321        };
7322        let job = starting_task_reservation(home.path(), &request);
7323        request.standalone = false;
7324        task_worker_spawn_error(
7325            home.path(),
7326            &request,
7327            anyhow::anyhow!("operation key is already reserved for a different request"),
7328        )
7329        .expect("a different standalone request is the handoff race, not our startup failure");
7330        let active = crate::worker::active(home.path()).unwrap();
7331        assert_eq!(active.len(), 1);
7332        assert_eq!(active[0].id, job.id);
7333        assert_eq!(active[0].payload, job.payload);
7334        assert!(
7335            notices::Notices::at(home.path().join("notifications"))
7336                .list()
7337                .is_empty()
7338        );
7339    }
7340
7341    #[test]
7342    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7343        let home = tempfile::tempdir().unwrap();
7344        let queue = Queue::at(home.path().join("queue"));
7345        let mut task = task();
7346        task.runs = vec!["previous".into()];
7347        queue.put(&mut task).unwrap();
7348        let request = TaskWorker {
7349            opts: Opts::default(),
7350            queue: home.path().join("queue"),
7351            task: task.id.clone(),
7352            lane: PermitKind::Ordinary,
7353            standalone: false,
7354        };
7355        let job = starting_task_reservation(home.path(), &request);
7356        let claims = current_work(home.path(), Timestamp::now());
7357        assert_eq!(claims.len(), 1);
7358        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7359        assert_eq!(claims[0].run, "previous");
7360        assert!(other_claims_run(&claims, "previous", None));
7361        // Only after confirming the executing caller may admission ignore
7362        // this exact projection. Cleanup continues to observe it as live.
7363        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7364        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7365    }
7366
7367    #[test]
7368    fn admission_excludes_only_the_callers_exact_reservation() {
7369        let own = Current {
7370            worker: Some("own".into()),
7371            task: "same-task".into(),
7372            run: "previous".into(),
7373        };
7374        assert!(!other_claims_run(
7375            std::slice::from_ref(&own),
7376            "previous",
7377            Some("own")
7378        ));
7379        assert!(other_claims_run(
7380            std::slice::from_ref(&own),
7381            "previous",
7382            None
7383        ));
7384        for worker in [None, Some("other".into())] {
7385            let other = Current {
7386                worker,
7387                ..own.clone()
7388            };
7389            assert!(other_claims_run(
7390                &[own.clone(), other],
7391                "previous",
7392                Some("own")
7393            ));
7394        }
7395        let legacy: Current =
7396            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7397        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7398    }
7399
7400    #[test]
7401    fn os_leased_task_worker_survives_wall_clock_advance() {
7402        let home = tempfile::tempdir().unwrap();
7403        let queue = Queue::at(home.path().join("queue"));
7404        let mut task = task();
7405        let run = "20260903-100000-abcd";
7406        task.start(run.into());
7407        queue.put(&mut task).unwrap();
7408        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
7409        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
7410        assert!(
7411            current_work(home.path(), future)
7412                .iter()
7413                .any(
7414                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
7415                        && claim.run == run
7416                )
7417        );
7418        worker.release_lease();
7419        assert!(worker.dir.join("job.json").is_file());
7420        assert!(!is_working_on(home.path(), run, future));
7421        let dir = worker.dir.clone();
7422        drop(worker);
7423        assert!(!dir.exists());
7424    }
7425
7426    #[test]
7427    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7428        let mut task = task();
7429        let mut run = run_state(RunStatus::Reviewing);
7430        run.task_instruction = Some(task.instruction.clone());
7431        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7432        let branch = "magi/test/B";
7433        run.candidates.push(crate::run::Candidate {
7434            branch: branch.into(),
7435            ..candidate('B', "preserved work", false, None)
7436        });
7437        task.runs = vec![run.id.clone()];
7438        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7439        assert_eq!(
7440            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7441            Starter::Resume(run.id.clone())
7442        );
7443        assert!(matches!(
7444            review_retry_starter(
7445                &task,
7446                Some(&run),
7447                Some("different"),
7448                true,
7449                unfinished.as_deref()
7450            ),
7451            Starter::Review(_)
7452        ));
7453        assert_eq!(
7454            review_retry_starter(
7455                &task,
7456                Some(&run),
7457                Some(branch),
7458                false,
7459                unfinished.as_deref()
7460            ),
7461            Starter::Start
7462        );
7463        task.instruction.push_str(" changed criteria");
7464        assert!(matches!(
7465            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7466            Starter::Review(_)
7467        ));
7468        assert!(matches!(
7469            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7470            Starter::Review(_)
7471        ));
7472    }
7473
7474    #[test]
7475    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7476        let dir = tempfile::tempdir().unwrap();
7477        let queue = Queue::at(dir.path().join("queue"));
7478        let mut task = task();
7479        task.status = TaskStatus::Running;
7480        task.attempts = 1;
7481        queue.put(&mut task).unwrap();
7482        let live = std::collections::BTreeSet::from([task.id.clone()]);
7483        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7484        drop(queue.claim(&task.id).unwrap());
7485        let saved = queue.get(&task.id).unwrap();
7486        assert_eq!(saved.status, TaskStatus::Running);
7487        assert_eq!(saved.attempts, 1);
7488        assert!(saved.last_error.is_none());
7489    }
7490
7491    #[test]
7492    fn standalone_workers_do_not_consume_scheduler_lanes() {
7493        let request = |task: &str, lane, standalone| TaskWorker {
7494            opts: Opts::default(),
7495            queue: PathBuf::from("/queue"),
7496            task: task.to_owned(),
7497            lane,
7498            standalone,
7499        };
7500        let mut jobs = vec![
7501            request("ordinary", PermitKind::Ordinary, false),
7502            request("standalone-urgent", PermitKind::Urgent, true),
7503            request("standalone-ordinary", PermitKind::Ordinary, true),
7504            request("decision", PermitKind::None, false),
7505        ];
7506        assert_eq!(available_slots(&jobs, 2), (1, 1));
7507        jobs.push(request("urgent", PermitKind::Urgent, false));
7508        assert_eq!(available_slots(&jobs, 2), (1, 0));
7509        assert_eq!(available_slots(&jobs, 0), (0, 0));
7510    }
7511
7512    #[test]
7513    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7514        let now = Timestamp::now();
7515        let mut reading = Reading {
7516            pid: Some(std::process::id()),
7517            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7518            ..Reading::default()
7519        };
7520        assert!(!reading.running(now));
7521        assert!(legacy_scheduler_running(&reading, now, 0));
7522        reading.worker_protocol = Some(1);
7523        assert!(!legacy_scheduler_running(&reading, now, 0));
7524    }
7525
7526    #[test]
7527    fn selected_public_head_overrides_historical_resume_and_pin() {
7528        let mut t = task();
7529        let mut old = run_state(RunStatus::Blocked);
7530        let selection = crate::pr_recovery::Selection {
7531            url: "url".into(),
7532            branch: format!("magi/task-{}", t.id),
7533            head: "a".repeat(40),
7534            source_head: None,
7535            source_run: None,
7536            source_proof: None,
7537            disposition: Some(crate::pr_recovery::Disposition::Review),
7538            instruction: t.instruction.clone(),
7539            approved_at: Timestamp::now(),
7540        };
7541        t.resume_override = Some(crate::queue::OperatorResume {
7542            pinned_run: Some(old.id.clone()),
7543            question_id: "choice".into(),
7544            at: Timestamp::now(),
7545            conductor_rehold: None,
7546            forced: false,
7547        });
7548        assert_eq!(
7549            selected_starter(&selection, Some(&old), Some(&old.id)),
7550            Starter::Review(selection.branch.clone())
7551        );
7552        old.pr_recovery = Some(selection.clone());
7553        assert_eq!(
7554            selected_starter(&selection, Some(&old), Some(&old.id)),
7555            Starter::Review(selection.branch.clone())
7556        );
7557        old.reviewed_commits = Some(vec!["implementation".into()]);
7558        assert_eq!(
7559            selected_starter(&selection, Some(&old), Some(&old.id)),
7560            Starter::Resume(old.id.clone())
7561        );
7562        let mut changed = selection.clone();
7563        changed.head = "b".repeat(40);
7564        assert_eq!(
7565            selected_starter(&changed, Some(&old), Some(&old.id)),
7566            Starter::Review(changed.branch)
7567        );
7568    }
7569
7570    #[test]
7571    fn candidate_transplant_failure_is_one_actionable_hold() {
7572        let dir = tempfile::tempdir().unwrap();
7573        let q = Queue::at(dir.path().join("queue"));
7574        let mut t = task();
7575        let mut state = run_state(RunStatus::Blocked);
7576        state.event("prep", "cannot apply referenced commit: conflict");
7577        state.prep_failure = Some("conflict".into());
7578        t.start(state.id.clone());
7579        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7580        assert_eq!(t.attempts, 1);
7581        assert_eq!(t.status, TaskStatus::Held);
7582        assert!(t.operator_held());
7583        assert!(!t.status.runnable());
7584        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7585        let first = t.chat_notice_key().unwrap();
7586        t.chat_notices.push(first.clone());
7587        t.release_operator("test", None);
7588        state.id = "another-unprepared-run".into();
7589        t.start(state.id.clone());
7590        finish_attempt(
7591            3,
7592            &q,
7593            &mut t,
7594            &state,
7595            &[],
7596            Err(anyhow::anyhow!("still conflicts")),
7597        );
7598        assert_eq!(
7599            t.chat_notice_key().as_ref(),
7600            Some(&first),
7601            "no work happened"
7602        );
7603        t.release_operator("test", None);
7604        state.prep_failure = None;
7605        state.status = RunStatus::Failed;
7606        state.begin_pass();
7607        t.start(state.id.clone());
7608        finish_attempt(
7609            1,
7610            &q,
7611            &mut t,
7612            &state,
7613            &[],
7614            Err(anyhow::anyhow!("new gate failure")),
7615        );
7616        let failure = t.chat_notice_key().unwrap();
7617        assert_ne!(failure, first, "approved recovery reached a real failure");
7618        t.release_operator("test", None);
7619        state.begin_pass();
7620        t.start(state.id.clone());
7621        finish_attempt(
7622            1,
7623            &q,
7624            &mut t,
7625            &state,
7626            &[],
7627            Err(anyhow::anyhow!("new failure on resume")),
7628        );
7629        assert_ne!(
7630            t.chat_notice_key().as_ref(),
7631            Some(&failure),
7632            "a new settled pass"
7633        );
7634    }
7635
7636    #[test]
7637    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7638        for source in ["cli", "web"] {
7639            let mut t = task();
7640            let mut run = run_state(RunStatus::Blocked);
7641            run.instruction = "Run A original criteria".into();
7642            run.task_instruction = Some(run.instruction.clone());
7643            t.start(run.id.clone());
7644            t.release_operator("choice", Some("resume-question"));
7645            t.resume_override = Some(crate::queue::OperatorResume {
7646                question_id: "resume-question".into(),
7647                at: Timestamp::now(),
7648                conductor_rehold: None,
7649                forced: true,
7650                pinned_run: Some(run.id.clone()),
7651            });
7652            t.hold_machine(Some("not enough free space to start a run".into()));
7653            let mut unchanged = t.clone();
7654            unchanged
7655                .edit("title changed".into(), unchanged.instruction.clone())
7656                .unwrap();
7657            unchanged.release_operator(source, None);
7658            assert_eq!(
7659                unchanged
7660                    .resume_override
7661                    .as_ref()
7662                    .unwrap()
7663                    .pinned_run
7664                    .as_deref(),
7665                Some(run.id.as_str())
7666            );
7667            assert!(!compatible_run_instruction(&run, &unchanged));
7668            assert!(may_resume_run(&run, &unchanged));
7669
7670            t.edit(
7671                "approved recovery".into(),
7672                "Reuse measured PR head B; fix Clippy; review".into(),
7673            )
7674            .unwrap();
7675            assert!(t.resume_override.is_none());
7676            t.release_operator(source, None);
7677            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7678            assert!(reloaded.resume_override.is_none());
7679            assert!(!may_resume_run(&run, &reloaded));
7680            let unfinished =
7681                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7682                    .filter(|_| may_resume_run(&run, &reloaded));
7683            assert_eq!(
7684                choose_starter(None, false, unfinished.as_deref()),
7685                Starter::Start
7686            );
7687            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7688            assert_eq!(
7689                reloaded.resumption_history[0].question_id.as_deref(),
7690                Some("resume-question")
7691            );
7692
7693            // A revision already persisted with the old approval/pin is also
7694            // invalidated when the new operator release is recorded.
7695            unchanged.instruction = "Reuse measured PR head B".into();
7696            unchanged.hold_machine(Some("disk hold".into()));
7697            unchanged.release_operator(source, None);
7698            assert!(unchanged.resume_override.is_none());
7699            assert!(!may_resume_run(&run, &unchanged));
7700        }
7701    }
7702
7703    #[test]
7704    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7705        let mut t = task();
7706        let mut run = run_state(RunStatus::Blocked);
7707        t.review_of = Some("approved-head".into());
7708        t.instruction =
7709            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7710                .into();
7711        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();
7712        run.reviewed_commits = Some(vec!["Commit log".into()]);
7713        t.start(run.id.clone());
7714        t.hold_machine(Some("interrupted review".into()));
7715        t.release_operator("cli", None);
7716        assert!(
7717            compatible_run_instruction(&run, &t),
7718            "legacy explicit review remains resumable"
7719        );
7720        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7721            .filter(|_| compatible_run_instruction(&run, &t));
7722        assert_eq!(
7723            choose_starter(None, false, unfinished.as_deref()),
7724            Starter::Resume(run.id.clone())
7725        );
7726        run.task_instruction = Some(t.instruction.clone());
7727        assert!(compatible_run_instruction(&run, &t));
7728        let reloaded: RunState =
7729            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7730        assert!(compatible_run_instruction(&reloaded, &t));
7731        t.edit(
7732            "new approved head".into(),
7733            "Reuse measured PR head B".into(),
7734        )
7735        .unwrap();
7736        assert!(!compatible_run_instruction(&run, &t));
7737
7738        // Legacy recovery reviews retain the task criteria ahead of the log.
7739        t.review_of = None;
7740        t.instruction = "Fix Clippy on approved head".into();
7741        run.task_instruction = None;
7742        run.instruction = format!(
7743            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7744            t.instruction
7745        );
7746        assert!(compatible_run_instruction(&run, &t));
7747        t.instruction.push('\n');
7748        assert!(
7749            compatible_run_instruction(&run, &t),
7750            "legacy generated review trimmed the original criteria"
7751        );
7752        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7753        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7754        t.edit("new plan".into(), "Reuse measured PR head B".into())
7755            .unwrap();
7756        assert!(review_branch_for(&t, Some(&run)).is_none());
7757        assert!(!compatible_run_instruction(&run, &t));
7758        t.review_branch = Some("approved-head".into());
7759        t.review_instruction = None;
7760        assert!(
7761            review_branch_for(&t, Some(&run)).is_none(),
7762            "legacy retained candidate cannot replace a revised approved head"
7763        );
7764    }
7765
7766    #[test]
7767    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7768        let home = crate::run::test_home();
7769        crate::run::pin_test_home();
7770        let dir = tempfile::tempdir().unwrap();
7771        let queue = Queue::at(dir.path().join("queue"));
7772        for resume in [true, false] {
7773            let state = run_state(RunStatus::Blocked);
7774            let mut t = task();
7775            t.start(state.id.clone());
7776            let action = if resume {
7777                ask::ChoiceAction::Resume {
7778                    run: state.id.clone(),
7779                }
7780            } else {
7781                ask::ChoiceAction::Requeue
7782            };
7783            let mut q = action_question(&state.id, action);
7784            q.status = ask::QuestionStatus::Open;
7785            q.answer = None;
7786            q.answered_at = None;
7787            t.fail("run stopped with a question", 3);
7788            hold_if_runnable(&queue, &mut t);
7789            assert!(t.operator_decided_at.is_none());
7790            assert!(t.operator_held());
7791            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7792            let expected = if resume {
7793                ActionDecision::Resume(state.id.clone())
7794            } else {
7795                ActionDecision::Requeue
7796            };
7797            assert_eq!(
7798                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7799                expected
7800            );
7801            t.hold_manual(Some("later explicit hold".into()));
7802            assert_eq!(
7803                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7804                ActionDecision::Stale
7805            );
7806        }
7807    }
7808
7809    #[test]
7810    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7811        let mut t = task();
7812        t.answers.push(crate::queue::AnsweredQuestion {
7813            question: "Inspect the remote?".into(),
7814            answer: "Inspect then wait".into(),
7815        });
7816        let old = instruction_for(&t);
7817        assert!(compatible_instruction(&old, &t));
7818        t.instruction = "Reuse approved PR head and review".into();
7819        t.release_operator("cli", None);
7820        assert!(!compatible_instruction(&old, &t));
7821        let approved = instruction_for(&t);
7822        assert!(approved.contains("waiting premises are superseded"));
7823        assert!(compatible_instruction(&approved, &t));
7824        assert_eq!(resumed_instruction(&approved, &t), approved);
7825        t.release_operator("web", None);
7826        assert!(compatible_instruction(&approved, &t));
7827        assert_eq!(t.resumption_history.len(), 1);
7828        t.start("run".into());
7829        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7830    }
7831
7832    /// A run that stopped on an infrastructure wait asked no agent anything:
7833    /// the task is held by the machine under a `[resource]` reason (resumable,
7834    /// re-checked by triage), and the attempt it started is given back.
7835    #[test]
7836    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7837        let mut state = RunState::new(
7838            PathBuf::from("/repo"),
7839            "main".into(),
7840            "base".into(),
7841            "task".into(),
7842            Config::default(),
7843        );
7844        state.status = RunStatus::Landing;
7845        state.parked = true;
7846        state.pr_pushed_head = Some("head".into());
7847        state.land_unrelated = Some(
7848            serde_json::from_value(serde_json::json!({
7849                "head": "head", "question": "ci-question",
7850                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7851            }))
7852            .unwrap(),
7853        );
7854        let mut t = task();
7855        t.start(state.id.clone());
7856        let verdict = Verdict {
7857            status: RunStatus::Landing,
7858            left_pr: true,
7859            quota_hit: false,
7860            parked: true,
7861            no_viable_candidates: false,
7862        };
7863        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7864        assert_eq!(t.attempts, 0);
7865        assert_eq!(t.status, TaskStatus::Held);
7866        assert!(!t.operator_held());
7867        assert!(
7868            t.hold_reason
7869                .as_deref()
7870                .unwrap()
7871                .starts_with("[ci-unrelated]")
7872        );
7873        // A second settlement must not refund an earlier task attempt.
7874        t.attempts = 1;
7875        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7876        assert_eq!(t.attempts, 1);
7877        assert_eq!(t.passes.len(), 1);
7878        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7879        state.pr_pushed_head = Some("new-head".into());
7880        state.parked = false;
7881        state.status = RunStatus::Blocked;
7882        let stale = Verdict {
7883            status: RunStatus::Blocked,
7884            parked: false,
7885            ..verdict
7886        };
7887        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7888        assert_eq!(t.attempts, 1);
7889        // A new execution pass can refund its own newly charged attempt.
7890        state.begin_pass();
7891        state.begin_pass();
7892        state.status = RunStatus::Landing;
7893        state.parked = true;
7894        state.pr_pushed_head = Some("head".into());
7895        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7896        assert_eq!(t.attempts, 0);
7897        assert_eq!(t.passes.len(), 2);
7898    }
7899
7900    #[test]
7901    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7902        let mut state = run_state(RunStatus::Failed);
7903        state
7904            .quota
7905            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7906        state.begin_pass();
7907        let mut t = task();
7908        t.start(state.id.clone());
7909        reclaim(&mut t, Some(state), 2, "en");
7910        assert_eq!(t.attempts, 1);
7911    }
7912
7913    #[test]
7914    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7915        let mut state = run_state(RunStatus::Blocked);
7916        let losses: Vec<_> = ["alpha", "beta"]
7917            .into_iter()
7918            .enumerate()
7919            .map(|(i, agent)| {
7920                QuotaLoss::from_report(
7921                    format!("advisor-{i}"),
7922                    "advise",
7923                    Some(&crate::agent::Quota {
7924                        cause: crate::agent::QuotaCause::Authentication,
7925                        agent: agent.to_owned(),
7926                        reset: None,
7927                    }),
7928                )
7929            })
7930            .collect();
7931        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7932        state.quota = losses;
7933        let mut t = task();
7934        t.start(state.id.clone());
7935        let verdict = Verdict {
7936            status: state.status,
7937            left_pr: false,
7938            quota_hit: true,
7939            parked: false,
7940            no_viable_candidates: true,
7941        };
7942        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7943        assert_eq!(t.attempts, 0);
7944        assert_eq!(t.status, TaskStatus::Held);
7945        assert!(!t.operator_held());
7946        let reason = t.hold_reason.as_deref().unwrap();
7947        assert!(reason.starts_with("[authentication]"));
7948        assert!(
7949            reason.contains("alpha")
7950                && reason.contains("beta")
7951                && reason.contains("re-authenticate")
7952        );
7953        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7954        // Orphan recovery uses the same settlement and cannot spend an attempt.
7955        let mut orphan = task();
7956        orphan.start(state.id.clone());
7957        reclaim(&mut orphan, Some(state), 2, "en");
7958        assert_eq!(orphan.attempts, 0);
7959        assert_eq!(orphan.status, TaskStatus::Held);
7960    }
7961
7962    #[test]
7963    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7964        let mut state = RunState::new(
7965            PathBuf::from("/repo"),
7966            "main".to_owned(),
7967            "abc1234".to_owned(),
7968            "task".to_owned(),
7969            Config::default(),
7970        );
7971        state.status = RunStatus::Blocked;
7972        state.resource_block = Some(crate::run::ResourceBlock {
7973            cause: crate::run::ResourceBlockCause::Other,
7974            node: "graft".to_owned(),
7975            kind: "shared build cache".to_owned(),
7976            detail: "timed out".to_owned(),
7977            at: jiff::Timestamp::now(),
7978        });
7979        let mut t = task();
7980        t.start("20260902-000000-aaaa".to_owned());
7981        assert_eq!(t.attempts, 1);
7982        let verdict = Verdict {
7983            status: RunStatus::Blocked,
7984            left_pr: false,
7985            quota_hit: false,
7986            parked: false,
7987            no_viable_candidates: false,
7988        };
7989        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7990        assert_eq!(t.status, TaskStatus::Held);
7991        assert_eq!(t.attempts, 0, "the attempt is refunded");
7992        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7993        assert!(
7994            !t.operator_held(),
7995            "a machine hold, released without a human"
7996        );
7997
7998        let mut selected = task();
7999        selected.start("20260902-000000-cccc".into());
8000        selected.replacement = Some(crate::merge_decision::Replacement {
8001            question: "fixture".into(),
8002            run: "earlier".into(),
8003            pr: "https://example.invalid/pr/1".into(),
8004            agent: "selected".into(),
8005            context: "fixture".into(),
8006        });
8007        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
8008        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
8009        assert_eq!(selected.attempts, 0);
8010        assert!(
8011            !selected.operator_held(),
8012            "a selected agent also retains a machine resource hold"
8013        );
8014        assert!(
8015            selected
8016                .hold_reason
8017                .as_deref()
8018                .unwrap()
8019                .starts_with("[resource] ")
8020        );
8021
8022        // A park request outranks it: still the operator's doing.
8023        let mut p = task();
8024        p.start("20260902-000000-bbbb".to_owned());
8025        settle_and_diagnose(
8026            &mut p,
8027            Verdict {
8028                parked: true,
8029                ..verdict
8030            },
8031            "parked",
8032            2,
8033            &state,
8034        );
8035        assert_eq!(p.status, TaskStatus::Parked);
8036        assert_eq!(
8037            p.attempts, 0,
8038            "parking refunds once rather than also settling the resource hold"
8039        );
8040    }
8041
8042    #[test]
8043    fn record_failure_notice_links_the_task() {
8044        let dir = tempfile::tempdir().unwrap();
8045        // A regular file where the queue directory should be makes every
8046        // `put` fail, on every platform and whoever runs the test.
8047        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
8048        let queue = Queue::at(dir.path().join("queue"));
8049        let mut t = interrupt_task("rec-fail-1");
8050        record(&queue, &mut t);
8051
8052        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
8053        assert_eq!(found.len(), 1);
8054        assert_eq!(found[0].key, "loop:record");
8055        assert_eq!(
8056            found[0].link,
8057            Some(Link::Task {
8058                id: "rec-fail-1".to_owned()
8059            })
8060        );
8061    }
8062
8063    /// A runnable task marked to interrupt, with an id fixed for assertions
8064    /// rather than the random one [`Task::new`] mints.
8065    fn interrupt_task(id: &str) -> Task {
8066        let mut t = task();
8067        t.id = id.to_owned();
8068        t.interrupt = true;
8069        t
8070    }
8071
8072    /// An ordinary runnable task with an id fixed for assertions.
8073    fn task_with_id(id: &str) -> Task {
8074        let mut t = task();
8075        t.id = id.to_owned();
8076        t
8077    }
8078
8079    /// A runnable task marked `--urgent`, with an id fixed for assertions.
8080    fn urgent_task(id: &str) -> Task {
8081        let mut t = task();
8082        t.id = id.to_owned();
8083        t.urgent = true;
8084        t
8085    }
8086
8087    #[test]
8088    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
8089        let dir = tempfile::tempdir().unwrap();
8090        let queue = Queue::at(dir.path().join("queue"));
8091        let mut parked = task_with_id("parked");
8092        parked.start("run".into());
8093        parked.park("upgrade");
8094        parked.record_pass_at(
8095            "run",
8096            0,
8097            Some(Timestamp::now()),
8098            1,
8099            Some(crate::run::ParkCause::Upgrade {
8100                from: "old".into(),
8101                to: None,
8102            }),
8103        );
8104        let mut fresh = task_with_id("fresh");
8105        fresh.priority = 100;
8106        let mut urgent_task = urgent_task("urgent");
8107        for t in [&mut parked, &mut fresh, &mut urgent_task] {
8108            queue.put(t).unwrap();
8109        }
8110        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8111        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8112        let candidates = runnable(&queue);
8113        assert_eq!(candidates[0].id, parked.id);
8114        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
8115        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
8116        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
8117        drop(first);
8118        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
8119        let next = runnable(&queue)
8120            .into_iter()
8121            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
8122            .unwrap();
8123        assert_eq!(next.task.id, fresh.id);
8124        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
8125        drop(claimed_elsewhere);
8126        drop(next);
8127        assert!(matches!(
8128            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
8129            Err(SkipReason::CoolingDown)
8130        ));
8131    }
8132
8133    #[test]
8134    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
8135        let dir = tempfile::tempdir().unwrap();
8136        let queue = Queue::at(dir.path().join("queue"));
8137        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8138        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8139        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
8140        let mut first = task();
8141        queue.put(&mut first).unwrap();
8142        let stale_plain = queue.get(&first.id).unwrap();
8143        first.set_urgent(true).unwrap();
8144        queue.put(&mut first).unwrap();
8145        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
8146        let mut second = urgent_task("second");
8147        queue.put(&mut second).unwrap();
8148        assert!(matches!(
8149            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
8150            Err(SkipReason::UrgentCapacity)
8151        ));
8152        drop(queue.claim(&second.id).unwrap());
8153        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
8154        drop(dispatched);
8155        let stale_urgent = queue.get(&first.id).unwrap();
8156        first.set_urgent(false).unwrap();
8157        queue.put(&mut first).unwrap();
8158        assert!(matches!(
8159            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
8160            Err(SkipReason::OrdinaryCapacity)
8161        ));
8162        assert_eq!(urgent.available_permits(), 1);
8163        drop(queue.claim(&first.id).unwrap());
8164        drop(occupied);
8165    }
8166
8167    #[test]
8168    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
8169        let dir = tempfile::tempdir().unwrap();
8170        let queue = Queue::at(dir.path().join("queue"));
8171        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8172        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8173        let mut t = task();
8174        queue.put(&mut t).unwrap();
8175        for enabled in [true, false] {
8176            let stale = queue.get(&t.id).unwrap();
8177            t.set_urgent(enabled).unwrap();
8178            queue.put(&mut t).unwrap();
8179            assert_ne!(stale.urgent, enabled);
8180            let DispatchClaim {
8181                task: fresh,
8182                claim,
8183                permit,
8184            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
8185            assert_eq!(fresh.urgent, enabled);
8186            assert_eq!(ordinary.available_permits(), usize::from(enabled));
8187            assert_eq!(urgent.available_permits(), usize::from(!enabled));
8188            assert!(queue.claim(&t.id).is_err());
8189            assert_eq!(fresh.attempts, stale.attempts);
8190            drop((claim, permit));
8191            assert_eq!(ordinary.available_permits(), 1);
8192            assert_eq!(urgent.available_permits(), 1);
8193        }
8194        t.set_urgent(true).unwrap();
8195        queue.put(&mut t).unwrap();
8196        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
8197        assert!(matches!(
8198            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8199            Err(SkipReason::UrgentCapacity)
8200        ));
8201        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
8202        drop(queue.claim(&t.id).unwrap());
8203        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
8204        drop(occupied);
8205        assert!(matches!(
8206            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
8207            Err(SkipReason::CoolingDown)
8208        ));
8209        drop(queue.claim(&t.id).unwrap());
8210        let held = queue.claim(&t.id).unwrap();
8211        assert!(matches!(
8212            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8213            Err(SkipReason::ClaimUnavailable)
8214        ));
8215        drop(held);
8216        t.status = TaskStatus::Held;
8217        queue.put(&mut t).unwrap();
8218        assert!(matches!(
8219            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8220            Err(SkipReason::NoLongerRunnable)
8221        ));
8222        drop(queue.claim(&t.id).unwrap());
8223        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
8224        assert!(matches!(
8225            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8226            Err(SkipReason::RereadFailed)
8227        ));
8228        drop(queue.claim(&t.id).unwrap());
8229        assert_eq!(urgent.available_permits(), 1);
8230    }
8231
8232    /// The land-resume exemption wins outright, whether or not the candidate
8233    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
8234    /// queue behind anything" guarantee cannot be weaker just because the
8235    /// same task was also filed with `--urgent`.
8236    #[test]
8237    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8238        assert_eq!(permit_kind(true, false), PermitKind::None);
8239        assert_eq!(permit_kind(true, true), PermitKind::None);
8240    }
8241
8242    /// The one property this whole feature exists for: `--urgent` draws from
8243    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
8244    /// ordinary candidate draws from the ordinary pool exactly as before,
8245    /// untouched by the urgent slot's existence.
8246    #[test]
8247    fn permit_kind_separates_urgent_from_ordinary() {
8248        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8249        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8250    }
8251
8252    /// The exact wiring `attempt` runs before minting anything: a config's
8253    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
8254    /// Free space is injected rather than asked of the real disk - the point
8255    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
8256    /// is deterministic on every machine this test runs on, never dependent
8257    /// on how full the CI runner's own disk happens to be.
8258    #[test]
8259    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8260        let cfg = Config::default();
8261        let repo = Path::new("/any/repo/path");
8262
8263        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8264            .expect("must hold below the threshold");
8265        assert!(reason.contains("1024"), "{reason}");
8266        assert!(
8267            reason.contains(&cfg.disk.min_free_bytes.to_string()),
8268            "{reason}"
8269        );
8270
8271        assert_eq!(
8272            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8273            None,
8274            "exactly at the floor is open"
8275        );
8276        assert_eq!(
8277            disk_gate_with(
8278                repo,
8279                &cfg,
8280                PathBuf::new,
8281                |_| Ok(cfg.disk.min_free_bytes + 1)
8282            ),
8283            None,
8284            "comfortably above the floor is open"
8285        );
8286    }
8287
8288    #[test]
8289    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8290        let dir = tempfile::tempdir().unwrap();
8291        let repo = dir.path().join("repo");
8292        let cache = dir.path().join("cache");
8293        let worktrees = dir.path().join("worktrees");
8294        for path in [&repo, &cache, &worktrees] {
8295            std::fs::create_dir(path).unwrap();
8296        }
8297        let mut cfg = Config::default();
8298        cfg.graph.worktree_root = Some(worktrees.clone());
8299        cfg.verify.gate = vec![format!(
8300            "CARGO_TARGET_DIR='{}' cargo build",
8301            cache.display()
8302        )];
8303        for blocked in [&cache, &worktrees] {
8304            for unmeasured in [false, true] {
8305                assert!(
8306                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8307                        if path == blocked {
8308                            if unmeasured {
8309                                Err(anyhow::anyhow!("measurement failed"))
8310                            } else {
8311                                Ok(0)
8312                            }
8313                        } else {
8314                            Ok(u64::MAX)
8315                        }
8316                    })
8317                    .is_some(),
8318                    "a blocked secondary output volume must close admission"
8319                );
8320            }
8321        }
8322        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8323    }
8324
8325    #[test]
8326    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8327        let dir = tempfile::tempdir().unwrap();
8328        let repo = dir.path().join("repo");
8329        let cache = dir.path().join("cache");
8330        let home_parent = dir.path().join("run-volume");
8331        let home = home_parent.join("new-home");
8332        for path in [&repo, &cache, &home_parent] {
8333            std::fs::create_dir(path).unwrap();
8334        }
8335        let mut cfg = Config::default();
8336        cfg.graph.worktree_root = Some(repo.clone());
8337        cfg.verify.gate = vec![format!(
8338            "CARGO_TARGET_DIR='{}' cargo build",
8339            cache.display()
8340        )];
8341        cfg.verify.build_cache = BuildCache::Isolated;
8342        let denied = |blocked: &Path| {
8343            disk_gate_with(
8344                &repo,
8345                &cfg,
8346                || home.clone(),
8347                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8348            )
8349            .is_some()
8350        };
8351        assert!(!denied(&cache));
8352        assert!(denied(&home_parent));
8353    }
8354
8355    #[test]
8356    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8357        let mut cfg = Config::default();
8358        cfg.disk.min_free_bytes = 0;
8359        let repo = Path::new("/any/repo/path");
8360        assert_eq!(
8361            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8362            None,
8363            "a zero floor never measures at all"
8364        );
8365    }
8366
8367    #[test]
8368    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8369        let cfg = Config::default();
8370        let repo = Path::new("/any/repo/path");
8371        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8372            Err(anyhow::anyhow!("no df on this box"))
8373        })
8374        .expect("a measurement failure must close the gate, not open it");
8375        assert!(reason.contains("could not measure"), "{reason}");
8376    }
8377
8378    #[test]
8379    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8380        let ordinary = task();
8381        let next = advance_interrupt(
8382            Interrupt::Idle,
8383            std::slice::from_ref(&ordinary.id),
8384            std::slice::from_ref(&ordinary),
8385        );
8386        assert_eq!(next, Interrupt::Idle);
8387    }
8388
8389    #[test]
8390    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8391        // Nothing to interrupt - this is just an ordinary candidate, and the
8392        // loop's normal dispatch will pick it up like any other.
8393        let marked = interrupt_task("marked");
8394        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8395        assert_eq!(next, Interrupt::Idle);
8396    }
8397
8398    #[test]
8399    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8400        let marked = interrupt_task("marked");
8401        let next = advance_interrupt(
8402            Interrupt::Idle,
8403            &["running".to_owned()],
8404            std::slice::from_ref(&marked),
8405        );
8406        assert_eq!(
8407            next,
8408            Interrupt::Parking {
8409                parked: vec!["running".to_owned()],
8410                interrupt_task: "marked".to_owned(),
8411            }
8412        );
8413    }
8414
8415    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
8416    /// one run can be in flight when a task becomes runnable and marked.
8417    /// Parking all of them would mean `Resuming` later has more than one id
8418    /// to release back to ordinary dispatch, which cannot be made safe
8419    /// against that same setting's own extra concurrency slots letting two
8420    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
8421    /// The simplification the task's own constraints ask for: do not begin
8422    /// a sequence at all until the herd settles back to exactly one.
8423    #[test]
8424    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8425        let marked = interrupt_task("marked");
8426
8427        let two = advance_interrupt(
8428            Interrupt::Idle,
8429            &["a".to_owned(), "b".to_owned()],
8430            std::slice::from_ref(&marked),
8431        );
8432        assert_eq!(two, Interrupt::Idle);
8433
8434        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8435        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8436    }
8437
8438    #[test]
8439    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8440        let state = Interrupt::Parking {
8441            parked: vec!["running".to_owned()],
8442            interrupt_task: "marked".to_owned(),
8443        };
8444        // Still in flight: no change.
8445        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8446        assert_eq!(still_going, state);
8447
8448        // Left flight, but the interrupt task has not been dispatched yet on
8449        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8450        // as long as it is still runnable.
8451        let stopped_but_not_yet_dispatched =
8452            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8453        assert_eq!(stopped_but_not_yet_dispatched, state);
8454
8455        // Left flight, and the interrupt task is now in flight itself.
8456        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8457        assert_eq!(
8458            dispatched,
8459            Interrupt::Running {
8460                parked: vec!["running".to_owned()],
8461                interrupt_task: "marked".to_owned(),
8462            }
8463        );
8464    }
8465
8466    #[test]
8467    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8468        let state = Interrupt::Running {
8469            parked: vec!["running".to_owned()],
8470            interrupt_task: "marked".to_owned(),
8471        };
8472        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8473        assert_eq!(still_running, state);
8474
8475        // Whatever it ended as - merged, failed, held - is not this
8476        // function's concern: leaving flight is the only trigger, driven
8477        // straight off the same in-flight list `poll` already reaps. It does
8478        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8479        // why that would let an unrelated task start ahead of, or alongside,
8480        // the guaranteed resume.
8481        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8482        assert_eq!(
8483            ended,
8484            Interrupt::Resuming {
8485                parked: vec!["running".to_owned()]
8486            }
8487        );
8488    }
8489
8490    #[test]
8491    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8492        let state = Interrupt::Resuming {
8493            parked: vec!["running".to_owned()],
8494        };
8495        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8496        assert_eq!(still_waiting, state);
8497
8498        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8499        assert_eq!(dispatched, Interrupt::Idle);
8500    }
8501
8502    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8503    /// or otherwise moved on by an operator with no claim standing in the
8504    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8505    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8506    /// come. The parked run still gets its resume.
8507    #[test]
8508    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8509    {
8510        let state = Interrupt::Parking {
8511            parked: vec!["running".to_owned()],
8512            interrupt_task: "marked".to_owned(),
8513        };
8514        // `marked` has been held/blocked/deleted since the sequence began:
8515        // it no longer appears in `runnable` at all.
8516        let next = advance_interrupt(state, &[], &[]);
8517        assert_eq!(
8518            next,
8519            Interrupt::Resuming {
8520                parked: vec!["running".to_owned()]
8521            },
8522            "abandoning the interrupt must not abandon the resume it owes"
8523        );
8524    }
8525
8526    /// The same abandonment, one step later: `Resuming` itself must not wait
8527    /// forever for a parked task that has since become unrunnable.
8528    #[test]
8529    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8530        let state = Interrupt::Resuming {
8531            parked: vec!["running".to_owned()],
8532        };
8533        let next = advance_interrupt(state, &[], &[]);
8534        assert_eq!(
8535            next,
8536            Interrupt::Idle,
8537            "nothing is left to wait for; the loop must not stay wedged"
8538        );
8539    }
8540
8541    #[test]
8542    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8543        let marked = interrupt_task("marked");
8544        let next = advance_interrupt_tick(
8545            false,
8546            Interrupt::Idle,
8547            &["running".to_owned()],
8548            std::slice::from_ref(&marked),
8549        );
8550        assert_eq!(
8551            next,
8552            Interrupt::Idle,
8553            "an unmarked, unconfigured daemon must behave exactly as before"
8554        );
8555    }
8556
8557    #[test]
8558    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8559        let state = Interrupt::Parking {
8560            parked: vec!["running".to_owned()],
8561            interrupt_task: "marked".to_owned(),
8562        };
8563        let candidates = vec![interrupt_task("marked"), task()];
8564        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8565        assert!(
8566            allowed.is_empty(),
8567            "nothing may dispatch - not even the interrupt task itself - \
8568             until the parked run has actually stopped"
8569        );
8570    }
8571
8572    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8573    /// grow a special case for it: an urgent candidate that is not the
8574    /// interrupt task withholds exactly like an ordinary one for as long as
8575    /// the parked run it is racing has not actually left flight. A version
8576    /// of this feature once bypassed the gate for urgent candidates, on the
8577    /// theory that a genuinely separate concurrency lane could not collide
8578    /// with 75dd's own; it could, and did - the bypassed task dispatched
8579    /// alongside a run 75dd's own state machine had only *asked* to park,
8580    /// not yet confirmed gone, which is exactly the second run
8581    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8582    /// tick during Parking/Running/Resuming where letting an extra
8583    /// candidate through is safe, urgent or not - the parked run may still
8584    /// be genuinely mid-call.
8585    #[test]
8586    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8587        for state in [
8588            Interrupt::Parking {
8589                parked: vec!["running".to_owned()],
8590                interrupt_task: "marked".to_owned(),
8591            },
8592            Interrupt::Running {
8593                parked: vec!["running".to_owned()],
8594                interrupt_task: "marked".to_owned(),
8595            },
8596            Interrupt::Resuming {
8597                parked: vec!["running".to_owned()],
8598            },
8599        ] {
8600            let candidates = vec![
8601                interrupt_task("marked"),
8602                urgent_task("hot"),
8603                task_with_id("ordinary"),
8604            ];
8605            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8606            assert!(
8607                !allowed.iter().any(|t| t.id == "hot"),
8608                "an urgent candidate must wait out the same gate as anything \
8609                 else while the run it would run alongside has not actually \
8610                 left flight, for state {state:?}: {allowed:?}"
8611            );
8612        }
8613    }
8614
8615    /// The one case where marking a task `--urgent` and `interrupt` at once
8616    /// is not redundant: once the interrupt sequence's own guaranteed
8617    /// resume/dispatch actually admits the task, it is unaffected by also
8618    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8619    /// never on the urgent flag.
8620    #[test]
8621    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8622        let state = Interrupt::Resuming {
8623            parked: vec!["hot".to_owned()],
8624        };
8625        let candidates = vec![urgent_task("hot"), task()];
8626        let allowed = interrupt_gate(&state, &[], candidates);
8627        assert_eq!(
8628            allowed.iter().filter(|t| t.id == "hot").count(),
8629            1,
8630            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8631        );
8632    }
8633
8634    #[test]
8635    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8636        let state = Interrupt::Parking {
8637            parked: vec!["running".to_owned()],
8638            interrupt_task: "marked".to_owned(),
8639        };
8640        let other = task();
8641        let candidates = vec![interrupt_task("marked"), other.clone()];
8642        let allowed = interrupt_gate(&state, &[], candidates);
8643        assert_eq!(allowed.len(), 1);
8644        assert_eq!(allowed[0].id, "marked");
8645    }
8646
8647    #[test]
8648    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8649        let state = Interrupt::Running {
8650            parked: vec!["running".to_owned()],
8651            interrupt_task: "marked".to_owned(),
8652        };
8653        let candidates = vec![task(), task()];
8654        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8655        assert!(allowed.is_empty());
8656    }
8657
8658    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8659    /// sequence began (only reachable above the default
8660    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8661    /// never both in the same tick, which is what "exactly one resume, no
8662    /// simultaneous run" actually requires structurally rather than by
8663    /// coincidence of how many ordinary slots happen to be free.
8664    #[test]
8665    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8666        let state = Interrupt::Resuming {
8667            parked: vec!["a".to_owned(), "c".to_owned()],
8668        };
8669        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8670        let allowed = interrupt_gate(&state, &[], candidates);
8671        assert_eq!(
8672            allowed.len(),
8673            1,
8674            "at most one candidate may be offered while resuming: {allowed:?}"
8675        );
8676        assert_eq!(allowed[0].id, "a");
8677    }
8678
8679    #[test]
8680    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8681        let state = Interrupt::Resuming {
8682            parked: vec!["a".to_owned()],
8683        };
8684        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8685        assert!(allowed.is_empty());
8686    }
8687
8688    /// The invariant the completion criteria ask for by name: across a whole
8689    /// simulated sequence, there is never a tick where the gate would let
8690    /// through both the parked run's resume and the interrupt task, and
8691    /// exactly one candidate resumes the instant the interrupt task's run
8692    /// ends - never zero, never more than one.
8693    #[test]
8694    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8695        let running = task(); // id: whatever `Task::new` minted
8696        let marked = interrupt_task("marked");
8697
8698        let mut state = Interrupt::Idle;
8699        // Tick 1: `running` is in flight, `marked` becomes runnable.
8700        let in_flight = vec![running.id.clone()];
8701        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8702        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8703        assert!(gated.is_empty(), "still waiting on `running` to park");
8704
8705        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8706        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8707        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8708        assert_eq!(
8709            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8710            vec!["marked"],
8711            "only the interrupt task may be offered to the dispatcher now"
8712        );
8713
8714        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8715        state = advance_interrupt_tick(
8716            true,
8717            state,
8718            &["marked".to_owned()],
8719            std::slice::from_ref(&running),
8720        );
8721        let gated = interrupt_gate(
8722            &state,
8723            &["marked".to_owned()],
8724            vec![marked.clone(), running.clone()],
8725        );
8726        assert!(
8727            gated.is_empty(),
8728            "the parked run must not be offered back while the interrupt \
8729             task is still running"
8730        );
8731
8732        // Tick 4: `marked`'s run reached a terminal status and left flight.
8733        // A higher-priority ordinary task `other` is also runnable now - it
8734        // must not be let through instead of, or alongside, `running`.
8735        let other = task_with_id("other");
8736        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8737        assert_eq!(
8738            state,
8739            Interrupt::Resuming {
8740                parked: vec![running.id.clone()]
8741            }
8742        );
8743        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8744        assert_eq!(
8745            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8746            vec![running.id.as_str()],
8747            "exactly the parked run resumes - not the unrelated task, even \
8748             though it was offered first"
8749        );
8750
8751        // Tick 5: `running` is now in flight (dispatched from tick 4's
8752        // gate). Only now does the sequence end and ordinary dispatch fully
8753        // resume.
8754        state = advance_interrupt_tick(
8755            true,
8756            state,
8757            std::slice::from_ref(&running.id),
8758            std::slice::from_ref(&other),
8759        );
8760        assert_eq!(state, Interrupt::Idle);
8761        let gated = interrupt_gate(
8762            &state,
8763            std::slice::from_ref(&running.id),
8764            vec![other.clone()],
8765        );
8766        assert_eq!(
8767            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8768            vec![other.id.as_str()],
8769            "ordinary dispatch is unrestricted again"
8770        );
8771    }
8772
8773    #[test]
8774    fn every_run_status_settles_the_task_it_came_from() {
8775        // run status, resulting task status, attempts still standing after one
8776        let table = [
8777            (RunStatus::Merged, TaskStatus::Done, 1),
8778            (RunStatus::Ready, TaskStatus::Done, 1),
8779            (RunStatus::Stalled, TaskStatus::Failed, 0),
8780            (RunStatus::Blocked, TaskStatus::Failed, 1),
8781            (RunStatus::Failed, TaskStatus::Failed, 1),
8782            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8783            (RunStatus::Prep, TaskStatus::Failed, 1),
8784            (RunStatus::Implementing, TaskStatus::Failed, 1),
8785            (RunStatus::Judging, TaskStatus::Failed, 1),
8786            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8787            (RunStatus::Voting, TaskStatus::Failed, 1),
8788            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8789            (RunStatus::Gating, TaskStatus::Failed, 1),
8790        ];
8791        for (run, want, attempts) in table {
8792            let mut t = task();
8793            t.start("20260902-000000-aaaa".to_owned());
8794            settle(
8795                &mut t,
8796                Verdict {
8797                    status: run,
8798                    left_pr: false,
8799                    parked: false,
8800                    quota_hit: matches!(run, RunStatus::Stalled),
8801                    no_viable_candidates: false,
8802                },
8803                "why",
8804                2,
8805            );
8806            assert_eq!(t.status, want, "task status after {}", label(run));
8807            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8808        }
8809    }
8810
8811    #[test]
8812    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8813        let mut stalled = task();
8814        stalled.start("20260902-000000-aaaa".to_owned());
8815        settle(
8816            &mut stalled,
8817            Verdict {
8818                status: RunStatus::Stalled,
8819                left_pr: false,
8820                parked: false,
8821                quota_hit: true,
8822                no_viable_candidates: false,
8823            },
8824            "quota",
8825            1,
8826        );
8827        assert_eq!(stalled.attempts, 0);
8828        assert!(
8829            stalled.status.runnable(),
8830            "a machine problem must leave the task in line"
8831        );
8832
8833        let mut blocked = task();
8834        blocked.start("20260902-000000-aaaa".to_owned());
8835        settle(
8836            &mut blocked,
8837            Verdict {
8838                status: RunStatus::Blocked,
8839                left_pr: false,
8840                parked: false,
8841                quota_hit: false,
8842                no_viable_candidates: false,
8843            },
8844            "findings open",
8845            1,
8846        );
8847        assert_eq!(blocked.attempts, 1);
8848        assert_eq!(
8849            blocked.status,
8850            TaskStatus::Held,
8851            "the last attempt hands the task to a human"
8852        );
8853    }
8854
8855    #[test]
8856    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8857        // Attempts to spare: without the pull request this task would go
8858        // straight back in line and run the whole competition again.
8859        let mut delivered = task();
8860        delivered.start("20260903-080619-01c2".to_owned());
8861        settle(
8862            &mut delivered,
8863            Verdict {
8864                status: RunStatus::Blocked,
8865                left_pr: true,
8866                parked: false,
8867                quota_hit: false,
8868                no_viable_candidates: false,
8869            },
8870            "no check status",
8871            4,
8872        );
8873        assert_eq!(
8874            delivered.status,
8875            TaskStatus::Held,
8876            "a pull request waiting on CI or a person is not a retryable failure"
8877        );
8878        assert!(
8879            !delivered.status.runnable(),
8880            "the loop must not pick this task up again"
8881        );
8882        assert_eq!(
8883            delivered.last_error.as_deref(),
8884            Some("no check status"),
8885            "the operator needs to be told what the gate was waiting for"
8886        );
8887
8888        // The same status without a pull request is a plain failure, and with
8889        // attempts left it is retried.
8890        let mut empty_handed = task();
8891        empty_handed.start("20260903-080619-01c2".to_owned());
8892        settle(
8893            &mut empty_handed,
8894            Verdict {
8895                status: RunStatus::Blocked,
8896                left_pr: false,
8897                parked: false,
8898                quota_hit: false,
8899                no_viable_candidates: false,
8900            },
8901            "findings open",
8902            4,
8903        );
8904        assert_eq!(empty_handed.status, TaskStatus::Failed);
8905        assert!(empty_handed.status.runnable());
8906    }
8907
8908    #[test]
8909    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8910        // Every candidate agreed, with evidence, that nothing belonged in the
8911        // worktree. That is not a confirmed success to close automatically -
8912        // a human still has to check the claim - and it is not an ordinary
8913        // failure either, so this settles exactly like a pull request nobody
8914        // merged yet: `Held`, same as `Blocked` with a PR.
8915        let mut noop = task();
8916        noop.start("20260912-131304-391f".to_owned());
8917        settle(
8918            &mut noop,
8919            Verdict {
8920                status: RunStatus::VerifiedNoop,
8921                left_pr: false,
8922                parked: false,
8923                quota_hit: false,
8924                no_viable_candidates: true,
8925            },
8926            "candidate A: already fixed by b32cfc4, on main",
8927            4,
8928        );
8929        assert_eq!(
8930            noop.status,
8931            TaskStatus::Held,
8932            "an unverified claim is a request for a human, not a failure"
8933        );
8934        assert!(
8935            !noop.status.runnable(),
8936            "the loop must not requeue this on the same unverified claim"
8937        );
8938        // `Task::release` resets attempts to zero the moment a human looks at
8939        // the evidence and lets it run again, so it does not matter here
8940        // whether the one attempt already spent stays spent - what matters is
8941        // that nothing retries this task unattended in the meantime.
8942        assert_eq!(noop.attempts, 1);
8943    }
8944
8945    #[test]
8946    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8947        // Parking is the operator asking for the process back - to replace the
8948        // binary, most of all. The run's work is intact on disk, so this is
8949        // not a failed attempt, and charging for it would mean a few upgrades
8950        // could exhaust a budget meant for agents that misbehaved.
8951        let mut parked = task();
8952        parked.start("20260903-183634-2d98".to_owned());
8953        settle(
8954            &mut parked,
8955            Verdict {
8956                status: RunStatus::Implementing,
8957                left_pr: false,
8958                quota_hit: false,
8959                parked: true,
8960                no_viable_candidates: false,
8961            },
8962            "parked after `implementing`",
8963            2,
8964        );
8965        assert_eq!(parked.attempts, 0, "a park is refunded");
8966        assert!(
8967            parked.status.runnable(),
8968            "and the task stays in line so the next loop resumes its run"
8969        );
8970        assert_eq!(parked.status, TaskStatus::Parked);
8971        assert_eq!(
8972            parked.park_reason.as_deref(),
8973            Some("parked after `implementing`"),
8974            "the card says where it stopped"
8975        );
8976        assert_eq!(parked.last_error, None, "nothing failed");
8977
8978        // Without the park flag the same non-terminal status is what it always
8979        // was: `execute` returning mid-flight, which is a bug and spends an
8980        // attempt so a task cannot loop on it forever.
8981        let mut broken = task();
8982        broken.start("20260903-183634-2d98".to_owned());
8983        settle(
8984            &mut broken,
8985            Verdict {
8986                status: RunStatus::Implementing,
8987                left_pr: false,
8988                quota_hit: false,
8989                parked: false,
8990                no_viable_candidates: false,
8991            },
8992            "returned mid-flight",
8993            2,
8994        );
8995        assert_eq!(broken.attempts, 1);
8996    }
8997
8998    #[test]
8999    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
9000        // Run e633: quorum lost because two judges answered with the wrong
9001        // JSON shape, `quota: []`. Refunding that takes the bound off the
9002        // retry loop, and each retry pays for a fresh hour-long implement
9003        // wave before it can fail the same way.
9004        let mut flaky = task();
9005        flaky.start("20260903-123023-e633".to_owned());
9006        settle(
9007            &mut flaky,
9008            Verdict {
9009                status: RunStatus::Stalled,
9010                left_pr: false,
9011                parked: false,
9012                quota_hit: false,
9013                no_viable_candidates: false,
9014            },
9015            "verdict rests on 1 of 3 judges",
9016            2,
9017        );
9018        assert_eq!(
9019            flaky.attempts, 1,
9020            "flakiness spends an attempt, so `max_attempts` still bounds it"
9021        );
9022        assert!(flaky.status.runnable(), "and it is still worth retrying");
9023
9024        // The same status, lost to a rate limit, is the machine's fault.
9025        let mut limited = task();
9026        limited.start("20260903-123023-e633".to_owned());
9027        settle(
9028            &mut limited,
9029            Verdict {
9030                status: RunStatus::Stalled,
9031                left_pr: false,
9032                parked: false,
9033                quota_hit: true,
9034                no_viable_candidates: false,
9035            },
9036            "judge-2, judge-3 out of quota",
9037            2,
9038        );
9039        assert_eq!(limited.attempts, 0, "a quota window is refunded");
9040        assert!(limited.status.runnable());
9041
9042        // And the bound really binds: a task that keeps stalling on flakiness
9043        // reaches a human instead of running the roster forever.
9044        let mut worn = task();
9045        for _ in 0..2 {
9046            worn.release();
9047        }
9048        worn.start("20260903-123023-e633".to_owned());
9049        worn.attempts = 2;
9050        settle(
9051            &mut worn,
9052            Verdict {
9053                status: RunStatus::Stalled,
9054                left_pr: false,
9055                parked: false,
9056                quota_hit: false,
9057                no_viable_candidates: false,
9058            },
9059            "no quorum again",
9060            2,
9061        );
9062        assert_eq!(worn.status, TaskStatus::Held);
9063        assert!(!worn.status.runnable());
9064    }
9065
9066    #[test]
9067    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
9068        // The implement wave loses every seat to the same rate limit and
9069        // `after_implement` bails with nothing viable, which surfaces as
9070        // `Failed` rather than `Stalled`. That is the same machine fact the
9071        // `Stalled`-quota row already refunds, and must be refunded the same
9072        // way, or a quota outage quietly holds every task it touches instead
9073        // of leaving them in line for the reset.
9074        let mut wiped_out = task();
9075        wiped_out.start("20260907-025000-a1b2".to_owned());
9076        settle(
9077            &mut wiped_out,
9078            Verdict {
9079                status: RunStatus::Failed,
9080                left_pr: false,
9081                parked: false,
9082                quota_hit: true,
9083                no_viable_candidates: true,
9084            },
9085            "no candidate produced a change; nothing to judge",
9086            2,
9087        );
9088        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
9089        assert!(
9090            wiped_out.status.runnable(),
9091            "a machine problem must leave the task in line"
9092        );
9093
9094        // This is the exemption that must stay narrow: a candidate that did
9095        // produce a change, and then failed for some other reason, still
9096        // spends the attempt even though a seat elsewhere hit its quota.
9097        // Otherwise every ordinary failure that happens to share a run with
9098        // an unrelated rate limit would be refunded for free.
9099        let mut partial_progress = task();
9100        partial_progress.start("20260907-025500-c3d4".to_owned());
9101        settle(
9102            &mut partial_progress,
9103            Verdict {
9104                status: RunStatus::Failed,
9105                left_pr: false,
9106                parked: false,
9107                quota_hit: true,
9108                no_viable_candidates: false,
9109            },
9110            "gate failed on the winning candidate",
9111            2,
9112        );
9113        assert_eq!(
9114            partial_progress.attempts, 1,
9115            "a candidate that actually produced a change spends the attempt \
9116             even though some other seat hit its quota"
9117        );
9118        assert!(partial_progress.status.runnable());
9119    }
9120
9121    #[test]
9122    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
9123        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
9124        // disk, and that construction must reach the same conclusion as the
9125        // one `attempt` builds from a live run, or a crash at exactly the
9126        // wrong moment gives a recovered task a different policy than one a
9127        // daemon finished settling itself.
9128        let mut t = task();
9129        t.start("20260907-025000-a1b2".to_owned());
9130        let mut state = run_state(RunStatus::Failed);
9131        state.quota.push(QuotaLoss {
9132            cause: crate::agent::QuotaCause::UsageLimit,
9133            agent: String::new(),
9134            seat: "cand-a".to_owned(),
9135            node: "implement".to_owned(),
9136            at: Timestamp::now(),
9137            reset: None,
9138        });
9139        assert!(
9140            state.viable().is_empty(),
9141            "no candidate was added, so nothing is viable"
9142        );
9143        reclaim(&mut t, Some(state), 2, "en");
9144        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
9145        assert!(t.status.runnable());
9146    }
9147
9148    #[test]
9149    fn a_held_task_is_never_offered_to_the_loop() {
9150        let dir = tempfile::tempdir().unwrap();
9151        let queue = Queue::at(dir.path().to_path_buf());
9152        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
9153            let mut t = task();
9154            t.id = format!("2026090{n}-000000-000{n}");
9155            t.priority = priority;
9156            queue.put(&mut t).unwrap();
9157        }
9158        let mut held = task();
9159        held.id = "20260909-000000-9999".to_owned();
9160        held.priority = 99;
9161        held.hold_machine(None);
9162        queue.put(&mut held).unwrap();
9163
9164        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
9165        assert_eq!(order.len(), 3);
9166        assert!(!order.contains(&held.id));
9167        assert_eq!(
9168            order.first().cloned(),
9169            queue.next_runnable().map(|t| t.id),
9170            "the loop's first candidate is exactly what the queue offers"
9171        );
9172        assert_eq!(
9173            order,
9174            vec![
9175                "20260902-000000-0002".to_owned(),
9176                "20260903-000000-0003".to_owned(),
9177                "20260901-000000-0001".to_owned(),
9178            ],
9179            "priority first, then oldest, so nothing starves"
9180        );
9181    }
9182
9183    #[test]
9184    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
9185        let dir = tempfile::tempdir().unwrap();
9186        let queue = Queue::at(dir.path().to_path_buf());
9187        let mut old = task();
9188        old.id = "20260101-000000-old0".to_owned();
9189        queue.put(&mut old).unwrap();
9190        let mut fresh = task();
9191        fresh.id = "20260101-000000-new0".to_owned();
9192        queue.put(&mut fresh).unwrap();
9193
9194        // No parseable pid at all, so age is the only signal there is to
9195        // check - unlike a real `Queue::claim`, which always names a real,
9196        // and therefore alive, pid this test cannot fake as dead.
9197        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
9198        std::thread::sleep(Duration::from_millis(60));
9199        let live = queue.claim(&fresh.id).unwrap();
9200
9201        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9202        assert_eq!(swept, vec![old.id.clone()]);
9203        assert!(
9204            queue.claim(&old.id).is_ok(),
9205            "an unparseable lock older than the threshold is swept"
9206        );
9207        assert!(
9208            queue.claim(&fresh.id).is_err(),
9209            "a live pid protects its lock regardless of age"
9210        );
9211        drop(live);
9212    }
9213
9214    #[test]
9215    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
9216        // A live worker's claim remains authoritative even beyond the sweep's
9217        // age limit. Sweeping it would permit a second competing attempt.
9218        let dir = tempfile::tempdir().unwrap();
9219        let queue = Queue::at(dir.path().to_path_buf());
9220        let mut t = task();
9221        t.id = "20260101-000000-live".to_owned();
9222        queue.put(&mut t).unwrap();
9223
9224        let claim = queue.claim(&t.id).unwrap();
9225        std::thread::sleep(Duration::from_millis(60));
9226
9227        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9228        assert!(
9229            swept.is_empty(),
9230            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9231        );
9232        assert!(
9233            queue.claim(&t.id).is_err(),
9234            "the lock still protects its task"
9235        );
9236        drop(claim);
9237    }
9238
9239    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
9240    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
9241    fn injected_dead_pid() -> u32 {
9242        std::process::id().checked_add(1).unwrap_or(1)
9243    }
9244
9245    #[test]
9246    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
9247        let dir = tempfile::tempdir().unwrap();
9248        let queue = Queue::at(dir.path().to_path_buf());
9249        let mut t = task();
9250        t.id = "20260101-000000-dead".to_owned();
9251        queue.put(&mut t).unwrap();
9252        let dead_pid = injected_dead_pid();
9253
9254        // Written directly rather than through `Queue::claim`, which would
9255        // stamp this test process's own very much alive pid and defeat the
9256        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
9257        // like moments after it died, not six hours later.
9258        std::fs::write(
9259            dir.path().join(format!("{}.lock", t.id)),
9260            dead_pid.to_string(),
9261        )
9262        .unwrap();
9263
9264        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9265            pid != dead_pid
9266        });
9267        assert_eq!(
9268            swept,
9269            vec![t.id.clone()],
9270            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9271        );
9272        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9273    }
9274
9275    #[test]
9276    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9277        let dir = tempfile::tempdir().unwrap();
9278        let queue = Queue::at(dir.path().to_path_buf());
9279        let mut t = task();
9280        t.id = "20260101-000000-late".to_owned();
9281        queue.put(&mut t).unwrap();
9282        let dead_pid = injected_dead_pid();
9283
9284        // Tick one, standing in for the sweep `poll` already runs at
9285        // startup: nothing to find yet.
9286        assert!(
9287            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9288            "nothing has claimed the task yet"
9289        );
9290
9291        // A second daemon claims the task and dies before it ever writes
9292        // `running`, well after this loop's own startup sweep already ran.
9293        std::fs::write(
9294            dir.path().join(format!("{}.lock", t.id)),
9295            dead_pid.to_string(),
9296        )
9297        .unwrap();
9298
9299        // Tick two, standing in for a poll long into this daemon's uptime:
9300        // the same function, called again, notices what only just appeared -
9301        // proving the sweep is not a one-shot startup check.
9302        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9303            pid != dead_pid
9304        });
9305        assert_eq!(swept, vec![t.id.clone()]);
9306    }
9307
9308    #[test]
9309    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9310        // `reclaim_orphaned_running` looks up the task's last run, which
9311        // touches `run::home()`; the first call anywhere in this binary wins,
9312        // so this is a no-op if another test already pinned one, and either
9313        // way the run id below is never written under it.
9314        crate::run::pin_test_home();
9315        let dir = tempfile::tempdir().unwrap();
9316        let queue = Queue::at(dir.path().to_path_buf());
9317        let mut t = task();
9318        t.id = "20260101-000000-crsh".to_owned();
9319        t.status = TaskStatus::Running;
9320        t.attempts = 1;
9321        // No `run.json` behind this id: standing in for a run this test does
9322        // not need to make readable, since the point is the lock, not the
9323        // recovery table `reclaim` already has its own tests for.
9324        t.runs.push("20260904-000000-4043".to_owned());
9325        queue.put(&mut t).unwrap();
9326        let dead_pid = injected_dead_pid();
9327
9328        // The crashed daemon's own claim, naming a pid nothing on the
9329        // machine holds anymore.
9330        std::fs::write(
9331            dir.path().join(format!("{}.lock", t.id)),
9332            dead_pid.to_string(),
9333        )
9334        .unwrap();
9335
9336        // Before the lock is swept the task looks claimed, and
9337        // `reclaim_orphaned_running` must leave it alone - this is exactly
9338        // the bug: a `running` task stranded behind a dead daemon's lock,
9339        // invisible to the claim-as-proof check because the lock outlived
9340        // the process that wrote it.
9341        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9342        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9343
9344        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9345            pid != dead_pid
9346        });
9347        assert_eq!(swept, vec![t.id.clone()]);
9348
9349        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9350        assert_eq!(reclaimed, vec![t.id.clone()]);
9351        let after = queue.get(&t.id).unwrap();
9352        assert_eq!(
9353            after.status,
9354            TaskStatus::Held,
9355            "no run.json to recover from, so a human is asked"
9356        );
9357        assert_eq!(
9358            after.runs,
9359            vec!["20260904-000000-4043".to_owned()],
9360            "the crashed run's id is kept as evidence, not discarded"
9361        );
9362    }
9363
9364    #[test]
9365    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9366        let dir = tempfile::tempdir().unwrap();
9367        let queue = Queue::at(dir.path().to_path_buf());
9368        let mut t = task();
9369        t.id = "20260101-000000-unknown".to_owned();
9370        queue.put(&mut t).unwrap();
9371        let dead_pid = injected_dead_pid();
9372        std::fs::write(
9373            dir.path().join(format!("{}.lock", t.id)),
9374            dead_pid.to_string(),
9375        )
9376        .unwrap();
9377
9378        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9379        assert!(swept.is_empty(), "an unknown pid must keep its lock");
9380        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9381    }
9382
9383    fn run_state_in(status: RunStatus, language: &str) -> RunState {
9384        let mut s = run_state(status);
9385        s.config.graph.language = language.to_owned();
9386        s
9387    }
9388
9389    fn unstarted_verdict(status: RunStatus) -> Verdict {
9390        Verdict {
9391            status,
9392            left_pr: false,
9393            quota_hit: false,
9394            parked: false,
9395            no_viable_candidates: false,
9396        }
9397    }
9398
9399    #[test]
9400    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9401        let mut t = task();
9402        t.attempts = 1;
9403        settle_in(
9404            &mut t,
9405            unstarted_verdict(RunStatus::AlreadyInBase),
9406            "already in main",
9407            1,
9408            phrases("en"),
9409            None,
9410        );
9411        assert_eq!(t.status, TaskStatus::Done);
9412        assert_eq!(t.attempts, 0);
9413    }
9414
9415    #[test]
9416    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9417        let reason = |language: &str| {
9418            let mut t = task();
9419            settle_in(
9420                &mut t,
9421                unstarted_verdict(RunStatus::Judging),
9422                "boom",
9423                1,
9424                phrases(language),
9425                None,
9426            );
9427            t.last_error.or(t.hold_reason).unwrap_or_default()
9428        };
9429        assert!(
9430            reason("en").starts_with("the graph stopped at `"),
9431            "{}",
9432            reason("en")
9433        );
9434        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9435        assert!(reason("日本語").contains("boom"));
9436        assert_eq!(reason("fr"), reason("en"));
9437    }
9438
9439    #[test]
9440    fn describe_follows_the_run_language_and_keeps_the_run_id() {
9441        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9442        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9443        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9444        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9445        assert!(ja.contains("[run "), "{ja}");
9446        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9447        assert!(ended.starts_with("run 終了: "), "{ended}");
9448        let mut de = run_state_in(RunStatus::Failed, "de");
9449        let mut en = run_state_in(RunStatus::Failed, "en");
9450        de.id = "same".to_owned();
9451        en.id = "same".to_owned();
9452        assert_eq!(describe(&de), describe(&en));
9453    }
9454
9455    #[test]
9456    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9457        use crate::handover::Refused;
9458        let cases = [
9459            Refused::Foreign {
9460                branch: "b".into(),
9461                path: "/w/x".into(),
9462                why: "made by hand".into(),
9463            },
9464            Refused::Unsafe {
9465                branch: "b".into(),
9466                path: "/w/x".into(),
9467                why: "its worktree has uncommitted changes (a.rs)".into(),
9468            },
9469            Refused::ReleaseFailed {
9470                branch: "b".into(),
9471                path: "/w/x".into(),
9472                run: "ab12".into(),
9473            },
9474        ];
9475        for r in &cases {
9476            let en = (phrases("en").handover_refused)(r);
9477            assert_eq!(en, r.to_string());
9478            let ja = (phrases("ja").handover_refused)(r);
9479            assert!(
9480                !ja.contains("is checked out") && !ja.contains("try again"),
9481                "{ja}"
9482            );
9483            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9484            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9485                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9486            }
9487        }
9488        assert!(phrases("en").handover_hint.contains("release the task"));
9489        assert!(phrases("ja").handover_hint.contains("解放"));
9490    }
9491
9492    #[test]
9493    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9494        let build = |lang: &str| {
9495            let mut s = run_state_in(RunStatus::Blocked, lang);
9496            s.id = "same".to_owned();
9497            s.config.graph.review_rounds = 3;
9498            let mut r = review_round(3);
9499            r.expected = 3;
9500            r.answered = 1;
9501            s.reviews.push(r);
9502            s.event(
9503                "review",
9504                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9505            );
9506            s
9507        };
9508        let en = describe(&build("en"));
9509        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9510        let ja = describe(&build("ja"));
9511        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9512        assert!(!ja.contains("never answered"), "{ja}");
9513        assert!(ja.contains("[run "), "{ja}");
9514
9515        // An incomplete panel whose verification failed is a different stop:
9516        // the real event must survive in ja too.
9517        let mut failed = build("ja");
9518        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9519            command: "cargo test".to_owned(),
9520            code: Some(1),
9521            output_tail: String::new(),
9522            duration_ms: 0,
9523            resource_blocked: false,
9524            ..Default::default()
9525        });
9526        failed.event("review", "stopped; e2e failed: cargo test");
9527        let ja = describe(&failed);
9528        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9529        assert!(!ja.contains("席のレビュアー"), "{ja}");
9530    }
9531
9532    #[test]
9533    fn refusals_and_recovery_prose_follow_the_language() {
9534        let home = crate::run::test_home();
9535        let t = held_task_with("r1");
9536        let q = action_question(
9537            "r1",
9538            ask::ChoiceAction::Resume {
9539                run: "r1".to_owned(),
9540            },
9541        );
9542        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9543            ActionDecision::Refuse(s) => s,
9544            other => panic!("{other:?}"),
9545        };
9546        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9547        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9548        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9549
9550        let mut held = task();
9551        reclaim(&mut held, None, 2, "ja");
9552        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9553        let mut held = task();
9554        reclaim(&mut held, None, 2, "xx");
9555        assert!(held.hold_reason.unwrap().contains("held for a human"));
9556    }
9557
9558    fn run_state(status: RunStatus) -> RunState {
9559        let mut state = RunState::new(
9560            PathBuf::from("/repo"),
9561            "main".to_owned(),
9562            "abc1234def".to_owned(),
9563            "add retries".to_owned(),
9564            Config::default(),
9565        );
9566        state.status = status;
9567        state
9568    }
9569
9570    #[test]
9571    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
9572        crate::run::pin_test_home();
9573        let dir = tempfile::tempdir().unwrap();
9574        let mut state = run_state(RunStatus::Blocked);
9575        state.id = "20260101-000000-audit".into();
9576        state.save_under(dir.path()).unwrap();
9577        let mut t = task();
9578        t.start(state.id.clone());
9579        // The final state is newer than disk, as when a worker settles its
9580        // in-memory outcome or recovery is passed an already loaded run.
9581        state.status = RunStatus::Ready;
9582        settle_and_diagnose(
9583            &mut t,
9584            unstarted_verdict(RunStatus::Ready),
9585            "Verified local delivery",
9586            2,
9587            &state,
9588        );
9589        let completion = t.completion_history.last().unwrap();
9590        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
9591        assert_eq!(completion.prior_status, TaskStatus::Running);
9592        assert_eq!(
9593            completion.reason.as_deref(),
9594            Some("Verified local delivery")
9595        );
9596        let snapshot = completion.run.as_ref().unwrap();
9597        assert_eq!(snapshot.id, state.id);
9598        assert_eq!(snapshot.status, Some(RunStatus::Ready));
9599        assert_eq!(
9600            RunState::load_under(&state.id, dir.path()).unwrap().status,
9601            RunStatus::Blocked,
9602            "settlement records the actual outcome without rewriting run history"
9603        );
9604    }
9605
9606    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9607        Candidate {
9608            index: 0,
9609            label,
9610            agent: "claude".to_owned(),
9611            branch: format!("magi/x/{label}"),
9612            worktree: PathBuf::from("/repo"),
9613            summary: summary.to_owned(),
9614            stat: String::new(),
9615            files: 0,
9616            commits: usize::from(!empty),
9617            empty,
9618            failed: failed.map(str::to_owned),
9619            verified_noop: None,
9620            duration_ms: 0,
9621            folded: false,
9622        }
9623    }
9624
9625    #[test]
9626    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9627        let mut state = run_state(RunStatus::Blocked);
9628        state.gate = vec![
9629            CommandOutcome {
9630                command: "cargo make check".to_owned(),
9631                code: Some(0),
9632                output_tail: "ok".to_owned(),
9633                duration_ms: 0,
9634                resource_blocked: false,
9635                ..Default::default()
9636            },
9637            CommandOutcome {
9638                command: "cargo test".to_owned(),
9639                code: Some(101),
9640                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9641                duration_ms: 0,
9642                resource_blocked: false,
9643                ..Default::default()
9644            },
9645        ];
9646        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9647        assert!(d.contains("cargo test"), "{d}");
9648        assert!(
9649            !d.contains("cargo make check"),
9650            "a passing check is not a diagnostic: {d}"
9651        );
9652        assert!(d.contains("assertion failed"), "{d}");
9653    }
9654
9655    #[test]
9656    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9657        let mut state = run_state(RunStatus::Blocked);
9658        state.event(
9659            "land",
9660            "stopped: the fixer produced no commit while 2 check(s) were failing \
9661             (build, lint); stopping instead of looping on an unchanged tree",
9662        );
9663        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9664        assert!(d.contains("build"), "{d}");
9665        assert!(d.contains("lint"), "{d}");
9666        assert!(d.contains("fixer produced no commit"), "{d}");
9667    }
9668
9669    #[test]
9670    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9671        // `describe`'s output becomes `Task::last_error` verbatim, and the
9672        // phone renders that in the same alarm-styled box an ordinary
9673        // failure gets. A bare `verified_noop` there would read exactly like
9674        // the failure this status exists to be told apart from.
9675        let state = run_state(RunStatus::VerifiedNoop);
9676        let d = describe(&state);
9677        assert!(
9678            d.contains("agent-verified no-op"),
9679            "expected the display label, not the wire spelling: {d}"
9680        );
9681        assert!(!d.contains("verified_noop"), "{d}");
9682    }
9683
9684    #[test]
9685    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9686        let mut state = run_state(RunStatus::Failed);
9687        state.gate.push(crate::run::CommandOutcome {
9688            command: "cargo test".into(),
9689            code: Some(101),
9690            output_tail: format!(
9691                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9692                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9693            ),
9694            duration_ms: 1,
9695            resource_blocked: false,
9696            ..Default::default()
9697        });
9698        let d = diagnostic(&state).unwrap();
9699        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9700        assert!(d.contains("assertion failed: widget missing"));
9701        assert!(d.contains("widget log"));
9702    }
9703
9704    #[test]
9705    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9706        // The whole point of the feature: a run held as "no candidate produced
9707        // a change" can mean the implementer actually finished the task and
9708        // only left a clean local tree behind - see AGENTS.md on this exact
9709        // failure mode. The diagnostic has to carry what the agent actually
9710        // said, not just the fact that nothing was there to judge.
9711        let mut state = run_state(RunStatus::Failed);
9712        state.candidates = vec![candidate(
9713            'A',
9714            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9715            true,
9716            None,
9717        )];
9718        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9719        assert!(d.contains("candidate A"), "{d}");
9720        assert!(d.contains("tagged v1.2.3"), "{d}");
9721    }
9722
9723    #[test]
9724    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9725        let mut state = run_state(RunStatus::Failed);
9726        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9727        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9728        assert!(d.contains("candidate A"), "{d}");
9729        assert!(d.contains("agent timed out"), "{d}");
9730    }
9731
9732    #[test]
9733    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9734        // A viable candidate existed, the gate never ran, and nothing land
9735        // said matches - `Task::last_error` is left to explain this one alone.
9736        let mut state = run_state(RunStatus::Failed);
9737        state.candidates = vec![candidate('A', "did the work", false, None)];
9738        assert!(diagnostic(&state).is_none());
9739    }
9740
9741    #[test]
9742    fn diagnostic_is_bounded_however_much_a_run_printed() {
9743        let mut state = run_state(RunStatus::Blocked);
9744        state.gate = vec![
9745            CommandOutcome {
9746                command: "cargo test".to_owned(),
9747                code: Some(101),
9748                output_tail: "x".repeat(50_000),
9749                duration_ms: 0,
9750                resource_blocked: false,
9751                ..Default::default()
9752            },
9753            CommandOutcome {
9754                command: "cargo clippy".to_owned(),
9755                code: Some(1),
9756                output_tail: "y".repeat(50_000),
9757                duration_ms: 0,
9758                resource_blocked: false,
9759                ..Default::default()
9760            },
9761        ];
9762        state.candidates = vec![
9763            candidate('A', &"z".repeat(50_000), true, None),
9764            candidate('B', &"w".repeat(50_000), true, None),
9765        ];
9766        let d = diagnostic(&state).expect("plenty here to diagnose");
9767        assert!(
9768            d.len() <= DIAGNOSTIC_MAX,
9769            "diagnostic grew to {} bytes, unbounded",
9770            d.len()
9771        );
9772    }
9773
9774    #[test]
9775    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9776        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9777            let mut t = task();
9778            let mut state = run_state(status);
9779            t.pr_recovery = Some(crate::pr_recovery::Selection {
9780                url: "url".into(),
9781                branch: format!("magi/task-{}", t.id),
9782                head: "a".repeat(40),
9783                source_head: None,
9784                source_run: None,
9785                source_proof: None,
9786                disposition: Some(crate::pr_recovery::Disposition::Land),
9787                instruction: t.instruction.clone(),
9788                approved_at: Timestamp::now(),
9789            });
9790            state.pr_recovery = t.pr_recovery.clone();
9791            t.start(state.id.clone());
9792            settle_and_diagnose(
9793                &mut t,
9794                Verdict {
9795                    status,
9796                    left_pr: false,
9797                    quota_hit: false,
9798                    parked: false,
9799                    no_viable_candidates: false,
9800                },
9801                "delivery stopped",
9802                5,
9803                &state,
9804            );
9805            assert_eq!(t.status, TaskStatus::Held);
9806            let reason = t.hold_reason.as_deref().unwrap();
9807            if status == RunStatus::Ready {
9808                assert!(reason.contains("Selected PR delivery is incomplete"));
9809                assert!(t.recovery_budget.is_none());
9810            } else {
9811                assert!(reason.contains("Selected recovery stopped"));
9812                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9813            }
9814            assert!(t.pr_recovery.is_some());
9815        }
9816    }
9817
9818    #[test]
9819    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9820        let mut state = run_state(RunStatus::Voting);
9821        state.base_sync = Some(crate::run::BaseSync {
9822            tip: "base-tip".into(),
9823            behind: 3,
9824            attempts: 4,
9825            conflict: Some("base stopped".into()),
9826            already_in: None,
9827        });
9828        state.record_base_sync_stop("candidate-head");
9829        let mut t = task();
9830        t.start(state.id.clone());
9831        let verdict = Verdict {
9832            status: RunStatus::Blocked,
9833            left_pr: false,
9834            quota_hit: false,
9835            parked: false,
9836            no_viable_candidates: false,
9837        };
9838        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9839        assert_eq!(
9840            t.status,
9841            TaskStatus::Held,
9842            "unspent task attempts cannot start another competition"
9843        );
9844        let at = t.held_at;
9845        let cause = t.hold_notice_cause.clone();
9846        state.begin_pass();
9847        t.release_operator("test-resume", None);
9848        t.start(state.id.clone());
9849        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9850        assert_eq!(t.status, TaskStatus::Held);
9851        assert_eq!(t.held_at, at);
9852        assert_eq!(t.hold_notice_cause, cause);
9853    }
9854
9855    #[test]
9856    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9857        let mut state = run_state(RunStatus::Blocked);
9858        state.gate = vec![CommandOutcome {
9859            command: "cargo test".to_owned(),
9860            code: Some(101),
9861            output_tail: "assertion failed".to_owned(),
9862            duration_ms: 0,
9863            resource_blocked: false,
9864            ..Default::default()
9865        }];
9866        let verdict = Verdict {
9867            status: RunStatus::Blocked,
9868            left_pr: false,
9869            quota_hit: false,
9870            parked: false,
9871            no_viable_candidates: false,
9872        };
9873
9874        // Attempt one of two still has a retry coming: no diagnostic yet, the
9875        // task is going to run again and this run's evidence would go stale.
9876        let mut t = task();
9877        t.start("run-1".to_owned());
9878        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9879        assert_eq!(t.status, TaskStatus::Failed);
9880        assert!(t.diagnostic.is_none());
9881
9882        // Attempt two exhausts the budget: now it is held, and the
9883        // diagnostic is what `magi task show` has to say more than one line.
9884        t.start("run-2".to_owned());
9885        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9886        assert_eq!(t.status, TaskStatus::Held);
9887        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9888        assert!(d.contains("cargo test"), "{d}");
9889    }
9890
9891    #[test]
9892    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9893        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9894        // `magi ask` question settled Held with `hold_reason: null`, so the
9895        // notification said nothing actionable. `note_open_question` should
9896        // append the question id to whatever `handed_off` already wrote.
9897        crate::run::pin_test_home();
9898        let home = crate::run::home();
9899        let state = run_state(RunStatus::VerifiedNoop);
9900        let mut q = ask::Question::new(
9901            state.id.clone(),
9902            "implement".to_owned(),
9903            "impl-A".to_owned(),
9904            "is this really a no-op?".to_owned(),
9905            String::new(),
9906            Vec::new(),
9907        );
9908        Questions::at(home.join("questions")).put(&mut q).unwrap();
9909
9910        let verdict = Verdict {
9911            status: RunStatus::VerifiedNoop,
9912            left_pr: false,
9913            quota_hit: false,
9914            parked: false,
9915            no_viable_candidates: false,
9916        };
9917        let mut t = task();
9918        t.start(state.id.clone());
9919        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9920
9921        assert_eq!(t.status, TaskStatus::Held);
9922        let reason = t.hold_reason.expect("a held task must record why");
9923        assert!(
9924            reason.starts_with("run ended agent-verified no-op"),
9925            "the original settle reason must survive unchanged: {reason}"
9926        );
9927        assert!(
9928            reason.contains(q.short()),
9929            "the open question's id must be named so the notice is actionable: {reason}"
9930        );
9931    }
9932
9933    #[test]
9934    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9935        crate::run::pin_test_home();
9936        let state = run_state(RunStatus::VerifiedNoop);
9937
9938        let verdict = Verdict {
9939            status: RunStatus::VerifiedNoop,
9940            left_pr: false,
9941            quota_hit: false,
9942            parked: false,
9943            no_viable_candidates: false,
9944        };
9945        let mut t = task();
9946        t.start(state.id.clone());
9947        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9948
9949        assert_eq!(t.status, TaskStatus::Held);
9950        assert_eq!(
9951            t.hold_reason.as_deref(),
9952            Some("run ended agent-verified no-op"),
9953            "nothing to append when the question was already answered or never asked"
9954        );
9955    }
9956
9957    #[test]
9958    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9959        crate::run::pin_test_home();
9960        let mut first = run_state(RunStatus::Blocked);
9961        first.id = "20260101-000000-sup1".to_owned();
9962        first.save().unwrap();
9963        let mut second = run_state(RunStatus::Merged);
9964        second.id = "20260101-000000-sup2".to_owned();
9965        second.save().unwrap();
9966
9967        let mut t = task();
9968        t.runs = vec![first.id.clone(), second.id.clone()];
9969        t.status = TaskStatus::Done;
9970
9971        supersede_prior_runs(&t, &crate::run::home());
9972
9973        assert_eq!(
9974            RunState::load(&first.id).unwrap().status,
9975            RunStatus::Superseded,
9976            "the first attempt's Blocked no longer needs anyone's attention"
9977        );
9978        assert_eq!(
9979            RunState::load(&second.id).unwrap().status,
9980            RunStatus::Merged,
9981            "the run that actually succeeded is left exactly as it was"
9982        );
9983    }
9984
9985    #[test]
9986    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9987        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9988        // --resume` invoked by hand outside the daemon never touches
9989        // `daemon.json` at all, so it would look identical to a genuinely
9990        // idle run without also consulting `RunState::liveness`, which reads
9991        // this run's own recorded `driver_pid` instead.
9992        crate::run::pin_test_home();
9993        let mut first = run_state(RunStatus::Blocked);
9994        first.id = "20260101-000000-sup9".to_owned();
9995        // This test process's own pid: guaranteed alive without needing a
9996        // real second process or daemon.
9997        first.driver_pid = Some(std::process::id());
9998        first.driver_started_at = Some(
9999            crate::proc::process_started_at(std::process::id())
10000                .expect("this test process's own start time must be queryable"),
10001        );
10002        first.save().unwrap();
10003        let mut second = run_state(RunStatus::Merged);
10004        second.id = "20260101-000000-supa".to_owned();
10005        second.save().unwrap();
10006
10007        let mut t = task();
10008        t.runs = vec![first.id.clone(), second.id.clone()];
10009        t.status = TaskStatus::Done;
10010
10011        supersede_prior_runs(&t, &crate::run::home());
10012
10013        assert_eq!(
10014            RunState::load(&first.id).unwrap().status,
10015            RunStatus::Blocked,
10016            "a live driver_pid means something is still actually working this run, \
10017             even though no daemon claims it - rewriting under it would just be \
10018             undone the next time that process saves"
10019        );
10020    }
10021
10022    #[test]
10023    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
10024        // The first resweep must skip a still-live attempt exactly like
10025        // `supersede_prior_runs` itself does; a later resweep, once that
10026        // process is no longer actually driving it, is what closes the gap
10027        // `supersede_prior_runs` alone leaves - a task only ever reaches
10028        // `Done` once, so nothing else would ever look at this run again.
10029        let dir = tempfile::tempdir().unwrap();
10030        let home = dir.path().to_path_buf();
10031        let queue = Queue::at(dir.path().join("queue"));
10032
10033        let mut first = run_state(RunStatus::Blocked);
10034        first.id = "20260101-000000-supd".to_owned();
10035        first.driver_pid = Some(std::process::id());
10036        first.driver_started_at = Some(
10037            crate::proc::process_started_at(std::process::id())
10038                .expect("this test process's own start time must be queryable"),
10039        );
10040        first.save_under(&home).unwrap();
10041        let mut second = run_state(RunStatus::Merged);
10042        second.id = "20260101-000000-supe".to_owned();
10043        second.save_under(&home).unwrap();
10044
10045        let mut t = task();
10046        t.runs = vec![first.id.clone(), second.id.clone()];
10047        t.status = TaskStatus::Done;
10048        queue.put(&mut t).unwrap();
10049
10050        resweep_superseded_attempts(&queue, &home);
10051        assert_eq!(
10052            RunState::load_under(&first.id, &home).unwrap().status,
10053            RunStatus::Blocked,
10054            "still live on the first pass, so still untouched"
10055        );
10056
10057        // Stand in for the manual process no longer being the one driving
10058        // this run: same pid (this test process really is still alive), but
10059        // an identity marker that no longer matches it - see
10060        // `RunState::liveness`'s own doc for why a mismatched
10061        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
10062        let mut stale = RunState::load_under(&first.id, &home).unwrap();
10063        stale.driver_started_at = Some("1".to_owned());
10064        stale.save_under(&home).unwrap();
10065
10066        resweep_superseded_attempts(&queue, &home);
10067        assert_eq!(
10068            RunState::load_under(&first.id, &home).unwrap().status,
10069            RunStatus::Superseded,
10070            "the second pass catches up what the first one correctly skipped"
10071        );
10072    }
10073
10074    #[test]
10075    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
10076        crate::run::pin_test_home();
10077        let mut first = run_state(RunStatus::Blocked);
10078        first.id = "20260101-000000-sup3".to_owned();
10079        first.save().unwrap();
10080        let mut second = run_state(RunStatus::Blocked);
10081        second.id = "20260101-000000-sup4".to_owned();
10082        second.save().unwrap();
10083
10084        let mut t = task();
10085        t.runs = vec![first.id.clone(), second.id.clone()];
10086        // Still retrying: nothing about this task's story is settled yet, so
10087        // neither Blocked run may be relabelled, even though a later attempt
10088        // already exists.
10089        t.status = TaskStatus::Failed;
10090
10091        supersede_prior_runs(&t, &crate::run::home());
10092
10093        assert_eq!(
10094            RunState::load(&first.id).unwrap().status,
10095            RunStatus::Blocked
10096        );
10097        assert_eq!(
10098            RunState::load(&second.id).unwrap().status,
10099            RunStatus::Blocked
10100        );
10101    }
10102
10103    #[test]
10104    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
10105        // `magi task done` (or the API's equivalent) can close a task with no
10106        // run of its own ever having succeeded - there is nothing here that
10107        // counts as "the attempt that finished it", so nothing is rewritten.
10108        crate::run::pin_test_home();
10109        let mut first = run_state(RunStatus::Blocked);
10110        first.id = "20260101-000000-sup5".to_owned();
10111        first.save().unwrap();
10112
10113        let mut t = task();
10114        t.runs = vec![first.id.clone()];
10115        t.status = TaskStatus::Done;
10116
10117        supersede_prior_runs(&t, &crate::run::home());
10118
10119        assert_eq!(
10120            RunState::load(&first.id).unwrap().status,
10121            RunStatus::Blocked,
10122            "a single-attempt task has no earlier run to supersede"
10123        );
10124    }
10125
10126    #[test]
10127    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
10128        for status in [
10129            RunStatus::Blocked,
10130            RunStatus::Stalled,
10131            RunStatus::Failed,
10132            RunStatus::Ready,
10133            RunStatus::Merged,
10134        ] {
10135            let dir = tempfile::tempdir().unwrap();
10136            let home = dir.path();
10137            let mut first = run_state(RunStatus::Blocked);
10138            first.id = "20260101-000000-supb".to_owned();
10139            first.save_under(home).unwrap();
10140            let mut second = run_state(status);
10141            second.id = "20260101-000000-supc".to_owned();
10142            second.save_under(home).unwrap();
10143
10144            let mut t = task();
10145            t.runs = vec![first.id.clone(), second.id.clone()];
10146            t.hold_manual(Some("Unmerged work remains".into()));
10147            let mut context = CompletionContext::new(
10148                CompletionActor::Cli,
10149                Some("Discard the unmerged attempts".into()),
10150                home,
10151                &t,
10152            );
10153            context.discard = true;
10154            t.succeed(context);
10155            assert_eq!(t.completion_history.len(), 1);
10156
10157            supersede_prior_runs(&t, home);
10158
10159            assert_eq!(
10160                RunState::load_under(&first.id, home).unwrap().status,
10161                RunStatus::Blocked,
10162                "an audited manual close is not proof the earlier work landed"
10163            );
10164            assert_eq!(
10165                RunState::load_under(&second.id, home).unwrap().status,
10166                status,
10167                "the latest attempt retains its actual outcome"
10168            );
10169        }
10170    }
10171
10172    #[test]
10173    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
10174        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
10175        // to look" - `Failed` and `VerifiedNoop` are already their own
10176        // terminal answers and must not be relabelled into a third one.
10177        crate::run::pin_test_home();
10178        let mut failed = run_state(RunStatus::Failed);
10179        failed.id = "20260101-000000-sup6".to_owned();
10180        failed.save().unwrap();
10181        let mut noop = run_state(RunStatus::VerifiedNoop);
10182        noop.id = "20260101-000000-sup7".to_owned();
10183        noop.save().unwrap();
10184        let mut winner = run_state(RunStatus::Ready);
10185        winner.id = "20260101-000000-sup8".to_owned();
10186        winner.save().unwrap();
10187
10188        let mut t = task();
10189        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
10190        t.status = TaskStatus::Done;
10191
10192        supersede_prior_runs(&t, &crate::run::home());
10193
10194        assert_eq!(
10195            RunState::load(&failed.id).unwrap().status,
10196            RunStatus::Failed
10197        );
10198        assert_eq!(
10199            RunState::load(&noop.id).unwrap().status,
10200            RunStatus::VerifiedNoop
10201        );
10202    }
10203
10204    fn approval_question(run: &str) -> ask::Question {
10205        ask::Question::new(
10206            run.to_owned(),
10207            land::APPROVAL_NODE.to_owned(),
10208            "land".to_owned(),
10209            "merge?".to_owned(),
10210            String::new(),
10211            vec!["merge".to_owned(), "hold".to_owned()],
10212        )
10213    }
10214
10215    #[test]
10216    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
10217        crate::run::pin_test_home();
10218        let mut state = run_state(RunStatus::Landing);
10219        state.id = "20260101-000000-fre1".to_owned();
10220        state.parked = true;
10221        state.save().unwrap();
10222        ask::Questions::open()
10223            .put(&mut approval_question(&state.id))
10224            .unwrap();
10225
10226        let mut t = task();
10227        t.runs.push(state.id.clone());
10228        assert_eq!(
10229            land_resume_state(&t),
10230            LandResume::StillWaiting,
10231            "nobody has answered and the timeout has not passed"
10232        );
10233    }
10234
10235    #[test]
10236    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
10237        crate::run::pin_test_home();
10238        let mut state = run_state(RunStatus::Gating);
10239        state.id = "20260101-000000-gt01".to_owned();
10240        state.parked = true;
10241        state.config.graph.answer_timeout = 60;
10242        state.github_text = Some(crate::run::GithubTextAsk {
10243            rewrite: None,
10244            fingerprint: "f".into(),
10245            title: true,
10246            body: false,
10247            categories: vec!["title-language".into()],
10248            question: None,
10249            asks: 1,
10250            resolved: false,
10251            chosen_title: None,
10252            choice: None,
10253            publication: None,
10254        });
10255        state.save().unwrap();
10256        let store = ask::Questions::open();
10257        let mut q = ask::Question::new(
10258            state.id.clone(),
10259            crate::github_text::ASK_NODE.to_owned(),
10260            crate::github_text::ASK_SEAT.to_owned(),
10261            "s".into(),
10262            String::new(),
10263            vec!["use fallback".into()],
10264        );
10265        store.put(&mut q).unwrap();
10266        let mut t = task();
10267        t.runs.push(state.id.clone());
10268        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
10269        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10270        store.put(&mut q).unwrap();
10271        assert_eq!(land_resume_state(&t), LandResume::Ready);
10272        assert!(!store.get(&q.id).unwrap().status.open());
10273        // Once decided, a parked run is an ordinary candidate again.
10274        state.github_text.as_mut().unwrap().resolved = true;
10275        state.save().unwrap();
10276        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
10277    }
10278
10279    #[test]
10280    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
10281        // `ask::ask_and_wait`'s own deadline used to retire a question
10282        // nobody answered; land's approval bypasses that wait (see
10283        // `land::approval_gate`), so this is now the only place
10284        // `graph.answer_timeout` is enforced for a land approval at all.
10285        crate::run::pin_test_home();
10286        let mut state = run_state(RunStatus::Landing);
10287        state.id = "20260101-000000-exp1".to_owned();
10288        state.parked = true;
10289        state.config.graph.answer_timeout = 60;
10290        state.save().unwrap();
10291
10292        let store = ask::Questions::open();
10293        let mut q = approval_question(&state.id);
10294        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10295        store.put(&mut q).unwrap();
10296
10297        let mut t = task();
10298        t.runs.push(state.id.clone());
10299        assert_eq!(
10300            land_resume_state(&t),
10301            LandResume::Ready,
10302            "an expired question must not be waited on forever"
10303        );
10304
10305        let after = store.get(&q.id).unwrap();
10306        assert!(
10307            !after.status.open(),
10308            "the question is abandoned, not silently ignored"
10309        );
10310        assert!(
10311            after.resolution().is_none(),
10312            "an abandoned question is not read as a decision"
10313        );
10314    }
10315
10316    #[test]
10317    fn reclaim_settles_a_running_task_against_its_last_run() {
10318        let mut t = task();
10319        t.start("20260904-000000-4043".to_owned());
10320        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10321        assert_eq!(
10322            t.status,
10323            TaskStatus::Done,
10324            "a run that actually finished must not stay `running` forever"
10325        );
10326    }
10327
10328    #[test]
10329    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10330        let dir = tempfile::tempdir().unwrap();
10331        let queue = Queue::at(dir.path().join("queue"));
10332        let mut task = task();
10333        let mut run = run_state(RunStatus::Blocked);
10334        run.reserve_under(dir.path()).unwrap();
10335        run.driver_exited = true;
10336        run.save_under(dir.path()).unwrap();
10337        queue.put(&mut task).unwrap();
10338        let stale = task.clone();
10339        task.resume_override = Some(crate::queue::OperatorResume {
10340            question_id: "pending-resume".into(),
10341            at: Timestamp::now(),
10342            conductor_rehold: None,
10343            forced: true,
10344            pinned_run: Some(run.id.clone()),
10345        });
10346        task.start(run.id.clone());
10347        queue.put(&mut task).unwrap();
10348        // Discard every in-memory handoff, as a worker death before execute does.
10349        let mut recovered = queue.get(&task.id).unwrap();
10350        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10351        reclaim(&mut recovered, Some(disk), 2, "en");
10352        queue.put(&mut recovered).unwrap();
10353        assert!(recovered.resume_override.is_none());
10354        assert_eq!(
10355            recovered.dispatched_resumes.get("pending-resume"),
10356            Some(&run.id)
10357        );
10358        let mut stale = stale;
10359        queue.put(&mut stale).unwrap();
10360        assert_eq!(
10361            stale.dispatched_resumes, recovered.dispatched_resumes,
10362            "a stale task writer cannot erase dispatch ownership"
10363        );
10364        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10365        assert!(resumed.decision_starts.is_empty());
10366        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10367        assert!(
10368            resumed.decision_starts.is_empty(),
10369            "handoff is not execution proof"
10370        );
10371        resumed.begin_pass();
10372        resumed.save_under(dir.path()).unwrap();
10373        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10374        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10375        disk.carry_dispatched_resumes(&recovered);
10376        disk.begin_pass();
10377        assert_eq!(
10378            disk.decision_starts.get("pending-resume"),
10379            Some(&0),
10380            "later execution must preserve the original pass receipt"
10381        );
10382    }
10383
10384    #[test]
10385    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10386        let mut t = task();
10387        t.start("20260904-000000-4043".to_owned());
10388        t.last_error = Some("earlier trouble".to_owned());
10389        let mut state = run_state(RunStatus::Judging);
10390        state.parked = true;
10391        reclaim(&mut t, Some(state), 1, "en");
10392        assert_eq!(t.status, TaskStatus::Parked);
10393        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10394        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10395        assert!(t.park_reason.is_some());
10396        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10397        assert!(!t.fresh_start);
10398        assert!(t.status.runnable());
10399    }
10400
10401    #[test]
10402    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10403        let mut t = task();
10404        t.start("20260904-000000-4043".to_owned());
10405        t.last_error = Some("earlier trouble".to_owned());
10406        settle(
10407            &mut t,
10408            Verdict {
10409                status: RunStatus::Judging,
10410                left_pr: false,
10411                quota_hit: false,
10412                parked: true,
10413                no_viable_candidates: false,
10414            },
10415            "parked after `judging`",
10416            1,
10417        );
10418        assert_eq!(t.status, TaskStatus::Parked);
10419        assert_eq!(t.attempts, 0);
10420        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10421        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10422        assert_eq!(t.schema, crate::queue::SCHEMA);
10423        assert!(
10424            crate::notices::task_held(&t).is_none(),
10425            "a park is not news"
10426        );
10427        t.start("20260904-000000-4043".to_owned());
10428        assert_eq!(t.park_reason, None);
10429    }
10430
10431    #[test]
10432    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10433        // A blocked run with attempts left goes back to `Failed`, exactly as
10434        // it would from `attempt` itself - `reclaim` must not invent a second
10435        // policy for a task a daemon merely stopped without reporting.
10436        let mut t = task();
10437        t.start("20260904-000000-4043".to_owned());
10438        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10439        assert_eq!(t.status, TaskStatus::Failed);
10440        assert!(t.status.runnable());
10441    }
10442
10443    #[test]
10444    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10445        let mut t = task();
10446        t.start("20260904-000000-4043".to_owned());
10447        assert_eq!(t.attempts, 1);
10448        let mut run = run_state(RunStatus::Implementing);
10449        run.id = "20260904-000000-4043".to_owned();
10450        run.begin_pass();
10451        let cause = crate::run::ParkCause::Upgrade {
10452            from: "0.121.0".to_owned(),
10453            to: Some("0.121.1".to_owned()),
10454        };
10455        run.end_pass_parked(cause.clone());
10456        run.parked = true;
10457        let verdict = Verdict {
10458            status: run.status,
10459            left_pr: false,
10460            quota_hit: false,
10461            parked: true,
10462            no_viable_candidates: false,
10463        };
10464        // A crash after the checkpoint but before queue settlement must
10465        // recover exactly the same scheduling evidence and refund.
10466        let mut orphan = t.clone();
10467        reclaim(&mut orphan, Some(run.clone()), 2, "en");
10468        assert_eq!(orphan.status, TaskStatus::Parked);
10469        assert_eq!(orphan.attempts, 0);
10470        assert_eq!(
10471            orphan.upgrade_resume_key(),
10472            Some((run.passes[0].started_at, orphan.id.as_str()))
10473        );
10474        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10475        assert_eq!(t.attempts, 0);
10476        assert_eq!(t.passes.len(), 1);
10477        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10478        assert_eq!(t.passes[0].parked, Some(cause));
10479        assert_eq!(t.passes[0].pass_index, 0);
10480        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10481        assert!(t.upgrade_resume_key().is_some());
10482
10483        // A resumed pass that then fails spends its attempt, and the earlier
10484        // pass's entry is untouched.
10485        t.start("20260904-000000-4043".to_owned());
10486        run.begin_pass();
10487        run.status = RunStatus::Failed;
10488        let verdict = Verdict {
10489            status: RunStatus::Failed,
10490            left_pr: false,
10491            quota_hit: false,
10492            parked: false,
10493            no_viable_candidates: false,
10494        };
10495        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10496        assert_eq!(t.passes.len(), 2);
10497        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10498        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10499        assert_eq!(t.passes[1].pass_index, 1);
10500        assert_eq!(t.attempts, 1);
10501    }
10502
10503    #[test]
10504    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10505        let mut t = task();
10506        t.start("20260904-000000-4043".to_owned());
10507        reclaim(&mut t, None, 2, "en");
10508        assert_eq!(t.status, TaskStatus::Held);
10509        assert!(
10510            t.last_error
10511                .as_deref()
10512                .is_some_and(|e| e.contains("running")),
10513            "the operator needs to know why this task was held"
10514        );
10515    }
10516
10517    #[test]
10518    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10519        let dir = tempfile::tempdir().unwrap();
10520        let queue = Queue::at(dir.path().to_path_buf());
10521        let mut task = task();
10522        let run = "20261124-000000-dead";
10523        task.link_run(run);
10524        task.attempts = 2;
10525        task.status = TaskStatus::Running;
10526        task.sync_only = Some(crate::base_sync_only::Request {
10527            run: run.into(),
10528            at: Timestamp::now(),
10529        });
10530        queue.put(&mut task).unwrap();
10531        assert_eq!(
10532            reclaim_orphaned_running(&queue, 3, &Default::default()),
10533            vec![task.id.clone()]
10534        );
10535        let saved = queue.get(&task.id).unwrap();
10536        assert_eq!(saved.status, TaskStatus::Held);
10537        assert_eq!(saved.attempts, 2);
10538        assert_eq!(saved.execution_runs(), [run]);
10539        assert!(
10540            saved
10541                .last_error
10542                .unwrap()
10543                .contains("verification was not allowed")
10544        );
10545        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10546    }
10547
10548    #[test]
10549    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10550        use crate::base_sync_only::{Outcome, Pass, Request};
10551
10552        let mut state = run_state(RunStatus::Blocked);
10553        let mut task = task();
10554        let request = Request {
10555            run: state.id.clone(),
10556            at: Timestamp::now(),
10557        };
10558        task.start(state.id.clone());
10559        task.sync_only = Some(request.clone());
10560        // Dedicated dispatch saves Running with the pre-pass attempt count.
10561        task.attempts = 2;
10562        let mut pass = Pass::new(request, &state);
10563        pass.result = Outcome::AlreadyCurrent;
10564        state.sync_only_passes.push(pass);
10565        state.begin_pass();
10566
10567        reclaim(&mut task, Some(state), 3, "en");
10568
10569        assert_eq!(task.status, TaskStatus::Held);
10570        assert_eq!(task.attempts, 2);
10571        assert!(task.sync_only.is_none());
10572        let detail = task.hold_reason.unwrap();
10573        assert!(detail.contains("HEAD already contains the base"));
10574        assert!(detail.contains("verification was not allowed"));
10575    }
10576
10577    #[test]
10578    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10579        let dir = tempfile::tempdir().unwrap();
10580        let queue = Queue::at(dir.path().to_path_buf());
10581
10582        // No run recorded, so this never has to touch `RunState::load`.
10583        let mut orphaned = task();
10584        orphaned.id = "20260904-000000-orph".to_owned();
10585        orphaned.status = TaskStatus::Running;
10586        orphaned.attempts = 1;
10587        queue.put(&mut orphaned).unwrap();
10588
10589        let mut alive = task();
10590        alive.id = "20260904-000000-live".to_owned();
10591        alive.status = TaskStatus::Running;
10592        alive.attempts = 1;
10593        queue.put(&mut alive).unwrap();
10594        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10595
10596        let mut queued = task();
10597        queued.id = "20260904-000000-wait".to_owned();
10598        queue.put(&mut queued).unwrap();
10599
10600        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10601        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10602
10603        assert_eq!(
10604            queue.get(&orphaned.id).unwrap().status,
10605            TaskStatus::Held,
10606            "nothing was driving it and there was no run to recover"
10607        );
10608        assert_eq!(
10609            queue.get(&alive.id).unwrap().status,
10610            TaskStatus::Running,
10611            "a live claim must protect the task it belongs to"
10612        );
10613        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10614    }
10615
10616    /// Read a run.json back from an explicit `home`, the same way
10617    /// `reclaim_abandoned_runs` itself does - never through the
10618    /// process-global `RunState::load`, which this test's own `home` (an
10619    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10620    /// use at all.
10621    fn read_run_under(home: &Path, id: &str) -> RunState {
10622        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10623        serde_json::from_str(&body).unwrap()
10624    }
10625
10626    #[test]
10627    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10628        let dir = tempfile::tempdir().unwrap();
10629        let home = dir.path().to_path_buf();
10630        let now = Timestamp::now();
10631        let overrun_seat = || crate::run::ActiveSeat {
10632            node: "implement".to_owned(),
10633            started_at: now - jiff::SignedDuration::new(21_000, 0),
10634            timeout_secs: 3_600,
10635            attempt: 0,
10636            task: None,
10637            command: None,
10638            index: None,
10639            total: None,
10640        };
10641
10642        let mut dead = run_state(RunStatus::Implementing);
10643        dead.id = "20260101-000000-dead".to_owned();
10644        dead.active.insert("impl-A".to_owned(), overrun_seat());
10645        // A `driver_pid` the injected query below confirms gone outright —
10646        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10647        dead.driver_pid = Some(4242);
10648        dead.save_under(&home).unwrap();
10649
10650        // Same shape, but a live daemon's heartbeat names it: must be left
10651        // exactly alone, however far past its own timeout the seat sits.
10652        let mut alive = run_state(RunStatus::Implementing);
10653        alive.id = "20260101-000000-aliv".to_owned();
10654        alive.active.insert("impl-A".to_owned(), overrun_seat());
10655        alive.save_under(&home).unwrap();
10656        let mut status = Status::new();
10657        status.current = vec![Current {
10658            worker: None,
10659            task: "20260101-000000-task".to_owned(),
10660            run: alive.id.clone(),
10661        }];
10662        write_status_to(&home.join("daemon.json"), &status).unwrap();
10663
10664        // The abandoned seat left an open question behind: nobody is left to
10665        // read an answer once the run is failed, and this must not wait for
10666        // some later daemon startup's own sweep to notice that.
10667        let questions = Questions::at(home.join("questions"));
10668        let mut q = ask::Question::new(
10669            dead.id.clone(),
10670            "implement".to_owned(),
10671            "impl-A".to_owned(),
10672            "Which storage backend?".to_owned(),
10673            String::new(),
10674            vec!["SQLite".to_owned(), "Redis".to_owned()],
10675        );
10676        questions.put(&mut q).unwrap();
10677
10678        let abandoned = reclaim_abandoned_runs_with(
10679            &home,
10680            now,
10681            |pid| if pid == 4242 { Some(false) } else { None },
10682            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10683        );
10684        assert_eq!(abandoned, vec![dead.id.clone()]);
10685
10686        let reloaded = read_run_under(&home, &dead.id);
10687        assert_eq!(reloaded.status, RunStatus::Failed);
10688        assert!(reloaded.active.is_empty());
10689        assert!(
10690            !questions.get(&q.id).unwrap().status.open(),
10691            "the failed run's own open question must be settled in the same pass"
10692        );
10693
10694        let still_alive = read_run_under(&home, &alive.id);
10695        assert_eq!(
10696            still_alive.status,
10697            RunStatus::Implementing,
10698            "a live daemon's claim protects it"
10699        );
10700        assert!(!still_alive.active.is_empty());
10701    }
10702
10703    /// The exact shape a review round flagged as broken: `magi serve` running
10704    /// in this same `home` scans *every* run on disk, including a manual
10705    /// `magi review` / `magi run` this daemon never started and that
10706    /// therefore claims no heartbeat of its own. Before this scan asked
10707    /// `liveness` rather than just `is_working_on`, a manual run whose active
10708    /// seat merely ran a little past its own timeout — the CLI finishing up,
10709    /// its result still being collected — got wiped and failed by a daemon
10710    /// that had nothing to do with it, out from under a process that was
10711    /// still very much running.
10712    #[test]
10713    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10714        let dir = tempfile::tempdir().unwrap();
10715        let home = dir.path().to_path_buf();
10716        let now = Timestamp::now();
10717
10718        let mut manual = run_state(RunStatus::Reviewing);
10719        manual.id = "20260101-000000-manl".to_owned();
10720        manual.active.insert(
10721            "review-1".to_owned(),
10722            crate::run::ActiveSeat {
10723                node: "review".to_owned(),
10724                started_at: now - jiff::SignedDuration::new(21_000, 0),
10725                timeout_secs: 3_600,
10726                attempt: 0,
10727                task: None,
10728                command: None,
10729                index: None,
10730                total: None,
10731            },
10732        );
10733        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10734        // but a real, still-running process: `liveness` must corroborate this
10735        // as `Live`, not read the missing daemon claim as death.
10736        manual.driver_pid = Some(4242);
10737        manual.driver_started_at = Some("1790000000".to_owned());
10738        manual.save_under(&home).unwrap();
10739
10740        let abandoned = reclaim_abandoned_runs_with(
10741            &home,
10742            now,
10743            |pid| if pid == 4242 { Some(true) } else { None },
10744            |pid| {
10745                if pid == 4242 {
10746                    Some("1790000000".to_owned())
10747                } else {
10748                    None
10749                }
10750            },
10751        );
10752        assert!(
10753            abandoned.is_empty(),
10754            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10755        );
10756
10757        let reloaded = read_run_under(&home, &manual.id);
10758        assert_eq!(reloaded.status, RunStatus::Reviewing);
10759        assert!(!reloaded.active.is_empty());
10760    }
10761
10762    #[test]
10763    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10764        let dir = tempfile::tempdir().unwrap();
10765        let queue = Queue::at(dir.path().to_path_buf());
10766        let mut only = task();
10767        queue.put(&mut only).unwrap();
10768
10769        let _elsewhere = queue.claim(&only.id).unwrap();
10770        let candidates = runnable(&queue);
10771        assert_eq!(candidates.len(), 1, "the task is still runnable");
10772        assert!(
10773            queue.claim(&candidates[0].id).is_err(),
10774            "the loop cannot take a claim somebody else holds"
10775        );
10776
10777        let after = queue.get(&only.id).unwrap();
10778        assert_eq!(after.status, TaskStatus::Queued);
10779        assert_eq!(
10780            after.attempts, 0,
10781            "losing the race is not an attempt at the task"
10782        );
10783        assert_eq!(after.last_error, None);
10784    }
10785
10786    #[test]
10787    fn the_status_file_round_trips_and_its_heartbeat_advances() {
10788        let dir = tempfile::tempdir().unwrap();
10789        let path = dir.path().join("daemon.json");
10790
10791        let mut status = Status::new();
10792        status.idle = false;
10793        status.completed = 7;
10794        status.current = vec![Current {
10795            worker: None,
10796            task: "20260902-000000-t111".to_owned(),
10797            run: "20260902-000001-r111".to_owned(),
10798        }];
10799        write_status_to(&path, &status).unwrap();
10800        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10801        assert_eq!(first.schema, SCHEMA);
10802        assert_eq!(first.pid, std::process::id());
10803        assert!(!first.idle);
10804        assert_eq!(first.completed, 7);
10805        assert_eq!(first.current, status.current);
10806        assert!(
10807            !path.with_extension("json.tmp").exists(),
10808            "the temp file is renamed, not left behind"
10809        );
10810
10811        std::thread::sleep(Duration::from_millis(5));
10812        status.updated_at = Timestamp::now();
10813        status.polls = 3;
10814        write_status_to(&path, &status).unwrap();
10815        let second: Status =
10816            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10817        assert!(
10818            second.updated_at > first.updated_at,
10819            "a reader can only detect staleness if the heartbeat moves"
10820        );
10821        assert_eq!(
10822            second.started_at, first.started_at,
10823            "the start time is not a heartbeat"
10824        );
10825        assert_eq!(second.polls, 3);
10826    }
10827
10828    #[test]
10829    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10830        let dir = tempfile::tempdir().unwrap();
10831
10832        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10833
10834        let mut status = Status::new();
10835        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10836        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10837        let stale = read_status(dir.path()).unwrap();
10838        assert!(
10839            !stale.running(Timestamp::now()),
10840            "a minute without a heartbeat is a dead daemon, not a busy one"
10841        );
10842        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10843
10844        status.updated_at = Timestamp::now();
10845        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10846        let fresh = read_status(dir.path()).unwrap();
10847        assert!(fresh.running(Timestamp::now()));
10848    }
10849
10850    #[test]
10851    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10852        let dir = tempfile::tempdir().unwrap();
10853        let now = Timestamp::now();
10854        let mine = "20260903-080619-01c2";
10855
10856        assert!(
10857            !is_working_on(dir.path(), mine, now),
10858            "no status file means nobody is working on anything"
10859        );
10860
10861        let mut status = Status::new();
10862        status.current = vec![Current {
10863            worker: None,
10864            task: "20260903-080340-0167".to_owned(),
10865            run: mine.to_owned(),
10866        }];
10867        status.updated_at = now;
10868        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10869        assert!(is_working_on(dir.path(), mine, now));
10870        assert!(
10871            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10872            "a daemon busy with one run is not working on another"
10873        );
10874
10875        // A killed daemon stops writing heartbeats but leaves the file behind
10876        // naming the run it died in. That run must not be undeletable forever.
10877        status.updated_at = now - jiff::SignedDuration::from_secs(600);
10878        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10879        assert!(
10880            !is_working_on(dir.path(), mine, now),
10881            "a stale heartbeat is a dead daemon, so its run is a leftover"
10882        );
10883    }
10884
10885    #[test]
10886    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10887        let dir = tempfile::tempdir().unwrap();
10888        let now = Timestamp::now();
10889
10890        assert!(
10891            !is_working_on_short(dir.path(), "01c2", now),
10892            "no status file means nobody is working on anything"
10893        );
10894
10895        let mut status = Status::new();
10896        status.current = vec![Current {
10897            worker: None,
10898            task: "20260903-080340-0167".to_owned(),
10899            run: "20260903-080619-01c2".to_owned(),
10900        }];
10901        status.updated_at = now;
10902        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10903        assert!(
10904            is_working_on_short(dir.path(), "01c2", now),
10905            "the run's short id is the last block of its full id"
10906        );
10907        assert!(
10908            !is_working_on_short(dir.path(), "3cbf", now),
10909            "a daemon busy with one worktree bay is not working on another"
10910        );
10911    }
10912
10913    #[test]
10914    fn a_newer_status_file_still_yields_a_reading() {
10915        let dir = tempfile::tempdir().unwrap();
10916        // A field this build has never heard of must not turn the reading into
10917        // nothing at all; that is the whole reason the reader is permissive.
10918        std::fs::write(
10919            dir.path().join("daemon.json"),
10920            serde_json::json!({
10921                "schema": 2,
10922                "updated_at": Timestamp::now().to_string(),
10923                "idle": true,
10924                "surprise": { "nested": [1, 2, 3] },
10925            })
10926            .to_string(),
10927        )
10928        .unwrap();
10929
10930        let reading = read_status(dir.path()).expect("a forward-compatible read");
10931        assert!(reading.running(Timestamp::now()));
10932        assert!(reading.idle);
10933        assert!(reading.current.is_empty());
10934    }
10935
10936    #[test]
10937    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10938        // A daemon started before `current` became a list keeps writing this
10939        // shape on every heartbeat until it is restarted. A rolling upgrade
10940        // - a newer `magi web` or `magi doctor` reading an older `magi
10941        // serve`'s heartbeat - must still see the run it is on, not "no
10942        // daemon" from a type mismatch failing the whole struct.
10943        let dir = tempfile::tempdir().unwrap();
10944        std::fs::write(
10945            dir.path().join("daemon.json"),
10946            serde_json::json!({
10947                "schema": 1,
10948                "pid": 4242,
10949                "updated_at": Timestamp::now().to_string(),
10950                "idle": false,
10951                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10952                "completed": 3,
10953                "polls": 9,
10954            })
10955            .to_string(),
10956        )
10957        .unwrap();
10958
10959        let reading = read_status(dir.path()).expect("an older shape must still parse");
10960        assert!(reading.running(Timestamp::now()));
10961        assert_eq!(
10962            reading.current,
10963            vec![Current {
10964                worker: None,
10965                task: "20260902-140501-aaaa".to_owned(),
10966                run: "20260902-140502-bbbb".to_owned(),
10967            }]
10968        );
10969    }
10970
10971    #[test]
10972    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10973        let dir = tempfile::tempdir().unwrap();
10974        std::fs::write(
10975            dir.path().join("daemon.json"),
10976            serde_json::json!({
10977                "schema": 1,
10978                "updated_at": Timestamp::now().to_string(),
10979                "idle": true,
10980                "current": null,
10981            })
10982            .to_string(),
10983        )
10984        .unwrap();
10985        let with_null = read_status(dir.path()).expect("null must still parse");
10986        assert!(with_null.current.is_empty());
10987
10988        std::fs::write(
10989            dir.path().join("daemon.json"),
10990            serde_json::json!({
10991                "schema": 1,
10992                "updated_at": Timestamp::now().to_string(),
10993                "idle": true,
10994            })
10995            .to_string(),
10996        )
10997        .unwrap();
10998        let absent = read_status(dir.path()).expect("a missing field must still parse");
10999        assert!(absent.current.is_empty());
11000    }
11001
11002    #[test]
11003    fn a_task_without_a_repository_runs_in_the_daemons_default() {
11004        let fallback = Path::new("/default");
11005        let mut blank = task();
11006        blank.repo = PathBuf::new();
11007        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
11008        let mut dot = task();
11009        dot.repo = PathBuf::from(".");
11010        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
11011        assert_eq!(
11012            repo_for(&task(), fallback),
11013            PathBuf::from("/repo"),
11014            "a task that names a repository keeps it"
11015        );
11016    }
11017
11018    #[test]
11019    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
11020        let dir = tempfile::tempdir().unwrap();
11021        let repo = dir.path();
11022        let path = repo.join("explicit.toml");
11023        std::fs::write(
11024            &path,
11025            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
11026        )
11027        .unwrap();
11028        let opts = Opts {
11029            config: Some(path),
11030            ..Opts::default()
11031        };
11032        let queue = Queue::at(repo.join("queue"));
11033        let mut new = task();
11034        queue.put(&mut new).unwrap();
11035        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
11036        assert_eq!(
11037            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
11038            BuildCache::Isolated
11039        );
11040
11041        let mut old = task();
11042        old.schema = 22;
11043        queue.put(&mut old).unwrap();
11044        let mut old = queue.get(&old.id).unwrap();
11045        let config = resolved(&old);
11046        assert_eq!(config.verify.build_cache, BuildCache::Shared);
11047        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
11048        old.hold_manual(Some("wait".into()));
11049        queue.put(&mut old).unwrap();
11050
11051        let mut saved = queue.get(&old.id).unwrap();
11052        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
11053        saved
11054            .overrides
11055            .as_mut()
11056            .unwrap()
11057            .merge_over(&crate::queue::RunOverrides {
11058                build_cache: Some(BuildCache::Isolated),
11059                ..Default::default()
11060            });
11061        queue.put(&mut saved).unwrap();
11062        assert_eq!(
11063            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
11064            BuildCache::Isolated
11065        );
11066    }
11067
11068    #[test]
11069    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
11070        let dir = tempfile::tempdir().unwrap();
11071        let path = dir.path().join("explicit.toml");
11072        let write = |verify: &str| {
11073            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
11074        };
11075        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
11076        let opts = Opts {
11077            config: Some(path.clone()),
11078            ..Opts::default()
11079        };
11080        let mut task = task();
11081        task.set_urgent(true).unwrap();
11082        let resolved = |task: &Task| {
11083            prepare_for(dir.path(), &opts, task)
11084                .unwrap()
11085                .verify
11086                .build_cache
11087        };
11088        assert_eq!(resolved(&task), BuildCache::Isolated);
11089        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
11090        assert_eq!(resolved(&task), BuildCache::Shared);
11091        task.change_build_cache(None).unwrap();
11092        assert_eq!(resolved(&task), BuildCache::Isolated);
11093        task.set_urgent(false).unwrap();
11094        assert_eq!(resolved(&task), BuildCache::Shared);
11095
11096        // Urgent work must never be the one stopped by isolation: with no
11097        // shared cache to wait behind, or with a verification command isolated
11098        // mode cannot run, an urgent task keeps the configured mode.
11099        task.set_urgent(true).unwrap();
11100        write("e2e = [\"npm test\"]\n");
11101        assert_eq!(resolved(&task), BuildCache::Shared);
11102        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
11103        assert_eq!(resolved(&task), BuildCache::Shared);
11104        // An explicit choice stays strict and is applied as asked.
11105        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
11106        assert_eq!(resolved(&task), BuildCache::Isolated);
11107    }
11108
11109    #[test]
11110    fn task_implementers_edit_inherits_daemon_config_and_merge() {
11111        let dir = tempfile::tempdir().unwrap();
11112        let path = dir.path().join("explicit.toml");
11113        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
11114        let opts = Opts {
11115            config: Some(path),
11116            merge: Some("none".into()),
11117            ..Default::default()
11118        };
11119        let mut t = task();
11120        t.set_implementers(
11121            2,
11122            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11123                .unwrap(),
11124        )
11125        .unwrap();
11126        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11127        assert_eq!(cfg.graph.implementers, 2);
11128        assert_eq!(cfg.graph.judges, 1);
11129        assert_eq!(cfg.merge.mode, MergeMode::None);
11130        t.set_implementers(1, &cfg).unwrap();
11131        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11132        apply_task_implementers(&mut cfg, &t);
11133        assert_eq!(cfg.graph.implementers, 1);
11134        assert_eq!(cfg.graph.judges, 1);
11135        assert_eq!(cfg.merge.mode, MergeMode::None);
11136    }
11137
11138    #[test]
11139    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
11140        let dir = tempfile::tempdir().unwrap();
11141        let repo = dir.path().join("repo");
11142        std::fs::create_dir(&repo).unwrap();
11143        std::fs::write(
11144            repo.join("magi.toml"),
11145            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
11146        )
11147        .unwrap();
11148        let daemon_config = dir.path().join("daemon.toml");
11149        std::fs::write(
11150            &daemon_config,
11151            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
11152        )
11153        .unwrap();
11154        let opts = Opts {
11155            config: Some(daemon_config),
11156            merge: Some("pr".into()),
11157            ..Default::default()
11158        };
11159        let q = Queue::at(dir.path().join("queue"));
11160        let validation: Config =
11161            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11162                .unwrap();
11163        // No provenance field on legacy direct tasks: both shapes stay isolated.
11164        for record in ["{}", r#"{"candidates":2}"#] {
11165            let overrides = serde_json::from_str(record).unwrap();
11166            let filing = crate::direct::Filing {
11167                instruction: "work".into(),
11168                title: "direct".into(),
11169                repo: repo.clone(),
11170                source: crate::queue::Source::Human,
11171                solo: false,
11172                overrides,
11173                review_of: None,
11174                sources: Default::default(),
11175            };
11176            let filed =
11177                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
11178            let crate::direct::Filed::Standalone {
11179                mut task,
11180                claim: _claim,
11181            } = filed
11182            else {
11183                panic!("local filing")
11184            };
11185            let before = prepare_for(&repo, &opts, &task).unwrap();
11186            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
11187            assert_eq!(
11188                before.merge.mode,
11189                MergeMode::None,
11190                "daemon --merge must not leak"
11191            );
11192            for n in [2, 1, 2] {
11193                task.set_implementers(n, &validation).unwrap();
11194                q.put(&mut task).unwrap();
11195                task = q.get(&task.id).unwrap();
11196                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
11197                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
11198                apply_task_implementers(&mut cfg, &task);
11199                assert_eq!(cfg.graph.implementers, usize::from(n));
11200                assert_eq!(cfg.graph.judges, 2);
11201                assert_eq!(cfg.merge.mode, MergeMode::None);
11202            }
11203        }
11204    }
11205
11206    #[test]
11207    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
11208        let cfg: Config =
11209            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11210                .unwrap();
11211        let mut t = task();
11212        t.review_of = Some("review-target".into());
11213        t.hold_manual(Some("retry".into()));
11214        let mut previous = RunState::new(
11215            PathBuf::from("/repo"),
11216            "main".into(),
11217            "abc1234".into(),
11218            "review".into(),
11219            cfg.clone(),
11220        );
11221        previous.config.graph.implementers = 2;
11222        for count in [1, 3] {
11223            t.set_implementers(count, &cfg).unwrap();
11224            t.release();
11225            assert_eq!(t.review_of.as_deref(), Some("review-target"));
11226            for proposed in [
11227                Starter::Resume(previous.id.clone()),
11228                Starter::Review("recovery-target".into()),
11229            ] {
11230                assert_eq!(
11231                    starter_with_implementers(&t, Some(&previous), proposed),
11232                    Starter::Review("review-target".into())
11233                );
11234            }
11235            let mut configured = cfg.clone();
11236            apply_task_implementers(&mut configured, &t);
11237            assert_eq!(configured.graph.implementers, usize::from(count));
11238            assert_eq!(previous.config.graph.implementers, 2);
11239        }
11240    }
11241
11242    #[test]
11243    fn task_implementers_dispatch_and_resume_agree() {
11244        let mut t = task();
11245        let cfg: crate::config::Config =
11246            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11247                .unwrap();
11248        let mut run = RunState::new(
11249            PathBuf::from("/repo"),
11250            "main".into(),
11251            "abc1234".into(),
11252            "work".into(),
11253            cfg.clone(),
11254        );
11255        run.config.graph.implementers = 2;
11256        for n in [2, 1, 3, 2] {
11257            t.set_implementers(n, &cfg).unwrap();
11258            let mut dispatched = cfg.clone();
11259            apply_task_implementers(&mut dispatched, &t);
11260            assert_eq!(dispatched.graph.implementers, usize::from(n));
11261            assert_eq!(implementers_match(&t, &run), n == 2);
11262            for proposed in [
11263                Starter::Resume(run.id.clone()),
11264                Starter::Review("old-branch".into()),
11265            ] {
11266                let expected = if n == 2 {
11267                    proposed.clone()
11268                } else {
11269                    Starter::Start
11270                };
11271                assert_eq!(
11272                    starter_with_implementers(&t, Some(&run), proposed),
11273                    expected
11274                );
11275            }
11276            assert_eq!(
11277                run.config.graph.implementers, 2,
11278                "history must not be rewritten"
11279            );
11280        }
11281        t.solo = false;
11282        t.overrides = None;
11283        assert!(implementers_match(&t, &run));
11284    }
11285
11286    #[test]
11287    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
11288        // Three seats said out loud. What `solo` promises is one candidate
11289        // *whatever the config asks for*, so the contrast has to be a number
11290        // this test owns - it used to be `Config::default()`'s, which became
11291        // 1 when one implementation became the default and left the two
11292        // halves of this test asserting the same thing.
11293        let mut solo_cfg = Config::default();
11294        solo_cfg.graph.implementers = 3;
11295        let mut solo_task = task();
11296        solo_task.solo = true;
11297        apply_task_implementers(&mut solo_cfg, &solo_task);
11298        assert_eq!(solo_cfg.graph.implementers, 1);
11299
11300        let mut plain_cfg = Config::default();
11301        plain_cfg.graph.implementers = 3;
11302        let plain_task = task();
11303        assert!(!plain_task.solo);
11304        apply_task_implementers(&mut plain_cfg, &plain_task);
11305        assert_eq!(
11306            plain_cfg.graph.implementers, 3,
11307            "a task that did not ask to run alone keeps the config's candidates"
11308        );
11309    }
11310
11311    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11312        QuotaLoss {
11313            cause: crate::agent::QuotaCause::UsageLimit,
11314            agent: String::new(),
11315            seat: seat.into(),
11316            node: "judge".into(),
11317            at: at.parse().unwrap(),
11318            reset: reset.map(str::to_string),
11319        }
11320    }
11321
11322    #[test]
11323    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11324        let now = Timestamp::now();
11325        for reset in [None, Some("in 1h")] {
11326            let auth = crate::agent::Quota {
11327                cause: crate::agent::QuotaCause::Authentication,
11328                agent: "alpha".into(),
11329                reset: reset.map(str::to_owned),
11330            };
11331            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11332            assert_eq!(cooldown_until(&[loss], now), None);
11333        }
11334    }
11335
11336    #[test]
11337    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11338        let old: Vec<QuotaLoss> = (1..=4)
11339            .map(|i| {
11340                loss(
11341                    &format!("judge-{i}"),
11342                    "2026-09-23T05:23:00Z",
11343                    Some("2:40pm (Asia/Tokyo)"),
11344                )
11345            })
11346            .collect();
11347        let fresh = losses_this_attempt(&old, &old);
11348        assert!(fresh.is_empty());
11349        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11350        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
11351    }
11352
11353    #[test]
11354    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11355        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11356        let now = Timestamp::now();
11357        let mut after = old.clone();
11358        after.push(loss("judge-2", &now.to_string(), None));
11359        let fresh = losses_this_attempt(&old, &after);
11360        assert_eq!(fresh, vec![after[1].clone()]);
11361        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11362        assert_eq!(
11363            until,
11364            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11365        );
11366    }
11367
11368    #[test]
11369    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11370        // `recover_stall` removes judge-1's loss and the retry then hits quota
11371        // again: the vector is the same length, so an index diff sees nothing.
11372        let before = vec![
11373            loss("judge-1", "2026-09-23T05:23:00Z", None),
11374            loss("judge-2", "2026-09-23T05:24:00Z", None),
11375        ];
11376        let after = vec![
11377            loss("judge-2", "2026-09-23T05:24:00Z", None),
11378            loss("judge-1", "2026-09-24T01:00:00Z", None),
11379        ];
11380        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11381    }
11382
11383    #[test]
11384    fn merge_overrides_are_parsed_or_refused() {
11385        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11386        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11387        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11388        assert!(merge_mode("squash").is_err());
11389    }
11390
11391    #[test]
11392    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11393        let now = Timestamp::now();
11394        let fallback = Duration::from_secs(300);
11395        let cap = Duration::from_secs(1800);
11396
11397        // No reset hint at all: the fallback.
11398        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11399
11400        // A reset ten minutes out, well inside the cap: waited for exactly.
11401        let soon = now + jiff::SignedDuration::from_secs(600);
11402        assert_eq!(
11403            quota_wait(Some(soon), now, fallback, cap),
11404            Duration::from_secs(600)
11405        );
11406
11407        // A reset already in the past is not trusted: the fallback, not a
11408        // zero or negative wait that would spin the loop right back around.
11409        let past = now - jiff::SignedDuration::from_secs(60);
11410        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11411
11412        // A reset further out than the cap is trusted for direction but not
11413        // for magnitude: a parsing slip must not sleep the loop for a day.
11414        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11415        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11416    }
11417
11418    #[test]
11419    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11420        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11421
11422        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11423        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11424
11425        // Same clock reading, but it has already gone by today: read as
11426        // tomorrow's, since the CLI would not still be reporting a limit past
11427        // its own stated reset.
11428        let already_past =
11429            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11430        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11431
11432        assert!(
11433            parse_reset_hint("session limit reached", now, now).is_none(),
11434            "free text with no recognised shape is not guessed at"
11435        );
11436        assert!(
11437            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11438            "an unresolvable zone name is not guessed at either"
11439        );
11440    }
11441
11442    #[test]
11443    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11444        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11445
11446        let at = parse_reset_hint(
11447            "You've hit your usage limit. Visit \
11448             https://chatgpt.com/codex/settings/usage to purchase more \
11449             credits or try again at Sep 19th, 2026 5:10 PM.",
11450            now,
11451            now,
11452        )
11453        .expect("the codex reset wording is a recognised shape");
11454        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11455
11456        // The month is explicit, so a date already earlier in the same
11457        // sentence-implied year than `now` is trusted as written rather than
11458        // rolled forward a year the way the bracketed shape rolls a
11459        // same-day clock reading to tomorrow.
11460        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11461            .expect("an explicit year needs no rollover");
11462        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11463
11464        assert!(
11465            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11466            "a two-digit year is not the documented shape and is not guessed at"
11467        );
11468        assert!(
11469            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11470            "a four-letter month name is not the documented three-letter abbreviation"
11471        );
11472        assert!(
11473            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11474            "an explicit zone on the dated shape is a format nobody has \
11475             documented, and is refused rather than guessed at as UTC"
11476        );
11477    }
11478
11479    #[test]
11480    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11481        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11482        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11483
11484        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11485        assert_eq!(at.as_second() - recorded.as_second(), 3769);
11486
11487        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11488        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11489
11490        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11491            assert!(
11492                parse_reset_hint(bad, now, recorded).is_none(),
11493                "{bad:?} must not be guessed at"
11494            );
11495        }
11496    }
11497
11498    /// A loop whose queue lives in a temp tree and whose poll interval is far
11499    /// longer than the test's patience, so anything that waits out a poll
11500    /// instead of noticing the stop fails rather than merely being slow.
11501    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11502        let config = dir.join("magi.toml");
11503        std::fs::write(
11504            &config,
11505            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11506        )
11507        .unwrap();
11508        let opts = Opts {
11509            poll: Duration::from_secs(30),
11510            config: Some(config),
11511            // The explicit fixture config keeps startup cleanup from reading
11512            // machine configuration. This fictional repository likewise
11513            // keeps any best-effort git cleanup away from this checkout.
11514            repo: dir.join("repo"),
11515            ..Opts::default()
11516        };
11517        // The status file goes in a directory that does not exist yet, so its
11518        // creation is itself evidence the loop published one. `worktrees`
11519        // must be just as fictional: the janitor reclaims worktrees under it
11520        // for real, and a test that let it fall through to
11521        // `crate::run::default_worktree_root()` would have it reclaim
11522        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
11523        // which is exactly what happened before this function took the
11524        // parameter at all.
11525        let home = dir.join("home");
11526        // These control-only fixtures do not launch native workers. Give the
11527        // independently tested maintenance services a fresh cadence receipt.
11528        let stamps = home.join("service-ticks");
11529        std::fs::create_dir_all(&stamps).unwrap();
11530        for service in ["waiter", "deputies", "release-watch"] {
11531            std::fs::write(
11532                stamps.join(service),
11533                Timestamp::now().as_second().to_string(),
11534            )
11535            .unwrap();
11536        }
11537        for operation in [
11538            "conductor",
11539            "maintenance",
11540            "housekeeping",
11541            "disk-pressure",
11542            "cache",
11543            "fetch",
11544            "chat-goals",
11545        ] {
11546            std::fs::write(
11547                stamps.join(format!("daemon-{operation}")),
11548                serde_json::to_vec(&Timestamp::now()).unwrap(),
11549            )
11550            .unwrap();
11551        }
11552        let worktrees = dir.join("wt");
11553        (
11554            opts,
11555            Queue::at(dir.join("queue")),
11556            home.join("daemon.json"),
11557            home,
11558            worktrees,
11559        )
11560    }
11561
11562    #[tokio::test]
11563    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11564        let dir = tempfile::tempdir().unwrap();
11565        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11566        let mut waiting = task();
11567        waiting.repo = opts.repo.clone();
11568        waiting.hold_machine(crate::disk::gate(1, 100));
11569        waiting.mark_disk_capacity();
11570        waiting.attempts = 2;
11571        queue.put(&mut waiting).unwrap();
11572        let mut busy = task();
11573        busy.status = TaskStatus::Running;
11574        queue.put(&mut busy).unwrap();
11575        let payload = serde_json::to_value(ServiceWorker {
11576            opts,
11577            queue: queue.root().to_owned(),
11578            worktrees_root: worktrees,
11579            operation: "maintenance".into(),
11580        })
11581        .unwrap();
11582        run_service_worker(&home, payload.clone()).await.unwrap();
11583        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11584        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11585        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11586        run_service_worker(&home, payload).await.unwrap();
11587        assert!(
11588            crate::worker::active(&home).unwrap().is_empty(),
11589            "monitoring only queues; normal dispatch owns launches"
11590        );
11591        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11592    }
11593
11594    #[tokio::test]
11595    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11596        let dir = tempfile::tempdir().unwrap();
11597        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11598        let cfg = Config::default();
11599        start_service(
11600            &home,
11601            &opts,
11602            &queue,
11603            &worktrees,
11604            "housekeeping",
11605            Some(&cfg),
11606            true,
11607        )
11608        .await
11609        .unwrap();
11610        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11611        let read = |path: &Path| -> serde_json::Value {
11612            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11613        };
11614        assert_eq!(read(&receipt)["detail"], "cadence not due");
11615        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11616        start_service(
11617            &home,
11618            &opts,
11619            &queue,
11620            &worktrees,
11621            "housekeeping",
11622            Some(&cfg),
11623            true,
11624        )
11625        .await
11626        .unwrap();
11627        assert_eq!(
11628            read(&receipt)["detail"],
11629            "active work or runnable task queue"
11630        );
11631        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11632        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11633        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11634        start_service(
11635            &home,
11636            &opts,
11637            &queue,
11638            &worktrees,
11639            "disk-pressure",
11640            Some(&cfg),
11641            false,
11642        )
11643        .await
11644        .unwrap();
11645        assert_eq!(
11646            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11647            "no active work; idle housekeeping owns scan"
11648        );
11649        assert!(crate::worker::active(&home).unwrap().is_empty());
11650    }
11651
11652    #[tokio::test]
11653    async fn goal_observation_service_does_not_block_scheduler_decisions() {
11654        let dir = tempfile::tempdir().unwrap();
11655        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11656        let queue = Queue::at(home.join("queue"));
11657        let mut task = task();
11658        task.repo = opts.repo.clone();
11659        task.chat = Some("decision-chat".into());
11660        task.hold_machine(Some("waiting for a decision".into()));
11661        queue.put(&mut task).unwrap();
11662        let questions = Questions::at(home.join("questions"));
11663        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11664        question.node = crate::conduct::NODE.into();
11665        question.status = ask::QuestionStatus::Open;
11666        question.answer = None;
11667        question.answered_at = None;
11668        questions.put(&mut question).unwrap();
11669        questions
11670            .update(&question.id, |q| {
11671                q.answer(ask::Answer::Choice("resume で続行する".into()))
11672            })
11673            .unwrap();
11674
11675        let talks = crate::talk::Talks::at(home.join("talks"));
11676        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11677        decision_chat.pending = "Keep this unsent status question".into();
11678        talks.put(&mut decision_chat).unwrap();
11679        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11680        talk.goals.push(serde_json::from_value(serde_json::json!({
11681            "id":"goal","purpose":"follow the retained job","scope":"one task",
11682            "condition":{"description":"land the result","kind":"runs_merged"},
11683            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11684            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11685            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11686        })).unwrap());
11687        talks.put(&mut talk).unwrap();
11688
11689        // A retained service lease models an observation still waiting on its
11690        // external dependency. Admission must neither await nor repeat it.
11691        let directory = home.join("workers/jobs/abcdef");
11692        std::fs::create_dir_all(&directory).unwrap();
11693        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11694        crate::pr_head::try_lock_file(&lease).unwrap();
11695        let mut job = crate::worker::Job {
11696            id: "abcdef".into(),
11697            sequence: 1,
11698            kind: "daemon-service".into(),
11699            key: "service:daemon-chat-goals".into(),
11700            payload: serde_json::Value::Null,
11701            generation: "fixture".into(),
11702            version: None,
11703            status: crate::worker::Status::Running,
11704            result: None,
11705            pid: Some(std::process::id()),
11706            created_at: Timestamp::now().as_second() as u64,
11707            finished_at: None,
11708        };
11709        let record = directory.join("job.json");
11710        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11711        let status = Arc::new(Mutex::new(Status::new()));
11712        let stop = Stop::new();
11713        let mut dispatch = Box::pin(poll(
11714            &opts,
11715            &queue,
11716            &status,
11717            &home,
11718            &worktrees,
11719            &stop,
11720            DispatchLimits {
11721                max_concurrent: 1,
11722                pause_for_interrupts: false,
11723                recovery_cfg: None,
11724            },
11725        ));
11726        std::future::poll_fn(|cx| {
11727            assert!(dispatch.as_mut().poll(cx).is_pending());
11728            std::task::Poll::Ready(())
11729        })
11730        .await;
11731        assert!(lock(&status).polls > 0);
11732        let saved = queue.get(&task.id).unwrap();
11733        assert_eq!(saved.status, TaskStatus::Done);
11734        assert!(saved.action_applied(&question.id));
11735        assert!(
11736            talks
11737                .get("decision-chat")
11738                .unwrap()
11739                .pending
11740                .contains("Keep this unsent status question")
11741        );
11742        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11743        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11744        assert_eq!(
11745            goal.started,
11746            Some(1),
11747            "only the observation worker may reconcile its goal"
11748        );
11749        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11750
11751        stop.stop();
11752        dispatch.await.unwrap();
11753        job.status = crate::worker::Status::Finished;
11754        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11755        drop(lease);
11756    }
11757
11758    #[test]
11759    fn a_stop_is_idempotent_and_once_set_stays_set() {
11760        let stop = Stop::new();
11761        assert!(!stop.stopped());
11762
11763        stop.stop();
11764        assert!(stop.stopped());
11765        stop.stop();
11766        assert!(stop.stopped(), "a second stop is not a toggle");
11767
11768        let shared = stop.clone();
11769        assert!(
11770            shared.stopped(),
11771            "a clone is the same stop; that is how the loop and its caller share one"
11772        );
11773    }
11774
11775    #[tokio::test]
11776    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11777        for operation in ["conductor", "maintenance", "housekeeping"] {
11778            let dir = tempfile::tempdir().unwrap();
11779            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11780            opts.once = true;
11781            opts.poll = Duration::from_millis(1);
11782            // This test exercises answer scheduling, not explicit discard:
11783            // ordinary Done requires a completed retained execution.
11784            let mut state = run_state(RunStatus::Ready);
11785            state.reserve_under(&home).unwrap();
11786            state.save_under(&home).unwrap();
11787            let mut task = task();
11788            task.runs.push(state.id.clone());
11789            queue.put(&mut task).unwrap();
11790            let claim = queue.claim(&task.id).unwrap();
11791
11792            // Model a live service holding the task's claim across the
11793            // scheduler's dispatch scan. No real subprocess or timed race.
11794            let directory = home.join("workers/jobs/abcdef");
11795            std::fs::create_dir_all(&directory).unwrap();
11796            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11797            crate::pr_head::try_lock_file(&lease).unwrap();
11798            let mut job = crate::worker::Job {
11799                id: "abcdef".into(),
11800                sequence: 1,
11801                kind: "daemon-service".into(),
11802                key: format!("service:daemon-{operation}"),
11803                payload: serde_json::Value::Null,
11804                generation: "fixture".into(),
11805                version: None,
11806                status: crate::worker::Status::Running,
11807                result: None,
11808                pid: Some(std::process::id()),
11809                created_at: Timestamp::now().as_second() as u64,
11810                finished_at: None,
11811            };
11812            let record = directory.join("job.json");
11813            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11814
11815            let status = Arc::new(Mutex::new(Status::new()));
11816            let stop = Stop::new();
11817            let mut drain = Box::pin(poll(
11818                &opts,
11819                &queue,
11820                &status,
11821                &home,
11822                &worktrees,
11823                &stop,
11824                DispatchLimits {
11825                    max_concurrent: 1,
11826                    pause_for_interrupts: false,
11827                    recovery_cfg: None,
11828                },
11829            ));
11830            std::future::poll_fn(|cx| {
11831                use std::future::Future;
11832                assert!(
11833                    drain.as_mut().poll(cx).is_pending(),
11834                    "--once must wait for {operation} to release its queue claim"
11835                );
11836                std::task::Poll::Ready(())
11837            })
11838            .await;
11839            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11840
11841            // An answer arrives while the service still owns the claim. A
11842            // fresh scheduling pass must apply it before declaring idle.
11843            let questions = Questions::at(home.join("questions"));
11844            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11845            questions.put(&mut q).unwrap();
11846            drop(claim);
11847            // Model services that took longer than their cadence, without a
11848            // wall-clock sleep. The final scans must not respawn them even
11849            // though their receipts now permit another periodic invocation.
11850            let expired =
11851                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11852            for service in [operation, "housekeeping"] {
11853                std::fs::write(
11854                    home.join("service-ticks").join(format!("daemon-{service}")),
11855                    &expired,
11856                )
11857                .unwrap();
11858            }
11859            job.status = crate::worker::Status::Finished;
11860            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11861            drop(lease);
11862            tokio::time::timeout(Duration::from_secs(2), drain)
11863                .await
11864                .expect("the settled service must allow the drain to finish")
11865                .unwrap();
11866            let after = queue.get(&task.id).unwrap();
11867            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11868            assert!(after.action_applied(&q.id));
11869            for service in [operation, "housekeeping"] {
11870                assert_eq!(
11871                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11872                        .unwrap(),
11873                    expired,
11874                    "the final once rescan must not restart {service}"
11875                );
11876            }
11877        }
11878    }
11879
11880    #[test]
11881    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11882        let stop = Stop::new();
11883        stop.busy.store(1, Ordering::SeqCst);
11884        assert!(
11885            !stop.finishing(),
11886            "a busy loop nobody has asked to stop is just running"
11887        );
11888
11889        stop.stop();
11890        assert!(
11891            stop.finishing(),
11892            "a stop asked for mid-run has not landed until the run is settled"
11893        );
11894
11895        stop.busy.store(0, Ordering::SeqCst);
11896        assert!(
11897            !stop.finishing(),
11898            "once the run is settled the stop has landed and there is nothing to finish"
11899        );
11900    }
11901
11902    #[test]
11903    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11904        let stop = Stop::new();
11905        stop.busy.store(2, Ordering::SeqCst);
11906        stop.stop();
11907        assert!(stop.finishing(), "two runs still in flight");
11908
11909        stop.busy.store(1, Ordering::SeqCst);
11910        assert!(
11911            stop.finishing(),
11912            "one run finished, but a sibling is still working"
11913        );
11914
11915        stop.busy.store(0, Ordering::SeqCst);
11916        assert!(
11917            !stop.finishing(),
11918            "the last run out is what actually lands the stop"
11919        );
11920    }
11921
11922    #[tokio::test]
11923    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11924        let dir = tempfile::tempdir().unwrap();
11925        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11926        let stop = Stop::new();
11927        stop.stop();
11928
11929        let began = std::time::Instant::now();
11930        tokio::time::timeout(
11931            Duration::from_secs(2),
11932            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11933        )
11934        .await
11935        .expect("a stopped loop must return, not sit out its poll interval")
11936        .expect("the loop's own setup and teardown must not fail");
11937        assert!(
11938            began.elapsed() < opts.poll,
11939            "returned only after {:?}, which is a poll interval, not a stop",
11940            began.elapsed()
11941        );
11942    }
11943
11944    #[tokio::test]
11945    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11946        let dir = tempfile::tempdir().unwrap();
11947        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11948        let stop = Stop::new();
11949
11950        // Asked for after the loop is already parked on its empty queue, which
11951        // is the case an operator tapping stop on a phone actually hits.
11952        let asker = {
11953            let stop = stop.clone();
11954            tokio::spawn(async move {
11955                tokio::time::sleep(Duration::from_millis(20)).await;
11956                stop.stop();
11957            })
11958        };
11959
11960        let began = std::time::Instant::now();
11961        tokio::time::timeout(
11962            Duration::from_secs(2),
11963            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11964        )
11965        .await
11966        .expect("a stop asked for while idle must wake the wait")
11967        .expect("the loop's own setup and teardown must not fail");
11968        asker.await.unwrap();
11969        assert!(
11970            began.elapsed() < opts.poll,
11971            "returned only after {:?}, so the stop waited on the sleep",
11972            began.elapsed()
11973        );
11974    }
11975
11976    #[tokio::test]
11977    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11978        let dir = tempfile::tempdir().unwrap();
11979        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11980        let stop = Stop::new();
11981        stop.stop();
11982
11983        tokio::time::timeout(
11984            Duration::from_secs(2),
11985            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11986        )
11987        .await
11988        .expect("a stopped loop must return")
11989        .expect("the loop's own setup and teardown must not fail");
11990
11991        assert!(
11992            home.is_dir(),
11993            "the loop did publish a status file, so its removal is the teardown and not an absence"
11994        );
11995        assert!(
11996            !status_file.exists(),
11997            "a stopped loop clears its status file"
11998        );
11999        assert!(
12000            read_status(&home).is_none(),
12001            "a reader must see no daemon at all, not a heartbeat that merely stopped"
12002        );
12003    }
12004
12005    #[tokio::test]
12006    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
12007        let dir = tempfile::tempdir().unwrap();
12008        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12009
12010        let mut settled = RunState::new(
12011            dir.path().join("repo"),
12012            "main".to_owned(),
12013            "abc1234".to_owned(),
12014            "fixture".to_owned(),
12015            Config::default(),
12016        );
12017        settled.status = RunStatus::Ready;
12018        let run_dir = home.join("runs").join(&settled.id);
12019        std::fs::create_dir_all(&run_dir).unwrap();
12020        std::fs::write(
12021            run_dir.join("run.json"),
12022            serde_json::to_string_pretty(&settled).unwrap(),
12023        )
12024        .unwrap();
12025        let questions = Questions::at(home.join("questions"));
12026        let mut question = ask::Question::new(
12027            settled.id.clone(),
12028            "review".to_owned(),
12029            "reviewer-1".to_owned(),
12030            "Continue?".to_owned(),
12031            String::new(),
12032            Vec::new(),
12033        );
12034        questions.put(&mut question).unwrap();
12035
12036        run_service_worker(
12037            &home,
12038            serde_json::to_value(ServiceWorker {
12039                opts,
12040                queue: queue.root().to_path_buf(),
12041                worktrees_root: worktrees,
12042                operation: "housekeeping".to_owned(),
12043            })
12044            .unwrap(),
12045        )
12046        .await
12047        .unwrap();
12048
12049        assert_eq!(
12050            questions.get(&question.id).unwrap().status,
12051            ask::QuestionStatus::Abandoned,
12052            "the independent housekeeping worker settles ended-run questions"
12053        );
12054    }
12055
12056    #[test]
12057    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
12058        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12059
12060        assert!(
12061            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
12062            "never checked before: due at once"
12063        );
12064
12065        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
12066        assert!(
12067            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
12068            "well inside the interval: not due yet"
12069        );
12070
12071        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
12072        assert!(
12073            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
12074            "exactly at the edge: not yet due, same convention as `clean::due`"
12075        );
12076
12077        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12078        assert!(
12079            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
12080            "past the interval: due again"
12081        );
12082    }
12083
12084    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
12085    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
12086    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
12087    /// and the congestion test below both need, and must not drift apart.
12088    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
12089        let config = dir.join("magi.toml");
12090        // A literal (single-quoted) TOML string, not a basic one: the cache
12091        // path is a Windows path full of backslashes, and a basic string
12092        // would have TOML try to interpret `\U` (from `\Users\...`) as a
12093        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
12094        // `{{ vars.cache }}` rendering documents.
12095        std::fs::write(
12096            &config,
12097            format!(
12098                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
12099                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
12100                cache_dir.display()
12101            ),
12102        )
12103        .unwrap();
12104        Opts {
12105            config: Some(config),
12106            repo: dir.join("repo"),
12107            ..Opts::default()
12108        }
12109    }
12110
12111    #[tokio::test]
12112    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
12113        let dir = tempfile::tempdir().unwrap();
12114        let home = dir.path().join("home");
12115        let cache_dir = dir.path().join("cache");
12116        std::fs::create_dir_all(&cache_dir).unwrap();
12117        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12118        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12119
12120        // Nobody has asked this daemon to stop, which is the ordinary case;
12121        // the skip that a stop buys is asserted by its own test below.
12122        let running = Stop::new();
12123        let mut last_checked = None;
12124        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12125        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
12126            .await;
12127        assert_eq!(
12128            crate::disk::dir_size(&cache_dir),
12129            0,
12130            "over the cap on the first check ever: pruned at once, no idle queue required"
12131        );
12132        assert_eq!(last_checked, Some(t0));
12133
12134        // A fresh oversized file lands, but the next check is not due yet.
12135        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
12136        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
12137        maybe_prune_cache_between_runs(
12138            &opts.repo,
12139            &opts,
12140            &home,
12141            &running,
12142            &mut last_checked,
12143            too_soon,
12144        )
12145        .await;
12146        assert_eq!(
12147            crate::disk::dir_size(&cache_dir),
12148            10,
12149            "too soon since the last check: left alone rather than rescanned every call"
12150        );
12151        assert_eq!(
12152            last_checked,
12153            Some(t0),
12154            "an idle check does not reset the clock"
12155        );
12156
12157        // Once the interval elapses, the same oversized cache is caught again.
12158        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12159        maybe_prune_cache_between_runs(
12160            &opts.repo,
12161            &opts,
12162            &home,
12163            &running,
12164            &mut last_checked,
12165            due_again,
12166        )
12167        .await;
12168        assert_eq!(
12169            crate::disk::dir_size(&cache_dir),
12170            0,
12171            "due again: pruned back under the cap"
12172        );
12173    }
12174
12175    /// A stop must not queue behind housekeeping. The prune below is a
12176    /// synchronous walk of the whole cache with no await point in it, so a
12177    /// loop that entered it could not get back to its own `stopped()` test
12178    /// until the walk finished - and because no run is in flight at this
12179    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
12180    /// the stop had already landed. The idle branch has always made this same
12181    /// check before reaching `janitor`; the between-runs path makes it too.
12182    #[tokio::test]
12183    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
12184        let dir = tempfile::tempdir().unwrap();
12185        let home = dir.path().join("home");
12186        let cache_dir = dir.path().join("cache");
12187        std::fs::create_dir_all(&cache_dir).unwrap();
12188        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12189        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12190
12191        let stop = Stop::new();
12192        stop.stop();
12193        assert!(
12194            !stop.finishing(),
12195            "no run is in flight at a between-runs boundary, so nothing else \
12196             would tell the operator this stop had not taken effect yet"
12197        );
12198
12199        let mut last_checked = None;
12200        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12201        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
12202            .await;
12203        assert_eq!(
12204            crate::disk::dir_size(&cache_dir),
12205            10,
12206            "over its cap, and due for the first check ever, but a stop outranks \
12207             it: the cap is a standing policy the next start measures again"
12208        );
12209        assert_eq!(
12210            last_checked, None,
12211            "a check that never happened must not claim the interval"
12212        );
12213    }
12214
12215    /// A backlog must not starve cache pruning. The finite cache worker runs
12216    /// independently of queue drain and must not consume any task attempts.
12217    #[tokio::test]
12218    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
12219        let dir = tempfile::tempdir().unwrap();
12220        let cache_dir = dir.path().join("cache");
12221        std::fs::create_dir_all(&cache_dir).unwrap();
12222        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
12223
12224        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
12225        opts.poll = Duration::from_millis(20);
12226        opts.max_attempts = 1_000;
12227
12228        let queue = Queue::at(dir.path().join("queue"));
12229        for i in 0..128 {
12230            let mut task = Task::new(
12231                format!("queued work {i}"),
12232                format!("queued work {i}"),
12233                opts.repo.clone(),
12234                Source::Human,
12235            );
12236            queue.put(&mut task).unwrap();
12237        }
12238
12239        let home = dir.path().join("home");
12240        let worktrees = dir.path().join("wt");
12241        run_service_worker(
12242            &home,
12243            serde_json::to_value(ServiceWorker {
12244                opts,
12245                queue: queue.root().to_path_buf(),
12246                worktrees_root: worktrees,
12247                operation: "cache".to_owned(),
12248            })
12249            .unwrap(),
12250        )
12251        .await
12252        .unwrap();
12253        let after = queue.list();
12254        assert_eq!(after.len(), 128);
12255        assert!(
12256            after
12257                .iter()
12258                .all(|task| task.status.runnable() && task.attempts == 0)
12259        );
12260
12261        assert_eq!(
12262            crate::disk::dir_size(&cache_dir),
12263            0,
12264            "an oversized cache must not be left to grow unboundedly just because the \
12265             queue kept the loop busy the whole time"
12266        );
12267    }
12268
12269    #[test]
12270    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
12271        let dir = tempfile::tempdir().unwrap();
12272        let queue = Queue::at(dir.path().join("queue"));
12273        let questions = Questions::at(dir.path().join("questions"));
12274        let mut task = task();
12275        queue.put(&mut task).unwrap();
12276
12277        let mut task_question = ask::Question::new(
12278            task.id.clone(),
12279            crate::conduct::NODE.to_owned(),
12280            "conduct".to_owned(),
12281            "Which backend?".to_owned(),
12282            String::new(),
12283            Vec::new(),
12284        );
12285        questions.put(&mut task_question).unwrap();
12286        task.block(vec![task_question.id.clone()], None);
12287        queue.put(&mut task).unwrap();
12288
12289        let mut run_question = ask::Question::new(
12290            "20260101-000000-run1".to_owned(),
12291            "review".to_owned(),
12292            "reviewer-1".to_owned(),
12293            "Run question".to_owned(),
12294            String::new(),
12295            Vec::new(),
12296        );
12297        questions.put(&mut run_question).unwrap();
12298
12299        // A question from another node whose `run` happens to equal this
12300        // task's id — the same field, filled in for an unrelated reason. Only
12301        // `crate::conduct::NODE` questions use `run` as a task id; this one
12302        // must never be touched by this reconciliation, even after release.
12303        let mut coincidental = ask::Question::new(
12304            task.id.clone(),
12305            "review".to_owned(),
12306            "reviewer-1".to_owned(),
12307            "Unrelated review question".to_owned(),
12308            String::new(),
12309            Vec::new(),
12310        );
12311        questions.put(&mut coincidental).unwrap();
12312
12313        reconcile_task_questions(&queue, &questions);
12314        assert!(questions.get(&task_question.id).unwrap().status.open());
12315        assert!(questions.get(&run_question.id).unwrap().status.open());
12316        assert!(questions.get(&coincidental.id).unwrap().status.open());
12317
12318        task.release();
12319        queue.put(&mut task).unwrap();
12320        reconcile_task_questions(&queue, &questions);
12321        assert_eq!(
12322            questions.get(&task_question.id).unwrap().status,
12323            ask::QuestionStatus::Abandoned
12324        );
12325        assert!(
12326            questions.get(&run_question.id).unwrap().status.open(),
12327            "run questions remain the run janitor's responsibility"
12328        );
12329        assert!(
12330            questions.get(&coincidental.id).unwrap().status.open(),
12331            "a non-conductor question must not be abandoned just because its \
12332             run id coincides with a task id"
12333        );
12334    }
12335
12336    #[test]
12337    fn a_freshly_started_running_task_is_never_stalled() {
12338        let dir = tempfile::tempdir().unwrap();
12339        let mut t = task();
12340        t.start("run-1".to_owned());
12341        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
12342        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
12343        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12344    }
12345
12346    #[test]
12347    fn a_long_running_task_with_no_live_daemon_is_stalled() {
12348        let dir = tempfile::tempdir().unwrap();
12349        let mut t = task();
12350        t.start("run-1".to_owned());
12351        t.updated_at = Timestamp::now()
12352            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12353        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12354        assert_eq!(
12355            stalled_tasks(
12356                &Queue::at(dir.path().join("q")),
12357                dir.path(),
12358                Timestamp::now()
12359            )
12360            .len(),
12361            0,
12362            "the task was never written to this queue"
12363        );
12364    }
12365
12366    #[test]
12367    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12368        let dir = tempfile::tempdir().unwrap();
12369        let mut t = task();
12370        t.id = "20260903-080340-0167".to_owned();
12371        t.start("20260903-080619-01c2".to_owned());
12372        t.updated_at = Timestamp::now()
12373            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12374
12375        let mut status = Status::new();
12376        status.current = vec![Current {
12377            worker: None,
12378            task: t.id.clone(),
12379            run: "20260903-080619-01c2".to_owned(),
12380        }];
12381        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12382
12383        assert!(
12384            !is_stalled(&t, dir.path(), Timestamp::now()),
12385            "a live daemon's own heartbeat rules out stalled, however long the task has run"
12386        );
12387    }
12388
12389    /// Rewrite a task's `updated_at` on disk directly, bypassing
12390    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
12391    /// a fixture look like it has genuinely been `running` for a while.
12392    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12393        let path = queue.path_of(id);
12394        let body = std::fs::read_to_string(&path).unwrap();
12395        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12396        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12397        v["updated_at"] = serde_json::Value::String(old.to_string());
12398        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12399    }
12400
12401    #[test]
12402    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12403        // The realistic `poll()` ordering, not `is_stalled` in isolation:
12404        // `reclaim_orphaned_running` runs first, on every poll, and settles
12405        // any `running` task whose claim it can actually take. For most
12406        // crashes that is immediate - a dead pid is proof enough for
12407        // `sweep_stale_claims` to drop the lock the same tick, and the very
12408        // next claim attempt succeeds. But a lock whose pid cannot be parsed
12409        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
12410        // `sweep_stale_claims`'s own doc), so the lock - and the claim
12411        // failure behind it - can legitimately outlive many polls. This is
12412        // exactly the gap `stalled_tasks` exists to surface well before that
12413        // six-hour sweep would: reclaim leaves the task `running`, and it
12414        // must still reach the conductor as stalled.
12415        let dir = tempfile::tempdir().unwrap();
12416        let queue = Queue::at(dir.path().join("queue"));
12417        let home = dir.path().join("home");
12418
12419        let mut t = task();
12420        t.id = "20260101-000001-lock".to_owned();
12421        t.start("run-1".to_owned());
12422        queue.put(&mut t).unwrap();
12423        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12424        std::fs::write(
12425            dir.path().join("queue").join(format!("{}.lock", t.id)),
12426            "not a pid",
12427        )
12428        .unwrap();
12429
12430        let now = Timestamp::now();
12431        assert!(
12432            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12433            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12434             and reclaim must leave the task alone"
12435        );
12436        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12437
12438        let stalled = stalled_tasks(&queue, &home, now);
12439        assert_eq!(
12440            stalled.len(),
12441            1,
12442            "reclaim's inability to claim it yet must not hide it from the conductor"
12443        );
12444        assert_eq!(stalled[0].id, t.id);
12445    }
12446
12447    #[test]
12448    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12449        let dir = tempfile::tempdir().unwrap();
12450        crate::run::set_home(dir.path().join("run-home"));
12451        let queue = Queue::at(dir.path().join("queue"));
12452        let home = dir.path().join("home");
12453        let questions = Questions::at(dir.path().join("questions"));
12454
12455        let mut t = task();
12456        t.id = "20260101-000003-dead".to_owned();
12457        t.start("missing-run".to_owned());
12458        queue.put(&mut t).unwrap();
12459        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12460
12461        // This is the real poll ordering: retain the deterministic stalled
12462        // input before a claim proves the owner is gone and reclaims it.
12463        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12464        assert_eq!(
12465            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12466            [&t.id]
12467        );
12468        assert_eq!(
12469            reclaim_orphaned_running(&queue, 2, &Default::default()),
12470            [t.id.clone()]
12471        );
12472        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12473
12474        // Reclaim drops its guard before conductor decisions are applied, so
12475        // the decision for the captured stalled input has a real write path.
12476        crate::conduct::apply(
12477            &queue,
12478            &questions,
12479            &crate::conduct::Verdict {
12480                decisions: vec![crate::conduct::Decision {
12481                    id: t.id.clone(),
12482                    recovery: Some(crate::conduct::Recovery::Requeue),
12483                    ..crate::conduct::Decision::default()
12484                }],
12485            },
12486        )
12487        .unwrap();
12488        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12489    }
12490
12491    #[test]
12492    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12493        let dir = tempfile::tempdir().unwrap();
12494        let queue = Queue::at(dir.path().join("queue"));
12495        let home = dir.path().join("home");
12496
12497        let mut fresh = task();
12498        fresh.id = "20260101-000001-aaaa".to_owned();
12499        fresh.start("run-1".to_owned());
12500        queue.put(&mut fresh).unwrap();
12501
12502        let mut old = task();
12503        old.id = "20260101-000002-bbbb".to_owned();
12504        old.start("run-2".to_owned());
12505        queue.put(&mut old).unwrap();
12506        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12507
12508        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12509        assert_eq!(stalled.len(), 1);
12510        assert_eq!(stalled[0].id, old.id);
12511    }
12512
12513    #[test]
12514    fn queued_and_finished_task_views_partition_by_status() {
12515        let dir = tempfile::tempdir().unwrap();
12516        let queue = Queue::at(dir.path().join("queue"));
12517
12518        let mut queued = task();
12519        queued.id = "20260101-000001-aaaa".to_owned();
12520        queue.put(&mut queued).unwrap();
12521
12522        let mut failed = task();
12523        failed.id = "20260101-000002-bbbb".to_owned();
12524        failed.start("run-1".to_owned());
12525        failed.fail("gate red", 5);
12526        queue.put(&mut failed).unwrap();
12527
12528        let mut held = task();
12529        held.id = "20260101-000003-cccc".to_owned();
12530        held.hold_machine(None);
12531        queue.put(&mut held).unwrap();
12532
12533        let mut running = task();
12534        running.id = "20260101-000004-dddd".to_owned();
12535        running.start("run-2".to_owned());
12536        queue.put(&mut running).unwrap();
12537
12538        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12539        assert_eq!(queued_ids, [queued.id.clone()]);
12540
12541        let mut finished_ids: Vec<String> =
12542            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12543        finished_ids.sort_unstable();
12544        let mut want = vec![failed.id.clone(), held.id.clone()];
12545        want.sort_unstable();
12546        assert_eq!(finished_ids, want);
12547    }
12548
12549    #[test]
12550    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12551        for short in [false, true] {
12552            let dir = tempfile::tempdir().unwrap();
12553            let queue = Queue::at(dir.path().join("queue"));
12554            let questions = ask::Questions::at(dir.path().join("questions"));
12555            let mut running = task();
12556            running.id = "20261013-192213-feb2".into();
12557            running.start("existing-run".into());
12558            queue.put(&mut running).unwrap();
12559            let mut middle = task();
12560            middle.id = "20261013-193611-ca5b".into();
12561            middle.block(
12562                vec![if short {
12563                    "feb2".into()
12564                } else {
12565                    running.id.clone()
12566                }],
12567                None,
12568            );
12569            queue.put(&mut middle).unwrap();
12570            let mut waiting = task();
12571            waiting.id = "20261013-202849-ee37".into();
12572            waiting.block(
12573                vec![if short {
12574                    "ca5b".into()
12575                } else {
12576                    middle.id.clone()
12577                }],
12578                Some("wait for implementation".into()),
12579            );
12580            queue.put(&mut waiting).unwrap();
12581            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12582            let inv = crate::blockers::Inventory::load(&queue, &questions);
12583            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12584            assert!(inv.stuck().is_empty());
12585            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12586            assert!(report.quarantined.is_empty());
12587            assert!(report.asked.is_empty());
12588            resolve_blockers(&queue, &questions);
12589            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12590            assert!(questions.list().is_empty());
12591            // Finishing the transitive prerequisite alone does not satisfy
12592            // the task's direct dependency.
12593            running.succeed(CompletionContext::new(
12594                CompletionActor::DaemonSettle,
12595                None,
12596                dir.path(),
12597                &running,
12598            ));
12599            queue.put(&mut running).unwrap();
12600            resolve_blockers(&queue, &questions);
12601            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12602            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12603            middle = queue.get(&middle.id).unwrap();
12604            middle.succeed(CompletionContext::new(
12605                CompletionActor::DaemonSettle,
12606                None,
12607                dir.path(),
12608                &middle,
12609            ));
12610            queue.put(&mut middle).unwrap();
12611            resolve_blockers(&queue, &questions);
12612            let after = queue.get(&waiting.id).unwrap();
12613            assert_eq!(after.status, TaskStatus::Queued);
12614            assert!(after.blocked_by.is_empty());
12615            assert_eq!(after.instruction, waiting.instruction);
12616        }
12617    }
12618
12619    #[test]
12620    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12621        for future_schema in [false, true] {
12622            let name = "20261013-193611-ca5b";
12623            let mut future = task();
12624            future.id = name.into();
12625            future.schema = crate::queue::SCHEMA + 1;
12626            let contents = if future_schema {
12627                serde_json::to_string(&future).unwrap()
12628            } else {
12629                "corrupt".into()
12630            };
12631            let dir = tempfile::tempdir().unwrap();
12632            let queue = Queue::at(dir.path().join("queue"));
12633            let questions = ask::Questions::at(dir.path().join("questions"));
12634            let mut waiting = task();
12635            waiting.id = "20261013-202849-ee37".into();
12636            waiting.block(vec!["ca5b".into()], None);
12637            queue.put(&mut waiting).unwrap();
12638            std::fs::write(queue.path_of(name), contents).unwrap();
12639            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12640            assert!(
12641                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12642            );
12643            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12644            assert!(report.asked.is_empty());
12645            resolve_blockers(&queue, &questions);
12646            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12647            assert!(questions.list().is_empty());
12648        }
12649        let dir = tempfile::tempdir().unwrap();
12650        let queue = Queue::at(dir.path().join("queue"));
12651        let questions = ask::Questions::at(dir.path().join("questions"));
12652        let mut waiting = task();
12653        waiting.id = "20261013-202849-ee37".into();
12654        waiting.block(vec!["ca5b".into()], None);
12655        queue.put(&mut waiting).unwrap();
12656        let mut done = task();
12657        done.id = "20261013-193611-ca5b".into();
12658        done.succeed(CompletionContext::new(
12659            CompletionActor::Cli,
12660            None,
12661            dir.path(),
12662            &done,
12663        ));
12664        queue.put(&mut done).unwrap();
12665        // An unreadable second match must not disappear from uniqueness
12666        // checks just because Queue::list skips it.
12667        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12668        assert!(queue.get("ca5b").is_err());
12669        assert_eq!(
12670            crate::queue::dependency(&queue, &questions, "ca5b"),
12671            crate::queue::Dependency::Ambiguous
12672        );
12673        resolve_blockers(&queue, &questions);
12674        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12675        assert!(report.asked.is_empty());
12676        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12677        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12678    }
12679
12680    #[test]
12681    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12682        for held in [false, true] {
12683            for question in [false, true] {
12684                for reference in ["ca5b", "20261013-193611-ca5b"] {
12685                    let dir = tempfile::tempdir().unwrap();
12686                    let queue = Queue::at(dir.path().join("queue"));
12687                    let questions = ask::Questions::at(dir.path().join("questions"));
12688                    let mut prerequisite = task();
12689                    prerequisite.id = "20261013-193611-ca5b".into();
12690                    prerequisite.start("existing-run".into());
12691                    queue.put(&mut prerequisite).unwrap();
12692                    let mut waiting = task();
12693                    waiting.id = "20261013-202849-ee37".into();
12694                    if held {
12695                        waiting.hold_machine(Some("waiting for separate consent".into()));
12696                    }
12697                    queue.put(&mut waiting).unwrap();
12698                    let reason = "Deleting saved data requires separate owner consent";
12699                    crate::conduct::apply(
12700                        &queue,
12701                        &questions,
12702                        &crate::conduct::Verdict {
12703                            decisions: vec![crate::conduct::Decision {
12704                                id: waiting.id.clone(),
12705                                blocked_by: vec![reference.into()],
12706                                question: question.then(|| "May the saved data be deleted?".into()),
12707                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12708                                reason: Some(reason.into()),
12709                                ..crate::conduct::Decision::default()
12710                            }],
12711                        },
12712                    )
12713                    .unwrap();
12714                    let before = queue.get(&waiting.id).unwrap();
12715                    if question {
12716                        assert_eq!(before.status, TaskStatus::Blocked);
12717                        let q = questions.get(&before.blocked_by[0]).unwrap();
12718                        assert_eq!(q.summary, "May the saved data be deleted?");
12719                        assert!(q.status.open());
12720                    } else {
12721                        assert_eq!(before.status, TaskStatus::Held);
12722                        let recorded_reason = before.hold_reason.as_deref().unwrap();
12723                        assert!(recorded_reason.starts_with(reason));
12724                        if held {
12725                            assert!(recorded_reason.contains("waiting for separate consent"));
12726                        }
12727                    }
12728                    prerequisite.succeed(CompletionContext::new(
12729                        CompletionActor::DaemonSettle,
12730                        None,
12731                        dir.path(),
12732                        &prerequisite,
12733                    ));
12734                    queue.put(&mut prerequisite).unwrap();
12735                    resolve_blockers(&queue, &questions);
12736                    let after = queue.get(&waiting.id).unwrap();
12737                    assert_eq!(after.status, before.status);
12738                    assert_eq!(after.blocked_by, before.blocked_by);
12739                    assert_eq!(after.hold_reason, before.hold_reason);
12740                    assert_eq!(after.instruction, waiting.instruction);
12741                    if question {
12742                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12743                    }
12744                    assert!(
12745                        queue.next_runnable().is_none(),
12746                        "dependency completion is not consent"
12747                    );
12748                }
12749            }
12750        }
12751    }
12752
12753    #[test]
12754    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12755        let dir = tempfile::tempdir().unwrap();
12756        let queue = Queue::at(dir.path().join("queue"));
12757        let questions = ask::Questions::at(dir.path().join("questions"));
12758
12759        let mut dep = task();
12760        dep.id = "20260101-000001-dep0".to_owned();
12761        dep.succeed(CompletionContext::new(
12762            CompletionActor::DaemonSettle,
12763            None,
12764            dir.path(),
12765            &dep,
12766        ));
12767        queue.put(&mut dep).unwrap();
12768
12769        let mut still_going = task();
12770        still_going.id = "20260101-000002-dep1".to_owned();
12771        queue.put(&mut still_going).unwrap();
12772
12773        let mut blocked = task();
12774        blocked.id = "20260101-000003-main".to_owned();
12775        blocked.block(
12776            vec![dep.id.clone(), still_going.id.clone()],
12777            Some("waits on both".to_owned()),
12778        );
12779        queue.put(&mut blocked).unwrap();
12780
12781        resolve_blockers(&queue, &questions);
12782
12783        let after = queue.get(&blocked.id).unwrap();
12784        assert_eq!(
12785            after.status,
12786            TaskStatus::Blocked,
12787            "one dependency is still outstanding"
12788        );
12789        assert_eq!(after.blocked_by, [still_going.id.clone()]);
12790    }
12791
12792    #[test]
12793    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12794        let dir = tempfile::tempdir().unwrap();
12795        let queue = Queue::at(dir.path().join("queue"));
12796        let questions = ask::Questions::at(dir.path().join("questions"));
12797
12798        let mut q = crate::ask::Question::new(
12799            "20260101-000001-main".to_owned(),
12800            crate::conduct::NODE.to_owned(),
12801            "conduct".to_owned(),
12802            "Which backend?".to_owned(),
12803            String::new(),
12804            Vec::new(),
12805        );
12806        questions.put(&mut q).unwrap();
12807        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12808            .unwrap();
12809        questions.put(&mut q).unwrap();
12810
12811        let mut blocked = task();
12812        blocked.id = "20260101-000001-main".to_owned();
12813        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12814        queue.put(&mut blocked).unwrap();
12815
12816        resolve_blockers(&queue, &questions);
12817
12818        let after = queue.get(&blocked.id).unwrap();
12819        assert_eq!(
12820            after.status,
12821            TaskStatus::Queued,
12822            "the only blocker resolved"
12823        );
12824        assert_eq!(after.answers.len(), 1);
12825        assert_eq!(after.answers[0].question, "Which backend?");
12826        assert_eq!(after.answers[0].answer, "SQLite");
12827
12828        // And the run this task starts next is told about it.
12829        let instruction = instruction_for(&after);
12830        assert!(instruction.contains("Which backend?"));
12831        assert!(instruction.contains("SQLite"));
12832    }
12833
12834    #[test]
12835    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12836        let dir = tempfile::tempdir().unwrap();
12837        let queue = Queue::at(dir.path().join("queue"));
12838        let questions = ask::Questions::at(dir.path().join("questions"));
12839
12840        let mut q = crate::ask::Question::new(
12841            "20260101-000001-main".to_owned(),
12842            crate::conduct::NODE.to_owned(),
12843            "conduct".to_owned(),
12844            "Is the setup done?".to_owned(),
12845            String::new(),
12846            Vec::new(),
12847        );
12848        q.abandon("no answer within 60s of asking");
12849        questions.put(&mut q).unwrap();
12850
12851        let mut blocked = task();
12852        blocked.id = "20260101-000001-main".to_owned();
12853        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12854        queue.put(&mut blocked).unwrap();
12855
12856        resolve_blockers(&queue, &questions);
12857
12858        let after = queue.get(&blocked.id).unwrap();
12859        assert_eq!(
12860            after.status,
12861            TaskStatus::Held,
12862            "never left blocked on nothing"
12863        );
12864        assert!(!after.operator_held(), "a machine hold, for triage");
12865        assert!(
12866            after
12867                .hold_reason
12868                .as_deref()
12869                .unwrap_or_default()
12870                .contains("went unanswered")
12871        );
12872    }
12873
12874    #[test]
12875    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12876        // Reproduces the reported bug (task 3958): a task held out of
12877        // attempts, blocked on a `crate::conduct` follow-up question, must
12878        // come back `held` once that question is answered - never `queued`,
12879        // whatever the answer said - or it silently re-enters the
12880        // competition queue with its attempts already exhausted.
12881        let dir = tempfile::tempdir().unwrap();
12882        let queue = Queue::at(dir.path().join("queue"));
12883        let questions = ask::Questions::at(dir.path().join("questions"));
12884
12885        let mut q = crate::ask::Question::new(
12886            "20260101-000001-main".to_owned(),
12887            crate::conduct::NODE.to_owned(),
12888            "conduct".to_owned(),
12889            "How should this be handled?".to_owned(),
12890            String::new(),
12891            Vec::new(),
12892        );
12893        questions.put(&mut q).unwrap();
12894        q.answer(crate::ask::Answer::Text(
12895            "leave it held, a human will look at it later".to_owned(),
12896        ))
12897        .unwrap();
12898        questions.put(&mut q).unwrap();
12899
12900        let mut held = task();
12901        held.id = "20260101-000001-main".to_owned();
12902        held.hold_machine(Some("out of attempts".to_owned()));
12903        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12904        queue.put(&mut held).unwrap();
12905
12906        resolve_blockers(&queue, &questions);
12907
12908        let after = queue.get(&held.id).unwrap();
12909        assert_eq!(after.status, TaskStatus::Held);
12910        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12911        assert_eq!(
12912            after.answers[0].answer,
12913            "leave it held, a human will look at it later"
12914        );
12915    }
12916
12917    #[test]
12918    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
12919        let dir = tempfile::tempdir().unwrap();
12920        let queue = Queue::at(dir.path().join("queue"));
12921        let questions = ask::Questions::at(dir.path().join("questions"));
12922        let mut dep = task();
12923        dep.id = "20260101-000001-gone".to_owned();
12924        queue.put(&mut dep).unwrap();
12925        let mut blocked = task();
12926        blocked.id = "20260101-000003-main".to_owned();
12927        blocked.block(vec![dep.id.clone()], None);
12928        queue.put(&mut blocked).unwrap();
12929
12930        // Claimed, so `remove` cannot rewrite it and the resolver must.
12931        let claim = queue.claim(&blocked.id).unwrap();
12932        queue.remove(&dep.id, false, &questions).unwrap();
12933        drop(claim);
12934        resolve_blockers(&queue, &questions);
12935
12936        let after = queue.get(&blocked.id).unwrap();
12937        assert_eq!(after.status, TaskStatus::Queued);
12938        assert!(after.blocked_by.is_empty());
12939    }
12940
12941    #[test]
12942    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12943        // Reproduces the reported bug: a task blocked on a task id that was
12944        // removed (`magi task rm`, or deleted by hand) can never see that id
12945        // reach `Done`, so the ordinary per-id loop has nothing to notice and
12946        // would otherwise leave the task `blocked` forever with no way for an
12947        // operator to find out why.
12948        let dir = tempfile::tempdir().unwrap();
12949        let queue = Queue::at(dir.path().join("queue"));
12950        let questions = ask::Questions::at(dir.path().join("questions"));
12951
12952        let mut still_going = task();
12953        still_going.id = "20260101-000002-dep1".to_owned();
12954        queue.put(&mut still_going).unwrap();
12955
12956        let mut blocked = task();
12957        blocked.id = "20260101-000003-main".to_owned();
12958        blocked.block(
12959            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12960            Some("waits on both".to_owned()),
12961        );
12962        queue.put(&mut blocked).unwrap();
12963
12964        resolve_blockers(&queue, &questions);
12965
12966        let after = queue.get(&blocked.id).unwrap();
12967        assert_eq!(
12968            after.status,
12969            TaskStatus::Held,
12970            "a missing dependency must not leave the task blocked forever"
12971        );
12972        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12973        assert!(after.blocked_by.is_empty());
12974        let reason = after.hold_reason.as_deref().unwrap_or_default();
12975        assert!(
12976            reason.contains("20260101-000001-gone"),
12977            "the missing id must be named so an operator can tell what happened: {reason}"
12978        );
12979        assert!(
12980            reason.contains(&still_going.id),
12981            "the still-valid dependency must not silently vanish from the record: {reason}"
12982        );
12983    }
12984
12985    #[test]
12986    fn instruction_for_is_unchanged_without_any_answers() {
12987        let t = task();
12988        assert_eq!(instruction_for(&t), t.instruction);
12989    }
12990
12991    #[test]
12992    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12993        let dir = tempfile::tempdir().unwrap();
12994        let q = Queue::at(dir.path().join("queue"));
12995        let src = dir.path().join("shot.png");
12996        std::fs::write(&src, "x").unwrap();
12997        let mut t = task();
12998        q.attach(&mut t, &[src]).unwrap();
12999        let paths = task_attachments(&q, &t).unwrap();
13000        assert_eq!(paths.len(), 1);
13001        assert!(paths[0].is_absolute() && paths[0].is_file());
13002        std::fs::remove_file(&paths[0]).unwrap();
13003        let err = task_attachments(&q, &t).unwrap_err().to_string();
13004        assert!(err.contains("shot.png"), "{err}");
13005    }
13006
13007    #[tokio::test]
13008    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
13009        let dir = tempfile::tempdir().unwrap();
13010        let queue_path = dir.path().join("queue");
13011        let queue = Queue::at(queue_path.clone());
13012        let mut t = task();
13013        t.source = Source::Agent {
13014            run: "originating-chat".into(),
13015            node: crate::queue::CHAT_NODE.into(),
13016        };
13017        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
13018            stage: "config-fetch",
13019            target: "origin/main".into(),
13020        });
13021        record_config_failure(&mut t, &fetch);
13022        t.hold_machine(Some(format!("{fetch:#}")));
13023        let fetch_key = t.chat_notice_due().unwrap();
13024        t.chat_notices.push(fetch_key.clone());
13025        queue.put(&mut t).unwrap();
13026
13027        let queue = Queue::at(queue_path);
13028        let mut t = queue.get(&t.id).unwrap();
13029        let a = dir.path().join("a.toml");
13030        let b = dir.path().join("b.toml");
13031        for (path, text, new_cause) in [
13032            (&a, "[graph", true),
13033            (&a, "[verify", false),
13034            (&a, "[graph]\nimplementers = 'invalid-type'", true),
13035            (&b, "[graph]\nimplementers = 'invalid-type'", true),
13036        ] {
13037            t.release_operator("test", None);
13038            std::fs::write(path, text).unwrap();
13039            let error = Config::discover_fetched(dir.path(), Some(path))
13040                .await
13041                .unwrap_err();
13042            record_config_failure(&mut t, &error);
13043            t.hold_machine(Some(format!("{error:#}")));
13044            let due = t.chat_notice_due();
13045            assert_eq!(due.is_some(), new_cause, "{error:#}");
13046            if let Some(key) = due {
13047                assert_ne!(key, fetch_key);
13048                t.chat_notices.push(key);
13049            }
13050        }
13051        t.succeed(CompletionContext::new(
13052            CompletionActor::DaemonSettle,
13053            None,
13054            dir.path(),
13055            &t,
13056        ));
13057        assert_eq!(
13058            t.chat_notice_due(),
13059            Some(format!(
13060                "done:{}",
13061                t.completion_history.last().unwrap().occurrence
13062            ))
13063        );
13064    }
13065
13066    #[test]
13067    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
13068        let dir = tempfile::tempdir().unwrap();
13069        let queue_path = dir.path().join("queue");
13070        let queue = Queue::at(queue_path.clone());
13071        let mut t = task();
13072        t.source = crate::queue::Source::Agent {
13073            run: "originating-chat".into(),
13074            node: crate::queue::CHAT_NODE.into(),
13075        };
13076        let a = dir.path().join("a.png");
13077        let b = dir.path().join("b.png");
13078        std::fs::write(&a, "a").unwrap();
13079        std::fs::write(&b, "b").unwrap();
13080        queue.attach(&mut t, &[a, b]).unwrap();
13081        let paths = task_attachments(&queue, &t).unwrap();
13082        for path in &paths {
13083            std::fs::remove_file(path).unwrap();
13084        }
13085        let missing = task_attachments(&queue, &t).unwrap_err();
13086        t.attempts += 1;
13087        let reason = missing.to_string();
13088        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13089        let first = t.chat_notice_due().expect("first attachment notice");
13090        t.chat_notices.push(first.clone());
13091        queue.put(&mut t).unwrap();
13092
13093        let queue = Queue::at(queue_path.clone());
13094        let mut t = queue.get(&t.id).unwrap();
13095        assert!(t.chat_notice_due().is_none(), "restart does not replay");
13096        t.release_operator("test", None);
13097        t.attempts += 1;
13098        let missing = task_attachments(&queue, &t).unwrap_err();
13099        t.fail_startup_target(
13100            "startup-attachments",
13101            missing.name,
13102            "same missing attachment with regenerated wording",
13103            1,
13104        );
13105        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
13106
13107        std::fs::write(&paths[0], "restored").unwrap();
13108        t.release_operator("test", None);
13109        t.attempts += 1;
13110        let missing = task_attachments(&queue, &t).unwrap_err();
13111        let reason = missing.to_string();
13112        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13113        let second = t
13114            .chat_notice_due()
13115            .expect("different attachment must notify");
13116        assert_ne!(first, second);
13117        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
13118    }
13119
13120    #[test]
13121    fn resumed_instruction_is_unchanged_without_any_answers() {
13122        let t = task();
13123        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
13124    }
13125
13126    #[test]
13127    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
13128        let mut t = task();
13129        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13130        // The run's own instruction on disk predates the answer: it is the
13131        // plain original text `Runner::start` saved before the operator was
13132        // ever asked anything.
13133        let old = t.instruction.clone();
13134
13135        let refreshed = resumed_instruction(&old, &t);
13136        assert!(refreshed.starts_with(&old), "the original text is kept");
13137        assert!(refreshed.contains("Which backend?"));
13138        assert!(refreshed.contains("SQLite"));
13139    }
13140
13141    #[test]
13142    fn resumed_instruction_keeps_an_original_answers_heading() {
13143        let mut t = task();
13144        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
13145        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13146
13147        let refreshed = resumed_instruction(&t.instruction, &t);
13148
13149        assert!(
13150            refreshed.starts_with(&t.instruction),
13151            "an answers heading in the original instruction is not the appended block"
13152        );
13153        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
13154        assert!(refreshed.contains("Which backend?"));
13155        assert!(refreshed.contains("SQLite"));
13156
13157        let repeated = resumed_instruction(&refreshed, &t);
13158        assert_eq!(
13159            repeated, refreshed,
13160            "only the final appended block is refreshed"
13161        );
13162    }
13163
13164    #[test]
13165    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
13166        let mut t = task();
13167        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13168
13169        // A first resume appends the block; a second resume of the same run,
13170        // with no new answer in between, must reproduce exactly the same
13171        // text rather than appending the block a second time.
13172        let once = resumed_instruction(&t.instruction, &t);
13173        let twice = resumed_instruction(&once, &t);
13174        assert_eq!(once, twice);
13175        assert_eq!(once.matches("Which backend?").count(), 1);
13176
13177        // A later answer replaces the block wholesale rather than growing it.
13178        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
13179        let refreshed = resumed_instruction(&once, &t);
13180        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
13181        assert!(refreshed.contains("Which backend?"));
13182        assert!(refreshed.contains("Which cache?"));
13183    }
13184
13185    #[test]
13186    fn prepare_instruction_covers_all_three_starters() {
13187        let mut t = task();
13188        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13189
13190        // Start: a fresh run gets the task text plus every answer so far —
13191        // exactly `instruction_for`.
13192        assert_eq!(
13193            prepare_instruction(&Starter::Start, None, &t),
13194            Some(instruction_for(&t))
13195        );
13196
13197        // Resume: the run's prior instruction is refreshed with the answer,
13198        // not discarded and not left stale.
13199        let old = t.instruction.clone();
13200        assert_eq!(
13201            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
13202            Some(resumed_instruction(&old, &t))
13203        );
13204
13205        // Review: a review-only pass builds its own instruction from the
13206        // branch's history in `crate::graph`, with no task statement at all -
13207        // this boundary must leave it alone.
13208        assert_eq!(
13209            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
13210            None
13211        );
13212    }
13213
13214    #[test]
13215    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
13216        assert_eq!(
13217            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
13218            Starter::Review("magi/eba2/A".to_owned())
13219        );
13220    }
13221
13222    #[test]
13223    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
13224        assert_eq!(
13225            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
13226            Starter::Start,
13227            "a vanished review branch must not fall back to resuming the old run either"
13228        );
13229    }
13230
13231    #[test]
13232    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
13233        let mut t = task();
13234        t.start("old-run".to_owned());
13235        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
13236        t.release();
13237        let branch = t.review_branch.take();
13238        assert_eq!(
13239            choose_starter(branch.as_deref(), true, Some("old-run")),
13240            Starter::Review("magi/eba2/A".to_owned()),
13241            "a review wins over resuming the old run"
13242        );
13243    }
13244
13245    #[test]
13246    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
13247        assert_eq!(
13248            choose_starter(None, false, Some("some-run")),
13249            Starter::Resume("some-run".to_owned())
13250        );
13251        assert_eq!(choose_starter(None, false, None), Starter::Start);
13252    }
13253
13254    #[test]
13255    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
13256        let mut released = task();
13257        released.start("stalled-run".to_owned());
13258        released.requeue();
13259        let unfinished = (!released.fresh_start)
13260            .then(|| Some("stalled-run".to_owned()))
13261            .flatten();
13262        assert_eq!(
13263            choose_starter(None, false, unfinished.as_deref()),
13264            Starter::Start,
13265            "release keeps run history but must not resume it"
13266        );
13267        assert_eq!(released.runs, ["stalled-run"]);
13268    }
13269
13270    #[test]
13271    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
13272        let dir = tempfile::tempdir().unwrap();
13273        let queue = Queue::at(dir.path().join("queue"));
13274        let mut state = run_state(RunStatus::Blocked);
13275        state.merge_decision = Some(crate::merge_decision::Decision {
13276            question: "hold-inquiry".into(),
13277            target: crate::merge_decision::Target {
13278                pr: "https://example.test/pull/1".into(),
13279                head: "reviewed-head".into(),
13280                language: "en".into(),
13281            },
13282            choice: land::HOLD.into(),
13283            closed: false,
13284            replacement_run: None,
13285            replacement_pr: None,
13286        });
13287        let mut t = task();
13288        t.start(state.id.clone());
13289        settle_and_diagnose(
13290            &mut t,
13291            Verdict {
13292                status: RunStatus::Blocked,
13293                left_pr: true,
13294                quota_hit: false,
13295                parked: false,
13296                no_viable_candidates: false,
13297            },
13298            "held",
13299            2,
13300            &state,
13301        );
13302        queue.put(&mut t).unwrap();
13303        t.release_operator("chat", None);
13304        t.edit("revised".into(), "revised instruction".into())
13305            .unwrap();
13306        queue.put(&mut t).unwrap();
13307        drop(state);
13308        assert_eq!(
13309            queue
13310                .get(&t.id)
13311                .unwrap()
13312                .decision_effects
13313                .get("hold-inquiry"),
13314            Some(&format!("decision: {}", land::HOLD))
13315        );
13316    }
13317
13318    fn stopped_public_run(status: RunStatus) -> RunState {
13319        let mut state = run_state(status);
13320        state.driver_exited = true;
13321        state.config.graph.land = true;
13322        state.config.graph.review_rounds = 1;
13323        state.reviews = vec![review_round(1)];
13324        state.merge = Some(crate::run::MergeOutcome {
13325            mode: MergeMode::Pr,
13326            ok: false,
13327            detail: "landing stopped".into(),
13328            empty: false,
13329        });
13330        state.pr = Some(crate::run::PrRecord {
13331            url: "https://example.test/pull/1".into(),
13332            number: 1,
13333            state: "open".into(),
13334            checks: "red".into(),
13335            round: 1,
13336            rounds: 1,
13337            red_at_merge: Vec::new(),
13338        });
13339        state
13340    }
13341
13342    #[test]
13343    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13344        for status in [RunStatus::Blocked, RunStatus::Gating] {
13345            let home = tempfile::tempdir().unwrap();
13346            let mut state = stopped_public_run(status);
13347            state.save_under(home.path()).unwrap();
13348            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13349            assert!(!exhausted_review_budget(&state));
13350            let mut task = held_task_with(&state.id);
13351            task.release();
13352            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13353            assert_eq!(
13354                choose_starter(None, false, unfinished.as_deref()),
13355                Starter::Resume(state.id.clone())
13356            );
13357            let question = action_question(&state.id, resume_action(&state.id));
13358            assert_eq!(
13359                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13360                    state.clone()
13361                )),
13362                ActionDecision::Resume(state.id.clone())
13363            );
13364            // The control-plane command uses this same preflight before pinning.
13365            assert_eq!(
13366                crate::resume::validate(home.path(), &state.id).unwrap().id,
13367                state.id
13368            );
13369            let queue = Queue::at(home.path().join("queue"));
13370            let mut controlled = Task::new(
13371                "resume land".into(),
13372                state.instruction.clone(),
13373                state.repo.clone(),
13374                Source::Agent {
13375                    run: "talk".into(),
13376                    node: crate::queue::CHAT_NODE.into(),
13377                },
13378            );
13379            controlled.runs.push(state.id.clone());
13380            controlled.hold_machine(Some("land stopped".into()));
13381            queue.put(&mut controlled).unwrap();
13382            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13383            assert_eq!(resumed.status, TaskStatus::Queued);
13384            assert_eq!(
13385                resumed.resume_override.unwrap().pinned_run,
13386                Some(state.id.clone())
13387            );
13388            assert_eq!(resumed.attempts, 0);
13389        }
13390    }
13391
13392    #[test]
13393    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13394        for review_rounds in [0, 1] {
13395            let home = tempfile::tempdir().unwrap();
13396            let mut state = run_state(RunStatus::Blocked);
13397            state.config.graph.review_rounds = review_rounds;
13398            if review_rounds > 0 {
13399                let mut review = review_round(1);
13400                review.clean = true;
13401                state.reviews = vec![review];
13402            }
13403            state.gate_ran = true;
13404            state.gate = vec![crate::run::CommandOutcome {
13405                command: "verify".into(),
13406                code: Some(1),
13407                output_tail: "gate failed after repair budget exhausted".into(),
13408                duration_ms: 0,
13409                resource_blocked: false,
13410                ..Default::default()
13411            }];
13412            state.save_under(home.path()).unwrap();
13413            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13414            assert!(exhausted_review_budget(&state));
13415            let mut task = held_task_with(&state.id);
13416            task.release();
13417            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13418            let question = action_question(&state.id, resume_action(&state.id));
13419            assert_ne!(
13420                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13421                    state.clone()
13422                )),
13423                ActionDecision::Resume(state.id.clone())
13424            );
13425            let error = crate::resume::validate(home.path(), &state.id)
13426                .unwrap_err()
13427                .to_string();
13428            assert!(!error.contains("review budget exhausted"), "{error}");
13429            assert!(
13430                error.contains(if review_rounds == 0 {
13431                    "review is disabled"
13432                } else {
13433                    "gate already ran"
13434                }),
13435                "{error}"
13436            );
13437
13438            // An unexecuted gate still has work to do with or without reviews.
13439            state.gate_ran = false;
13440            state.gate.clear();
13441            assert!(!exhausted_review_budget(&state));
13442            assert_eq!(
13443                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13444                Some(state.id)
13445            );
13446        }
13447    }
13448
13449    #[test]
13450    fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
13451        let home = tempfile::tempdir().unwrap();
13452        let mut state = run_state(RunStatus::Blocked);
13453        state.config.graph.review_rounds = 1;
13454        let mut unresolved = review_round(1);
13455        unresolved.blocking = 1;
13456        unresolved.e2e.push(crate::run::CommandOutcome {
13457            command: "verify".into(),
13458            code: Some(1),
13459            output_tail: "previous verification failed".into(),
13460            duration_ms: 0,
13461            resource_blocked: false,
13462            ..Default::default()
13463        });
13464        state.reviews.push(unresolved);
13465        state.base_sync = Some(crate::run::BaseSync {
13466            tip: "base".into(),
13467            behind: 1,
13468            attempts: 0,
13469            conflict: None,
13470            already_in: None,
13471        });
13472        state.reserve_base_operation("winner", "base");
13473        state.resource_block = Some(crate::run::ResourceBlock {
13474            cause: crate::run::ResourceBlockCause::Other,
13475            node: "rebase".into(),
13476            kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
13477            detail: "recording exec failed".into(),
13478            at: jiff::Timestamp::now(),
13479        });
13480        state.save_under(home.path()).unwrap();
13481        assert_eq!(
13482            crate::resume::validate(home.path(), &state.id).unwrap().id,
13483            state.id
13484        );
13485        assert_eq!(
13486            crate::repair_budget::legacy::classify(&state, "winner", "base").class,
13487            crate::repair_budget::legacy::Class::SequencerInfrastructure
13488        );
13489        state.finish_base_operation(None);
13490        state.save_under(home.path()).unwrap();
13491        assert!(crate::resume::validate(home.path(), &state.id).is_err());
13492    }
13493
13494    #[test]
13495    fn resource_blocked_verification_resumes_the_same_run() {
13496        for (kind, stage) in [
13497            ("cache", "clean"),
13498            ("coordination", "clean"),
13499            ("cache", "review-e2e"),
13500            ("coordination", "no-reviews"),
13501            ("coordination", "handoff"),
13502        ] {
13503            let home = tempfile::tempdir().unwrap();
13504            let mut state = run_state(RunStatus::Blocked);
13505            state.config.graph.review_rounds = 1;
13506            let mut review = review_round(1);
13507            review.clean = true;
13508            state.reviews = vec![review];
13509            if stage == "review-e2e" {
13510                let review = &mut state.reviews[0];
13511                review.clean = false;
13512                review.blocking = 1;
13513                review.e2e = vec![crate::run::CommandOutcome {
13514                    command: "verify".into(),
13515                    code: None,
13516                    output_tail: "resource wait expired".into(),
13517                    duration_ms: 0,
13518                    resource_blocked: true,
13519                    ..Default::default()
13520                }];
13521            } else if stage == "no-reviews" {
13522                state.config.graph.review_rounds = 0;
13523                state.reviews.clear();
13524            } else if stage == "handoff" {
13525                // A completed final verification can hand off to the gate
13526                // even when the review still carries contested findings.
13527                let review = &mut state.reviews[0];
13528                review.clean = false;
13529                review.blocking = 1;
13530                review.e2e = vec![crate::run::CommandOutcome {
13531                    command: "verify".into(),
13532                    code: Some(0),
13533                    output_tail: String::new(),
13534                    duration_ms: 0,
13535                    resource_blocked: false,
13536                    ..Default::default()
13537                }];
13538            }
13539            state.gate_ran = false;
13540            state.resource_block = Some(crate::run::ResourceBlock {
13541                cause: crate::run::ResourceBlockCause::Other,
13542                node: if stage == "review-e2e" {
13543                    "review"
13544                } else {
13545                    "gate"
13546                }
13547                .into(),
13548                kind: kind.into(),
13549                detail: "resource wait expired".into(),
13550                at: jiff::Timestamp::now(),
13551            });
13552            state.save_under(home.path()).unwrap();
13553            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13554            assert!(!exhausted_review_budget(&state));
13555            let mut task = held_task_with(&state.id);
13556            task.release();
13557            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13558            assert_eq!(
13559                choose_starter(None, false, unfinished.as_deref()),
13560                Starter::Resume(state.id.clone())
13561            );
13562            let question = action_question(&state.id, resume_action(&state.id));
13563            assert_eq!(
13564                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13565                    state.clone()
13566                )),
13567                ActionDecision::Resume(state.id.clone())
13568            );
13569            assert_eq!(
13570                crate::resume::validate(home.path(), &state.id).unwrap().id,
13571                state.id
13572            );
13573            let queue = Queue::at(home.path().join("queue"));
13574            let mut controlled = Task::new(
13575                "resume verification".into(),
13576                state.instruction.clone(),
13577                state.repo.clone(),
13578                Source::Agent {
13579                    run: "talk".into(),
13580                    node: crate::queue::CHAT_NODE.into(),
13581                },
13582            );
13583            controlled.runs.push(state.id.clone());
13584            controlled.hold_machine(Some("verification resource unavailable".into()));
13585            queue.put(&mut controlled).unwrap();
13586            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13587            assert_eq!(resumed.status, TaskStatus::Queued);
13588            assert_eq!(
13589                resumed.resume_override.unwrap().pinned_run,
13590                Some(state.id.clone())
13591            );
13592            assert_eq!(resumed.attempts, 0);
13593
13594            // A genuinely unresolved final review still exhausts the budget.
13595            state.config.graph.review_rounds = 1;
13596            let mut unresolved = review_round(1);
13597            unresolved.blocking = 1;
13598            state.reviews = vec![unresolved];
13599            state.resource_block = None;
13600            state.save_under(home.path()).unwrap();
13601            assert!(exhausted_review_budget(&state));
13602            assert!(crate::resume::validate(home.path(), &state.id).is_err());
13603        }
13604    }
13605
13606    #[tokio::test]
13607    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13608        if !crate::standalone_test(
13609            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13610        ) {
13611            return;
13612        }
13613        let home = tempfile::tempdir().unwrap();
13614        let mut owner = stopped_public_run(RunStatus::Blocked);
13615        owner.save_under(home.path()).unwrap();
13616        let history = vec![owner.id.clone()];
13617        let repo = owner.repo.clone();
13618        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13619        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13620        let initial =
13621            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13622        assert!(
13623            initial.is_pending(),
13624            "a busy record must not hold or resume the task"
13625        );
13626        owner.retired_to = Some("20260101-000001-bbbb".into());
13627        owner.save_under(home.path()).unwrap();
13628        drop(lock);
13629        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13630            .await
13631            .expect("ownership lock released")
13632            .expect("read settled owner");
13633        assert!(
13634            result.is_none(),
13635            "the retired owner must not be resumed from a stale read"
13636        );
13637    }
13638
13639    #[tokio::test]
13640    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13641        if !crate::standalone_test(
13642            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13643        ) {
13644            return;
13645        }
13646        let home = tempfile::tempdir().unwrap();
13647        let mut owner = stopped_public_run(RunStatus::Blocked);
13648        let repo = tempfile::tempdir().unwrap();
13649        crate::git::git(repo.path(), &["init"]).await.unwrap();
13650        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13651        owner.id = "20260101-000000-aaaa".into();
13652        owner.save_under(home.path()).unwrap();
13653        let mut successor = run_state(RunStatus::Blocked);
13654        successor.id = "20260101-000001-bbbb".into();
13655        successor.save_under(home.path()).unwrap();
13656        let runs = vec![owner.id.clone(), successor.id.clone()];
13657        assert_eq!(
13658            public_resume_owner(home.path(), &runs, &owner.repo)
13659                .await
13660                .unwrap()
13661                .unwrap()
13662                .id,
13663            owner.id
13664        );
13665        let subdir = owner.repo.join("nested");
13666        std::fs::create_dir(&subdir).unwrap();
13667        assert_eq!(
13668            public_resume_owner(home.path(), &runs, &subdir)
13669                .await
13670                .unwrap()
13671                .unwrap()
13672                .id,
13673            owner.id
13674        );
13675        #[cfg(unix)]
13676        {
13677            let alias = home.path().join("repo-alias");
13678            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13679            assert_eq!(
13680                public_resume_owner(home.path(), &runs, &alias.join("nested"))
13681                    .await
13682                    .unwrap()
13683                    .unwrap()
13684                    .id,
13685                owner.id
13686            );
13687        }
13688        let different = tempfile::tempdir().unwrap();
13689        crate::git::git(different.path(), &["init"]).await.unwrap();
13690        assert!(
13691            public_resume_owner(home.path(), &runs, different.path())
13692                .await
13693                .is_err()
13694        );
13695        std::fs::remove_file(
13696            home.path()
13697                .join("runs")
13698                .join(&successor.id)
13699                .join("run.json"),
13700        )
13701        .unwrap();
13702        assert!(
13703            public_resume_owner(home.path(), &runs, &owner.repo)
13704                .await
13705                .is_err()
13706        );
13707    }
13708
13709    #[test]
13710    fn an_ordinary_release_keeps_a_resumable_run_available() {
13711        let mut released = task();
13712        released.start("stalled-run".to_owned());
13713        released.release();
13714        let unfinished = (!released.fresh_start)
13715            .then(|| Some("stalled-run".to_owned()))
13716            .flatten();
13717        assert_eq!(
13718            choose_starter(None, false, unfinished.as_deref()),
13719            Starter::Resume("stalled-run".to_owned()),
13720            "manual release must preserve the normal resume path"
13721        );
13722    }
13723
13724    #[test]
13725    fn resume_refusals_explain_admission_without_changing_task_or_run() {
13726        use crate::handover::{ResumeRefusal, resume_refusal_under};
13727        let home = tempfile::tempdir().unwrap();
13728        let mut exhausted = run_state(RunStatus::Blocked);
13729        exhausted.driver_exited = true;
13730        exhausted.config.graph.review_rounds = 3;
13731        exhausted.reviews = (1..=3).map(review_round).collect();
13732        for refusal in [
13733            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13734            ResumeRefusal::Status(RunStatus::Ready),
13735            ResumeRefusal::Released("20261022-000000-aaaa".into()),
13736            ResumeRefusal::Retired("retirement-successor".into()),
13737            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13738        ] {
13739            let mut state = exhausted.clone();
13740            let expected = match refusal {
13741                ResumeRefusal::Status(_) => {
13742                    state.status = RunStatus::Ready;
13743                    "status `ready`"
13744                }
13745                ResumeRefusal::Released(ref target) => {
13746                    state.released_to = Some(target.clone());
13747                    "execution was released"
13748                }
13749                ResumeRefusal::Retired(ref target) => {
13750                    state.retired_to = Some(target.clone());
13751                    "execution was retired"
13752                }
13753                ResumeRefusal::OwnershipTransferred(ref target) => {
13754                    state.pr_taken_over_by = Some(target.clone());
13755                    "PR ownership was transferred"
13756                }
13757                _ => "review budget exhausted (3/3 rounds used)",
13758            };
13759            assert_eq!(
13760                resume_refusal_under(&state, Some(home.path())),
13761                Some(refusal.clone())
13762            );
13763            assert_eq!(
13764                refusal.successor(),
13765                state
13766                    .released_to
13767                    .as_deref()
13768                    .or(state.retired_to.as_deref())
13769                    .or(state.pr_taken_over_by.as_deref())
13770            );
13771            state.save_under(home.path()).unwrap();
13772            let queue = Queue::at(home.path().join("queue"));
13773            let mut task = Task::new(
13774                "retained implementation".into(),
13775                state.instruction.clone(),
13776                state.repo.clone(),
13777                Source::Agent {
13778                    run: "talk".into(),
13779                    node: crate::queue::CHAT_NODE.into(),
13780                },
13781            );
13782            task.runs.push(state.id.clone());
13783            task.hold_machine(Some("stopped".into()));
13784            queue.put(&mut task).unwrap();
13785            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13786            let before_run = serde_json::to_value(&state).unwrap();
13787            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13788                .unwrap_err()
13789                .to_string();
13790            assert!(error.contains(expected), "{error}");
13791            assert!(!error.contains("only a stalled or blocked"), "{error}");
13792            if matches!(refusal, ResumeRefusal::Status(_)) {
13793                assert!(
13794                    error.contains("is final; there is nothing left to resume"),
13795                    "{error}"
13796                );
13797            }
13798            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13799                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13800                assert!(error.contains("review-only successor with a new review budget"));
13801                assert!(error.contains("does not resume this run"));
13802            }
13803            for target in [
13804                &state.released_to,
13805                &state.retired_to,
13806                &state.pr_taken_over_by,
13807            ]
13808            .into_iter()
13809            .flatten()
13810            {
13811                let short = if state.retired_to.as_ref() == Some(target) {
13812                    target.as_str()
13813                } else {
13814                    crate::run::short_of(target)
13815                };
13816                assert!(
13817                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
13818                    "{error}"
13819                );
13820                if short != target {
13821                    assert!(!error.contains(target), "full successor id leaked: {error}");
13822                }
13823            }
13824            assert_eq!(
13825                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13826                before_task
13827            );
13828            assert_eq!(
13829                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13830                    .unwrap(),
13831                before_run
13832            );
13833            let question = action_question(&state.id, resume_action(&state.id));
13834            for phrases in [&PHRASES_EN, &PHRASES_JA] {
13835                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13836                    RunState::load_under(id, home.path())
13837                });
13838                let ActionDecision::Refuse(detail) = decision else {
13839                    panic!(
13840                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13841                        state.id,
13842                        home.path().display()
13843                    );
13844                };
13845                assert!(detail.contains(expected), "{detail}");
13846            }
13847        }
13848        // Preserve predicate ordering, while keeping every recorded destination visible.
13849        exhausted.status = RunStatus::Ready;
13850        exhausted.released_to = Some("released".into());
13851        exhausted.retired_to = Some("retired".into());
13852        exhausted.pr_taken_over_by = Some("owner".into());
13853        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13854        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13855        let detail = reason.diagnostic(&exhausted);
13856        for target in ["released", "retired", "owner"] {
13857            assert!(detail.contains(&format!("magi show {target}")));
13858        }
13859    }
13860
13861    #[test]
13862    fn resume_action_ignores_question_checkpoints_in_another_home() {
13863        crate::run::pin_test_home();
13864        let home = tempfile::tempdir().unwrap();
13865        let mut state = run_state(RunStatus::Blocked);
13866        // The private directory reserves this fixture's identity even while
13867        // other tests write questions into the process-wide store.
13868        state.id = format!(
13869            "resume-context-{}",
13870            home.path().file_name().unwrap().to_str().unwrap()
13871        );
13872        state.driver_exited = true;
13873        state.config.graph.review_rounds = 1;
13874        state.reviews = vec![review_round(1)];
13875        state.save_under(home.path()).unwrap();
13876        let task = held_task_with(&state.id);
13877        let answer = action_question(&state.id, resume_action(&state.id));
13878        let mut checkpoint = approval_question(&state.id);
13879        let foreign = Questions::open();
13880        foreign.put(&mut checkpoint).unwrap();
13881        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13882        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13883            RunState::load_under(id, home.path())
13884        });
13885        let matching: Vec<_> = foreign
13886            .list()
13887            .into_iter()
13888            .filter(|q| q.run == state.id && q.status.open())
13889            .collect();
13890        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13891        assert!(
13892            matches!(decision, ActionDecision::Refuse(_)),
13893            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13894            state.id,
13895            home.path().display(),
13896            crate::run::test_home().display()
13897        );
13898        assert_eq!(
13899            refusal,
13900            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13901        );
13902        let local = Questions::at(home.path().join("questions"));
13903        for status in [
13904            ask::QuestionStatus::Open,
13905            ask::QuestionStatus::Answered,
13906            ask::QuestionStatus::Abandoned,
13907        ] {
13908            let mut question = checkpoint.clone();
13909            match status {
13910                ask::QuestionStatus::Open => {}
13911                ask::QuestionStatus::Answered => {
13912                    question
13913                        .answer(ask::Answer::Choice(question.choices[0].clone()))
13914                        .unwrap();
13915                }
13916                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13917            }
13918            local.put(&mut question).unwrap();
13919            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13920                RunState::load_under(id, home.path())
13921            });
13922            if status.open() {
13923                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13924            } else {
13925                assert!(
13926                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13927                    "status={status:?}, decision={decision:?}"
13928                );
13929            }
13930        }
13931    }
13932
13933    #[test]
13934    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13935        let home = tempfile::tempdir().unwrap();
13936        let mut state = run_state(RunStatus::Stalled);
13937        state.id = format!(
13938            "resume-driver-{}",
13939            home.path().file_name().unwrap().to_str().unwrap()
13940        );
13941        state.driver_claimed = Some(false);
13942        state.save_under(home.path()).unwrap();
13943        let task = held_task_with(&state.id);
13944        let question = action_question(&state.id, resume_action(&state.id));
13945        let decide = || {
13946            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13947                RunState::load_under(id, home.path())
13948            })
13949        };
13950        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13951        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13952        assert_eq!(
13953            decide(),
13954            ActionDecision::Refuse("run already has a live driver".into())
13955        );
13956        drop(lease);
13957        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13958    }
13959
13960    #[test]
13961    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13962        let home = tempfile::tempdir().unwrap();
13963        let mut state = run_state(RunStatus::Blocked);
13964        state.driver_exited = true;
13965        state.config.graph.review_rounds = 1;
13966        state.reviews = vec![review_round(1)];
13967        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13968        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13969            let mut saved = state.clone();
13970            match checkpoint {
13971                "publication" => saved.pr_publication_pending = true,
13972                "approval" => {
13973                    saved.land_approval = Some(crate::run::LandApproval {
13974                        question: "approval".into(),
13975                        head: "head".into(),
13976                    })
13977                }
13978                "armed" => saved.land_armed_head = Some("head".into()),
13979                "landing" => saved.status = RunStatus::Landing,
13980                _ => {
13981                    let mut question = ask::Question::new(
13982                        saved.id.clone(),
13983                        "review".into(),
13984                        "review-1".into(),
13985                        "continue?".into(),
13986                        String::new(),
13987                        vec!["continue".into()],
13988                    );
13989                    ask::Questions::at(home.path().join("questions"))
13990                        .put(&mut question)
13991                        .unwrap();
13992                }
13993            }
13994            saved.save_under(home.path()).unwrap();
13995            assert!(
13996                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13997                "{checkpoint}"
13998            );
13999            assert!(
14000                crate::resume::validate(home.path(), &saved.id).is_ok(),
14001                "{checkpoint}"
14002            );
14003        }
14004    }
14005
14006    #[test]
14007    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
14008        let mut state = run_state(RunStatus::Blocked);
14009        state.config.graph.review_rounds = 3;
14010        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
14011        assert!(exhausted_review_budget(&state));
14012
14013        // One round still unused: resuming can still ask a reviewer something.
14014        state.reviews.pop();
14015        assert!(!exhausted_review_budget(&state));
14016
14017        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
14018        // count: only a `Blocked` run re-enters the review loop on resume.
14019        let mut stalled = run_state(RunStatus::Stalled);
14020        stalled.config.graph.review_rounds = 1;
14021        stalled.reviews = vec![review_round(1)];
14022        assert!(!exhausted_review_budget(&stalled));
14023    }
14024
14025    fn review_round(round: usize) -> crate::run::ReviewRound {
14026        crate::run::ReviewRound {
14027            round,
14028            head: "deadbeef".to_owned(),
14029            verified_head: None,
14030            verified_at: None,
14031            reviews: Vec::new(),
14032            e2e: Vec::new(),
14033            verify_retried: false,
14034            e2e_deferred: false,
14035            e2e_defer_reason: None,
14036            fix: None,
14037            blocking: 0,
14038            answered: 1,
14039            expected: 1,
14040            clean: false,
14041            progressed: true,
14042            vote_split: false,
14043            reconsideration: Vec::new(),
14044            verdict: None,
14045        }
14046    }
14047
14048    #[test]
14049    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
14050        let mut run = RunState::new(
14051            PathBuf::from("/repo"),
14052            "main".to_owned(),
14053            "abc1234def".to_owned(),
14054            "add retries".to_owned(),
14055            Config::default(),
14056        );
14057        run.status = RunStatus::Judging;
14058        run.parked = true;
14059        let mut task = Task::new(
14060            "add retries".to_owned(),
14061            "add retries".to_owned(),
14062            PathBuf::from("/repo"),
14063            crate::queue::Source::Human,
14064        );
14065        task.status = TaskStatus::Failed;
14066        task.runs = vec![run.id.clone()];
14067        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
14068        assert!(with(&task, &run), "parked after judging is the case");
14069        let mut parked_task = task.clone();
14070        parked_task.status = TaskStatus::Parked;
14071        assert!(with(&parked_task, &run), "the Parked status is the case");
14072
14073        let mut not_parked = run.clone();
14074        not_parked.parked = false;
14075        not_parked.status = RunStatus::Stalled;
14076        assert!(!with(&task, &not_parked), "a stall is the conductor's");
14077
14078        let mut fresh = task.clone();
14079        fresh.fresh_start = true;
14080        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
14081
14082        let mut review = task.clone();
14083        review.review_branch = Some("magi/x/A".to_owned());
14084        assert!(!with(&review, &run), "review is ranked before resume");
14085
14086        let mut held = task.clone();
14087        held.status = TaskStatus::Held;
14088        assert!(!with(&held, &run), "a hold stays visible to the conductor");
14089
14090        let mut released = run.clone();
14091        released.released_to = Some("20260901-000000-new1".to_owned());
14092        assert!(!with(&task, &released), "nothing left to resume into");
14093
14094        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
14095            "unreadable"
14096        )));
14097    }
14098
14099    #[test]
14100    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
14101        let mut released = RunState::new(
14102            PathBuf::from("/repo"),
14103            "main".to_owned(),
14104            "abc1234def".to_owned(),
14105            "add retries".to_owned(),
14106            Config::default(),
14107        );
14108        released.status = RunStatus::Blocked;
14109        assert_eq!(
14110            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14111            Some(released.id.clone())
14112        );
14113        released.released_to = Some("20260901-000000-new1".to_owned());
14114        assert_eq!(
14115            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14116            None,
14117            "there is nothing left to resume it into"
14118        );
14119    }
14120
14121    #[test]
14122    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
14123        // Mirrors the failure this exists to close: a task's last run ended
14124        // `Blocked` with the review budget spent, `crate::conduct` chose
14125        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
14126        // evidence), and without this check `attempt` would go on treating
14127        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
14128        // review loop iterates zero times over an already-spent budget, so
14129        // the resumed run settles right back to `Blocked` having asked nobody
14130        // anything, and `Requeue`'s promised fresh competition never happens.
14131        let mut exhausted = RunState::new(
14132            PathBuf::from("/repo"),
14133            "main".to_owned(),
14134            "abc1234def".to_owned(),
14135            "add retries".to_owned(),
14136            Config::default(),
14137        );
14138        exhausted.status = RunStatus::Blocked;
14139        exhausted.config.graph.review_rounds = 1;
14140        exhausted.reviews = vec![review_round(1)];
14141
14142        assert_eq!(
14143            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
14144            None,
14145            "an exhausted `Blocked` run must not be offered as resumable"
14146        );
14147
14148        // A `Blocked` run with rounds still unused is genuinely worth
14149        // resuming, and must still be found.
14150        let mut has_budget_left = RunState::new(
14151            PathBuf::from("/repo"),
14152            "main".to_owned(),
14153            "abc1234def".to_owned(),
14154            "add retries".to_owned(),
14155            Config::default(),
14156        );
14157        has_budget_left.status = RunStatus::Blocked;
14158        has_budget_left.config.graph.review_rounds = 3;
14159        has_budget_left.reviews = vec![review_round(1)];
14160
14161        assert_eq!(
14162            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
14163                Ok(has_budget_left.clone())
14164            }),
14165            Some(has_budget_left.id.clone())
14166        );
14167    }
14168
14169    #[test]
14170    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
14171        let mut run = RunState::new(
14172            PathBuf::from("/repo"),
14173            "main".to_owned(),
14174            "abc1234def".to_owned(),
14175            "add retries".to_owned(),
14176            Config::default(),
14177        );
14178        run.status = RunStatus::Blocked;
14179        run.config.graph.review_rounds = 1;
14180        run.reviews = vec![review_round(1)];
14181        run.pr_publication_pending = true;
14182        assert_eq!(
14183            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
14184            Some(run.id.clone()),
14185            "a spent review budget must not turn a failed publication into a re-competition"
14186        );
14187    }
14188
14189    #[test]
14190    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
14191        let mut task = Task::new(
14192            "recover work".into(),
14193            "recover work".into(),
14194            PathBuf::from("/repo"),
14195            crate::queue::Source::Human,
14196        );
14197        let mut history = std::collections::BTreeMap::new();
14198        for index in 0..8 {
14199            let mut run = run_state(RunStatus::Blocked);
14200            run.id = format!("20260101-000000-{index:04}");
14201            run.base_commit = format!("upstream-{index}");
14202            // Seven empty newer attempts must not erase the old recovery owner.
14203            if index > 0 {
14204                run.candidates.clear();
14205            }
14206            task.runs.extend([run.id.clone(), run.id.clone()]);
14207            history.insert(run.id.clone(), run);
14208            task.requeue();
14209        }
14210        let check = |task: &Task, starter: &Starter, limit| {
14211            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
14212        };
14213        assert!(
14214            check(&task, &Starter::Start, 8)
14215                .unwrap()
14216                .contains("8 unretired")
14217        );
14218        assert!(check(&task, &Starter::Start, 9).is_none());
14219        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
14220        task.release_operator("owner", None);
14221        assert_eq!(task.attempts, 0);
14222        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14223        assert!(check(&restored, &Starter::Start, 8).is_some());
14224        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
14225        assert!(check(&restored, &Starter::Start, 0).is_none());
14226    }
14227
14228    #[test]
14229    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
14230        let tmp = tempfile::tempdir().unwrap();
14231        let mut task = Task::new(
14232            "recover selected PR".into(),
14233            "preserve implementation".into(),
14234            tmp.path().join("repo"),
14235            crate::queue::Source::Human,
14236        );
14237        let mut failed = run_state(RunStatus::Failed);
14238        failed.id = "20260101-000000-fail".into();
14239        failed.candidates.clear();
14240        failed.prep_complete = Some(false);
14241        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
14242        failed.startup = Some(crate::run::Startup {
14243            kind: "pr-recovery".into(),
14244            branch: Some("selected-public-head".into()),
14245            stage: "worktree-setup".into(),
14246            complete: false,
14247            failure: Some("setup modified a tracked file and failed".into()),
14248        });
14249        // Setup may fail before a candidate is recorded; its dirty worktree
14250        // still needs protection and consumes the independent retained bound.
14251        let worktree = failed.worktree_root().join("under-review");
14252        std::fs::create_dir_all(&worktree).unwrap();
14253        let retained_edit = worktree.join("implementation");
14254        std::fs::write(&retained_edit, "retained setup edit").unwrap();
14255        task.record_startup_failure(crate::run::StartupFailure {
14256            run: failed.id.clone(),
14257            stage: "worktree-setup".into(),
14258        });
14259        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14260        assert!(task.runs.is_empty() && task.passes.is_empty());
14261        assert_eq!(task.attempts, 0);
14262        let starter = Starter::Review("selected-public-head".into());
14263        assert!(
14264            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
14265                .unwrap()
14266                .contains("1 unretired")
14267        );
14268        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
14269        assert!(
14270            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
14271                .unwrap()
14272                .contains("Cannot verify")
14273        );
14274        // Older or mixed writers can link the same reservation in both lists.
14275        let mut mixed = task.clone();
14276        mixed.runs.push(failed.id.clone());
14277        mixed
14278            .startup_failures
14279            .push(task.startup_failures[0].clone());
14280        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
14281        failed.retired_to = Some("verified-recovery-owner".into());
14282        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
14283        assert!(
14284            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
14285                panic!("resuming the existing owner must not allocate a new attempt")
14286            })
14287            .is_none()
14288        );
14289        assert_eq!(
14290            std::fs::read_to_string(retained_edit).unwrap(),
14291            "retained setup edit"
14292        );
14293        assert!(task.runs.is_empty() && task.passes.is_empty());
14294        assert_eq!(task.attempts, 0);
14295    }
14296
14297    #[test]
14298    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
14299        let mut task = Task::new(
14300            "recover work".into(),
14301            "recover work".into(),
14302            PathBuf::from("/repo"),
14303            crate::queue::Source::Human,
14304        );
14305        let mut run = run_state(RunStatus::Superseded);
14306        run.candidates.clear();
14307        task.runs.push(run.id.clone());
14308        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
14309        run.retired_to = Some("authority".into());
14310        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14311        run.retired_to = None;
14312        run.released_to = Some("authority".into());
14313        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14314        assert!(
14315            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
14316                .unwrap()
14317                .contains("Cannot verify")
14318        );
14319        // Resuming an existing owner needs no new inventory or worktree budget.
14320        assert!(
14321            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
14322                panic!("resume must not load historical attempts")
14323            })
14324            .is_none()
14325        );
14326    }
14327
14328    #[test]
14329    fn retired_resume_requires_a_valid_same_repository_authority() {
14330        let mut source = run_state(RunStatus::Blocked);
14331        let mut empty = run_state(RunStatus::Blocked);
14332        empty.retired_to = Some(source.id.clone());
14333        let runs = vec![source.id.clone(), empty.id.clone()];
14334        let resolve = |source: &RunState, empty: &RunState| {
14335            unfinished_run_with(&runs, "fixture", |id| {
14336                if id == source.id {
14337                    Ok(source.clone())
14338                } else if id == empty.id {
14339                    Ok(empty.clone())
14340                } else {
14341                    bail!("unreadable authority")
14342                }
14343            })
14344        };
14345        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
14346        assert_eq!(
14347            choose_starter(None, false, resolve(&source, &empty).as_deref()),
14348            Starter::Resume(source.id.clone())
14349        );
14350        source.retired_to = Some(empty.id.clone());
14351        assert!(
14352            resolve(&source, &empty).is_none(),
14353            "cycles do not revive obsolete runs"
14354        );
14355        source.retired_to = None;
14356        source.repo = PathBuf::from("/another-repository");
14357        assert!(resolve(&source, &empty).is_none());
14358        source.repo = empty.repo.clone();
14359        source.released_to = Some("later".into());
14360        assert!(resolve(&source, &empty).is_none());
14361        empty.retired_to = Some("unlisted-run".into());
14362        assert!(resolve(&source, &empty).is_none());
14363    }
14364
14365    #[test]
14366    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
14367        // A task whose history holds an *older* run that still looks
14368        // resumable (say, a competition `Runner::review` was started
14369        // alongside after that older run went `Stalled`) and a *newest* run
14370        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
14371        // on this task must mean a fresh competition — falling back to the
14372        // stale, superseded `Stalled` run instead would resurrect history
14373        // nothing asked to revisit and silently defeat the requeue.
14374        let mut older_stalled = RunState::new(
14375            PathBuf::from("/repo"),
14376            "main".to_owned(),
14377            "abc1234def".to_owned(),
14378            "add retries".to_owned(),
14379            Config::default(),
14380        );
14381        older_stalled.status = RunStatus::Stalled;
14382
14383        let mut newest_exhausted = RunState::new(
14384            PathBuf::from("/repo"),
14385            "main".to_owned(),
14386            "abc1234def".to_owned(),
14387            "add retries".to_owned(),
14388            Config::default(),
14389        );
14390        newest_exhausted.status = RunStatus::Blocked;
14391        newest_exhausted.config.graph.review_rounds = 1;
14392        newest_exhausted.reviews = vec![review_round(1)];
14393
14394        assert_eq!(
14395            unfinished_run_with(
14396                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14397                "t",
14398                |_| Ok(newest_exhausted.clone())
14399            ),
14400            None,
14401            "the newest run is exhausted, so nothing here is worth resuming - \
14402             least of all the older, already-superseded run"
14403        );
14404    }
14405
14406    #[test]
14407    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14408        assert_eq!(
14409            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14410                Err(anyhow::anyhow!("fixture is absent"))
14411            }),
14412            None
14413        );
14414    }
14415
14416    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14417        let mut q = ask::Question::new(
14418            run.to_owned(),
14419            "implement".to_owned(),
14420            "impl-A".to_owned(),
14421            "continue?".to_owned(),
14422            String::new(),
14423            vec!["resume で続行する".to_owned(), "other".to_owned()],
14424        );
14425        q.actions.insert("resume で続行する".to_owned(), action);
14426        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14427            .unwrap();
14428        q
14429    }
14430
14431    fn held_task_with(run: &str) -> Task {
14432        let mut t = task();
14433        t.runs = vec![run.to_owned()];
14434        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14435        t
14436    }
14437
14438    fn resume_action(run: &str) -> ask::ChoiceAction {
14439        ask::ChoiceAction::Resume { run: run.into() }
14440    }
14441
14442    #[test]
14443    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14444        let home = crate::run::test_home();
14445        for parked in [false, true] {
14446            let mut t = task();
14447            t.start("A".into());
14448            t.start("B".into());
14449            assert_eq!(t.runs, vec!["A", "B"]);
14450            t.start("A".into());
14451            let mut resumed = run_state(RunStatus::Blocked);
14452            resumed.id = "A".into();
14453            resumed.parked = parked;
14454            resumed.driver_exited = true;
14455            t.hold_machine(Some("resumed run stopped".into()));
14456            let q = action_question("A", resume_action("A"));
14457            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14458            assert_eq!(
14459                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14460                    assert_eq!(id, "A");
14461                    Ok(resumed.clone())
14462                }),
14463                ActionDecision::Resume("A".into())
14464            );
14465            assert_eq!(
14466                action_standing(&t, &action_question("B", resume_action("B"))),
14467                ActionStanding::Stale
14468            );
14469            t.release_operator("cli", None);
14470            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14471                assert_eq!(id, "A");
14472                Ok(resumed.clone())
14473            });
14474            assert_eq!(
14475                choose_starter(None, false, unfinished.as_deref()),
14476                Starter::Resume("A".into())
14477            );
14478            assert_eq!(t.runs, vec!["B", "A"]);
14479        }
14480    }
14481
14482    #[test]
14483    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14484        let home = crate::run::test_home();
14485        let mut state = crate::land::tests::repair_state(true, true);
14486        state.status = RunStatus::Landing;
14487        state.parked = true;
14488        state.driver_exited = true;
14489        let mut q = ask::Question::new(
14490            state.id.clone(),
14491            land::APPROVAL_NODE.into(),
14492            "land".into(),
14493            "Merge?".into(),
14494            String::new(),
14495            vec![land::APPROVE.into(), land::HOLD.into()],
14496        );
14497        q.id = state.id.clone();
14498        state.land_approval = Some(crate::run::LandApproval {
14499            question: q.id.clone(),
14500            head: "current-head".into(),
14501        });
14502        assert!(land::upgrade_repair_choice(&mut q, &state));
14503        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14504        let mut task = held_task_with(&state.id);
14505        task.status = TaskStatus::Parked;
14506        assert_eq!(
14507            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14508            ActionDecision::Resume(state.id.clone())
14509        );
14510        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14511        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14512        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14513        assert_eq!(
14514            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14515            ActionDecision::Resume(state.id.clone()),
14516            "a repair answer newer than the manual hold resumes the existing owner"
14517        );
14518        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14519        for answered_at in [q.answered_at, None] {
14520            let mut older = q.clone();
14521            older.answered_at = answered_at;
14522            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14523                panic!("a later manual hold must prevent dispatch")
14524            });
14525            let ActionDecision::Refuse(reason) = refused else {
14526                panic!("expected an actionable refusal, got {refused:?}");
14527            };
14528            assert!(reason.contains("later operator decision"));
14529            assert!(reason.contains(&format!("magi task release {}", task.id)));
14530        }
14531        task.operator_decided_at = None;
14532        let mut superseded = state.clone();
14533        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14534        assert_eq!(
14535            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14536            ActionDecision::Stale
14537        );
14538        for case in 1..4 {
14539            let mut changed = state.clone();
14540            match case {
14541                1 => changed.status = RunStatus::Blocked,
14542                2 => changed.released_to = Some("new-owner".into()),
14543                _ => changed.land_approval.as_mut().unwrap().head.clear(),
14544            }
14545            assert!(matches!(
14546                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14547                ActionDecision::Refuse(_)
14548            ));
14549        }
14550        assert!(matches!(
14551            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14552                "missing owner"
14553            )),
14554            ActionDecision::Refuse(_)
14555        ));
14556        task.runs.push("replacement".into());
14557        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14558        assert_eq!(
14559            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14560                "old owner must not load"
14561            )),
14562            ActionDecision::Stale
14563        );
14564    }
14565
14566    #[test]
14567    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14568        let mut state = crate::land::tests::repair_state(true, true);
14569        state.status = RunStatus::Landing;
14570        state.parked = true;
14571        state.driver_exited = true;
14572        let mut q = ask::Question::new(
14573            state.id.clone(),
14574            land::APPROVAL_NODE.into(),
14575            "land".into(),
14576            "Merge?".into(),
14577            String::new(),
14578            vec![land::APPROVE.into(), land::HOLD.into()],
14579        );
14580        q.id = state.id.clone();
14581        state.land_approval = Some(crate::run::LandApproval {
14582            question: q.id.clone(),
14583            head: "current-head".into(),
14584        });
14585        state.save().unwrap();
14586        land::upgrade_repair_choice(&mut q, &state);
14587        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14588        Questions::open().put(&mut q).unwrap();
14589        let tmp = tempfile::tempdir().unwrap();
14590        let queue = Queue::at(tmp.path().join("queue"));
14591        let mut task = held_task_with(&state.id);
14592        task.status = TaskStatus::Parked;
14593        queue.put(&mut task).unwrap();
14594        let empty = Arc::new(tokio::sync::Semaphore::new(0));
14595        let free = Arc::new(tokio::sync::Semaphore::new(1));
14596        assert!(matches!(
14597            claim_dispatch(&queue, &task, false, &empty, &free),
14598            Err(SkipReason::OrdinaryCapacity)
14599        ));
14600        assert!(matches!(
14601            claim_dispatch(&queue, &task, true, &free, &free),
14602            Err(SkipReason::CoolingDown)
14603        ));
14604        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14605        assert!(claim.permit.is_some());
14606        assert!(matches!(
14607            claim_dispatch(&queue, &task, false, &free, &free),
14608            Err(SkipReason::ClaimUnavailable)
14609        ));
14610        drop(claim);
14611        Questions::open()
14612            .update(&q.id, |q| {
14613                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14614                Ok(())
14615            })
14616            .unwrap();
14617        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14618        assert!(claim.permit.is_none());
14619        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14620    }
14621
14622    #[test]
14623    fn decide_action_resumes_only_the_latest_resumable_run() {
14624        let home = crate::run::test_home();
14625        let t = held_task_with("r1");
14626        let q = action_question("r1", resume_action("r1"));
14627        let load = |s: RunState| move |_: &str| Ok(s);
14628        assert_eq!(
14629            decide_action(
14630                &home,
14631                &t,
14632                &q,
14633                &PHRASES_EN,
14634                load(run_state(RunStatus::Blocked))
14635            ),
14636            ActionDecision::Resume("r1".into())
14637        );
14638        // Not the latest run of the task.
14639        let q_other = action_question("r1", resume_action("r0"));
14640        assert!(matches!(
14641            decide_action(
14642                &home,
14643                &t,
14644                &q_other,
14645                &PHRASES_EN,
14646                load(run_state(RunStatus::Blocked))
14647            ),
14648            ActionDecision::Refuse(_)
14649        ));
14650        // A finished run cannot make progress.
14651        assert!(matches!(
14652            decide_action(
14653                &home,
14654                &t,
14655                &q,
14656                &PHRASES_EN,
14657                load(run_state(RunStatus::Ready))
14658            ),
14659            ActionDecision::Refuse(_)
14660        ));
14661        // A released one either.
14662        let mut released = run_state(RunStatus::Blocked);
14663        released.released_to = Some("elsewhere".into());
14664        assert!(matches!(
14665            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14666            ActionDecision::Refuse(_)
14667        ));
14668        // Unreadable state is a refusal, never a fresh competition.
14669        assert!(matches!(
14670            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14671            ActionDecision::Refuse(_)
14672        ));
14673    }
14674
14675    #[test]
14676    fn decide_action_ignores_a_question_about_an_earlier_run() {
14677        let home = crate::run::test_home();
14678        let mut t = held_task_with("r1");
14679        t.runs.push("r2".to_owned());
14680        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14681        assert_eq!(
14682            decide_action(
14683                &home,
14684                &t,
14685                &action_question("r1", ask::ChoiceAction::Done),
14686                &PHRASES_EN,
14687                never
14688            ),
14689            ActionDecision::Stale
14690        );
14691    }
14692
14693    #[test]
14694    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14695        let home = crate::run::test_home();
14696        let mut t = held_task_with("r1");
14697        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14698        assert_eq!(
14699            decide_action(
14700                &home,
14701                &t,
14702                &action_question("r1", ask::ChoiceAction::Requeue),
14703                &PHRASES_EN,
14704                never
14705            ),
14706            ActionDecision::Requeue
14707        );
14708        let done_q = action_question("r1", ask::ChoiceAction::Done);
14709        assert_eq!(
14710            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14711            ActionDecision::Done
14712        );
14713        t.mark_action_applied(&done_q.id);
14714        assert_eq!(
14715            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14716            ActionDecision::Skip
14717        );
14718
14719        // A plain answer (no action for that label) does nothing.
14720        let mut plain = action_question("r1", ask::ChoiceAction::Done);
14721        plain.actions.clear();
14722        assert_eq!(
14723            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14724            ActionDecision::Skip
14725        );
14726        // A running task is left alone.
14727        let mut running = held_task_with("r1");
14728        running.status = TaskStatus::Running;
14729        assert_eq!(
14730            decide_action(
14731                &home,
14732                &running,
14733                &action_question("r1", ask::ChoiceAction::Done),
14734                &PHRASES_EN,
14735                never
14736            ),
14737            ActionDecision::Skip
14738        );
14739    }
14740
14741    #[test]
14742    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14743        crate::run::pin_test_home();
14744        for legacy in [false, true] {
14745            let dir = tempfile::tempdir().unwrap();
14746            let queue = Queue::at(dir.path().join("queue"));
14747            let questions = Questions::at(dir.path().join("questions"));
14748            let run = "20260101-000000-hold";
14749            let mut task = held_task_with(run);
14750            task.status = TaskStatus::Parked;
14751            let mut q = ask::Question::new(
14752                run.into(),
14753                land::APPROVAL_NODE.into(),
14754                "land".into(),
14755                "Repair?".into(),
14756                String::new(),
14757                vec![land::REPAIR.into()],
14758            );
14759            q.actions.insert(land::REPAIR.into(), resume_action(run));
14760            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14761            // Deterministically order the answer before the actual manual hold.
14762            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14763            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14764            questions.put(&mut q).unwrap();
14765            task.hold_manual(Some("Keep this PR paused".into()));
14766            if legacy {
14767                task.hold_source = None;
14768            }
14769            queue.put(&mut task).unwrap();
14770
14771            apply_task_choice_actions(&queue, &questions, dir.path());
14772            let after = queue.get(&task.id).unwrap();
14773            assert!(after.operator_held());
14774            assert_eq!(after.hold_source, task.hold_source);
14775            assert_eq!(after.operator_decided_at, task.operator_decided_at);
14776            assert_eq!(after.runs, task.runs);
14777            assert_eq!(after.instruction, task.instruction);
14778            assert!(after.resume_override.is_none());
14779            assert!(after.action_applied(&q.id));
14780            let reason = after.hold_reason.as_deref().unwrap();
14781            assert!(reason.starts_with("Keep this PR paused"));
14782            assert!(reason.contains("later operator decision"));
14783            assert!(reason.contains(&format!("magi task release {}", task.id)));
14784
14785            for recovery in [
14786                crate::conduct::Recovery::Review,
14787                crate::conduct::Recovery::Requeue,
14788            ] {
14789                crate::conduct::apply(
14790                    &queue,
14791                    &questions,
14792                    &crate::conduct::Verdict {
14793                        decisions: vec![crate::conduct::Decision {
14794                            id: task.id.clone(),
14795                            recovery: Some(recovery),
14796                            ..Default::default()
14797                        }],
14798                    },
14799                )
14800                .unwrap();
14801            }
14802            // Reconciliation is idempotent, and automatic recovery cannot
14803            // reopen this owner after it observes the rejected repair answer.
14804            apply_task_choice_actions(&queue, &questions, dir.path());
14805            let still_held = queue.get(&task.id).unwrap();
14806            assert!(still_held.operator_held());
14807            assert_eq!(still_held.hold_reason, after.hold_reason);
14808            assert_eq!(still_held.runs, task.runs);
14809            assert!(still_held.review_branch.is_none());
14810            assert!(!still_held.fresh_start);
14811            assert!(queue.next_runnable().is_none());
14812        }
14813    }
14814
14815    #[test]
14816    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14817        for held in [false, true] {
14818            for retry in [false, true] {
14819                let dir = tempfile::tempdir().unwrap();
14820                let queue = Queue::at(dir.path().join("queue"));
14821                let questions = Questions::at(dir.path().join("questions"));
14822                let home = dir.path().join("home");
14823                let mut t = task();
14824                if held {
14825                    t.hold_machine(Some("driver state unknown".into()));
14826                }
14827                queue.put(&mut t).unwrap();
14828                let verdict = serde_json::from_value(serde_json::json!({
14829                    "decisions": [{
14830                        "id": t.id,
14831                        "question": "Driver state unknown; retry the checks or hold?",
14832                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14833                        "actions": {
14834                            "daemon: recheck and retry": {"do": "requeue"},
14835                            "daemon: hold the task": {"do": "hold"}
14836                        }
14837                    }]
14838                }))
14839                .unwrap();
14840                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14841                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14842                let mut q = questions.list().pop().unwrap();
14843                let choice = if retry {
14844                    "daemon: recheck and retry"
14845                } else {
14846                    "daemon: hold the task"
14847                };
14848                assert_eq!(q.actions.len(), 2);
14849                q.answer(ask::Answer::Choice(choice.into())).unwrap();
14850                questions.put(&mut q).unwrap();
14851
14852                // A Web answer does not remove the deputy's fresh lease.
14853                questions.beat(&q.id, ask::WaiterKind::Deputy);
14854                for _ in 0..2 {
14855                    resolve_blockers(&queue, &questions);
14856                    apply_task_choice_actions(&queue, &questions, &home);
14857                    let waiting = queue.get(&t.id).unwrap();
14858                    assert_eq!(waiting.status, TaskStatus::Blocked);
14859                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
14860                    assert!(waiting.answers.is_empty());
14861                    assert!(!waiting.action_applied(&q.id));
14862                    assert!(runnable(&queue).is_empty());
14863                    let free = Arc::new(tokio::sync::Semaphore::new(1));
14864                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14865                }
14866                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14867
14868                // Releasing the blocker and applying the operation share one save.
14869                resolve_blockers(&queue, &questions);
14870                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14871                apply_task_choice_actions(&queue, &questions, &home);
14872                let after = queue.get(&t.id).unwrap();
14873                assert_eq!(
14874                    after.status,
14875                    if retry {
14876                        TaskStatus::Queued
14877                    } else {
14878                        TaskStatus::Held
14879                    }
14880                );
14881                assert!(after.action_applied(&q.id));
14882                assert_eq!(after.operator_held(), !retry);
14883                assert_eq!(after.answers.len(), 1);
14884
14885                // A later operator decision must not replay this answer.
14886                let mut changed = after;
14887                if retry {
14888                    changed.hold_manual(Some("later hold".into()));
14889                } else {
14890                    changed.release_operator("test", None);
14891                }
14892                let expected = changed.status;
14893                queue.put(&mut changed).unwrap();
14894                apply_task_choice_actions(&queue, &questions, &home);
14895                assert_eq!(queue.get(&t.id).unwrap().status, expected);
14896            }
14897        }
14898    }
14899
14900    #[test]
14901    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14902        let dir = tempfile::tempdir().unwrap();
14903        let queue = Queue::at(dir.path().join("queue"));
14904        let questions = Questions::at(dir.path().join("questions"));
14905        let home = dir.path().join("home");
14906        let mut state = run_state(RunStatus::Blocked);
14907        state.id = "20260101-000000-act1".to_owned();
14908        state.save_under(&home).unwrap();
14909
14910        let mut t = held_task_with(&state.id);
14911        queue.put(&mut t).unwrap();
14912        let mut q = action_question(&state.id, resume_action(&state.id));
14913        questions.put(&mut q).unwrap();
14914
14915        apply_task_choice_actions(&queue, &questions, &home);
14916        let after = queue.get(&t.id).unwrap();
14917        assert_eq!(after.status, TaskStatus::Queued);
14918        assert!(!after.fresh_start);
14919        assert!(after.action_applied(&q.id));
14920        let pin = after.resume_override.clone().unwrap();
14921        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14922        assert!(pin.forced);
14923
14924        // Held again later: the same answer does not release it a second time.
14925        let mut again = queue.get(&t.id).unwrap();
14926        again.hold_machine(Some("later".into()));
14927        queue.put(&mut again).unwrap();
14928        apply_task_choice_actions(&queue, &questions, &home);
14929        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14930    }
14931
14932    #[test]
14933    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
14934        let dir = tempfile::tempdir().unwrap();
14935        let home = dir.path();
14936        let queue = Queue::at(home.join("queue"));
14937        let questions = Questions::at(home.join("questions"));
14938        let mut state = run_state(RunStatus::Blocked);
14939        state.save_under(home).unwrap();
14940        let mut task = held_task_with(&state.id);
14941        queue.put(&mut task).unwrap();
14942        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
14943        questions.put(&mut question).unwrap();
14944
14945        apply_task_choice_actions(&queue, &questions, home);
14946
14947        let after = queue.get(&task.id).unwrap();
14948        assert_eq!(after.status, TaskStatus::Held);
14949        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
14950        assert_eq!(after.runs, task.runs);
14951        assert!(after.completion_history.is_empty());
14952        assert!(!after.decision_effects.contains_key(&question.id));
14953        assert_eq!(
14954            RunState::load_under(&state.id, home).unwrap().status,
14955            RunStatus::Blocked
14956        );
14957    }
14958
14959    #[test]
14960    fn a_delivered_answer_is_still_acted_on_exactly_once() {
14961        let dir = tempfile::tempdir().unwrap();
14962        let queue = Queue::at(dir.path().join("queue"));
14963        let questions = Questions::at(dir.path().join("questions"));
14964        let home = dir.path().join("home");
14965        let mut state = run_state(RunStatus::Blocked);
14966        state.id = "20260101-000000-act2".to_owned();
14967        state.save_under(&home).unwrap();
14968
14969        let mut t = held_task_with(&state.id);
14970        queue.put(&mut t).unwrap();
14971        let mut q = action_question(&state.id, resume_action(&state.id));
14972        q.answer_delivered = true;
14973        questions.put(&mut q).unwrap();
14974
14975        // Delivered, and the agent then died: the task is still held, so the
14976        // chosen action applies.
14977        apply_task_choice_actions(&queue, &questions, &home);
14978        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14979        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14980
14981        // Held again: the same answer does nothing a second time.
14982        let mut again = queue.get(&t.id).unwrap();
14983        again.hold_machine(Some("later".into()));
14984        queue.put(&mut again).unwrap();
14985        apply_task_choice_actions(&queue, &questions, &home);
14986        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14987    }
14988
14989    #[test]
14990    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14991        let dir = tempfile::tempdir().unwrap();
14992        let queue = Queue::at(dir.path().join("queue"));
14993        let questions = Questions::at(dir.path().join("questions"));
14994        let home = dir.path().join("home");
14995        let mut state = run_state(RunStatus::Blocked);
14996        state.id = "20260101-000000-act3".to_owned();
14997        state.save_under(&home).unwrap();
14998        let mut t = held_task_with(&state.id);
14999        queue.put(&mut t).unwrap();
15000        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
15001        questions.put(&mut q).unwrap();
15002
15003        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
15004        apply_task_choice_actions(&queue, &questions, &home);
15005        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15006
15007        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
15008        apply_task_choice_actions(&queue, &questions, &home);
15009        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
15010    }
15011
15012    #[test]
15013    fn action_standing_tells_the_reasons_apart() {
15014        let mut t = held_task_with("r1");
15015        let q = action_question("r1", ask::ChoiceAction::Requeue);
15016        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
15017        let mut plain = q.clone();
15018        plain.actions.clear();
15019        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
15020
15021        // Applied wins over everything, even a running task.
15022        t.mark_action_applied(&q.id);
15023        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
15024
15025        // A newer attempt running: the old question is Stale, not Busy.
15026        let mut t = held_task_with("r1");
15027        t.start("r2".to_owned());
15028        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
15029        // The same question about the latest run just waits.
15030        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
15031        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15032        t.status = TaskStatus::Blocked;
15033        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15034
15035        // A conductor question is keyed by the task, never stale.
15036        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
15037        c.node = crate::conduct::NODE.to_owned();
15038        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
15039        assert!(!ActionStanding::Busy.daemon_owns());
15040    }
15041
15042    #[test]
15043    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
15044        let dir = tempfile::tempdir().unwrap();
15045        let queue = Queue::at(dir.path().join("queue"));
15046        let questions = Questions::at(dir.path().join("questions"));
15047        let home = dir.path().join("home");
15048        // Execution finished before task settlement; Done is not a discard.
15049        let mut state = run_state(RunStatus::Ready);
15050        state.id = "20260101-000000-act4".to_owned();
15051        state.save_under(&home).unwrap();
15052        let mut t = held_task_with(&state.id);
15053        t.status = TaskStatus::Running;
15054        queue.put(&mut t).unwrap();
15055        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
15056        q.cwd = Some(dir.path().display().to_string());
15057        questions.put(&mut q).unwrap();
15058
15059        // While the task runs the daemon will not act, so the waiter still
15060        // delivers the word to the dead asker's seat ...
15061        let running = queue.get(&t.id).unwrap();
15062        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
15063        assert!(matches!(
15064            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
15065            crate::waiter::Action::Deliver(_)
15066        ));
15067        // ... and the daemon waits while the task runs, then applies once.
15068        apply_task_choice_actions(&queue, &questions, &home);
15069        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
15070        let mut back = queue.get(&t.id).unwrap();
15071        back.hold_machine(Some("later".into()));
15072        queue.put(&mut back).unwrap();
15073        apply_task_choice_actions(&queue, &questions, &home);
15074        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
15075        let mut again = queue.get(&t.id).unwrap();
15076        again.hold_machine(Some("again".into()));
15077        queue.put(&mut again).unwrap();
15078        apply_task_choice_actions(&queue, &questions, &home);
15079        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15080    }
15081}