Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// 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 decision = decide_action(home, &task, &q, phrases(&language), |id| {
1633            RunState::load_under(id, home)
1634        });
1635        let ran = matches!(
1636            decision,
1637            ActionDecision::Resume(_)
1638                | ActionDecision::Requeue
1639                | ActionDecision::Hold
1640                | ActionDecision::Done
1641        );
1642        if ran && asker_may_still_read(questions, &q, home) {
1643            // The asking process or its seat can still take the word; act
1644            // once it has gone quiet. Bound on the remaining window: the
1645            // check is not atomic with the write below, so an asker that
1646            // takes the word in between (at most one poll, never more than
1647            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1648            // and `Task::actions_applied` under the claim keeps the action to
1649            // one application. The waiter does not deliver an answer that
1650            // carries an action (`waiter::decide_owned`), so it cannot race.
1651            continue;
1652        }
1653        let done = matches!(decision, ActionDecision::Done);
1654        // Resume owes an execution pass; only these task-local effects finish
1655        // in this write. Stale/refused actions never acquire an effect receipt.
1656        let completed = matches!(
1657            decision,
1658            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1659        );
1660        match decision {
1661            ActionDecision::Skip => continue,
1662            ActionDecision::Resume(run) => {
1663                task.release_operator("choice", Some(&q.id));
1664                task.resume_override = Some(crate::queue::OperatorResume {
1665                    question_id: q.id.clone(),
1666                    at: Timestamp::now(),
1667                    conductor_rehold: None,
1668                    forced: true,
1669                    pinned_run: Some(run),
1670                });
1671            }
1672            ActionDecision::Stale => {}
1673            ActionDecision::Requeue => {
1674                task.release_operator("choice-requeue", Some(&q.id));
1675                task.requeue();
1676            }
1677            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1678            ActionDecision::Done => task.succeed(),
1679            ActionDecision::Refuse(why) => {
1680                let _ =
1681                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1682                if task.operator_held() {
1683                    // A rejected answer does not release the operator's hold
1684                    // or reclassify it as recoverable by the conductor.
1685                    task.hold_reason = Some(match task.hold_reason.take() {
1686                        Some(reason) => format!("{reason}\n\n{why}"),
1687                        None => why,
1688                    });
1689                } else {
1690                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1691                    task.hold_machine(Some(why));
1692                }
1693                notices::raise(
1694                    Notice::warn(
1695                        &format!("action:{}", q.id),
1696                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1697                    )
1698                    .link(Link::Task {
1699                        id: task.id.clone(),
1700                    }),
1701                );
1702            }
1703        }
1704        task.mark_action_applied(&q.id);
1705        if completed {
1706            task.decision_effects.insert(
1707                q.id.clone(),
1708                format!("decision: {}", q.resolution().expect("answered action")),
1709            );
1710        }
1711        // The applied id travels with the transition, so a failed save loses
1712        // neither and the answer is acted on at the next poll.
1713        record(queue, &mut task);
1714        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1715            supersede_prior_runs(&task, home);
1716        }
1717        // Delivery is only a note of who has read the answer; the task's own
1718        // mark above is the authority. Best effort.
1719        let _ = questions.update_in(&q.id, &ownership, |r| {
1720            r.answer_delivered = true;
1721            Ok(())
1722        });
1723    }
1724}
1725
1726/// Whether something may still read the answer to `q`: a fresh lease, or the
1727/// asking seat still listed as active in its run (its CLI can outlive the
1728/// `magi ask` that was killed).
1729fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1730    let now = Timestamp::now();
1731    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1732        return true;
1733    }
1734    q.node != crate::conduct::NODE
1735        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1736            s.seats_active()
1737                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1738        })
1739}
1740
1741/// Retire an unanswered conductor question after its task no longer refers to
1742/// it. Conductor questions use the task id in `Question::run`, so run-based
1743/// cleanup cannot observe a manual release or completion.
1744///
1745/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1746/// own question also carries a `run`, and a run id that happens to collide
1747/// with some task's id is not this loop's business — only a conductor
1748/// question actually uses the task id that way. One `Questions::list()` scan
1749/// is taken up front and matched against the in-memory task set, rather than
1750/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1751fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1752    let tasks = queue.list();
1753    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1754    let by_id: std::collections::BTreeMap<&str, &Task> =
1755        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1756    let referenced: Vec<&str> = tasks
1757        .iter()
1758        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1759        .collect();
1760
1761    for mut question in questions.list_for_effects_in(&ownership) {
1762        if !question.status.open()
1763            || question.node != crate::conduct::NODE
1764            || questions.held_reply_in(&question.id, &ownership)
1765        {
1766            continue;
1767        }
1768        // Keep questions a task still names, including when the reference
1769        // moved to a dependent task.
1770        // Preserve even ambiguous references: retiring a possibly referenced
1771        // question is unsafe until the operator disambiguates it.
1772        if referenced
1773            .iter()
1774            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1775        {
1776            continue;
1777        }
1778        let Some(task) = by_id.get(question.run.as_str()) else {
1779            continue;
1780        };
1781        question.abandon(format!(
1782            "task {} no longer waits for this answer",
1783            task.short()
1784        ));
1785        if let Err(e) = questions.put_in(&mut question, &ownership) {
1786            tracing::warn!(
1787                "could not retire question {} for task {}: {e:#}",
1788                question.short(),
1789                task.short()
1790            );
1791        }
1792    }
1793}
1794
1795/// What a finished run tells the queue about the task it came from.
1796///
1797/// A struct rather than a fourth and fifth boolean argument: the two flags
1798/// answer different questions about the same run, and a call site passing
1799/// `(…, true, false)` is one transposition away from refunding attempts
1800/// forever.
1801#[derive(Debug, Clone, Copy)]
1802pub struct Verdict {
1803    /// Where the graph stopped.
1804    pub status: RunStatus,
1805    /// The run opened a pull request.
1806    pub left_pr: bool,
1807    /// At least one seat was lost to a rate limit.
1808    pub quota_hit: bool,
1809    /// The run parked at a node boundary because it was asked to.
1810    pub parked: bool,
1811    /// The run never produced a single candidate a judge could look at.
1812    ///
1813    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1814    /// still have another candidate worth judging, in which case the loss was
1815    /// not the reason nothing came of the run. This is `true` only when the
1816    /// implement wave ended with nothing viable at all.
1817    pub no_viable_candidates: bool,
1818}
1819
1820/// Record a finished run against the task it came from.
1821///
1822/// Kept pure and separate from the loop because this mapping *is* the retry
1823/// policy, and a policy that can only be exercised by spawning a graph is a
1824/// policy nobody checks. The table:
1825///
1826/// | run status                           | task becomes        | attempt spent |
1827/// |---------------------------------------|---------------------|---------------|
1828/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1829/// | `Merged`, `Ready`                      | `Done`               | yes          |
1830/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1831/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1832/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1833/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1834/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1835/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1836/// | `Blocked` with a PR                    | `Held`               | yes          |
1837/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1838/// | `VerifiedNoop`                          | `Held`               | yes          |
1839/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1840///
1841/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1842/// deliberately: every candidate agreeing there is nothing to write is not a
1843/// machine fact about a rate limit, it is an unverified claim about the
1844/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1845/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1846/// claim could be wrong (a misread instruction, a stale check), and closing
1847/// the task automatically on an implementer's say-so would be the exact
1848/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1849/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1850/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1851/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1852/// claim regardless of whether the one already-spent attempt is refunded, and
1853/// [`Task::release`] resets the count to zero anyway the moment a human looks
1854/// at the evidence and lets it run again.
1855///
1856/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1857/// twice, together. A quorum lost to rate limits is a property of the machine
1858/// and not of the task, so the attempt is refunded and a reset quota picks
1859/// the work up where it stopped — and that is just as true when every
1860/// implement seat lost the same race and `after_implement` bails with nothing
1861/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1862/// machine fact. The `no_viable_candidates` guard is what keeps that row
1863/// narrow: a `Failed` run that produced a real candidate which then lost for
1864/// some other reason still spends the attempt, exactly like the quorum lost
1865/// to judges that answered with the wrong shape is ordinary flakiness, and
1866/// refunding *that* takes the bound off the retry loop entirely: run e633
1867/// stalled with `quota: []` after two judges wrote unusable JSON, was
1868/// refunded, and the next attempt paid for a fresh hour-long implement wave
1869/// before it could fail the same way. `max_attempts` exists precisely so
1870/// that cannot repeat forever.
1871///
1872/// A non-terminal status means `execute` returned while the graph was still
1873/// mid-flight, which is a bug rather than a verdict; it is treated as a
1874/// failure so that a task cannot loop on it either.
1875///
1876/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1877/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1878pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1879    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1880}
1881
1882/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1883fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1884    // A parked run is the operator's own doing, and its work is intact on
1885    // disk. The task goes back in line with its attempt refunded so the next
1886    // loop resumes the same run - which `one_task` prefers over competing
1887    // again - and so that swapping the binary a few times cannot exhaust a
1888    // budget meant for agents that actually misbehaved.
1889    if verdict.parked {
1890        task.park(detail);
1891        return;
1892    }
1893    match verdict.status {
1894        RunStatus::Merged | RunStatus::Ready
1895            if task.pr_recovery.as_ref().is_some_and(|s| {
1896                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1897            }) =>
1898        {
1899            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()));
1900        }
1901        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1902        RunStatus::AlreadyInBase => task.already_landed(detail),
1903        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1904        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1905            task.stall(detail)
1906        }
1907        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1908        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1909        RunStatus::Blocked => task.fail(detail, max_attempts),
1910        RunStatus::VerifiedNoop => task.handed_off(detail),
1911        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1912    }
1913}
1914
1915/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1916/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1917/// itself has actually finished *and* its own last attempt is provably why:
1918/// this loads that run and requires `Merged`/`Ready` before touching
1919/// anything earlier in `runs`, since `Task::succeed` can also be called
1920/// directly on a task whose last attempt never landed at all.
1921///
1922/// Called right after whatever call set `task.status` to
1923/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1924/// `reclaim`'s, but also every other place a task can be closed by hand
1925/// without the loop ever settling it itself: `magi task done`
1926/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1927/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1928/// GitHub merge, say, exactly the workflow this repository's own
1929/// "Landing a run's winner by hand" documents — is just as much "this task's
1930/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1931/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1932/// forever, which is the exact backlog this status exists to clear. `pub`
1933/// for those two out-of-module callers; everything else about this stays
1934/// internal bookkeeping.
1935///
1936/// A run something is still actually driving is left alone: a
1937/// task cannot be `Done` while one of its *own* attempts is still in flight,
1938/// so a live one at this point can only be an unrelated process — a manual
1939/// `--resume` of this old, now-moot run — and rewriting under it would just
1940/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1941/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1942/// pair `run_report`/`run_detail` use for the same question elsewhere:
1943/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1944/// --resume` invoked by hand outside it, which `liveness` also checks via
1945/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1946/// (already terminal in some other way, or itself mid-run) is left untouched
1947/// too.
1948///
1949/// Best-effort, like the rest of this module's bookkeeping: a load or save
1950/// failure here is a `tracing::warn`, not a failed settle, and the next time
1951/// this same task's completion is recorded — or a daemon restart replays
1952/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1953/// separate reconciliation pass; if that gap ever matters in practice, one
1954/// can be added then.
1955///
1956/// `home` is a parameter, not the process-global [`crate::run::home`], for
1957/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1958/// calls this with `ui.home`, which is `crate::run::home()` in a real
1959/// process but a fixture's own directory under test — falling through to
1960/// the global there would read and write through whichever home some other
1961/// test in the same binary happened to pin into that `OnceLock` first, not
1962/// the run this call actually means.
1963pub fn supersede_prior_runs(task: &Task, home: &Path) {
1964    let now = Timestamp::now();
1965    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1966    // right behind a `Merged`/`Ready` verdict) from one set directly by
1967    // `magi task done`/its web equivalent/the conductor on a task whose last
1968    // recorded attempt never actually landed - that requires reading the
1969    // run itself, which is exactly what this does before trusting anything
1970    // in `runs` is safe to relabel.
1971    let last_run_succeeded = task
1972        .runs
1973        .last()
1974        .and_then(|id| RunState::load_under(id, home).ok())
1975        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1976    for id in task.superseded_attempts(last_run_succeeded) {
1977        let mut state = match RunState::load_under(id, home) {
1978            Ok(s) => s,
1979            Err(e) => {
1980                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1981                continue;
1982            }
1983        };
1984        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1985            continue;
1986        }
1987        let daemon_claims = is_working_on(home, id, now);
1988        if state.liveness(daemon_claims) == Liveness::Live {
1989            continue;
1990        }
1991        state.status = RunStatus::Superseded;
1992        if let Err(e) = state.save_under(home) {
1993            tracing::warn!("could not mark run {id} superseded: {e:#}");
1994        }
1995    }
1996}
1997
1998/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1999/// finish the moment it was called, because one of its earlier attempts was
2000/// still live then - a `magi run --resume` invoked by hand on an old run,
2001/// most likely.
2002///
2003/// That skip is correct at the time (rewriting under a run something is
2004/// still actively saving would just be undone), but a task only ever
2005/// reaches `Done` once, so without this nothing would ever look at it
2006/// again: if that manual process later ends anywhere other than
2007/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2008/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2009/// backlog this status exists to clear. Called on the same idle-only
2010/// cadence as [`janitor`], next to it rather than folded into it: this
2011/// walks `queue` and `janitor` never otherwise needs one.
2012///
2013/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2014/// more than one attempt, every pass: each call is a handful of local file
2015/// reads bounded by that task's own attempt count, the same order of cost
2016/// [`clean::fold_due`] already pays scanning every run on disk on the same
2017/// cadence, and a task already fully resolved costs one failed liveness
2018/// check turned no-op the moment its lingering attempt is no longer live.
2019fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2020    for task in queue.list() {
2021        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2022            continue;
2023        }
2024        supersede_prior_runs(&task, home);
2025    }
2026}
2027
2028/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2029/// task ends up held.
2030///
2031/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2032/// dead daemon never got back to) share this, so the two cannot drift into
2033/// disagreeing about which held tasks get a diagnostic.
2034fn settle_and_diagnose(
2035    task: &mut Task,
2036    verdict: Verdict,
2037    detail: &str,
2038    max_attempts: usize,
2039    state: &RunState,
2040) {
2041    let p = phrases(&state.config.graph.language);
2042    // Shared by normal completion and crash recovery, under the task claim.
2043    // No new attempt can own the task until the old driver has exited.
2044    if let Some(d) = &state.merge_decision {
2045        use crate::merge_decision as md;
2046        if task
2047            .execution_runs()
2048            .last()
2049            .is_some_and(|id| id != &state.id)
2050        {
2051            return;
2052        }
2053        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2054            task.succeed();
2055        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2056            if state.liveness(false) != Liveness::Dead {
2057                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2058                return;
2059            }
2060            let replacement = md::Replacement {
2061                question: d.question.clone(),
2062                run: state.id.clone(),
2063                pr: d.target.pr.clone(),
2064                agent: agent.to_owned(),
2065                context: format!(
2066                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2067                    d.target.pr,
2068                    state.id,
2069                    serde_json::to_string(&state.reviews).unwrap_or_default()
2070                ),
2071            };
2072            task.requeue();
2073            task.pr_recovery = None;
2074            task.review_of = None;
2075            task.replacement = Some(replacement);
2076        } else {
2077            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2078                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2079            } 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())) }));
2080        }
2081        task.mark_action_applied(&d.question);
2082        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2083            task.decision_effects
2084                .insert(d.question.clone(), format!("decision: {}", d.choice));
2085        }
2086        if let Some(pass) = state.passes.last() {
2087            task.record_pass_at(
2088                &state.id,
2089                pass.index,
2090                Some(pass.started_at),
2091                task.attempts,
2092                None,
2093            );
2094        }
2095        return;
2096    }
2097    if let Some(replacement) = &task.replacement
2098        && !state.parked
2099        && state.resource_block.is_none()
2100        && (state.viable().is_empty()
2101            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2102    {
2103        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)));
2104        return;
2105    }
2106    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2107        let mut agents: Vec<_> = state
2108            .quota
2109            .iter()
2110            .filter(|q| {
2111                q.cause == crate::agent::QuotaCause::Authentication
2112                    && state
2113                        .passes
2114                        .last()
2115                        .is_none_or(|pass| q.at >= pass.started_at)
2116            })
2117            .map(|q| q.agent.as_str())
2118            .collect();
2119        agents.sort_unstable();
2120        agents.dedup();
2121        if !agents.is_empty() {
2122            task.stall(detail);
2123            task.notice_cause("agent-authentication", None, None);
2124            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2125            return;
2126        }
2127    }
2128    let attempts_before = task.attempts;
2129    // A run that stopped because a shared resource stayed busy was never a
2130    // failure of the task or of an agent. Earlier nodes may have run; only
2131    // the blocked operation lacks a result. The attempt is
2132    // refunded and the task is held by the machine, under a reason `triage`
2133    // can re-check, so the same run resumes with the same agents once the
2134    // resource is free. A park request still wins (it is the operator's).
2135    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2136        let disk_checked_at = task.disk_checked_at;
2137        task.notice_cause(
2138            &format!("resource:{}:{}", block.kind, block.node),
2139            None,
2140            None,
2141        );
2142        task.last_error = Some(detail.to_owned());
2143        task.diagnostic = None;
2144        task.attempts = task.attempts.saturating_sub(1);
2145        if block.kind == "agent authentication" {
2146            task.hold_machine(Some(format!(
2147                "[authentication] {}; no attempt was spent",
2148                block.detail
2149            )));
2150        } else if block.kind == "agent usage limit" {
2151            // Usage limits keep the existing cooldown-and-resume policy.
2152            if let Some(agent) = &state.config.graph.selected_implementer {
2153                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.")));
2154            } else {
2155                task.status = TaskStatus::Failed;
2156                task.last_error = Some(block.detail.clone());
2157            }
2158        } else if block.kind == "disk pressure" {
2159            task.hold_machine(Some(format!(
2160                "{}{}",
2161                crate::disk::RUNNING_PRESSURE,
2162                block.detail
2163            )));
2164        } else {
2165            task.hold_machine(Some(format!(
2166                "{}{}; no attempt was spent; resume to retry the affected operation",
2167                crate::cache::RESOURCE_HOLD,
2168                block.description()
2169            )));
2170        }
2171        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2172            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2173        {
2174            task.mark_disk_capacity();
2175            task.disk_checked_at = disk_checked_at;
2176        }
2177        if let Some(pass) = state.passes.last() {
2178            task.record_pass_at(
2179                &state.id,
2180                pass.index,
2181                Some(pass.started_at),
2182                attempts_before,
2183                None,
2184            );
2185        }
2186        return;
2187    }
2188    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2189        state.parked
2190            && state.status == RunStatus::Landing
2191            && state
2192                .pr_pushed_head
2193                .as_ref()
2194                .is_none_or(|h| h == &hold.head)
2195            && task.execution_runs().last() == Some(&state.id)
2196    }) {
2197        // Settlement and crash recovery share this idempotency key. A later
2198        // explicit resume is a new pass and may refund its own attempt once.
2199        let pass = state.passes.last().map_or(0, |p| p.index);
2200        if !task
2201            .passes
2202            .iter()
2203            .any(|p| p.run == state.id && p.pass_index == pass)
2204        {
2205            task.attempts = task.attempts.saturating_sub(1);
2206        }
2207        task.hold_machine(Some(format!(
2208            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2209            hold.question
2210        )));
2211        task.last_error = Some(detail.to_owned());
2212        task.diagnostic = None;
2213        task.record_pass_at(
2214            &state.id,
2215            pass,
2216            state.passes.last().map(|p| p.started_at),
2217            attempts_before,
2218            Some(crate::run::ParkCause::Question),
2219        );
2220        return;
2221    }
2222    let unresolved = task.hold_notice_cause.clone();
2223    if state.base_sync_blocked() {
2224        // No automatic retry may turn a retained sync stop into a new competition.
2225        task.hold_machine(Some(detail.to_owned()));
2226        task.last_error = Some(detail.to_owned());
2227    } else if !verdict.parked
2228        && task
2229            .pr_recovery
2230            .as_ref()
2231            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2232        && matches!(
2233            verdict.status,
2234            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2235        )
2236    {
2237        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2238            task.succeed();
2239        } else {
2240            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()));
2241        }
2242    } else if !verdict.parked
2243        && task.pr_recovery.is_some()
2244        && matches!(
2245            verdict.status,
2246            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2247        )
2248        && !verdict.quota_hit
2249    {
2250        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.")));
2251    } else {
2252        settle_in(task, verdict, detail, max_attempts, p);
2253    }
2254    if !verdict.parked
2255        && !verdict.quota_hit
2256        && matches!(
2257            verdict.status,
2258            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2259        )
2260    {
2261        task.recovery_failed(state);
2262    }
2263    if state.prep_failure.is_some() {
2264        // Minting a run whose candidates could not be prepared is not work
2265        // on a newly approved attempt. Keep the unresolved outcome anchor.
2266        task.hold_notice_cause = unresolved;
2267        task.startup_notice_cause("startup-candidates");
2268    }
2269    // Written here, where the refund (or not) is decided, so the history is a
2270    // fact and not a later guess from the run's status.
2271    if let Some(pass) = state.passes.last() {
2272        let parked = match &pass.end {
2273            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2274            _ => None,
2275        };
2276        task.record_pass_at(
2277            &state.id,
2278            pass.index,
2279            Some(pass.started_at),
2280            attempts_before,
2281            parked,
2282        );
2283    }
2284    if task.status == TaskStatus::Held {
2285        if state.base_sync_blocked() {
2286            task.base_sync_notice(state);
2287        } else if state.prep_failure.is_none() {
2288            task.notice_cause(
2289                label(verdict.status),
2290                Some(&state.id),
2291                state.passes.last().map(|p| p.index),
2292            );
2293        }
2294        task.diagnostic = diagnostic(state);
2295        note_open_question(task, &state.id, p);
2296    }
2297}
2298
2299/// If `task` is held with a `magi ask` question still open on `run`, name the
2300/// question in [`Task::hold_reason`] rather than leaving the hold reading
2301/// only [`describe`]'s run summary.
2302///
2303/// This is the shape task 20260928-191407-05fd left underspecified: an
2304/// implementer settled a verified no-op and filed a question for the
2305/// operator, and the hold that followed said nothing about the question
2306/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2307/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2308/// marker) and must keep seeing it unchanged.
2309///
2310/// Best-effort: an unreadable question store must not stop a run from
2311/// settling, so this is a no-op rather than a propagated error when
2312/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2313fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2314    let Some(home) = crate::run::try_home() else {
2315        return;
2316    };
2317    let open = Questions::at(home.join("questions")).open_for(run);
2318    let Some(q) = open.first() else {
2319        return;
2320    };
2321    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2322    decisions.sort_unstable();
2323    task.notice_cause(
2324        &format!("questions:{}", decisions.join(",")),
2325        Some(run),
2326        None,
2327    );
2328    let base = task.hold_reason.clone().unwrap_or_default();
2329    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2330}
2331
2332/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2333/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2334/// by some other means entirely, like a manual `magi run` resume that
2335/// finishes the graph outside the queue's bookkeeping.
2336///
2337/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2338/// `settle` is separate from `attempt`: a task recovered this way must land
2339/// exactly where a live daemon would have put it — the same policy table,
2340/// not a second one that quietly drifts from it — and that is only checkable
2341/// without spawning a real run.
2342fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2343    match last_run {
2344        Some(state) => {
2345            let verdict = Verdict {
2346                status: state.status,
2347                left_pr: state.pr.is_some(),
2348                quota_hit: state.quota.iter().any(|loss| {
2349                    state
2350                        .passes
2351                        .last()
2352                        .is_none_or(|pass| loss.at >= pass.started_at)
2353                }),
2354                parked: state.parked,
2355                no_viable_candidates: state.viable().is_empty(),
2356            };
2357            let detail = format!(
2358                "{}{}",
2359                phrases(&state.config.graph.language).recovered_running,
2360                describe(&state)
2361            );
2362            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2363        }
2364        None => {
2365            // No run, so no config of its own: `language` is the task's
2366            // repository's setting, read by the caller.
2367            let why = phrases(language).no_run_to_recover;
2368            task.last_error = Some(why.to_owned());
2369            // The phone shows `hold_reason`, so a task held by the machine
2370            // says why there too and not only in `last_error`.
2371            task.notice_cause("missing-run", None, None);
2372            task.hold_machine(Some(why.to_owned()));
2373        }
2374    }
2375}
2376
2377/// Find every task left at `running` that no live process is actually
2378/// driving, and settle each one against whatever its last run became.
2379///
2380/// # Why a claim is proof, not a guess
2381///
2382/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2383/// `running`, and the guard is held for the task's whole time in that status:
2384/// `attempt` does not return, and the loop does not move past the scope
2385/// holding the claim, until the run has settled. So a `running` task whose
2386/// lock is gone cannot have a live owner — this process or any other —
2387/// without needing a staleness threshold or a pid check the way
2388/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2389/// task that never got as far as `running` at all. Taking the claim here is
2390/// the whole test: it either fails, because something really does hold it
2391/// and the task is left alone, or it succeeds, which is the proof — and it is
2392/// kept for the rest of the decision so nothing else can start a competing
2393/// run while this one is being written.
2394///
2395/// Called on every poll, not only at startup, for the reason
2396/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2397/// keep noticing this, not only on the one morning it happened to restart.
2398fn reclaim_orphaned_running(
2399    queue: &Queue,
2400    max_attempts: usize,
2401    live_workers: &std::collections::BTreeSet<String>,
2402) -> Vec<String> {
2403    let mut reclaimed = Vec::new();
2404    for listed in queue.list() {
2405        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2406            continue;
2407        }
2408        let Ok(_claim) = queue.claim(&listed.id) else {
2409            continue;
2410        };
2411        // Re-read under the claim: a release or an edit landed by a human
2412        // between the listing above and the claim just taken must not be
2413        // clobbered by a decision based on the stale copy.
2414        let Ok(mut task) = queue.get(&listed.id) else {
2415            continue;
2416        };
2417        if task.status != TaskStatus::Running {
2418            continue;
2419        }
2420        let last_run = task
2421            .execution_runs()
2422            .last()
2423            .and_then(|id| RunState::load(id).ok());
2424        // `execute` normally abandons a run's own open questions the moment
2425        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2426        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2427        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2428        // with the question still `open`, because the process died before
2429        // reaching that call. `reclaim` itself stays pure on purpose (see its
2430        // own doc), so the same cleanup runs here instead, against the run
2431        // this reclaim is already reading. `settle_run` costs nothing when
2432        // `execute` already got there first.
2433        if let Some(state) = &last_run
2434            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2435        {
2436            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2437        }
2438        let language = if last_run.is_none() {
2439            language_of(&task, Path::new("."))
2440        } else {
2441            String::new()
2442        };
2443        reclaim(&mut task, last_run, max_attempts, &language);
2444        if task.status == TaskStatus::Done {
2445            supersede_prior_runs(&task, &crate::run::home());
2446        }
2447        record(queue, &mut task);
2448        reclaimed.push(task.id.clone());
2449    }
2450    reclaimed
2451}
2452
2453/// Find every run whose `run.json` is provably dead — every seat it still
2454/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2455/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2456/// not merely "no daemon claims it" — and fail it, clearing the leftover
2457/// active seats so the run stops reading as `implementing` (or whichever
2458/// node) forever.
2459///
2460/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2461/// `running`, using whatever `run.json` already says — but nothing in that
2462/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2463/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2464/// never got back to sits exactly where it was left: `active` full of seats
2465/// nobody will ever answer for, `status` stuck on whatever node was in
2466/// flight. `magi show` already tells an operator this in prose (`no live
2467/// daemon claims this run right now`); this is what makes that fact durable
2468/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2469/// stay stuck once nothing is driving it.
2470///
2471/// Runs on every poll, not only at startup, for the reason
2472/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2473/// daemon up for days must keep noticing a run some other, now-dead, daemon
2474/// left behind just as readily as one it trips over on the way up.
2475///
2476/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2477/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2478/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2479/// `runs` directory instead: `home` here is a parameter precisely so a test
2480/// can point it away from the operator's real history (see [`drive`]'s own
2481/// doc), and a scan that fell through to the global home anyway would walk
2482/// whichever directory some *other* process or test pinned into that
2483/// `OnceLock` first — mutating runs this call was never handed.
2484fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2485    reclaim_abandoned_runs_with(
2486        home,
2487        now,
2488        crate::proc::pid_status,
2489        crate::proc::process_started_at,
2490    )
2491}
2492
2493/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2494/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2495/// for the identical reason: this sweep's real damage (wiping a run's active
2496/// seats and failing it) has to be provable against an injected answer in a
2497/// test, not just the real process table.
2498fn reclaim_abandoned_runs_with<F, G>(
2499    home: &Path,
2500    now: Timestamp,
2501    query: F,
2502    identity: G,
2503) -> Vec<String>
2504where
2505    F: Fn(u32) -> Option<bool>,
2506    G: Fn(u32) -> Option<String>,
2507{
2508    let mut abandoned = Vec::new();
2509    for entry in std::fs::read_dir(home.join("runs"))
2510        .into_iter()
2511        .flatten()
2512        .flatten()
2513    {
2514        let id = entry.file_name().to_string_lossy().into_owned();
2515        if !crate::run::is_run_id(&id) {
2516            continue;
2517        }
2518        // Serialize the proof and save with claims and takeover: a new
2519        // execution must not be overwritten after the liveness observation.
2520        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2521            continue;
2522        };
2523        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2524        // that module's docs for why a run this cannot parse is left alone
2525        // rather than guessed at. A different schema number is not that: this
2526        // touches only `status` and `active`, never a field whose meaning a
2527        // schema bump changed, so an old record's values serve this exactly
2528        // as well as a current one's (see `clean::read_state`'s own doc for
2529        // the same reasoning applied to folding).
2530        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2531            continue;
2532        };
2533        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2534            continue;
2535        };
2536        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2537            continue;
2538        }
2539        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2540        // it", which is also the normal, healthy shape of a manual `magi
2541        // run` / `magi review` sharing this same home — this scan walks
2542        // every run on disk, not only ones this daemon itself started. Such
2543        // a run's active seats can legitimately sit past their own timeout
2544        // for a little while (the CLI finishing up, its result still being
2545        // collected) without the process driving it having died. `liveness`
2546        // is what actually tells the two apart, by corroborating
2547        // `driver_pid` against the process it names — see its own doc. Only
2548        // its strongest, provable answer licenses wiping this run's active
2549        // seats and failing it out from under whatever is still running it.
2550        let daemon_claims = is_working_on(home, &id, now);
2551        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2552            != crate::run::Liveness::Dead
2553        {
2554            continue;
2555        }
2556        state.abandon("daemon");
2557        if let Err(e) = state.save_under(home) {
2558            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2559            continue;
2560        }
2561        // This run never passes through `Runner::execute` again, so its end
2562        // is announced here.
2563        if let Some(notice) = notices::run_ended(&state) {
2564            notices::raise_in(home, notice);
2565        }
2566        // The seat that asked is gone for good now, exactly like any other
2567        // door `graph::Runner::settle_questions` closes the moment `status`
2568        // lands somewhere non-resumable - see that method's own doc. Nothing
2569        // else reaches this one before the next `janitor()` startup pass
2570        // (`clean::abandon_settled_questions`), and a daemon that stays up
2571        // for days must not leave an open question badging the operator
2572        // until it happens to restart.
2573        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2574            tracing::warn!("abandon questions for {id}: {e:#}");
2575        }
2576        abandoned.push(id);
2577    }
2578    abandoned
2579}
2580
2581#[derive(Debug, Clone, Serialize, Deserialize)]
2582struct TaskWorker {
2583    opts: Opts,
2584    queue: PathBuf,
2585    task: String,
2586    #[serde(default)]
2587    lane: PermitKind,
2588    #[serde(default)]
2589    standalone: bool,
2590}
2591
2592fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2593    Ok(crate::worker::active(home)?
2594        .into_iter()
2595        .filter(|job| job.kind == "task")
2596        .collect())
2597}
2598
2599fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2600    task_jobs(home)?
2601        .into_iter()
2602        .filter_map(
2603            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2604                Ok(request) if !request.standalone => Some(Ok(job)),
2605                Ok(_) => None,
2606                Err(error) => Some(Err(error.into())),
2607            },
2608        )
2609        .collect()
2610}
2611
2612/// Whether an independent scheduler can be controlled without its web parent.
2613#[must_use]
2614pub fn managed(home: &Path) -> bool {
2615    match crate::worker::active(home) {
2616        Err(error) => {
2617            tracing::error!("cannot determine scheduler ownership: {error:#}");
2618            true
2619        }
2620        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2621        Ok(_) => {
2622            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2623                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2624        }
2625    }
2626}
2627
2628/// Start a detached, singleton scheduler using this executable generation.
2629pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2630    anyhow::ensure!(
2631        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2632        "the scheduler is stopping; wait for retirement before starting it again"
2633    );
2634    crate::worker::spawn(
2635        home,
2636        "scheduler",
2637        "scheduler",
2638        serde_json::to_value(opts.absolute()?)?,
2639    )
2640    .await
2641}
2642
2643fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2644    home.join("worker-parks").join(format!("{}.json", job.id))
2645}
2646
2647fn request_task_park(
2648    home: &Path,
2649    job: &crate::worker::Job,
2650    cause: crate::run::ParkCause,
2651) -> Result<()> {
2652    let path = park_request_path(home, job);
2653    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2654    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2655    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2656}
2657
2658/// Stop dispatch immediately; only an explicit park reaches existing workers.
2659pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2660    if control == crate::worker::Control::Park {
2661        for job in owned_task_jobs(home)? {
2662            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2663        }
2664    }
2665    crate::worker::request(home, "scheduler", control)
2666}
2667
2668/// Replace the scheduler, leaving all active task and conversation jobs alone.
2669pub async fn restart_detached(home: &Path) -> Result<()> {
2670    let active = crate::worker::active(home)?;
2671    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2672    if prior.is_none() && !managed(home) {
2673        return Ok(());
2674    }
2675    let opts: Opts = match prior {
2676        Some(job) => serde_json::from_value(job.payload)?,
2677        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2678    };
2679    request_control(home, crate::worker::Control::Stop)?;
2680    loop {
2681        let reserved = crate::worker::active(home)?
2682            .iter()
2683            .any(|job| job.kind == "scheduler");
2684        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2685            break;
2686        }
2687        tokio::time::sleep(Duration::from_millis(100)).await;
2688    }
2689    spawn_detached(home, &opts).await?;
2690    Ok(())
2691}
2692
2693/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2694pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2695    let opts: Opts = serde_json::from_value(payload)?;
2696    let _ = home;
2697    serve_until(opts, Stop::new()).await
2698}
2699
2700/// Execute and settle one task with the queue claim owned by this process.
2701pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2702    let request: TaskWorker = serde_json::from_value(payload)?;
2703    let queue = Queue::at(request.queue);
2704    let key = format!("task:{}", request.task);
2705    let job = task_jobs(home)?
2706        .into_iter()
2707        .find(|job| job.key == key)
2708        .context("task worker reservation is missing")?;
2709    let park_path = park_request_path(home, &job);
2710    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2711    // our durable reservation. Never execute before that ownership hand-off.
2712    let _claim = loop {
2713        match queue.claim(&request.task) {
2714            Ok(claim) => break claim,
2715            // Only contention (the claim file exists) is worth waiting out; an
2716            // I/O failure must end this worker instead of pinning its lane.
2717            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2718                return Err(e.context("claim the task for its worker"));
2719            }
2720            Err(_) => {
2721                sweep_stale_claims(&queue, STALE_CLAIM);
2722                tokio::time::sleep(Duration::from_millis(50)).await;
2723            }
2724        }
2725    };
2726    let mut task = queue.get(&request.task)?;
2727    if !task.status.runnable()
2728        || (!request.standalone
2729            && request.lane
2730                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2731    {
2732        return Ok(());
2733    }
2734    let stop = Stop::new();
2735    let watcher = {
2736        let home = home.to_path_buf();
2737        let stop = stop.clone();
2738        let park_path = park_path.clone();
2739        tokio::spawn(async move {
2740            loop {
2741                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2742                    let cause = std::fs::read(&park_path)
2743                        .ok()
2744                        .and_then(|body| serde_json::from_slice(&body).ok())
2745                        .unwrap_or(crate::run::ParkCause::Operator);
2746                    stop.park(cause);
2747                    return;
2748                }
2749                tokio::time::sleep(Duration::from_millis(200)).await;
2750            }
2751        })
2752    };
2753    let quota = if request.standalone {
2754        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2755    } else {
2756        let status = Arc::new(Mutex::new(Status::new()));
2757        Box::pin(attempt(
2758            &request.opts,
2759            &queue,
2760            &status,
2761            &stop,
2762            crate::graph::Pause::new(),
2763            &mut task,
2764        ))
2765        .await
2766    };
2767    watcher.abort();
2768    let _ = std::fs::remove_file(park_path);
2769    persist_cooldown(home, &quota).await?;
2770    Ok(())
2771}
2772
2773/// Launch the standalone task worker with a claim-to-reservation handoff.
2774/// Returns only after the worker owns a durable execution reservation.
2775pub async fn spawn_claimed(
2776    home: &Path,
2777    opts: &Opts,
2778    queue: &Queue,
2779    task: &Task,
2780    claim: crate::queue::Claim,
2781) -> Result<crate::worker::Job> {
2782    let request = TaskWorker {
2783        opts: opts.absolute()?,
2784        queue: std::path::absolute(queue.root())?,
2785        task: task.id.clone(),
2786        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2787        standalone: true,
2788    };
2789    let job = crate::worker::spawn(
2790        home,
2791        "task",
2792        &format!("task:{}", task.id),
2793        serde_json::to_value(request)?,
2794    )
2795    .await?;
2796    drop(claim);
2797    Ok(job)
2798}
2799
2800/// Transfer a standalone caller's claim only after the detached worker is live,
2801/// then follow that worker to its final (non-automatically-retrying) outcome.
2802pub async fn run_detached_claimed(
2803    opts: &Opts,
2804    queue: &Queue,
2805    task: &mut Task,
2806    claim: crate::queue::Claim,
2807) -> Result<()> {
2808    let home = crate::run::home();
2809    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2810    loop {
2811        // Reconcile execution leases even without a scheduler. A dead worker
2812        // must become a reported failure, never an infinite persisted wait.
2813        crate::worker::active(&home)?;
2814        let current = crate::worker::get(&home, &job.id)?;
2815        if matches!(
2816            current.status,
2817            crate::worker::Status::Finished | crate::worker::Status::Failed
2818        ) {
2819            *task = queue.get(&task.id)?;
2820            anyhow::ensure!(
2821                current.status != crate::worker::Status::Failed,
2822                "task worker failed: {}",
2823                current.result.as_deref().unwrap_or("unknown failure")
2824            );
2825            return Ok(());
2826        }
2827        tokio::time::sleep(Duration::from_millis(200)).await;
2828    }
2829}
2830
2831async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2832    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2833        let _lease = loop {
2834            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2835                break lease;
2836            }
2837            tokio::time::sleep(Duration::from_millis(10)).await;
2838        };
2839        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2840            let path = home.join("task-quota-cooldown.json");
2841            let temporary = path.with_extension("json.tmp");
2842            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2843            std::fs::rename(temporary, path)?;
2844        }
2845    }
2846    Ok(())
2847}
2848
2849fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2850    match std::fs::read(home.join("task-quota-cooldown.json")) {
2851        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2852        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2853        Err(error) => Err(error.into()),
2854    }
2855}
2856
2857/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2858///
2859/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2860/// sets, so there is one loop body rather than two that drift apart the first
2861/// time the retry policy changes on only one of them.
2862pub async fn serve(opts: Opts) -> Result<()> {
2863    tracing::info!(
2864        "automatic update and restart requires magi web; standalone serve does not restart"
2865    );
2866    serve_until(opts, Stop::new()).await
2867}
2868
2869/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2870///
2871/// A stop retires dispatch promptly, including while a worker launch is being
2872/// acknowledged. Already reserved workers own their attempts independently and
2873/// finish with their started executable. Explicit park additionally forwards
2874/// durable park requests; neither scheduler retirement nor update does so.
2875///
2876/// While the queue is empty the stop is honoured within one wakeup rather than
2877/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2878/// caller that taps stop does not sit through the remainder of a sleep.
2879pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2880    let opts = opts.absolute()?;
2881    let home = crate::run::home();
2882    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2883        .context("another scheduler already owns this home")?;
2884    if let Some(reading) = read_status(&home)
2885        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2886    {
2887        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2888    }
2889    if !crate::worker::active(&home)?
2890        .iter()
2891        .any(|job| job.kind == "scheduler")
2892    {
2893        crate::worker::clear_control(&home, "scheduler")?;
2894    }
2895    std::fs::write(
2896        home.join("scheduler-options.json"),
2897        serde_json::to_vec(&opts)?,
2898    )?;
2899    let control = {
2900        let home = home.clone();
2901        let stop = stop.clone();
2902        tokio::spawn(async move {
2903            loop {
2904                match crate::worker::control(&home, "scheduler").ok().flatten() {
2905                    Some(crate::worker::Control::Park) => {
2906                        let _ = request_control(&home, crate::worker::Control::Park);
2907                        stop.park(crate::run::ParkCause::Operator);
2908                        break;
2909                    }
2910                    Some(crate::worker::Control::Stop) => {
2911                        stop.stop();
2912                        break;
2913                    }
2914                    None => {}
2915                }
2916                tokio::time::sleep(Duration::from_millis(100)).await;
2917            }
2918        })
2919    };
2920    let signal = {
2921        let stop = stop.clone();
2922        tokio::spawn(async move {
2923            if tokio::signal::ctrl_c().await.is_ok() {
2924                stop.stop();
2925                tracing::info!("scheduler shutdown requested; independent workers continue");
2926            }
2927        })
2928    };
2929
2930    let worktrees_root = opts
2931        .worktrees_root
2932        .clone()
2933        .unwrap_or_else(crate::run::default_worktree_root);
2934    let outcome = drive(
2935        &opts,
2936        &Queue::open(),
2937        &status_path(),
2938        &crate::run::home(),
2939        &worktrees_root,
2940        &stop,
2941    )
2942    .await;
2943
2944    signal.abort();
2945    control.abort();
2946    outcome
2947}
2948
2949/// The loop proper: setup, poll, teardown, with the queue and the status file
2950/// supplied rather than discovered.
2951///
2952/// All three of `home`, `worktrees_root` and the queue/status paths are
2953/// parameters rather than resolved here, for the same reason:
2954/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2955/// so a unit test that pinned it would fight every other test in the binary,
2956/// and a loop that resolved its own worktree bay could only be exercised
2957/// against the operator's real `~/wt/<repo>` - publishing over a live
2958/// daemon's status file, claiming tasks out of a live backlog, and, since
2959/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2960/// whatever the operator actually has on disk.
2961async fn drive(
2962    opts: &Opts,
2963    queue: &Queue,
2964    status_file: &Path,
2965    home: &Path,
2966    worktrees_root: &Path,
2967    stop: &Stop,
2968) -> Result<()> {
2969    // The status file is a *snapshot*, not a stream of events: a reader only
2970    // ever wants the latest values, and every tick rewrites the whole file
2971    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2972    // while an mpsc channel would force the loop to re-send unchanged fields on
2973    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2974    // for no gain. The lock is only ever held across a field assignment, never
2975    // across an await.
2976    let recovery_cfg = prepare(&opts.repo, opts).ok();
2977    let daemon_cfg = recovery_cfg
2978        .as_ref()
2979        .map(|c| c.daemon.clone())
2980        .unwrap_or_default();
2981    let reconciled = crate::driver::reconcile(home);
2982    if !reconciled.is_empty() {
2983        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2984    }
2985    let mut initial_status = Status::new();
2986    let owned = owned_task_jobs(home)?;
2987    initial_status.current = current_work(home, Timestamp::now())
2988        .into_iter()
2989        .filter(|current| {
2990            owned
2991                .iter()
2992                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2993        })
2994        .collect();
2995    initial_status.idle = initial_status.current.is_empty();
2996    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2997        recovery_cfg.as_ref(),
2998        daemon_cfg.max_deputies,
2999    ));
3000    let status = Arc::new(Mutex::new(initial_status));
3001    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3002    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3003
3004    // Read once at startup, not per task: how many runs this loop drives at
3005    // once is a property of the machine running it, not of whichever
3006    // repository a given task happens to name - see
3007    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3008    // fact in the same sense the agent roster is.
3009    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3010
3011    tracing::info!(
3012        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3013        queue.root().display(),
3014        opts.poll.as_secs(),
3015        opts.max_attempts,
3016        concurrency,
3017        if daemon_cfg.pause_for_interrupts {
3018            ", interrupts enabled"
3019        } else {
3020            ""
3021        }
3022    );
3023
3024    let outcome = tokio::select! {
3025        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3026            max_concurrent: concurrency,
3027            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3028            recovery_cfg,
3029        }) => outcome,
3030        () = async {
3031            while !stop.stopped() {
3032                tokio::time::sleep(Duration::from_millis(25)).await;
3033            }
3034        } => {
3035            if stop.parking() {
3036                request_control(home, crate::worker::Control::Park)?;
3037            }
3038            Ok(())
3039        }
3040    };
3041
3042    stop.busy.store(0, Ordering::SeqCst);
3043    beat.abort();
3044    clear_status_at(status_file);
3045    outcome
3046}
3047
3048/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3049/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3050pub(crate) fn release_watch_settings_from_config(
3051    home: &Path,
3052    repo: &Path,
3053    cfg: &Config,
3054) -> (Vec<PathBuf>, u64) {
3055    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3056        .into_iter()
3057        .map(|r| r.path)
3058        .collect();
3059    // Repositories the daemon has worked in, wherever they live: a task may
3060    // name one outside `[repos] roots`, and its release PR must be watched too.
3061    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3062        .list()
3063        .into_iter()
3064        .map(|t| t.repo)
3065        .collect();
3066    let runs = home.join("runs");
3067    for id in crate::run::list_ids_in(&runs) {
3068        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3069            .ok()
3070            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3071            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3072        known.extend(repo);
3073    }
3074    for k in known {
3075        let k = k.canonicalize().unwrap_or(k);
3076        if k.join(".git").exists() && !paths.contains(&k) {
3077            paths.push(k);
3078        }
3079    }
3080    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3081    if !paths.contains(&own) {
3082        paths.push(own);
3083    }
3084    (paths, cfg.daemon.release_stall_minutes)
3085}
3086
3087/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3088const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3089
3090/// Refresh the status file on a fixed tick.
3091///
3092/// Separate from the loop because a run takes tens of minutes: a status file
3093/// written only between tasks would look stale for the whole of every run, and
3094/// a reader would report the daemon dead exactly while it was busiest.
3095async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3096    loop {
3097        tokio::time::sleep(HEARTBEAT).await;
3098        let snapshot = {
3099            let mut guard = lock(&status);
3100            guard.updated_at = Timestamp::now();
3101            guard.clone()
3102        };
3103        if let Err(e) = write_status_to(&path, &snapshot) {
3104            // A failed heartbeat must not take the daemon down: the loop is the
3105            // product, the status file is only the window onto it.
3106            tracing::warn!("could not refresh the daemon status file: {e:#}");
3107        }
3108    }
3109}
3110
3111/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3112/// if so, whether that wait is over.
3113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3114enum LandResume {
3115    /// The task's last run is not parked on a land approval; schedule it
3116    /// like any other candidate.
3117    NotLanding,
3118    /// Parked in `land`, waiting on a question nobody has answered yet.
3119    /// Left alone: attempting it now would only re-observe the same pull
3120    /// request and park again, spending a `gh` call on a decision that has
3121    /// not changed since the last time this was checked.
3122    StillWaiting,
3123    /// Parked in `land`, and the question is settled - answered or
3124    /// abandoned. Resuming this is the one kind of candidate that must not
3125    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3126    Ready,
3127}
3128
3129/// Classify a runnable candidate by whether it is parked on a land-merge
3130/// approval. Read-only - no claim taken, nothing written - so it is cheap
3131/// enough to call on every candidate, every poll.
3132fn land_resume_state(task: &Task) -> LandResume {
3133    let Some(run_id) = task.execution_runs().last() else {
3134        return LandResume::NotLanding;
3135    };
3136    let Ok(state) = RunState::load(run_id) else {
3137        return LandResume::NotLanding;
3138    };
3139    if !state.parked {
3140        return LandResume::NotLanding;
3141    }
3142    if state.status == RunStatus::Landing
3143        && state.land_approval.as_ref().is_some_and(|binding| {
3144            ask::Questions::open()
3145                .get_for_effects(&binding.question)
3146                .is_ok_and(|q| {
3147                    q.run == state.id
3148                        && q.resolution()
3149                            .as_deref()
3150                            .is_some_and(crate::merge_decision::stops)
3151                })
3152        })
3153    {
3154        return LandResume::Ready;
3155    }
3156    if !implementers_match(task, &state) {
3157        return LandResume::NotLanding;
3158    }
3159    // Parked in `land` on the merge approval, or at `merge` on the owner's
3160    // word about a title/body the posting gate withheld. Told apart by the
3161    // run's own record, not by a status both can share.
3162    let node = if state.status == RunStatus::Landing {
3163        land::APPROVAL_NODE
3164    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3165        crate::github_text::ASK_NODE
3166    } else {
3167        return LandResume::NotLanding;
3168    };
3169    let store = ask::Questions::open();
3170    let waiting = store
3171        .list_for_effects()
3172        .into_iter()
3173        .filter(|q| &q.run == run_id && q.node == node)
3174        .max_by(|a, b| a.id.cmp(&b.id));
3175    let Some(mut q) = waiting else {
3176        return LandResume::Ready;
3177    };
3178    if !q.status.open() {
3179        // Repair spends agent resources and must obey concurrency and quota
3180        // waits; only a merge/hold decision may use the decision-only lane.
3181        if q.resolution().as_deref() == Some(land::REPAIR) {
3182            return if state.liveness(false) == Liveness::Live {
3183                LandResume::StillWaiting
3184            } else {
3185                LandResume::NotLanding
3186            };
3187        }
3188        return LandResume::Ready;
3189    }
3190    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3191    // nobody ever answered; land's approval bypasses that wait entirely (see
3192    // `land::approval_gate`), so the same deadline has to be enforced here
3193    // instead, or `graph.answer_timeout` silently stops meaning anything for
3194    // a land approval and a run can sit `StillWaiting` forever with nobody
3195    // told to look at it.
3196    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3197    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3198    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3199        q.abandon(format!(
3200            "no answer within {}s of asking",
3201            timeout.as_secs().max(1)
3202        ));
3203        // If this can't be persisted, do not treat the wait as settled on a
3204        // guess: fall through and try again next poll.
3205        if store.put(&mut q).is_ok() {
3206            return LandResume::Ready;
3207        }
3208    }
3209    LandResume::StillWaiting
3210}
3211
3212/// How often the loop rechecks for new work while something it already
3213/// started is still running, rather than sleeping out the whole
3214/// [`Opts::poll`] interval.
3215///
3216/// Short on purpose: this is what lets a land-merge approval that comes back
3217/// while another task is mid-competition be noticed and resumed within a
3218/// fraction of a second, not within the next multi-second poll.
3219const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3220
3221/// How often [`poll`] rechecks the shared build cache against its cap at a
3222/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3223/// waiting for the queue to run dry.
3224///
3225/// A queue that never empties means the `janitor` call at the bottom of this
3226/// loop's fully-idle branch can go unreached for as long as the backlog
3227/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3228/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3229/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3230/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3231/// backlog of short tasks does not pay for that walk on every poll.
3232const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3233
3234/// State of [`poll`]'s own interrupt-scheduling sequence - see
3235/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3236/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3237/// both kept free of `Task`'s non-identity fields on purpose: every decision
3238/// here turns only on task ids and which ones are in flight, so the "never
3239/// more than one run at once" and "exactly one resume" invariants can be
3240/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3241/// queue - which is exactly the coverage this feature's first two attempts
3242/// were missing.
3243///
3244/// Persisted after every transition, so scheduler replacement preserves the
3245/// interrupt's exclusive turn and the interrupted task's priority resume.
3246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3247enum Interrupt {
3248    /// No interrupt sequence in progress. Ordinary dispatch applies.
3249    Idle,
3250    /// `interrupt_task` is runnable and exactly one other run is in flight;
3251    /// `parked` names that one task's id. Dispatch is withheld from
3252    /// everyone, including `interrupt_task` itself, until it has left
3253    /// flight - only then is `interrupt_task` let through.
3254    ///
3255    /// `parked` is a `Vec` rather than a bare id for symmetry with
3256    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3257    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3258    /// when exactly one run is in flight, so it is guaranteed to hold
3259    /// exactly one entry in practice - see that branch's own doc for why
3260    /// more than one is deliberately never attempted.
3261    Parking {
3262        parked: Vec<String>,
3263        interrupt_task: String,
3264    },
3265    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3266    /// withheld from everyone until it leaves flight - merged, failed, held,
3267    /// it makes no difference - at which point the sequence moves to
3268    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3269    /// going straight to `Idle` would hand `parked` back to ordinary
3270    /// priority-order dispatch, where a higher-priority task filed in the
3271    /// meantime could start ahead of it.
3272    Running {
3273        parked: Vec<String>,
3274        interrupt_task: String,
3275    },
3276    /// `interrupt_task` left flight; `parked` still names the one run this
3277    /// sequence owes a resume. Dispatch is withheld from everyone except
3278    /// that task - see [`interrupt_gate`] - so the resume this feature
3279    /// promises is never raced by, or run alongside, an unrelated candidate.
3280    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3281    /// own doc on abandonment - the moment it is no longer runnable at all.
3282    Resuming { parked: Vec<String> },
3283}
3284
3285/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3286/// and `runnable` are read-only snapshots of this tick's reality, and the
3287/// only side effect the caller still owes the world is asking whichever
3288/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3289/// site.
3290///
3291/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3292/// accepted rather than a narrower type because that is what [`poll`] already
3293/// has on hand from [`runnable`], and building a second, smaller list on
3294/// every tick just to satisfy this signature would cost more than it proves.
3295///
3296/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3297/// back to a task they are waiting on no longer being [`runnable`] - held,
3298/// blocked, deleted, or finished by some other means entirely, all of which
3299/// an operator can do to a task sitting in the queue with no claim on it at
3300/// all, at any moment, interrupt sequence or not. Without this check the
3301/// sequence would wait forever for a dispatch that can never come, and
3302/// `interrupt_gate` would withhold every other task in the queue right along
3303/// with it - a single `magi task hold` on the wrong id turning into a
3304/// daemon that never dispatches anything again.
3305fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3306    match state {
3307        Interrupt::Idle => {
3308            // Not just "something to interrupt": exactly one thing. More
3309            // than one run in flight only happens above the default
3310            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3311            // one resume, never run alongside anything else" only because
3312            // it is only ever seeded with exactly one id - see
3313            // `Interrupt::Resuming`'s own doc on why releasing more than one
3314            // parked id back to ordinary dispatch cannot be made safe
3315            // against that same setting's own extra concurrency slots.
3316            // Waiting here for the herd to settle to one is the
3317            // simplification this feature's own constraints ask for rather
3318            // than a second concurrency model to reconcile with the first.
3319            if in_flight.len() != 1 {
3320                return Interrupt::Idle;
3321            }
3322            match runnable.iter().find(|t| t.interrupt) {
3323                Some(t) => Interrupt::Parking {
3324                    parked: in_flight.to_vec(),
3325                    interrupt_task: t.id.clone(),
3326                },
3327                None => Interrupt::Idle,
3328            }
3329        }
3330        Interrupt::Parking {
3331            parked,
3332            interrupt_task,
3333        } => {
3334            if in_flight.iter().any(|id| parked.contains(id)) {
3335                // Still waiting for what was in flight to actually stop.
3336                Interrupt::Parking {
3337                    parked,
3338                    interrupt_task,
3339                }
3340            } else if in_flight.contains(&interrupt_task) {
3341                Interrupt::Running {
3342                    parked,
3343                    interrupt_task,
3344                }
3345            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3346                // The parked run(s) are gone, but the interrupt task has not
3347                // been dispatched yet on this tick - `interrupt_gate` is
3348                // what lets it through next.
3349                Interrupt::Parking {
3350                    parked,
3351                    interrupt_task,
3352                }
3353            } else {
3354                // The interrupt task itself is no longer runnable - see this
3355                // function's own doc on abandonment. The parked run(s) still
3356                // get their guaranteed resume; there is simply no interrupt
3357                // to run ahead of them any longer.
3358                Interrupt::Resuming { parked }
3359            }
3360        }
3361        Interrupt::Running {
3362            parked,
3363            interrupt_task,
3364        } => {
3365            if in_flight.contains(&interrupt_task) {
3366                Interrupt::Running {
3367                    parked,
3368                    interrupt_task,
3369                }
3370            } else {
3371                // The interrupt task's own run reached a terminal status,
3372                // whichever one - this is the *only* trigger that moves the
3373                // sequence on, driven straight off the same in-flight
3374                // bookkeeping `poll` already reaps every tick, not a second,
3375                // independent poll of anything.
3376                Interrupt::Resuming { parked }
3377            }
3378        }
3379        Interrupt::Resuming { parked } => {
3380            if in_flight.iter().any(|id| parked.contains(id)) {
3381                // One of the parked runs has been dispatched - the resume
3382                // this sequence owed is fulfilled. Whatever else is left in
3383                // `parked` (ordinarily nothing, at the default concurrency
3384                // of one) rejoins ordinary priority-order dispatch, same as
3385                // any other runnable task.
3386                Interrupt::Idle
3387            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3388                Interrupt::Resuming { parked }
3389            } else {
3390                // Abandonment (see this function's own doc): nothing left in
3391                // `parked` is even runnable any longer.
3392                Interrupt::Idle
3393            }
3394        }
3395    }
3396}
3397
3398/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3399/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3400/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3401/// indistinguishable from any other runnable task - exactly the "off does
3402/// nothing" this feature promises.
3403fn advance_interrupt_tick(
3404    enabled: bool,
3405    state: Interrupt,
3406    in_flight: &[String],
3407    runnable: &[Task],
3408) -> Interrupt {
3409    if !enabled {
3410        return Interrupt::Idle;
3411    }
3412    advance_interrupt(state, in_flight, runnable)
3413}
3414
3415/// Which of this tick's runnable candidates the interrupt sequence actually
3416/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3417/// each half is assertable on its own: this is the half that keeps a
3418/// competition and an interrupt from ever running at the same moment.
3419fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3420    match state {
3421        Interrupt::Idle => candidates,
3422        Interrupt::Parking {
3423            parked,
3424            interrupt_task,
3425        } => {
3426            if in_flight.iter().any(|id| parked.contains(id)) {
3427                Vec::new()
3428            } else {
3429                candidates
3430                    .into_iter()
3431                    .filter(|t| &t.id == interrupt_task)
3432                    .collect()
3433            }
3434        }
3435        Interrupt::Running { .. } => Vec::new(),
3436        // At most one: even if `parked` names more than one id (more than
3437        // one run was in flight when the sequence began, only possible
3438        // above the default `max_concurrent_runs = 1`), only the first match
3439        // is offered. Capping this to a single candidate - not merely to
3440        // `parked`'s own ids - is what makes "exactly one resume, never two
3441        // dispatched together" true regardless of how many ordinary slots
3442        // happen to be free this tick.
3443        Interrupt::Resuming { parked } => candidates
3444            .into_iter()
3445            .find(|t| parked.contains(&t.id))
3446            .into_iter()
3447            .collect(),
3448    }
3449}
3450
3451/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3452/// bundled into one parameter so `poll`'s own signature stays readable -
3453/// see [`drive`]'s call site for where these are actually read.
3454struct DispatchLimits {
3455    /// How many *ordinary* candidates run at once. See
3456    /// [`crate::config::Daemon::max_concurrent_runs`].
3457    max_concurrent: usize,
3458    /// See [`crate::config::Daemon::pause_for_interrupts`].
3459    pause_for_interrupts: bool,
3460    recovery_cfg: Option<Config>,
3461}
3462
3463/// Which semaphore, if any, dispatching a candidate should draw its permit
3464/// from.
3465///
3466/// Pure and separate from [`poll`]'s loop body for the same reason
3467/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3468/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3469/// exactly the policy this feature adds, and a policy only exercisable by
3470/// running the whole loop is a policy nobody checks.
3471#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3472enum PermitKind {
3473    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3474    /// Checked first - a task can be both a land resume and marked
3475    /// [`Task::urgent`], and the resume's own "must not queue behind
3476    /// anything" guarantee takes precedence.
3477    None,
3478    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3479    /// (never in addition to trying) the ordinary pool. This is what lets
3480    /// an urgent task dispatch while every ordinary slot is already checked
3481    /// out, and what stops a second urgent task from opening a third run: it
3482    /// waits on this same one-slot semaphore rather than falling through to
3483    /// the ordinary one.
3484    Urgent,
3485    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3486    /// above.
3487    #[default]
3488    Ordinary,
3489}
3490
3491/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3492/// own boolean, already computed by the caller from [`land_resume_state`].
3493fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3494    if priority {
3495        PermitKind::None
3496    } else if urgent {
3497        PermitKind::Urgent
3498    } else {
3499        PermitKind::Ordinary
3500    }
3501}
3502
3503fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3504    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3505        (0usize, 0usize),
3506        |(ordinary, urgent), request| match request.lane {
3507            PermitKind::Ordinary => (ordinary + 1, urgent),
3508            PermitKind::Urgent => (ordinary, urgent + 1),
3509            PermitKind::None => (ordinary, urgent),
3510        },
3511    );
3512    (
3513        limit.saturating_sub(ordinary),
3514        1usize.saturating_sub(urgent),
3515    )
3516}
3517
3518/// Why a runnable candidate was not dispatched. This does not alter policy.
3519#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3520enum SkipReason {
3521    ClaimUnavailable,
3522    RereadFailed,
3523    NoLongerRunnable,
3524    WaitingOnLanding,
3525    CoolingDown,
3526    OrdinaryCapacity,
3527    UrgentCapacity,
3528    InterruptGate,
3529}
3530
3531impl SkipReason {
3532    fn key(self) -> &'static str {
3533        match self {
3534            Self::ClaimUnavailable => "claim_unavailable",
3535            Self::RereadFailed => "reread_failed",
3536            Self::NoLongerRunnable => "no_longer_runnable",
3537            Self::WaitingOnLanding => "waiting_on_landing",
3538            Self::CoolingDown => "cooling_down",
3539            Self::OrdinaryCapacity => "ordinary_capacity",
3540            Self::UrgentCapacity => "urgent_capacity",
3541            Self::InterruptGate => "interrupt_gate",
3542        }
3543    }
3544
3545    fn describe(self) -> &'static str {
3546        match self {
3547            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3548            Self::RereadFailed => "could not re-read it",
3549            Self::NoLongerRunnable => "no longer runnable",
3550            Self::WaitingOnLanding => "waiting on landing",
3551            Self::CoolingDown => "quota cooldown",
3552            Self::OrdinaryCapacity => "no free ordinary slot",
3553            Self::UrgentCapacity => "urgent slot busy",
3554            Self::InterruptGate => "withheld by the interrupt sequence",
3555        }
3556    }
3557}
3558
3559/// A reason count from a completed dispatch scan.
3560#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3561pub struct DispatchReasonCount {
3562    /// Stable string key, so readers can preserve future reasons.
3563    pub reason: String,
3564    /// Candidates skipped for this reason.
3565    pub count: usize,
3566}
3567
3568/// Observations from a completed scan, not a fresh queue estimate.
3569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3570pub struct DispatchWait {
3571    /// Runnable candidates before the interrupt gate.
3572    pub runnable: usize,
3573    /// Counts in descending order, with stable reason order for ties.
3574    pub reasons: Vec<DispatchReasonCount>,
3575}
3576
3577type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3578
3579fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3580    if runnable == 0 {
3581        return None;
3582    }
3583    let mut counts = std::collections::BTreeMap::new();
3584    for (_, reason) in skips {
3585        *counts.entry(*reason).or_insert(0usize) += 1;
3586    }
3587    let mut counts: Vec<_> = counts.into_iter().collect();
3588    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3589    Some(DispatchWait {
3590        runnable,
3591        reasons: counts
3592            .into_iter()
3593            .map(|(reason, count)| DispatchReasonCount {
3594                reason: reason.key().to_owned(),
3595                count,
3596            })
3597            .collect(),
3598    })
3599}
3600
3601fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3602    before
3603        .iter()
3604        .filter(|id| !after.iter().any(|task| &task.id == *id))
3605        .map(|id| (id.clone(), SkipReason::InterruptGate))
3606        .collect()
3607}
3608
3609fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3610    if *previous == current {
3611        return false;
3612    }
3613    *previous = current;
3614    true
3615}
3616
3617struct DispatchClaim {
3618    task: Task,
3619    claim: crate::queue::Claim,
3620    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3621}
3622
3623/// Claim and re-read before choosing a lane: a queue listing may predate an
3624/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3625fn claim_dispatch(
3626    queue: &Queue,
3627    candidate: &Task,
3628    cooling_down: bool,
3629    ordinary: &Arc<tokio::sync::Semaphore>,
3630    urgent: &Arc<tokio::sync::Semaphore>,
3631) -> std::result::Result<DispatchClaim, SkipReason> {
3632    let claim = queue
3633        .claim(&candidate.id)
3634        .map_err(|_| SkipReason::ClaimUnavailable)?;
3635    let task = match queue.get(&candidate.id) {
3636        Ok(t) if t.status.runnable() => t,
3637        Ok(_) => return Err(SkipReason::NoLongerRunnable),
3638        Err(e) => {
3639            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3640            return Err(SkipReason::RereadFailed);
3641        }
3642    };
3643    let resume = land_resume_state(&task);
3644    if resume == LandResume::StillWaiting {
3645        return Err(SkipReason::WaitingOnLanding);
3646    }
3647    let priority = resume == LandResume::Ready;
3648    if !priority && cooling_down {
3649        return Err(SkipReason::CoolingDown);
3650    }
3651    // Never borrow an ordinary slot when the single urgent slot is busy.
3652    // Keep scanning other candidates when either pool has no free slot.
3653    let permit = match permit_kind(priority, task.urgent) {
3654        PermitKind::None => None,
3655        PermitKind::Urgent => Some(
3656            Arc::clone(urgent)
3657                .try_acquire_owned()
3658                .map_err(|_| SkipReason::UrgentCapacity)?,
3659        ),
3660        PermitKind::Ordinary => Some(
3661            Arc::clone(ordinary)
3662                .try_acquire_owned()
3663                .map_err(|_| SkipReason::OrdinaryCapacity)?,
3664        ),
3665    };
3666    // Persist the dispatch order under the claim, before config discovery or
3667    // coordination waits can reorder concurrent starts.
3668    let stamp = Timestamp::now();
3669    let mut task = task;
3670    task.dispatched_at = Some(stamp);
3671    if let Err(e) = queue.modify(&task.id, |t| {
3672        t.dispatched_at = Some(stamp);
3673        true
3674    }) {
3675        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3676    }
3677    Ok(DispatchClaim {
3678        task,
3679        claim,
3680        permit,
3681    })
3682}
3683
3684/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3685/// teardown and cannot skip the teardown on an early return.
3686///
3687/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3688/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3689/// land approval that has since been answered is dispatched outside that
3690/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3691/// the whole point of parking there is that it must not queue behind
3692/// whatever else the loop happens to be running, even at the default of one.
3693/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3694/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3695/// these exemptions is still subject to the interrupt gate below, urgent
3696/// included: a land-resume or urgent candidate is exactly as much "something
3697/// else running" as an ordinary one from the interrupt sequence's point of
3698/// view, and letting either slip through while a run is being parked, or
3699/// while the interrupt task itself has the floor, is precisely the second
3700/// run 75dd's own "at most one run, ever, at once" guarantee must never
3701/// allow - see [`Interrupt`]'s own doc.
3702#[derive(Serialize, Deserialize)]
3703struct ServiceWorker {
3704    opts: Opts,
3705    queue: PathBuf,
3706    worktrees_root: PathBuf,
3707    operation: String,
3708}
3709
3710fn load_conductor(home: &Path) -> Result<Conductor> {
3711    match std::fs::read(home.join("conductor-state.json")) {
3712        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3713        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3714        Err(error) => Err(error.into()),
3715    }
3716}
3717
3718fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3719    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3720        .into_iter()
3721        .map(|c| c.task)
3722        .collect();
3723    let stalled = stalled_tasks(queue, home, Timestamp::now());
3724    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3725    let finished = finished_tasks(queue)
3726        .into_iter()
3727        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3728        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3729        .collect();
3730    let queued = queued_tasks(queue)
3731        .into_iter()
3732        .filter(|t| !live.contains(&t.id))
3733        .collect();
3734    (queued, stalled, finished)
3735}
3736
3737// Separate latest dispatch and worker receipts expose version handoff and skips
3738// without erasing the last completed scan or treating observations as authority.
3739fn retention_service_receipt(
3740    home: &Path,
3741    operation: &str,
3742    phase: &str,
3743    outcome: &str,
3744    detail: &str,
3745    cfg: Option<&Config>,
3746) {
3747    if !matches!(operation, "housekeeping" | "disk-pressure") {
3748        return;
3749    }
3750    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3751        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3752        "operation": operation, "outcome": outcome, "detail": detail,
3753        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3754        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3755    if let Err(error) = crate::fold_evidence::atomic_write(
3756        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3757        &serde_json::to_vec(&receipt).expect("service receipt"),
3758    ) {
3759        tracing::warn!("retention service receipt failed: {error:#}");
3760    }
3761}
3762
3763async fn start_service(
3764    home: &Path,
3765    opts: &Opts,
3766    queue: &Queue,
3767    worktrees_root: &Path,
3768    operation: &str,
3769    cfg: Option<&Config>,
3770    busy: bool,
3771) -> Result<()> {
3772    // Fetch policy is live configuration, unlike question recovery capacity.
3773    // Reload before both cadence and eligibility, including disabled -> enabled.
3774    let fetch_cfg = if operation == "fetch" {
3775        match prepare(&opts.repo, opts) {
3776            Ok(cfg) => Some(cfg),
3777            Err(error) => {
3778                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3779                return Ok(());
3780            }
3781        }
3782    } else {
3783        None
3784    };
3785    let cfg = fetch_cfg.as_ref().or(cfg);
3786    let ticks = home.join("service-ticks");
3787    std::fs::create_dir_all(&ticks)?;
3788    let receipt = ticks.join(format!("daemon-{operation}"));
3789    let last = std::fs::read(&receipt)
3790        .ok()
3791        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3792    let interval = match operation {
3793        "disk-pressure" => 30,
3794        "chat-goals" => 60,
3795        "cache" => CACHE_CHECK_INTERVAL_SECS,
3796        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3797        _ => opts.poll.as_secs().max(1),
3798    };
3799    let now = Timestamp::now();
3800    if !cache_check_due(last, now, interval) {
3801        retention_service_receipt(
3802            home,
3803            operation,
3804            "dispatch",
3805            "skipped",
3806            "cadence not due",
3807            cfg,
3808        );
3809        return Ok(());
3810    }
3811    let key = format!("service:daemon-{operation}");
3812    if crate::worker::active(home)?
3813        .iter()
3814        .any(|job| job.key == key)
3815    {
3816        retention_service_receipt(
3817            home,
3818            operation,
3819            "dispatch",
3820            "skipped",
3821            "service worker already active",
3822            cfg,
3823        );
3824        return Ok(());
3825    }
3826    let eligible = match operation {
3827        "conductor" => {
3828            let (queued, stalled, finished) = conductor_work(queue, home);
3829            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3830                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3831        }
3832        "maintenance" => {
3833            queue.list().iter().any(|task| {
3834                crate::triage::disk_wait_eligible(task)
3835                    && task
3836                        .disk_checked_at
3837                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3838            }) || Questions::at(home.join("questions"))
3839                .list_for_effects()
3840                .iter()
3841                .any(|q| {
3842                    q.chosen_action().is_some_and(|action| action.maintenance())
3843                        && !home
3844                            .join("choice-actions")
3845                            .join(format!("{}.json", q.id))
3846                            .exists()
3847                })
3848        }
3849        "housekeeping" => !busy && runnable(queue).is_empty(),
3850        "cache" => {
3851            !busy
3852                && !runnable(queue).is_empty()
3853                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3854        }
3855        "disk-pressure" => busy,
3856        "fetch" => {
3857            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3858        }
3859        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
3860            .list()
3861            .iter()
3862            .any(|talk| {
3863                talk.status.open()
3864                    && talk.pending.is_empty()
3865                    && talk.pending_attachments.is_empty()
3866                    && talk.goals.iter().any(|goal| goal.active())
3867            }),
3868        _ => false,
3869    };
3870    if !eligible {
3871        retention_service_receipt(
3872            home,
3873            operation,
3874            "dispatch",
3875            "skipped",
3876            if operation == "housekeeping" {
3877                "active work or runnable task queue"
3878            } else {
3879                "no active work; idle housekeeping owns scan"
3880            },
3881            cfg,
3882        );
3883        return Ok(());
3884    }
3885    retention_service_receipt(
3886        home,
3887        operation,
3888        "dispatch",
3889        "launching",
3890        "eligible and cadence due",
3891        cfg,
3892    );
3893    let request = ServiceWorker {
3894        opts: opts.absolute()?,
3895        queue: std::path::absolute(queue.root())?,
3896        worktrees_root: std::path::absolute(worktrees_root)?,
3897        operation: operation.to_owned(),
3898    };
3899    if let Err(error) =
3900        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3901    {
3902        retention_service_receipt(
3903            home,
3904            operation,
3905            "dispatch",
3906            "error",
3907            &format!("worker launch: {error:#}"),
3908            cfg,
3909        );
3910        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3911    }
3912    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3913    Ok(())
3914}
3915
3916/// Finite maintenance jobs survive scheduler replacement without duplicating
3917/// agent calls or cancelling an operation between its effect and receipt.
3918pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3919    let request: ServiceWorker = serde_json::from_value(payload)?;
3920    let opts = &request.opts;
3921    let queue = Queue::at(request.queue);
3922    let questions = Questions::at(home.join("questions"));
3923    match request.operation.as_str() {
3924        "chat-goals" => {
3925            let talks = crate::talk::Talks::at(home.join("talks"));
3926            crate::chat_goal_runtime::sweep(&talks, false).await;
3927        }
3928        "maintenance" => {
3929            apply_maintenance_choices(&queue, &questions, home).await;
3930            triage::monitor_disk_waits(
3931                &queue,
3932                &questions,
3933                opts.config.as_deref(),
3934                Timestamp::now(),
3935            );
3936        }
3937        "conductor" => {
3938            let path = home.join("conductor-state.json");
3939            let mut conductor = load_conductor(home)?;
3940            let (queued, stalled, finished) = conductor_work(&queue, home);
3941            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3942                && conductor.worth_a_look(&queue, &stalled, &finished)
3943            {
3944                let cfg = prepare(&opts.repo, opts)?;
3945                conductor
3946                    .maybe_run(
3947                        &cfg,
3948                        &opts.repo,
3949                        &queue,
3950                        &questions,
3951                        home,
3952                        &queued,
3953                        &stalled,
3954                        &finished,
3955                        opts.max_attempts,
3956                    )
3957                    .await;
3958                let temporary = path.with_extension("json.tmp");
3959                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3960                std::fs::rename(temporary, path)?;
3961            }
3962        }
3963        "fetch" => {
3964            let cfg = prepare(&opts.repo, opts)?;
3965            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3966                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3967                tracing::debug!("fetch origins: {outcome:?}");
3968            }
3969        }
3970        "cache" => {
3971            if task_jobs(home)?.is_empty() {
3972                let mut checked = None;
3973                maybe_prune_cache_between_runs(
3974                    &opts.repo,
3975                    opts,
3976                    home,
3977                    &Stop::new(),
3978                    &mut checked,
3979                    Timestamp::now(),
3980                )
3981                .await;
3982            }
3983        }
3984        "disk-pressure" => {
3985            if let Ok(cfg) = prepare(&opts.repo, opts) {
3986                retention_service_receipt(
3987                    home,
3988                    "disk-pressure",
3989                    "worker",
3990                    "running",
3991                    "retention sweep",
3992                    Some(&cfg),
3993                );
3994                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3995                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3996                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3997                }
3998                for current in current_work(home, Timestamp::now()) {
3999                    if let Ok(state) = RunState::load_under(&current.run, home)
4000                        && let Some(reason) = disk_gate(&state.repo, &state.config)
4001                    {
4002                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4003                            job.key.strip_prefix("task:") == Some(current.task.as_str())
4004                        }) {
4005                            request_task_park(
4006                                home,
4007                                &job,
4008                                crate::run::ParkCause::Interrupt {
4009                                    reason: reason.clone(),
4010                                },
4011                            )?;
4012                        }
4013                        notices::raise_in(
4014                            home,
4015                            Notice::warn(
4016                                "disk:pressure",
4017                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4018                            ),
4019                        );
4020                    }
4021                }
4022            } else {
4023                retention_service_receipt(
4024                    home,
4025                    "disk-pressure",
4026                    "worker",
4027                    "error",
4028                    "configuration could not be loaded",
4029                    None,
4030                );
4031            }
4032        }
4033        "housekeeping" => {
4034            if task_jobs(home)?.is_empty() {
4035                match prepare(&opts.repo, opts) {
4036                    Ok(cfg) => {
4037                        retention_service_receipt(
4038                            home,
4039                            "housekeeping",
4040                            "worker",
4041                            "running",
4042                            "retention sweep",
4043                            Some(&cfg),
4044                        );
4045                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4046                    }
4047                    Err(error) => retention_service_receipt(
4048                        home,
4049                        "housekeeping",
4050                        "worker",
4051                        "error",
4052                        &format!("configuration: {error:#}"),
4053                        None,
4054                    ),
4055                }
4056                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4057                resweep_superseded_attempts(&queue, home);
4058                triage_held(&queue, home, opts).await;
4059            } else {
4060                retention_service_receipt(
4061                    home,
4062                    "housekeeping",
4063                    "worker",
4064                    "skipped",
4065                    "task worker became active",
4066                    None,
4067                );
4068            }
4069        }
4070        operation => bail!("unknown daemon service {operation}"),
4071    }
4072    Ok(())
4073}
4074
4075/// Only a different request under the same key is a dispatch handoff race.
4076/// Our own unacknowledged reservation is a startup failure, not competing work:
4077/// stop dispatch without fencing it, so an already detached child may still run.
4078fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4079    let key = format!("task:{}", request.task);
4080    let payload = serde_json::to_value(request)?;
4081    if crate::worker::active(home)?
4082        .iter()
4083        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4084    {
4085        tracing::warn!(
4086            "task {} acquired a competing worker reservation: {error:#}",
4087            crate::run::short_of(&request.task)
4088        );
4089        return Ok(());
4090    }
4091    tracing::error!("task worker startup stopped dispatch: {error:#}");
4092    notices::raise_in(
4093        home,
4094        Notice::error(
4095            "loop:worker-startup",
4096            // Startup diagnostics may contain private child-process details;
4097            // keep them in the local error/log rather than the chat or notifier.
4098            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),
4099        ).link(Link::Task { id: request.task.clone() }),
4100    );
4101    Err(error).with_context(|| {
4102        format!(
4103            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4104            crate::run::short_of(&request.task)
4105        )
4106    })
4107}
4108
4109async fn poll(
4110    opts: &Opts,
4111    queue: &Queue,
4112    status: &Arc<Mutex<Status>>,
4113    home: &Path,
4114    worktrees_root: &Path,
4115    stop: &Stop,
4116    limits: DispatchLimits,
4117) -> Result<()> {
4118    let mut attempted = Vec::new();
4119    let mut settling_once_services = false;
4120    let interrupt_path = home.join("scheduler-interrupt.json");
4121    let mut interrupt = match std::fs::read(&interrupt_path) {
4122        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4123        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4124        Err(error) => return Err(error.into()),
4125    };
4126    let mut previous = std::collections::BTreeSet::<String>::new();
4127    let mut previous_skips = DispatchSkips::new();
4128    while !stop.stopped() {
4129        let jobs: Vec<_> = crate::worker::active(home)?
4130            .into_iter()
4131            .filter(|job| job.kind == "task")
4132            .collect();
4133        let requests: Vec<_> = jobs
4134            .iter()
4135            .map(|job| {
4136                serde_json::from_value::<TaskWorker>(job.payload.clone())
4137                    .with_context(|| format!("read live task worker {}", job.id))
4138            })
4139            .collect::<Result<_>>()?;
4140        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4141        let owned: std::collections::BTreeSet<_> = requests
4142            .iter()
4143            .filter(|r| !r.standalone)
4144            .map(|r| r.task.clone())
4145            .collect();
4146        let current: Vec<_> = requests
4147            .iter()
4148            .zip(&jobs)
4149            .filter(|(request, _)| !request.standalone)
4150            .map(|(request, job)| Current {
4151                worker: Some(job.id.clone()),
4152                task: request.task.clone(),
4153                run: queue
4154                    .get(&request.task)
4155                    .ok()
4156                    .and_then(|task| task.execution_runs().last().cloned())
4157                    .unwrap_or_default(),
4158            })
4159            .collect();
4160        {
4161            let mut snapshot = lock(status);
4162            snapshot.polls += 1;
4163            snapshot.completed += previous.difference(&owned).count();
4164            snapshot.current = current;
4165            snapshot.idle = owned.is_empty();
4166            snapshot.dispatch_wait = None;
4167        }
4168        previous = owned.clone();
4169        stop.busy.store(owned.len(), Ordering::SeqCst);
4170
4171        // Slots are reconstructed from durable reservations and OS-held worker
4172        // leases, not this scheduler's lifetime or mutable task urgency.
4173        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4174        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4175        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4176        let mut permits = Vec::new();
4177        sweep_stale_claims(queue, STALE_CLAIM);
4178        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4179        reclaim_abandoned_runs(home, Timestamp::now());
4180        let questions = Questions::at(home.join("questions"));
4181
4182        // Deterministic: no model, run before the conductor sees anything so
4183        // its input reflects the queue's current, already-resolved state.
4184        crate::task_chat::sweep(
4185            queue,
4186            &crate::talk::Talks::at(home.join("talks")),
4187            &questions,
4188            home,
4189        );
4190        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4191            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4192        {
4193            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4194        }
4195        repair_choice_offers(&questions);
4196        resolve_blockers(queue, &questions);
4197        apply_task_choice_actions(queue, &questions, home);
4198        triage::apply_answers(queue, &questions);
4199        reconcile_task_questions(queue, &questions);
4200        let talks = crate::talk::Talks::at(home.join("talks"));
4201        crate::chat_notify::sweep(queue, &talks, home);
4202        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4203        crate::chat_watch::sweep(home, &talks);
4204        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4205            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4206        }
4207        let mut turns = tokio::task::JoinSet::new();
4208        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4209        // start_turns dispatches detached turns; no paid work lives in this set.
4210        while turns.join_next().await.is_some() {}
4211
4212        crate::consult::start_services(
4213            home,
4214            &opts.repo,
4215            limits.recovery_cfg.as_ref(),
4216            opts.config.as_deref(),
4217        )
4218        .await?;
4219        for operation in [
4220            "conductor",
4221            "maintenance",
4222            "housekeeping",
4223            "disk-pressure",
4224            "cache",
4225            "fetch",
4226            "chat-goals",
4227        ] {
4228            // Once an idle --once drain starts settling services, subsequent
4229            // scans only consume their effects. An expired cadence receipt
4230            // must not start another service and keep the drain alive.
4231            if settling_once_services {
4232                break;
4233            }
4234            if operation == "chat-goals" && stop.parking() {
4235                continue;
4236            }
4237            start_service(
4238                home,
4239                opts,
4240                queue,
4241                worktrees_root,
4242                operation,
4243                limits.recovery_cfg.as_ref(),
4244                !live.is_empty(),
4245            )
4246            .await?;
4247        }
4248        let latest = crate::worker::active(home)?;
4249        if latest.iter().any(|job| job.key == "service:daemon-cache")
4250            || latest
4251                .iter()
4252                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4253        {
4254            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4255            continue;
4256        }
4257        let candidates: Vec<Task> = runnable(queue)
4258            .into_iter()
4259            .filter(|task| !live.contains(&task.id))
4260            .filter(|task| !opts.once || !attempted.contains(&task.id))
4261            .collect();
4262        let in_flight: Vec<_> = owned.iter().cloned().collect();
4263        let prior_interrupt = std::mem::discriminant(&interrupt);
4264        interrupt = advance_interrupt_tick(
4265            limits.pause_for_interrupts,
4266            interrupt,
4267            &in_flight,
4268            &candidates,
4269        );
4270        // Same-variant transitions preserve their identities. Only an actual
4271        // transition needs a durable write, atomically before sending controls.
4272        if prior_interrupt != std::mem::discriminant(&interrupt) {
4273            let temporary = interrupt_path.with_extension("json.tmp");
4274            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4275            std::fs::rename(temporary, &interrupt_path)?;
4276        }
4277        if let Interrupt::Parking {
4278            parked,
4279            interrupt_task,
4280        } = &interrupt
4281        {
4282            for job in jobs.iter().filter(|job| {
4283                parked
4284                    .iter()
4285                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4286            }) {
4287                if crate::worker::control(home, &job.key)?.is_none() {
4288                    request_task_park(
4289                        home,
4290                        job,
4291                        crate::run::ParkCause::Interrupt {
4292                            reason: format!(
4293                                "task {} asked to run first",
4294                                crate::run::short_of(interrupt_task)
4295                            ),
4296                        },
4297                    )?;
4298                }
4299            }
4300        }
4301        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4302        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4303        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4304        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4305        let mut started = false;
4306        let mut resync = false;
4307        for candidate in candidates {
4308            if stop.stopped() {
4309                break;
4310            }
4311            let DispatchClaim {
4312                task,
4313                claim,
4314                permit,
4315            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4316                Ok(claim) => claim,
4317                Err(reason) => {
4318                    skips.insert((candidate.id, reason));
4319                    continue;
4320                }
4321            };
4322            if crate::worker::active(home)?
4323                .iter()
4324                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4325            {
4326                drop(claim);
4327                resync = true;
4328                break;
4329            }
4330            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4331            let request = TaskWorker {
4332                opts: opts.absolute()?,
4333                queue: std::path::absolute(queue.root())?,
4334                task: task.id.clone(),
4335                lane,
4336                standalone: false,
4337            };
4338            // Keep the claim until spawn acknowledges the worker's durable
4339            // reservation. The worker then claims and re-reads before attempt.
4340            if let Err(error) = crate::worker::spawn(
4341                home,
4342                "task",
4343                &format!("task:{}", task.id),
4344                serde_json::to_value(&request)?,
4345            )
4346            .await
4347            {
4348                task_worker_spawn_error(home, &request, error)?;
4349                drop(claim);
4350                resync = true;
4351                break;
4352            }
4353            drop(claim);
4354            permits.extend(permit);
4355            attempted.push(task.id);
4356            started = true;
4357        }
4358        if !resync && !stop.stopped() {
4359            if !started {
4360                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4361            }
4362            if changed_dispatch_skips(&mut previous_skips, skips) {
4363                if previous_skips.is_empty() {
4364                    tracing::info!("dispatch skips cleared");
4365                }
4366                for (task, reason) in &previous_skips {
4367                    tracing::info!(
4368                        task,
4369                        reason = reason.key(),
4370                        "task {} skipped: {}",
4371                        crate::run::short_of(task),
4372                        reason.describe()
4373                    );
4374                }
4375            }
4376        }
4377        if started || resync {
4378            continue;
4379        }
4380        if owned.is_empty() && opts.once {
4381            settling_once_services = true;
4382            // These finite services can own queue claims or publish answers.
4383            // A skipped claim is not an idle queue until they have finished;
4384            // scan again afterwards so their changes are actually scheduled.
4385            if crate::worker::active(home)?.iter().any(|job| {
4386                job.kind == "daemon-service"
4387                    && matches!(
4388                        job.key.as_str(),
4389                        "service:daemon-housekeeping"
4390                            | "service:daemon-conductor"
4391                            | "service:daemon-maintenance"
4392                    )
4393            }) {
4394                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4395                continue;
4396            }
4397            break;
4398        }
4399        stop.idle(if live.is_empty() {
4400            opts.poll
4401        } else {
4402            RECHECK_WHILE_BUSY.min(opts.poll)
4403        })
4404        .await;
4405    }
4406    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4407    // every queue claim and Runner driver lease through outcome settlement.
4408    stop.busy.store(0, Ordering::SeqCst);
4409    lock(status).dispatch_wait = None;
4410    Ok(())
4411}
4412
4413/// A maintenance pass may briefly own the same record while a worker starts.
4414/// Wait without blocking the executor or charging an agent attempt, then read
4415/// ownership again under the acquired lock. Other I/O failures still fail closed.
4416async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4417    let busy = |error: &anyhow::Error| {
4418        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4419            error.kind() == std::io::ErrorKind::WouldBlock
4420                || cfg!(windows) && error.raw_os_error() == Some(33)
4421        })
4422    };
4423    match crate::pr_head::owner_lock(home, id) {
4424        Ok(lock) => return Ok(lock),
4425        Err(error) if busy(&error) => {}
4426        Err(error) => return Err(error),
4427    }
4428    let wait = RunState::load_under(id, home)?
4429        .config
4430        .graph
4431        .timeout_resource_wait;
4432    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4433}
4434
4435/// Historical successors do not revoke a still-resumable public owner. Scan
4436/// under the same lock as publication/driver claims, and fail closed on unknown
4437/// history before spending another attempt.
4438async fn public_resume_owner(
4439    home: &Path,
4440    runs: &[String],
4441    repo: &Path,
4442) -> Result<Option<RunState>> {
4443    let mut owner = None;
4444    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4445        let _lock = resume_owner_lock(home, id).await?;
4446        let state = RunState::load_under(id, home)?;
4447        if state.released()
4448            || state.retired_to.is_some()
4449            || state.pr_taken_over_by.is_some()
4450            || !crate::handover::landing_checkpoint(&state)
4451        {
4452            continue;
4453        }
4454        anyhow::ensure!(
4455            crate::git::toplevel(&state.repo).await?.canonicalize()?
4456                == crate::git::toplevel(repo).await?.canonicalize()?,
4457            "public owner repository differs; inspect run lineage"
4458        );
4459        anyhow::ensure!(
4460            owner.is_none(),
4461            "multiple retained public owners; inspect run lineage"
4462        );
4463        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4464            anyhow::bail!(reason.diagnostic(&state));
4465        }
4466        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4467        anyhow::ensure!(
4468            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4469            "public owner's driver is live or unknown; wait before retrying"
4470        );
4471        owner = Some(state);
4472    }
4473    Ok(owner)
4474}
4475
4476/// Run one claimed task to a terminal status and record the outcome.
4477///
4478/// Every transition is flushed to the queue as it happens, so the state on disk
4479/// is what actually occurred rather than what this process still intends to
4480/// write.
4481async fn attempt(
4482    opts: &Opts,
4483    queue: &Queue,
4484    status: &Arc<Mutex<Status>>,
4485    stop: &Stop,
4486    interrupt_pause: crate::graph::Pause,
4487    task: &mut Task,
4488) -> Vec<QuotaLoss> {
4489    let repo = repo_for(task, &opts.repo);
4490    tracing::info!(
4491        "task {} — {} (repo {})",
4492        task.short(),
4493        task.title,
4494        repo.display()
4495    );
4496
4497    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4498        Ok(owner) => owner,
4499        Err(e) => {
4500            task.hold_machine(Some(format!(
4501                "Cannot verify existing public owner: {e:#}; no attempt started."
4502            )));
4503            record(queue, task);
4504            return Vec::new();
4505        }
4506    };
4507    let resume_runs = public_owner
4508        .as_ref()
4509        .map(|s| vec![s.id.clone()])
4510        .unwrap_or_else(|| task.execution_runs().to_vec());
4511
4512    // A stop spends no agent resources and uses the saved landing owner.
4513    // Current roster edits, missing attachments or a failed config fetch must
4514    // never turn it into a new implementation, or prevent a PR from closing.
4515    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4516        && previous
4517            .merge_decision
4518            .as_ref()
4519            .is_some_and(|decision| !decision.closed)
4520        && previous.status != RunStatus::Landing
4521        && !crate::merge_decision::resumable_hold(&previous)
4522    {
4523        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)));
4524        record(queue, task);
4525        return Vec::new();
4526    }
4527    let stop_owner = resume_runs
4528        .last()
4529        .and_then(|id| RunState::load(id).ok())
4530        .filter(|state| {
4531            crate::merge_decision::resumable_hold(state)
4532                || state.status == RunStatus::Landing
4533                    && state.land_approval.as_ref().is_some_and(|binding| {
4534                        Questions::open()
4535                            .get_for_effects(&binding.question)
4536                            .is_ok_and(|q| {
4537                                q.run == state.id
4538                                    && q.resolution()
4539                                        .as_deref()
4540                                        .is_some_and(crate::merge_decision::stops)
4541                            })
4542                    })
4543        });
4544    if let Some(owner) = stop_owner {
4545        let mut runner = match Runner::resume(&owner.id) {
4546            Ok(runner) => runner,
4547            Err(e) => {
4548                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4549                record(queue, task);
4550                return Vec::new();
4551            }
4552        };
4553        runner.on_pause(stop.pause());
4554        runner.watch_interrupt(interrupt_pause);
4555        let quota_before = runner.state.quota.clone();
4556        let before_start = task.clone();
4557        task.start(owner.id.clone());
4558        if let Err(error) = queue.put(task) {
4559            *task = before_start;
4560            let error = runner.fail_startup("task-start", error);
4561            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4562                task.record_startup_failure(failure.clone());
4563            }
4564            task.hold_manual(Some(format!(
4565                "Could not persist task start; no agents dispatched: {error:#}"
4566            )));
4567            record(queue, task);
4568            return Vec::new();
4569        }
4570        lock(status).current.push(Current {
4571            worker: None,
4572            task: task.id.clone(),
4573            run: owner.id,
4574        });
4575        runner.state.carry_dispatched_resumes(task);
4576        runner.state.next_pass_task_entry = true;
4577        let result = runner.execute().await;
4578        return finish_attempt(
4579            opts.max_attempts,
4580            queue,
4581            task,
4582            &runner.state,
4583            &quota_before,
4584            result,
4585        );
4586    }
4587
4588    if let Some(owner) = &public_owner
4589        && (task.fresh_start || !may_resume_run(owner, task))
4590    {
4591        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)));
4592        record(queue, task);
4593        return Vec::new();
4594    }
4595
4596    if let Some(state) = task
4597        .execution_runs()
4598        .last()
4599        .and_then(|id| RunState::load(id).ok())
4600        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4601    {
4602        task.hold_machine(Some(reason));
4603        record(queue, task);
4604        return Vec::new();
4605    }
4606
4607    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4608        && !task.fresh_start
4609        && task.pr_recovery.is_none()
4610    {
4611        // Authorization still takes the owner lock and execution lease and
4612        // rechecks liveness, retained HEAD and ownership before saving.
4613        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4614            true
4615        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4616            let home = queue.root().parent().expect("queue has a home");
4617            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4618                Ok(()) => true,
4619                Err(error) => {
4620                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4621                    false
4622                }
4623            }
4624        } else {
4625            false
4626        };
4627        if !authorized {
4628            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())));
4629            // Retain the existing stop identity when an old release reached the queue.
4630            task.base_sync_notice(&held);
4631            task.resume_override = None;
4632            record(queue, task);
4633            return Vec::new();
4634        }
4635    }
4636    let unfinished = (!task.fresh_start)
4637        .then(|| unfinished_run(&resume_runs, task.short()))
4638        .flatten()
4639        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4640    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4641    if let Some(id) = &task.disk_resume_run
4642        && unfinished.as_ref() != Some(id)
4643    {
4644        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()));
4645        record(queue, task);
4646        return Vec::new();
4647    }
4648
4649    if !task.fresh_start
4650        && task.pr_recovery.is_none()
4651        && task.review_branch.is_none()
4652        && task.resume_override.is_none()
4653        && previous
4654            .as_ref()
4655            .is_some_and(|run| run.retired_to.is_some())
4656        && unfinished.is_none()
4657    {
4658        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()));
4659        record(queue, task);
4660        return Vec::new();
4661    }
4662
4663    let saved_recovery = previous.as_ref().filter(|run| {
4664        task.replacement.is_none()
4665            && task.pr_recovery.as_ref().is_some_and(|selected| {
4666                selected
4667                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4668                    .is_ok()
4669                    && selected_starter(selected, Some(run), unfinished.as_deref())
4670                        == Starter::Resume(run.id.clone())
4671            })
4672    });
4673
4674    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4675    // failure here is the network's or the operator's, not the task's: hold
4676    // without spending an attempt, never fall back to a possibly stale copy.
4677    let explicit = match &task.overrides {
4678        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4679        Some(_) => opts.config.as_deref(),
4680        None => opts.config.as_deref(),
4681    };
4682    let (mut config, layers) = if let Some(run) = saved_recovery {
4683        // A matching resume owns its resolved configuration and evidence;
4684        // current layers and inherited overrides only configure new work.
4685        let mut saved = run.clone();
4686        if let Err(e) = saved.configure_recovery_resume() {
4687            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4688            record(queue, task);
4689            return Vec::new();
4690        }
4691        (saved.config, Vec::new())
4692    } else {
4693        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4694            Ok(loaded) => loaded,
4695            Err(e) => {
4696                let reason = format!("[config] {e:#}");
4697                record_config_failure(task, &e);
4698                task.last_error = Some(reason.clone());
4699                task.hold_machine(Some(reason));
4700                record(queue, task);
4701                return Vec::new();
4702            }
4703        };
4704        if let Err(e) = apply_options(&mut config, opts, task) {
4705            task.hold_manual(Some(format!(
4706                "[config] {e:#}; correct the merge override before releasing the task"
4707            )));
4708            record(queue, task);
4709            return Vec::new();
4710        }
4711        if let Some(selected) = &task.pr_recovery
4712            && let Err(e) = selected.configure(&mut config)
4713        {
4714            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4715            record(queue, task);
4716            return Vec::new();
4717        }
4718        (config, layers)
4719    };
4720    let config_evidence = crate::pr_recovery::ConfigEvidence {
4721        layers,
4722        overrides: task.overrides.clone(),
4723        daemon_merge: task
4724            .overrides
4725            .as_ref()
4726            .is_none_or(|o| o.inherit_daemon_options)
4727            .then(|| opts.merge.clone())
4728            .flatten(),
4729    };
4730    apply_task_implementers(&mut config, task);
4731    if let Some(replacement) = &task.replacement {
4732        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4733            old.liveness(false) == Liveness::Dead
4734                && old.merge_decision.as_ref().is_some_and(|d| {
4735                    d.closed
4736                        && d.question == replacement.question
4737                        && d.replacement_run.as_ref().is_none_or(|run| {
4738                            task.execution_runs().last() == Some(run)
4739                                && RunState::load(run).is_ok_and(|current| {
4740                                    current.replaces.as_ref().is_some_and(|pin| {
4741                                        pin.question == replacement.question
4742                                            && pin.agent == replacement.agent
4743                                    })
4744                                })
4745                        })
4746                })
4747        });
4748        if !safe {
4749            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()));
4750            record(queue, task);
4751            return Vec::new();
4752        }
4753        match config.agent(&replacement.agent) {
4754            Ok(agent) if crate::agent::installed(agent) => {}
4755            _ => {
4756                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)));
4757                record(queue, task);
4758                return Vec::new();
4759            }
4760        }
4761        config.graph.implementers = 1;
4762        config.graph.land_approval = true;
4763        config.merge.mode = MergeMode::Pr;
4764        config.graph.selected_implementer = Some(replacement.agent.clone());
4765    }
4766    let p = phrases(&config.graph.language);
4767    let start_failed = p.could_not_start;
4768    // Resolve once for both admission and settlement. The inputs are the
4769    // task's explicit sources (never prose), plus an explicit review source's
4770    // current head; review-only runs may rebase later, and neither fact can
4771    // refund a failed automatic generation.
4772    if let Ok(base) =
4773        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4774            .await
4775        && let Ok(head) =
4776            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4777    {
4778        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4779        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4780            let source = crate::git::rev_parse(&repo, branch)
4781                .await
4782                .unwrap_or_default();
4783            inputs.push_str(&format!(";review:{branch}:{source}"));
4784        }
4785        if let Some(reason) = task
4786            .recovery_exhausted(
4787                &head,
4788                &inputs,
4789                task.attempt_limit
4790                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4791            )
4792            .filter(|_| {
4793                !task.repair_grants.last().is_some_and(|receipt| {
4794                    RunState::load(&receipt.request.run)
4795                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4796                })
4797            })
4798        {
4799            task.hold_unrequested_retry(Some(reason));
4800            record(queue, task);
4801            return Vec::new();
4802        }
4803        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4804    }
4805
4806    // The free-space gate, checked *before* anything is minted: a task that
4807    // waits out a full disk costs nothing yet, and must not spend an attempt
4808    // or start a run the machine cannot finish. Held tasks stay in the list
4809    // for the human to see; triage requeues them automatically when capacity
4810    // and output reservations permit the same execution to resume. A volume whose free
4811    // space cannot be measured closes the gate too: starting a run blind on a
4812    // disk that may be full is how the machine ends up with 6.7 GB free.
4813    if let Some(reason) = disk_gate(&repo, &config) {
4814        task.notice_cause("disk-space", None, None);
4815        task.last_error = Some(reason.clone());
4816        let disk_checked_at = task.disk_checked_at;
4817        task.hold_machine(Some(reason.clone()));
4818        task.mark_disk_capacity();
4819        task.disk_checked_at = disk_checked_at;
4820        record(queue, task);
4821        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4822        // Stable wording - the free-space figures live in the task's hold
4823        // reason, and changing numbers would relight the bell every poll.
4824        notices::raise(
4825            Notice::warn(
4826                &format!("disk:{}", repo.display()),
4827                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
4828            )
4829            .link(Link::Task {
4830                id: task.id.clone(),
4831            }),
4832        );
4833        return Vec::new();
4834    }
4835
4836    // A resumable run of this task is carried on, never re-competed. The
4837    // candidates are built and paid for, and a fresh competition races a
4838    // second implementation against them.
4839    //
4840    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4841    // started 3cbf on the same task a moment later, duplicating two and a
4842    // half hours of agent work. Then b25f stalled on a judge that timed out
4843    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4844    // was to blame for - and 4043 started **one second** later, buying three
4845    // fresh implementations to reach the same panel. `RunStatus::resumable`
4846    // rather than `!done()` is what catches the second case: a stall is
4847    // terminal, and its cheap recovery re-asks only the absent seats.
4848    //
4849    // A load failure is warned about rather than silently read as "not
4850    // resumable": the alternative is exactly what let a schema mismatch on
4851    // run `eba2` fall through to a full re-competition with nobody told why.
4852    // `crate::conduct` is what actually offers a better answer than
4853    // `Runner::start` here (see `Recovery::Review`), once this task's next
4854    // failure shows it up as `held`/`failed` with the run state unreadable.
4855    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4856    // branch survived, and this reopens exactly that branch as a
4857    // review-only pass rather than resuming or competing again. Consumed
4858    // (cleared) here whichever way this goes, so it never outlives this one
4859    // attempt - see `queue::Task::review_branch`.
4860    let review_branch = if previous
4861        .as_ref()
4862        .is_some_and(|state| crate::repair_budget::pending(task, state))
4863    {
4864        None
4865    } else {
4866        take_review_branch(task, previous.as_ref())
4867    };
4868    let branch_exists = match &review_branch {
4869        Some(branch) => crate::git::branch_exists(&repo, branch)
4870            .await
4871            .unwrap_or(false),
4872        None => false,
4873    };
4874    // An explicit `magi review <branch>` is reviewed whatever happens to the
4875    // branch unless an explicit implementer change requires fresh work. An
4876    // unfinished run of the same task still wins, so a retry resumes.
4877    let proposed = review_retry_starter(
4878        task,
4879        previous.as_ref(),
4880        review_branch.as_deref(),
4881        branch_exists,
4882        unfinished.as_deref(),
4883    );
4884    let retry_selected = task.replacement.is_some()
4885        && task.resumption.is_some()
4886        && !task.fresh_start
4887        && previous.as_ref().is_some_and(|run| {
4888            run.replaces.is_some()
4889                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4890                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4891        });
4892    let stop_pin = task
4893        .resume_override
4894        .as_ref()
4895        .filter(|pin| {
4896            Questions::open()
4897                .get_for_effects(&pin.question_id)
4898                .is_ok_and(|q| {
4899                    q.node == land::APPROVAL_NODE
4900                        && q.resolution()
4901                            .as_deref()
4902                            .is_some_and(crate::merge_decision::stops)
4903                })
4904        })
4905        .and_then(|pin| pin.pinned_run.clone());
4906    let granted_run = task.repair_grants.last().and_then(|receipt| {
4907        let state = RunState::load(&receipt.request.run).ok()?;
4908        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4909    });
4910    let starter = if let Some(run) = granted_run {
4911        Starter::Resume(run)
4912    } else if let Some(owner) = &public_owner {
4913        Starter::Resume(owner.id.clone())
4914    } else if let Some(run) = stop_pin {
4915        // Stop actions resume their exact owner even after seat-count edits;
4916        // they must never fall through to implementation or a takeover.
4917        Starter::Resume(run)
4918    } else if retry_selected {
4919        Starter::Resume(previous.as_ref().unwrap().id.clone())
4920    } else if let Some(selected) = &task.pr_recovery {
4921        if selected
4922            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4923            .is_ok()
4924        {
4925            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4926        } else {
4927            Starter::Review(selected.branch.clone())
4928        }
4929    } else {
4930        starter_with_implementers(task, previous.as_ref(), proposed)
4931    };
4932    // An explicit resume pin must never degrade into a new competition or
4933    // takeover, including when its run stops being eligible after the answer.
4934    if let Some(pin) = &task.resume_override
4935        && let Some(run) = &pin.pinned_run
4936        && starter != Starter::Resume(run.clone())
4937    {
4938        let run = run.clone();
4939        task.notice_cause("resume-owner", Some(&run), None);
4940        task.hold_machine(Some(format!(
4941            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4942            task.id
4943        )));
4944        record(queue, task);
4945        return Vec::new();
4946    }
4947    // Automatic disk recovery resumes its retained run or stops: a changed
4948    // seat count or review branch must not turn it into a new competition.
4949    // No attempt is spent here.
4950    if let Some(run) = &task.disk_resume_run
4951        && starter != Starter::Resume(run.clone())
4952    {
4953        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()));
4954        record(queue, task);
4955        return Vec::new();
4956    }
4957    if task.replacement.is_some()
4958        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4959        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4960    {
4961        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()));
4962        record(queue, task);
4963        return Vec::new();
4964    }
4965    if let Some(reason) = retained_attempt_hold(
4966        task,
4967        &starter,
4968        config.disk.retained_attempt_limit,
4969        RunState::load,
4970    ) {
4971        // The review choice was consumed above. Preserve it across this hold
4972        // so a later release cannot silently become a fresh implementation.
4973        if let Starter::Review(branch) = &starter {
4974            task.review_branch = Some(branch.clone());
4975        }
4976        task.hold_unrequested_retry(Some(reason));
4977        record(queue, task);
4978        return Vec::new();
4979    }
4980    // Absolute paths of the files the task was filed with, re-read from the
4981    // task now so a file attached while it was held reaches a resumed run
4982    // too. A stored name whose file has gone is an error before any agent is
4983    // paid for, never a silent omission the implementer cannot notice.
4984    let attachments = match task_attachments(queue, task) {
4985        Ok(a) => a,
4986        Err(e) => {
4987            task.attempts += 1;
4988            task.fail_startup_target(
4989                "startup-attachments",
4990                e.name.clone(),
4991                format!("{start_failed}{e:#}"),
4992                opts.max_attempts,
4993            );
4994            record(queue, task);
4995            return Vec::new();
4996        }
4997    };
4998    let startup_pause = stop.pause();
4999    let startup_interrupt = interrupt_pause.clone();
5000    let wait = crate::repo_lock::WaitPolicy::new(
5001        Duration::from_secs(config.graph.timeout_resource_wait),
5002        move || startup_pause.parked() || startup_interrupt.parked(),
5003    );
5004    // Startup includes review takeover and recovery. Do not embed its large
5005    // future in both the wait scope and the surrounding attempt stack frame.
5006    let started = wait.scope(Box::pin(async { match &starter {
5007        Starter::Review(_) if task.pr_recovery.is_some() => {
5008            let selected = task.pr_recovery.clone().expect("selected recovery");
5009            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5010                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5011                    .await
5012                    .map(|mut r| {
5013                        r.state.attachments = attachments.clone();
5014                        r
5015                    }),
5016                Err(e) => Err(e),
5017            }
5018        }
5019        Starter::Review(branch) => {
5020            tracing::info!(
5021                "task {} reopens `{branch}` as a review-only pass",
5022                task.short()
5023            );
5024            // Every earlier attempt is superseded by the one being minted
5025            // now, so a branch one of them still holds may be taken over.
5026            let takeover = crate::handover::Takeover {
5027                earlier: task.earlier_attempts().to_vec(),
5028                home: crate::run::home(),
5029                choice: take_divergence_answer(branch, &config.merge.remote, task),
5030                task_instruction: Some(instruction_for(task)),
5031            };
5032            Runner::review_taking_over(
5033                &repo,
5034                branch,
5035                config,
5036                Some(takeover),
5037                crate::run::Origin::queue(&task.id),
5038            )
5039            .await
5040        }
5041        Starter::Resume(id) => {
5042            tracing::info!("resuming run {id} rather than competing again");
5043            Runner::resume(id).and_then(|mut r| {
5044                if retry_selected {
5045                    // The explicit queue release retries this same pinned
5046                    // implementation, preserving the attempt and worktrees.
5047                    for candidate in &mut r.state.candidates {
5048                        candidate.failed = None;
5049                        candidate.empty = false;
5050                        candidate.commits = 0;
5051                    }
5052                    r.state.status = RunStatus::Implementing;
5053                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5054                }
5055                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5056                    r.state.sources = task.sources.clone();
5057                }
5058                if r.state.prep_failure.is_some() {
5059                    let approval = task
5060                        .resumption
5061                        .as_ref()
5062                        .context("preparation retry requires an explicit task release")?;
5063                    r.retry_preparation(approval.at)?;
5064                }
5065                if let Some(instruction) =
5066                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5067                {
5068                    r.state.instruction = instruction;
5069                }
5070                r.state.attachments = attachments.clone();
5071                if task.replacement.is_some() {
5072                    r.state.config.merge.mode = MergeMode::Pr;
5073                    r.state.config.graph.land_approval = true;
5074                }
5075                // Replacements publish a new PR and ask again. Selected PR
5076                // recoveries keep their saved disposition; ordinary runs can
5077                // retain the task's merge override.
5078                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5079                    .overrides
5080                    .as_ref()
5081                    .and_then(|o| o.merge.as_deref())
5082                    .and_then(|m| merge_mode(m).ok())
5083                {
5084                    r.state.config.merge.mode = mode;
5085                }
5086                Ok(r)
5087            })
5088        }
5089        Starter::Start => {
5090            if let Some(branch) = &review_branch {
5091                tracing::warn!(
5092                    "conductor chose review for task {} but branch `{branch}` no longer \
5093                     exists; requeuing as a fresh competition instead",
5094                    task.short()
5095                );
5096            }
5097            let instruction = prepare_instruction(&starter, None, task)
5098                .unwrap_or_else(|| task.instruction.clone());
5099            Runner::start_naming(
5100                &repo,
5101                instruction,
5102                &task.title,
5103                config,
5104                crate::run::Origin::queue(&task.id),
5105            )
5106            .await
5107            .map(|mut r| {
5108                r.state.attachments = attachments.clone();
5109                r.state.sources = task.sources.clone();
5110                r
5111            })
5112        }
5113    }})).await;
5114    if let Err(error) = &started
5115        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5116    {
5117        task.record_startup_failure(failure.clone());
5118    }
5119    let mut runner = match started {
5120        Ok(r) => r,
5121        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5122            task.last_error = Some(e.to_string());
5123            if stop.parking() || interrupt_pause.parked() {
5124                let attempts = task.attempts;
5125                task.park(e.to_string());
5126                // Startup has not spent an attempt to refund.
5127                task.attempts = attempts;
5128            } else {
5129                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5130            }
5131            record(queue, task);
5132            return Vec::new();
5133        }
5134        // A branch an earlier attempt still holds and magi will not release
5135        // by itself is the operator's call, not a failed attempt: hold the
5136        // task with the reason, spend nothing, and say so on the bell.
5137        Err(e) if task.pr_recovery.is_some() => {
5138            task.startup_notice_cause("startup-public-head");
5139            task.attempts += 1;
5140            task.last_error = Some(format!("{start_failed}{e:#}"));
5141            task.hold_unrequested_retry(Some(format!(
5142                "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."
5143            )));
5144            record(queue, task);
5145            return Vec::new();
5146        }
5147        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5148            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5149                Some(r) => (p.handover_refused)(r),
5150                None => format!("{e:#}"),
5151            };
5152            task.startup_notice_cause("startup-handover");
5153            let reason = format!("{start_failed}{detail}");
5154            task.last_error = Some(reason.clone());
5155            // Consumed above by `take`; keep it so the released task retries
5156            // as a review of this same branch.
5157            let branch = match &starter {
5158                Starter::Review(branch) => Some(branch.clone()),
5159                _ => None,
5160            };
5161            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5162            // one page; the guidance rides in the reason, fixed per state so a
5163            // re-put never changes the wording and relights it.
5164            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5165            record(queue, task);
5166            tracing::warn!(
5167                "holding {} for a branch it cannot take over: {e:#}",
5168                task.short()
5169            );
5170            return Vec::new();
5171        }
5172        // A branch that differs between here and the remote in ways magi
5173        // cannot prove are the same change is a decision for the owner, not a
5174        // failed attempt: ask with both sides laid out, spend no attempt, and
5175        // let the answer requeue the task.
5176        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5177            let d = e
5178                .downcast_ref::<crate::reconcile::Diverged>()
5179                .expect("checked by the guard");
5180            let mut q = ask::Question::new(
5181                task.id.clone(),
5182                crate::reconcile::NODE.to_owned(),
5183                crate::reconcile::SEAT.to_owned(),
5184                d.summary(),
5185                d.detail(),
5186                d.choices(),
5187            );
5188            match Questions::open().put(&mut q) {
5189                Ok(()) => {
5190                    task.last_error = Some(format!("{e:#}"));
5191                    // Consumed above by `take`; the answer has to reach a review
5192                    // of this same branch, so keep pointing the task at it.
5193                    task.review_branch = Some(d.branch.clone());
5194                    task.review_instruction = Some(task.instruction.clone());
5195                    task.block(vec![q.id.clone()], Some(d.summary()));
5196                }
5197                Err(put) => {
5198                    tracing::warn!("could not file the divergence question: {put:#}");
5199                    task.attempts += 1;
5200                    task.fail_startup(
5201                        "startup-question-store",
5202                        format!("{start_failed}{e:#}"),
5203                        opts.max_attempts,
5204                    );
5205                }
5206            }
5207            record(queue, task);
5208            return Vec::new();
5209        }
5210        Err(e) => {
5211            // The answer was stale and nothing was applied: keep pointing at
5212            // the branch so the next attempt asks again against its new tips.
5213            // Nothing went wrong with the task, so no attempt is spent: a
5214            // budget one short of its limit must not hold it instead of
5215            // letting the question be asked again.
5216            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5217                && let Starter::Review(branch) = &starter
5218            {
5219                task.review_branch = Some(branch.clone());
5220                task.review_instruction = Some(task.instruction.clone());
5221                task.last_error = Some(format!("{start_failed}{e:#}"));
5222                task.status = crate::queue::TaskStatus::Failed;
5223                record(queue, task);
5224                return Vec::new();
5225            }
5226            task.attempts += 1;
5227            task.last_error = Some(format!("{start_failed}{e:#}"));
5228            task.startup_notice_cause("startup-source");
5229            task.hold_unrequested_retry(Some(format!(
5230                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5231            )));
5232            record(queue, task);
5233            return Vec::new();
5234        }
5235    };
5236    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5237        runner.state.recovery_config = Some(config_evidence);
5238    }
5239    if let Some(replacement) = &task.replacement {
5240        if matches!(starter, Starter::Start) {
5241            runner.state.instruction.push_str(&format!(
5242                "\n\n# Replacement review context\n{}",
5243                replacement.context
5244            ));
5245        }
5246        runner.state.replaces = Some(replacement.clone());
5247        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5248        if let Ok(mut old) = RunState::load(&replacement.run)
5249            && let Some(d) = &mut old.merge_decision
5250        {
5251            d.replacement_run = Some(runner.state.id.clone());
5252            old.event(
5253                "replacement",
5254                format!(
5255                    "replacement run {} owns the next attempt; old PR remains closed",
5256                    runner.state.id
5257                ),
5258            );
5259            if let Err(e) = old.save() {
5260                let error = runner.fail_startup("replacement-history", e);
5261                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5262                    task.record_startup_failure(failure.clone());
5263                }
5264                task.hold_manual(Some(format!(
5265                    "Could not link replacement history: {error:#}; no agents dispatched"
5266                )));
5267                record(queue, task);
5268                return Vec::new();
5269            }
5270        }
5271    }
5272    runner.state.task_instruction = Some(task.instruction.clone());
5273    // The follow-up depth is fixed now, while the task certainly exists:
5274    // deleting it later must not reset the cap (`crate::followup`).
5275    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5276    if runner.state.origin_chat.is_none() {
5277        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5278    }
5279    // A stop that means "park" reaches the graph through this handle.
5280    runner.on_pause(stop.pause());
5281    // `poll`'s interrupt scheduler reaches this one run - and no other -
5282    // through this handle. See `Pause`'s own doc for why these are never
5283    // the same one.
5284    runner.watch_interrupt(interrupt_pause);
5285
5286    // `start` has minted the run, so the task can now point at it. Persisting
5287    // `Running` before `execute` is what makes a crash mid-run legible.
5288    let run = runner.state.id.clone();
5289    let before_start = task.clone();
5290    task.start(run.clone());
5291    if let Err(error) = queue.put(task) {
5292        *task = before_start;
5293        let error = runner.fail_startup("task-start", error);
5294        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5295            task.record_startup_failure(failure.clone());
5296        }
5297        task.hold_manual(Some(format!(
5298            "Could not persist task start; no agents dispatched: {error:#}"
5299        )));
5300        record(queue, task);
5301        return Vec::new();
5302    }
5303    lock(status).current.push(Current {
5304        worker: None,
5305        task: task.id.clone(),
5306        run,
5307    });
5308
5309    // `RunState::quota` is the run's whole history across every resume, so
5310    // only what this execution added may arm the cooldown or earn a refund.
5311    let quota_before = runner.state.quota.clone();
5312    runner.state.carry_dispatched_resumes(task);
5313    runner.state.next_pass_task_entry = true;
5314    let result = runner.execute().await;
5315    finish_attempt(
5316        opts.max_attempts,
5317        queue,
5318        task,
5319        &runner.state,
5320        &quota_before,
5321        result,
5322    )
5323}
5324
5325/// Settle `task` after its run executed: the verdict, the diagnosis, the
5326/// supersession of earlier attempts and the save. Shared by the loop and by
5327/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5328/// Returns the quota losses this execution added to the run.
5329pub fn finish_attempt(
5330    max_attempts: usize,
5331    queue: &Queue,
5332    task: &mut Task,
5333    state: &RunState,
5334    quota_before: &[QuotaLoss],
5335    result: Result<()>,
5336) -> Vec<QuotaLoss> {
5337    let detail = match result {
5338        Ok(()) => describe(state),
5339        Err(e) => format!("{e:#}"),
5340    };
5341    let fresh = losses_this_attempt(quota_before, &state.quota);
5342    let verdict = Verdict {
5343        status: state.status,
5344        // A run that opened a pull request handed its work over, whatever the
5345        // gate then decided about merging it.
5346        left_pr: state.pr.is_some(),
5347        // Only a rate limit earns the task its attempt back - and only one
5348        // suffered now: a refund justified by a previous session's loss is
5349        // the same mistake as re-arming the cooldown from it. A stalled run
5350        // resumed without hitting quota again therefore spends its attempt,
5351        // like any other failure of the task's own.
5352        quota_hit: !fresh.is_empty(),
5353        // A run that parked was asked to stop; that is not a failure and must
5354        // not spend an attempt, or replacing the binary a few times would
5355        // exhaust a task's budget without an agent ever misbehaving.
5356        parked: state.parked,
5357        // A quota loss that left nothing viable is the same machine fact as a
5358        // `Stalled` quota loss; see `settle`'s doc table.
5359        no_viable_candidates: state.viable().is_empty(),
5360    };
5361    if let Some(replacement) = &state.replaces
5362        && let Some(pr) = &state.pr
5363        && let Ok(mut old) = RunState::load(&replacement.run)
5364        && let Some(d) = &mut old.merge_decision
5365    {
5366        d.replacement_pr = Some(pr.url.clone());
5367        let _ = old.save();
5368    }
5369    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5370    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5371        task.hold_unrequested_retry(Some(format!(
5372            "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.",
5373            task.short()
5374        )));
5375    }
5376    if task.status == TaskStatus::Done {
5377        supersede_prior_runs(task, &crate::run::home());
5378    }
5379    record(queue, task);
5380    tracing::info!(
5381        "task {} is {} after run {} ({})",
5382        task.short(),
5383        task.status.as_str(),
5384        state.short(),
5385        label(state.status)
5386    );
5387    fresh
5388}
5389
5390/// A task a hand-started run leaves runnable (failed with attempts to spare,
5391/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5392/// later must not spend agent calls on it. `magi task release` retries.
5393pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5394    // Parked work (including legacy Failed records with a parked run) is a
5395    // checkpoint or owner handoff, not an unrequested retry.
5396    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5397        && !awaiting_resume_with(task, RunState::load)
5398        // A run parked on the owner's word about a withheld PR title/body
5399        // resumes via `land_resume_state`, including review-only tasks that
5400        // `awaiting_resume_with` does not consider.
5401        && withheld_text_wait(task).is_none()
5402        && !(task.fresh_start && task.replacement.is_some())
5403    {
5404        let why = task.last_error.clone().map_or_else(
5405            || "the run did not finish".to_owned(),
5406            |e| format!("the run did not finish: {e}"),
5407        );
5408        task.hold_unrequested_retry(Some(format!(
5409            "{why}. It was started by hand, so it is not retried \
5410             automatically; `magi task release` retries it."
5411        )));
5412        record(queue, task);
5413    }
5414}
5415
5416/// Whether an attempt at a task whose newest run is `run` would resume that
5417/// run rather than start a fresh competition. `magi run --resume` hands a run
5418/// to a live loop only when this holds.
5419#[must_use]
5420pub fn loop_would_resume(run: &str) -> bool {
5421    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5422}
5423
5424/// A loop in another process that is alive right now: a fresh heartbeat in
5425/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5426/// carries the pid it published (`None` inside when it published none - a
5427/// fresh heartbeat is still evidence of a live loop).
5428///
5429/// The one judgement of "is somebody else serving this queue", shared by the
5430/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5431/// deciding whether to hand a task to the loop. A claim file proves nothing
5432/// here: whether a claim succeeds says nothing about whether its owner lives.
5433#[must_use]
5434pub fn foreign_loop(
5435    reading: Option<&Reading>,
5436    now: Timestamp,
5437    own_pid: u32,
5438) -> Option<Option<u32>> {
5439    let reading = reading.filter(|r| r.running(now))?;
5440    match reading.pid {
5441        Some(pid) if pid == own_pid => None,
5442        pid => Some(pid),
5443    }
5444}
5445
5446fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5447    reading.worker_protocol != Some(1)
5448        && (foreign_loop(Some(reading), now, own_pid).is_some()
5449            || reading
5450                .pid
5451                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5452}
5453
5454/// Low-level claimed-task execution shared by the detached standalone worker
5455/// and focused lifecycle fixtures. The caller must retain the queue claim for
5456/// this entire call. CLI callers transfer ownership through
5457/// [`run_detached_claimed`] instead of executing inside their own runtime.
5458///
5459/// The one deliberate difference from the loop: a task the attempt leaves
5460/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5461/// Nobody asked for a retry, and a daemon starting later must not spend agent
5462/// calls re-running a hand-started task behind the operator's back;
5463/// `magi task release` is the explicit retry.
5464pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5465    run_claimed_until(opts, queue, task, &Stop::new()).await;
5466}
5467
5468async fn run_claimed_until(
5469    opts: &Opts,
5470    queue: &Queue,
5471    task: &mut Task,
5472    stop: &Stop,
5473) -> Vec<QuotaLoss> {
5474    let status = Arc::new(Mutex::new(Status::new()));
5475    // An attempt embeds startup and graph futures. Keep it off the standalone
5476    // caller's stack, on both the initial execution and withheld-text resume.
5477    let mut quota = Box::pin(attempt(
5478        opts,
5479        queue,
5480        &status,
5481        stop,
5482        crate::graph::Pause::new(),
5483        task,
5484    ))
5485    .await;
5486    // A run parked on the owner's word about a withheld PR title/body has no
5487    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5488    // here with the claim still held, and resume once the question is settled
5489    // (answered, or abandoned at its deadline -> the neutral text).
5490    // A rejected reply files one more question (the gate asks at most twice),
5491    // so after a resume the run may be waiting again: keep going, with a fresh
5492    // limit for the new question. `resumes` bounds it even if a resume parks
5493    // without asking anything new.
5494    let mut resumes = 0;
5495    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5496        let Some(timeout) = withheld_text_wait(task) else {
5497            break;
5498        };
5499        eprintln!(
5500            "waiting for the owner's answer on a withheld pull request text \
5501             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5502        );
5503        // The deadline abandons the question itself; the extra margin only
5504        // covers an abandon that could not be saved.
5505        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5506        let ready = loop {
5507            match land_resume_state(task) {
5508                LandResume::StillWaiting
5509                    if !stop.parking() && std::time::Instant::now() < limit =>
5510                {
5511                    tokio::time::sleep(WITHHELD_POLL).await;
5512                }
5513                LandResume::Ready => break true,
5514                _ => break false,
5515            }
5516        };
5517        if !ready || stop.parking() {
5518            break;
5519        }
5520        resumes += 1;
5521        quota.extend(
5522            Box::pin(attempt(
5523                opts,
5524                queue,
5525                &status,
5526                stop,
5527                crate::graph::Pause::new(),
5528                task,
5529            ))
5530            .await,
5531        );
5532    }
5533    hold_if_runnable(queue, task);
5534    quota
5535}
5536
5537/// Resumes an in-process run makes for withheld-text questions: the gate asks
5538/// at most twice, plus one for a resume that asks nothing new.
5539const MAX_WITHHELD_RESUMES: u32 = 3;
5540
5541/// How often an in-process run rechecks its withheld-text question.
5542const WITHHELD_POLL: Duration = Duration::from_secs(15);
5543
5544/// The `answer_timeout` (seconds) of the task's last run when that run is
5545/// parked on an unresolved withheld-text question; `None` otherwise.
5546fn withheld_text_wait(task: &Task) -> Option<u64> {
5547    let id = task.execution_runs().last()?;
5548    let s = RunState::load(id).ok()?;
5549    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5550        .then_some(s.config.graph.answer_timeout)
5551}
5552
5553/// The quota losses `after` holds that `before` did not: what one execution
5554/// suffered, as opposed to the run's history.
5555///
5556/// Compared by value rather than by length or position because
5557/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5558/// the vector can shrink and shift under a resume. A retried seat that hits
5559/// quota again is a `push` with a new `at`, so it shows up as new here.
5560/// Crash recovery uses the recorded pass start as its boundary when available;
5561/// legacy records without passes retain their original history-based policy.
5562fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5563    after
5564        .iter()
5565        .filter(|q| !before.contains(q))
5566        .cloned()
5567        .collect()
5568}
5569
5570/// When the loop-wide quota cooldown should end, given this attempt's losses;
5571/// `None` when there were none. Reset-hint parsing and the cap live here.
5572fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5573    let quota: Vec<_> = quota
5574        .iter()
5575        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5576        .collect();
5577    if quota.is_empty() {
5578        return None;
5579    }
5580    let with_hint = quota.iter().find(|q| q.reset.is_some());
5581    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5582    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5583    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5584    Some(
5585        now.checked_add(jiff::SignedDuration::from_secs(secs))
5586            .unwrap_or(Timestamp::MAX),
5587    )
5588}
5589
5590/// An explicit task count must agree with a run before any resume.
5591fn implementers_match(task: &Task, state: &RunState) -> bool {
5592    task.replacement.as_ref().map_or_else(
5593        || {
5594            task.implementers()
5595                .is_none_or(|n| n == state.config.graph.implementers)
5596        },
5597        |replacement| {
5598            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5599                && state.config.graph.implementers == 1
5600        },
5601    )
5602}
5603
5604/// Never resume or take over candidate work built for a different seat count.
5605fn starter_with_implementers(
5606    task: &Task,
5607    previous: Option<&RunState>,
5608    proposed: Starter,
5609) -> Starter {
5610    if previous.is_some_and(|s| !implementers_match(task, s)) {
5611        task.review_of
5612            .as_ref()
5613            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5614    } else {
5615        proposed
5616    }
5617}
5618
5619/// Apply this task's explicit count to the new attempt, without changing defaults.
5620fn apply_task_implementers(config: &mut Config, task: &Task) {
5621    if let Some(n) = task.implementers() {
5622        config.graph.implementers = n;
5623    }
5624}
5625
5626/// [`prepare`] for one task: its own `--config` and command-line overrides
5627/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5628/// over the loop's, so handing a hand-started task to a daemon changes nothing
5629/// about what it does.
5630#[cfg(test)]
5631fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5632    let explicit = match &task.overrides {
5633        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5634        _ => opts.config.as_deref(),
5635    };
5636    let (mut config, _) = Config::discover(repo, explicit)?;
5637    apply_options(&mut config, opts, task)?;
5638    Ok(config)
5639}
5640
5641fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5642    if task
5643        .overrides
5644        .as_ref()
5645        .is_none_or(|o| o.inherit_daemon_options)
5646        && let Some(mode) = opts.merge.as_deref()
5647    {
5648        config.merge.mode = merge_mode(mode)?;
5649    }
5650    if let Some(o) = &task.overrides {
5651        o.apply(config);
5652    }
5653    Ok(())
5654}
5655
5656/// Load the config for a task's repository, with the merge override applied.
5657fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5658    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5659    if let Some(mode) = &opts.merge {
5660        config.merge.mode = merge_mode(mode)?;
5661    }
5662    Ok(config)
5663}
5664
5665/// Prune the shared build cache at a between-runs boundary. The detached cache
5666/// service checks authoritative task jobs first; dispatch waits for that finite
5667/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5668/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5669async fn maybe_prune_cache_between_runs(
5670    repo: &Path,
5671    opts: &Opts,
5672    home: &Path,
5673    stop: &Stop,
5674    last_checked: &mut Option<Timestamp>,
5675    now: Timestamp,
5676) {
5677    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5678        return;
5679    }
5680    *last_checked = Some(now);
5681    let cfg = match prepare(repo, opts) {
5682        Ok(cfg) => cfg,
5683        Err(e) => {
5684            tracing::warn!("cache check: no config: {e:#}");
5685            return;
5686        }
5687    };
5688    match clean::prune_cache_if_over_limit(&cfg, home) {
5689        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5690            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5691            pruned.files,
5692            pruned.freed
5693        ),
5694        Ok(_) => {}
5695        Err(e) => {
5696            tracing::warn!("housekeep: prune cache: {e:#}");
5697            notices::raise_in(
5698                home,
5699                Notice::warn(
5700                    "housekeep:cache",
5701                    format!(
5702                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5703                        e.to_string()
5704                            .lines()
5705                            .next()
5706                            .unwrap_or("unknown cleanup error")
5707                    ),
5708                ),
5709            );
5710        }
5711    }
5712}
5713
5714/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5715/// now, given when it last did (if ever). Pure, so the cadence is asserted
5716/// directly rather than by waiting out real minutes in a test.
5717fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5718    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5719}
5720
5721/// The disk janitor, with its housekeeping logged rather than fatal.
5722///
5723/// Called only at the loop's idle points, for the reason the caller documents:
5724/// a prune racing a live compile would delete files mid-build. The config is
5725/// re-read on every call because the repository that just ran may not be the
5726/// daemon's own default, and the cache directory is a repository fact.
5727///
5728/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5729/// and [`crate::run::default_worktree_root`] read here, for the same reason
5730/// [`drive`] takes its queue and status file rather than resolving them: a
5731/// test driving the loop must not reach through to the operator's real home
5732/// or worktree bay just because the janitor runs on every idle tick.
5733/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5734/// to get wrong silently - a test's `home` was already isolated, but nothing
5735/// exercised the parameter next to it, so a real worktree bay stayed wired in
5736/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5737/// it for real, every test in this file that drives the loop at all started
5738/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5739async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5740    let cfg = match prepare(repo, opts) {
5741        Ok(cfg) => cfg,
5742        Err(e) => {
5743            tracing::warn!("housekeep: no config: {e:#}");
5744            return;
5745        }
5746    };
5747    // A run's own worktree lives under `config.graph.worktree_root` when the
5748    // repository sets one - the same precedence `RunState::worktree_root`
5749    // uses - and `worktrees_root` only stands in for the *default* an
5750    // unconfigured repository resolves to (see this function's own
5751    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5752    // that always swept the default regardless of this override would never
5753    // see, and so never reclaim, a single worktree for a repository that
5754    // relocated them elsewhere.
5755    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5756    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5757    // Reported whenever there is anything to say, not only when `folded > 0`:
5758    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5759    // folded, on every single pass, for months - a report gated on `folded`
5760    // would have stayed silent through every one of them.
5761    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5762        let mut extra = Vec::new();
5763        if out.unreadable > 0 {
5764            extra.push(format!("{} unreadable", out.unreadable));
5765        }
5766        if out.orphaned_worktrees > 0 {
5767            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5768        }
5769        let detail = if extra.is_empty() {
5770            String::new()
5771        } else {
5772            format!(" ({})", extra.join(", "))
5773        };
5774        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5775    }
5776    if out.external_merges_recorded > 0 {
5777        tracing::info!(
5778            "housekeep: recorded {} run(s) as merged externally",
5779            out.external_merges_recorded
5780        );
5781    }
5782    if out.stale_pr_states_repaired > 0 {
5783        tracing::info!(
5784            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5785            out.stale_pr_states_repaired
5786        );
5787    }
5788    if out.cache_files > 0 {
5789        tracing::info!(
5790            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5791            out.cache_files,
5792            out.cache_freed
5793        );
5794    }
5795    if out.questions_abandoned > 0 {
5796        tracing::info!(
5797            "housekeep: abandoned {} question(s) left open by a finished run",
5798            out.questions_abandoned
5799        );
5800    }
5801}
5802
5803/// Run [`triage::run_once`] and log whatever it did, the same "only when
5804/// there is something to say" rule [`janitor`] follows for its own report.
5805///
5806/// Called at the same idle points as [`janitor`] - once per full poll
5807/// interval, never mid-attempt - for the same reason: it is not liveness
5808/// critical, and a task's own `hold_reason` string is the one thing this
5809/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5810/// tick for no benefit.
5811async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5812    let questions = Questions::at(home.join("questions"));
5813    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5814    if report.is_empty() {
5815        return;
5816    }
5817    if !report.quarantined.is_empty() {
5818        tracing::info!(
5819            "triage: held {} blocked task(s) whose blocked-on task or \
5820             question no longer exists: {}",
5821            report.quarantined.len(),
5822            report.quarantined.join(", ")
5823        );
5824    }
5825    if !report.resumed.is_empty() {
5826        tracing::info!(
5827            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5828            report.resumed.len(),
5829            report.resumed.join(", ")
5830        );
5831    }
5832    if !report.asked.is_empty() {
5833        tracing::info!(
5834            "triage: asked about {} held task(s): {}",
5835            report.asked.len(),
5836            report.asked.join(", ")
5837        );
5838    }
5839    if !report.answered.is_empty() {
5840        tracing::info!(
5841            "triage: applied {} operator answer(s): {}",
5842            report.answered.len(),
5843            report.answered.join(", ")
5844        );
5845    }
5846}
5847
5848/// The free-space gate: what stands between this task and a new run, if
5849/// anything. `Some(reason)` holds the task; `None` lets it start.
5850///
5851/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5852/// the operator opted out. A measurement failure is a gate, not a pass: both
5853/// sides of "cannot tell" are served by not starting.
5854pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5855    disk_gate_with(repo, config, crate::disk::free_bytes)
5856}
5857
5858/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5859/// test can assert the exact wiring `attempt` runs - config's threshold in,
5860/// task-holding reason out - without asking the real machine's disk anything.
5861fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5862    repo: &Path,
5863    config: &Config,
5864    free_bytes: F,
5865) -> Option<String> {
5866    let min = config.disk.min_free_bytes;
5867    if min == 0 {
5868        return None;
5869    }
5870    let mut paths = vec![repo.to_owned()];
5871    if let Some(cache) = config.cache_dir() {
5872        paths.push(cache);
5873    }
5874    paths.push(
5875        config
5876            .graph
5877            .worktree_root
5878            .clone()
5879            .unwrap_or_else(crate::run::default_worktree_root),
5880    );
5881    for path in paths {
5882        let probe = if path == repo {
5883            path.as_path()
5884        } else {
5885            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5886        };
5887        let reason = match free_bytes(probe) {
5888            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5889            Err(e) => Some(crate::disk::unmeasured_in(
5890                probe,
5891                &e,
5892                &config.graph.language,
5893            )),
5894        };
5895        if reason.is_some() {
5896            return reason;
5897        }
5898    }
5899    None
5900}
5901
5902/// How long to wait before offering another task when a run lost a seat to a
5903/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5904/// could read, or carried nothing at all. Long enough that a quota outage
5905/// cannot burn through a whole backlog in the few seconds each doomed attempt
5906/// takes to fail; short enough that a quota which clears early is not left
5907/// idle for the fallback's sake.
5908const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5909
5910/// Longest a parsed reset hint may push the wait out to. The hint comes from
5911/// the CLI's own words, not a contract, so a parsing slip that lands a day
5912/// away must not leave the loop asleep for a day.
5913const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5914
5915/// How long [`poll`] should wait before offering the next task, after a run
5916/// lost at least one seat to a rate limit.
5917///
5918/// Pure and separate from the loop so the policy can be exercised without a
5919/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5920/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5921/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5922/// far a parsed hint is trusted to push the wait out.
5923fn quota_wait(
5924    reset_at: Option<Timestamp>,
5925    now: Timestamp,
5926    fallback: Duration,
5927    cap: Duration,
5928) -> Duration {
5929    match reset_at {
5930        Some(at) if at > now => {
5931            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5932            Duration::from_secs(secs).min(cap)
5933        }
5934        _ => fallback,
5935    }
5936}
5937
5938/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5939///
5940/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5941/// explains why parsing it exactly "would be a bug factory" — so this only
5942/// recognises the shapes actually observed in the wild, and returns `None`
5943/// for anything else rather than guess at a format nobody has seen.
5944///
5945/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5946/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5947/// said it, not from whenever this loop happens to read it: anchoring on `now`
5948/// would push the reset later on every read and would read an already-elapsed
5949/// reset as still in the future. (A long hint is still clamped by
5950/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5951fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5952    parse_reset_hint_zoned(text, now)
5953        .or_else(|| parse_reset_hint_dated(text))
5954        .or_else(|| parse_reset_hint_relative(text, recorded))
5955}
5956
5957/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5958/// optional but at least one required, in that order. A bare number or any
5959/// unknown unit is refused.
5960fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5961    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5962    let mut rest = rest.trim();
5963    if rest.is_empty() {
5964        return None;
5965    }
5966    let mut total: i64 = 0;
5967    let mut matched = false;
5968    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5969        if let Some((digits, tail)) = rest.split_once(unit)
5970            && !digits.is_empty()
5971            && digits.bytes().all(|b| b.is_ascii_digit())
5972        {
5973            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5974            rest = tail;
5975            matched = true;
5976        }
5977    }
5978    if !rest.is_empty() || !matched {
5979        return None;
5980    }
5981    recorded
5982        .checked_add(jiff::SignedDuration::from_secs(total))
5983        .ok()
5984}
5985
5986/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5987/// case-insensitive) into a 24-hour hour and minute. Shared by every
5988/// reset-hint shape below.
5989fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5990    let clock = clock.trim().to_lowercase();
5991    let (digits, pm) = clock
5992        .strip_suffix("am")
5993        .map(|d| (d, false))
5994        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5995    let (h, m) = digits.trim().split_once(':')?;
5996    let mut hour: i8 = h.trim().parse().ok()?;
5997    let minute: i8 = m.trim().parse().ok()?;
5998    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5999        return None;
6000    }
6001    if pm && hour != 12 {
6002        hour += 12;
6003    } else if !pm && hour == 12 {
6004        hour = 0;
6005    }
6006    Some((hour, minute))
6007}
6008
6009/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
6010/// and a zone, never a date. A clock reading already past today is read as
6011/// tomorrow's: a CLI naming a same-day reset that has already gone by means
6012/// the window rolled over while nothing was watching.
6013fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6014    let open = text.find('(')?;
6015    let close = text.rfind(')')?;
6016    if close <= open {
6017        return None;
6018    }
6019    let zone = text[open + 1..close].trim();
6020    let (hour, minute) = parse_12h_clock(&text[..open])?;
6021    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6022    let candidate = now
6023        .to_zoned(tz)
6024        .with()
6025        .hour(hour)
6026        .minute(minute)
6027        .second(0)
6028        .millisecond(0)
6029        .microsecond(0)
6030        .nanosecond(0)
6031        .build()
6032        .ok()?;
6033    let mut at = candidate.timestamp();
6034    if at <= now {
6035        at += jiff::SignedDuration::from_hours(24);
6036    }
6037    Some(at)
6038}
6039
6040/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6041/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6042/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6043/// "already past today" correction to make: the year already disambiguates
6044/// it. Scanned as a five-word window so it can be pulled out of the middle
6045/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6046/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6047/// any other timestamp with no zone attached.
6048fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6049    let words: Vec<&str> = text.split_whitespace().collect();
6050    if words.len() < 5 {
6051        return None;
6052    }
6053    (0..=words.len() - 5)
6054        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6055}
6056
6057/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6058/// parenthesis right after the window is refused rather than ignored — it
6059/// reads as an explicit zone annotation on a shape that otherwise carries
6060/// none, and guessing UTC anyway would be exactly the silent misread this
6061/// module's parsing otherwise avoids.
6062fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6063    if trailing.is_some_and(|next| next.starts_with('(')) {
6064        return None;
6065    }
6066    let month = month_number(window[0])?;
6067    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6068    let day_digits = ["st", "nd", "rd", "th"]
6069        .iter()
6070        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6071    let day: i8 = day_digits.parse().ok()?;
6072    let year_token = window[2];
6073    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6074        return None;
6075    }
6076    let year: i16 = year_token.parse().ok()?;
6077    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6078    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6079    // reusing the same 12-hour clock reader the bracketed shape uses.
6080    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6081    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6082    let date = jiff::civil::Date::new(year, month, day).ok()?;
6083    let candidate = date
6084        .at(hour, minute, 0, 0)
6085        .to_zoned(jiff::tz::TimeZone::UTC)
6086        .ok()?;
6087    Some(candidate.timestamp())
6088}
6089
6090/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6091/// case-insensitively, into a 1-based month number.
6092fn month_number(name: &str) -> Option<i8> {
6093    const NAMES: [&str; 12] = [
6094        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6095    ];
6096    let lower = name.to_lowercase();
6097    NAMES
6098        .iter()
6099        .position(|n| *n == lower.as_str())
6100        .map(|i| i as i8 + 1)
6101}
6102
6103/// Test probe for the shared resume policy's review-budget exclusion.
6104#[cfg(test)]
6105fn exhausted_review_budget(state: &RunState) -> bool {
6106    // A run whose task-head publication failed has nothing left to review:
6107    // resuming it only retries the publication, so it is never "exhausted".
6108    !crate::handover::can_resume(state)
6109        && state.status == RunStatus::Blocked
6110        && !state.released()
6111        && state.retired_to.is_none()
6112}
6113
6114/// This task's *most recent* run, if resuming it would actually make
6115/// progress. `short` is only for the warning's own message.
6116///
6117/// Only ever `runs.last()` — never a search back through older history.
6118/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6119/// mint, oldest first, and every entry before the last one was already
6120/// superseded at the moment it was minted: the daemon only ever starts a new
6121/// run when the previous one was not worth resuming (unresumable, exhausted,
6122/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6123/// opens a fresh review-only run alongside an older, already-failed
6124/// competition. Searching further back would let an old run that merely
6125/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6126/// behind, say — get resumed instead of the fresh competition
6127/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6128/// nothing asked to revisit.
6129///
6130/// Two runs paid for the "prefer resuming over restarting" half of this
6131/// lesson, which is why this still checks `runs.last()` rather than always
6132/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6133/// task a moment later, duplicating two and a half hours of agent work. Then
6134/// b25f stalled on a judge that timed out and one that answered with no JSON
6135/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6136/// **one second** later, buying three fresh implementations to reach the
6137/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6138/// the second case: a stall is terminal, and its cheap recovery re-asks only
6139/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6140/// that is technically `resumable()` but provably cannot progress must not
6141/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6142/// no-op instead of the fresh competition it promises.
6143///
6144/// A load failure is warned about rather than silently read as "not
6145/// resumable": the alternative is exactly what let a schema mismatch on run
6146/// `eba2` fall through to a full re-competition with nobody told why.
6147/// `crate::conduct` is what actually offers a better answer than
6148/// `Runner::start` here (see `Recovery::Review`), once this task's next
6149/// failure shows it up as `held`/`failed` with the run state unreadable.
6150fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6151    unfinished_run_with(runs, short, RunState::load)
6152}
6153
6154/// [`unfinished_run`] with an injected state reader. Tests provide their
6155/// fixtures directly rather than touching the process-global run home.
6156pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6157where
6158    F: FnMut(&str) -> Result<RunState>,
6159{
6160    let mut id = runs.last()?.clone();
6161    let mut visited = std::collections::BTreeSet::new();
6162    let mut repo = None;
6163    loop {
6164        if !runs.contains(&id) || !visited.insert(id.clone()) {
6165            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6166            return None;
6167        }
6168        let state = match load(&id) {
6169            Ok(state) if state.id == id => state,
6170            Ok(_) => return None,
6171            Err(e) => {
6172                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6173                return None;
6174            }
6175        };
6176        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6177            return None;
6178        }
6179        repo = Some(state.repo.clone());
6180        if let Some(authority) = state.retired_to {
6181            id = authority;
6182            continue;
6183        }
6184        return (crate::handover::can_resume(&state)
6185            && state.liveness(false) != crate::run::Liveness::Live)
6186            .then_some(id);
6187    }
6188}
6189
6190/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6191/// that [`attempt`] will resume it on its own?
6192///
6193/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6194/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6195/// injected reader like its sibling. An unreadable run is not awaiting
6196/// anything: it keeps going to the conductor as before.
6197fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6198where
6199    F: FnOnce(&str) -> Result<RunState>,
6200{
6201    // `Failed` stays: a record an older build wrote for a parked run.
6202    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6203        || task.fresh_start
6204        || task.review_branch.is_some()
6205    {
6206        return false;
6207    }
6208    let Some(id) = task.execution_runs().last() else {
6209        return false;
6210    };
6211    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6212}
6213
6214/// Which of the three ways [`attempt`] can mint or continue a run this task
6215/// should use.
6216#[derive(Debug, Clone, PartialEq, Eq)]
6217enum Starter {
6218    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6219    /// and that still exists.
6220    Review(String),
6221    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6222    Resume(String),
6223    /// `crate::graph::Runner::start`: a fresh competition.
6224    Start,
6225}
6226
6227/// A second bound independent of inputs and the resettable failure counter.
6228/// Count execution and failed-startup recovery records once per run. Startup
6229/// failures can retain unrecorded preparation assets without an execution pass.
6230/// Unknown history is not evidence that a new set of worktrees is affordable.
6231fn retained_attempt_hold(
6232    task: &Task,
6233    starter: &Starter,
6234    limit: usize,
6235    mut load: impl FnMut(&str) -> Result<RunState>,
6236) -> Option<String> {
6237    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6238        return None;
6239    }
6240    let mut retained = 0;
6241    for id in task
6242        .runs
6243        .iter()
6244        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6245        .collect::<std::collections::BTreeSet<_>>()
6246    {
6247        let state = match load(id) {
6248            Ok(state) if state.id == *id => state,
6249            _ => {
6250                return Some(format!(
6251                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6252                ));
6253            }
6254        };
6255        if state.retired_to.is_some() || state.released() {
6256            continue;
6257        }
6258        // Neither a completed status nor an empty candidate array proves that
6259        // all recovery sources (including unrecorded preparation) were retired.
6260        retained += 1;
6261    }
6262    (retained >= limit).then(|| format!(
6263        "[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."
6264    ))
6265}
6266
6267/// A selected public implementation overrides every historical candidate and pin.
6268fn selected_starter(
6269    selected: &crate::pr_recovery::Selection,
6270    previous: Option<&RunState>,
6271    unfinished: Option<&str>,
6272) -> Starter {
6273    if let Some(id) = unfinished
6274        && previous.is_some_and(|r| {
6275            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6276        })
6277    {
6278        Starter::Resume(id.to_owned())
6279    } else {
6280        Starter::Review(selected.branch.clone())
6281    }
6282}
6283
6284/// The owner's answer to this branch's divergence question, consumed from the
6285/// task so a later, different divergence asks again. The runner applies it
6286/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6287fn take_divergence_answer(
6288    branch: &str,
6289    remote: &str,
6290    task: &mut Task,
6291) -> Option<crate::reconcile::Choice> {
6292    let summary = crate::reconcile::summary_for(branch, remote);
6293    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6294        (a.question == summary)
6295            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6296            .flatten()
6297            .map(|c| (i, c))
6298    })?;
6299    task.answers.remove(idx);
6300    Some(choice)
6301}
6302
6303/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6304/// this attempt should use. Pure, and separate from [`attempt`], so the
6305/// routing itself is assertable without spawning a real graph or a git
6306/// process: `attempt`'s own `crate::git::branch_exists` call has already
6307/// happened by the time this is called.
6308///
6309/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6310/// whose branch is gone falls all the way through to [`Starter::Start`], not
6311/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6312/// old (likely `Blocked`) run in the first place, and a branch that vanished
6313/// out from under that choice is not evidence resuming it would fare better.
6314fn choose_starter(
6315    review_branch: Option<&str>,
6316    branch_exists: bool,
6317    unfinished: Option<&str>,
6318) -> Starter {
6319    match review_branch {
6320        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6321        Some(_) => Starter::Start,
6322        None => match unfinished {
6323            Some(id) => Starter::Resume(id.to_owned()),
6324            None => Starter::Start,
6325        },
6326    }
6327}
6328
6329/// Reuse a compatible latest review owner instead of taking its checked-out
6330/// branch into a new run. Different branches and changed criteria still use
6331/// the ordinary review/takeover policy.
6332fn review_retry_starter(
6333    task: &Task,
6334    previous: Option<&RunState>,
6335    branch: Option<&str>,
6336    exists: bool,
6337    unfinished: Option<&str>,
6338) -> Starter {
6339    if let Some(run) = previous
6340        && unfinished == Some(run.id.as_str())
6341        && run.reviewed_commits.is_some()
6342        && branch.is_some_and(|branch| {
6343            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6344        })
6345        && may_resume_run(run, task)
6346    {
6347        return Starter::Resume(run.id.clone());
6348    }
6349    match (branch, unfinished, &task.review_of) {
6350        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6351        _ => choose_starter(branch, exists, unfinished),
6352    }
6353}
6354
6355/// Consume a retained review only while its authored criteria still match.
6356fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
6357    let branch = task.review_branch.take();
6358    let instruction = task.review_instruction.take();
6359    branch.filter(|branch| match &instruction {
6360        Some(authored) => *authored == task.instruction,
6361        // Legacy retained branches must agree with their prior run; only an
6362        // explicitly pinned review can proceed without recoverable provenance.
6363        None => previous.map_or_else(
6364            || task.review_of.as_ref() == Some(branch),
6365            |run| compatible_run_instruction(run, task),
6366        ),
6367    })
6368}
6369
6370/// A current explicit pin can select an otherwise incompatible run. Edits
6371/// and subsequent approvals invalidate pins selected for earlier criteria.
6372fn may_resume_run(run: &RunState, task: &Task) -> bool {
6373    if !task.assignment_accepts(run) {
6374        return false;
6375    }
6376    task.resume_override
6377        .as_ref()
6378        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6379        || compatible_run_instruction(run, task)
6380}
6381
6382/// Review scaffolding is execution context, not evidence of an operator edit.
6383pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6384    if let Some(authored) = &run.task_instruction {
6385        return compatible_instruction(authored, task);
6386    }
6387    if compatible_instruction(&run.instruction, task) {
6388        return true;
6389    }
6390    // Recognize only the existing generated review shapes on legacy runs.
6391    // Ordinary authored text with a similar heading is left intact.
6392    if run.reviewed_commits.is_some() {
6393        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6394            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6395        }
6396        if let Some(branch) = &task.review_of {
6397            let canonical = format!(
6398                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6399            );
6400            let generated = format!(
6401                "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"
6402            );
6403            return task.instruction == canonical && run.instruction.starts_with(&generated);
6404        }
6405    }
6406    false
6407}
6408
6409/// Compare authored instructions, excluding answer blocks appended by the daemon.
6410pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6411    strip_answers_block(old, task) == task.instruction
6412}
6413
6414/// Which repository a task runs in. A task that names none — the normal case
6415/// for one filed from a phone — runs in the daemon's own default.
6416fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6417    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6418        return fallback.to_path_buf();
6419    }
6420    task.repo.clone()
6421}
6422
6423/// The header [`append_answers`] appends operator answers under. Shared with
6424/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6425/// rather than grown a new block on every resume.
6426const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6427
6428/// Render the first `count` answers in the block appended to an instruction.
6429fn answers_block(task: &Task, count: usize) -> String {
6430    let mut s = ANSWERS_HEADER.to_owned();
6431    for a in &task.answers[..count] {
6432        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6433    }
6434    s
6435}
6436
6437/// Render the approval independently of transient task state, so historical
6438/// suffixes remain recognizable after another explicit release.
6439fn resumption_block(r: &crate::queue::Resumption) -> String {
6440    format!(
6441        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6442         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6443        r.generation, r.at, r.instruction, r.answers_through,
6444    )
6445}
6446
6447/// Append audit answers and the latest explicit approval to the instruction.
6448fn append_answers(base: &str, task: &Task) -> String {
6449    let mut s = base.to_owned();
6450    if !task.answers.is_empty() {
6451        s.push_str(&answers_block(task, task.answers.len()));
6452    }
6453    if let Some(r) = &task.resumption {
6454        s.push_str(&resumption_block(r));
6455    }
6456    s
6457}
6458
6459/// Drop the prior answer block only when it is exactly the suffix this task
6460/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6461/// the task author is ordinary instruction text, not a block to remove.
6462fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6463    let mut instruction = instruction;
6464    for approval in task
6465        .resumption
6466        .iter()
6467        .chain(task.resumption_history.iter().rev())
6468    {
6469        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6470            instruction = base;
6471            break;
6472        }
6473    }
6474    for count in (1..=task.answers.len()).rev() {
6475        let block = answers_block(task, count);
6476        if let Some(base) = instruction.strip_suffix(&block) {
6477            return base;
6478        }
6479    }
6480    instruction
6481}
6482
6483/// The instruction handed to `Runner::start`: the task's own text, plus any
6484/// operator answers `crate::conduct` collected for it (see
6485/// [`Task::answers`]), so a decision the operator actually made reaches the
6486/// implementers rather than only clearing the block that was waiting on it.
6487///
6488/// Appended rather than merged into [`Task::instruction`] itself, so the
6489/// task's own record stays exactly what its author wrote.
6490fn instruction_for(task: &Task) -> String {
6491    append_answers(&task.instruction, task)
6492}
6493
6494/// The instruction a resumed run should carry on with: whatever it already
6495/// had, refreshed with the task's *current* operator answers.
6496///
6497/// A resumable run's own `RunState::instruction` predates any answer
6498/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6499/// the behaviour before this function existed — silently drops the very
6500/// decision the operator made to unblock it. Re-stripping any block this
6501/// function appended on an earlier resume before re-appending the current
6502/// list (rather than blindly appending again) is what keeps a task resumed
6503/// three times over three answered questions from carrying the same answer
6504/// three times.
6505fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6506    append_answers(strip_answers_block(old_instruction, task), task)
6507}
6508
6509/// Preserve the producer's verified boundary and target, independent of prose.
6510fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6511    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6512    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6513    if let Some(cause) = task.hold_notice_cause.as_mut() {
6514        cause.target = failure.map(|f| f.target.clone());
6515    }
6516}
6517
6518#[derive(Debug, thiserror::Error)]
6519#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6520struct MissingAttachment {
6521    name: String,
6522    path: PathBuf,
6523}
6524
6525/// The task's attachments as absolute paths, each checked to still exist.
6526fn task_attachments(
6527    queue: &Queue,
6528    task: &Task,
6529) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6530    let paths = queue.attachment_paths(task);
6531    for (name, path) in task.attachments.iter().zip(&paths) {
6532        if !path.is_file() {
6533            return Err(MissingAttachment {
6534                name: name.clone(),
6535                path: path.clone(),
6536            });
6537        }
6538    }
6539    Ok(paths)
6540}
6541
6542/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6543/// answers before handing it to `Runner` — the actual boundary between
6544/// [`choose_starter`]'s routing and the graph, factored out so it is
6545/// assertable without a real repository, git branch, or agent CLI.
6546///
6547/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6548/// instruction from the reviewed branch's own commit log because there is no
6549/// task statement to speak of for hand-written work, and splicing operator
6550/// answers into that text would contradict the very message it sends
6551/// reviewers ("there is no task statement").
6552fn prepare_instruction(
6553    starter: &Starter,
6554    old_instruction: Option<&str>,
6555    task: &Task,
6556) -> Option<String> {
6557    match starter {
6558        Starter::Start => Some(instruction_for(task)),
6559        Starter::Resume(_) => Some(resumed_instruction(
6560            old_instruction.expect("a resumed run always has a prior instruction"),
6561            task,
6562        )),
6563        Starter::Review(_) => None,
6564    }
6565}
6566
6567/// Persist a transition. A queue write failure is logged rather than fatal: the
6568/// run already happened, and taking the daemon down would only add a lost
6569/// backlog to a full disk.
6570fn record(queue: &Queue, task: &mut Task) {
6571    if let Err(e) = queue.put(task) {
6572        tracing::error!("could not record task {}: {e:#}", task.short());
6573        let notice = Notice::error(
6574            "loop:record",
6575            format!(
6576                "Task {} state could not be saved: {}. Check the disk.",
6577                task.id,
6578                e.to_string().lines().next().unwrap_or("unknown save error")
6579            ),
6580        )
6581        .link(Link::Task {
6582            id: task.id.clone(),
6583        });
6584        // The queue lives at `<home>/queue`, so its parent is the home.
6585        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6586            Some(home) => notices::raise_in(home, notice),
6587            None => notices::raise(notice),
6588        }
6589    }
6590}
6591
6592/// Every runnable task, in the order the loop should try them.
6593///
6594/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6595/// tail exists so that a claim somebody else holds costs the loop the next
6596/// candidate rather than a whole poll interval of idleness.
6597fn runnable(queue: &Queue) -> Vec<Task> {
6598    let mut tasks: Vec<Task> = queue
6599        .list()
6600        .into_iter()
6601        .filter(|t| t.status.runnable())
6602        .collect();
6603    tasks.sort_unstable_by(crate::queue::dispatch_order);
6604    tasks
6605}
6606
6607/// Why a run ended where it did, in one line, for [`Task::last_error`].
6608///
6609/// A stalled run names the seats the quota took out: "out of quota" is not
6610/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6611/// agent to replace or which plan to top up.
6612///
6613/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6614/// purpose: unlike `label`'s other callers (an internal log line, an
6615/// already-a-bug fallback message), this string becomes `Task::last_error`
6616/// verbatim, which the phone renders in the same alarm-styled box an
6617/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6618/// `.err` styling. A bare `verified_noop` there would read exactly like the
6619/// failure this whole feature exists to tell apart from one.
6620fn describe(state: &RunState) -> String {
6621    let p = phrases(&state.config.graph.language);
6622    let mut detail = if state.status == RunStatus::Stalled {
6623        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6624        seats.sort_unstable();
6625        seats.dedup();
6626        if seats.is_empty() {
6627            p.quorum_lost.to_owned()
6628        } else {
6629            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6630        }
6631    } else {
6632        format!("{}{}", p.run_ended, state.status.display_label())
6633    };
6634    if let Some(cause) = state.verification_blocking_cause() {
6635        detail.push_str(&format!(" ({cause})"));
6636    } else if let Some(last) = state.events.last() {
6637        // The review loop's "never answered" stop is the one event worth
6638        // translating; it is recognised from structured state, not by
6639        // matching the English event text (which stays as recorded).
6640        let unanswered = state
6641            .reviews
6642            .last()
6643            .filter(|r| {
6644                state.status == RunStatus::Blocked
6645                    && last.node == "review"
6646                    && r.incomplete()
6647                    && r.blocking == 0
6648                    && r.round == state.config.graph.review_rounds
6649                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6650            })
6651            .map(|r| (r.expected - r.answered, r.round));
6652        match unanswered {
6653            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6654                detail.push_str(&format!(
6655                    " ({}: {})",
6656                    last.node,
6657                    (p.reviewers_never_answered)(missing, rounds)
6658                ));
6659            }
6660            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6661        }
6662    }
6663    detail.push_str(&format!(" [run {}]", state.id));
6664    detail
6665}
6666
6667/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6668///
6669/// The task file lives in the backlog indefinitely; a diagnostic is an
6670/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6671/// stay small regardless of how much a gate command or a candidate printed.
6672const DIAGNOSTIC_MAX: usize = 4_000;
6673
6674/// Tail kept from a single failing command's output inside a diagnostic.
6675/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6676/// pointer for a human deciding whether to go read the full artifact by hand,
6677/// not a replacement for reading it.
6678const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6679
6680/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6681/// `magi task show` says more than the one-line reason in [`describe`].
6682///
6683/// The one-liner answers "where did the run stop"; this answers "what would a
6684/// human have found opening `artifacts/` by hand" — the point of the whole
6685/// feature is the case that one-liner actively misleads on: a run held as "no
6686/// candidate produced a change" can mean the implementer actually finished
6687/// the task (opened a PR, merged it, tagged a release) and only left a clean
6688/// local worktree behind, which reads as "nothing happened" unless someone
6689/// goes and reads what the agent actually said. `None` when the run carries
6690/// none of the three shapes this recognises — an ordinary run held for
6691/// something not diagnosable from `RunState` alone still explains itself
6692/// through `Task::last_error`.
6693fn diagnostic(state: &RunState) -> Option<String> {
6694    let mut parts: Vec<String> = Vec::new();
6695
6696    // Gate failure: which check(s), and the tail of what each printed.
6697    for o in state.gate.iter().filter(|o| !o.ok()) {
6698        parts.push(format!(
6699            "gate `{}` failed ({}):\n{}",
6700            o.command,
6701            notices::exit_status(o.code),
6702            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6703        ));
6704    }
6705
6706    // The land loop gave up because the fixer declined while checks were
6707    // still red: the message already names them (see `land::run`).
6708    if let Some(last) = state
6709        .events
6710        .iter()
6711        .rev()
6712        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6713    {
6714        parts.push(last.message.clone());
6715    }
6716
6717    // No viable candidate: every implementer's own final word, sanitized the
6718    // same way a judge would have read it, so a run that actually finished
6719    // the job does not read as an unexplained failure. A verified no-op is
6720    // called out ahead of its own summary and apart from an ordinary
6721    // failure's `why` — this is the one candidate shape whose diagnostic a
6722    // human is expected to actually judge, not just skim.
6723    if state.viable().is_empty() {
6724        for c in &state.candidates {
6725            if let Some(evidence) = &c.verified_noop {
6726                parts.push(format!(
6727                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6728                    c.label
6729                ));
6730            } else if !c.summary.trim().is_empty() {
6731                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6732            } else if let Some(why) = &c.failed {
6733                parts.push(format!("candidate {}: {why}", c.label));
6734            }
6735        }
6736    }
6737
6738    if parts.is_empty() {
6739        return None;
6740    }
6741    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6742    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6743    // back slightly over. Leave it enough room to always land under the
6744    // limit.
6745    Some(crate::run::tail(
6746        &parts.join("\n\n"),
6747        DIAGNOSTIC_MAX.saturating_sub(100),
6748    ))
6749}
6750
6751/// Stable lower-case name for a run status, for an internal log line and the
6752/// "graph stopped without reaching a terminal status" bug message in
6753/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6754/// doc for why that one reads [`RunStatus::display_label`] instead. One
6755/// definition of a status's name, on the type that owns it: this table used
6756/// to live here as a second copy, and a status renamed in one place would
6757/// have gone on reading correctly in the other.
6758fn label(status: RunStatus) -> &'static str {
6759    status.as_str()
6760}
6761
6762/// Parse a merge mode override.
6763pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6764    match mode {
6765        "none" => Ok(MergeMode::None),
6766        "local" => Ok(MergeMode::Local),
6767        "pr" => Ok(MergeMode::Pr),
6768        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6769    }
6770}
6771
6772/// Take the status lock, recovering from a poisoned one.
6773///
6774/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6775/// data, and the worst a poisoned lock can hold is a stale timestamp.
6776fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6777    mutex
6778        .lock()
6779        .unwrap_or_else(std::sync::PoisonError::into_inner)
6780}
6781
6782#[cfg(test)]
6783mod tests {
6784    use super::*;
6785    use crate::queue::{Source, TaskStatus};
6786    use crate::run::{Candidate, CommandOutcome};
6787    use pretty_assertions::assert_eq;
6788
6789    fn task() -> Task {
6790        Task::new(
6791            "add retries".to_owned(),
6792            "add retries".to_owned(),
6793            PathBuf::from("/repo"),
6794            Source::Human,
6795        )
6796    }
6797
6798    #[test]
6799    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
6800        let skips = DispatchSkips::from([
6801            ("a".into(), SkipReason::CoolingDown),
6802            ("b".into(), SkipReason::WaitingOnLanding),
6803            ("c".into(), SkipReason::WaitingOnLanding),
6804            ("d".into(), SkipReason::OrdinaryCapacity),
6805        ]);
6806        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
6807        assert_eq!(wait.runnable, 4);
6808        assert_eq!(
6809            wait.reasons
6810                .iter()
6811                .map(|r| (r.reason.as_str(), r.count))
6812                .collect::<Vec<_>>(),
6813            [
6814                ("waiting_on_landing", 2),
6815                ("cooling_down", 1),
6816                ("ordinary_capacity", 1)
6817            ]
6818        );
6819        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
6820        assert!(
6821            aggregate_dispatch_wait(2, &DispatchSkips::new())
6822                .unwrap()
6823                .reasons
6824                .is_empty()
6825        );
6826    }
6827
6828    #[test]
6829    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
6830        let before = vec!["a".into(), "b".into(), "c".into()];
6831        let allowed = vec![task_with_id("b")];
6832        let skips = interrupt_skips(&before, &allowed);
6833        assert_eq!(
6834            skips,
6835            DispatchSkips::from([
6836                ("a".into(), SkipReason::InterruptGate),
6837                ("c".into(), SkipReason::InterruptGate),
6838            ])
6839        );
6840        let mut previous = DispatchSkips::new();
6841        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
6842        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
6843        assert!(!changed_dispatch_skips(&mut previous, skips));
6844        assert!(changed_dispatch_skips(
6845            &mut previous,
6846            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
6847        ));
6848        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
6849    }
6850
6851    #[test]
6852    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
6853        let mut value = serde_json::to_value(Status::new()).unwrap();
6854        value.as_object_mut().unwrap().remove("dispatch_wait");
6855        assert!(
6856            serde_json::from_value::<Status>(value.clone())
6857                .unwrap()
6858                .dispatch_wait
6859                .is_none()
6860        );
6861        assert!(
6862            serde_json::from_value::<Reading>(value.clone())
6863                .unwrap()
6864                .dispatch_wait
6865                .is_none()
6866        );
6867        value["dispatch_wait"] = serde_json::json!({
6868            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
6869        });
6870        let reading = serde_json::from_value::<Reading>(value).unwrap();
6871        assert_eq!(
6872            reading.dispatch_wait.unwrap().reasons[0].reason,
6873            "future_reason"
6874        );
6875    }
6876
6877    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6878        let job = crate::worker::Job {
6879            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6880            sequence: 1,
6881            kind: "task".into(),
6882            key: format!("task:{}", request.task),
6883            payload: serde_json::to_value(request).unwrap(),
6884            generation: "a".repeat(64),
6885            version: None,
6886            status: crate::worker::Status::Starting,
6887            result: None,
6888            pid: None,
6889            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6890            finished_at: None,
6891        };
6892        let dir = home.join("workers/jobs").join(&job.id);
6893        std::fs::create_dir_all(&dir).unwrap();
6894        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6895        job
6896    }
6897
6898    #[test]
6899    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6900        let home = tempfile::tempdir().unwrap();
6901        let request = TaskWorker {
6902            opts: Opts::default(),
6903            queue: home.path().join("queue"),
6904            task: "startup".into(),
6905            lane: PermitKind::Ordinary,
6906            standalone: false,
6907        };
6908        let job = starting_task_reservation(home.path(), &request);
6909        let error = task_worker_spawn_error(
6910            home.path(),
6911            &request,
6912            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6913        )
6914        .expect_err("our own reservation must not turn a failed spawn into a resync");
6915        let active = crate::worker::active(home.path()).unwrap();
6916        assert_eq!(active.len(), 1);
6917        assert_eq!(active[0].id, job.id);
6918        assert_eq!(active[0].status, crate::worker::Status::Starting);
6919        assert!(
6920            crate::worker::control(home.path(), &job.key)
6921                .unwrap()
6922                .is_none()
6923        );
6924        let notices = notices::Notices::at(home.path().join("notifications")).list();
6925        assert_eq!(notices.len(), 1);
6926        assert_eq!(notices[0].key, "loop:worker-startup");
6927        assert!(!notices[0].message.contains("private-error-detail"));
6928        assert!(notices[0].message.contains(&request.task));
6929        assert!(
6930            notices[0]
6931                .message
6932                .contains("could not be started or acknowledged")
6933        );
6934        assert!(notices[0].message.contains("worker.log"));
6935        assert_eq!(
6936            notices[0].link,
6937            Some(Link::Task {
6938                id: request.task.clone()
6939            })
6940        );
6941        assert!(format!("{error:#}").contains("private-error-detail"));
6942    }
6943
6944    #[test]
6945    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6946        let home = tempfile::tempdir().unwrap();
6947        let mut request = TaskWorker {
6948            opts: Opts::default(),
6949            queue: home.path().join("queue"),
6950            task: "handoff".into(),
6951            lane: PermitKind::Ordinary,
6952            standalone: true,
6953        };
6954        let job = starting_task_reservation(home.path(), &request);
6955        request.standalone = false;
6956        task_worker_spawn_error(
6957            home.path(),
6958            &request,
6959            anyhow::anyhow!("operation key is already reserved for a different request"),
6960        )
6961        .expect("a different standalone request is the handoff race, not our startup failure");
6962        let active = crate::worker::active(home.path()).unwrap();
6963        assert_eq!(active.len(), 1);
6964        assert_eq!(active[0].id, job.id);
6965        assert_eq!(active[0].payload, job.payload);
6966        assert!(
6967            notices::Notices::at(home.path().join("notifications"))
6968                .list()
6969                .is_empty()
6970        );
6971    }
6972
6973    #[test]
6974    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6975        let home = tempfile::tempdir().unwrap();
6976        let queue = Queue::at(home.path().join("queue"));
6977        let mut task = task();
6978        task.runs = vec!["previous".into()];
6979        queue.put(&mut task).unwrap();
6980        let request = TaskWorker {
6981            opts: Opts::default(),
6982            queue: home.path().join("queue"),
6983            task: task.id.clone(),
6984            lane: PermitKind::Ordinary,
6985            standalone: false,
6986        };
6987        let job = starting_task_reservation(home.path(), &request);
6988        let claims = current_work(home.path(), Timestamp::now());
6989        assert_eq!(claims.len(), 1);
6990        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6991        assert_eq!(claims[0].run, "previous");
6992        assert!(other_claims_run(&claims, "previous", None));
6993        // Only after confirming the executing caller may admission ignore
6994        // this exact projection. Cleanup continues to observe it as live.
6995        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6996        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6997    }
6998
6999    #[test]
7000    fn admission_excludes_only_the_callers_exact_reservation() {
7001        let own = Current {
7002            worker: Some("own".into()),
7003            task: "same-task".into(),
7004            run: "previous".into(),
7005        };
7006        assert!(!other_claims_run(
7007            std::slice::from_ref(&own),
7008            "previous",
7009            Some("own")
7010        ));
7011        assert!(other_claims_run(
7012            std::slice::from_ref(&own),
7013            "previous",
7014            None
7015        ));
7016        for worker in [None, Some("other".into())] {
7017            let other = Current {
7018                worker,
7019                ..own.clone()
7020            };
7021            assert!(other_claims_run(
7022                &[own.clone(), other],
7023                "previous",
7024                Some("own")
7025            ));
7026        }
7027        let legacy: Current =
7028            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7029        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7030    }
7031
7032    #[test]
7033    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7034        let mut task = task();
7035        let mut run = run_state(RunStatus::Reviewing);
7036        run.task_instruction = Some(task.instruction.clone());
7037        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7038        let branch = "magi/test/B";
7039        run.candidates.push(crate::run::Candidate {
7040            branch: branch.into(),
7041            ..candidate('B', "preserved work", false, None)
7042        });
7043        task.runs = vec![run.id.clone()];
7044        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7045        assert_eq!(
7046            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7047            Starter::Resume(run.id.clone())
7048        );
7049        assert!(matches!(
7050            review_retry_starter(
7051                &task,
7052                Some(&run),
7053                Some("different"),
7054                true,
7055                unfinished.as_deref()
7056            ),
7057            Starter::Review(_)
7058        ));
7059        assert_eq!(
7060            review_retry_starter(
7061                &task,
7062                Some(&run),
7063                Some(branch),
7064                false,
7065                unfinished.as_deref()
7066            ),
7067            Starter::Start
7068        );
7069        task.instruction.push_str(" changed criteria");
7070        assert!(matches!(
7071            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7072            Starter::Review(_)
7073        ));
7074        assert!(matches!(
7075            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7076            Starter::Review(_)
7077        ));
7078    }
7079
7080    #[test]
7081    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7082        let dir = tempfile::tempdir().unwrap();
7083        let queue = Queue::at(dir.path().join("queue"));
7084        let mut task = task();
7085        task.status = TaskStatus::Running;
7086        task.attempts = 1;
7087        queue.put(&mut task).unwrap();
7088        let live = std::collections::BTreeSet::from([task.id.clone()]);
7089        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7090        drop(queue.claim(&task.id).unwrap());
7091        let saved = queue.get(&task.id).unwrap();
7092        assert_eq!(saved.status, TaskStatus::Running);
7093        assert_eq!(saved.attempts, 1);
7094        assert!(saved.last_error.is_none());
7095    }
7096
7097    #[test]
7098    fn standalone_workers_do_not_consume_scheduler_lanes() {
7099        let request = |task: &str, lane, standalone| TaskWorker {
7100            opts: Opts::default(),
7101            queue: PathBuf::from("/queue"),
7102            task: task.to_owned(),
7103            lane,
7104            standalone,
7105        };
7106        let mut jobs = vec![
7107            request("ordinary", PermitKind::Ordinary, false),
7108            request("standalone-urgent", PermitKind::Urgent, true),
7109            request("standalone-ordinary", PermitKind::Ordinary, true),
7110            request("decision", PermitKind::None, false),
7111        ];
7112        assert_eq!(available_slots(&jobs, 2), (1, 1));
7113        jobs.push(request("urgent", PermitKind::Urgent, false));
7114        assert_eq!(available_slots(&jobs, 2), (1, 0));
7115        assert_eq!(available_slots(&jobs, 0), (0, 0));
7116    }
7117
7118    #[test]
7119    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7120        let now = Timestamp::now();
7121        let mut reading = Reading {
7122            pid: Some(std::process::id()),
7123            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7124            ..Reading::default()
7125        };
7126        assert!(!reading.running(now));
7127        assert!(legacy_scheduler_running(&reading, now, 0));
7128        reading.worker_protocol = Some(1);
7129        assert!(!legacy_scheduler_running(&reading, now, 0));
7130    }
7131
7132    #[test]
7133    fn selected_public_head_overrides_historical_resume_and_pin() {
7134        let mut t = task();
7135        let mut old = run_state(RunStatus::Blocked);
7136        let selection = crate::pr_recovery::Selection {
7137            url: "url".into(),
7138            branch: format!("magi/task-{}", t.id),
7139            head: "a".repeat(40),
7140            source_head: None,
7141            source_run: None,
7142            source_proof: None,
7143            disposition: Some(crate::pr_recovery::Disposition::Review),
7144            instruction: t.instruction.clone(),
7145            approved_at: Timestamp::now(),
7146        };
7147        t.resume_override = Some(crate::queue::OperatorResume {
7148            pinned_run: Some(old.id.clone()),
7149            question_id: "choice".into(),
7150            at: Timestamp::now(),
7151            conductor_rehold: None,
7152            forced: false,
7153        });
7154        assert_eq!(
7155            selected_starter(&selection, Some(&old), Some(&old.id)),
7156            Starter::Review(selection.branch.clone())
7157        );
7158        old.pr_recovery = Some(selection.clone());
7159        assert_eq!(
7160            selected_starter(&selection, Some(&old), Some(&old.id)),
7161            Starter::Review(selection.branch.clone())
7162        );
7163        old.reviewed_commits = Some(vec!["implementation".into()]);
7164        assert_eq!(
7165            selected_starter(&selection, Some(&old), Some(&old.id)),
7166            Starter::Resume(old.id.clone())
7167        );
7168        let mut changed = selection.clone();
7169        changed.head = "b".repeat(40);
7170        assert_eq!(
7171            selected_starter(&changed, Some(&old), Some(&old.id)),
7172            Starter::Review(changed.branch)
7173        );
7174    }
7175
7176    #[test]
7177    fn candidate_transplant_failure_is_one_actionable_hold() {
7178        let dir = tempfile::tempdir().unwrap();
7179        let q = Queue::at(dir.path().join("queue"));
7180        let mut t = task();
7181        let mut state = run_state(RunStatus::Blocked);
7182        state.event("prep", "cannot apply referenced commit: conflict");
7183        state.prep_failure = Some("conflict".into());
7184        t.start(state.id.clone());
7185        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7186        assert_eq!(t.attempts, 1);
7187        assert_eq!(t.status, TaskStatus::Held);
7188        assert!(t.operator_held());
7189        assert!(!t.status.runnable());
7190        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7191        let first = t.chat_notice_key().unwrap();
7192        t.chat_notices.push(first.clone());
7193        t.release_operator("test", None);
7194        state.id = "another-unprepared-run".into();
7195        t.start(state.id.clone());
7196        finish_attempt(
7197            3,
7198            &q,
7199            &mut t,
7200            &state,
7201            &[],
7202            Err(anyhow::anyhow!("still conflicts")),
7203        );
7204        assert_eq!(
7205            t.chat_notice_key().as_ref(),
7206            Some(&first),
7207            "no work happened"
7208        );
7209        t.release_operator("test", None);
7210        state.prep_failure = None;
7211        state.status = RunStatus::Failed;
7212        state.begin_pass();
7213        t.start(state.id.clone());
7214        finish_attempt(
7215            1,
7216            &q,
7217            &mut t,
7218            &state,
7219            &[],
7220            Err(anyhow::anyhow!("new gate failure")),
7221        );
7222        let failure = t.chat_notice_key().unwrap();
7223        assert_ne!(failure, first, "approved recovery reached a real failure");
7224        t.release_operator("test", None);
7225        state.begin_pass();
7226        t.start(state.id.clone());
7227        finish_attempt(
7228            1,
7229            &q,
7230            &mut t,
7231            &state,
7232            &[],
7233            Err(anyhow::anyhow!("new failure on resume")),
7234        );
7235        assert_ne!(
7236            t.chat_notice_key().as_ref(),
7237            Some(&failure),
7238            "a new settled pass"
7239        );
7240    }
7241
7242    #[test]
7243    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7244        for source in ["cli", "web"] {
7245            let mut t = task();
7246            let mut run = run_state(RunStatus::Blocked);
7247            run.instruction = "Run A original criteria".into();
7248            run.task_instruction = Some(run.instruction.clone());
7249            t.start(run.id.clone());
7250            t.release_operator("choice", Some("resume-question"));
7251            t.resume_override = Some(crate::queue::OperatorResume {
7252                question_id: "resume-question".into(),
7253                at: Timestamp::now(),
7254                conductor_rehold: None,
7255                forced: true,
7256                pinned_run: Some(run.id.clone()),
7257            });
7258            t.hold_machine(Some("not enough free space to start a run".into()));
7259            let mut unchanged = t.clone();
7260            unchanged
7261                .edit("title changed".into(), unchanged.instruction.clone())
7262                .unwrap();
7263            unchanged.release_operator(source, None);
7264            assert_eq!(
7265                unchanged
7266                    .resume_override
7267                    .as_ref()
7268                    .unwrap()
7269                    .pinned_run
7270                    .as_deref(),
7271                Some(run.id.as_str())
7272            );
7273            assert!(!compatible_run_instruction(&run, &unchanged));
7274            assert!(may_resume_run(&run, &unchanged));
7275
7276            t.edit(
7277                "approved recovery".into(),
7278                "Reuse measured PR head B; fix Clippy; review".into(),
7279            )
7280            .unwrap();
7281            assert!(t.resume_override.is_none());
7282            t.release_operator(source, None);
7283            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7284            assert!(reloaded.resume_override.is_none());
7285            assert!(!may_resume_run(&run, &reloaded));
7286            let unfinished =
7287                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7288                    .filter(|_| may_resume_run(&run, &reloaded));
7289            assert_eq!(
7290                choose_starter(None, false, unfinished.as_deref()),
7291                Starter::Start
7292            );
7293            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7294            assert_eq!(
7295                reloaded.resumption_history[0].question_id.as_deref(),
7296                Some("resume-question")
7297            );
7298
7299            // A revision already persisted with the old approval/pin is also
7300            // invalidated when the new operator release is recorded.
7301            unchanged.instruction = "Reuse measured PR head B".into();
7302            unchanged.hold_machine(Some("disk hold".into()));
7303            unchanged.release_operator(source, None);
7304            assert!(unchanged.resume_override.is_none());
7305            assert!(!may_resume_run(&run, &unchanged));
7306        }
7307    }
7308
7309    #[test]
7310    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7311        let mut t = task();
7312        let mut run = run_state(RunStatus::Blocked);
7313        t.review_of = Some("approved-head".into());
7314        t.instruction =
7315            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7316                .into();
7317        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();
7318        run.reviewed_commits = Some(vec!["Commit log".into()]);
7319        t.start(run.id.clone());
7320        t.hold_machine(Some("interrupted review".into()));
7321        t.release_operator("cli", None);
7322        assert!(
7323            compatible_run_instruction(&run, &t),
7324            "legacy explicit review remains resumable"
7325        );
7326        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7327            .filter(|_| compatible_run_instruction(&run, &t));
7328        assert_eq!(
7329            choose_starter(None, false, unfinished.as_deref()),
7330            Starter::Resume(run.id.clone())
7331        );
7332        run.task_instruction = Some(t.instruction.clone());
7333        assert!(compatible_run_instruction(&run, &t));
7334        let reloaded: RunState =
7335            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7336        assert!(compatible_run_instruction(&reloaded, &t));
7337        t.edit(
7338            "new approved head".into(),
7339            "Reuse measured PR head B".into(),
7340        )
7341        .unwrap();
7342        assert!(!compatible_run_instruction(&run, &t));
7343
7344        // Legacy recovery reviews retain the task criteria ahead of the log.
7345        t.review_of = None;
7346        t.instruction = "Fix Clippy on approved head".into();
7347        run.task_instruction = None;
7348        run.instruction = format!(
7349            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7350            t.instruction
7351        );
7352        assert!(compatible_run_instruction(&run, &t));
7353        t.instruction.push('\n');
7354        assert!(
7355            compatible_run_instruction(&run, &t),
7356            "legacy generated review trimmed the original criteria"
7357        );
7358        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7359        let mut unchanged = t.clone();
7360        assert_eq!(
7361            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
7362            Some("approved-head")
7363        );
7364        t.edit("new plan".into(), "Reuse measured PR head B".into())
7365            .unwrap();
7366        assert!(take_review_branch(&mut t, Some(&run)).is_none());
7367        assert!(!compatible_run_instruction(&run, &t));
7368        t.review_branch = Some("approved-head".into());
7369        t.review_instruction = None;
7370        assert!(
7371            take_review_branch(&mut t, Some(&run)).is_none(),
7372            "legacy retained candidate cannot replace a revised approved head"
7373        );
7374    }
7375
7376    #[test]
7377    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7378        let home = crate::run::test_home();
7379        crate::run::pin_test_home();
7380        let dir = tempfile::tempdir().unwrap();
7381        let queue = Queue::at(dir.path().join("queue"));
7382        for resume in [true, false] {
7383            let state = run_state(RunStatus::Blocked);
7384            let mut t = task();
7385            t.start(state.id.clone());
7386            let action = if resume {
7387                ask::ChoiceAction::Resume {
7388                    run: state.id.clone(),
7389                }
7390            } else {
7391                ask::ChoiceAction::Requeue
7392            };
7393            let mut q = action_question(&state.id, action);
7394            q.status = ask::QuestionStatus::Open;
7395            q.answer = None;
7396            q.answered_at = None;
7397            t.fail("run stopped with a question", 3);
7398            hold_if_runnable(&queue, &mut t);
7399            assert!(t.operator_decided_at.is_none());
7400            assert!(t.operator_held());
7401            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7402            let expected = if resume {
7403                ActionDecision::Resume(state.id.clone())
7404            } else {
7405                ActionDecision::Requeue
7406            };
7407            assert_eq!(
7408                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7409                expected
7410            );
7411            t.hold_manual(Some("later explicit hold".into()));
7412            assert_eq!(
7413                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7414                ActionDecision::Stale
7415            );
7416        }
7417    }
7418
7419    #[test]
7420    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7421        let mut t = task();
7422        t.answers.push(crate::queue::AnsweredQuestion {
7423            question: "Inspect the remote?".into(),
7424            answer: "Inspect then wait".into(),
7425        });
7426        let old = instruction_for(&t);
7427        assert!(compatible_instruction(&old, &t));
7428        t.instruction = "Reuse approved PR head and review".into();
7429        t.release_operator("cli", None);
7430        assert!(!compatible_instruction(&old, &t));
7431        let approved = instruction_for(&t);
7432        assert!(approved.contains("waiting premises are superseded"));
7433        assert!(compatible_instruction(&approved, &t));
7434        assert_eq!(resumed_instruction(&approved, &t), approved);
7435        t.release_operator("web", None);
7436        assert!(compatible_instruction(&approved, &t));
7437        assert_eq!(t.resumption_history.len(), 1);
7438        t.start("run".into());
7439        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7440    }
7441
7442    /// A run that stopped on an infrastructure wait asked no agent anything:
7443    /// the task is held by the machine under a `[resource]` reason (resumable,
7444    /// re-checked by triage), and the attempt it started is given back.
7445    #[test]
7446    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7447        let mut state = RunState::new(
7448            PathBuf::from("/repo"),
7449            "main".into(),
7450            "base".into(),
7451            "task".into(),
7452            Config::default(),
7453        );
7454        state.status = RunStatus::Landing;
7455        state.parked = true;
7456        state.pr_pushed_head = Some("head".into());
7457        state.land_unrelated = Some(
7458            serde_json::from_value(serde_json::json!({
7459                "head": "head", "question": "ci-question",
7460                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7461            }))
7462            .unwrap(),
7463        );
7464        let mut t = task();
7465        t.start(state.id.clone());
7466        let verdict = Verdict {
7467            status: RunStatus::Landing,
7468            left_pr: true,
7469            quota_hit: false,
7470            parked: true,
7471            no_viable_candidates: false,
7472        };
7473        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7474        assert_eq!(t.attempts, 0);
7475        assert_eq!(t.status, TaskStatus::Held);
7476        assert!(!t.operator_held());
7477        assert!(
7478            t.hold_reason
7479                .as_deref()
7480                .unwrap()
7481                .starts_with("[ci-unrelated]")
7482        );
7483        // A second settlement must not refund an earlier task attempt.
7484        t.attempts = 1;
7485        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7486        assert_eq!(t.attempts, 1);
7487        assert_eq!(t.passes.len(), 1);
7488        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7489        state.pr_pushed_head = Some("new-head".into());
7490        state.parked = false;
7491        state.status = RunStatus::Blocked;
7492        let stale = Verdict {
7493            status: RunStatus::Blocked,
7494            parked: false,
7495            ..verdict
7496        };
7497        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7498        assert_eq!(t.attempts, 1);
7499        // A new execution pass can refund its own newly charged attempt.
7500        state.begin_pass();
7501        state.begin_pass();
7502        state.status = RunStatus::Landing;
7503        state.parked = true;
7504        state.pr_pushed_head = Some("head".into());
7505        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7506        assert_eq!(t.attempts, 0);
7507        assert_eq!(t.passes.len(), 2);
7508    }
7509
7510    #[test]
7511    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7512        let mut state = run_state(RunStatus::Failed);
7513        state
7514            .quota
7515            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7516        state.begin_pass();
7517        let mut t = task();
7518        t.start(state.id.clone());
7519        reclaim(&mut t, Some(state), 2, "en");
7520        assert_eq!(t.attempts, 1);
7521    }
7522
7523    #[test]
7524    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7525        let mut state = run_state(RunStatus::Blocked);
7526        let losses: Vec<_> = ["alpha", "beta"]
7527            .into_iter()
7528            .enumerate()
7529            .map(|(i, agent)| {
7530                QuotaLoss::from_report(
7531                    format!("advisor-{i}"),
7532                    "advise",
7533                    Some(&crate::agent::Quota {
7534                        cause: crate::agent::QuotaCause::Authentication,
7535                        agent: agent.to_owned(),
7536                        reset: None,
7537                    }),
7538                )
7539            })
7540            .collect();
7541        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7542        state.quota = losses;
7543        let mut t = task();
7544        t.start(state.id.clone());
7545        let verdict = Verdict {
7546            status: state.status,
7547            left_pr: false,
7548            quota_hit: true,
7549            parked: false,
7550            no_viable_candidates: true,
7551        };
7552        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7553        assert_eq!(t.attempts, 0);
7554        assert_eq!(t.status, TaskStatus::Held);
7555        assert!(!t.operator_held());
7556        let reason = t.hold_reason.as_deref().unwrap();
7557        assert!(reason.starts_with("[authentication]"));
7558        assert!(
7559            reason.contains("alpha")
7560                && reason.contains("beta")
7561                && reason.contains("re-authenticate")
7562        );
7563        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7564        // Orphan recovery uses the same settlement and cannot spend an attempt.
7565        let mut orphan = task();
7566        orphan.start(state.id.clone());
7567        reclaim(&mut orphan, Some(state), 2, "en");
7568        assert_eq!(orphan.attempts, 0);
7569        assert_eq!(orphan.status, TaskStatus::Held);
7570    }
7571
7572    #[test]
7573    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7574        let mut state = RunState::new(
7575            PathBuf::from("/repo"),
7576            "main".to_owned(),
7577            "abc1234".to_owned(),
7578            "task".to_owned(),
7579            Config::default(),
7580        );
7581        state.status = RunStatus::Blocked;
7582        state.resource_block = Some(crate::run::ResourceBlock {
7583            cause: crate::run::ResourceBlockCause::Other,
7584            node: "graft".to_owned(),
7585            kind: "shared build cache".to_owned(),
7586            detail: "timed out".to_owned(),
7587            at: jiff::Timestamp::now(),
7588        });
7589        let mut t = task();
7590        t.start("20260902-000000-aaaa".to_owned());
7591        assert_eq!(t.attempts, 1);
7592        let verdict = Verdict {
7593            status: RunStatus::Blocked,
7594            left_pr: false,
7595            quota_hit: false,
7596            parked: false,
7597            no_viable_candidates: false,
7598        };
7599        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7600        assert_eq!(t.status, TaskStatus::Held);
7601        assert_eq!(t.attempts, 0, "the attempt is refunded");
7602        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7603        assert!(
7604            !t.operator_held(),
7605            "a machine hold, released without a human"
7606        );
7607
7608        let mut selected = task();
7609        selected.start("20260902-000000-cccc".into());
7610        selected.replacement = Some(crate::merge_decision::Replacement {
7611            question: "fixture".into(),
7612            run: "earlier".into(),
7613            pr: "https://example.invalid/pr/1".into(),
7614            agent: "selected".into(),
7615            context: "fixture".into(),
7616        });
7617        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7618        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7619        assert_eq!(selected.attempts, 0);
7620        assert!(
7621            !selected.operator_held(),
7622            "a selected agent also retains a machine resource hold"
7623        );
7624        assert!(
7625            selected
7626                .hold_reason
7627                .as_deref()
7628                .unwrap()
7629                .starts_with("[resource] ")
7630        );
7631
7632        // A park request outranks it: still the operator's doing.
7633        let mut p = task();
7634        p.start("20260902-000000-bbbb".to_owned());
7635        settle_and_diagnose(
7636            &mut p,
7637            Verdict {
7638                parked: true,
7639                ..verdict
7640            },
7641            "parked",
7642            2,
7643            &state,
7644        );
7645        assert_eq!(p.status, TaskStatus::Parked);
7646        assert_eq!(
7647            p.attempts, 0,
7648            "parking refunds once rather than also settling the resource hold"
7649        );
7650    }
7651
7652    #[test]
7653    fn record_failure_notice_links_the_task() {
7654        let dir = tempfile::tempdir().unwrap();
7655        // A regular file where the queue directory should be makes every
7656        // `put` fail, on every platform and whoever runs the test.
7657        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7658        let queue = Queue::at(dir.path().join("queue"));
7659        let mut t = interrupt_task("rec-fail-1");
7660        record(&queue, &mut t);
7661
7662        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7663        assert_eq!(found.len(), 1);
7664        assert_eq!(found[0].key, "loop:record");
7665        assert_eq!(
7666            found[0].link,
7667            Some(Link::Task {
7668                id: "rec-fail-1".to_owned()
7669            })
7670        );
7671    }
7672
7673    /// A runnable task marked to interrupt, with an id fixed for assertions
7674    /// rather than the random one [`Task::new`] mints.
7675    fn interrupt_task(id: &str) -> Task {
7676        let mut t = task();
7677        t.id = id.to_owned();
7678        t.interrupt = true;
7679        t
7680    }
7681
7682    /// An ordinary runnable task with an id fixed for assertions.
7683    fn task_with_id(id: &str) -> Task {
7684        let mut t = task();
7685        t.id = id.to_owned();
7686        t
7687    }
7688
7689    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7690    fn urgent_task(id: &str) -> Task {
7691        let mut t = task();
7692        t.id = id.to_owned();
7693        t.urgent = true;
7694        t
7695    }
7696
7697    #[test]
7698    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7699        let dir = tempfile::tempdir().unwrap();
7700        let queue = Queue::at(dir.path().join("queue"));
7701        let mut parked = task_with_id("parked");
7702        parked.start("run".into());
7703        parked.park("upgrade");
7704        parked.record_pass_at(
7705            "run",
7706            0,
7707            Some(Timestamp::now()),
7708            1,
7709            Some(crate::run::ParkCause::Upgrade {
7710                from: "old".into(),
7711                to: None,
7712            }),
7713        );
7714        let mut fresh = task_with_id("fresh");
7715        fresh.priority = 100;
7716        let mut urgent_task = urgent_task("urgent");
7717        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7718            queue.put(t).unwrap();
7719        }
7720        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7721        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7722        let candidates = runnable(&queue);
7723        assert_eq!(candidates[0].id, parked.id);
7724        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7725        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
7726        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
7727        drop(first);
7728        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7729        let next = runnable(&queue)
7730            .into_iter()
7731            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
7732            .unwrap();
7733        assert_eq!(next.task.id, fresh.id);
7734        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7735        drop(claimed_elsewhere);
7736        drop(next);
7737        assert!(matches!(
7738            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
7739            Err(SkipReason::CoolingDown)
7740        ));
7741    }
7742
7743    #[test]
7744    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7745        let dir = tempfile::tempdir().unwrap();
7746        let queue = Queue::at(dir.path().join("queue"));
7747        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7748        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7749        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7750        let mut first = task();
7751        queue.put(&mut first).unwrap();
7752        let stale_plain = queue.get(&first.id).unwrap();
7753        first.set_urgent(true).unwrap();
7754        queue.put(&mut first).unwrap();
7755        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7756        let mut second = urgent_task("second");
7757        queue.put(&mut second).unwrap();
7758        assert!(matches!(
7759            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
7760            Err(SkipReason::UrgentCapacity)
7761        ));
7762        drop(queue.claim(&second.id).unwrap());
7763        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7764        drop(dispatched);
7765        let stale_urgent = queue.get(&first.id).unwrap();
7766        first.set_urgent(false).unwrap();
7767        queue.put(&mut first).unwrap();
7768        assert!(matches!(
7769            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
7770            Err(SkipReason::OrdinaryCapacity)
7771        ));
7772        assert_eq!(urgent.available_permits(), 1);
7773        drop(queue.claim(&first.id).unwrap());
7774        drop(occupied);
7775    }
7776
7777    #[test]
7778    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7779        let dir = tempfile::tempdir().unwrap();
7780        let queue = Queue::at(dir.path().join("queue"));
7781        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7782        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7783        let mut t = task();
7784        queue.put(&mut t).unwrap();
7785        for enabled in [true, false] {
7786            let stale = queue.get(&t.id).unwrap();
7787            t.set_urgent(enabled).unwrap();
7788            queue.put(&mut t).unwrap();
7789            assert_ne!(stale.urgent, enabled);
7790            let DispatchClaim {
7791                task: fresh,
7792                claim,
7793                permit,
7794            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7795            assert_eq!(fresh.urgent, enabled);
7796            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7797            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7798            assert!(queue.claim(&t.id).is_err());
7799            assert_eq!(fresh.attempts, stale.attempts);
7800            drop((claim, permit));
7801            assert_eq!(ordinary.available_permits(), 1);
7802            assert_eq!(urgent.available_permits(), 1);
7803        }
7804        t.set_urgent(true).unwrap();
7805        queue.put(&mut t).unwrap();
7806        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7807        assert!(matches!(
7808            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7809            Err(SkipReason::UrgentCapacity)
7810        ));
7811        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7812        drop(queue.claim(&t.id).unwrap());
7813        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7814        drop(occupied);
7815        assert!(matches!(
7816            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
7817            Err(SkipReason::CoolingDown)
7818        ));
7819        drop(queue.claim(&t.id).unwrap());
7820        let held = queue.claim(&t.id).unwrap();
7821        assert!(matches!(
7822            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7823            Err(SkipReason::ClaimUnavailable)
7824        ));
7825        drop(held);
7826        t.status = TaskStatus::Held;
7827        queue.put(&mut t).unwrap();
7828        assert!(matches!(
7829            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7830            Err(SkipReason::NoLongerRunnable)
7831        ));
7832        drop(queue.claim(&t.id).unwrap());
7833        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7834        assert!(matches!(
7835            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7836            Err(SkipReason::RereadFailed)
7837        ));
7838        drop(queue.claim(&t.id).unwrap());
7839        assert_eq!(urgent.available_permits(), 1);
7840    }
7841
7842    /// The land-resume exemption wins outright, whether or not the candidate
7843    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7844    /// queue behind anything" guarantee cannot be weaker just because the
7845    /// same task was also filed with `--urgent`.
7846    #[test]
7847    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7848        assert_eq!(permit_kind(true, false), PermitKind::None);
7849        assert_eq!(permit_kind(true, true), PermitKind::None);
7850    }
7851
7852    /// The one property this whole feature exists for: `--urgent` draws from
7853    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7854    /// ordinary candidate draws from the ordinary pool exactly as before,
7855    /// untouched by the urgent slot's existence.
7856    #[test]
7857    fn permit_kind_separates_urgent_from_ordinary() {
7858        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7859        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7860    }
7861
7862    /// The exact wiring `attempt` runs before minting anything: a config's
7863    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7864    /// Free space is injected rather than asked of the real disk - the point
7865    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7866    /// is deterministic on every machine this test runs on, never dependent
7867    /// on how full the CI runner's own disk happens to be.
7868    #[test]
7869    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7870        let cfg = Config::default();
7871        let repo = Path::new("/any/repo/path");
7872
7873        let reason =
7874            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7875        assert!(reason.contains("1024"), "{reason}");
7876        assert!(
7877            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7878            "{reason}"
7879        );
7880
7881        assert_eq!(
7882            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7883            None,
7884            "exactly at the floor is open"
7885        );
7886        assert_eq!(
7887            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7888            None,
7889            "comfortably above the floor is open"
7890        );
7891    }
7892
7893    #[test]
7894    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
7895        let dir = tempfile::tempdir().unwrap();
7896        let repo = dir.path().join("repo");
7897        let cache = dir.path().join("cache");
7898        let worktrees = dir.path().join("worktrees");
7899        for path in [&repo, &cache, &worktrees] {
7900            std::fs::create_dir(path).unwrap();
7901        }
7902        let mut cfg = Config::default();
7903        cfg.graph.worktree_root = Some(worktrees.clone());
7904        cfg.verify.gate = vec![format!(
7905            "CARGO_TARGET_DIR='{}' cargo build",
7906            cache.display()
7907        )];
7908        for blocked in [&cache, &worktrees] {
7909            for unmeasured in [false, true] {
7910                assert!(
7911                    disk_gate_with(&repo, &cfg, |path| {
7912                        if path == blocked {
7913                            if unmeasured {
7914                                Err(anyhow::anyhow!("measurement failed"))
7915                            } else {
7916                                Ok(0)
7917                            }
7918                        } else {
7919                            Ok(u64::MAX)
7920                        }
7921                    })
7922                    .is_some(),
7923                    "a blocked secondary output volume must close admission"
7924                );
7925            }
7926        }
7927        assert!(disk_gate_with(&repo, &cfg, |_| Ok(u64::MAX)).is_none());
7928    }
7929
7930    #[test]
7931    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7932        let mut cfg = Config::default();
7933        cfg.disk.min_free_bytes = 0;
7934        let repo = Path::new("/any/repo/path");
7935        assert_eq!(
7936            disk_gate_with(repo, &cfg, |_| Ok(0)),
7937            None,
7938            "a zero floor never measures at all"
7939        );
7940    }
7941
7942    #[test]
7943    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7944        let cfg = Config::default();
7945        let repo = Path::new("/any/repo/path");
7946        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7947            .expect("a measurement failure must close the gate, not open it");
7948        assert!(reason.contains("could not measure"), "{reason}");
7949    }
7950
7951    #[test]
7952    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7953        let ordinary = task();
7954        let next = advance_interrupt(
7955            Interrupt::Idle,
7956            std::slice::from_ref(&ordinary.id),
7957            std::slice::from_ref(&ordinary),
7958        );
7959        assert_eq!(next, Interrupt::Idle);
7960    }
7961
7962    #[test]
7963    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7964        // Nothing to interrupt - this is just an ordinary candidate, and the
7965        // loop's normal dispatch will pick it up like any other.
7966        let marked = interrupt_task("marked");
7967        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7968        assert_eq!(next, Interrupt::Idle);
7969    }
7970
7971    #[test]
7972    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7973        let marked = interrupt_task("marked");
7974        let next = advance_interrupt(
7975            Interrupt::Idle,
7976            &["running".to_owned()],
7977            std::slice::from_ref(&marked),
7978        );
7979        assert_eq!(
7980            next,
7981            Interrupt::Parking {
7982                parked: vec!["running".to_owned()],
7983                interrupt_task: "marked".to_owned(),
7984            }
7985        );
7986    }
7987
7988    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7989    /// one run can be in flight when a task becomes runnable and marked.
7990    /// Parking all of them would mean `Resuming` later has more than one id
7991    /// to release back to ordinary dispatch, which cannot be made safe
7992    /// against that same setting's own extra concurrency slots letting two
7993    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7994    /// The simplification the task's own constraints ask for: do not begin
7995    /// a sequence at all until the herd settles back to exactly one.
7996    #[test]
7997    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7998        let marked = interrupt_task("marked");
7999
8000        let two = advance_interrupt(
8001            Interrupt::Idle,
8002            &["a".to_owned(), "b".to_owned()],
8003            std::slice::from_ref(&marked),
8004        );
8005        assert_eq!(two, Interrupt::Idle);
8006
8007        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8008        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8009    }
8010
8011    #[test]
8012    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8013        let state = Interrupt::Parking {
8014            parked: vec!["running".to_owned()],
8015            interrupt_task: "marked".to_owned(),
8016        };
8017        // Still in flight: no change.
8018        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8019        assert_eq!(still_going, state);
8020
8021        // Left flight, but the interrupt task has not been dispatched yet on
8022        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8023        // as long as it is still runnable.
8024        let stopped_but_not_yet_dispatched =
8025            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8026        assert_eq!(stopped_but_not_yet_dispatched, state);
8027
8028        // Left flight, and the interrupt task is now in flight itself.
8029        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8030        assert_eq!(
8031            dispatched,
8032            Interrupt::Running {
8033                parked: vec!["running".to_owned()],
8034                interrupt_task: "marked".to_owned(),
8035            }
8036        );
8037    }
8038
8039    #[test]
8040    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8041        let state = Interrupt::Running {
8042            parked: vec!["running".to_owned()],
8043            interrupt_task: "marked".to_owned(),
8044        };
8045        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8046        assert_eq!(still_running, state);
8047
8048        // Whatever it ended as - merged, failed, held - is not this
8049        // function's concern: leaving flight is the only trigger, driven
8050        // straight off the same in-flight list `poll` already reaps. It does
8051        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8052        // why that would let an unrelated task start ahead of, or alongside,
8053        // the guaranteed resume.
8054        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8055        assert_eq!(
8056            ended,
8057            Interrupt::Resuming {
8058                parked: vec!["running".to_owned()]
8059            }
8060        );
8061    }
8062
8063    #[test]
8064    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8065        let state = Interrupt::Resuming {
8066            parked: vec!["running".to_owned()],
8067        };
8068        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8069        assert_eq!(still_waiting, state);
8070
8071        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8072        assert_eq!(dispatched, Interrupt::Idle);
8073    }
8074
8075    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8076    /// or otherwise moved on by an operator with no claim standing in the
8077    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8078    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8079    /// come. The parked run still gets its resume.
8080    #[test]
8081    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8082    {
8083        let state = Interrupt::Parking {
8084            parked: vec!["running".to_owned()],
8085            interrupt_task: "marked".to_owned(),
8086        };
8087        // `marked` has been held/blocked/deleted since the sequence began:
8088        // it no longer appears in `runnable` at all.
8089        let next = advance_interrupt(state, &[], &[]);
8090        assert_eq!(
8091            next,
8092            Interrupt::Resuming {
8093                parked: vec!["running".to_owned()]
8094            },
8095            "abandoning the interrupt must not abandon the resume it owes"
8096        );
8097    }
8098
8099    /// The same abandonment, one step later: `Resuming` itself must not wait
8100    /// forever for a parked task that has since become unrunnable.
8101    #[test]
8102    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8103        let state = Interrupt::Resuming {
8104            parked: vec!["running".to_owned()],
8105        };
8106        let next = advance_interrupt(state, &[], &[]);
8107        assert_eq!(
8108            next,
8109            Interrupt::Idle,
8110            "nothing is left to wait for; the loop must not stay wedged"
8111        );
8112    }
8113
8114    #[test]
8115    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8116        let marked = interrupt_task("marked");
8117        let next = advance_interrupt_tick(
8118            false,
8119            Interrupt::Idle,
8120            &["running".to_owned()],
8121            std::slice::from_ref(&marked),
8122        );
8123        assert_eq!(
8124            next,
8125            Interrupt::Idle,
8126            "an unmarked, unconfigured daemon must behave exactly as before"
8127        );
8128    }
8129
8130    #[test]
8131    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8132        let state = Interrupt::Parking {
8133            parked: vec!["running".to_owned()],
8134            interrupt_task: "marked".to_owned(),
8135        };
8136        let candidates = vec![interrupt_task("marked"), task()];
8137        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8138        assert!(
8139            allowed.is_empty(),
8140            "nothing may dispatch - not even the interrupt task itself - \
8141             until the parked run has actually stopped"
8142        );
8143    }
8144
8145    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8146    /// grow a special case for it: an urgent candidate that is not the
8147    /// interrupt task withholds exactly like an ordinary one for as long as
8148    /// the parked run it is racing has not actually left flight. A version
8149    /// of this feature once bypassed the gate for urgent candidates, on the
8150    /// theory that a genuinely separate concurrency lane could not collide
8151    /// with 75dd's own; it could, and did - the bypassed task dispatched
8152    /// alongside a run 75dd's own state machine had only *asked* to park,
8153    /// not yet confirmed gone, which is exactly the second run
8154    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8155    /// tick during Parking/Running/Resuming where letting an extra
8156    /// candidate through is safe, urgent or not - the parked run may still
8157    /// be genuinely mid-call.
8158    #[test]
8159    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8160        for state in [
8161            Interrupt::Parking {
8162                parked: vec!["running".to_owned()],
8163                interrupt_task: "marked".to_owned(),
8164            },
8165            Interrupt::Running {
8166                parked: vec!["running".to_owned()],
8167                interrupt_task: "marked".to_owned(),
8168            },
8169            Interrupt::Resuming {
8170                parked: vec!["running".to_owned()],
8171            },
8172        ] {
8173            let candidates = vec![
8174                interrupt_task("marked"),
8175                urgent_task("hot"),
8176                task_with_id("ordinary"),
8177            ];
8178            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8179            assert!(
8180                !allowed.iter().any(|t| t.id == "hot"),
8181                "an urgent candidate must wait out the same gate as anything \
8182                 else while the run it would run alongside has not actually \
8183                 left flight, for state {state:?}: {allowed:?}"
8184            );
8185        }
8186    }
8187
8188    /// The one case where marking a task `--urgent` and `interrupt` at once
8189    /// is not redundant: once the interrupt sequence's own guaranteed
8190    /// resume/dispatch actually admits the task, it is unaffected by also
8191    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8192    /// never on the urgent flag.
8193    #[test]
8194    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8195        let state = Interrupt::Resuming {
8196            parked: vec!["hot".to_owned()],
8197        };
8198        let candidates = vec![urgent_task("hot"), task()];
8199        let allowed = interrupt_gate(&state, &[], candidates);
8200        assert_eq!(
8201            allowed.iter().filter(|t| t.id == "hot").count(),
8202            1,
8203            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8204        );
8205    }
8206
8207    #[test]
8208    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8209        let state = Interrupt::Parking {
8210            parked: vec!["running".to_owned()],
8211            interrupt_task: "marked".to_owned(),
8212        };
8213        let other = task();
8214        let candidates = vec![interrupt_task("marked"), other.clone()];
8215        let allowed = interrupt_gate(&state, &[], candidates);
8216        assert_eq!(allowed.len(), 1);
8217        assert_eq!(allowed[0].id, "marked");
8218    }
8219
8220    #[test]
8221    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8222        let state = Interrupt::Running {
8223            parked: vec!["running".to_owned()],
8224            interrupt_task: "marked".to_owned(),
8225        };
8226        let candidates = vec![task(), task()];
8227        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8228        assert!(allowed.is_empty());
8229    }
8230
8231    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8232    /// sequence began (only reachable above the default
8233    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8234    /// never both in the same tick, which is what "exactly one resume, no
8235    /// simultaneous run" actually requires structurally rather than by
8236    /// coincidence of how many ordinary slots happen to be free.
8237    #[test]
8238    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8239        let state = Interrupt::Resuming {
8240            parked: vec!["a".to_owned(), "c".to_owned()],
8241        };
8242        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8243        let allowed = interrupt_gate(&state, &[], candidates);
8244        assert_eq!(
8245            allowed.len(),
8246            1,
8247            "at most one candidate may be offered while resuming: {allowed:?}"
8248        );
8249        assert_eq!(allowed[0].id, "a");
8250    }
8251
8252    #[test]
8253    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8254        let state = Interrupt::Resuming {
8255            parked: vec!["a".to_owned()],
8256        };
8257        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8258        assert!(allowed.is_empty());
8259    }
8260
8261    /// The invariant the completion criteria ask for by name: across a whole
8262    /// simulated sequence, there is never a tick where the gate would let
8263    /// through both the parked run's resume and the interrupt task, and
8264    /// exactly one candidate resumes the instant the interrupt task's run
8265    /// ends - never zero, never more than one.
8266    #[test]
8267    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8268        let running = task(); // id: whatever `Task::new` minted
8269        let marked = interrupt_task("marked");
8270
8271        let mut state = Interrupt::Idle;
8272        // Tick 1: `running` is in flight, `marked` becomes runnable.
8273        let in_flight = vec![running.id.clone()];
8274        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8275        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8276        assert!(gated.is_empty(), "still waiting on `running` to park");
8277
8278        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8279        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8280        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8281        assert_eq!(
8282            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8283            vec!["marked"],
8284            "only the interrupt task may be offered to the dispatcher now"
8285        );
8286
8287        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8288        state = advance_interrupt_tick(
8289            true,
8290            state,
8291            &["marked".to_owned()],
8292            std::slice::from_ref(&running),
8293        );
8294        let gated = interrupt_gate(
8295            &state,
8296            &["marked".to_owned()],
8297            vec![marked.clone(), running.clone()],
8298        );
8299        assert!(
8300            gated.is_empty(),
8301            "the parked run must not be offered back while the interrupt \
8302             task is still running"
8303        );
8304
8305        // Tick 4: `marked`'s run reached a terminal status and left flight.
8306        // A higher-priority ordinary task `other` is also runnable now - it
8307        // must not be let through instead of, or alongside, `running`.
8308        let other = task_with_id("other");
8309        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8310        assert_eq!(
8311            state,
8312            Interrupt::Resuming {
8313                parked: vec![running.id.clone()]
8314            }
8315        );
8316        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8317        assert_eq!(
8318            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8319            vec![running.id.as_str()],
8320            "exactly the parked run resumes - not the unrelated task, even \
8321             though it was offered first"
8322        );
8323
8324        // Tick 5: `running` is now in flight (dispatched from tick 4's
8325        // gate). Only now does the sequence end and ordinary dispatch fully
8326        // resume.
8327        state = advance_interrupt_tick(
8328            true,
8329            state,
8330            std::slice::from_ref(&running.id),
8331            std::slice::from_ref(&other),
8332        );
8333        assert_eq!(state, Interrupt::Idle);
8334        let gated = interrupt_gate(
8335            &state,
8336            std::slice::from_ref(&running.id),
8337            vec![other.clone()],
8338        );
8339        assert_eq!(
8340            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8341            vec![other.id.as_str()],
8342            "ordinary dispatch is unrestricted again"
8343        );
8344    }
8345
8346    #[test]
8347    fn every_run_status_settles_the_task_it_came_from() {
8348        // run status, resulting task status, attempts still standing after one
8349        let table = [
8350            (RunStatus::Merged, TaskStatus::Done, 1),
8351            (RunStatus::Ready, TaskStatus::Done, 1),
8352            (RunStatus::Stalled, TaskStatus::Failed, 0),
8353            (RunStatus::Blocked, TaskStatus::Failed, 1),
8354            (RunStatus::Failed, TaskStatus::Failed, 1),
8355            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8356            (RunStatus::Prep, TaskStatus::Failed, 1),
8357            (RunStatus::Implementing, TaskStatus::Failed, 1),
8358            (RunStatus::Judging, TaskStatus::Failed, 1),
8359            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8360            (RunStatus::Voting, TaskStatus::Failed, 1),
8361            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8362            (RunStatus::Gating, TaskStatus::Failed, 1),
8363        ];
8364        for (run, want, attempts) in table {
8365            let mut t = task();
8366            t.start("20260902-000000-aaaa".to_owned());
8367            settle(
8368                &mut t,
8369                Verdict {
8370                    status: run,
8371                    left_pr: false,
8372                    parked: false,
8373                    quota_hit: matches!(run, RunStatus::Stalled),
8374                    no_viable_candidates: false,
8375                },
8376                "why",
8377                2,
8378            );
8379            assert_eq!(t.status, want, "task status after {}", label(run));
8380            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8381        }
8382    }
8383
8384    #[test]
8385    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8386        let mut stalled = task();
8387        stalled.start("20260902-000000-aaaa".to_owned());
8388        settle(
8389            &mut stalled,
8390            Verdict {
8391                status: RunStatus::Stalled,
8392                left_pr: false,
8393                parked: false,
8394                quota_hit: true,
8395                no_viable_candidates: false,
8396            },
8397            "quota",
8398            1,
8399        );
8400        assert_eq!(stalled.attempts, 0);
8401        assert!(
8402            stalled.status.runnable(),
8403            "a machine problem must leave the task in line"
8404        );
8405
8406        let mut blocked = task();
8407        blocked.start("20260902-000000-aaaa".to_owned());
8408        settle(
8409            &mut blocked,
8410            Verdict {
8411                status: RunStatus::Blocked,
8412                left_pr: false,
8413                parked: false,
8414                quota_hit: false,
8415                no_viable_candidates: false,
8416            },
8417            "findings open",
8418            1,
8419        );
8420        assert_eq!(blocked.attempts, 1);
8421        assert_eq!(
8422            blocked.status,
8423            TaskStatus::Held,
8424            "the last attempt hands the task to a human"
8425        );
8426    }
8427
8428    #[test]
8429    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8430        // Attempts to spare: without the pull request this task would go
8431        // straight back in line and run the whole competition again.
8432        let mut delivered = task();
8433        delivered.start("20260903-080619-01c2".to_owned());
8434        settle(
8435            &mut delivered,
8436            Verdict {
8437                status: RunStatus::Blocked,
8438                left_pr: true,
8439                parked: false,
8440                quota_hit: false,
8441                no_viable_candidates: false,
8442            },
8443            "no check status",
8444            4,
8445        );
8446        assert_eq!(
8447            delivered.status,
8448            TaskStatus::Held,
8449            "a pull request waiting on CI or a person is not a retryable failure"
8450        );
8451        assert!(
8452            !delivered.status.runnable(),
8453            "the loop must not pick this task up again"
8454        );
8455        assert_eq!(
8456            delivered.last_error.as_deref(),
8457            Some("no check status"),
8458            "the operator needs to be told what the gate was waiting for"
8459        );
8460
8461        // The same status without a pull request is a plain failure, and with
8462        // attempts left it is retried.
8463        let mut empty_handed = task();
8464        empty_handed.start("20260903-080619-01c2".to_owned());
8465        settle(
8466            &mut empty_handed,
8467            Verdict {
8468                status: RunStatus::Blocked,
8469                left_pr: false,
8470                parked: false,
8471                quota_hit: false,
8472                no_viable_candidates: false,
8473            },
8474            "findings open",
8475            4,
8476        );
8477        assert_eq!(empty_handed.status, TaskStatus::Failed);
8478        assert!(empty_handed.status.runnable());
8479    }
8480
8481    #[test]
8482    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8483        // Every candidate agreed, with evidence, that nothing belonged in the
8484        // worktree. That is not a confirmed success to close automatically -
8485        // a human still has to check the claim - and it is not an ordinary
8486        // failure either, so this settles exactly like a pull request nobody
8487        // merged yet: `Held`, same as `Blocked` with a PR.
8488        let mut noop = task();
8489        noop.start("20260912-131304-391f".to_owned());
8490        settle(
8491            &mut noop,
8492            Verdict {
8493                status: RunStatus::VerifiedNoop,
8494                left_pr: false,
8495                parked: false,
8496                quota_hit: false,
8497                no_viable_candidates: true,
8498            },
8499            "candidate A: already fixed by b32cfc4, on main",
8500            4,
8501        );
8502        assert_eq!(
8503            noop.status,
8504            TaskStatus::Held,
8505            "an unverified claim is a request for a human, not a failure"
8506        );
8507        assert!(
8508            !noop.status.runnable(),
8509            "the loop must not requeue this on the same unverified claim"
8510        );
8511        // `Task::release` resets attempts to zero the moment a human looks at
8512        // the evidence and lets it run again, so it does not matter here
8513        // whether the one attempt already spent stays spent - what matters is
8514        // that nothing retries this task unattended in the meantime.
8515        assert_eq!(noop.attempts, 1);
8516    }
8517
8518    #[test]
8519    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8520        // Parking is the operator asking for the process back - to replace the
8521        // binary, most of all. The run's work is intact on disk, so this is
8522        // not a failed attempt, and charging for it would mean a few upgrades
8523        // could exhaust a budget meant for agents that misbehaved.
8524        let mut parked = task();
8525        parked.start("20260903-183634-2d98".to_owned());
8526        settle(
8527            &mut parked,
8528            Verdict {
8529                status: RunStatus::Implementing,
8530                left_pr: false,
8531                quota_hit: false,
8532                parked: true,
8533                no_viable_candidates: false,
8534            },
8535            "parked after `implementing`",
8536            2,
8537        );
8538        assert_eq!(parked.attempts, 0, "a park is refunded");
8539        assert!(
8540            parked.status.runnable(),
8541            "and the task stays in line so the next loop resumes its run"
8542        );
8543        assert_eq!(parked.status, TaskStatus::Parked);
8544        assert_eq!(
8545            parked.park_reason.as_deref(),
8546            Some("parked after `implementing`"),
8547            "the card says where it stopped"
8548        );
8549        assert_eq!(parked.last_error, None, "nothing failed");
8550
8551        // Without the park flag the same non-terminal status is what it always
8552        // was: `execute` returning mid-flight, which is a bug and spends an
8553        // attempt so a task cannot loop on it forever.
8554        let mut broken = task();
8555        broken.start("20260903-183634-2d98".to_owned());
8556        settle(
8557            &mut broken,
8558            Verdict {
8559                status: RunStatus::Implementing,
8560                left_pr: false,
8561                quota_hit: false,
8562                parked: false,
8563                no_viable_candidates: false,
8564            },
8565            "returned mid-flight",
8566            2,
8567        );
8568        assert_eq!(broken.attempts, 1);
8569    }
8570
8571    #[test]
8572    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8573        // Run e633: quorum lost because two judges answered with the wrong
8574        // JSON shape, `quota: []`. Refunding that takes the bound off the
8575        // retry loop, and each retry pays for a fresh hour-long implement
8576        // wave before it can fail the same way.
8577        let mut flaky = task();
8578        flaky.start("20260903-123023-e633".to_owned());
8579        settle(
8580            &mut flaky,
8581            Verdict {
8582                status: RunStatus::Stalled,
8583                left_pr: false,
8584                parked: false,
8585                quota_hit: false,
8586                no_viable_candidates: false,
8587            },
8588            "verdict rests on 1 of 3 judges",
8589            2,
8590        );
8591        assert_eq!(
8592            flaky.attempts, 1,
8593            "flakiness spends an attempt, so `max_attempts` still bounds it"
8594        );
8595        assert!(flaky.status.runnable(), "and it is still worth retrying");
8596
8597        // The same status, lost to a rate limit, is the machine's fault.
8598        let mut limited = task();
8599        limited.start("20260903-123023-e633".to_owned());
8600        settle(
8601            &mut limited,
8602            Verdict {
8603                status: RunStatus::Stalled,
8604                left_pr: false,
8605                parked: false,
8606                quota_hit: true,
8607                no_viable_candidates: false,
8608            },
8609            "judge-2, judge-3 out of quota",
8610            2,
8611        );
8612        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8613        assert!(limited.status.runnable());
8614
8615        // And the bound really binds: a task that keeps stalling on flakiness
8616        // reaches a human instead of running the roster forever.
8617        let mut worn = task();
8618        for _ in 0..2 {
8619            worn.release();
8620        }
8621        worn.start("20260903-123023-e633".to_owned());
8622        worn.attempts = 2;
8623        settle(
8624            &mut worn,
8625            Verdict {
8626                status: RunStatus::Stalled,
8627                left_pr: false,
8628                parked: false,
8629                quota_hit: false,
8630                no_viable_candidates: false,
8631            },
8632            "no quorum again",
8633            2,
8634        );
8635        assert_eq!(worn.status, TaskStatus::Held);
8636        assert!(!worn.status.runnable());
8637    }
8638
8639    #[test]
8640    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8641        // The implement wave loses every seat to the same rate limit and
8642        // `after_implement` bails with nothing viable, which surfaces as
8643        // `Failed` rather than `Stalled`. That is the same machine fact the
8644        // `Stalled`-quota row already refunds, and must be refunded the same
8645        // way, or a quota outage quietly holds every task it touches instead
8646        // of leaving them in line for the reset.
8647        let mut wiped_out = task();
8648        wiped_out.start("20260907-025000-a1b2".to_owned());
8649        settle(
8650            &mut wiped_out,
8651            Verdict {
8652                status: RunStatus::Failed,
8653                left_pr: false,
8654                parked: false,
8655                quota_hit: true,
8656                no_viable_candidates: true,
8657            },
8658            "no candidate produced a change; nothing to judge",
8659            2,
8660        );
8661        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8662        assert!(
8663            wiped_out.status.runnable(),
8664            "a machine problem must leave the task in line"
8665        );
8666
8667        // This is the exemption that must stay narrow: a candidate that did
8668        // produce a change, and then failed for some other reason, still
8669        // spends the attempt even though a seat elsewhere hit its quota.
8670        // Otherwise every ordinary failure that happens to share a run with
8671        // an unrelated rate limit would be refunded for free.
8672        let mut partial_progress = task();
8673        partial_progress.start("20260907-025500-c3d4".to_owned());
8674        settle(
8675            &mut partial_progress,
8676            Verdict {
8677                status: RunStatus::Failed,
8678                left_pr: false,
8679                parked: false,
8680                quota_hit: true,
8681                no_viable_candidates: false,
8682            },
8683            "gate failed on the winning candidate",
8684            2,
8685        );
8686        assert_eq!(
8687            partial_progress.attempts, 1,
8688            "a candidate that actually produced a change spends the attempt \
8689             even though some other seat hit its quota"
8690        );
8691        assert!(partial_progress.status.runnable());
8692    }
8693
8694    #[test]
8695    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8696        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8697        // disk, and that construction must reach the same conclusion as the
8698        // one `attempt` builds from a live run, or a crash at exactly the
8699        // wrong moment gives a recovered task a different policy than one a
8700        // daemon finished settling itself.
8701        let mut t = task();
8702        t.start("20260907-025000-a1b2".to_owned());
8703        let mut state = run_state(RunStatus::Failed);
8704        state.quota.push(QuotaLoss {
8705            cause: crate::agent::QuotaCause::UsageLimit,
8706            agent: String::new(),
8707            seat: "cand-a".to_owned(),
8708            node: "implement".to_owned(),
8709            at: Timestamp::now(),
8710            reset: None,
8711        });
8712        assert!(
8713            state.viable().is_empty(),
8714            "no candidate was added, so nothing is viable"
8715        );
8716        reclaim(&mut t, Some(state), 2, "en");
8717        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8718        assert!(t.status.runnable());
8719    }
8720
8721    #[test]
8722    fn a_held_task_is_never_offered_to_the_loop() {
8723        let dir = tempfile::tempdir().unwrap();
8724        let queue = Queue::at(dir.path().to_path_buf());
8725        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8726            let mut t = task();
8727            t.id = format!("2026090{n}-000000-000{n}");
8728            t.priority = priority;
8729            queue.put(&mut t).unwrap();
8730        }
8731        let mut held = task();
8732        held.id = "20260909-000000-9999".to_owned();
8733        held.priority = 99;
8734        held.hold_machine(None);
8735        queue.put(&mut held).unwrap();
8736
8737        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8738        assert_eq!(order.len(), 3);
8739        assert!(!order.contains(&held.id));
8740        assert_eq!(
8741            order.first().cloned(),
8742            queue.next_runnable().map(|t| t.id),
8743            "the loop's first candidate is exactly what the queue offers"
8744        );
8745        assert_eq!(
8746            order,
8747            vec![
8748                "20260902-000000-0002".to_owned(),
8749                "20260903-000000-0003".to_owned(),
8750                "20260901-000000-0001".to_owned(),
8751            ],
8752            "priority first, then oldest, so nothing starves"
8753        );
8754    }
8755
8756    #[test]
8757    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8758        let dir = tempfile::tempdir().unwrap();
8759        let queue = Queue::at(dir.path().to_path_buf());
8760        let mut old = task();
8761        old.id = "20260101-000000-old0".to_owned();
8762        queue.put(&mut old).unwrap();
8763        let mut fresh = task();
8764        fresh.id = "20260101-000000-new0".to_owned();
8765        queue.put(&mut fresh).unwrap();
8766
8767        // No parseable pid at all, so age is the only signal there is to
8768        // check - unlike a real `Queue::claim`, which always names a real,
8769        // and therefore alive, pid this test cannot fake as dead.
8770        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8771        std::thread::sleep(Duration::from_millis(60));
8772        let live = queue.claim(&fresh.id).unwrap();
8773
8774        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8775        assert_eq!(swept, vec![old.id.clone()]);
8776        assert!(
8777            queue.claim(&old.id).is_ok(),
8778            "an unparseable lock older than the threshold is swept"
8779        );
8780        assert!(
8781            queue.claim(&fresh.id).is_err(),
8782            "a live pid protects its lock regardless of age"
8783        );
8784        drop(live);
8785    }
8786
8787    #[test]
8788    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8789        // A live worker's claim remains authoritative even beyond the sweep's
8790        // age limit. Sweeping it would permit a second competing attempt.
8791        let dir = tempfile::tempdir().unwrap();
8792        let queue = Queue::at(dir.path().to_path_buf());
8793        let mut t = task();
8794        t.id = "20260101-000000-live".to_owned();
8795        queue.put(&mut t).unwrap();
8796
8797        let claim = queue.claim(&t.id).unwrap();
8798        std::thread::sleep(Duration::from_millis(60));
8799
8800        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8801        assert!(
8802            swept.is_empty(),
8803            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8804        );
8805        assert!(
8806            queue.claim(&t.id).is_err(),
8807            "the lock still protects its task"
8808        );
8809        drop(claim);
8810    }
8811
8812    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8813    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8814    fn injected_dead_pid() -> u32 {
8815        std::process::id().checked_add(1).unwrap_or(1)
8816    }
8817
8818    #[test]
8819    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8820        let dir = tempfile::tempdir().unwrap();
8821        let queue = Queue::at(dir.path().to_path_buf());
8822        let mut t = task();
8823        t.id = "20260101-000000-dead".to_owned();
8824        queue.put(&mut t).unwrap();
8825        let dead_pid = injected_dead_pid();
8826
8827        // Written directly rather than through `Queue::claim`, which would
8828        // stamp this test process's own very much alive pid and defeat the
8829        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8830        // like moments after it died, not six hours later.
8831        std::fs::write(
8832            dir.path().join(format!("{}.lock", t.id)),
8833            dead_pid.to_string(),
8834        )
8835        .unwrap();
8836
8837        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8838            pid != dead_pid
8839        });
8840        assert_eq!(
8841            swept,
8842            vec![t.id.clone()],
8843            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8844        );
8845        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8846    }
8847
8848    #[test]
8849    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8850        let dir = tempfile::tempdir().unwrap();
8851        let queue = Queue::at(dir.path().to_path_buf());
8852        let mut t = task();
8853        t.id = "20260101-000000-late".to_owned();
8854        queue.put(&mut t).unwrap();
8855        let dead_pid = injected_dead_pid();
8856
8857        // Tick one, standing in for the sweep `poll` already runs at
8858        // startup: nothing to find yet.
8859        assert!(
8860            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8861            "nothing has claimed the task yet"
8862        );
8863
8864        // A second daemon claims the task and dies before it ever writes
8865        // `running`, well after this loop's own startup sweep already ran.
8866        std::fs::write(
8867            dir.path().join(format!("{}.lock", t.id)),
8868            dead_pid.to_string(),
8869        )
8870        .unwrap();
8871
8872        // Tick two, standing in for a poll long into this daemon's uptime:
8873        // the same function, called again, notices what only just appeared -
8874        // proving the sweep is not a one-shot startup check.
8875        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8876            pid != dead_pid
8877        });
8878        assert_eq!(swept, vec![t.id.clone()]);
8879    }
8880
8881    #[test]
8882    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8883        // `reclaim_orphaned_running` looks up the task's last run, which
8884        // touches `run::home()`; the first call anywhere in this binary wins,
8885        // so this is a no-op if another test already pinned one, and either
8886        // way the run id below is never written under it.
8887        crate::run::pin_test_home();
8888        let dir = tempfile::tempdir().unwrap();
8889        let queue = Queue::at(dir.path().to_path_buf());
8890        let mut t = task();
8891        t.id = "20260101-000000-crsh".to_owned();
8892        t.status = TaskStatus::Running;
8893        t.attempts = 1;
8894        // No `run.json` behind this id: standing in for a run this test does
8895        // not need to make readable, since the point is the lock, not the
8896        // recovery table `reclaim` already has its own tests for.
8897        t.runs.push("20260904-000000-4043".to_owned());
8898        queue.put(&mut t).unwrap();
8899        let dead_pid = injected_dead_pid();
8900
8901        // The crashed daemon's own claim, naming a pid nothing on the
8902        // machine holds anymore.
8903        std::fs::write(
8904            dir.path().join(format!("{}.lock", t.id)),
8905            dead_pid.to_string(),
8906        )
8907        .unwrap();
8908
8909        // Before the lock is swept the task looks claimed, and
8910        // `reclaim_orphaned_running` must leave it alone - this is exactly
8911        // the bug: a `running` task stranded behind a dead daemon's lock,
8912        // invisible to the claim-as-proof check because the lock outlived
8913        // the process that wrote it.
8914        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8915        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8916
8917        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8918            pid != dead_pid
8919        });
8920        assert_eq!(swept, vec![t.id.clone()]);
8921
8922        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8923        assert_eq!(reclaimed, vec![t.id.clone()]);
8924        let after = queue.get(&t.id).unwrap();
8925        assert_eq!(
8926            after.status,
8927            TaskStatus::Held,
8928            "no run.json to recover from, so a human is asked"
8929        );
8930        assert_eq!(
8931            after.runs,
8932            vec!["20260904-000000-4043".to_owned()],
8933            "the crashed run's id is kept as evidence, not discarded"
8934        );
8935    }
8936
8937    #[test]
8938    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8939        let dir = tempfile::tempdir().unwrap();
8940        let queue = Queue::at(dir.path().to_path_buf());
8941        let mut t = task();
8942        t.id = "20260101-000000-unknown".to_owned();
8943        queue.put(&mut t).unwrap();
8944        let dead_pid = injected_dead_pid();
8945        std::fs::write(
8946            dir.path().join(format!("{}.lock", t.id)),
8947            dead_pid.to_string(),
8948        )
8949        .unwrap();
8950
8951        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8952        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8953        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8954    }
8955
8956    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8957        let mut s = run_state(status);
8958        s.config.graph.language = language.to_owned();
8959        s
8960    }
8961
8962    fn unstarted_verdict(status: RunStatus) -> Verdict {
8963        Verdict {
8964            status,
8965            left_pr: false,
8966            quota_hit: false,
8967            parked: false,
8968            no_viable_candidates: false,
8969        }
8970    }
8971
8972    #[test]
8973    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8974        let mut t = task();
8975        t.attempts = 1;
8976        settle_in(
8977            &mut t,
8978            unstarted_verdict(RunStatus::AlreadyInBase),
8979            "already in main",
8980            1,
8981            phrases("en"),
8982        );
8983        assert_eq!(t.status, TaskStatus::Done);
8984        assert_eq!(t.attempts, 0);
8985    }
8986
8987    #[test]
8988    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8989        let reason = |language: &str| {
8990            let mut t = task();
8991            settle_in(
8992                &mut t,
8993                unstarted_verdict(RunStatus::Judging),
8994                "boom",
8995                1,
8996                phrases(language),
8997            );
8998            t.last_error.or(t.hold_reason).unwrap_or_default()
8999        };
9000        assert!(
9001            reason("en").starts_with("the graph stopped at `"),
9002            "{}",
9003            reason("en")
9004        );
9005        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9006        assert!(reason("日本語").contains("boom"));
9007        assert_eq!(reason("fr"), reason("en"));
9008    }
9009
9010    #[test]
9011    fn describe_follows_the_run_language_and_keeps_the_run_id() {
9012        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9013        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9014        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9015        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9016        assert!(ja.contains("[run "), "{ja}");
9017        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9018        assert!(ended.starts_with("run 終了: "), "{ended}");
9019        let mut de = run_state_in(RunStatus::Failed, "de");
9020        let mut en = run_state_in(RunStatus::Failed, "en");
9021        de.id = "same".to_owned();
9022        en.id = "same".to_owned();
9023        assert_eq!(describe(&de), describe(&en));
9024    }
9025
9026    #[test]
9027    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9028        use crate::handover::Refused;
9029        let cases = [
9030            Refused::Foreign {
9031                branch: "b".into(),
9032                path: "/w/x".into(),
9033                why: "made by hand".into(),
9034            },
9035            Refused::Unsafe {
9036                branch: "b".into(),
9037                path: "/w/x".into(),
9038                why: "its worktree has uncommitted changes (a.rs)".into(),
9039            },
9040            Refused::ReleaseFailed {
9041                branch: "b".into(),
9042                path: "/w/x".into(),
9043                run: "ab12".into(),
9044            },
9045        ];
9046        for r in &cases {
9047            let en = (phrases("en").handover_refused)(r);
9048            assert_eq!(en, r.to_string());
9049            let ja = (phrases("ja").handover_refused)(r);
9050            assert!(
9051                !ja.contains("is checked out") && !ja.contains("try again"),
9052                "{ja}"
9053            );
9054            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9055            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9056                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9057            }
9058        }
9059        assert!(phrases("en").handover_hint.contains("release the task"));
9060        assert!(phrases("ja").handover_hint.contains("解放"));
9061    }
9062
9063    #[test]
9064    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9065        let build = |lang: &str| {
9066            let mut s = run_state_in(RunStatus::Blocked, lang);
9067            s.id = "same".to_owned();
9068            s.config.graph.review_rounds = 3;
9069            let mut r = review_round(3);
9070            r.expected = 3;
9071            r.answered = 1;
9072            s.reviews.push(r);
9073            s.event(
9074                "review",
9075                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9076            );
9077            s
9078        };
9079        let en = describe(&build("en"));
9080        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9081        let ja = describe(&build("ja"));
9082        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9083        assert!(!ja.contains("never answered"), "{ja}");
9084        assert!(ja.contains("[run "), "{ja}");
9085
9086        // An incomplete panel whose verification failed is a different stop:
9087        // the real event must survive in ja too.
9088        let mut failed = build("ja");
9089        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9090            command: "cargo test".to_owned(),
9091            code: Some(1),
9092            output_tail: String::new(),
9093            duration_ms: 0,
9094            resource_blocked: false,
9095        });
9096        failed.event("review", "stopped; e2e failed: cargo test");
9097        let ja = describe(&failed);
9098        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9099        assert!(!ja.contains("席のレビュアー"), "{ja}");
9100    }
9101
9102    #[test]
9103    fn refusals_and_recovery_prose_follow_the_language() {
9104        let home = crate::run::test_home();
9105        let t = held_task_with("r1");
9106        let q = action_question(
9107            "r1",
9108            ask::ChoiceAction::Resume {
9109                run: "r1".to_owned(),
9110            },
9111        );
9112        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9113            ActionDecision::Refuse(s) => s,
9114            other => panic!("{other:?}"),
9115        };
9116        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9117        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9118        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9119
9120        let mut held = task();
9121        reclaim(&mut held, None, 2, "ja");
9122        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9123        let mut held = task();
9124        reclaim(&mut held, None, 2, "xx");
9125        assert!(held.hold_reason.unwrap().contains("held for a human"));
9126    }
9127
9128    fn run_state(status: RunStatus) -> RunState {
9129        let mut state = RunState::new(
9130            PathBuf::from("/repo"),
9131            "main".to_owned(),
9132            "abc1234def".to_owned(),
9133            "add retries".to_owned(),
9134            Config::default(),
9135        );
9136        state.status = status;
9137        state
9138    }
9139
9140    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9141        Candidate {
9142            index: 0,
9143            label,
9144            agent: "claude".to_owned(),
9145            branch: format!("magi/x/{label}"),
9146            worktree: PathBuf::from("/repo"),
9147            summary: summary.to_owned(),
9148            stat: String::new(),
9149            files: 0,
9150            commits: usize::from(!empty),
9151            empty,
9152            failed: failed.map(str::to_owned),
9153            verified_noop: None,
9154            duration_ms: 0,
9155            folded: false,
9156        }
9157    }
9158
9159    #[test]
9160    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9161        let mut state = run_state(RunStatus::Blocked);
9162        state.gate = vec![
9163            CommandOutcome {
9164                command: "cargo make check".to_owned(),
9165                code: Some(0),
9166                output_tail: "ok".to_owned(),
9167                duration_ms: 0,
9168                resource_blocked: false,
9169            },
9170            CommandOutcome {
9171                command: "cargo test".to_owned(),
9172                code: Some(101),
9173                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9174                duration_ms: 0,
9175                resource_blocked: false,
9176            },
9177        ];
9178        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9179        assert!(d.contains("cargo test"), "{d}");
9180        assert!(
9181            !d.contains("cargo make check"),
9182            "a passing check is not a diagnostic: {d}"
9183        );
9184        assert!(d.contains("assertion failed"), "{d}");
9185    }
9186
9187    #[test]
9188    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9189        let mut state = run_state(RunStatus::Blocked);
9190        state.event(
9191            "land",
9192            "stopped: the fixer produced no commit while 2 check(s) were failing \
9193             (build, lint); stopping instead of looping on an unchanged tree",
9194        );
9195        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9196        assert!(d.contains("build"), "{d}");
9197        assert!(d.contains("lint"), "{d}");
9198        assert!(d.contains("fixer produced no commit"), "{d}");
9199    }
9200
9201    #[test]
9202    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9203        // `describe`'s output becomes `Task::last_error` verbatim, and the
9204        // phone renders that in the same alarm-styled box an ordinary
9205        // failure gets. A bare `verified_noop` there would read exactly like
9206        // the failure this status exists to be told apart from.
9207        let state = run_state(RunStatus::VerifiedNoop);
9208        let d = describe(&state);
9209        assert!(
9210            d.contains("agent-verified no-op"),
9211            "expected the display label, not the wire spelling: {d}"
9212        );
9213        assert!(!d.contains("verified_noop"), "{d}");
9214    }
9215
9216    #[test]
9217    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9218        let mut state = run_state(RunStatus::Failed);
9219        state.gate.push(crate::run::CommandOutcome {
9220            command: "cargo test".into(),
9221            code: Some(101),
9222            output_tail: format!(
9223                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9224                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9225            ),
9226            duration_ms: 1,
9227            resource_blocked: false,
9228        });
9229        let d = diagnostic(&state).unwrap();
9230        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9231        assert!(d.contains("assertion failed: widget missing"));
9232        assert!(d.contains("widget log"));
9233    }
9234
9235    #[test]
9236    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9237        // The whole point of the feature: a run held as "no candidate produced
9238        // a change" can mean the implementer actually finished the task and
9239        // only left a clean local tree behind - see AGENTS.md on this exact
9240        // failure mode. The diagnostic has to carry what the agent actually
9241        // said, not just the fact that nothing was there to judge.
9242        let mut state = run_state(RunStatus::Failed);
9243        state.candidates = vec![candidate(
9244            'A',
9245            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9246            true,
9247            None,
9248        )];
9249        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9250        assert!(d.contains("candidate A"), "{d}");
9251        assert!(d.contains("tagged v1.2.3"), "{d}");
9252    }
9253
9254    #[test]
9255    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9256        let mut state = run_state(RunStatus::Failed);
9257        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9258        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9259        assert!(d.contains("candidate A"), "{d}");
9260        assert!(d.contains("agent timed out"), "{d}");
9261    }
9262
9263    #[test]
9264    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9265        // A viable candidate existed, the gate never ran, and nothing land
9266        // said matches - `Task::last_error` is left to explain this one alone.
9267        let mut state = run_state(RunStatus::Failed);
9268        state.candidates = vec![candidate('A', "did the work", false, None)];
9269        assert!(diagnostic(&state).is_none());
9270    }
9271
9272    #[test]
9273    fn diagnostic_is_bounded_however_much_a_run_printed() {
9274        let mut state = run_state(RunStatus::Blocked);
9275        state.gate = vec![
9276            CommandOutcome {
9277                command: "cargo test".to_owned(),
9278                code: Some(101),
9279                output_tail: "x".repeat(50_000),
9280                duration_ms: 0,
9281                resource_blocked: false,
9282            },
9283            CommandOutcome {
9284                command: "cargo clippy".to_owned(),
9285                code: Some(1),
9286                output_tail: "y".repeat(50_000),
9287                duration_ms: 0,
9288                resource_blocked: false,
9289            },
9290        ];
9291        state.candidates = vec![
9292            candidate('A', &"z".repeat(50_000), true, None),
9293            candidate('B', &"w".repeat(50_000), true, None),
9294        ];
9295        let d = diagnostic(&state).expect("plenty here to diagnose");
9296        assert!(
9297            d.len() <= DIAGNOSTIC_MAX,
9298            "diagnostic grew to {} bytes, unbounded",
9299            d.len()
9300        );
9301    }
9302
9303    #[test]
9304    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9305        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9306            let mut t = task();
9307            let mut state = run_state(status);
9308            t.pr_recovery = Some(crate::pr_recovery::Selection {
9309                url: "url".into(),
9310                branch: format!("magi/task-{}", t.id),
9311                head: "a".repeat(40),
9312                source_head: None,
9313                source_run: None,
9314                source_proof: None,
9315                disposition: Some(crate::pr_recovery::Disposition::Land),
9316                instruction: t.instruction.clone(),
9317                approved_at: Timestamp::now(),
9318            });
9319            state.pr_recovery = t.pr_recovery.clone();
9320            t.start(state.id.clone());
9321            settle_and_diagnose(
9322                &mut t,
9323                Verdict {
9324                    status,
9325                    left_pr: false,
9326                    quota_hit: false,
9327                    parked: false,
9328                    no_viable_candidates: false,
9329                },
9330                "delivery stopped",
9331                5,
9332                &state,
9333            );
9334            assert_eq!(t.status, TaskStatus::Held);
9335            let reason = t.hold_reason.as_deref().unwrap();
9336            if status == RunStatus::Ready {
9337                assert!(reason.contains("Selected PR delivery is incomplete"));
9338                assert!(t.recovery_budget.is_none());
9339            } else {
9340                assert!(reason.contains("Selected recovery stopped"));
9341                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9342            }
9343            assert!(t.pr_recovery.is_some());
9344        }
9345    }
9346
9347    #[test]
9348    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9349        let mut state = run_state(RunStatus::Voting);
9350        state.base_sync = Some(crate::run::BaseSync {
9351            tip: "base-tip".into(),
9352            behind: 3,
9353            attempts: 4,
9354            conflict: Some("base stopped".into()),
9355            already_in: None,
9356        });
9357        state.record_base_sync_stop("candidate-head");
9358        let mut t = task();
9359        t.start(state.id.clone());
9360        let verdict = Verdict {
9361            status: RunStatus::Blocked,
9362            left_pr: false,
9363            quota_hit: false,
9364            parked: false,
9365            no_viable_candidates: false,
9366        };
9367        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9368        assert_eq!(
9369            t.status,
9370            TaskStatus::Held,
9371            "unspent task attempts cannot start another competition"
9372        );
9373        let at = t.held_at;
9374        let cause = t.hold_notice_cause.clone();
9375        state.begin_pass();
9376        t.release_operator("test-resume", None);
9377        t.start(state.id.clone());
9378        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9379        assert_eq!(t.status, TaskStatus::Held);
9380        assert_eq!(t.held_at, at);
9381        assert_eq!(t.hold_notice_cause, cause);
9382    }
9383
9384    #[test]
9385    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9386        let mut state = run_state(RunStatus::Blocked);
9387        state.gate = vec![CommandOutcome {
9388            command: "cargo test".to_owned(),
9389            code: Some(101),
9390            output_tail: "assertion failed".to_owned(),
9391            duration_ms: 0,
9392            resource_blocked: false,
9393        }];
9394        let verdict = Verdict {
9395            status: RunStatus::Blocked,
9396            left_pr: false,
9397            quota_hit: false,
9398            parked: false,
9399            no_viable_candidates: false,
9400        };
9401
9402        // Attempt one of two still has a retry coming: no diagnostic yet, the
9403        // task is going to run again and this run's evidence would go stale.
9404        let mut t = task();
9405        t.start("run-1".to_owned());
9406        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9407        assert_eq!(t.status, TaskStatus::Failed);
9408        assert!(t.diagnostic.is_none());
9409
9410        // Attempt two exhausts the budget: now it is held, and the
9411        // diagnostic is what `magi task show` has to say more than one line.
9412        t.start("run-2".to_owned());
9413        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9414        assert_eq!(t.status, TaskStatus::Held);
9415        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9416        assert!(d.contains("cargo test"), "{d}");
9417    }
9418
9419    #[test]
9420    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9421        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9422        // `magi ask` question settled Held with `hold_reason: null`, so the
9423        // notification said nothing actionable. `note_open_question` should
9424        // append the question id to whatever `handed_off` already wrote.
9425        crate::run::pin_test_home();
9426        let home = crate::run::home();
9427        let state = run_state(RunStatus::VerifiedNoop);
9428        let mut q = ask::Question::new(
9429            state.id.clone(),
9430            "implement".to_owned(),
9431            "impl-A".to_owned(),
9432            "is this really a no-op?".to_owned(),
9433            String::new(),
9434            Vec::new(),
9435        );
9436        Questions::at(home.join("questions")).put(&mut q).unwrap();
9437
9438        let verdict = Verdict {
9439            status: RunStatus::VerifiedNoop,
9440            left_pr: false,
9441            quota_hit: false,
9442            parked: false,
9443            no_viable_candidates: false,
9444        };
9445        let mut t = task();
9446        t.start(state.id.clone());
9447        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9448
9449        assert_eq!(t.status, TaskStatus::Held);
9450        let reason = t.hold_reason.expect("a held task must record why");
9451        assert!(
9452            reason.starts_with("run ended agent-verified no-op"),
9453            "the original settle reason must survive unchanged: {reason}"
9454        );
9455        assert!(
9456            reason.contains(q.short()),
9457            "the open question's id must be named so the notice is actionable: {reason}"
9458        );
9459    }
9460
9461    #[test]
9462    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9463        crate::run::pin_test_home();
9464        let state = run_state(RunStatus::VerifiedNoop);
9465
9466        let verdict = Verdict {
9467            status: RunStatus::VerifiedNoop,
9468            left_pr: false,
9469            quota_hit: false,
9470            parked: false,
9471            no_viable_candidates: false,
9472        };
9473        let mut t = task();
9474        t.start(state.id.clone());
9475        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9476
9477        assert_eq!(t.status, TaskStatus::Held);
9478        assert_eq!(
9479            t.hold_reason.as_deref(),
9480            Some("run ended agent-verified no-op"),
9481            "nothing to append when the question was already answered or never asked"
9482        );
9483    }
9484
9485    #[test]
9486    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9487        crate::run::pin_test_home();
9488        let mut first = run_state(RunStatus::Blocked);
9489        first.id = "20260101-000000-sup1".to_owned();
9490        first.save().unwrap();
9491        let mut second = run_state(RunStatus::Merged);
9492        second.id = "20260101-000000-sup2".to_owned();
9493        second.save().unwrap();
9494
9495        let mut t = task();
9496        t.runs = vec![first.id.clone(), second.id.clone()];
9497        t.status = TaskStatus::Done;
9498
9499        supersede_prior_runs(&t, &crate::run::home());
9500
9501        assert_eq!(
9502            RunState::load(&first.id).unwrap().status,
9503            RunStatus::Superseded,
9504            "the first attempt's Blocked no longer needs anyone's attention"
9505        );
9506        assert_eq!(
9507            RunState::load(&second.id).unwrap().status,
9508            RunStatus::Merged,
9509            "the run that actually succeeded is left exactly as it was"
9510        );
9511    }
9512
9513    #[test]
9514    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9515        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9516        // --resume` invoked by hand outside the daemon never touches
9517        // `daemon.json` at all, so it would look identical to a genuinely
9518        // idle run without also consulting `RunState::liveness`, which reads
9519        // this run's own recorded `driver_pid` instead.
9520        crate::run::pin_test_home();
9521        let mut first = run_state(RunStatus::Blocked);
9522        first.id = "20260101-000000-sup9".to_owned();
9523        // This test process's own pid: guaranteed alive without needing a
9524        // real second process or daemon.
9525        first.driver_pid = Some(std::process::id());
9526        first.driver_started_at = Some(
9527            crate::proc::process_started_at(std::process::id())
9528                .expect("this test process's own start time must be queryable"),
9529        );
9530        first.save().unwrap();
9531        let mut second = run_state(RunStatus::Merged);
9532        second.id = "20260101-000000-supa".to_owned();
9533        second.save().unwrap();
9534
9535        let mut t = task();
9536        t.runs = vec![first.id.clone(), second.id.clone()];
9537        t.status = TaskStatus::Done;
9538
9539        supersede_prior_runs(&t, &crate::run::home());
9540
9541        assert_eq!(
9542            RunState::load(&first.id).unwrap().status,
9543            RunStatus::Blocked,
9544            "a live driver_pid means something is still actually working this run, \
9545             even though no daemon claims it - rewriting under it would just be \
9546             undone the next time that process saves"
9547        );
9548    }
9549
9550    #[test]
9551    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9552        // The first resweep must skip a still-live attempt exactly like
9553        // `supersede_prior_runs` itself does; a later resweep, once that
9554        // process is no longer actually driving it, is what closes the gap
9555        // `supersede_prior_runs` alone leaves - a task only ever reaches
9556        // `Done` once, so nothing else would ever look at this run again.
9557        let dir = tempfile::tempdir().unwrap();
9558        let home = dir.path().to_path_buf();
9559        let queue = Queue::at(dir.path().join("queue"));
9560
9561        let mut first = run_state(RunStatus::Blocked);
9562        first.id = "20260101-000000-supd".to_owned();
9563        first.driver_pid = Some(std::process::id());
9564        first.driver_started_at = Some(
9565            crate::proc::process_started_at(std::process::id())
9566                .expect("this test process's own start time must be queryable"),
9567        );
9568        first.save_under(&home).unwrap();
9569        let mut second = run_state(RunStatus::Merged);
9570        second.id = "20260101-000000-supe".to_owned();
9571        second.save_under(&home).unwrap();
9572
9573        let mut t = task();
9574        t.runs = vec![first.id.clone(), second.id.clone()];
9575        t.status = TaskStatus::Done;
9576        queue.put(&mut t).unwrap();
9577
9578        resweep_superseded_attempts(&queue, &home);
9579        assert_eq!(
9580            RunState::load_under(&first.id, &home).unwrap().status,
9581            RunStatus::Blocked,
9582            "still live on the first pass, so still untouched"
9583        );
9584
9585        // Stand in for the manual process no longer being the one driving
9586        // this run: same pid (this test process really is still alive), but
9587        // an identity marker that no longer matches it - see
9588        // `RunState::liveness`'s own doc for why a mismatched
9589        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9590        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9591        stale.driver_started_at = Some("1".to_owned());
9592        stale.save_under(&home).unwrap();
9593
9594        resweep_superseded_attempts(&queue, &home);
9595        assert_eq!(
9596            RunState::load_under(&first.id, &home).unwrap().status,
9597            RunStatus::Superseded,
9598            "the second pass catches up what the first one correctly skipped"
9599        );
9600    }
9601
9602    #[test]
9603    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9604        crate::run::pin_test_home();
9605        let mut first = run_state(RunStatus::Blocked);
9606        first.id = "20260101-000000-sup3".to_owned();
9607        first.save().unwrap();
9608        let mut second = run_state(RunStatus::Blocked);
9609        second.id = "20260101-000000-sup4".to_owned();
9610        second.save().unwrap();
9611
9612        let mut t = task();
9613        t.runs = vec![first.id.clone(), second.id.clone()];
9614        // Still retrying: nothing about this task's story is settled yet, so
9615        // neither Blocked run may be relabelled, even though a later attempt
9616        // already exists.
9617        t.status = TaskStatus::Failed;
9618
9619        supersede_prior_runs(&t, &crate::run::home());
9620
9621        assert_eq!(
9622            RunState::load(&first.id).unwrap().status,
9623            RunStatus::Blocked
9624        );
9625        assert_eq!(
9626            RunState::load(&second.id).unwrap().status,
9627            RunStatus::Blocked
9628        );
9629    }
9630
9631    #[test]
9632    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9633        // `magi task done` (or the API's equivalent) can close a task with no
9634        // run of its own ever having succeeded - there is nothing here that
9635        // counts as "the attempt that finished it", so nothing is rewritten.
9636        crate::run::pin_test_home();
9637        let mut first = run_state(RunStatus::Blocked);
9638        first.id = "20260101-000000-sup5".to_owned();
9639        first.save().unwrap();
9640
9641        let mut t = task();
9642        t.runs = vec![first.id.clone()];
9643        t.status = TaskStatus::Done;
9644
9645        supersede_prior_runs(&t, &crate::run::home());
9646
9647        assert_eq!(
9648            RunState::load(&first.id).unwrap().status,
9649            RunStatus::Blocked,
9650            "a single-attempt task has no earlier run to supersede"
9651        );
9652    }
9653
9654    #[test]
9655    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9656        // `magi task done` (or the web/conductor equivalents) can close a
9657        // task in any status, including one whose *last* recorded attempt is
9658        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9659        // never watched, say. `runs.last()` being `Done`-adjacent is not
9660        // proof it actually succeeded, so nothing earlier may be relabelled
9661        // on its say-so alone.
9662        crate::run::pin_test_home();
9663        let mut first = run_state(RunStatus::Blocked);
9664        first.id = "20260101-000000-supb".to_owned();
9665        first.save().unwrap();
9666        let mut second = run_state(RunStatus::Failed);
9667        second.id = "20260101-000000-supc".to_owned();
9668        second.save().unwrap();
9669
9670        let mut t = task();
9671        t.runs = vec![first.id.clone(), second.id.clone()];
9672        t.status = TaskStatus::Done;
9673
9674        supersede_prior_runs(&t, &crate::run::home());
9675
9676        assert_eq!(
9677            RunState::load(&first.id).unwrap().status,
9678            RunStatus::Blocked,
9679            "the task's last attempt never landed, so there is nothing here \
9680             actually superseding it"
9681        );
9682    }
9683
9684    #[test]
9685    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9686        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9687        // to look" - `Failed` and `VerifiedNoop` are already their own
9688        // terminal answers and must not be relabelled into a third one.
9689        crate::run::pin_test_home();
9690        let mut failed = run_state(RunStatus::Failed);
9691        failed.id = "20260101-000000-sup6".to_owned();
9692        failed.save().unwrap();
9693        let mut noop = run_state(RunStatus::VerifiedNoop);
9694        noop.id = "20260101-000000-sup7".to_owned();
9695        noop.save().unwrap();
9696        let mut winner = run_state(RunStatus::Ready);
9697        winner.id = "20260101-000000-sup8".to_owned();
9698        winner.save().unwrap();
9699
9700        let mut t = task();
9701        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9702        t.status = TaskStatus::Done;
9703
9704        supersede_prior_runs(&t, &crate::run::home());
9705
9706        assert_eq!(
9707            RunState::load(&failed.id).unwrap().status,
9708            RunStatus::Failed
9709        );
9710        assert_eq!(
9711            RunState::load(&noop.id).unwrap().status,
9712            RunStatus::VerifiedNoop
9713        );
9714    }
9715
9716    fn approval_question(run: &str) -> ask::Question {
9717        ask::Question::new(
9718            run.to_owned(),
9719            land::APPROVAL_NODE.to_owned(),
9720            "land".to_owned(),
9721            "merge?".to_owned(),
9722            String::new(),
9723            vec!["merge".to_owned(), "hold".to_owned()],
9724        )
9725    }
9726
9727    #[test]
9728    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9729        crate::run::pin_test_home();
9730        let mut state = run_state(RunStatus::Landing);
9731        state.id = "20260101-000000-fre1".to_owned();
9732        state.parked = true;
9733        state.save().unwrap();
9734        ask::Questions::open()
9735            .put(&mut approval_question(&state.id))
9736            .unwrap();
9737
9738        let mut t = task();
9739        t.runs.push(state.id.clone());
9740        assert_eq!(
9741            land_resume_state(&t),
9742            LandResume::StillWaiting,
9743            "nobody has answered and the timeout has not passed"
9744        );
9745    }
9746
9747    #[test]
9748    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9749        crate::run::pin_test_home();
9750        let mut state = run_state(RunStatus::Gating);
9751        state.id = "20260101-000000-gt01".to_owned();
9752        state.parked = true;
9753        state.config.graph.answer_timeout = 60;
9754        state.github_text = Some(crate::run::GithubTextAsk {
9755            rewrite: None,
9756            fingerprint: "f".into(),
9757            title: true,
9758            body: false,
9759            categories: vec!["title-language".into()],
9760            question: None,
9761            asks: 1,
9762            resolved: false,
9763            chosen_title: None,
9764            choice: None,
9765            publication: None,
9766        });
9767        state.save().unwrap();
9768        let store = ask::Questions::open();
9769        let mut q = ask::Question::new(
9770            state.id.clone(),
9771            crate::github_text::ASK_NODE.to_owned(),
9772            crate::github_text::ASK_SEAT.to_owned(),
9773            "s".into(),
9774            String::new(),
9775            vec!["use fallback".into()],
9776        );
9777        store.put(&mut q).unwrap();
9778        let mut t = task();
9779        t.runs.push(state.id.clone());
9780        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9781        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9782        store.put(&mut q).unwrap();
9783        assert_eq!(land_resume_state(&t), LandResume::Ready);
9784        assert!(!store.get(&q.id).unwrap().status.open());
9785        // Once decided, a parked run is an ordinary candidate again.
9786        state.github_text.as_mut().unwrap().resolved = true;
9787        state.save().unwrap();
9788        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9789    }
9790
9791    #[test]
9792    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9793        // `ask::ask_and_wait`'s own deadline used to retire a question
9794        // nobody answered; land's approval bypasses that wait (see
9795        // `land::approval_gate`), so this is now the only place
9796        // `graph.answer_timeout` is enforced for a land approval at all.
9797        crate::run::pin_test_home();
9798        let mut state = run_state(RunStatus::Landing);
9799        state.id = "20260101-000000-exp1".to_owned();
9800        state.parked = true;
9801        state.config.graph.answer_timeout = 60;
9802        state.save().unwrap();
9803
9804        let store = ask::Questions::open();
9805        let mut q = approval_question(&state.id);
9806        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9807        store.put(&mut q).unwrap();
9808
9809        let mut t = task();
9810        t.runs.push(state.id.clone());
9811        assert_eq!(
9812            land_resume_state(&t),
9813            LandResume::Ready,
9814            "an expired question must not be waited on forever"
9815        );
9816
9817        let after = store.get(&q.id).unwrap();
9818        assert!(
9819            !after.status.open(),
9820            "the question is abandoned, not silently ignored"
9821        );
9822        assert!(
9823            after.resolution().is_none(),
9824            "an abandoned question is not read as a decision"
9825        );
9826    }
9827
9828    #[test]
9829    fn reclaim_settles_a_running_task_against_its_last_run() {
9830        let mut t = task();
9831        t.start("20260904-000000-4043".to_owned());
9832        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9833        assert_eq!(
9834            t.status,
9835            TaskStatus::Done,
9836            "a run that actually finished must not stay `running` forever"
9837        );
9838    }
9839
9840    #[test]
9841    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
9842        let dir = tempfile::tempdir().unwrap();
9843        let queue = Queue::at(dir.path().join("queue"));
9844        let mut task = task();
9845        let mut run = run_state(RunStatus::Blocked);
9846        run.reserve_under(dir.path()).unwrap();
9847        run.driver_exited = true;
9848        run.save_under(dir.path()).unwrap();
9849        queue.put(&mut task).unwrap();
9850        let stale = task.clone();
9851        task.resume_override = Some(crate::queue::OperatorResume {
9852            question_id: "pending-resume".into(),
9853            at: Timestamp::now(),
9854            conductor_rehold: None,
9855            forced: true,
9856            pinned_run: Some(run.id.clone()),
9857        });
9858        task.start(run.id.clone());
9859        queue.put(&mut task).unwrap();
9860        // Discard every in-memory handoff, as a worker death before execute does.
9861        let mut recovered = queue.get(&task.id).unwrap();
9862        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
9863        reclaim(&mut recovered, Some(disk), 2, "en");
9864        queue.put(&mut recovered).unwrap();
9865        assert!(recovered.resume_override.is_none());
9866        assert_eq!(
9867            recovered.dispatched_resumes.get("pending-resume"),
9868            Some(&run.id)
9869        );
9870        let mut stale = stale;
9871        queue.put(&mut stale).unwrap();
9872        assert_eq!(
9873            stale.dispatched_resumes, recovered.dispatched_resumes,
9874            "a stale task writer cannot erase dispatch ownership"
9875        );
9876        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
9877        assert!(resumed.decision_starts.is_empty());
9878        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
9879        assert!(
9880            resumed.decision_starts.is_empty(),
9881            "handoff is not execution proof"
9882        );
9883        resumed.begin_pass();
9884        resumed.save_under(dir.path()).unwrap();
9885        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
9886        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
9887        disk.carry_dispatched_resumes(&recovered);
9888        disk.begin_pass();
9889        assert_eq!(
9890            disk.decision_starts.get("pending-resume"),
9891            Some(&0),
9892            "later execution must preserve the original pass receipt"
9893        );
9894    }
9895
9896    #[test]
9897    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9898        let mut t = task();
9899        t.start("20260904-000000-4043".to_owned());
9900        t.last_error = Some("earlier trouble".to_owned());
9901        let mut state = run_state(RunStatus::Judging);
9902        state.parked = true;
9903        reclaim(&mut t, Some(state), 1, "en");
9904        assert_eq!(t.status, TaskStatus::Parked);
9905        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9906        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9907        assert!(t.park_reason.is_some());
9908        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9909        assert!(!t.fresh_start);
9910        assert!(t.status.runnable());
9911    }
9912
9913    #[test]
9914    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9915        let mut t = task();
9916        t.start("20260904-000000-4043".to_owned());
9917        t.last_error = Some("earlier trouble".to_owned());
9918        settle(
9919            &mut t,
9920            Verdict {
9921                status: RunStatus::Judging,
9922                left_pr: false,
9923                quota_hit: false,
9924                parked: true,
9925                no_viable_candidates: false,
9926            },
9927            "parked after `judging`",
9928            1,
9929        );
9930        assert_eq!(t.status, TaskStatus::Parked);
9931        assert_eq!(t.attempts, 0);
9932        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9933        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9934        assert_eq!(t.schema, crate::queue::SCHEMA);
9935        assert!(
9936            crate::notices::task_held(&t).is_none(),
9937            "a park is not news"
9938        );
9939        t.start("20260904-000000-4043".to_owned());
9940        assert_eq!(t.park_reason, None);
9941    }
9942
9943    #[test]
9944    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9945        // A blocked run with attempts left goes back to `Failed`, exactly as
9946        // it would from `attempt` itself - `reclaim` must not invent a second
9947        // policy for a task a daemon merely stopped without reporting.
9948        let mut t = task();
9949        t.start("20260904-000000-4043".to_owned());
9950        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9951        assert_eq!(t.status, TaskStatus::Failed);
9952        assert!(t.status.runnable());
9953    }
9954
9955    #[test]
9956    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9957        let mut t = task();
9958        t.start("20260904-000000-4043".to_owned());
9959        assert_eq!(t.attempts, 1);
9960        let mut run = run_state(RunStatus::Implementing);
9961        run.id = "20260904-000000-4043".to_owned();
9962        run.begin_pass();
9963        let cause = crate::run::ParkCause::Upgrade {
9964            from: "0.121.0".to_owned(),
9965            to: Some("0.121.1".to_owned()),
9966        };
9967        run.end_pass_parked(cause.clone());
9968        run.parked = true;
9969        let verdict = Verdict {
9970            status: run.status,
9971            left_pr: false,
9972            quota_hit: false,
9973            parked: true,
9974            no_viable_candidates: false,
9975        };
9976        // A crash after the checkpoint but before queue settlement must
9977        // recover exactly the same scheduling evidence and refund.
9978        let mut orphan = t.clone();
9979        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9980        assert_eq!(orphan.status, TaskStatus::Parked);
9981        assert_eq!(orphan.attempts, 0);
9982        assert_eq!(
9983            orphan.upgrade_resume_key(),
9984            Some((run.passes[0].started_at, orphan.id.as_str()))
9985        );
9986        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9987        assert_eq!(t.attempts, 0);
9988        assert_eq!(t.passes.len(), 1);
9989        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9990        assert_eq!(t.passes[0].parked, Some(cause));
9991        assert_eq!(t.passes[0].pass_index, 0);
9992        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9993        assert!(t.upgrade_resume_key().is_some());
9994
9995        // A resumed pass that then fails spends its attempt, and the earlier
9996        // pass's entry is untouched.
9997        t.start("20260904-000000-4043".to_owned());
9998        run.begin_pass();
9999        run.status = RunStatus::Failed;
10000        let verdict = Verdict {
10001            status: RunStatus::Failed,
10002            left_pr: false,
10003            quota_hit: false,
10004            parked: false,
10005            no_viable_candidates: false,
10006        };
10007        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10008        assert_eq!(t.passes.len(), 2);
10009        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10010        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10011        assert_eq!(t.passes[1].pass_index, 1);
10012        assert_eq!(t.attempts, 1);
10013    }
10014
10015    #[test]
10016    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10017        let mut t = task();
10018        t.start("20260904-000000-4043".to_owned());
10019        reclaim(&mut t, None, 2, "en");
10020        assert_eq!(t.status, TaskStatus::Held);
10021        assert!(
10022            t.last_error
10023                .as_deref()
10024                .is_some_and(|e| e.contains("running")),
10025            "the operator needs to know why this task was held"
10026        );
10027    }
10028
10029    #[test]
10030    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10031        let dir = tempfile::tempdir().unwrap();
10032        let queue = Queue::at(dir.path().to_path_buf());
10033
10034        // No run recorded, so this never has to touch `RunState::load`.
10035        let mut orphaned = task();
10036        orphaned.id = "20260904-000000-orph".to_owned();
10037        orphaned.status = TaskStatus::Running;
10038        orphaned.attempts = 1;
10039        queue.put(&mut orphaned).unwrap();
10040
10041        let mut alive = task();
10042        alive.id = "20260904-000000-live".to_owned();
10043        alive.status = TaskStatus::Running;
10044        alive.attempts = 1;
10045        queue.put(&mut alive).unwrap();
10046        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10047
10048        let mut queued = task();
10049        queued.id = "20260904-000000-wait".to_owned();
10050        queue.put(&mut queued).unwrap();
10051
10052        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10053        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10054
10055        assert_eq!(
10056            queue.get(&orphaned.id).unwrap().status,
10057            TaskStatus::Held,
10058            "nothing was driving it and there was no run to recover"
10059        );
10060        assert_eq!(
10061            queue.get(&alive.id).unwrap().status,
10062            TaskStatus::Running,
10063            "a live claim must protect the task it belongs to"
10064        );
10065        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10066    }
10067
10068    /// Read a run.json back from an explicit `home`, the same way
10069    /// `reclaim_abandoned_runs` itself does - never through the
10070    /// process-global `RunState::load`, which this test's own `home` (an
10071    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10072    /// use at all.
10073    fn read_run_under(home: &Path, id: &str) -> RunState {
10074        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10075        serde_json::from_str(&body).unwrap()
10076    }
10077
10078    #[test]
10079    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10080        let dir = tempfile::tempdir().unwrap();
10081        let home = dir.path().to_path_buf();
10082        let now = Timestamp::now();
10083        let overrun_seat = || crate::run::ActiveSeat {
10084            node: "implement".to_owned(),
10085            started_at: now - jiff::SignedDuration::new(21_000, 0),
10086            timeout_secs: 3_600,
10087            attempt: 0,
10088            task: None,
10089            command: None,
10090            index: None,
10091            total: None,
10092        };
10093
10094        let mut dead = run_state(RunStatus::Implementing);
10095        dead.id = "20260101-000000-dead".to_owned();
10096        dead.active.insert("impl-A".to_owned(), overrun_seat());
10097        // A `driver_pid` the injected query below confirms gone outright —
10098        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10099        dead.driver_pid = Some(4242);
10100        dead.save_under(&home).unwrap();
10101
10102        // Same shape, but a live daemon's heartbeat names it: must be left
10103        // exactly alone, however far past its own timeout the seat sits.
10104        let mut alive = run_state(RunStatus::Implementing);
10105        alive.id = "20260101-000000-aliv".to_owned();
10106        alive.active.insert("impl-A".to_owned(), overrun_seat());
10107        alive.save_under(&home).unwrap();
10108        let mut status = Status::new();
10109        status.current = vec![Current {
10110            worker: None,
10111            task: "20260101-000000-task".to_owned(),
10112            run: alive.id.clone(),
10113        }];
10114        write_status_to(&home.join("daemon.json"), &status).unwrap();
10115
10116        // The abandoned seat left an open question behind: nobody is left to
10117        // read an answer once the run is failed, and this must not wait for
10118        // some later daemon startup's own sweep to notice that.
10119        let questions = Questions::at(home.join("questions"));
10120        let mut q = ask::Question::new(
10121            dead.id.clone(),
10122            "implement".to_owned(),
10123            "impl-A".to_owned(),
10124            "Which storage backend?".to_owned(),
10125            String::new(),
10126            vec!["SQLite".to_owned(), "Redis".to_owned()],
10127        );
10128        questions.put(&mut q).unwrap();
10129
10130        let abandoned = reclaim_abandoned_runs_with(
10131            &home,
10132            now,
10133            |pid| if pid == 4242 { Some(false) } else { None },
10134            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10135        );
10136        assert_eq!(abandoned, vec![dead.id.clone()]);
10137
10138        let reloaded = read_run_under(&home, &dead.id);
10139        assert_eq!(reloaded.status, RunStatus::Failed);
10140        assert!(reloaded.active.is_empty());
10141        assert!(
10142            !questions.get(&q.id).unwrap().status.open(),
10143            "the failed run's own open question must be settled in the same pass"
10144        );
10145
10146        let still_alive = read_run_under(&home, &alive.id);
10147        assert_eq!(
10148            still_alive.status,
10149            RunStatus::Implementing,
10150            "a live daemon's claim protects it"
10151        );
10152        assert!(!still_alive.active.is_empty());
10153    }
10154
10155    /// The exact shape a review round flagged as broken: `magi serve` running
10156    /// in this same `home` scans *every* run on disk, including a manual
10157    /// `magi review` / `magi run` this daemon never started and that
10158    /// therefore claims no heartbeat of its own. Before this scan asked
10159    /// `liveness` rather than just `is_working_on`, a manual run whose active
10160    /// seat merely ran a little past its own timeout — the CLI finishing up,
10161    /// its result still being collected — got wiped and failed by a daemon
10162    /// that had nothing to do with it, out from under a process that was
10163    /// still very much running.
10164    #[test]
10165    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10166        let dir = tempfile::tempdir().unwrap();
10167        let home = dir.path().to_path_buf();
10168        let now = Timestamp::now();
10169
10170        let mut manual = run_state(RunStatus::Reviewing);
10171        manual.id = "20260101-000000-manl".to_owned();
10172        manual.active.insert(
10173            "review-1".to_owned(),
10174            crate::run::ActiveSeat {
10175                node: "review".to_owned(),
10176                started_at: now - jiff::SignedDuration::new(21_000, 0),
10177                timeout_secs: 3_600,
10178                attempt: 0,
10179                task: None,
10180                command: None,
10181                index: None,
10182                total: None,
10183            },
10184        );
10185        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10186        // but a real, still-running process: `liveness` must corroborate this
10187        // as `Live`, not read the missing daemon claim as death.
10188        manual.driver_pid = Some(4242);
10189        manual.driver_started_at = Some("1790000000".to_owned());
10190        manual.save_under(&home).unwrap();
10191
10192        let abandoned = reclaim_abandoned_runs_with(
10193            &home,
10194            now,
10195            |pid| if pid == 4242 { Some(true) } else { None },
10196            |pid| {
10197                if pid == 4242 {
10198                    Some("1790000000".to_owned())
10199                } else {
10200                    None
10201                }
10202            },
10203        );
10204        assert!(
10205            abandoned.is_empty(),
10206            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10207        );
10208
10209        let reloaded = read_run_under(&home, &manual.id);
10210        assert_eq!(reloaded.status, RunStatus::Reviewing);
10211        assert!(!reloaded.active.is_empty());
10212    }
10213
10214    #[test]
10215    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10216        let dir = tempfile::tempdir().unwrap();
10217        let queue = Queue::at(dir.path().to_path_buf());
10218        let mut only = task();
10219        queue.put(&mut only).unwrap();
10220
10221        let _elsewhere = queue.claim(&only.id).unwrap();
10222        let candidates = runnable(&queue);
10223        assert_eq!(candidates.len(), 1, "the task is still runnable");
10224        assert!(
10225            queue.claim(&candidates[0].id).is_err(),
10226            "the loop cannot take a claim somebody else holds"
10227        );
10228
10229        let after = queue.get(&only.id).unwrap();
10230        assert_eq!(after.status, TaskStatus::Queued);
10231        assert_eq!(
10232            after.attempts, 0,
10233            "losing the race is not an attempt at the task"
10234        );
10235        assert_eq!(after.last_error, None);
10236    }
10237
10238    #[test]
10239    fn the_status_file_round_trips_and_its_heartbeat_advances() {
10240        let dir = tempfile::tempdir().unwrap();
10241        let path = dir.path().join("daemon.json");
10242
10243        let mut status = Status::new();
10244        status.idle = false;
10245        status.completed = 7;
10246        status.current = vec![Current {
10247            worker: None,
10248            task: "20260902-000000-t111".to_owned(),
10249            run: "20260902-000001-r111".to_owned(),
10250        }];
10251        write_status_to(&path, &status).unwrap();
10252        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10253        assert_eq!(first.schema, SCHEMA);
10254        assert_eq!(first.pid, std::process::id());
10255        assert!(!first.idle);
10256        assert_eq!(first.completed, 7);
10257        assert_eq!(first.current, status.current);
10258        assert!(
10259            !path.with_extension("json.tmp").exists(),
10260            "the temp file is renamed, not left behind"
10261        );
10262
10263        std::thread::sleep(Duration::from_millis(5));
10264        status.updated_at = Timestamp::now();
10265        status.polls = 3;
10266        write_status_to(&path, &status).unwrap();
10267        let second: Status =
10268            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10269        assert!(
10270            second.updated_at > first.updated_at,
10271            "a reader can only detect staleness if the heartbeat moves"
10272        );
10273        assert_eq!(
10274            second.started_at, first.started_at,
10275            "the start time is not a heartbeat"
10276        );
10277        assert_eq!(second.polls, 3);
10278    }
10279
10280    #[test]
10281    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10282        let dir = tempfile::tempdir().unwrap();
10283
10284        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10285
10286        let mut status = Status::new();
10287        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10288        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10289        let stale = read_status(dir.path()).unwrap();
10290        assert!(
10291            !stale.running(Timestamp::now()),
10292            "a minute without a heartbeat is a dead daemon, not a busy one"
10293        );
10294        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10295
10296        status.updated_at = Timestamp::now();
10297        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10298        let fresh = read_status(dir.path()).unwrap();
10299        assert!(fresh.running(Timestamp::now()));
10300    }
10301
10302    #[test]
10303    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10304        let dir = tempfile::tempdir().unwrap();
10305        let now = Timestamp::now();
10306        let mine = "20260903-080619-01c2";
10307
10308        assert!(
10309            !is_working_on(dir.path(), mine, now),
10310            "no status file means nobody is working on anything"
10311        );
10312
10313        let mut status = Status::new();
10314        status.current = vec![Current {
10315            worker: None,
10316            task: "20260903-080340-0167".to_owned(),
10317            run: mine.to_owned(),
10318        }];
10319        status.updated_at = now;
10320        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10321        assert!(is_working_on(dir.path(), mine, now));
10322        assert!(
10323            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10324            "a daemon busy with one run is not working on another"
10325        );
10326
10327        // A killed daemon stops writing heartbeats but leaves the file behind
10328        // naming the run it died in. That run must not be undeletable forever.
10329        status.updated_at = now - jiff::SignedDuration::from_secs(600);
10330        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10331        assert!(
10332            !is_working_on(dir.path(), mine, now),
10333            "a stale heartbeat is a dead daemon, so its run is a leftover"
10334        );
10335    }
10336
10337    #[test]
10338    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10339        let dir = tempfile::tempdir().unwrap();
10340        let now = Timestamp::now();
10341
10342        assert!(
10343            !is_working_on_short(dir.path(), "01c2", now),
10344            "no status file means nobody is working on anything"
10345        );
10346
10347        let mut status = Status::new();
10348        status.current = vec![Current {
10349            worker: None,
10350            task: "20260903-080340-0167".to_owned(),
10351            run: "20260903-080619-01c2".to_owned(),
10352        }];
10353        status.updated_at = now;
10354        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10355        assert!(
10356            is_working_on_short(dir.path(), "01c2", now),
10357            "the run's short id is the last block of its full id"
10358        );
10359        assert!(
10360            !is_working_on_short(dir.path(), "3cbf", now),
10361            "a daemon busy with one worktree bay is not working on another"
10362        );
10363    }
10364
10365    #[test]
10366    fn a_newer_status_file_still_yields_a_reading() {
10367        let dir = tempfile::tempdir().unwrap();
10368        // A field this build has never heard of must not turn the reading into
10369        // nothing at all; that is the whole reason the reader is permissive.
10370        std::fs::write(
10371            dir.path().join("daemon.json"),
10372            serde_json::json!({
10373                "schema": 2,
10374                "updated_at": Timestamp::now().to_string(),
10375                "idle": true,
10376                "surprise": { "nested": [1, 2, 3] },
10377            })
10378            .to_string(),
10379        )
10380        .unwrap();
10381
10382        let reading = read_status(dir.path()).expect("a forward-compatible read");
10383        assert!(reading.running(Timestamp::now()));
10384        assert!(reading.idle);
10385        assert!(reading.current.is_empty());
10386    }
10387
10388    #[test]
10389    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10390        // A daemon started before `current` became a list keeps writing this
10391        // shape on every heartbeat until it is restarted. A rolling upgrade
10392        // - a newer `magi web` or `magi doctor` reading an older `magi
10393        // serve`'s heartbeat - must still see the run it is on, not "no
10394        // daemon" from a type mismatch failing the whole struct.
10395        let dir = tempfile::tempdir().unwrap();
10396        std::fs::write(
10397            dir.path().join("daemon.json"),
10398            serde_json::json!({
10399                "schema": 1,
10400                "pid": 4242,
10401                "updated_at": Timestamp::now().to_string(),
10402                "idle": false,
10403                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10404                "completed": 3,
10405                "polls": 9,
10406            })
10407            .to_string(),
10408        )
10409        .unwrap();
10410
10411        let reading = read_status(dir.path()).expect("an older shape must still parse");
10412        assert!(reading.running(Timestamp::now()));
10413        assert_eq!(
10414            reading.current,
10415            vec![Current {
10416                worker: None,
10417                task: "20260902-140501-aaaa".to_owned(),
10418                run: "20260902-140502-bbbb".to_owned(),
10419            }]
10420        );
10421    }
10422
10423    #[test]
10424    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10425        let dir = tempfile::tempdir().unwrap();
10426        std::fs::write(
10427            dir.path().join("daemon.json"),
10428            serde_json::json!({
10429                "schema": 1,
10430                "updated_at": Timestamp::now().to_string(),
10431                "idle": true,
10432                "current": null,
10433            })
10434            .to_string(),
10435        )
10436        .unwrap();
10437        let with_null = read_status(dir.path()).expect("null must still parse");
10438        assert!(with_null.current.is_empty());
10439
10440        std::fs::write(
10441            dir.path().join("daemon.json"),
10442            serde_json::json!({
10443                "schema": 1,
10444                "updated_at": Timestamp::now().to_string(),
10445                "idle": true,
10446            })
10447            .to_string(),
10448        )
10449        .unwrap();
10450        let absent = read_status(dir.path()).expect("a missing field must still parse");
10451        assert!(absent.current.is_empty());
10452    }
10453
10454    #[test]
10455    fn a_task_without_a_repository_runs_in_the_daemons_default() {
10456        let fallback = Path::new("/default");
10457        let mut blank = task();
10458        blank.repo = PathBuf::new();
10459        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10460        let mut dot = task();
10461        dot.repo = PathBuf::from(".");
10462        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10463        assert_eq!(
10464            repo_for(&task(), fallback),
10465            PathBuf::from("/repo"),
10466            "a task that names a repository keeps it"
10467        );
10468    }
10469
10470    #[test]
10471    fn task_implementers_edit_inherits_daemon_config_and_merge() {
10472        let dir = tempfile::tempdir().unwrap();
10473        let path = dir.path().join("explicit.toml");
10474        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10475        let opts = Opts {
10476            config: Some(path),
10477            merge: Some("none".into()),
10478            ..Default::default()
10479        };
10480        let mut t = task();
10481        t.set_implementers(
10482            2,
10483            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10484                .unwrap(),
10485        )
10486        .unwrap();
10487        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10488        assert_eq!(cfg.graph.implementers, 2);
10489        assert_eq!(cfg.graph.judges, 1);
10490        assert_eq!(cfg.merge.mode, MergeMode::None);
10491        t.set_implementers(1, &cfg).unwrap();
10492        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10493        apply_task_implementers(&mut cfg, &t);
10494        assert_eq!(cfg.graph.implementers, 1);
10495        assert_eq!(cfg.graph.judges, 1);
10496        assert_eq!(cfg.merge.mode, MergeMode::None);
10497    }
10498
10499    #[test]
10500    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10501        let dir = tempfile::tempdir().unwrap();
10502        let repo = dir.path().join("repo");
10503        std::fs::create_dir(&repo).unwrap();
10504        std::fs::write(
10505            repo.join("magi.toml"),
10506            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10507        )
10508        .unwrap();
10509        let daemon_config = dir.path().join("daemon.toml");
10510        std::fs::write(
10511            &daemon_config,
10512            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10513        )
10514        .unwrap();
10515        let opts = Opts {
10516            config: Some(daemon_config),
10517            merge: Some("pr".into()),
10518            ..Default::default()
10519        };
10520        let q = Queue::at(dir.path().join("queue"));
10521        let validation: Config =
10522            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10523                .unwrap();
10524        // No provenance field on legacy direct tasks: both shapes stay isolated.
10525        for record in ["{}", r#"{"candidates":2}"#] {
10526            let overrides = serde_json::from_str(record).unwrap();
10527            let filing = crate::direct::Filing {
10528                instruction: "work".into(),
10529                title: "direct".into(),
10530                repo: repo.clone(),
10531                source: crate::queue::Source::Human,
10532                solo: false,
10533                overrides,
10534                review_of: None,
10535                sources: Default::default(),
10536            };
10537            let filed =
10538                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
10539            let crate::direct::Filed::Standalone {
10540                mut task,
10541                claim: _claim,
10542            } = filed
10543            else {
10544                panic!("local filing")
10545            };
10546            let before = prepare_for(&repo, &opts, &task).unwrap();
10547            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
10548            assert_eq!(
10549                before.merge.mode,
10550                MergeMode::None,
10551                "daemon --merge must not leak"
10552            );
10553            for n in [2, 1, 2] {
10554                task.set_implementers(n, &validation).unwrap();
10555                q.put(&mut task).unwrap();
10556                task = q.get(&task.id).unwrap();
10557                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
10558                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
10559                apply_task_implementers(&mut cfg, &task);
10560                assert_eq!(cfg.graph.implementers, usize::from(n));
10561                assert_eq!(cfg.graph.judges, 2);
10562                assert_eq!(cfg.merge.mode, MergeMode::None);
10563            }
10564        }
10565    }
10566
10567    #[test]
10568    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
10569        let cfg: Config =
10570            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10571                .unwrap();
10572        let mut t = task();
10573        t.review_of = Some("review-target".into());
10574        t.hold_manual(Some("retry".into()));
10575        let mut previous = RunState::new(
10576            PathBuf::from("/repo"),
10577            "main".into(),
10578            "abc1234".into(),
10579            "review".into(),
10580            cfg.clone(),
10581        );
10582        previous.config.graph.implementers = 2;
10583        for count in [1, 3] {
10584            t.set_implementers(count, &cfg).unwrap();
10585            t.release();
10586            assert_eq!(t.review_of.as_deref(), Some("review-target"));
10587            for proposed in [
10588                Starter::Resume(previous.id.clone()),
10589                Starter::Review("recovery-target".into()),
10590            ] {
10591                assert_eq!(
10592                    starter_with_implementers(&t, Some(&previous), proposed),
10593                    Starter::Review("review-target".into())
10594                );
10595            }
10596            let mut configured = cfg.clone();
10597            apply_task_implementers(&mut configured, &t);
10598            assert_eq!(configured.graph.implementers, usize::from(count));
10599            assert_eq!(previous.config.graph.implementers, 2);
10600        }
10601    }
10602
10603    #[test]
10604    fn task_implementers_dispatch_and_resume_agree() {
10605        let mut t = task();
10606        let cfg: crate::config::Config =
10607            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10608                .unwrap();
10609        let mut run = RunState::new(
10610            PathBuf::from("/repo"),
10611            "main".into(),
10612            "abc1234".into(),
10613            "work".into(),
10614            cfg.clone(),
10615        );
10616        run.config.graph.implementers = 2;
10617        for n in [2, 1, 3, 2] {
10618            t.set_implementers(n, &cfg).unwrap();
10619            let mut dispatched = cfg.clone();
10620            apply_task_implementers(&mut dispatched, &t);
10621            assert_eq!(dispatched.graph.implementers, usize::from(n));
10622            assert_eq!(implementers_match(&t, &run), n == 2);
10623            for proposed in [
10624                Starter::Resume(run.id.clone()),
10625                Starter::Review("old-branch".into()),
10626            ] {
10627                let expected = if n == 2 {
10628                    proposed.clone()
10629                } else {
10630                    Starter::Start
10631                };
10632                assert_eq!(
10633                    starter_with_implementers(&t, Some(&run), proposed),
10634                    expected
10635                );
10636            }
10637            assert_eq!(
10638                run.config.graph.implementers, 2,
10639                "history must not be rewritten"
10640            );
10641        }
10642        t.solo = false;
10643        t.overrides = None;
10644        assert!(implementers_match(&t, &run));
10645    }
10646
10647    #[test]
10648    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10649        // Three seats said out loud. What `solo` promises is one candidate
10650        // *whatever the config asks for*, so the contrast has to be a number
10651        // this test owns - it used to be `Config::default()`'s, which became
10652        // 1 when one implementation became the default and left the two
10653        // halves of this test asserting the same thing.
10654        let mut solo_cfg = Config::default();
10655        solo_cfg.graph.implementers = 3;
10656        let mut solo_task = task();
10657        solo_task.solo = true;
10658        apply_task_implementers(&mut solo_cfg, &solo_task);
10659        assert_eq!(solo_cfg.graph.implementers, 1);
10660
10661        let mut plain_cfg = Config::default();
10662        plain_cfg.graph.implementers = 3;
10663        let plain_task = task();
10664        assert!(!plain_task.solo);
10665        apply_task_implementers(&mut plain_cfg, &plain_task);
10666        assert_eq!(
10667            plain_cfg.graph.implementers, 3,
10668            "a task that did not ask to run alone keeps the config's candidates"
10669        );
10670    }
10671
10672    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10673        QuotaLoss {
10674            cause: crate::agent::QuotaCause::UsageLimit,
10675            agent: String::new(),
10676            seat: seat.into(),
10677            node: "judge".into(),
10678            at: at.parse().unwrap(),
10679            reset: reset.map(str::to_string),
10680        }
10681    }
10682
10683    #[test]
10684    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10685        let now = Timestamp::now();
10686        for reset in [None, Some("in 1h")] {
10687            let auth = crate::agent::Quota {
10688                cause: crate::agent::QuotaCause::Authentication,
10689                agent: "alpha".into(),
10690                reset: reset.map(str::to_owned),
10691            };
10692            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10693            assert_eq!(cooldown_until(&[loss], now), None);
10694        }
10695    }
10696
10697    #[test]
10698    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10699        let old: Vec<QuotaLoss> = (1..=4)
10700            .map(|i| {
10701                loss(
10702                    &format!("judge-{i}"),
10703                    "2026-09-23T05:23:00Z",
10704                    Some("2:40pm (Asia/Tokyo)"),
10705                )
10706            })
10707            .collect();
10708        let fresh = losses_this_attempt(&old, &old);
10709        assert!(fresh.is_empty());
10710        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10711        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10712    }
10713
10714    #[test]
10715    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10716        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10717        let now = Timestamp::now();
10718        let mut after = old.clone();
10719        after.push(loss("judge-2", &now.to_string(), None));
10720        let fresh = losses_this_attempt(&old, &after);
10721        assert_eq!(fresh, vec![after[1].clone()]);
10722        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10723        assert_eq!(
10724            until,
10725            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10726        );
10727    }
10728
10729    #[test]
10730    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10731        // `recover_stall` removes judge-1's loss and the retry then hits quota
10732        // again: the vector is the same length, so an index diff sees nothing.
10733        let before = vec![
10734            loss("judge-1", "2026-09-23T05:23:00Z", None),
10735            loss("judge-2", "2026-09-23T05:24:00Z", None),
10736        ];
10737        let after = vec![
10738            loss("judge-2", "2026-09-23T05:24:00Z", None),
10739            loss("judge-1", "2026-09-24T01:00:00Z", None),
10740        ];
10741        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10742    }
10743
10744    #[test]
10745    fn merge_overrides_are_parsed_or_refused() {
10746        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10747        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10748        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10749        assert!(merge_mode("squash").is_err());
10750    }
10751
10752    #[test]
10753    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10754        let now = Timestamp::now();
10755        let fallback = Duration::from_secs(300);
10756        let cap = Duration::from_secs(1800);
10757
10758        // No reset hint at all: the fallback.
10759        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10760
10761        // A reset ten minutes out, well inside the cap: waited for exactly.
10762        let soon = now + jiff::SignedDuration::from_secs(600);
10763        assert_eq!(
10764            quota_wait(Some(soon), now, fallback, cap),
10765            Duration::from_secs(600)
10766        );
10767
10768        // A reset already in the past is not trusted: the fallback, not a
10769        // zero or negative wait that would spin the loop right back around.
10770        let past = now - jiff::SignedDuration::from_secs(60);
10771        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10772
10773        // A reset further out than the cap is trusted for direction but not
10774        // for magnitude: a parsing slip must not sleep the loop for a day.
10775        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10776        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10777    }
10778
10779    #[test]
10780    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10781        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10782
10783        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10784        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10785
10786        // Same clock reading, but it has already gone by today: read as
10787        // tomorrow's, since the CLI would not still be reporting a limit past
10788        // its own stated reset.
10789        let already_past =
10790            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10791        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10792
10793        assert!(
10794            parse_reset_hint("session limit reached", now, now).is_none(),
10795            "free text with no recognised shape is not guessed at"
10796        );
10797        assert!(
10798            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10799            "an unresolvable zone name is not guessed at either"
10800        );
10801    }
10802
10803    #[test]
10804    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10805        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10806
10807        let at = parse_reset_hint(
10808            "You've hit your usage limit. Visit \
10809             https://chatgpt.com/codex/settings/usage to purchase more \
10810             credits or try again at Sep 19th, 2026 5:10 PM.",
10811            now,
10812            now,
10813        )
10814        .expect("the codex reset wording is a recognised shape");
10815        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10816
10817        // The month is explicit, so a date already earlier in the same
10818        // sentence-implied year than `now` is trusted as written rather than
10819        // rolled forward a year the way the bracketed shape rolls a
10820        // same-day clock reading to tomorrow.
10821        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10822            .expect("an explicit year needs no rollover");
10823        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10824
10825        assert!(
10826            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10827            "a two-digit year is not the documented shape and is not guessed at"
10828        );
10829        assert!(
10830            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10831            "a four-letter month name is not the documented three-letter abbreviation"
10832        );
10833        assert!(
10834            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10835            "an explicit zone on the dated shape is a format nobody has \
10836             documented, and is refused rather than guessed at as UTC"
10837        );
10838    }
10839
10840    #[test]
10841    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10842        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10843        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10844
10845        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10846        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10847
10848        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10849        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10850
10851        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10852            assert!(
10853                parse_reset_hint(bad, now, recorded).is_none(),
10854                "{bad:?} must not be guessed at"
10855            );
10856        }
10857    }
10858
10859    /// A loop whose queue lives in a temp tree and whose poll interval is far
10860    /// longer than the test's patience, so anything that waits out a poll
10861    /// instead of noticing the stop fails rather than merely being slow.
10862    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10863        let config = dir.join("magi.toml");
10864        std::fs::write(
10865            &config,
10866            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10867        )
10868        .unwrap();
10869        let opts = Opts {
10870            poll: Duration::from_secs(30),
10871            config: Some(config),
10872            // The explicit fixture config keeps startup cleanup from reading
10873            // machine configuration. This fictional repository likewise
10874            // keeps any best-effort git cleanup away from this checkout.
10875            repo: dir.join("repo"),
10876            ..Opts::default()
10877        };
10878        // The status file goes in a directory that does not exist yet, so its
10879        // creation is itself evidence the loop published one. `worktrees`
10880        // must be just as fictional: the janitor reclaims worktrees under it
10881        // for real, and a test that let it fall through to
10882        // `crate::run::default_worktree_root()` would have it reclaim
10883        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10884        // which is exactly what happened before this function took the
10885        // parameter at all.
10886        let home = dir.join("home");
10887        // These control-only fixtures do not launch native workers. Give the
10888        // independently tested maintenance services a fresh cadence receipt.
10889        let stamps = home.join("service-ticks");
10890        std::fs::create_dir_all(&stamps).unwrap();
10891        for service in ["waiter", "deputies", "release-watch"] {
10892            std::fs::write(
10893                stamps.join(service),
10894                Timestamp::now().as_second().to_string(),
10895            )
10896            .unwrap();
10897        }
10898        for operation in [
10899            "conductor",
10900            "maintenance",
10901            "housekeeping",
10902            "disk-pressure",
10903            "cache",
10904            "fetch",
10905            "chat-goals",
10906        ] {
10907            std::fs::write(
10908                stamps.join(format!("daemon-{operation}")),
10909                serde_json::to_vec(&Timestamp::now()).unwrap(),
10910            )
10911            .unwrap();
10912        }
10913        let worktrees = dir.join("wt");
10914        (
10915            opts,
10916            Queue::at(dir.join("queue")),
10917            home.join("daemon.json"),
10918            home,
10919            worktrees,
10920        )
10921    }
10922
10923    #[tokio::test]
10924    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
10925        let dir = tempfile::tempdir().unwrap();
10926        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10927        let mut waiting = task();
10928        waiting.repo = opts.repo.clone();
10929        waiting.hold_machine(crate::disk::gate(1, 100));
10930        waiting.mark_disk_capacity();
10931        waiting.attempts = 2;
10932        queue.put(&mut waiting).unwrap();
10933        let mut busy = task();
10934        busy.status = TaskStatus::Running;
10935        queue.put(&mut busy).unwrap();
10936        let payload = serde_json::to_value(ServiceWorker {
10937            opts,
10938            queue: queue.root().to_owned(),
10939            worktrees_root: worktrees,
10940            operation: "maintenance".into(),
10941        })
10942        .unwrap();
10943        run_service_worker(&home, payload.clone()).await.unwrap();
10944        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
10945        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
10946        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
10947        run_service_worker(&home, payload).await.unwrap();
10948        assert!(
10949            crate::worker::active(&home).unwrap().is_empty(),
10950            "monitoring only queues; normal dispatch owns launches"
10951        );
10952        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
10953    }
10954
10955    #[tokio::test]
10956    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
10957        let dir = tempfile::tempdir().unwrap();
10958        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10959        let cfg = Config::default();
10960        start_service(
10961            &home,
10962            &opts,
10963            &queue,
10964            &worktrees,
10965            "housekeeping",
10966            Some(&cfg),
10967            true,
10968        )
10969        .await
10970        .unwrap();
10971        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
10972        let read = |path: &Path| -> serde_json::Value {
10973            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
10974        };
10975        assert_eq!(read(&receipt)["detail"], "cadence not due");
10976        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
10977        start_service(
10978            &home,
10979            &opts,
10980            &queue,
10981            &worktrees,
10982            "housekeeping",
10983            Some(&cfg),
10984            true,
10985        )
10986        .await
10987        .unwrap();
10988        assert_eq!(
10989            read(&receipt)["detail"],
10990            "active work or runnable task queue"
10991        );
10992        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
10993        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
10994        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
10995        start_service(
10996            &home,
10997            &opts,
10998            &queue,
10999            &worktrees,
11000            "disk-pressure",
11001            Some(&cfg),
11002            false,
11003        )
11004        .await
11005        .unwrap();
11006        assert_eq!(
11007            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11008            "no active work; idle housekeeping owns scan"
11009        );
11010        assert!(crate::worker::active(&home).unwrap().is_empty());
11011    }
11012
11013    #[tokio::test]
11014    async fn goal_observation_service_does_not_block_scheduler_decisions() {
11015        let dir = tempfile::tempdir().unwrap();
11016        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11017        let queue = Queue::at(home.join("queue"));
11018        let mut task = task();
11019        task.repo = opts.repo.clone();
11020        task.chat = Some("decision-chat".into());
11021        task.hold_machine(Some("waiting for a decision".into()));
11022        queue.put(&mut task).unwrap();
11023        let questions = Questions::at(home.join("questions"));
11024        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11025        question.node = crate::conduct::NODE.into();
11026        question.status = ask::QuestionStatus::Open;
11027        question.answer = None;
11028        question.answered_at = None;
11029        questions.put(&mut question).unwrap();
11030        questions
11031            .update(&question.id, |q| {
11032                q.answer(ask::Answer::Choice("resume で続行する".into()))
11033            })
11034            .unwrap();
11035
11036        let talks = crate::talk::Talks::at(home.join("talks"));
11037        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11038        decision_chat.pending = "Keep this unsent status question".into();
11039        talks.put(&mut decision_chat).unwrap();
11040        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11041        talk.goals.push(serde_json::from_value(serde_json::json!({
11042            "id":"goal","purpose":"follow the retained job","scope":"one task",
11043            "condition":{"description":"land the result","kind":"runs_merged"},
11044            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11045            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11046            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11047        })).unwrap());
11048        talks.put(&mut talk).unwrap();
11049
11050        // A retained service lease models an observation still waiting on its
11051        // external dependency. Admission must neither await nor repeat it.
11052        let directory = home.join("workers/jobs/abcdef");
11053        std::fs::create_dir_all(&directory).unwrap();
11054        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11055        crate::pr_head::try_lock_file(&lease).unwrap();
11056        let mut job = crate::worker::Job {
11057            id: "abcdef".into(),
11058            sequence: 1,
11059            kind: "daemon-service".into(),
11060            key: "service:daemon-chat-goals".into(),
11061            payload: serde_json::Value::Null,
11062            generation: "fixture".into(),
11063            version: None,
11064            status: crate::worker::Status::Running,
11065            result: None,
11066            pid: Some(std::process::id()),
11067            created_at: Timestamp::now().as_second() as u64,
11068            finished_at: None,
11069        };
11070        let record = directory.join("job.json");
11071        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11072        let status = Arc::new(Mutex::new(Status::new()));
11073        let stop = Stop::new();
11074        let mut dispatch = Box::pin(poll(
11075            &opts,
11076            &queue,
11077            &status,
11078            &home,
11079            &worktrees,
11080            &stop,
11081            DispatchLimits {
11082                max_concurrent: 1,
11083                pause_for_interrupts: false,
11084                recovery_cfg: None,
11085            },
11086        ));
11087        std::future::poll_fn(|cx| {
11088            assert!(dispatch.as_mut().poll(cx).is_pending());
11089            std::task::Poll::Ready(())
11090        })
11091        .await;
11092        assert!(lock(&status).polls > 0);
11093        let saved = queue.get(&task.id).unwrap();
11094        assert_eq!(saved.status, TaskStatus::Done);
11095        assert!(saved.action_applied(&question.id));
11096        assert!(
11097            talks
11098                .get("decision-chat")
11099                .unwrap()
11100                .pending
11101                .contains("Keep this unsent status question")
11102        );
11103        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11104        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11105        assert_eq!(
11106            goal.started,
11107            Some(1),
11108            "only the observation worker may reconcile its goal"
11109        );
11110        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11111
11112        stop.stop();
11113        dispatch.await.unwrap();
11114        job.status = crate::worker::Status::Finished;
11115        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11116        drop(lease);
11117    }
11118
11119    #[test]
11120    fn a_stop_is_idempotent_and_once_set_stays_set() {
11121        let stop = Stop::new();
11122        assert!(!stop.stopped());
11123
11124        stop.stop();
11125        assert!(stop.stopped());
11126        stop.stop();
11127        assert!(stop.stopped(), "a second stop is not a toggle");
11128
11129        let shared = stop.clone();
11130        assert!(
11131            shared.stopped(),
11132            "a clone is the same stop; that is how the loop and its caller share one"
11133        );
11134    }
11135
11136    #[tokio::test]
11137    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11138        for operation in ["conductor", "maintenance", "housekeeping"] {
11139            let dir = tempfile::tempdir().unwrap();
11140            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11141            opts.once = true;
11142            opts.poll = Duration::from_millis(1);
11143            let mut task = task();
11144            task.runs.push("fixture-run".into());
11145            queue.put(&mut task).unwrap();
11146            let claim = queue.claim(&task.id).unwrap();
11147
11148            // Model a live service holding the task's claim across the
11149            // scheduler's dispatch scan. No real subprocess or timed race.
11150            let directory = home.join("workers/jobs/abcdef");
11151            std::fs::create_dir_all(&directory).unwrap();
11152            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11153            crate::pr_head::try_lock_file(&lease).unwrap();
11154            let mut job = crate::worker::Job {
11155                id: "abcdef".into(),
11156                sequence: 1,
11157                kind: "daemon-service".into(),
11158                key: format!("service:daemon-{operation}"),
11159                payload: serde_json::Value::Null,
11160                generation: "fixture".into(),
11161                version: None,
11162                status: crate::worker::Status::Running,
11163                result: None,
11164                pid: Some(std::process::id()),
11165                created_at: Timestamp::now().as_second() as u64,
11166                finished_at: None,
11167            };
11168            let record = directory.join("job.json");
11169            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11170
11171            let status = Arc::new(Mutex::new(Status::new()));
11172            let stop = Stop::new();
11173            let mut drain = Box::pin(poll(
11174                &opts,
11175                &queue,
11176                &status,
11177                &home,
11178                &worktrees,
11179                &stop,
11180                DispatchLimits {
11181                    max_concurrent: 1,
11182                    pause_for_interrupts: false,
11183                    recovery_cfg: None,
11184                },
11185            ));
11186            std::future::poll_fn(|cx| {
11187                use std::future::Future;
11188                assert!(
11189                    drain.as_mut().poll(cx).is_pending(),
11190                    "--once must wait for {operation} to release its queue claim"
11191                );
11192                std::task::Poll::Ready(())
11193            })
11194            .await;
11195            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11196
11197            // An answer arrives while the service still owns the claim. A
11198            // fresh scheduling pass must apply it before declaring idle.
11199            let questions = Questions::at(home.join("questions"));
11200            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
11201            questions.put(&mut q).unwrap();
11202            drop(claim);
11203            // Model services that took longer than their cadence, without a
11204            // wall-clock sleep. The final scans must not respawn them even
11205            // though their receipts now permit another periodic invocation.
11206            let expired =
11207                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11208            for service in [operation, "housekeeping"] {
11209                std::fs::write(
11210                    home.join("service-ticks").join(format!("daemon-{service}")),
11211                    &expired,
11212                )
11213                .unwrap();
11214            }
11215            job.status = crate::worker::Status::Finished;
11216            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11217            drop(lease);
11218            tokio::time::timeout(Duration::from_secs(2), drain)
11219                .await
11220                .expect("the settled service must allow the drain to finish")
11221                .unwrap();
11222            let after = queue.get(&task.id).unwrap();
11223            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11224            assert!(after.action_applied(&q.id));
11225            for service in [operation, "housekeeping"] {
11226                assert_eq!(
11227                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11228                        .unwrap(),
11229                    expired,
11230                    "the final once rescan must not restart {service}"
11231                );
11232            }
11233        }
11234    }
11235
11236    #[test]
11237    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11238        let stop = Stop::new();
11239        stop.busy.store(1, Ordering::SeqCst);
11240        assert!(
11241            !stop.finishing(),
11242            "a busy loop nobody has asked to stop is just running"
11243        );
11244
11245        stop.stop();
11246        assert!(
11247            stop.finishing(),
11248            "a stop asked for mid-run has not landed until the run is settled"
11249        );
11250
11251        stop.busy.store(0, Ordering::SeqCst);
11252        assert!(
11253            !stop.finishing(),
11254            "once the run is settled the stop has landed and there is nothing to finish"
11255        );
11256    }
11257
11258    #[test]
11259    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11260        let stop = Stop::new();
11261        stop.busy.store(2, Ordering::SeqCst);
11262        stop.stop();
11263        assert!(stop.finishing(), "two runs still in flight");
11264
11265        stop.busy.store(1, Ordering::SeqCst);
11266        assert!(
11267            stop.finishing(),
11268            "one run finished, but a sibling is still working"
11269        );
11270
11271        stop.busy.store(0, Ordering::SeqCst);
11272        assert!(
11273            !stop.finishing(),
11274            "the last run out is what actually lands the stop"
11275        );
11276    }
11277
11278    #[tokio::test]
11279    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11280        let dir = tempfile::tempdir().unwrap();
11281        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11282        let stop = Stop::new();
11283        stop.stop();
11284
11285        let began = std::time::Instant::now();
11286        tokio::time::timeout(
11287            Duration::from_secs(2),
11288            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11289        )
11290        .await
11291        .expect("a stopped loop must return, not sit out its poll interval")
11292        .expect("the loop's own setup and teardown must not fail");
11293        assert!(
11294            began.elapsed() < opts.poll,
11295            "returned only after {:?}, which is a poll interval, not a stop",
11296            began.elapsed()
11297        );
11298    }
11299
11300    #[tokio::test]
11301    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11302        let dir = tempfile::tempdir().unwrap();
11303        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11304        let stop = Stop::new();
11305
11306        // Asked for after the loop is already parked on its empty queue, which
11307        // is the case an operator tapping stop on a phone actually hits.
11308        let asker = {
11309            let stop = stop.clone();
11310            tokio::spawn(async move {
11311                tokio::time::sleep(Duration::from_millis(20)).await;
11312                stop.stop();
11313            })
11314        };
11315
11316        let began = std::time::Instant::now();
11317        tokio::time::timeout(
11318            Duration::from_secs(2),
11319            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11320        )
11321        .await
11322        .expect("a stop asked for while idle must wake the wait")
11323        .expect("the loop's own setup and teardown must not fail");
11324        asker.await.unwrap();
11325        assert!(
11326            began.elapsed() < opts.poll,
11327            "returned only after {:?}, so the stop waited on the sleep",
11328            began.elapsed()
11329        );
11330    }
11331
11332    #[tokio::test]
11333    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11334        let dir = tempfile::tempdir().unwrap();
11335        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11336        let stop = Stop::new();
11337        stop.stop();
11338
11339        tokio::time::timeout(
11340            Duration::from_secs(2),
11341            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11342        )
11343        .await
11344        .expect("a stopped loop must return")
11345        .expect("the loop's own setup and teardown must not fail");
11346
11347        assert!(
11348            home.is_dir(),
11349            "the loop did publish a status file, so its removal is the teardown and not an absence"
11350        );
11351        assert!(
11352            !status_file.exists(),
11353            "a stopped loop clears its status file"
11354        );
11355        assert!(
11356            read_status(&home).is_none(),
11357            "a reader must see no daemon at all, not a heartbeat that merely stopped"
11358        );
11359    }
11360
11361    #[tokio::test]
11362    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
11363        let dir = tempfile::tempdir().unwrap();
11364        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11365
11366        let mut settled = RunState::new(
11367            dir.path().join("repo"),
11368            "main".to_owned(),
11369            "abc1234".to_owned(),
11370            "fixture".to_owned(),
11371            Config::default(),
11372        );
11373        settled.status = RunStatus::Ready;
11374        let run_dir = home.join("runs").join(&settled.id);
11375        std::fs::create_dir_all(&run_dir).unwrap();
11376        std::fs::write(
11377            run_dir.join("run.json"),
11378            serde_json::to_string_pretty(&settled).unwrap(),
11379        )
11380        .unwrap();
11381        let questions = Questions::at(home.join("questions"));
11382        let mut question = ask::Question::new(
11383            settled.id.clone(),
11384            "review".to_owned(),
11385            "reviewer-1".to_owned(),
11386            "Continue?".to_owned(),
11387            String::new(),
11388            Vec::new(),
11389        );
11390        questions.put(&mut question).unwrap();
11391
11392        run_service_worker(
11393            &home,
11394            serde_json::to_value(ServiceWorker {
11395                opts,
11396                queue: queue.root().to_path_buf(),
11397                worktrees_root: worktrees,
11398                operation: "housekeeping".to_owned(),
11399            })
11400            .unwrap(),
11401        )
11402        .await
11403        .unwrap();
11404
11405        assert_eq!(
11406            questions.get(&question.id).unwrap().status,
11407            ask::QuestionStatus::Abandoned,
11408            "the independent housekeeping worker settles ended-run questions"
11409        );
11410    }
11411
11412    #[test]
11413    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11414        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11415
11416        assert!(
11417            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11418            "never checked before: due at once"
11419        );
11420
11421        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11422        assert!(
11423            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11424            "well inside the interval: not due yet"
11425        );
11426
11427        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11428        assert!(
11429            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11430            "exactly at the edge: not yet due, same convention as `clean::due`"
11431        );
11432
11433        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11434        assert!(
11435            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11436            "past the interval: due again"
11437        );
11438    }
11439
11440    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
11441    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
11442    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
11443    /// and the congestion test below both need, and must not drift apart.
11444    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11445        let config = dir.join("magi.toml");
11446        // A literal (single-quoted) TOML string, not a basic one: the cache
11447        // path is a Windows path full of backslashes, and a basic string
11448        // would have TOML try to interpret `\U` (from `\Users\...`) as a
11449        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
11450        // `{{ vars.cache }}` rendering documents.
11451        std::fs::write(
11452            &config,
11453            format!(
11454                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
11455                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
11456                cache_dir.display()
11457            ),
11458        )
11459        .unwrap();
11460        Opts {
11461            config: Some(config),
11462            repo: dir.join("repo"),
11463            ..Opts::default()
11464        }
11465    }
11466
11467    #[tokio::test]
11468    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
11469        let dir = tempfile::tempdir().unwrap();
11470        let home = dir.path().join("home");
11471        let cache_dir = dir.path().join("cache");
11472        std::fs::create_dir_all(&cache_dir).unwrap();
11473        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11474        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11475
11476        // Nobody has asked this daemon to stop, which is the ordinary case;
11477        // the skip that a stop buys is asserted by its own test below.
11478        let running = Stop::new();
11479        let mut last_checked = None;
11480        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11481        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
11482            .await;
11483        assert_eq!(
11484            crate::disk::dir_size(&cache_dir),
11485            0,
11486            "over the cap on the first check ever: pruned at once, no idle queue required"
11487        );
11488        assert_eq!(last_checked, Some(t0));
11489
11490        // A fresh oversized file lands, but the next check is not due yet.
11491        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11492        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11493        maybe_prune_cache_between_runs(
11494            &opts.repo,
11495            &opts,
11496            &home,
11497            &running,
11498            &mut last_checked,
11499            too_soon,
11500        )
11501        .await;
11502        assert_eq!(
11503            crate::disk::dir_size(&cache_dir),
11504            10,
11505            "too soon since the last check: left alone rather than rescanned every call"
11506        );
11507        assert_eq!(
11508            last_checked,
11509            Some(t0),
11510            "an idle check does not reset the clock"
11511        );
11512
11513        // Once the interval elapses, the same oversized cache is caught again.
11514        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11515        maybe_prune_cache_between_runs(
11516            &opts.repo,
11517            &opts,
11518            &home,
11519            &running,
11520            &mut last_checked,
11521            due_again,
11522        )
11523        .await;
11524        assert_eq!(
11525            crate::disk::dir_size(&cache_dir),
11526            0,
11527            "due again: pruned back under the cap"
11528        );
11529    }
11530
11531    /// A stop must not queue behind housekeeping. The prune below is a
11532    /// synchronous walk of the whole cache with no await point in it, so a
11533    /// loop that entered it could not get back to its own `stopped()` test
11534    /// until the walk finished - and because no run is in flight at this
11535    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
11536    /// the stop had already landed. The idle branch has always made this same
11537    /// check before reaching `janitor`; the between-runs path makes it too.
11538    #[tokio::test]
11539    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
11540        let dir = tempfile::tempdir().unwrap();
11541        let home = dir.path().join("home");
11542        let cache_dir = dir.path().join("cache");
11543        std::fs::create_dir_all(&cache_dir).unwrap();
11544        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11545        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11546
11547        let stop = Stop::new();
11548        stop.stop();
11549        assert!(
11550            !stop.finishing(),
11551            "no run is in flight at a between-runs boundary, so nothing else \
11552             would tell the operator this stop had not taken effect yet"
11553        );
11554
11555        let mut last_checked = None;
11556        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11557        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
11558            .await;
11559        assert_eq!(
11560            crate::disk::dir_size(&cache_dir),
11561            10,
11562            "over its cap, and due for the first check ever, but a stop outranks \
11563             it: the cap is a standing policy the next start measures again"
11564        );
11565        assert_eq!(
11566            last_checked, None,
11567            "a check that never happened must not claim the interval"
11568        );
11569    }
11570
11571    /// A backlog must not starve cache pruning. The finite cache worker runs
11572    /// independently of queue drain and must not consume any task attempts.
11573    #[tokio::test]
11574    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
11575        let dir = tempfile::tempdir().unwrap();
11576        let cache_dir = dir.path().join("cache");
11577        std::fs::create_dir_all(&cache_dir).unwrap();
11578        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
11579
11580        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
11581        opts.poll = Duration::from_millis(20);
11582        opts.max_attempts = 1_000;
11583
11584        let queue = Queue::at(dir.path().join("queue"));
11585        for i in 0..128 {
11586            let mut task = Task::new(
11587                format!("queued work {i}"),
11588                format!("queued work {i}"),
11589                opts.repo.clone(),
11590                Source::Human,
11591            );
11592            queue.put(&mut task).unwrap();
11593        }
11594
11595        let home = dir.path().join("home");
11596        let worktrees = dir.path().join("wt");
11597        run_service_worker(
11598            &home,
11599            serde_json::to_value(ServiceWorker {
11600                opts,
11601                queue: queue.root().to_path_buf(),
11602                worktrees_root: worktrees,
11603                operation: "cache".to_owned(),
11604            })
11605            .unwrap(),
11606        )
11607        .await
11608        .unwrap();
11609        let after = queue.list();
11610        assert_eq!(after.len(), 128);
11611        assert!(
11612            after
11613                .iter()
11614                .all(|task| task.status.runnable() && task.attempts == 0)
11615        );
11616
11617        assert_eq!(
11618            crate::disk::dir_size(&cache_dir),
11619            0,
11620            "an oversized cache must not be left to grow unboundedly just because the \
11621             queue kept the loop busy the whole time"
11622        );
11623    }
11624
11625    #[test]
11626    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
11627        let dir = tempfile::tempdir().unwrap();
11628        let queue = Queue::at(dir.path().join("queue"));
11629        let questions = Questions::at(dir.path().join("questions"));
11630        let mut task = task();
11631        queue.put(&mut task).unwrap();
11632
11633        let mut task_question = ask::Question::new(
11634            task.id.clone(),
11635            crate::conduct::NODE.to_owned(),
11636            "conduct".to_owned(),
11637            "Which backend?".to_owned(),
11638            String::new(),
11639            Vec::new(),
11640        );
11641        questions.put(&mut task_question).unwrap();
11642        task.block(vec![task_question.id.clone()], None);
11643        queue.put(&mut task).unwrap();
11644
11645        let mut run_question = ask::Question::new(
11646            "20260101-000000-run1".to_owned(),
11647            "review".to_owned(),
11648            "reviewer-1".to_owned(),
11649            "Run question".to_owned(),
11650            String::new(),
11651            Vec::new(),
11652        );
11653        questions.put(&mut run_question).unwrap();
11654
11655        // A question from another node whose `run` happens to equal this
11656        // task's id — the same field, filled in for an unrelated reason. Only
11657        // `crate::conduct::NODE` questions use `run` as a task id; this one
11658        // must never be touched by this reconciliation, even after release.
11659        let mut coincidental = ask::Question::new(
11660            task.id.clone(),
11661            "review".to_owned(),
11662            "reviewer-1".to_owned(),
11663            "Unrelated review question".to_owned(),
11664            String::new(),
11665            Vec::new(),
11666        );
11667        questions.put(&mut coincidental).unwrap();
11668
11669        reconcile_task_questions(&queue, &questions);
11670        assert!(questions.get(&task_question.id).unwrap().status.open());
11671        assert!(questions.get(&run_question.id).unwrap().status.open());
11672        assert!(questions.get(&coincidental.id).unwrap().status.open());
11673
11674        task.release();
11675        queue.put(&mut task).unwrap();
11676        reconcile_task_questions(&queue, &questions);
11677        assert_eq!(
11678            questions.get(&task_question.id).unwrap().status,
11679            ask::QuestionStatus::Abandoned
11680        );
11681        assert!(
11682            questions.get(&run_question.id).unwrap().status.open(),
11683            "run questions remain the run janitor's responsibility"
11684        );
11685        assert!(
11686            questions.get(&coincidental.id).unwrap().status.open(),
11687            "a non-conductor question must not be abandoned just because its \
11688             run id coincides with a task id"
11689        );
11690    }
11691
11692    #[test]
11693    fn a_freshly_started_running_task_is_never_stalled() {
11694        let dir = tempfile::tempdir().unwrap();
11695        let mut t = task();
11696        t.start("run-1".to_owned());
11697        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
11698        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
11699        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
11700    }
11701
11702    #[test]
11703    fn a_long_running_task_with_no_live_daemon_is_stalled() {
11704        let dir = tempfile::tempdir().unwrap();
11705        let mut t = task();
11706        t.start("run-1".to_owned());
11707        t.updated_at = Timestamp::now()
11708            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11709        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
11710        assert_eq!(
11711            stalled_tasks(
11712                &Queue::at(dir.path().join("q")),
11713                dir.path(),
11714                Timestamp::now()
11715            )
11716            .len(),
11717            0,
11718            "the task was never written to this queue"
11719        );
11720    }
11721
11722    #[test]
11723    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
11724        let dir = tempfile::tempdir().unwrap();
11725        let mut t = task();
11726        t.id = "20260903-080340-0167".to_owned();
11727        t.start("20260903-080619-01c2".to_owned());
11728        t.updated_at = Timestamp::now()
11729            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11730
11731        let mut status = Status::new();
11732        status.current = vec![Current {
11733            worker: None,
11734            task: t.id.clone(),
11735            run: "20260903-080619-01c2".to_owned(),
11736        }];
11737        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11738
11739        assert!(
11740            !is_stalled(&t, dir.path(), Timestamp::now()),
11741            "a live daemon's own heartbeat rules out stalled, however long the task has run"
11742        );
11743    }
11744
11745    /// Rewrite a task's `updated_at` on disk directly, bypassing
11746    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
11747    /// a fixture look like it has genuinely been `running` for a while.
11748    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
11749        let path = queue.path_of(id);
11750        let body = std::fs::read_to_string(&path).unwrap();
11751        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
11752        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
11753        v["updated_at"] = serde_json::Value::String(old.to_string());
11754        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
11755    }
11756
11757    #[test]
11758    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
11759        // The realistic `poll()` ordering, not `is_stalled` in isolation:
11760        // `reclaim_orphaned_running` runs first, on every poll, and settles
11761        // any `running` task whose claim it can actually take. For most
11762        // crashes that is immediate - a dead pid is proof enough for
11763        // `sweep_stale_claims` to drop the lock the same tick, and the very
11764        // next claim attempt succeeds. But a lock whose pid cannot be parsed
11765        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
11766        // `sweep_stale_claims`'s own doc), so the lock - and the claim
11767        // failure behind it - can legitimately outlive many polls. This is
11768        // exactly the gap `stalled_tasks` exists to surface well before that
11769        // six-hour sweep would: reclaim leaves the task `running`, and it
11770        // must still reach the conductor as stalled.
11771        let dir = tempfile::tempdir().unwrap();
11772        let queue = Queue::at(dir.path().join("queue"));
11773        let home = dir.path().join("home");
11774
11775        let mut t = task();
11776        t.id = "20260101-000001-lock".to_owned();
11777        t.start("run-1".to_owned());
11778        queue.put(&mut t).unwrap();
11779        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11780        std::fs::write(
11781            dir.path().join("queue").join(format!("{}.lock", t.id)),
11782            "not a pid",
11783        )
11784        .unwrap();
11785
11786        let now = Timestamp::now();
11787        assert!(
11788            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
11789            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
11790             and reclaim must leave the task alone"
11791        );
11792        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11793
11794        let stalled = stalled_tasks(&queue, &home, now);
11795        assert_eq!(
11796            stalled.len(),
11797            1,
11798            "reclaim's inability to claim it yet must not hide it from the conductor"
11799        );
11800        assert_eq!(stalled[0].id, t.id);
11801    }
11802
11803    #[test]
11804    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
11805        let dir = tempfile::tempdir().unwrap();
11806        crate::run::set_home(dir.path().join("run-home"));
11807        let queue = Queue::at(dir.path().join("queue"));
11808        let home = dir.path().join("home");
11809        let questions = Questions::at(dir.path().join("questions"));
11810
11811        let mut t = task();
11812        t.id = "20260101-000003-dead".to_owned();
11813        t.start("missing-run".to_owned());
11814        queue.put(&mut t).unwrap();
11815        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11816
11817        // This is the real poll ordering: retain the deterministic stalled
11818        // input before a claim proves the owner is gone and reclaims it.
11819        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11820        assert_eq!(
11821            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
11822            [&t.id]
11823        );
11824        assert_eq!(
11825            reclaim_orphaned_running(&queue, 2, &Default::default()),
11826            [t.id.clone()]
11827        );
11828        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11829
11830        // Reclaim drops its guard before conductor decisions are applied, so
11831        // the decision for the captured stalled input has a real write path.
11832        crate::conduct::apply(
11833            &queue,
11834            &questions,
11835            &crate::conduct::Verdict {
11836                decisions: vec![crate::conduct::Decision {
11837                    id: t.id.clone(),
11838                    recovery: Some(crate::conduct::Recovery::Requeue),
11839                    ..crate::conduct::Decision::default()
11840                }],
11841            },
11842        )
11843        .unwrap();
11844        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11845    }
11846
11847    #[test]
11848    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
11849        let dir = tempfile::tempdir().unwrap();
11850        let queue = Queue::at(dir.path().join("queue"));
11851        let home = dir.path().join("home");
11852
11853        let mut fresh = task();
11854        fresh.id = "20260101-000001-aaaa".to_owned();
11855        fresh.start("run-1".to_owned());
11856        queue.put(&mut fresh).unwrap();
11857
11858        let mut old = task();
11859        old.id = "20260101-000002-bbbb".to_owned();
11860        old.start("run-2".to_owned());
11861        queue.put(&mut old).unwrap();
11862        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
11863
11864        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11865        assert_eq!(stalled.len(), 1);
11866        assert_eq!(stalled[0].id, old.id);
11867    }
11868
11869    #[test]
11870    fn queued_and_finished_task_views_partition_by_status() {
11871        let dir = tempfile::tempdir().unwrap();
11872        let queue = Queue::at(dir.path().join("queue"));
11873
11874        let mut queued = task();
11875        queued.id = "20260101-000001-aaaa".to_owned();
11876        queue.put(&mut queued).unwrap();
11877
11878        let mut failed = task();
11879        failed.id = "20260101-000002-bbbb".to_owned();
11880        failed.start("run-1".to_owned());
11881        failed.fail("gate red", 5);
11882        queue.put(&mut failed).unwrap();
11883
11884        let mut held = task();
11885        held.id = "20260101-000003-cccc".to_owned();
11886        held.hold_machine(None);
11887        queue.put(&mut held).unwrap();
11888
11889        let mut running = task();
11890        running.id = "20260101-000004-dddd".to_owned();
11891        running.start("run-2".to_owned());
11892        queue.put(&mut running).unwrap();
11893
11894        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11895        assert_eq!(queued_ids, [queued.id.clone()]);
11896
11897        let mut finished_ids: Vec<String> =
11898            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11899        finished_ids.sort_unstable();
11900        let mut want = vec![failed.id.clone(), held.id.clone()];
11901        want.sort_unstable();
11902        assert_eq!(finished_ids, want);
11903    }
11904
11905    #[test]
11906    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11907        for short in [false, true] {
11908            let dir = tempfile::tempdir().unwrap();
11909            let queue = Queue::at(dir.path().join("queue"));
11910            let questions = ask::Questions::at(dir.path().join("questions"));
11911            let mut running = task();
11912            running.id = "20261013-192213-feb2".into();
11913            running.start("existing-run".into());
11914            queue.put(&mut running).unwrap();
11915            let mut middle = task();
11916            middle.id = "20261013-193611-ca5b".into();
11917            middle.block(
11918                vec![if short {
11919                    "feb2".into()
11920                } else {
11921                    running.id.clone()
11922                }],
11923                None,
11924            );
11925            queue.put(&mut middle).unwrap();
11926            let mut waiting = task();
11927            waiting.id = "20261013-202849-ee37".into();
11928            waiting.block(
11929                vec![if short {
11930                    "ca5b".into()
11931                } else {
11932                    middle.id.clone()
11933                }],
11934                Some("wait for implementation".into()),
11935            );
11936            queue.put(&mut waiting).unwrap();
11937            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11938            let inv = crate::blockers::Inventory::load(&queue, &questions);
11939            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11940            assert!(inv.stuck().is_empty());
11941            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11942            assert!(report.quarantined.is_empty());
11943            assert!(report.asked.is_empty());
11944            resolve_blockers(&queue, &questions);
11945            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11946            assert!(questions.list().is_empty());
11947            // Finishing the transitive prerequisite alone does not satisfy
11948            // the task's direct dependency.
11949            running.succeed();
11950            queue.put(&mut running).unwrap();
11951            resolve_blockers(&queue, &questions);
11952            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11953            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11954            middle = queue.get(&middle.id).unwrap();
11955            middle.succeed();
11956            queue.put(&mut middle).unwrap();
11957            resolve_blockers(&queue, &questions);
11958            let after = queue.get(&waiting.id).unwrap();
11959            assert_eq!(after.status, TaskStatus::Queued);
11960            assert!(after.blocked_by.is_empty());
11961            assert_eq!(after.instruction, waiting.instruction);
11962        }
11963    }
11964
11965    #[test]
11966    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11967        for future_schema in [false, true] {
11968            let name = "20261013-193611-ca5b";
11969            let mut future = task();
11970            future.id = name.into();
11971            future.schema = crate::queue::SCHEMA + 1;
11972            let contents = if future_schema {
11973                serde_json::to_string(&future).unwrap()
11974            } else {
11975                "corrupt".into()
11976            };
11977            let dir = tempfile::tempdir().unwrap();
11978            let queue = Queue::at(dir.path().join("queue"));
11979            let questions = ask::Questions::at(dir.path().join("questions"));
11980            let mut waiting = task();
11981            waiting.id = "20261013-202849-ee37".into();
11982            waiting.block(vec!["ca5b".into()], None);
11983            queue.put(&mut waiting).unwrap();
11984            std::fs::write(queue.path_of(name), contents).unwrap();
11985            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11986            assert!(
11987                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11988            );
11989            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11990            assert!(report.asked.is_empty());
11991            resolve_blockers(&queue, &questions);
11992            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11993            assert!(questions.list().is_empty());
11994        }
11995        let dir = tempfile::tempdir().unwrap();
11996        let queue = Queue::at(dir.path().join("queue"));
11997        let questions = ask::Questions::at(dir.path().join("questions"));
11998        let mut waiting = task();
11999        waiting.id = "20261013-202849-ee37".into();
12000        waiting.block(vec!["ca5b".into()], None);
12001        queue.put(&mut waiting).unwrap();
12002        let mut done = task();
12003        done.id = "20261013-193611-ca5b".into();
12004        done.succeed();
12005        queue.put(&mut done).unwrap();
12006        // An unreadable second match must not disappear from uniqueness
12007        // checks just because Queue::list skips it.
12008        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12009        assert!(queue.get("ca5b").is_err());
12010        assert_eq!(
12011            crate::queue::dependency(&queue, &questions, "ca5b"),
12012            crate::queue::Dependency::Ambiguous
12013        );
12014        resolve_blockers(&queue, &questions);
12015        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12016        assert!(report.asked.is_empty());
12017        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12018        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12019    }
12020
12021    #[test]
12022    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12023        for held in [false, true] {
12024            for question in [false, true] {
12025                for reference in ["ca5b", "20261013-193611-ca5b"] {
12026                    let dir = tempfile::tempdir().unwrap();
12027                    let queue = Queue::at(dir.path().join("queue"));
12028                    let questions = ask::Questions::at(dir.path().join("questions"));
12029                    let mut prerequisite = task();
12030                    prerequisite.id = "20261013-193611-ca5b".into();
12031                    prerequisite.start("existing-run".into());
12032                    queue.put(&mut prerequisite).unwrap();
12033                    let mut waiting = task();
12034                    waiting.id = "20261013-202849-ee37".into();
12035                    if held {
12036                        waiting.hold_machine(Some("waiting for separate consent".into()));
12037                    }
12038                    queue.put(&mut waiting).unwrap();
12039                    let reason = "Deleting saved data requires separate owner consent";
12040                    crate::conduct::apply(
12041                        &queue,
12042                        &questions,
12043                        &crate::conduct::Verdict {
12044                            decisions: vec![crate::conduct::Decision {
12045                                id: waiting.id.clone(),
12046                                blocked_by: vec![reference.into()],
12047                                question: question.then(|| "May the saved data be deleted?".into()),
12048                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12049                                reason: Some(reason.into()),
12050                                ..crate::conduct::Decision::default()
12051                            }],
12052                        },
12053                    )
12054                    .unwrap();
12055                    let before = queue.get(&waiting.id).unwrap();
12056                    if question {
12057                        assert_eq!(before.status, TaskStatus::Blocked);
12058                        let q = questions.get(&before.blocked_by[0]).unwrap();
12059                        assert_eq!(q.summary, "May the saved data be deleted?");
12060                        assert!(q.status.open());
12061                    } else {
12062                        assert_eq!(before.status, TaskStatus::Held);
12063                        let recorded_reason = before.hold_reason.as_deref().unwrap();
12064                        assert!(recorded_reason.starts_with(reason));
12065                        if held {
12066                            assert!(recorded_reason.contains("waiting for separate consent"));
12067                        }
12068                    }
12069                    prerequisite.succeed();
12070                    queue.put(&mut prerequisite).unwrap();
12071                    resolve_blockers(&queue, &questions);
12072                    let after = queue.get(&waiting.id).unwrap();
12073                    assert_eq!(after.status, before.status);
12074                    assert_eq!(after.blocked_by, before.blocked_by);
12075                    assert_eq!(after.hold_reason, before.hold_reason);
12076                    assert_eq!(after.instruction, waiting.instruction);
12077                    if question {
12078                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12079                    }
12080                    assert!(
12081                        queue.next_runnable().is_none(),
12082                        "dependency completion is not consent"
12083                    );
12084                }
12085            }
12086        }
12087    }
12088
12089    #[test]
12090    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12091        let dir = tempfile::tempdir().unwrap();
12092        let queue = Queue::at(dir.path().join("queue"));
12093        let questions = ask::Questions::at(dir.path().join("questions"));
12094
12095        let mut dep = task();
12096        dep.id = "20260101-000001-dep0".to_owned();
12097        dep.succeed();
12098        queue.put(&mut dep).unwrap();
12099
12100        let mut still_going = task();
12101        still_going.id = "20260101-000002-dep1".to_owned();
12102        queue.put(&mut still_going).unwrap();
12103
12104        let mut blocked = task();
12105        blocked.id = "20260101-000003-main".to_owned();
12106        blocked.block(
12107            vec![dep.id.clone(), still_going.id.clone()],
12108            Some("waits on both".to_owned()),
12109        );
12110        queue.put(&mut blocked).unwrap();
12111
12112        resolve_blockers(&queue, &questions);
12113
12114        let after = queue.get(&blocked.id).unwrap();
12115        assert_eq!(
12116            after.status,
12117            TaskStatus::Blocked,
12118            "one dependency is still outstanding"
12119        );
12120        assert_eq!(after.blocked_by, [still_going.id.clone()]);
12121    }
12122
12123    #[test]
12124    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12125        let dir = tempfile::tempdir().unwrap();
12126        let queue = Queue::at(dir.path().join("queue"));
12127        let questions = ask::Questions::at(dir.path().join("questions"));
12128
12129        let mut q = crate::ask::Question::new(
12130            "20260101-000001-main".to_owned(),
12131            crate::conduct::NODE.to_owned(),
12132            "conduct".to_owned(),
12133            "Which backend?".to_owned(),
12134            String::new(),
12135            Vec::new(),
12136        );
12137        questions.put(&mut q).unwrap();
12138        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12139            .unwrap();
12140        questions.put(&mut q).unwrap();
12141
12142        let mut blocked = task();
12143        blocked.id = "20260101-000001-main".to_owned();
12144        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12145        queue.put(&mut blocked).unwrap();
12146
12147        resolve_blockers(&queue, &questions);
12148
12149        let after = queue.get(&blocked.id).unwrap();
12150        assert_eq!(
12151            after.status,
12152            TaskStatus::Queued,
12153            "the only blocker resolved"
12154        );
12155        assert_eq!(after.answers.len(), 1);
12156        assert_eq!(after.answers[0].question, "Which backend?");
12157        assert_eq!(after.answers[0].answer, "SQLite");
12158
12159        // And the run this task starts next is told about it.
12160        let instruction = instruction_for(&after);
12161        assert!(instruction.contains("Which backend?"));
12162        assert!(instruction.contains("SQLite"));
12163    }
12164
12165    #[test]
12166    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12167        let dir = tempfile::tempdir().unwrap();
12168        let queue = Queue::at(dir.path().join("queue"));
12169        let questions = ask::Questions::at(dir.path().join("questions"));
12170
12171        let mut q = crate::ask::Question::new(
12172            "20260101-000001-main".to_owned(),
12173            crate::conduct::NODE.to_owned(),
12174            "conduct".to_owned(),
12175            "Is the setup done?".to_owned(),
12176            String::new(),
12177            Vec::new(),
12178        );
12179        q.abandon("no answer within 60s of asking");
12180        questions.put(&mut q).unwrap();
12181
12182        let mut blocked = task();
12183        blocked.id = "20260101-000001-main".to_owned();
12184        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12185        queue.put(&mut blocked).unwrap();
12186
12187        resolve_blockers(&queue, &questions);
12188
12189        let after = queue.get(&blocked.id).unwrap();
12190        assert_eq!(
12191            after.status,
12192            TaskStatus::Held,
12193            "never left blocked on nothing"
12194        );
12195        assert!(!after.operator_held(), "a machine hold, for triage");
12196        assert!(
12197            after
12198                .hold_reason
12199                .as_deref()
12200                .unwrap_or_default()
12201                .contains("went unanswered")
12202        );
12203    }
12204
12205    #[test]
12206    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12207        // Reproduces the reported bug (task 3958): a task held out of
12208        // attempts, blocked on a `crate::conduct` follow-up question, must
12209        // come back `held` once that question is answered - never `queued`,
12210        // whatever the answer said - or it silently re-enters the
12211        // competition queue with its attempts already exhausted.
12212        let dir = tempfile::tempdir().unwrap();
12213        let queue = Queue::at(dir.path().join("queue"));
12214        let questions = ask::Questions::at(dir.path().join("questions"));
12215
12216        let mut q = crate::ask::Question::new(
12217            "20260101-000001-main".to_owned(),
12218            crate::conduct::NODE.to_owned(),
12219            "conduct".to_owned(),
12220            "How should this be handled?".to_owned(),
12221            String::new(),
12222            Vec::new(),
12223        );
12224        questions.put(&mut q).unwrap();
12225        q.answer(crate::ask::Answer::Text(
12226            "leave it held, a human will look at it later".to_owned(),
12227        ))
12228        .unwrap();
12229        questions.put(&mut q).unwrap();
12230
12231        let mut held = task();
12232        held.id = "20260101-000001-main".to_owned();
12233        held.hold_machine(Some("out of attempts".to_owned()));
12234        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12235        queue.put(&mut held).unwrap();
12236
12237        resolve_blockers(&queue, &questions);
12238
12239        let after = queue.get(&held.id).unwrap();
12240        assert_eq!(after.status, TaskStatus::Held);
12241        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12242        assert_eq!(
12243            after.answers[0].answer,
12244            "leave it held, a human will look at it later"
12245        );
12246    }
12247
12248    #[test]
12249    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
12250        let dir = tempfile::tempdir().unwrap();
12251        let queue = Queue::at(dir.path().join("queue"));
12252        let questions = ask::Questions::at(dir.path().join("questions"));
12253        let mut dep = task();
12254        dep.id = "20260101-000001-gone".to_owned();
12255        queue.put(&mut dep).unwrap();
12256        let mut blocked = task();
12257        blocked.id = "20260101-000003-main".to_owned();
12258        blocked.block(vec![dep.id.clone()], None);
12259        queue.put(&mut blocked).unwrap();
12260
12261        // Claimed, so `remove` cannot rewrite it and the resolver must.
12262        let claim = queue.claim(&blocked.id).unwrap();
12263        queue.remove(&dep.id, false, &questions).unwrap();
12264        drop(claim);
12265        resolve_blockers(&queue, &questions);
12266
12267        let after = queue.get(&blocked.id).unwrap();
12268        assert_eq!(after.status, TaskStatus::Queued);
12269        assert!(after.blocked_by.is_empty());
12270    }
12271
12272    #[test]
12273    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12274        // Reproduces the reported bug: a task blocked on a task id that was
12275        // removed (`magi task rm`, or deleted by hand) can never see that id
12276        // reach `Done`, so the ordinary per-id loop has nothing to notice and
12277        // would otherwise leave the task `blocked` forever with no way for an
12278        // operator to find out why.
12279        let dir = tempfile::tempdir().unwrap();
12280        let queue = Queue::at(dir.path().join("queue"));
12281        let questions = ask::Questions::at(dir.path().join("questions"));
12282
12283        let mut still_going = task();
12284        still_going.id = "20260101-000002-dep1".to_owned();
12285        queue.put(&mut still_going).unwrap();
12286
12287        let mut blocked = task();
12288        blocked.id = "20260101-000003-main".to_owned();
12289        blocked.block(
12290            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12291            Some("waits on both".to_owned()),
12292        );
12293        queue.put(&mut blocked).unwrap();
12294
12295        resolve_blockers(&queue, &questions);
12296
12297        let after = queue.get(&blocked.id).unwrap();
12298        assert_eq!(
12299            after.status,
12300            TaskStatus::Held,
12301            "a missing dependency must not leave the task blocked forever"
12302        );
12303        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12304        assert!(after.blocked_by.is_empty());
12305        let reason = after.hold_reason.as_deref().unwrap_or_default();
12306        assert!(
12307            reason.contains("20260101-000001-gone"),
12308            "the missing id must be named so an operator can tell what happened: {reason}"
12309        );
12310        assert!(
12311            reason.contains(&still_going.id),
12312            "the still-valid dependency must not silently vanish from the record: {reason}"
12313        );
12314    }
12315
12316    #[test]
12317    fn instruction_for_is_unchanged_without_any_answers() {
12318        let t = task();
12319        assert_eq!(instruction_for(&t), t.instruction);
12320    }
12321
12322    #[test]
12323    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12324        let dir = tempfile::tempdir().unwrap();
12325        let q = Queue::at(dir.path().join("queue"));
12326        let src = dir.path().join("shot.png");
12327        std::fs::write(&src, "x").unwrap();
12328        let mut t = task();
12329        q.attach(&mut t, &[src]).unwrap();
12330        let paths = task_attachments(&q, &t).unwrap();
12331        assert_eq!(paths.len(), 1);
12332        assert!(paths[0].is_absolute() && paths[0].is_file());
12333        std::fs::remove_file(&paths[0]).unwrap();
12334        let err = task_attachments(&q, &t).unwrap_err().to_string();
12335        assert!(err.contains("shot.png"), "{err}");
12336    }
12337
12338    #[tokio::test]
12339    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
12340        let dir = tempfile::tempdir().unwrap();
12341        let queue_path = dir.path().join("queue");
12342        let queue = Queue::at(queue_path.clone());
12343        let mut t = task();
12344        t.source = Source::Agent {
12345            run: "originating-chat".into(),
12346            node: crate::queue::CHAT_NODE.into(),
12347        };
12348        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
12349            stage: "config-fetch",
12350            target: "origin/main".into(),
12351        });
12352        record_config_failure(&mut t, &fetch);
12353        t.hold_machine(Some(format!("{fetch:#}")));
12354        let fetch_key = t.chat_notice_due().unwrap();
12355        t.chat_notices.push(fetch_key.clone());
12356        queue.put(&mut t).unwrap();
12357
12358        let queue = Queue::at(queue_path);
12359        let mut t = queue.get(&t.id).unwrap();
12360        let a = dir.path().join("a.toml");
12361        let b = dir.path().join("b.toml");
12362        for (path, text, new_cause) in [
12363            (&a, "[graph", true),
12364            (&a, "[verify", false),
12365            (&a, "[graph]\nimplementers = 'invalid-type'", true),
12366            (&b, "[graph]\nimplementers = 'invalid-type'", true),
12367        ] {
12368            t.release_operator("test", None);
12369            std::fs::write(path, text).unwrap();
12370            let error = Config::discover_fetched(dir.path(), Some(path))
12371                .await
12372                .unwrap_err();
12373            record_config_failure(&mut t, &error);
12374            t.hold_machine(Some(format!("{error:#}")));
12375            let due = t.chat_notice_due();
12376            assert_eq!(due.is_some(), new_cause, "{error:#}");
12377            if let Some(key) = due {
12378                assert_ne!(key, fetch_key);
12379                t.chat_notices.push(key);
12380            }
12381        }
12382        t.succeed();
12383        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
12384    }
12385
12386    #[test]
12387    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12388        let dir = tempfile::tempdir().unwrap();
12389        let queue_path = dir.path().join("queue");
12390        let queue = Queue::at(queue_path.clone());
12391        let mut t = task();
12392        t.source = crate::queue::Source::Agent {
12393            run: "originating-chat".into(),
12394            node: crate::queue::CHAT_NODE.into(),
12395        };
12396        let a = dir.path().join("a.png");
12397        let b = dir.path().join("b.png");
12398        std::fs::write(&a, "a").unwrap();
12399        std::fs::write(&b, "b").unwrap();
12400        queue.attach(&mut t, &[a, b]).unwrap();
12401        let paths = task_attachments(&queue, &t).unwrap();
12402        for path in &paths {
12403            std::fs::remove_file(path).unwrap();
12404        }
12405        let missing = task_attachments(&queue, &t).unwrap_err();
12406        t.attempts += 1;
12407        let reason = missing.to_string();
12408        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12409        let first = t.chat_notice_due().expect("first attachment notice");
12410        t.chat_notices.push(first.clone());
12411        queue.put(&mut t).unwrap();
12412
12413        let queue = Queue::at(queue_path.clone());
12414        let mut t = queue.get(&t.id).unwrap();
12415        assert!(t.chat_notice_due().is_none(), "restart does not replay");
12416        t.release_operator("test", None);
12417        t.attempts += 1;
12418        let missing = task_attachments(&queue, &t).unwrap_err();
12419        t.fail_startup_target(
12420            "startup-attachments",
12421            missing.name,
12422            "same missing attachment with regenerated wording",
12423            1,
12424        );
12425        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
12426
12427        std::fs::write(&paths[0], "restored").unwrap();
12428        t.release_operator("test", None);
12429        t.attempts += 1;
12430        let missing = task_attachments(&queue, &t).unwrap_err();
12431        let reason = missing.to_string();
12432        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12433        let second = t
12434            .chat_notice_due()
12435            .expect("different attachment must notify");
12436        assert_ne!(first, second);
12437        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
12438    }
12439
12440    #[test]
12441    fn resumed_instruction_is_unchanged_without_any_answers() {
12442        let t = task();
12443        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
12444    }
12445
12446    #[test]
12447    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
12448        let mut t = task();
12449        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12450        // The run's own instruction on disk predates the answer: it is the
12451        // plain original text `Runner::start` saved before the operator was
12452        // ever asked anything.
12453        let old = t.instruction.clone();
12454
12455        let refreshed = resumed_instruction(&old, &t);
12456        assert!(refreshed.starts_with(&old), "the original text is kept");
12457        assert!(refreshed.contains("Which backend?"));
12458        assert!(refreshed.contains("SQLite"));
12459    }
12460
12461    #[test]
12462    fn resumed_instruction_keeps_an_original_answers_heading() {
12463        let mut t = task();
12464        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
12465        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12466
12467        let refreshed = resumed_instruction(&t.instruction, &t);
12468
12469        assert!(
12470            refreshed.starts_with(&t.instruction),
12471            "an answers heading in the original instruction is not the appended block"
12472        );
12473        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
12474        assert!(refreshed.contains("Which backend?"));
12475        assert!(refreshed.contains("SQLite"));
12476
12477        let repeated = resumed_instruction(&refreshed, &t);
12478        assert_eq!(
12479            repeated, refreshed,
12480            "only the final appended block is refreshed"
12481        );
12482    }
12483
12484    #[test]
12485    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
12486        let mut t = task();
12487        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12488
12489        // A first resume appends the block; a second resume of the same run,
12490        // with no new answer in between, must reproduce exactly the same
12491        // text rather than appending the block a second time.
12492        let once = resumed_instruction(&t.instruction, &t);
12493        let twice = resumed_instruction(&once, &t);
12494        assert_eq!(once, twice);
12495        assert_eq!(once.matches("Which backend?").count(), 1);
12496
12497        // A later answer replaces the block wholesale rather than growing it.
12498        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
12499        let refreshed = resumed_instruction(&once, &t);
12500        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
12501        assert!(refreshed.contains("Which backend?"));
12502        assert!(refreshed.contains("Which cache?"));
12503    }
12504
12505    #[test]
12506    fn prepare_instruction_covers_all_three_starters() {
12507        let mut t = task();
12508        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12509
12510        // Start: a fresh run gets the task text plus every answer so far —
12511        // exactly `instruction_for`.
12512        assert_eq!(
12513            prepare_instruction(&Starter::Start, None, &t),
12514            Some(instruction_for(&t))
12515        );
12516
12517        // Resume: the run's prior instruction is refreshed with the answer,
12518        // not discarded and not left stale.
12519        let old = t.instruction.clone();
12520        assert_eq!(
12521            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
12522            Some(resumed_instruction(&old, &t))
12523        );
12524
12525        // Review: a review-only pass builds its own instruction from the
12526        // branch's history in `crate::graph`, with no task statement at all -
12527        // this boundary must leave it alone.
12528        assert_eq!(
12529            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
12530            None
12531        );
12532    }
12533
12534    #[test]
12535    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
12536        assert_eq!(
12537            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
12538            Starter::Review("magi/eba2/A".to_owned())
12539        );
12540    }
12541
12542    #[test]
12543    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
12544        assert_eq!(
12545            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
12546            Starter::Start,
12547            "a vanished review branch must not fall back to resuming the old run either"
12548        );
12549    }
12550
12551    #[test]
12552    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
12553        let mut t = task();
12554        t.start("old-run".to_owned());
12555        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
12556        t.release();
12557        let branch = t.review_branch.take();
12558        assert_eq!(
12559            choose_starter(branch.as_deref(), true, Some("old-run")),
12560            Starter::Review("magi/eba2/A".to_owned()),
12561            "a review wins over resuming the old run"
12562        );
12563    }
12564
12565    #[test]
12566    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
12567        assert_eq!(
12568            choose_starter(None, false, Some("some-run")),
12569            Starter::Resume("some-run".to_owned())
12570        );
12571        assert_eq!(choose_starter(None, false, None), Starter::Start);
12572    }
12573
12574    #[test]
12575    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
12576        let mut released = task();
12577        released.start("stalled-run".to_owned());
12578        released.requeue();
12579        let unfinished = (!released.fresh_start)
12580            .then(|| Some("stalled-run".to_owned()))
12581            .flatten();
12582        assert_eq!(
12583            choose_starter(None, false, unfinished.as_deref()),
12584            Starter::Start,
12585            "release keeps run history but must not resume it"
12586        );
12587        assert_eq!(released.runs, ["stalled-run"]);
12588    }
12589
12590    #[test]
12591    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
12592        let dir = tempfile::tempdir().unwrap();
12593        let queue = Queue::at(dir.path().join("queue"));
12594        let mut state = run_state(RunStatus::Blocked);
12595        state.merge_decision = Some(crate::merge_decision::Decision {
12596            question: "hold-inquiry".into(),
12597            target: crate::merge_decision::Target {
12598                pr: "https://example.test/pull/1".into(),
12599                head: "reviewed-head".into(),
12600                language: "en".into(),
12601            },
12602            choice: land::HOLD.into(),
12603            closed: false,
12604            replacement_run: None,
12605            replacement_pr: None,
12606        });
12607        let mut t = task();
12608        t.start(state.id.clone());
12609        settle_and_diagnose(
12610            &mut t,
12611            Verdict {
12612                status: RunStatus::Blocked,
12613                left_pr: true,
12614                quota_hit: false,
12615                parked: false,
12616                no_viable_candidates: false,
12617            },
12618            "held",
12619            2,
12620            &state,
12621        );
12622        queue.put(&mut t).unwrap();
12623        t.release_operator("chat", None);
12624        t.edit("revised".into(), "revised instruction".into())
12625            .unwrap();
12626        queue.put(&mut t).unwrap();
12627        drop(state);
12628        assert_eq!(
12629            queue
12630                .get(&t.id)
12631                .unwrap()
12632                .decision_effects
12633                .get("hold-inquiry"),
12634            Some(&format!("decision: {}", land::HOLD))
12635        );
12636    }
12637
12638    fn stopped_public_run(status: RunStatus) -> RunState {
12639        let mut state = run_state(status);
12640        state.driver_exited = true;
12641        state.config.graph.land = true;
12642        state.config.graph.review_rounds = 1;
12643        state.reviews = vec![review_round(1)];
12644        state.merge = Some(crate::run::MergeOutcome {
12645            mode: MergeMode::Pr,
12646            ok: false,
12647            detail: "landing stopped".into(),
12648            empty: false,
12649        });
12650        state.pr = Some(crate::run::PrRecord {
12651            url: "https://example.test/pull/1".into(),
12652            number: 1,
12653            state: "open".into(),
12654            checks: "red".into(),
12655            round: 1,
12656            rounds: 1,
12657            red_at_merge: Vec::new(),
12658        });
12659        state
12660    }
12661
12662    #[test]
12663    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
12664        for status in [RunStatus::Blocked, RunStatus::Gating] {
12665            let home = tempfile::tempdir().unwrap();
12666            let mut state = stopped_public_run(status);
12667            state.save_under(home.path()).unwrap();
12668            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
12669            assert!(!exhausted_review_budget(&state));
12670            let mut task = held_task_with(&state.id);
12671            task.release();
12672            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12673            assert_eq!(
12674                choose_starter(None, false, unfinished.as_deref()),
12675                Starter::Resume(state.id.clone())
12676            );
12677            let question = action_question(&state.id, resume_action(&state.id));
12678            assert_eq!(
12679                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12680                    state.clone()
12681                )),
12682                ActionDecision::Resume(state.id.clone())
12683            );
12684            // The control-plane command uses this same preflight before pinning.
12685            assert_eq!(
12686                crate::resume::validate(home.path(), &state.id).unwrap().id,
12687                state.id
12688            );
12689            let queue = Queue::at(home.path().join("queue"));
12690            let mut controlled = Task::new(
12691                "resume land".into(),
12692                state.instruction.clone(),
12693                state.repo.clone(),
12694                Source::Agent {
12695                    run: "talk".into(),
12696                    node: crate::queue::CHAT_NODE.into(),
12697                },
12698            );
12699            controlled.runs.push(state.id.clone());
12700            controlled.hold_machine(Some("land stopped".into()));
12701            queue.put(&mut controlled).unwrap();
12702            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12703            assert_eq!(resumed.status, TaskStatus::Queued);
12704            assert_eq!(
12705                resumed.resume_override.unwrap().pinned_run,
12706                Some(state.id.clone())
12707            );
12708            assert_eq!(resumed.attempts, 0);
12709        }
12710    }
12711
12712    #[test]
12713    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
12714        for review_rounds in [0, 1] {
12715            let home = tempfile::tempdir().unwrap();
12716            let mut state = run_state(RunStatus::Blocked);
12717            state.config.graph.review_rounds = review_rounds;
12718            if review_rounds > 0 {
12719                let mut review = review_round(1);
12720                review.clean = true;
12721                state.reviews = vec![review];
12722            }
12723            state.gate_ran = true;
12724            state.gate = vec![crate::run::CommandOutcome {
12725                command: "verify".into(),
12726                code: Some(1),
12727                output_tail: "gate failed after repair budget exhausted".into(),
12728                duration_ms: 0,
12729                resource_blocked: false,
12730            }];
12731            state.save_under(home.path()).unwrap();
12732            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12733            assert!(exhausted_review_budget(&state));
12734            let mut task = held_task_with(&state.id);
12735            task.release();
12736            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
12737            let question = action_question(&state.id, resume_action(&state.id));
12738            assert_ne!(
12739                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12740                    state.clone()
12741                )),
12742                ActionDecision::Resume(state.id.clone())
12743            );
12744            let error = crate::resume::validate(home.path(), &state.id)
12745                .unwrap_err()
12746                .to_string();
12747            assert!(!error.contains("review budget exhausted"), "{error}");
12748            assert!(
12749                error.contains(if review_rounds == 0 {
12750                    "review is disabled"
12751                } else {
12752                    "gate already ran"
12753                }),
12754                "{error}"
12755            );
12756
12757            // An unexecuted gate still has work to do with or without reviews.
12758            state.gate_ran = false;
12759            state.gate.clear();
12760            assert!(!exhausted_review_budget(&state));
12761            assert_eq!(
12762                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
12763                Some(state.id)
12764            );
12765        }
12766    }
12767
12768    #[test]
12769    fn resource_blocked_verification_resumes_the_same_run() {
12770        for (kind, stage) in [
12771            ("cache", "clean"),
12772            ("coordination", "clean"),
12773            ("cache", "review-e2e"),
12774            ("coordination", "no-reviews"),
12775            ("coordination", "handoff"),
12776        ] {
12777            let home = tempfile::tempdir().unwrap();
12778            let mut state = run_state(RunStatus::Blocked);
12779            state.config.graph.review_rounds = 1;
12780            let mut review = review_round(1);
12781            review.clean = true;
12782            state.reviews = vec![review];
12783            if stage == "review-e2e" {
12784                let review = &mut state.reviews[0];
12785                review.clean = false;
12786                review.blocking = 1;
12787                review.e2e = vec![crate::run::CommandOutcome {
12788                    command: "verify".into(),
12789                    code: None,
12790                    output_tail: "resource wait expired".into(),
12791                    duration_ms: 0,
12792                    resource_blocked: true,
12793                }];
12794            } else if stage == "no-reviews" {
12795                state.config.graph.review_rounds = 0;
12796                state.reviews.clear();
12797            } else if stage == "handoff" {
12798                // A completed final verification can hand off to the gate
12799                // even when the review still carries contested findings.
12800                let review = &mut state.reviews[0];
12801                review.clean = false;
12802                review.blocking = 1;
12803                review.e2e = vec![crate::run::CommandOutcome {
12804                    command: "verify".into(),
12805                    code: Some(0),
12806                    output_tail: String::new(),
12807                    duration_ms: 0,
12808                    resource_blocked: false,
12809                }];
12810            }
12811            state.gate_ran = false;
12812            state.resource_block = Some(crate::run::ResourceBlock {
12813                cause: crate::run::ResourceBlockCause::Other,
12814                node: if stage == "review-e2e" {
12815                    "review"
12816                } else {
12817                    "gate"
12818                }
12819                .into(),
12820                kind: kind.into(),
12821                detail: "resource wait expired".into(),
12822                at: jiff::Timestamp::now(),
12823            });
12824            state.save_under(home.path()).unwrap();
12825            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12826            assert!(!exhausted_review_budget(&state));
12827            let mut task = held_task_with(&state.id);
12828            task.release();
12829            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12830            assert_eq!(
12831                choose_starter(None, false, unfinished.as_deref()),
12832                Starter::Resume(state.id.clone())
12833            );
12834            let question = action_question(&state.id, resume_action(&state.id));
12835            assert_eq!(
12836                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12837                    state.clone()
12838                )),
12839                ActionDecision::Resume(state.id.clone())
12840            );
12841            assert_eq!(
12842                crate::resume::validate(home.path(), &state.id).unwrap().id,
12843                state.id
12844            );
12845            let queue = Queue::at(home.path().join("queue"));
12846            let mut controlled = Task::new(
12847                "resume verification".into(),
12848                state.instruction.clone(),
12849                state.repo.clone(),
12850                Source::Agent {
12851                    run: "talk".into(),
12852                    node: crate::queue::CHAT_NODE.into(),
12853                },
12854            );
12855            controlled.runs.push(state.id.clone());
12856            controlled.hold_machine(Some("verification resource unavailable".into()));
12857            queue.put(&mut controlled).unwrap();
12858            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12859            assert_eq!(resumed.status, TaskStatus::Queued);
12860            assert_eq!(
12861                resumed.resume_override.unwrap().pinned_run,
12862                Some(state.id.clone())
12863            );
12864            assert_eq!(resumed.attempts, 0);
12865
12866            // A genuinely unresolved final review still exhausts the budget.
12867            state.config.graph.review_rounds = 1;
12868            let mut unresolved = review_round(1);
12869            unresolved.blocking = 1;
12870            state.reviews = vec![unresolved];
12871            state.resource_block = None;
12872            state.save_under(home.path()).unwrap();
12873            assert!(exhausted_review_budget(&state));
12874            assert!(crate::resume::validate(home.path(), &state.id).is_err());
12875        }
12876    }
12877
12878    #[tokio::test]
12879    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
12880        if !crate::standalone_test(
12881            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
12882        ) {
12883            return;
12884        }
12885        let home = tempfile::tempdir().unwrap();
12886        let mut owner = stopped_public_run(RunStatus::Blocked);
12887        owner.save_under(home.path()).unwrap();
12888        let history = vec![owner.id.clone()];
12889        let repo = owner.repo.clone();
12890        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
12891        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
12892        let initial =
12893            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
12894        assert!(
12895            initial.is_pending(),
12896            "a busy record must not hold or resume the task"
12897        );
12898        owner.retired_to = Some("20260101-000001-bbbb".into());
12899        owner.save_under(home.path()).unwrap();
12900        drop(lock);
12901        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
12902            .await
12903            .expect("ownership lock released")
12904            .expect("read settled owner");
12905        assert!(
12906            result.is_none(),
12907            "the retired owner must not be resumed from a stale read"
12908        );
12909    }
12910
12911    #[tokio::test]
12912    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
12913        if !crate::standalone_test(
12914            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
12915        ) {
12916            return;
12917        }
12918        let home = tempfile::tempdir().unwrap();
12919        let mut owner = stopped_public_run(RunStatus::Blocked);
12920        let repo = tempfile::tempdir().unwrap();
12921        crate::git::git(repo.path(), &["init"]).await.unwrap();
12922        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12923        owner.id = "20260101-000000-aaaa".into();
12924        owner.save_under(home.path()).unwrap();
12925        let mut successor = run_state(RunStatus::Blocked);
12926        successor.id = "20260101-000001-bbbb".into();
12927        successor.save_under(home.path()).unwrap();
12928        let runs = vec![owner.id.clone(), successor.id.clone()];
12929        assert_eq!(
12930            public_resume_owner(home.path(), &runs, &owner.repo)
12931                .await
12932                .unwrap()
12933                .unwrap()
12934                .id,
12935            owner.id
12936        );
12937        let subdir = owner.repo.join("nested");
12938        std::fs::create_dir(&subdir).unwrap();
12939        assert_eq!(
12940            public_resume_owner(home.path(), &runs, &subdir)
12941                .await
12942                .unwrap()
12943                .unwrap()
12944                .id,
12945            owner.id
12946        );
12947        #[cfg(unix)]
12948        {
12949            let alias = home.path().join("repo-alias");
12950            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12951            assert_eq!(
12952                public_resume_owner(home.path(), &runs, &alias.join("nested"))
12953                    .await
12954                    .unwrap()
12955                    .unwrap()
12956                    .id,
12957                owner.id
12958            );
12959        }
12960        let different = tempfile::tempdir().unwrap();
12961        crate::git::git(different.path(), &["init"]).await.unwrap();
12962        assert!(
12963            public_resume_owner(home.path(), &runs, different.path())
12964                .await
12965                .is_err()
12966        );
12967        std::fs::remove_file(
12968            home.path()
12969                .join("runs")
12970                .join(&successor.id)
12971                .join("run.json"),
12972        )
12973        .unwrap();
12974        assert!(
12975            public_resume_owner(home.path(), &runs, &owner.repo)
12976                .await
12977                .is_err()
12978        );
12979    }
12980
12981    #[test]
12982    fn an_ordinary_release_keeps_a_resumable_run_available() {
12983        let mut released = task();
12984        released.start("stalled-run".to_owned());
12985        released.release();
12986        let unfinished = (!released.fresh_start)
12987            .then(|| Some("stalled-run".to_owned()))
12988            .flatten();
12989        assert_eq!(
12990            choose_starter(None, false, unfinished.as_deref()),
12991            Starter::Resume("stalled-run".to_owned()),
12992            "manual release must preserve the normal resume path"
12993        );
12994    }
12995
12996    #[test]
12997    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12998        use crate::handover::{ResumeRefusal, resume_refusal_under};
12999        let home = tempfile::tempdir().unwrap();
13000        let mut exhausted = run_state(RunStatus::Blocked);
13001        exhausted.driver_exited = true;
13002        exhausted.config.graph.review_rounds = 3;
13003        exhausted.reviews = (1..=3).map(review_round).collect();
13004        for refusal in [
13005            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13006            ResumeRefusal::Status(RunStatus::Ready),
13007            ResumeRefusal::Released("20261022-000000-aaaa".into()),
13008            ResumeRefusal::Retired("retirement-successor".into()),
13009            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13010        ] {
13011            let mut state = exhausted.clone();
13012            let expected = match refusal {
13013                ResumeRefusal::Status(_) => {
13014                    state.status = RunStatus::Ready;
13015                    "status `ready`"
13016                }
13017                ResumeRefusal::Released(ref target) => {
13018                    state.released_to = Some(target.clone());
13019                    "execution was released"
13020                }
13021                ResumeRefusal::Retired(ref target) => {
13022                    state.retired_to = Some(target.clone());
13023                    "execution was retired"
13024                }
13025                ResumeRefusal::OwnershipTransferred(ref target) => {
13026                    state.pr_taken_over_by = Some(target.clone());
13027                    "PR ownership was transferred"
13028                }
13029                _ => "review budget exhausted (3/3 rounds used)",
13030            };
13031            assert_eq!(
13032                resume_refusal_under(&state, Some(home.path())),
13033                Some(refusal.clone())
13034            );
13035            assert_eq!(
13036                refusal.successor(),
13037                state
13038                    .released_to
13039                    .as_deref()
13040                    .or(state.retired_to.as_deref())
13041                    .or(state.pr_taken_over_by.as_deref())
13042            );
13043            state.save_under(home.path()).unwrap();
13044            let queue = Queue::at(home.path().join("queue"));
13045            let mut task = Task::new(
13046                "retained implementation".into(),
13047                state.instruction.clone(),
13048                state.repo.clone(),
13049                Source::Agent {
13050                    run: "talk".into(),
13051                    node: crate::queue::CHAT_NODE.into(),
13052                },
13053            );
13054            task.runs.push(state.id.clone());
13055            task.hold_machine(Some("stopped".into()));
13056            queue.put(&mut task).unwrap();
13057            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13058            let before_run = serde_json::to_value(&state).unwrap();
13059            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13060                .unwrap_err()
13061                .to_string();
13062            assert!(error.contains(expected), "{error}");
13063            assert!(!error.contains("only a stalled or blocked"), "{error}");
13064            if matches!(refusal, ResumeRefusal::Status(_)) {
13065                assert!(
13066                    error.contains("is final; there is nothing left to resume"),
13067                    "{error}"
13068                );
13069            }
13070            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13071                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13072                assert!(error.contains("review-only successor with a new review budget"));
13073                assert!(error.contains("does not resume this run"));
13074            }
13075            for target in [
13076                &state.released_to,
13077                &state.retired_to,
13078                &state.pr_taken_over_by,
13079            ]
13080            .into_iter()
13081            .flatten()
13082            {
13083                let short = if state.retired_to.as_ref() == Some(target) {
13084                    target.as_str()
13085                } else {
13086                    crate::run::short_of(target)
13087                };
13088                assert!(
13089                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
13090                    "{error}"
13091                );
13092                if short != target {
13093                    assert!(!error.contains(target), "full successor id leaked: {error}");
13094                }
13095            }
13096            assert_eq!(
13097                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13098                before_task
13099            );
13100            assert_eq!(
13101                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13102                    .unwrap(),
13103                before_run
13104            );
13105            let question = action_question(&state.id, resume_action(&state.id));
13106            for phrases in [&PHRASES_EN, &PHRASES_JA] {
13107                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13108                    RunState::load_under(id, home.path())
13109                });
13110                let ActionDecision::Refuse(detail) = decision else {
13111                    panic!(
13112                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13113                        state.id,
13114                        home.path().display()
13115                    );
13116                };
13117                assert!(detail.contains(expected), "{detail}");
13118            }
13119        }
13120        // Preserve predicate ordering, while keeping every recorded destination visible.
13121        exhausted.status = RunStatus::Ready;
13122        exhausted.released_to = Some("released".into());
13123        exhausted.retired_to = Some("retired".into());
13124        exhausted.pr_taken_over_by = Some("owner".into());
13125        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13126        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13127        let detail = reason.diagnostic(&exhausted);
13128        for target in ["released", "retired", "owner"] {
13129            assert!(detail.contains(&format!("magi show {target}")));
13130        }
13131    }
13132
13133    #[test]
13134    fn resume_action_ignores_question_checkpoints_in_another_home() {
13135        crate::run::pin_test_home();
13136        let home = tempfile::tempdir().unwrap();
13137        let mut state = run_state(RunStatus::Blocked);
13138        // The private directory reserves this fixture's identity even while
13139        // other tests write questions into the process-wide store.
13140        state.id = format!(
13141            "resume-context-{}",
13142            home.path().file_name().unwrap().to_str().unwrap()
13143        );
13144        state.driver_exited = true;
13145        state.config.graph.review_rounds = 1;
13146        state.reviews = vec![review_round(1)];
13147        state.save_under(home.path()).unwrap();
13148        let task = held_task_with(&state.id);
13149        let answer = action_question(&state.id, resume_action(&state.id));
13150        let mut checkpoint = approval_question(&state.id);
13151        let foreign = Questions::open();
13152        foreign.put(&mut checkpoint).unwrap();
13153        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13154        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13155            RunState::load_under(id, home.path())
13156        });
13157        let matching: Vec<_> = foreign
13158            .list()
13159            .into_iter()
13160            .filter(|q| q.run == state.id && q.status.open())
13161            .collect();
13162        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13163        assert!(
13164            matches!(decision, ActionDecision::Refuse(_)),
13165            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13166            state.id,
13167            home.path().display(),
13168            crate::run::test_home().display()
13169        );
13170        assert_eq!(
13171            refusal,
13172            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13173        );
13174        let local = Questions::at(home.path().join("questions"));
13175        for status in [
13176            ask::QuestionStatus::Open,
13177            ask::QuestionStatus::Answered,
13178            ask::QuestionStatus::Abandoned,
13179        ] {
13180            let mut question = checkpoint.clone();
13181            match status {
13182                ask::QuestionStatus::Open => {}
13183                ask::QuestionStatus::Answered => {
13184                    question
13185                        .answer(ask::Answer::Choice(question.choices[0].clone()))
13186                        .unwrap();
13187                }
13188                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13189            }
13190            local.put(&mut question).unwrap();
13191            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13192                RunState::load_under(id, home.path())
13193            });
13194            if status.open() {
13195                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13196            } else {
13197                assert!(
13198                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13199                    "status={status:?}, decision={decision:?}"
13200                );
13201            }
13202        }
13203    }
13204
13205    #[test]
13206    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13207        let home = tempfile::tempdir().unwrap();
13208        let mut state = run_state(RunStatus::Stalled);
13209        state.id = format!(
13210            "resume-driver-{}",
13211            home.path().file_name().unwrap().to_str().unwrap()
13212        );
13213        state.driver_claimed = Some(false);
13214        state.save_under(home.path()).unwrap();
13215        let task = held_task_with(&state.id);
13216        let question = action_question(&state.id, resume_action(&state.id));
13217        let decide = || {
13218            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13219                RunState::load_under(id, home.path())
13220            })
13221        };
13222        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13223        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13224        assert_eq!(
13225            decide(),
13226            ActionDecision::Refuse("run already has a live driver".into())
13227        );
13228        drop(lease);
13229        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13230    }
13231
13232    #[test]
13233    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13234        let home = tempfile::tempdir().unwrap();
13235        let mut state = run_state(RunStatus::Blocked);
13236        state.driver_exited = true;
13237        state.config.graph.review_rounds = 1;
13238        state.reviews = vec![review_round(1)];
13239        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13240        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13241            let mut saved = state.clone();
13242            match checkpoint {
13243                "publication" => saved.pr_publication_pending = true,
13244                "approval" => {
13245                    saved.land_approval = Some(crate::run::LandApproval {
13246                        question: "approval".into(),
13247                        head: "head".into(),
13248                    })
13249                }
13250                "armed" => saved.land_armed_head = Some("head".into()),
13251                "landing" => saved.status = RunStatus::Landing,
13252                _ => {
13253                    let mut question = ask::Question::new(
13254                        saved.id.clone(),
13255                        "review".into(),
13256                        "review-1".into(),
13257                        "continue?".into(),
13258                        String::new(),
13259                        vec!["continue".into()],
13260                    );
13261                    ask::Questions::at(home.path().join("questions"))
13262                        .put(&mut question)
13263                        .unwrap();
13264                }
13265            }
13266            saved.save_under(home.path()).unwrap();
13267            assert!(
13268                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13269                "{checkpoint}"
13270            );
13271            assert!(
13272                crate::resume::validate(home.path(), &saved.id).is_ok(),
13273                "{checkpoint}"
13274            );
13275        }
13276    }
13277
13278    #[test]
13279    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
13280        let mut state = run_state(RunStatus::Blocked);
13281        state.config.graph.review_rounds = 3;
13282        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
13283        assert!(exhausted_review_budget(&state));
13284
13285        // One round still unused: resuming can still ask a reviewer something.
13286        state.reviews.pop();
13287        assert!(!exhausted_review_budget(&state));
13288
13289        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
13290        // count: only a `Blocked` run re-enters the review loop on resume.
13291        let mut stalled = run_state(RunStatus::Stalled);
13292        stalled.config.graph.review_rounds = 1;
13293        stalled.reviews = vec![review_round(1)];
13294        assert!(!exhausted_review_budget(&stalled));
13295    }
13296
13297    fn review_round(round: usize) -> crate::run::ReviewRound {
13298        crate::run::ReviewRound {
13299            round,
13300            head: "deadbeef".to_owned(),
13301            verified_head: None,
13302            verified_at: None,
13303            reviews: Vec::new(),
13304            e2e: Vec::new(),
13305            verify_retried: false,
13306            e2e_deferred: false,
13307            e2e_defer_reason: None,
13308            fix: None,
13309            blocking: 0,
13310            answered: 1,
13311            expected: 1,
13312            clean: false,
13313            progressed: true,
13314            vote_split: false,
13315            reconsideration: Vec::new(),
13316            verdict: None,
13317        }
13318    }
13319
13320    #[test]
13321    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
13322        let mut run = RunState::new(
13323            PathBuf::from("/repo"),
13324            "main".to_owned(),
13325            "abc1234def".to_owned(),
13326            "add retries".to_owned(),
13327            Config::default(),
13328        );
13329        run.status = RunStatus::Judging;
13330        run.parked = true;
13331        let mut task = Task::new(
13332            "add retries".to_owned(),
13333            "add retries".to_owned(),
13334            PathBuf::from("/repo"),
13335            crate::queue::Source::Human,
13336        );
13337        task.status = TaskStatus::Failed;
13338        task.runs = vec![run.id.clone()];
13339        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
13340        assert!(with(&task, &run), "parked after judging is the case");
13341        let mut parked_task = task.clone();
13342        parked_task.status = TaskStatus::Parked;
13343        assert!(with(&parked_task, &run), "the Parked status is the case");
13344
13345        let mut not_parked = run.clone();
13346        not_parked.parked = false;
13347        not_parked.status = RunStatus::Stalled;
13348        assert!(!with(&task, &not_parked), "a stall is the conductor's");
13349
13350        let mut fresh = task.clone();
13351        fresh.fresh_start = true;
13352        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
13353
13354        let mut review = task.clone();
13355        review.review_branch = Some("magi/x/A".to_owned());
13356        assert!(!with(&review, &run), "review is ranked before resume");
13357
13358        let mut held = task.clone();
13359        held.status = TaskStatus::Held;
13360        assert!(!with(&held, &run), "a hold stays visible to the conductor");
13361
13362        let mut released = run.clone();
13363        released.released_to = Some("20260901-000000-new1".to_owned());
13364        assert!(!with(&task, &released), "nothing left to resume into");
13365
13366        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13367            "unreadable"
13368        )));
13369    }
13370
13371    #[test]
13372    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13373        let mut released = RunState::new(
13374            PathBuf::from("/repo"),
13375            "main".to_owned(),
13376            "abc1234def".to_owned(),
13377            "add retries".to_owned(),
13378            Config::default(),
13379        );
13380        released.status = RunStatus::Blocked;
13381        assert_eq!(
13382            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13383            Some(released.id.clone())
13384        );
13385        released.released_to = Some("20260901-000000-new1".to_owned());
13386        assert_eq!(
13387            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13388            None,
13389            "there is nothing left to resume it into"
13390        );
13391    }
13392
13393    #[test]
13394    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13395        // Mirrors the failure this exists to close: a task's last run ended
13396        // `Blocked` with the review budget spent, `crate::conduct` chose
13397        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
13398        // evidence), and without this check `attempt` would go on treating
13399        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
13400        // review loop iterates zero times over an already-spent budget, so
13401        // the resumed run settles right back to `Blocked` having asked nobody
13402        // anything, and `Requeue`'s promised fresh competition never happens.
13403        let mut exhausted = RunState::new(
13404            PathBuf::from("/repo"),
13405            "main".to_owned(),
13406            "abc1234def".to_owned(),
13407            "add retries".to_owned(),
13408            Config::default(),
13409        );
13410        exhausted.status = RunStatus::Blocked;
13411        exhausted.config.graph.review_rounds = 1;
13412        exhausted.reviews = vec![review_round(1)];
13413
13414        assert_eq!(
13415            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
13416            None,
13417            "an exhausted `Blocked` run must not be offered as resumable"
13418        );
13419
13420        // A `Blocked` run with rounds still unused is genuinely worth
13421        // resuming, and must still be found.
13422        let mut has_budget_left = RunState::new(
13423            PathBuf::from("/repo"),
13424            "main".to_owned(),
13425            "abc1234def".to_owned(),
13426            "add retries".to_owned(),
13427            Config::default(),
13428        );
13429        has_budget_left.status = RunStatus::Blocked;
13430        has_budget_left.config.graph.review_rounds = 3;
13431        has_budget_left.reviews = vec![review_round(1)];
13432
13433        assert_eq!(
13434            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
13435                Ok(has_budget_left.clone())
13436            }),
13437            Some(has_budget_left.id.clone())
13438        );
13439    }
13440
13441    #[test]
13442    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
13443        let mut run = RunState::new(
13444            PathBuf::from("/repo"),
13445            "main".to_owned(),
13446            "abc1234def".to_owned(),
13447            "add retries".to_owned(),
13448            Config::default(),
13449        );
13450        run.status = RunStatus::Blocked;
13451        run.config.graph.review_rounds = 1;
13452        run.reviews = vec![review_round(1)];
13453        run.pr_publication_pending = true;
13454        assert_eq!(
13455            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
13456            Some(run.id.clone()),
13457            "a spent review budget must not turn a failed publication into a re-competition"
13458        );
13459    }
13460
13461    #[test]
13462    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
13463        let mut task = Task::new(
13464            "recover work".into(),
13465            "recover work".into(),
13466            PathBuf::from("/repo"),
13467            crate::queue::Source::Human,
13468        );
13469        let mut history = std::collections::BTreeMap::new();
13470        for index in 0..8 {
13471            let mut run = run_state(RunStatus::Blocked);
13472            run.id = format!("20260101-000000-{index:04}");
13473            run.base_commit = format!("upstream-{index}");
13474            // Seven empty newer attempts must not erase the old recovery owner.
13475            if index > 0 {
13476                run.candidates.clear();
13477            }
13478            task.runs.extend([run.id.clone(), run.id.clone()]);
13479            history.insert(run.id.clone(), run);
13480            task.requeue();
13481        }
13482        let check = |task: &Task, starter: &Starter, limit| {
13483            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
13484        };
13485        assert!(
13486            check(&task, &Starter::Start, 8)
13487                .unwrap()
13488                .contains("8 unretired")
13489        );
13490        assert!(check(&task, &Starter::Start, 9).is_none());
13491        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13492        task.release_operator("owner", None);
13493        assert_eq!(task.attempts, 0);
13494        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13495        assert!(check(&restored, &Starter::Start, 8).is_some());
13496        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
13497        assert!(check(&restored, &Starter::Start, 0).is_none());
13498    }
13499
13500    #[test]
13501    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
13502        let tmp = tempfile::tempdir().unwrap();
13503        let mut task = Task::new(
13504            "recover selected PR".into(),
13505            "preserve implementation".into(),
13506            tmp.path().join("repo"),
13507            crate::queue::Source::Human,
13508        );
13509        let mut failed = run_state(RunStatus::Failed);
13510        failed.id = "20260101-000000-fail".into();
13511        failed.candidates.clear();
13512        failed.prep_complete = Some(false);
13513        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
13514        failed.startup = Some(crate::run::Startup {
13515            kind: "pr-recovery".into(),
13516            branch: Some("selected-public-head".into()),
13517            stage: "worktree-setup".into(),
13518            complete: false,
13519            failure: Some("setup modified a tracked file and failed".into()),
13520        });
13521        // Setup may fail before a candidate is recorded; its dirty worktree
13522        // still needs protection and consumes the independent retained bound.
13523        let worktree = failed.worktree_root().join("under-review");
13524        std::fs::create_dir_all(&worktree).unwrap();
13525        let retained_edit = worktree.join("implementation");
13526        std::fs::write(&retained_edit, "retained setup edit").unwrap();
13527        task.record_startup_failure(crate::run::StartupFailure {
13528            run: failed.id.clone(),
13529            stage: "worktree-setup".into(),
13530        });
13531        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13532        assert!(task.runs.is_empty() && task.passes.is_empty());
13533        assert_eq!(task.attempts, 0);
13534        let starter = Starter::Review("selected-public-head".into());
13535        assert!(
13536            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
13537                .unwrap()
13538                .contains("1 unretired")
13539        );
13540        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
13541        assert!(
13542            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
13543                .unwrap()
13544                .contains("Cannot verify")
13545        );
13546        // Older or mixed writers can link the same reservation in both lists.
13547        let mut mixed = task.clone();
13548        mixed.runs.push(failed.id.clone());
13549        mixed
13550            .startup_failures
13551            .push(task.startup_failures[0].clone());
13552        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
13553        failed.retired_to = Some("verified-recovery-owner".into());
13554        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
13555        assert!(
13556            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
13557                panic!("resuming the existing owner must not allocate a new attempt")
13558            })
13559            .is_none()
13560        );
13561        assert_eq!(
13562            std::fs::read_to_string(retained_edit).unwrap(),
13563            "retained setup edit"
13564        );
13565        assert!(task.runs.is_empty() && task.passes.is_empty());
13566        assert_eq!(task.attempts, 0);
13567    }
13568
13569    #[test]
13570    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
13571        let mut task = Task::new(
13572            "recover work".into(),
13573            "recover work".into(),
13574            PathBuf::from("/repo"),
13575            crate::queue::Source::Human,
13576        );
13577        let mut run = run_state(RunStatus::Superseded);
13578        run.candidates.clear();
13579        task.runs.push(run.id.clone());
13580        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
13581        run.retired_to = Some("authority".into());
13582        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13583        run.retired_to = None;
13584        run.released_to = Some("authority".into());
13585        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13586        assert!(
13587            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
13588                .unwrap()
13589                .contains("Cannot verify")
13590        );
13591        // Resuming an existing owner needs no new inventory or worktree budget.
13592        assert!(
13593            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
13594                panic!("resume must not load historical attempts")
13595            })
13596            .is_none()
13597        );
13598    }
13599
13600    #[test]
13601    fn retired_resume_requires_a_valid_same_repository_authority() {
13602        let mut source = run_state(RunStatus::Blocked);
13603        let mut empty = run_state(RunStatus::Blocked);
13604        empty.retired_to = Some(source.id.clone());
13605        let runs = vec![source.id.clone(), empty.id.clone()];
13606        let resolve = |source: &RunState, empty: &RunState| {
13607            unfinished_run_with(&runs, "fixture", |id| {
13608                if id == source.id {
13609                    Ok(source.clone())
13610                } else if id == empty.id {
13611                    Ok(empty.clone())
13612                } else {
13613                    bail!("unreadable authority")
13614                }
13615            })
13616        };
13617        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
13618        assert_eq!(
13619            choose_starter(None, false, resolve(&source, &empty).as_deref()),
13620            Starter::Resume(source.id.clone())
13621        );
13622        source.retired_to = Some(empty.id.clone());
13623        assert!(
13624            resolve(&source, &empty).is_none(),
13625            "cycles do not revive obsolete runs"
13626        );
13627        source.retired_to = None;
13628        source.repo = PathBuf::from("/another-repository");
13629        assert!(resolve(&source, &empty).is_none());
13630        source.repo = empty.repo.clone();
13631        source.released_to = Some("later".into());
13632        assert!(resolve(&source, &empty).is_none());
13633        empty.retired_to = Some("unlisted-run".into());
13634        assert!(resolve(&source, &empty).is_none());
13635    }
13636
13637    #[test]
13638    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
13639        // A task whose history holds an *older* run that still looks
13640        // resumable (say, a competition `Runner::review` was started
13641        // alongside after that older run went `Stalled`) and a *newest* run
13642        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
13643        // on this task must mean a fresh competition — falling back to the
13644        // stale, superseded `Stalled` run instead would resurrect history
13645        // nothing asked to revisit and silently defeat the requeue.
13646        let mut older_stalled = RunState::new(
13647            PathBuf::from("/repo"),
13648            "main".to_owned(),
13649            "abc1234def".to_owned(),
13650            "add retries".to_owned(),
13651            Config::default(),
13652        );
13653        older_stalled.status = RunStatus::Stalled;
13654
13655        let mut newest_exhausted = RunState::new(
13656            PathBuf::from("/repo"),
13657            "main".to_owned(),
13658            "abc1234def".to_owned(),
13659            "add retries".to_owned(),
13660            Config::default(),
13661        );
13662        newest_exhausted.status = RunStatus::Blocked;
13663        newest_exhausted.config.graph.review_rounds = 1;
13664        newest_exhausted.reviews = vec![review_round(1)];
13665
13666        assert_eq!(
13667            unfinished_run_with(
13668                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
13669                "t",
13670                |_| Ok(newest_exhausted.clone())
13671            ),
13672            None,
13673            "the newest run is exhausted, so nothing here is worth resuming - \
13674             least of all the older, already-superseded run"
13675        );
13676    }
13677
13678    #[test]
13679    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
13680        assert_eq!(
13681            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
13682                Err(anyhow::anyhow!("fixture is absent"))
13683            }),
13684            None
13685        );
13686    }
13687
13688    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
13689        let mut q = ask::Question::new(
13690            run.to_owned(),
13691            "implement".to_owned(),
13692            "impl-A".to_owned(),
13693            "continue?".to_owned(),
13694            String::new(),
13695            vec!["resume で続行する".to_owned(), "other".to_owned()],
13696        );
13697        q.actions.insert("resume で続行する".to_owned(), action);
13698        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
13699            .unwrap();
13700        q
13701    }
13702
13703    fn held_task_with(run: &str) -> Task {
13704        let mut t = task();
13705        t.runs = vec![run.to_owned()];
13706        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
13707        t
13708    }
13709
13710    fn resume_action(run: &str) -> ask::ChoiceAction {
13711        ask::ChoiceAction::Resume { run: run.into() }
13712    }
13713
13714    #[test]
13715    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
13716        let home = crate::run::test_home();
13717        for parked in [false, true] {
13718            let mut t = task();
13719            t.start("A".into());
13720            t.start("B".into());
13721            assert_eq!(t.runs, vec!["A", "B"]);
13722            t.start("A".into());
13723            let mut resumed = run_state(RunStatus::Blocked);
13724            resumed.id = "A".into();
13725            resumed.parked = parked;
13726            resumed.driver_exited = true;
13727            t.hold_machine(Some("resumed run stopped".into()));
13728            let q = action_question("A", resume_action("A"));
13729            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13730            assert_eq!(
13731                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
13732                    assert_eq!(id, "A");
13733                    Ok(resumed.clone())
13734                }),
13735                ActionDecision::Resume("A".into())
13736            );
13737            assert_eq!(
13738                action_standing(&t, &action_question("B", resume_action("B"))),
13739                ActionStanding::Stale
13740            );
13741            t.release_operator("cli", None);
13742            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
13743                assert_eq!(id, "A");
13744                Ok(resumed.clone())
13745            });
13746            assert_eq!(
13747                choose_starter(None, false, unfinished.as_deref()),
13748                Starter::Resume("A".into())
13749            );
13750            assert_eq!(t.runs, vec!["B", "A"]);
13751        }
13752    }
13753
13754    #[test]
13755    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
13756        let home = crate::run::test_home();
13757        let mut state = crate::land::tests::repair_state(true, true);
13758        state.status = RunStatus::Landing;
13759        state.parked = true;
13760        state.driver_exited = true;
13761        let mut q = ask::Question::new(
13762            state.id.clone(),
13763            land::APPROVAL_NODE.into(),
13764            "land".into(),
13765            "Merge?".into(),
13766            String::new(),
13767            vec![land::APPROVE.into(), land::HOLD.into()],
13768        );
13769        q.id = state.id.clone();
13770        state.land_approval = Some(crate::run::LandApproval {
13771            question: q.id.clone(),
13772            head: "current-head".into(),
13773        });
13774        assert!(land::upgrade_repair_choice(&mut q, &state));
13775        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13776        let mut task = held_task_with(&state.id);
13777        task.status = TaskStatus::Parked;
13778        assert_eq!(
13779            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13780            ActionDecision::Resume(state.id.clone())
13781        );
13782        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13783        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
13784        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
13785        assert_eq!(
13786            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13787            ActionDecision::Resume(state.id.clone()),
13788            "a repair answer newer than the manual hold resumes the existing owner"
13789        );
13790        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13791        for answered_at in [q.answered_at, None] {
13792            let mut older = q.clone();
13793            older.answered_at = answered_at;
13794            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
13795                panic!("a later manual hold must prevent dispatch")
13796            });
13797            let ActionDecision::Refuse(reason) = refused else {
13798                panic!("expected an actionable refusal, got {refused:?}");
13799            };
13800            assert!(reason.contains("later operator decision"));
13801            assert!(reason.contains(&format!("magi task release {}", task.id)));
13802        }
13803        task.operator_decided_at = None;
13804        let mut superseded = state.clone();
13805        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
13806        assert_eq!(
13807            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
13808            ActionDecision::Stale
13809        );
13810        for case in 1..4 {
13811            let mut changed = state.clone();
13812            match case {
13813                1 => changed.status = RunStatus::Blocked,
13814                2 => changed.released_to = Some("new-owner".into()),
13815                _ => changed.land_approval.as_mut().unwrap().head.clear(),
13816            }
13817            assert!(matches!(
13818                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
13819                ActionDecision::Refuse(_)
13820            ));
13821        }
13822        assert!(matches!(
13823            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
13824                "missing owner"
13825            )),
13826            ActionDecision::Refuse(_)
13827        ));
13828        task.runs.push("replacement".into());
13829        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13830        assert_eq!(
13831            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
13832                "old owner must not load"
13833            )),
13834            ActionDecision::Stale
13835        );
13836    }
13837
13838    #[test]
13839    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
13840        let mut state = crate::land::tests::repair_state(true, true);
13841        state.status = RunStatus::Landing;
13842        state.parked = true;
13843        state.driver_exited = true;
13844        let mut q = ask::Question::new(
13845            state.id.clone(),
13846            land::APPROVAL_NODE.into(),
13847            "land".into(),
13848            "Merge?".into(),
13849            String::new(),
13850            vec![land::APPROVE.into(), land::HOLD.into()],
13851        );
13852        q.id = state.id.clone();
13853        state.land_approval = Some(crate::run::LandApproval {
13854            question: q.id.clone(),
13855            head: "current-head".into(),
13856        });
13857        state.save().unwrap();
13858        land::upgrade_repair_choice(&mut q, &state);
13859        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13860        Questions::open().put(&mut q).unwrap();
13861        let tmp = tempfile::tempdir().unwrap();
13862        let queue = Queue::at(tmp.path().join("queue"));
13863        let mut task = held_task_with(&state.id);
13864        task.status = TaskStatus::Parked;
13865        queue.put(&mut task).unwrap();
13866        let empty = Arc::new(tokio::sync::Semaphore::new(0));
13867        let free = Arc::new(tokio::sync::Semaphore::new(1));
13868        assert!(matches!(
13869            claim_dispatch(&queue, &task, false, &empty, &free),
13870            Err(SkipReason::OrdinaryCapacity)
13871        ));
13872        assert!(matches!(
13873            claim_dispatch(&queue, &task, true, &free, &free),
13874            Err(SkipReason::CoolingDown)
13875        ));
13876        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
13877        assert!(claim.permit.is_some());
13878        assert!(matches!(
13879            claim_dispatch(&queue, &task, false, &free, &free),
13880            Err(SkipReason::ClaimUnavailable)
13881        ));
13882        drop(claim);
13883        Questions::open()
13884            .update(&q.id, |q| {
13885                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
13886                Ok(())
13887            })
13888            .unwrap();
13889        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
13890        assert!(claim.permit.is_none());
13891        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
13892    }
13893
13894    #[test]
13895    fn decide_action_resumes_only_the_latest_resumable_run() {
13896        let home = crate::run::test_home();
13897        let t = held_task_with("r1");
13898        let q = action_question("r1", resume_action("r1"));
13899        let load = |s: RunState| move |_: &str| Ok(s);
13900        assert_eq!(
13901            decide_action(
13902                &home,
13903                &t,
13904                &q,
13905                &PHRASES_EN,
13906                load(run_state(RunStatus::Blocked))
13907            ),
13908            ActionDecision::Resume("r1".into())
13909        );
13910        // Not the latest run of the task.
13911        let q_other = action_question("r1", resume_action("r0"));
13912        assert!(matches!(
13913            decide_action(
13914                &home,
13915                &t,
13916                &q_other,
13917                &PHRASES_EN,
13918                load(run_state(RunStatus::Blocked))
13919            ),
13920            ActionDecision::Refuse(_)
13921        ));
13922        // A finished run cannot make progress.
13923        assert!(matches!(
13924            decide_action(
13925                &home,
13926                &t,
13927                &q,
13928                &PHRASES_EN,
13929                load(run_state(RunStatus::Ready))
13930            ),
13931            ActionDecision::Refuse(_)
13932        ));
13933        // A released one either.
13934        let mut released = run_state(RunStatus::Blocked);
13935        released.released_to = Some("elsewhere".into());
13936        assert!(matches!(
13937            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13938            ActionDecision::Refuse(_)
13939        ));
13940        // Unreadable state is a refusal, never a fresh competition.
13941        assert!(matches!(
13942            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13943            ActionDecision::Refuse(_)
13944        ));
13945    }
13946
13947    #[test]
13948    fn decide_action_ignores_a_question_about_an_earlier_run() {
13949        let home = crate::run::test_home();
13950        let mut t = held_task_with("r1");
13951        t.runs.push("r2".to_owned());
13952        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13953        assert_eq!(
13954            decide_action(
13955                &home,
13956                &t,
13957                &action_question("r1", ask::ChoiceAction::Done),
13958                &PHRASES_EN,
13959                never
13960            ),
13961            ActionDecision::Stale
13962        );
13963    }
13964
13965    #[test]
13966    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13967        let home = crate::run::test_home();
13968        let mut t = held_task_with("r1");
13969        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13970        assert_eq!(
13971            decide_action(
13972                &home,
13973                &t,
13974                &action_question("r1", ask::ChoiceAction::Requeue),
13975                &PHRASES_EN,
13976                never
13977            ),
13978            ActionDecision::Requeue
13979        );
13980        let done_q = action_question("r1", ask::ChoiceAction::Done);
13981        assert_eq!(
13982            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13983            ActionDecision::Done
13984        );
13985        t.mark_action_applied(&done_q.id);
13986        assert_eq!(
13987            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13988            ActionDecision::Skip
13989        );
13990
13991        // A plain answer (no action for that label) does nothing.
13992        let mut plain = action_question("r1", ask::ChoiceAction::Done);
13993        plain.actions.clear();
13994        assert_eq!(
13995            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13996            ActionDecision::Skip
13997        );
13998        // A running task is left alone.
13999        let mut running = held_task_with("r1");
14000        running.status = TaskStatus::Running;
14001        assert_eq!(
14002            decide_action(
14003                &home,
14004                &running,
14005                &action_question("r1", ask::ChoiceAction::Done),
14006                &PHRASES_EN,
14007                never
14008            ),
14009            ActionDecision::Skip
14010        );
14011    }
14012
14013    #[test]
14014    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14015        crate::run::pin_test_home();
14016        for legacy in [false, true] {
14017            let dir = tempfile::tempdir().unwrap();
14018            let queue = Queue::at(dir.path().join("queue"));
14019            let questions = Questions::at(dir.path().join("questions"));
14020            let run = "20260101-000000-hold";
14021            let mut task = held_task_with(run);
14022            task.status = TaskStatus::Parked;
14023            let mut q = ask::Question::new(
14024                run.into(),
14025                land::APPROVAL_NODE.into(),
14026                "land".into(),
14027                "Repair?".into(),
14028                String::new(),
14029                vec![land::REPAIR.into()],
14030            );
14031            q.actions.insert(land::REPAIR.into(), resume_action(run));
14032            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14033            // Deterministically order the answer before the actual manual hold.
14034            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14035            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14036            questions.put(&mut q).unwrap();
14037            task.hold_manual(Some("Keep this PR paused".into()));
14038            if legacy {
14039                task.hold_source = None;
14040            }
14041            queue.put(&mut task).unwrap();
14042
14043            apply_task_choice_actions(&queue, &questions, dir.path());
14044            let after = queue.get(&task.id).unwrap();
14045            assert!(after.operator_held());
14046            assert_eq!(after.hold_source, task.hold_source);
14047            assert_eq!(after.operator_decided_at, task.operator_decided_at);
14048            assert_eq!(after.runs, task.runs);
14049            assert_eq!(after.instruction, task.instruction);
14050            assert!(after.resume_override.is_none());
14051            assert!(after.action_applied(&q.id));
14052            let reason = after.hold_reason.as_deref().unwrap();
14053            assert!(reason.starts_with("Keep this PR paused"));
14054            assert!(reason.contains("later operator decision"));
14055            assert!(reason.contains(&format!("magi task release {}", task.id)));
14056
14057            for recovery in [
14058                crate::conduct::Recovery::Review,
14059                crate::conduct::Recovery::Requeue,
14060            ] {
14061                crate::conduct::apply(
14062                    &queue,
14063                    &questions,
14064                    &crate::conduct::Verdict {
14065                        decisions: vec![crate::conduct::Decision {
14066                            id: task.id.clone(),
14067                            recovery: Some(recovery),
14068                            ..Default::default()
14069                        }],
14070                    },
14071                )
14072                .unwrap();
14073            }
14074            // Reconciliation is idempotent, and automatic recovery cannot
14075            // reopen this owner after it observes the rejected repair answer.
14076            apply_task_choice_actions(&queue, &questions, dir.path());
14077            let still_held = queue.get(&task.id).unwrap();
14078            assert!(still_held.operator_held());
14079            assert_eq!(still_held.hold_reason, after.hold_reason);
14080            assert_eq!(still_held.runs, task.runs);
14081            assert!(still_held.review_branch.is_none());
14082            assert!(!still_held.fresh_start);
14083            assert!(queue.next_runnable().is_none());
14084        }
14085    }
14086
14087    #[test]
14088    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14089        for held in [false, true] {
14090            for retry in [false, true] {
14091                let dir = tempfile::tempdir().unwrap();
14092                let queue = Queue::at(dir.path().join("queue"));
14093                let questions = Questions::at(dir.path().join("questions"));
14094                let home = dir.path().join("home");
14095                let mut t = task();
14096                if held {
14097                    t.hold_machine(Some("driver state unknown".into()));
14098                }
14099                queue.put(&mut t).unwrap();
14100                let verdict = serde_json::from_value(serde_json::json!({
14101                    "decisions": [{
14102                        "id": t.id,
14103                        "question": "Driver state unknown; retry the checks or hold?",
14104                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14105                        "actions": {
14106                            "daemon: recheck and retry": {"do": "requeue"},
14107                            "daemon: hold the task": {"do": "hold"}
14108                        }
14109                    }]
14110                }))
14111                .unwrap();
14112                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14113                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14114                let mut q = questions.list().pop().unwrap();
14115                let choice = if retry {
14116                    "daemon: recheck and retry"
14117                } else {
14118                    "daemon: hold the task"
14119                };
14120                assert_eq!(q.actions.len(), 2);
14121                q.answer(ask::Answer::Choice(choice.into())).unwrap();
14122                questions.put(&mut q).unwrap();
14123
14124                // A Web answer does not remove the deputy's fresh lease.
14125                questions.beat(&q.id, ask::WaiterKind::Deputy);
14126                for _ in 0..2 {
14127                    resolve_blockers(&queue, &questions);
14128                    apply_task_choice_actions(&queue, &questions, &home);
14129                    let waiting = queue.get(&t.id).unwrap();
14130                    assert_eq!(waiting.status, TaskStatus::Blocked);
14131                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
14132                    assert!(waiting.answers.is_empty());
14133                    assert!(!waiting.action_applied(&q.id));
14134                    assert!(runnable(&queue).is_empty());
14135                    let free = Arc::new(tokio::sync::Semaphore::new(1));
14136                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14137                }
14138                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14139
14140                // Releasing the blocker and applying the operation share one save.
14141                resolve_blockers(&queue, &questions);
14142                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14143                apply_task_choice_actions(&queue, &questions, &home);
14144                let after = queue.get(&t.id).unwrap();
14145                assert_eq!(
14146                    after.status,
14147                    if retry {
14148                        TaskStatus::Queued
14149                    } else {
14150                        TaskStatus::Held
14151                    }
14152                );
14153                assert!(after.action_applied(&q.id));
14154                assert_eq!(after.operator_held(), !retry);
14155                assert_eq!(after.answers.len(), 1);
14156
14157                // A later operator decision must not replay this answer.
14158                let mut changed = after;
14159                if retry {
14160                    changed.hold_manual(Some("later hold".into()));
14161                } else {
14162                    changed.release_operator("test", None);
14163                }
14164                let expected = changed.status;
14165                queue.put(&mut changed).unwrap();
14166                apply_task_choice_actions(&queue, &questions, &home);
14167                assert_eq!(queue.get(&t.id).unwrap().status, expected);
14168            }
14169        }
14170    }
14171
14172    #[test]
14173    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14174        let dir = tempfile::tempdir().unwrap();
14175        let queue = Queue::at(dir.path().join("queue"));
14176        let questions = Questions::at(dir.path().join("questions"));
14177        let home = dir.path().join("home");
14178        let mut state = run_state(RunStatus::Blocked);
14179        state.id = "20260101-000000-act1".to_owned();
14180        state.save_under(&home).unwrap();
14181
14182        let mut t = held_task_with(&state.id);
14183        queue.put(&mut t).unwrap();
14184        let mut q = action_question(&state.id, resume_action(&state.id));
14185        questions.put(&mut q).unwrap();
14186
14187        apply_task_choice_actions(&queue, &questions, &home);
14188        let after = queue.get(&t.id).unwrap();
14189        assert_eq!(after.status, TaskStatus::Queued);
14190        assert!(!after.fresh_start);
14191        assert!(after.action_applied(&q.id));
14192        let pin = after.resume_override.clone().unwrap();
14193        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14194        assert!(pin.forced);
14195
14196        // Held again later: the same answer does not release it a second time.
14197        let mut again = queue.get(&t.id).unwrap();
14198        again.hold_machine(Some("later".into()));
14199        queue.put(&mut again).unwrap();
14200        apply_task_choice_actions(&queue, &questions, &home);
14201        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14202    }
14203
14204    #[test]
14205    fn a_delivered_answer_is_still_acted_on_exactly_once() {
14206        let dir = tempfile::tempdir().unwrap();
14207        let queue = Queue::at(dir.path().join("queue"));
14208        let questions = Questions::at(dir.path().join("questions"));
14209        let home = dir.path().join("home");
14210        let mut state = run_state(RunStatus::Blocked);
14211        state.id = "20260101-000000-act2".to_owned();
14212        state.save_under(&home).unwrap();
14213
14214        let mut t = held_task_with(&state.id);
14215        queue.put(&mut t).unwrap();
14216        let mut q = action_question(&state.id, resume_action(&state.id));
14217        q.answer_delivered = true;
14218        questions.put(&mut q).unwrap();
14219
14220        // Delivered, and the agent then died: the task is still held, so the
14221        // chosen action applies.
14222        apply_task_choice_actions(&queue, &questions, &home);
14223        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14224        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14225
14226        // Held again: the same answer does nothing a second time.
14227        let mut again = queue.get(&t.id).unwrap();
14228        again.hold_machine(Some("later".into()));
14229        queue.put(&mut again).unwrap();
14230        apply_task_choice_actions(&queue, &questions, &home);
14231        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14232    }
14233
14234    #[test]
14235    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14236        let dir = tempfile::tempdir().unwrap();
14237        let queue = Queue::at(dir.path().join("queue"));
14238        let questions = Questions::at(dir.path().join("questions"));
14239        let home = dir.path().join("home");
14240        let mut state = run_state(RunStatus::Blocked);
14241        state.id = "20260101-000000-act3".to_owned();
14242        state.save_under(&home).unwrap();
14243        let mut t = held_task_with(&state.id);
14244        queue.put(&mut t).unwrap();
14245        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
14246        questions.put(&mut q).unwrap();
14247
14248        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
14249        apply_task_choice_actions(&queue, &questions, &home);
14250        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14251
14252        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14253        apply_task_choice_actions(&queue, &questions, &home);
14254        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14255    }
14256
14257    #[test]
14258    fn action_standing_tells_the_reasons_apart() {
14259        let mut t = held_task_with("r1");
14260        let q = action_question("r1", ask::ChoiceAction::Requeue);
14261        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14262        let mut plain = q.clone();
14263        plain.actions.clear();
14264        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
14265
14266        // Applied wins over everything, even a running task.
14267        t.mark_action_applied(&q.id);
14268        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
14269
14270        // A newer attempt running: the old question is Stale, not Busy.
14271        let mut t = held_task_with("r1");
14272        t.start("r2".to_owned());
14273        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
14274        // The same question about the latest run just waits.
14275        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
14276        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14277        t.status = TaskStatus::Blocked;
14278        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14279
14280        // A conductor question is keyed by the task, never stale.
14281        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
14282        c.node = crate::conduct::NODE.to_owned();
14283        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
14284        assert!(!ActionStanding::Busy.daemon_owns());
14285    }
14286
14287    #[test]
14288    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
14289        let dir = tempfile::tempdir().unwrap();
14290        let queue = Queue::at(dir.path().join("queue"));
14291        let questions = Questions::at(dir.path().join("questions"));
14292        let home = dir.path().join("home");
14293        let mut state = run_state(RunStatus::Blocked);
14294        state.id = "20260101-000000-act4".to_owned();
14295        state.save_under(&home).unwrap();
14296        let mut t = held_task_with(&state.id);
14297        t.status = TaskStatus::Running;
14298        queue.put(&mut t).unwrap();
14299        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
14300        q.cwd = Some(dir.path().display().to_string());
14301        questions.put(&mut q).unwrap();
14302
14303        // While the task runs the daemon will not act, so the waiter still
14304        // delivers the word to the dead asker's seat ...
14305        let running = queue.get(&t.id).unwrap();
14306        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
14307        assert!(matches!(
14308            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
14309            crate::waiter::Action::Deliver(_)
14310        ));
14311        // ... and the daemon waits while the task runs, then applies once.
14312        apply_task_choice_actions(&queue, &questions, &home);
14313        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14314        let mut back = queue.get(&t.id).unwrap();
14315        back.hold_machine(Some("later".into()));
14316        queue.put(&mut back).unwrap();
14317        apply_task_choice_actions(&queue, &questions, &home);
14318        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
14319        let mut again = queue.get(&t.id).unwrap();
14320        again.hold_machine(Some("again".into()));
14321        queue.put(&mut again).unwrap();
14322        apply_task_choice_actions(&queue, &questions, &home);
14323        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14324    }
14325}