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        "cache" => CACHE_CHECK_INTERVAL_SECS,
3795        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3796        _ => opts.poll.as_secs().max(1),
3797    };
3798    let now = Timestamp::now();
3799    if !cache_check_due(last, now, interval) {
3800        retention_service_receipt(
3801            home,
3802            operation,
3803            "dispatch",
3804            "skipped",
3805            "cadence not due",
3806            cfg,
3807        );
3808        return Ok(());
3809    }
3810    let key = format!("service:daemon-{operation}");
3811    if crate::worker::active(home)?
3812        .iter()
3813        .any(|job| job.key == key)
3814    {
3815        retention_service_receipt(
3816            home,
3817            operation,
3818            "dispatch",
3819            "skipped",
3820            "service worker already active",
3821            cfg,
3822        );
3823        return Ok(());
3824    }
3825    let eligible = match operation {
3826        "conductor" => {
3827            let (queued, stalled, finished) = conductor_work(queue, home);
3828            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3829                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3830        }
3831        "maintenance" => {
3832            queue.list().iter().any(|task| {
3833                crate::triage::disk_wait_eligible(task)
3834                    && task
3835                        .disk_checked_at
3836                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3837            }) || Questions::at(home.join("questions"))
3838                .list_for_effects()
3839                .iter()
3840                .any(|q| {
3841                    q.chosen_action().is_some_and(|action| action.maintenance())
3842                        && !home
3843                            .join("choice-actions")
3844                            .join(format!("{}.json", q.id))
3845                            .exists()
3846                })
3847        }
3848        "housekeeping" => !busy && runnable(queue).is_empty(),
3849        "cache" => {
3850            !busy
3851                && !runnable(queue).is_empty()
3852                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3853        }
3854        "disk-pressure" => busy,
3855        "fetch" => {
3856            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3857        }
3858        _ => false,
3859    };
3860    if !eligible {
3861        retention_service_receipt(
3862            home,
3863            operation,
3864            "dispatch",
3865            "skipped",
3866            if operation == "housekeeping" {
3867                "active work or runnable task queue"
3868            } else {
3869                "no active work; idle housekeeping owns scan"
3870            },
3871            cfg,
3872        );
3873        return Ok(());
3874    }
3875    retention_service_receipt(
3876        home,
3877        operation,
3878        "dispatch",
3879        "launching",
3880        "eligible and cadence due",
3881        cfg,
3882    );
3883    let request = ServiceWorker {
3884        opts: opts.absolute()?,
3885        queue: std::path::absolute(queue.root())?,
3886        worktrees_root: std::path::absolute(worktrees_root)?,
3887        operation: operation.to_owned(),
3888    };
3889    if let Err(error) =
3890        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3891    {
3892        retention_service_receipt(
3893            home,
3894            operation,
3895            "dispatch",
3896            "error",
3897            &format!("worker launch: {error:#}"),
3898            cfg,
3899        );
3900        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3901    }
3902    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3903    Ok(())
3904}
3905
3906/// Finite maintenance jobs survive scheduler replacement without duplicating
3907/// agent calls or cancelling an operation between its effect and receipt.
3908pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3909    let request: ServiceWorker = serde_json::from_value(payload)?;
3910    let opts = &request.opts;
3911    let queue = Queue::at(request.queue);
3912    let questions = Questions::at(home.join("questions"));
3913    match request.operation.as_str() {
3914        "maintenance" => {
3915            apply_maintenance_choices(&queue, &questions, home).await;
3916            triage::monitor_disk_waits(
3917                &queue,
3918                &questions,
3919                opts.config.as_deref(),
3920                Timestamp::now(),
3921            );
3922        }
3923        "conductor" => {
3924            let path = home.join("conductor-state.json");
3925            let mut conductor = load_conductor(home)?;
3926            let (queued, stalled, finished) = conductor_work(&queue, home);
3927            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3928                && conductor.worth_a_look(&queue, &stalled, &finished)
3929            {
3930                let cfg = prepare(&opts.repo, opts)?;
3931                conductor
3932                    .maybe_run(
3933                        &cfg,
3934                        &opts.repo,
3935                        &queue,
3936                        &questions,
3937                        home,
3938                        &queued,
3939                        &stalled,
3940                        &finished,
3941                        opts.max_attempts,
3942                    )
3943                    .await;
3944                let temporary = path.with_extension("json.tmp");
3945                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3946                std::fs::rename(temporary, path)?;
3947            }
3948        }
3949        "fetch" => {
3950            let cfg = prepare(&opts.repo, opts)?;
3951            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3952                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3953                tracing::debug!("fetch origins: {outcome:?}");
3954            }
3955        }
3956        "cache" => {
3957            if task_jobs(home)?.is_empty() {
3958                let mut checked = None;
3959                maybe_prune_cache_between_runs(
3960                    &opts.repo,
3961                    opts,
3962                    home,
3963                    &Stop::new(),
3964                    &mut checked,
3965                    Timestamp::now(),
3966                )
3967                .await;
3968            }
3969        }
3970        "disk-pressure" => {
3971            if let Ok(cfg) = prepare(&opts.repo, opts) {
3972                retention_service_receipt(
3973                    home,
3974                    "disk-pressure",
3975                    "worker",
3976                    "running",
3977                    "retention sweep",
3978                    Some(&cfg),
3979                );
3980                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3981                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3982                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3983                }
3984                for current in current_work(home, Timestamp::now()) {
3985                    if let Ok(state) = RunState::load_under(&current.run, home)
3986                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3987                    {
3988                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3989                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3990                        }) {
3991                            request_task_park(
3992                                home,
3993                                &job,
3994                                crate::run::ParkCause::Interrupt {
3995                                    reason: reason.clone(),
3996                                },
3997                            )?;
3998                        }
3999                        notices::raise_in(
4000                            home,
4001                            Notice::warn(
4002                                "disk:pressure",
4003                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4004                            ),
4005                        );
4006                    }
4007                }
4008            } else {
4009                retention_service_receipt(
4010                    home,
4011                    "disk-pressure",
4012                    "worker",
4013                    "error",
4014                    "configuration could not be loaded",
4015                    None,
4016                );
4017            }
4018        }
4019        "housekeeping" => {
4020            if task_jobs(home)?.is_empty() {
4021                match prepare(&opts.repo, opts) {
4022                    Ok(cfg) => {
4023                        retention_service_receipt(
4024                            home,
4025                            "housekeeping",
4026                            "worker",
4027                            "running",
4028                            "retention sweep",
4029                            Some(&cfg),
4030                        );
4031                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4032                    }
4033                    Err(error) => retention_service_receipt(
4034                        home,
4035                        "housekeeping",
4036                        "worker",
4037                        "error",
4038                        &format!("configuration: {error:#}"),
4039                        None,
4040                    ),
4041                }
4042                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4043                resweep_superseded_attempts(&queue, home);
4044                triage_held(&queue, home, opts).await;
4045            } else {
4046                retention_service_receipt(
4047                    home,
4048                    "housekeeping",
4049                    "worker",
4050                    "skipped",
4051                    "task worker became active",
4052                    None,
4053                );
4054            }
4055        }
4056        operation => bail!("unknown daemon service {operation}"),
4057    }
4058    Ok(())
4059}
4060
4061/// Only a different request under the same key is a dispatch handoff race.
4062/// Our own unacknowledged reservation is a startup failure, not competing work:
4063/// stop dispatch without fencing it, so an already detached child may still run.
4064fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4065    let key = format!("task:{}", request.task);
4066    let payload = serde_json::to_value(request)?;
4067    if crate::worker::active(home)?
4068        .iter()
4069        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4070    {
4071        tracing::warn!(
4072            "task {} acquired a competing worker reservation: {error:#}",
4073            crate::run::short_of(&request.task)
4074        );
4075        return Ok(());
4076    }
4077    tracing::error!("task worker startup stopped dispatch: {error:#}");
4078    notices::raise_in(
4079        home,
4080        Notice::error(
4081            "loop:worker-startup",
4082            // Startup diagnostics may contain private child-process details;
4083            // keep them in the local error/log rather than the chat or notifier.
4084            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),
4085        ).link(Link::Task { id: request.task.clone() }),
4086    );
4087    Err(error).with_context(|| {
4088        format!(
4089            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4090            crate::run::short_of(&request.task)
4091        )
4092    })
4093}
4094
4095async fn poll(
4096    opts: &Opts,
4097    queue: &Queue,
4098    status: &Arc<Mutex<Status>>,
4099    home: &Path,
4100    worktrees_root: &Path,
4101    stop: &Stop,
4102    limits: DispatchLimits,
4103) -> Result<()> {
4104    let mut attempted = Vec::new();
4105    let mut settling_once_services = false;
4106    let interrupt_path = home.join("scheduler-interrupt.json");
4107    let mut interrupt = match std::fs::read(&interrupt_path) {
4108        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4109        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4110        Err(error) => return Err(error.into()),
4111    };
4112    let mut previous = std::collections::BTreeSet::<String>::new();
4113    let mut previous_skips = DispatchSkips::new();
4114    while !stop.stopped() {
4115        let jobs: Vec<_> = crate::worker::active(home)?
4116            .into_iter()
4117            .filter(|job| job.kind == "task")
4118            .collect();
4119        let requests: Vec<_> = jobs
4120            .iter()
4121            .map(|job| {
4122                serde_json::from_value::<TaskWorker>(job.payload.clone())
4123                    .with_context(|| format!("read live task worker {}", job.id))
4124            })
4125            .collect::<Result<_>>()?;
4126        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4127        let owned: std::collections::BTreeSet<_> = requests
4128            .iter()
4129            .filter(|r| !r.standalone)
4130            .map(|r| r.task.clone())
4131            .collect();
4132        let current: Vec<_> = requests
4133            .iter()
4134            .zip(&jobs)
4135            .filter(|(request, _)| !request.standalone)
4136            .map(|(request, job)| Current {
4137                worker: Some(job.id.clone()),
4138                task: request.task.clone(),
4139                run: queue
4140                    .get(&request.task)
4141                    .ok()
4142                    .and_then(|task| task.execution_runs().last().cloned())
4143                    .unwrap_or_default(),
4144            })
4145            .collect();
4146        {
4147            let mut snapshot = lock(status);
4148            snapshot.polls += 1;
4149            snapshot.completed += previous.difference(&owned).count();
4150            snapshot.current = current;
4151            snapshot.idle = owned.is_empty();
4152            snapshot.dispatch_wait = None;
4153        }
4154        previous = owned.clone();
4155        stop.busy.store(owned.len(), Ordering::SeqCst);
4156
4157        // Slots are reconstructed from durable reservations and OS-held worker
4158        // leases, not this scheduler's lifetime or mutable task urgency.
4159        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4160        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4161        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4162        let mut permits = Vec::new();
4163        sweep_stale_claims(queue, STALE_CLAIM);
4164        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4165        reclaim_abandoned_runs(home, Timestamp::now());
4166        let questions = Questions::at(home.join("questions"));
4167
4168        // Deterministic: no model, run before the conductor sees anything so
4169        // its input reflects the queue's current, already-resolved state.
4170        crate::task_chat::sweep(
4171            queue,
4172            &crate::talk::Talks::at(home.join("talks")),
4173            &questions,
4174            home,
4175        );
4176        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4177            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4178        {
4179            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4180        }
4181        repair_choice_offers(&questions);
4182        resolve_blockers(queue, &questions);
4183        apply_task_choice_actions(queue, &questions, home);
4184        triage::apply_answers(queue, &questions);
4185        reconcile_task_questions(queue, &questions);
4186        let talks = crate::talk::Talks::at(home.join("talks"));
4187        crate::chat_notify::sweep(queue, &talks, home);
4188        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4189        crate::chat_watch::sweep(home, &talks);
4190        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4191            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4192        }
4193        let mut turns = tokio::task::JoinSet::new();
4194        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4195        // start_turns dispatches detached turns; no paid work lives in this set.
4196        while turns.join_next().await.is_some() {}
4197
4198        crate::consult::start_services(
4199            home,
4200            &opts.repo,
4201            limits.recovery_cfg.as_ref(),
4202            opts.config.as_deref(),
4203        )
4204        .await?;
4205        for operation in [
4206            "conductor",
4207            "maintenance",
4208            "housekeeping",
4209            "disk-pressure",
4210            "cache",
4211            "fetch",
4212        ] {
4213            // Once an idle --once drain starts settling services, subsequent
4214            // scans only consume their effects. An expired cadence receipt
4215            // must not start another service and keep the drain alive.
4216            if settling_once_services {
4217                break;
4218            }
4219            start_service(
4220                home,
4221                opts,
4222                queue,
4223                worktrees_root,
4224                operation,
4225                limits.recovery_cfg.as_ref(),
4226                !live.is_empty(),
4227            )
4228            .await?;
4229        }
4230        let latest = crate::worker::active(home)?;
4231        if latest.iter().any(|job| job.key == "service:daemon-cache")
4232            || latest
4233                .iter()
4234                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4235        {
4236            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4237            continue;
4238        }
4239        let candidates: Vec<Task> = runnable(queue)
4240            .into_iter()
4241            .filter(|task| !live.contains(&task.id))
4242            .filter(|task| !opts.once || !attempted.contains(&task.id))
4243            .collect();
4244        let in_flight: Vec<_> = owned.iter().cloned().collect();
4245        let prior_interrupt = std::mem::discriminant(&interrupt);
4246        interrupt = advance_interrupt_tick(
4247            limits.pause_for_interrupts,
4248            interrupt,
4249            &in_flight,
4250            &candidates,
4251        );
4252        // Same-variant transitions preserve their identities. Only an actual
4253        // transition needs a durable write, atomically before sending controls.
4254        if prior_interrupt != std::mem::discriminant(&interrupt) {
4255            let temporary = interrupt_path.with_extension("json.tmp");
4256            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4257            std::fs::rename(temporary, &interrupt_path)?;
4258        }
4259        if let Interrupt::Parking {
4260            parked,
4261            interrupt_task,
4262        } = &interrupt
4263        {
4264            for job in jobs.iter().filter(|job| {
4265                parked
4266                    .iter()
4267                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4268            }) {
4269                if crate::worker::control(home, &job.key)?.is_none() {
4270                    request_task_park(
4271                        home,
4272                        job,
4273                        crate::run::ParkCause::Interrupt {
4274                            reason: format!(
4275                                "task {} asked to run first",
4276                                crate::run::short_of(interrupt_task)
4277                            ),
4278                        },
4279                    )?;
4280                }
4281            }
4282        }
4283        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4284        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4285        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4286        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4287        let mut started = false;
4288        let mut resync = false;
4289        for candidate in candidates {
4290            if stop.stopped() {
4291                break;
4292            }
4293            let DispatchClaim {
4294                task,
4295                claim,
4296                permit,
4297            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4298                Ok(claim) => claim,
4299                Err(reason) => {
4300                    skips.insert((candidate.id, reason));
4301                    continue;
4302                }
4303            };
4304            if crate::worker::active(home)?
4305                .iter()
4306                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4307            {
4308                drop(claim);
4309                resync = true;
4310                break;
4311            }
4312            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4313            let request = TaskWorker {
4314                opts: opts.absolute()?,
4315                queue: std::path::absolute(queue.root())?,
4316                task: task.id.clone(),
4317                lane,
4318                standalone: false,
4319            };
4320            // Keep the claim until spawn acknowledges the worker's durable
4321            // reservation. The worker then claims and re-reads before attempt.
4322            if let Err(error) = crate::worker::spawn(
4323                home,
4324                "task",
4325                &format!("task:{}", task.id),
4326                serde_json::to_value(&request)?,
4327            )
4328            .await
4329            {
4330                task_worker_spawn_error(home, &request, error)?;
4331                drop(claim);
4332                resync = true;
4333                break;
4334            }
4335            drop(claim);
4336            permits.extend(permit);
4337            attempted.push(task.id);
4338            started = true;
4339        }
4340        if !resync && !stop.stopped() {
4341            if !started {
4342                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4343            }
4344            if changed_dispatch_skips(&mut previous_skips, skips) {
4345                if previous_skips.is_empty() {
4346                    tracing::info!("dispatch skips cleared");
4347                }
4348                for (task, reason) in &previous_skips {
4349                    tracing::info!(
4350                        task,
4351                        reason = reason.key(),
4352                        "task {} skipped: {}",
4353                        crate::run::short_of(task),
4354                        reason.describe()
4355                    );
4356                }
4357            }
4358        }
4359        if started || resync {
4360            continue;
4361        }
4362        if owned.is_empty() && opts.once {
4363            settling_once_services = true;
4364            // These finite services can own queue claims or publish answers.
4365            // A skipped claim is not an idle queue until they have finished;
4366            // scan again afterwards so their changes are actually scheduled.
4367            if crate::worker::active(home)?.iter().any(|job| {
4368                job.kind == "daemon-service"
4369                    && matches!(
4370                        job.key.as_str(),
4371                        "service:daemon-housekeeping"
4372                            | "service:daemon-conductor"
4373                            | "service:daemon-maintenance"
4374                    )
4375            }) {
4376                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4377                continue;
4378            }
4379            break;
4380        }
4381        stop.idle(if live.is_empty() {
4382            opts.poll
4383        } else {
4384            RECHECK_WHILE_BUSY.min(opts.poll)
4385        })
4386        .await;
4387    }
4388    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4389    // every queue claim and Runner driver lease through outcome settlement.
4390    stop.busy.store(0, Ordering::SeqCst);
4391    lock(status).dispatch_wait = None;
4392    Ok(())
4393}
4394
4395/// A maintenance pass may briefly own the same record while a worker starts.
4396/// Wait without blocking the executor or charging an agent attempt, then read
4397/// ownership again under the acquired lock. Other I/O failures still fail closed.
4398async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4399    let busy = |error: &anyhow::Error| {
4400        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4401            error.kind() == std::io::ErrorKind::WouldBlock
4402                || cfg!(windows) && error.raw_os_error() == Some(33)
4403        })
4404    };
4405    match crate::pr_head::owner_lock(home, id) {
4406        Ok(lock) => return Ok(lock),
4407        Err(error) if busy(&error) => {}
4408        Err(error) => return Err(error),
4409    }
4410    let wait = RunState::load_under(id, home)?
4411        .config
4412        .graph
4413        .timeout_resource_wait;
4414    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4415}
4416
4417/// Historical successors do not revoke a still-resumable public owner. Scan
4418/// under the same lock as publication/driver claims, and fail closed on unknown
4419/// history before spending another attempt.
4420async fn public_resume_owner(
4421    home: &Path,
4422    runs: &[String],
4423    repo: &Path,
4424) -> Result<Option<RunState>> {
4425    let mut owner = None;
4426    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4427        let _lock = resume_owner_lock(home, id).await?;
4428        let state = RunState::load_under(id, home)?;
4429        if state.released()
4430            || state.retired_to.is_some()
4431            || state.pr_taken_over_by.is_some()
4432            || !crate::handover::landing_checkpoint(&state)
4433        {
4434            continue;
4435        }
4436        anyhow::ensure!(
4437            crate::git::toplevel(&state.repo).await?.canonicalize()?
4438                == crate::git::toplevel(repo).await?.canonicalize()?,
4439            "public owner repository differs; inspect run lineage"
4440        );
4441        anyhow::ensure!(
4442            owner.is_none(),
4443            "multiple retained public owners; inspect run lineage"
4444        );
4445        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4446            anyhow::bail!(reason.diagnostic(&state));
4447        }
4448        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4449        anyhow::ensure!(
4450            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4451            "public owner's driver is live or unknown; wait before retrying"
4452        );
4453        owner = Some(state);
4454    }
4455    Ok(owner)
4456}
4457
4458/// Run one claimed task to a terminal status and record the outcome.
4459///
4460/// Every transition is flushed to the queue as it happens, so the state on disk
4461/// is what actually occurred rather than what this process still intends to
4462/// write.
4463async fn attempt(
4464    opts: &Opts,
4465    queue: &Queue,
4466    status: &Arc<Mutex<Status>>,
4467    stop: &Stop,
4468    interrupt_pause: crate::graph::Pause,
4469    task: &mut Task,
4470) -> Vec<QuotaLoss> {
4471    let repo = repo_for(task, &opts.repo);
4472    tracing::info!(
4473        "task {} — {} (repo {})",
4474        task.short(),
4475        task.title,
4476        repo.display()
4477    );
4478
4479    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4480        Ok(owner) => owner,
4481        Err(e) => {
4482            task.hold_machine(Some(format!(
4483                "Cannot verify existing public owner: {e:#}; no attempt started."
4484            )));
4485            record(queue, task);
4486            return Vec::new();
4487        }
4488    };
4489    let resume_runs = public_owner
4490        .as_ref()
4491        .map(|s| vec![s.id.clone()])
4492        .unwrap_or_else(|| task.execution_runs().to_vec());
4493
4494    // A stop spends no agent resources and uses the saved landing owner.
4495    // Current roster edits, missing attachments or a failed config fetch must
4496    // never turn it into a new implementation, or prevent a PR from closing.
4497    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4498        && previous
4499            .merge_decision
4500            .as_ref()
4501            .is_some_and(|decision| !decision.closed)
4502        && previous.status != RunStatus::Landing
4503        && !crate::merge_decision::resumable_hold(&previous)
4504    {
4505        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)));
4506        record(queue, task);
4507        return Vec::new();
4508    }
4509    let stop_owner = resume_runs
4510        .last()
4511        .and_then(|id| RunState::load(id).ok())
4512        .filter(|state| {
4513            crate::merge_decision::resumable_hold(state)
4514                || state.status == RunStatus::Landing
4515                    && state.land_approval.as_ref().is_some_and(|binding| {
4516                        Questions::open()
4517                            .get_for_effects(&binding.question)
4518                            .is_ok_and(|q| {
4519                                q.run == state.id
4520                                    && q.resolution()
4521                                        .as_deref()
4522                                        .is_some_and(crate::merge_decision::stops)
4523                            })
4524                    })
4525        });
4526    if let Some(owner) = stop_owner {
4527        let mut runner = match Runner::resume(&owner.id) {
4528            Ok(runner) => runner,
4529            Err(e) => {
4530                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4531                record(queue, task);
4532                return Vec::new();
4533            }
4534        };
4535        runner.on_pause(stop.pause());
4536        runner.watch_interrupt(interrupt_pause);
4537        let quota_before = runner.state.quota.clone();
4538        let before_start = task.clone();
4539        task.start(owner.id.clone());
4540        if let Err(error) = queue.put(task) {
4541            *task = before_start;
4542            let error = runner.fail_startup("task-start", error);
4543            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4544                task.record_startup_failure(failure.clone());
4545            }
4546            task.hold_manual(Some(format!(
4547                "Could not persist task start; no agents dispatched: {error:#}"
4548            )));
4549            record(queue, task);
4550            return Vec::new();
4551        }
4552        lock(status).current.push(Current {
4553            worker: None,
4554            task: task.id.clone(),
4555            run: owner.id,
4556        });
4557        runner.state.carry_dispatched_resumes(task);
4558        runner.state.next_pass_task_entry = true;
4559        let result = runner.execute().await;
4560        return finish_attempt(
4561            opts.max_attempts,
4562            queue,
4563            task,
4564            &runner.state,
4565            &quota_before,
4566            result,
4567        );
4568    }
4569
4570    if let Some(owner) = &public_owner
4571        && (task.fresh_start || !may_resume_run(owner, task))
4572    {
4573        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)));
4574        record(queue, task);
4575        return Vec::new();
4576    }
4577
4578    if let Some(state) = task
4579        .execution_runs()
4580        .last()
4581        .and_then(|id| RunState::load(id).ok())
4582        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4583    {
4584        task.hold_machine(Some(reason));
4585        record(queue, task);
4586        return Vec::new();
4587    }
4588
4589    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4590        && !task.fresh_start
4591        && task.pr_recovery.is_none()
4592    {
4593        // Authorization still takes the owner lock and execution lease and
4594        // rechecks liveness, retained HEAD and ownership before saving.
4595        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4596            true
4597        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4598            let home = queue.root().parent().expect("queue has a home");
4599            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4600                Ok(()) => true,
4601                Err(error) => {
4602                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4603                    false
4604                }
4605            }
4606        } else {
4607            false
4608        };
4609        if !authorized {
4610            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())));
4611            // Retain the existing stop identity when an old release reached the queue.
4612            task.base_sync_notice(&held);
4613            task.resume_override = None;
4614            record(queue, task);
4615            return Vec::new();
4616        }
4617    }
4618    let unfinished = (!task.fresh_start)
4619        .then(|| unfinished_run(&resume_runs, task.short()))
4620        .flatten()
4621        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4622    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4623    if let Some(id) = &task.disk_resume_run
4624        && unfinished.as_ref() != Some(id)
4625    {
4626        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()));
4627        record(queue, task);
4628        return Vec::new();
4629    }
4630
4631    if !task.fresh_start
4632        && task.pr_recovery.is_none()
4633        && task.review_branch.is_none()
4634        && task.resume_override.is_none()
4635        && previous
4636            .as_ref()
4637            .is_some_and(|run| run.retired_to.is_some())
4638        && unfinished.is_none()
4639    {
4640        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()));
4641        record(queue, task);
4642        return Vec::new();
4643    }
4644
4645    let saved_recovery = previous.as_ref().filter(|run| {
4646        task.replacement.is_none()
4647            && task.pr_recovery.as_ref().is_some_and(|selected| {
4648                selected
4649                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4650                    .is_ok()
4651                    && selected_starter(selected, Some(run), unfinished.as_deref())
4652                        == Starter::Resume(run.id.clone())
4653            })
4654    });
4655
4656    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4657    // failure here is the network's or the operator's, not the task's: hold
4658    // without spending an attempt, never fall back to a possibly stale copy.
4659    let explicit = match &task.overrides {
4660        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4661        Some(_) => opts.config.as_deref(),
4662        None => opts.config.as_deref(),
4663    };
4664    let (mut config, layers) = if let Some(run) = saved_recovery {
4665        // A matching resume owns its resolved configuration and evidence;
4666        // current layers and inherited overrides only configure new work.
4667        let mut saved = run.clone();
4668        if let Err(e) = saved.configure_recovery_resume() {
4669            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4670            record(queue, task);
4671            return Vec::new();
4672        }
4673        (saved.config, Vec::new())
4674    } else {
4675        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4676            Ok(loaded) => loaded,
4677            Err(e) => {
4678                let reason = format!("[config] {e:#}");
4679                record_config_failure(task, &e);
4680                task.last_error = Some(reason.clone());
4681                task.hold_machine(Some(reason));
4682                record(queue, task);
4683                return Vec::new();
4684            }
4685        };
4686        if let Err(e) = apply_options(&mut config, opts, task) {
4687            task.hold_manual(Some(format!(
4688                "[config] {e:#}; correct the merge override before releasing the task"
4689            )));
4690            record(queue, task);
4691            return Vec::new();
4692        }
4693        if let Some(selected) = &task.pr_recovery
4694            && let Err(e) = selected.configure(&mut config)
4695        {
4696            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4697            record(queue, task);
4698            return Vec::new();
4699        }
4700        (config, layers)
4701    };
4702    let config_evidence = crate::pr_recovery::ConfigEvidence {
4703        layers,
4704        overrides: task.overrides.clone(),
4705        daemon_merge: task
4706            .overrides
4707            .as_ref()
4708            .is_none_or(|o| o.inherit_daemon_options)
4709            .then(|| opts.merge.clone())
4710            .flatten(),
4711    };
4712    apply_task_implementers(&mut config, task);
4713    if let Some(replacement) = &task.replacement {
4714        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4715            old.liveness(false) == Liveness::Dead
4716                && old.merge_decision.as_ref().is_some_and(|d| {
4717                    d.closed
4718                        && d.question == replacement.question
4719                        && d.replacement_run.as_ref().is_none_or(|run| {
4720                            task.execution_runs().last() == Some(run)
4721                                && RunState::load(run).is_ok_and(|current| {
4722                                    current.replaces.as_ref().is_some_and(|pin| {
4723                                        pin.question == replacement.question
4724                                            && pin.agent == replacement.agent
4725                                    })
4726                                })
4727                        })
4728                })
4729        });
4730        if !safe {
4731            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()));
4732            record(queue, task);
4733            return Vec::new();
4734        }
4735        match config.agent(&replacement.agent) {
4736            Ok(agent) if crate::agent::installed(agent) => {}
4737            _ => {
4738                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)));
4739                record(queue, task);
4740                return Vec::new();
4741            }
4742        }
4743        config.graph.implementers = 1;
4744        config.graph.land_approval = true;
4745        config.merge.mode = MergeMode::Pr;
4746        config.graph.selected_implementer = Some(replacement.agent.clone());
4747    }
4748    let p = phrases(&config.graph.language);
4749    let start_failed = p.could_not_start;
4750    // Resolve once for both admission and settlement. The inputs are the
4751    // task's explicit sources (never prose), plus an explicit review source's
4752    // current head; review-only runs may rebase later, and neither fact can
4753    // refund a failed automatic generation.
4754    if let Ok(base) =
4755        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4756            .await
4757        && let Ok(head) =
4758            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4759    {
4760        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4761        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4762            let source = crate::git::rev_parse(&repo, branch)
4763                .await
4764                .unwrap_or_default();
4765            inputs.push_str(&format!(";review:{branch}:{source}"));
4766        }
4767        if let Some(reason) = task
4768            .recovery_exhausted(
4769                &head,
4770                &inputs,
4771                task.attempt_limit
4772                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4773            )
4774            .filter(|_| {
4775                !task.repair_grants.last().is_some_and(|receipt| {
4776                    RunState::load(&receipt.request.run)
4777                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4778                })
4779            })
4780        {
4781            task.hold_unrequested_retry(Some(reason));
4782            record(queue, task);
4783            return Vec::new();
4784        }
4785        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4786    }
4787
4788    // The free-space gate, checked *before* anything is minted: a task that
4789    // waits out a full disk costs nothing yet, and must not spend an attempt
4790    // or start a run the machine cannot finish. Held tasks stay in the list
4791    // for the human to see; triage requeues them automatically when capacity
4792    // and output reservations permit the same execution to resume. A volume whose free
4793    // space cannot be measured closes the gate too: starting a run blind on a
4794    // disk that may be full is how the machine ends up with 6.7 GB free.
4795    if let Some(reason) = disk_gate(&repo, &config) {
4796        task.notice_cause("disk-space", None, None);
4797        task.last_error = Some(reason.clone());
4798        let disk_checked_at = task.disk_checked_at;
4799        task.hold_machine(Some(reason.clone()));
4800        task.mark_disk_capacity();
4801        task.disk_checked_at = disk_checked_at;
4802        record(queue, task);
4803        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4804        // Stable wording - the free-space figures live in the task's hold
4805        // reason, and changing numbers would relight the bell every poll.
4806        notices::raise(
4807            Notice::warn(
4808                &format!("disk:{}", repo.display()),
4809                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
4810            )
4811            .link(Link::Task {
4812                id: task.id.clone(),
4813            }),
4814        );
4815        return Vec::new();
4816    }
4817
4818    // A resumable run of this task is carried on, never re-competed. The
4819    // candidates are built and paid for, and a fresh competition races a
4820    // second implementation against them.
4821    //
4822    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4823    // started 3cbf on the same task a moment later, duplicating two and a
4824    // half hours of agent work. Then b25f stalled on a judge that timed out
4825    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4826    // was to blame for - and 4043 started **one second** later, buying three
4827    // fresh implementations to reach the same panel. `RunStatus::resumable`
4828    // rather than `!done()` is what catches the second case: a stall is
4829    // terminal, and its cheap recovery re-asks only the absent seats.
4830    //
4831    // A load failure is warned about rather than silently read as "not
4832    // resumable": the alternative is exactly what let a schema mismatch on
4833    // run `eba2` fall through to a full re-competition with nobody told why.
4834    // `crate::conduct` is what actually offers a better answer than
4835    // `Runner::start` here (see `Recovery::Review`), once this task's next
4836    // failure shows it up as `held`/`failed` with the run state unreadable.
4837    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4838    // branch survived, and this reopens exactly that branch as a
4839    // review-only pass rather than resuming or competing again. Consumed
4840    // (cleared) here whichever way this goes, so it never outlives this one
4841    // attempt - see `queue::Task::review_branch`.
4842    let review_branch = if previous
4843        .as_ref()
4844        .is_some_and(|state| crate::repair_budget::pending(task, state))
4845    {
4846        None
4847    } else {
4848        take_review_branch(task, previous.as_ref())
4849    };
4850    let branch_exists = match &review_branch {
4851        Some(branch) => crate::git::branch_exists(&repo, branch)
4852            .await
4853            .unwrap_or(false),
4854        None => false,
4855    };
4856    // An explicit `magi review <branch>` is reviewed whatever happens to the
4857    // branch unless an explicit implementer change requires fresh work. An
4858    // unfinished run of the same task still wins, so a retry resumes.
4859    let proposed = review_retry_starter(
4860        task,
4861        previous.as_ref(),
4862        review_branch.as_deref(),
4863        branch_exists,
4864        unfinished.as_deref(),
4865    );
4866    let retry_selected = task.replacement.is_some()
4867        && task.resumption.is_some()
4868        && !task.fresh_start
4869        && previous.as_ref().is_some_and(|run| {
4870            run.replaces.is_some()
4871                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4872                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4873        });
4874    let stop_pin = task
4875        .resume_override
4876        .as_ref()
4877        .filter(|pin| {
4878            Questions::open()
4879                .get_for_effects(&pin.question_id)
4880                .is_ok_and(|q| {
4881                    q.node == land::APPROVAL_NODE
4882                        && q.resolution()
4883                            .as_deref()
4884                            .is_some_and(crate::merge_decision::stops)
4885                })
4886        })
4887        .and_then(|pin| pin.pinned_run.clone());
4888    let granted_run = task.repair_grants.last().and_then(|receipt| {
4889        let state = RunState::load(&receipt.request.run).ok()?;
4890        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4891    });
4892    let starter = if let Some(run) = granted_run {
4893        Starter::Resume(run)
4894    } else if let Some(owner) = &public_owner {
4895        Starter::Resume(owner.id.clone())
4896    } else if let Some(run) = stop_pin {
4897        // Stop actions resume their exact owner even after seat-count edits;
4898        // they must never fall through to implementation or a takeover.
4899        Starter::Resume(run)
4900    } else if retry_selected {
4901        Starter::Resume(previous.as_ref().unwrap().id.clone())
4902    } else if let Some(selected) = &task.pr_recovery {
4903        if selected
4904            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4905            .is_ok()
4906        {
4907            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4908        } else {
4909            Starter::Review(selected.branch.clone())
4910        }
4911    } else {
4912        starter_with_implementers(task, previous.as_ref(), proposed)
4913    };
4914    // An explicit resume pin must never degrade into a new competition or
4915    // takeover, including when its run stops being eligible after the answer.
4916    if let Some(pin) = &task.resume_override
4917        && let Some(run) = &pin.pinned_run
4918        && starter != Starter::Resume(run.clone())
4919    {
4920        let run = run.clone();
4921        task.notice_cause("resume-owner", Some(&run), None);
4922        task.hold_machine(Some(format!(
4923            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4924            task.id
4925        )));
4926        record(queue, task);
4927        return Vec::new();
4928    }
4929    // Automatic disk recovery resumes its retained run or stops: a changed
4930    // seat count or review branch must not turn it into a new competition.
4931    // No attempt is spent here.
4932    if let Some(run) = &task.disk_resume_run
4933        && starter != Starter::Resume(run.clone())
4934    {
4935        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()));
4936        record(queue, task);
4937        return Vec::new();
4938    }
4939    if task.replacement.is_some()
4940        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4941        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4942    {
4943        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()));
4944        record(queue, task);
4945        return Vec::new();
4946    }
4947    if let Some(reason) = retained_attempt_hold(
4948        task,
4949        &starter,
4950        config.disk.retained_attempt_limit,
4951        RunState::load,
4952    ) {
4953        // The review choice was consumed above. Preserve it across this hold
4954        // so a later release cannot silently become a fresh implementation.
4955        if let Starter::Review(branch) = &starter {
4956            task.review_branch = Some(branch.clone());
4957        }
4958        task.hold_unrequested_retry(Some(reason));
4959        record(queue, task);
4960        return Vec::new();
4961    }
4962    // Absolute paths of the files the task was filed with, re-read from the
4963    // task now so a file attached while it was held reaches a resumed run
4964    // too. A stored name whose file has gone is an error before any agent is
4965    // paid for, never a silent omission the implementer cannot notice.
4966    let attachments = match task_attachments(queue, task) {
4967        Ok(a) => a,
4968        Err(e) => {
4969            task.attempts += 1;
4970            task.fail_startup_target(
4971                "startup-attachments",
4972                e.name.clone(),
4973                format!("{start_failed}{e:#}"),
4974                opts.max_attempts,
4975            );
4976            record(queue, task);
4977            return Vec::new();
4978        }
4979    };
4980    let startup_pause = stop.pause();
4981    let startup_interrupt = interrupt_pause.clone();
4982    let wait = crate::repo_lock::WaitPolicy::new(
4983        Duration::from_secs(config.graph.timeout_resource_wait),
4984        move || startup_pause.parked() || startup_interrupt.parked(),
4985    );
4986    // Startup includes review takeover and recovery. Do not embed its large
4987    // future in both the wait scope and the surrounding attempt stack frame.
4988    let started = wait.scope(Box::pin(async { match &starter {
4989        Starter::Review(_) if task.pr_recovery.is_some() => {
4990            let selected = task.pr_recovery.clone().expect("selected recovery");
4991            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
4992                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4993                    .await
4994                    .map(|mut r| {
4995                        r.state.attachments = attachments.clone();
4996                        r
4997                    }),
4998                Err(e) => Err(e),
4999            }
5000        }
5001        Starter::Review(branch) => {
5002            tracing::info!(
5003                "task {} reopens `{branch}` as a review-only pass",
5004                task.short()
5005            );
5006            // Every earlier attempt is superseded by the one being minted
5007            // now, so a branch one of them still holds may be taken over.
5008            let takeover = crate::handover::Takeover {
5009                earlier: task.earlier_attempts().to_vec(),
5010                home: crate::run::home(),
5011                choice: take_divergence_answer(branch, &config.merge.remote, task),
5012                task_instruction: Some(instruction_for(task)),
5013            };
5014            Runner::review_taking_over(
5015                &repo,
5016                branch,
5017                config,
5018                Some(takeover),
5019                crate::run::Origin::queue(&task.id),
5020            )
5021            .await
5022        }
5023        Starter::Resume(id) => {
5024            tracing::info!("resuming run {id} rather than competing again");
5025            Runner::resume(id).and_then(|mut r| {
5026                if retry_selected {
5027                    // The explicit queue release retries this same pinned
5028                    // implementation, preserving the attempt and worktrees.
5029                    for candidate in &mut r.state.candidates {
5030                        candidate.failed = None;
5031                        candidate.empty = false;
5032                        candidate.commits = 0;
5033                    }
5034                    r.state.status = RunStatus::Implementing;
5035                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5036                }
5037                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5038                    r.state.sources = task.sources.clone();
5039                }
5040                if r.state.prep_failure.is_some() {
5041                    let approval = task
5042                        .resumption
5043                        .as_ref()
5044                        .context("preparation retry requires an explicit task release")?;
5045                    r.retry_preparation(approval.at)?;
5046                }
5047                if let Some(instruction) =
5048                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5049                {
5050                    r.state.instruction = instruction;
5051                }
5052                r.state.attachments = attachments.clone();
5053                if task.replacement.is_some() {
5054                    r.state.config.merge.mode = MergeMode::Pr;
5055                    r.state.config.graph.land_approval = true;
5056                }
5057                // Replacements publish a new PR and ask again. Selected PR
5058                // recoveries keep their saved disposition; ordinary runs can
5059                // retain the task's merge override.
5060                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5061                    .overrides
5062                    .as_ref()
5063                    .and_then(|o| o.merge.as_deref())
5064                    .and_then(|m| merge_mode(m).ok())
5065                {
5066                    r.state.config.merge.mode = mode;
5067                }
5068                Ok(r)
5069            })
5070        }
5071        Starter::Start => {
5072            if let Some(branch) = &review_branch {
5073                tracing::warn!(
5074                    "conductor chose review for task {} but branch `{branch}` no longer \
5075                     exists; requeuing as a fresh competition instead",
5076                    task.short()
5077                );
5078            }
5079            let instruction = prepare_instruction(&starter, None, task)
5080                .unwrap_or_else(|| task.instruction.clone());
5081            Runner::start_naming(
5082                &repo,
5083                instruction,
5084                &task.title,
5085                config,
5086                crate::run::Origin::queue(&task.id),
5087            )
5088            .await
5089            .map(|mut r| {
5090                r.state.attachments = attachments.clone();
5091                r.state.sources = task.sources.clone();
5092                r
5093            })
5094        }
5095    }})).await;
5096    if let Err(error) = &started
5097        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5098    {
5099        task.record_startup_failure(failure.clone());
5100    }
5101    let mut runner = match started {
5102        Ok(r) => r,
5103        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5104            task.last_error = Some(e.to_string());
5105            if stop.parking() || interrupt_pause.parked() {
5106                let attempts = task.attempts;
5107                task.park(e.to_string());
5108                // Startup has not spent an attempt to refund.
5109                task.attempts = attempts;
5110            } else {
5111                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5112            }
5113            record(queue, task);
5114            return Vec::new();
5115        }
5116        // A branch an earlier attempt still holds and magi will not release
5117        // by itself is the operator's call, not a failed attempt: hold the
5118        // task with the reason, spend nothing, and say so on the bell.
5119        Err(e) if task.pr_recovery.is_some() => {
5120            task.startup_notice_cause("startup-public-head");
5121            task.attempts += 1;
5122            task.last_error = Some(format!("{start_failed}{e:#}"));
5123            task.hold_unrequested_retry(Some(format!(
5124                "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."
5125            )));
5126            record(queue, task);
5127            return Vec::new();
5128        }
5129        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5130            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5131                Some(r) => (p.handover_refused)(r),
5132                None => format!("{e:#}"),
5133            };
5134            task.startup_notice_cause("startup-handover");
5135            let reason = format!("{start_failed}{detail}");
5136            task.last_error = Some(reason.clone());
5137            // Consumed above by `take`; keep it so the released task retries
5138            // as a review of this same branch.
5139            let branch = match &starter {
5140                Starter::Review(branch) => Some(branch.clone()),
5141                _ => None,
5142            };
5143            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5144            // one page; the guidance rides in the reason, fixed per state so a
5145            // re-put never changes the wording and relights it.
5146            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5147            record(queue, task);
5148            tracing::warn!(
5149                "holding {} for a branch it cannot take over: {e:#}",
5150                task.short()
5151            );
5152            return Vec::new();
5153        }
5154        // A branch that differs between here and the remote in ways magi
5155        // cannot prove are the same change is a decision for the owner, not a
5156        // failed attempt: ask with both sides laid out, spend no attempt, and
5157        // let the answer requeue the task.
5158        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5159            let d = e
5160                .downcast_ref::<crate::reconcile::Diverged>()
5161                .expect("checked by the guard");
5162            let mut q = ask::Question::new(
5163                task.id.clone(),
5164                crate::reconcile::NODE.to_owned(),
5165                crate::reconcile::SEAT.to_owned(),
5166                d.summary(),
5167                d.detail(),
5168                d.choices(),
5169            );
5170            match Questions::open().put(&mut q) {
5171                Ok(()) => {
5172                    task.last_error = Some(format!("{e:#}"));
5173                    // Consumed above by `take`; the answer has to reach a review
5174                    // of this same branch, so keep pointing the task at it.
5175                    task.review_branch = Some(d.branch.clone());
5176                    task.review_instruction = Some(task.instruction.clone());
5177                    task.block(vec![q.id.clone()], Some(d.summary()));
5178                }
5179                Err(put) => {
5180                    tracing::warn!("could not file the divergence question: {put:#}");
5181                    task.attempts += 1;
5182                    task.fail_startup(
5183                        "startup-question-store",
5184                        format!("{start_failed}{e:#}"),
5185                        opts.max_attempts,
5186                    );
5187                }
5188            }
5189            record(queue, task);
5190            return Vec::new();
5191        }
5192        Err(e) => {
5193            // The answer was stale and nothing was applied: keep pointing at
5194            // the branch so the next attempt asks again against its new tips.
5195            // Nothing went wrong with the task, so no attempt is spent: a
5196            // budget one short of its limit must not hold it instead of
5197            // letting the question be asked again.
5198            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5199                && let Starter::Review(branch) = &starter
5200            {
5201                task.review_branch = Some(branch.clone());
5202                task.review_instruction = Some(task.instruction.clone());
5203                task.last_error = Some(format!("{start_failed}{e:#}"));
5204                task.status = crate::queue::TaskStatus::Failed;
5205                record(queue, task);
5206                return Vec::new();
5207            }
5208            task.attempts += 1;
5209            task.last_error = Some(format!("{start_failed}{e:#}"));
5210            task.startup_notice_cause("startup-source");
5211            task.hold_unrequested_retry(Some(format!(
5212                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5213            )));
5214            record(queue, task);
5215            return Vec::new();
5216        }
5217    };
5218    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5219        runner.state.recovery_config = Some(config_evidence);
5220    }
5221    if let Some(replacement) = &task.replacement {
5222        if matches!(starter, Starter::Start) {
5223            runner.state.instruction.push_str(&format!(
5224                "\n\n# Replacement review context\n{}",
5225                replacement.context
5226            ));
5227        }
5228        runner.state.replaces = Some(replacement.clone());
5229        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5230        if let Ok(mut old) = RunState::load(&replacement.run)
5231            && let Some(d) = &mut old.merge_decision
5232        {
5233            d.replacement_run = Some(runner.state.id.clone());
5234            old.event(
5235                "replacement",
5236                format!(
5237                    "replacement run {} owns the next attempt; old PR remains closed",
5238                    runner.state.id
5239                ),
5240            );
5241            if let Err(e) = old.save() {
5242                let error = runner.fail_startup("replacement-history", e);
5243                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5244                    task.record_startup_failure(failure.clone());
5245                }
5246                task.hold_manual(Some(format!(
5247                    "Could not link replacement history: {error:#}; no agents dispatched"
5248                )));
5249                record(queue, task);
5250                return Vec::new();
5251            }
5252        }
5253    }
5254    runner.state.task_instruction = Some(task.instruction.clone());
5255    // The follow-up depth is fixed now, while the task certainly exists:
5256    // deleting it later must not reset the cap (`crate::followup`).
5257    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5258    if runner.state.origin_chat.is_none() {
5259        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5260    }
5261    // A stop that means "park" reaches the graph through this handle.
5262    runner.on_pause(stop.pause());
5263    // `poll`'s interrupt scheduler reaches this one run - and no other -
5264    // through this handle. See `Pause`'s own doc for why these are never
5265    // the same one.
5266    runner.watch_interrupt(interrupt_pause);
5267
5268    // `start` has minted the run, so the task can now point at it. Persisting
5269    // `Running` before `execute` is what makes a crash mid-run legible.
5270    let run = runner.state.id.clone();
5271    let before_start = task.clone();
5272    task.start(run.clone());
5273    if let Err(error) = queue.put(task) {
5274        *task = before_start;
5275        let error = runner.fail_startup("task-start", error);
5276        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5277            task.record_startup_failure(failure.clone());
5278        }
5279        task.hold_manual(Some(format!(
5280            "Could not persist task start; no agents dispatched: {error:#}"
5281        )));
5282        record(queue, task);
5283        return Vec::new();
5284    }
5285    lock(status).current.push(Current {
5286        worker: None,
5287        task: task.id.clone(),
5288        run,
5289    });
5290
5291    // `RunState::quota` is the run's whole history across every resume, so
5292    // only what this execution added may arm the cooldown or earn a refund.
5293    let quota_before = runner.state.quota.clone();
5294    runner.state.carry_dispatched_resumes(task);
5295    runner.state.next_pass_task_entry = true;
5296    let result = runner.execute().await;
5297    finish_attempt(
5298        opts.max_attempts,
5299        queue,
5300        task,
5301        &runner.state,
5302        &quota_before,
5303        result,
5304    )
5305}
5306
5307/// Settle `task` after its run executed: the verdict, the diagnosis, the
5308/// supersession of earlier attempts and the save. Shared by the loop and by
5309/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5310/// Returns the quota losses this execution added to the run.
5311pub fn finish_attempt(
5312    max_attempts: usize,
5313    queue: &Queue,
5314    task: &mut Task,
5315    state: &RunState,
5316    quota_before: &[QuotaLoss],
5317    result: Result<()>,
5318) -> Vec<QuotaLoss> {
5319    let detail = match result {
5320        Ok(()) => describe(state),
5321        Err(e) => format!("{e:#}"),
5322    };
5323    let fresh = losses_this_attempt(quota_before, &state.quota);
5324    let verdict = Verdict {
5325        status: state.status,
5326        // A run that opened a pull request handed its work over, whatever the
5327        // gate then decided about merging it.
5328        left_pr: state.pr.is_some(),
5329        // Only a rate limit earns the task its attempt back - and only one
5330        // suffered now: a refund justified by a previous session's loss is
5331        // the same mistake as re-arming the cooldown from it. A stalled run
5332        // resumed without hitting quota again therefore spends its attempt,
5333        // like any other failure of the task's own.
5334        quota_hit: !fresh.is_empty(),
5335        // A run that parked was asked to stop; that is not a failure and must
5336        // not spend an attempt, or replacing the binary a few times would
5337        // exhaust a task's budget without an agent ever misbehaving.
5338        parked: state.parked,
5339        // A quota loss that left nothing viable is the same machine fact as a
5340        // `Stalled` quota loss; see `settle`'s doc table.
5341        no_viable_candidates: state.viable().is_empty(),
5342    };
5343    if let Some(replacement) = &state.replaces
5344        && let Some(pr) = &state.pr
5345        && let Ok(mut old) = RunState::load(&replacement.run)
5346        && let Some(d) = &mut old.merge_decision
5347    {
5348        d.replacement_pr = Some(pr.url.clone());
5349        let _ = old.save();
5350    }
5351    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5352    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5353        task.hold_unrequested_retry(Some(format!(
5354            "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.",
5355            task.short()
5356        )));
5357    }
5358    if task.status == TaskStatus::Done {
5359        supersede_prior_runs(task, &crate::run::home());
5360    }
5361    record(queue, task);
5362    tracing::info!(
5363        "task {} is {} after run {} ({})",
5364        task.short(),
5365        task.status.as_str(),
5366        state.short(),
5367        label(state.status)
5368    );
5369    fresh
5370}
5371
5372/// A task a hand-started run leaves runnable (failed with attempts to spare,
5373/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5374/// later must not spend agent calls on it. `magi task release` retries.
5375pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5376    // Parked work (including legacy Failed records with a parked run) is a
5377    // checkpoint or owner handoff, not an unrequested retry.
5378    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5379        && !awaiting_resume_with(task, RunState::load)
5380        // A run parked on the owner's word about a withheld PR title/body
5381        // resumes via `land_resume_state`, including review-only tasks that
5382        // `awaiting_resume_with` does not consider.
5383        && withheld_text_wait(task).is_none()
5384        && !(task.fresh_start && task.replacement.is_some())
5385    {
5386        let why = task.last_error.clone().map_or_else(
5387            || "the run did not finish".to_owned(),
5388            |e| format!("the run did not finish: {e}"),
5389        );
5390        task.hold_unrequested_retry(Some(format!(
5391            "{why}. It was started by hand, so it is not retried \
5392             automatically; `magi task release` retries it."
5393        )));
5394        record(queue, task);
5395    }
5396}
5397
5398/// Whether an attempt at a task whose newest run is `run` would resume that
5399/// run rather than start a fresh competition. `magi run --resume` hands a run
5400/// to a live loop only when this holds.
5401#[must_use]
5402pub fn loop_would_resume(run: &str) -> bool {
5403    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5404}
5405
5406/// A loop in another process that is alive right now: a fresh heartbeat in
5407/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5408/// carries the pid it published (`None` inside when it published none - a
5409/// fresh heartbeat is still evidence of a live loop).
5410///
5411/// The one judgement of "is somebody else serving this queue", shared by the
5412/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5413/// deciding whether to hand a task to the loop. A claim file proves nothing
5414/// here: whether a claim succeeds says nothing about whether its owner lives.
5415#[must_use]
5416pub fn foreign_loop(
5417    reading: Option<&Reading>,
5418    now: Timestamp,
5419    own_pid: u32,
5420) -> Option<Option<u32>> {
5421    let reading = reading.filter(|r| r.running(now))?;
5422    match reading.pid {
5423        Some(pid) if pid == own_pid => None,
5424        pid => Some(pid),
5425    }
5426}
5427
5428fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5429    reading.worker_protocol != Some(1)
5430        && (foreign_loop(Some(reading), now, own_pid).is_some()
5431            || reading
5432                .pid
5433                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5434}
5435
5436/// Low-level claimed-task execution shared by the detached standalone worker
5437/// and focused lifecycle fixtures. The caller must retain the queue claim for
5438/// this entire call. CLI callers transfer ownership through
5439/// [`run_detached_claimed`] instead of executing inside their own runtime.
5440///
5441/// The one deliberate difference from the loop: a task the attempt leaves
5442/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5443/// Nobody asked for a retry, and a daemon starting later must not spend agent
5444/// calls re-running a hand-started task behind the operator's back;
5445/// `magi task release` is the explicit retry.
5446pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5447    run_claimed_until(opts, queue, task, &Stop::new()).await;
5448}
5449
5450async fn run_claimed_until(
5451    opts: &Opts,
5452    queue: &Queue,
5453    task: &mut Task,
5454    stop: &Stop,
5455) -> Vec<QuotaLoss> {
5456    let status = Arc::new(Mutex::new(Status::new()));
5457    // An attempt embeds startup and graph futures. Keep it off the standalone
5458    // caller's stack, on both the initial execution and withheld-text resume.
5459    let mut quota = Box::pin(attempt(
5460        opts,
5461        queue,
5462        &status,
5463        stop,
5464        crate::graph::Pause::new(),
5465        task,
5466    ))
5467    .await;
5468    // A run parked on the owner's word about a withheld PR title/body has no
5469    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5470    // here with the claim still held, and resume once the question is settled
5471    // (answered, or abandoned at its deadline -> the neutral text).
5472    // A rejected reply files one more question (the gate asks at most twice),
5473    // so after a resume the run may be waiting again: keep going, with a fresh
5474    // limit for the new question. `resumes` bounds it even if a resume parks
5475    // without asking anything new.
5476    let mut resumes = 0;
5477    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5478        let Some(timeout) = withheld_text_wait(task) else {
5479            break;
5480        };
5481        eprintln!(
5482            "waiting for the owner's answer on a withheld pull request text \
5483             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5484        );
5485        // The deadline abandons the question itself; the extra margin only
5486        // covers an abandon that could not be saved.
5487        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5488        let ready = loop {
5489            match land_resume_state(task) {
5490                LandResume::StillWaiting
5491                    if !stop.parking() && std::time::Instant::now() < limit =>
5492                {
5493                    tokio::time::sleep(WITHHELD_POLL).await;
5494                }
5495                LandResume::Ready => break true,
5496                _ => break false,
5497            }
5498        };
5499        if !ready || stop.parking() {
5500            break;
5501        }
5502        resumes += 1;
5503        quota.extend(
5504            Box::pin(attempt(
5505                opts,
5506                queue,
5507                &status,
5508                stop,
5509                crate::graph::Pause::new(),
5510                task,
5511            ))
5512            .await,
5513        );
5514    }
5515    hold_if_runnable(queue, task);
5516    quota
5517}
5518
5519/// Resumes an in-process run makes for withheld-text questions: the gate asks
5520/// at most twice, plus one for a resume that asks nothing new.
5521const MAX_WITHHELD_RESUMES: u32 = 3;
5522
5523/// How often an in-process run rechecks its withheld-text question.
5524const WITHHELD_POLL: Duration = Duration::from_secs(15);
5525
5526/// The `answer_timeout` (seconds) of the task's last run when that run is
5527/// parked on an unresolved withheld-text question; `None` otherwise.
5528fn withheld_text_wait(task: &Task) -> Option<u64> {
5529    let id = task.execution_runs().last()?;
5530    let s = RunState::load(id).ok()?;
5531    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5532        .then_some(s.config.graph.answer_timeout)
5533}
5534
5535/// The quota losses `after` holds that `before` did not: what one execution
5536/// suffered, as opposed to the run's history.
5537///
5538/// Compared by value rather than by length or position because
5539/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5540/// the vector can shrink and shift under a resume. A retried seat that hits
5541/// quota again is a `push` with a new `at`, so it shows up as new here.
5542/// Crash recovery uses the recorded pass start as its boundary when available;
5543/// legacy records without passes retain their original history-based policy.
5544fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5545    after
5546        .iter()
5547        .filter(|q| !before.contains(q))
5548        .cloned()
5549        .collect()
5550}
5551
5552/// When the loop-wide quota cooldown should end, given this attempt's losses;
5553/// `None` when there were none. Reset-hint parsing and the cap live here.
5554fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5555    let quota: Vec<_> = quota
5556        .iter()
5557        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5558        .collect();
5559    if quota.is_empty() {
5560        return None;
5561    }
5562    let with_hint = quota.iter().find(|q| q.reset.is_some());
5563    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5564    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5565    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5566    Some(
5567        now.checked_add(jiff::SignedDuration::from_secs(secs))
5568            .unwrap_or(Timestamp::MAX),
5569    )
5570}
5571
5572/// An explicit task count must agree with a run before any resume.
5573fn implementers_match(task: &Task, state: &RunState) -> bool {
5574    task.replacement.as_ref().map_or_else(
5575        || {
5576            task.implementers()
5577                .is_none_or(|n| n == state.config.graph.implementers)
5578        },
5579        |replacement| {
5580            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5581                && state.config.graph.implementers == 1
5582        },
5583    )
5584}
5585
5586/// Never resume or take over candidate work built for a different seat count.
5587fn starter_with_implementers(
5588    task: &Task,
5589    previous: Option<&RunState>,
5590    proposed: Starter,
5591) -> Starter {
5592    if previous.is_some_and(|s| !implementers_match(task, s)) {
5593        task.review_of
5594            .as_ref()
5595            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5596    } else {
5597        proposed
5598    }
5599}
5600
5601/// Apply this task's explicit count to the new attempt, without changing defaults.
5602fn apply_task_implementers(config: &mut Config, task: &Task) {
5603    if let Some(n) = task.implementers() {
5604        config.graph.implementers = n;
5605    }
5606}
5607
5608/// [`prepare`] for one task: its own `--config` and command-line overrides
5609/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5610/// over the loop's, so handing a hand-started task to a daemon changes nothing
5611/// about what it does.
5612#[cfg(test)]
5613fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5614    let explicit = match &task.overrides {
5615        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5616        _ => opts.config.as_deref(),
5617    };
5618    let (mut config, _) = Config::discover(repo, explicit)?;
5619    apply_options(&mut config, opts, task)?;
5620    Ok(config)
5621}
5622
5623fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5624    if task
5625        .overrides
5626        .as_ref()
5627        .is_none_or(|o| o.inherit_daemon_options)
5628        && let Some(mode) = opts.merge.as_deref()
5629    {
5630        config.merge.mode = merge_mode(mode)?;
5631    }
5632    if let Some(o) = &task.overrides {
5633        o.apply(config);
5634    }
5635    Ok(())
5636}
5637
5638/// Load the config for a task's repository, with the merge override applied.
5639fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5640    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5641    if let Some(mode) = &opts.merge {
5642        config.merge.mode = merge_mode(mode)?;
5643    }
5644    Ok(config)
5645}
5646
5647/// Prune the shared build cache at a between-runs boundary. The detached cache
5648/// service checks authoritative task jobs first; dispatch waits for that finite
5649/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5650/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5651async fn maybe_prune_cache_between_runs(
5652    repo: &Path,
5653    opts: &Opts,
5654    home: &Path,
5655    stop: &Stop,
5656    last_checked: &mut Option<Timestamp>,
5657    now: Timestamp,
5658) {
5659    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5660        return;
5661    }
5662    *last_checked = Some(now);
5663    let cfg = match prepare(repo, opts) {
5664        Ok(cfg) => cfg,
5665        Err(e) => {
5666            tracing::warn!("cache check: no config: {e:#}");
5667            return;
5668        }
5669    };
5670    match clean::prune_cache_if_over_limit(&cfg, home) {
5671        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5672            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5673            pruned.files,
5674            pruned.freed
5675        ),
5676        Ok(_) => {}
5677        Err(e) => {
5678            tracing::warn!("housekeep: prune cache: {e:#}");
5679            notices::raise_in(
5680                home,
5681                Notice::warn(
5682                    "housekeep:cache",
5683                    format!(
5684                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5685                        e.to_string()
5686                            .lines()
5687                            .next()
5688                            .unwrap_or("unknown cleanup error")
5689                    ),
5690                ),
5691            );
5692        }
5693    }
5694}
5695
5696/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5697/// now, given when it last did (if ever). Pure, so the cadence is asserted
5698/// directly rather than by waiting out real minutes in a test.
5699fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5700    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5701}
5702
5703/// The disk janitor, with its housekeeping logged rather than fatal.
5704///
5705/// Called only at the loop's idle points, for the reason the caller documents:
5706/// a prune racing a live compile would delete files mid-build. The config is
5707/// re-read on every call because the repository that just ran may not be the
5708/// daemon's own default, and the cache directory is a repository fact.
5709///
5710/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5711/// and [`crate::run::default_worktree_root`] read here, for the same reason
5712/// [`drive`] takes its queue and status file rather than resolving them: a
5713/// test driving the loop must not reach through to the operator's real home
5714/// or worktree bay just because the janitor runs on every idle tick.
5715/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5716/// to get wrong silently - a test's `home` was already isolated, but nothing
5717/// exercised the parameter next to it, so a real worktree bay stayed wired in
5718/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5719/// it for real, every test in this file that drives the loop at all started
5720/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5721async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5722    let cfg = match prepare(repo, opts) {
5723        Ok(cfg) => cfg,
5724        Err(e) => {
5725            tracing::warn!("housekeep: no config: {e:#}");
5726            return;
5727        }
5728    };
5729    // A run's own worktree lives under `config.graph.worktree_root` when the
5730    // repository sets one - the same precedence `RunState::worktree_root`
5731    // uses - and `worktrees_root` only stands in for the *default* an
5732    // unconfigured repository resolves to (see this function's own
5733    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5734    // that always swept the default regardless of this override would never
5735    // see, and so never reclaim, a single worktree for a repository that
5736    // relocated them elsewhere.
5737    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5738    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5739    // Reported whenever there is anything to say, not only when `folded > 0`:
5740    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5741    // folded, on every single pass, for months - a report gated on `folded`
5742    // would have stayed silent through every one of them.
5743    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5744        let mut extra = Vec::new();
5745        if out.unreadable > 0 {
5746            extra.push(format!("{} unreadable", out.unreadable));
5747        }
5748        if out.orphaned_worktrees > 0 {
5749            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5750        }
5751        let detail = if extra.is_empty() {
5752            String::new()
5753        } else {
5754            format!(" ({})", extra.join(", "))
5755        };
5756        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5757    }
5758    if out.external_merges_recorded > 0 {
5759        tracing::info!(
5760            "housekeep: recorded {} run(s) as merged externally",
5761            out.external_merges_recorded
5762        );
5763    }
5764    if out.stale_pr_states_repaired > 0 {
5765        tracing::info!(
5766            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5767            out.stale_pr_states_repaired
5768        );
5769    }
5770    if out.cache_files > 0 {
5771        tracing::info!(
5772            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5773            out.cache_files,
5774            out.cache_freed
5775        );
5776    }
5777    if out.questions_abandoned > 0 {
5778        tracing::info!(
5779            "housekeep: abandoned {} question(s) left open by a finished run",
5780            out.questions_abandoned
5781        );
5782    }
5783}
5784
5785/// Run [`triage::run_once`] and log whatever it did, the same "only when
5786/// there is something to say" rule [`janitor`] follows for its own report.
5787///
5788/// Called at the same idle points as [`janitor`] - once per full poll
5789/// interval, never mid-attempt - for the same reason: it is not liveness
5790/// critical, and a task's own `hold_reason` string is the one thing this
5791/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5792/// tick for no benefit.
5793async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5794    let questions = Questions::at(home.join("questions"));
5795    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5796    if report.is_empty() {
5797        return;
5798    }
5799    if !report.quarantined.is_empty() {
5800        tracing::info!(
5801            "triage: held {} blocked task(s) whose blocked-on task or \
5802             question no longer exists: {}",
5803            report.quarantined.len(),
5804            report.quarantined.join(", ")
5805        );
5806    }
5807    if !report.resumed.is_empty() {
5808        tracing::info!(
5809            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5810            report.resumed.len(),
5811            report.resumed.join(", ")
5812        );
5813    }
5814    if !report.asked.is_empty() {
5815        tracing::info!(
5816            "triage: asked about {} held task(s): {}",
5817            report.asked.len(),
5818            report.asked.join(", ")
5819        );
5820    }
5821    if !report.answered.is_empty() {
5822        tracing::info!(
5823            "triage: applied {} operator answer(s): {}",
5824            report.answered.len(),
5825            report.answered.join(", ")
5826        );
5827    }
5828}
5829
5830/// The free-space gate: what stands between this task and a new run, if
5831/// anything. `Some(reason)` holds the task; `None` lets it start.
5832///
5833/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5834/// the operator opted out. A measurement failure is a gate, not a pass: both
5835/// sides of "cannot tell" are served by not starting.
5836pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5837    disk_gate_with(repo, config, crate::disk::free_bytes)
5838}
5839
5840/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5841/// test can assert the exact wiring `attempt` runs - config's threshold in,
5842/// task-holding reason out - without asking the real machine's disk anything.
5843fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5844    repo: &Path,
5845    config: &Config,
5846    free_bytes: F,
5847) -> Option<String> {
5848    let min = config.disk.min_free_bytes;
5849    if min == 0 {
5850        return None;
5851    }
5852    let mut paths = vec![repo.to_owned()];
5853    if let Some(cache) = config.cache_dir() {
5854        paths.push(cache);
5855    }
5856    paths.push(
5857        config
5858            .graph
5859            .worktree_root
5860            .clone()
5861            .unwrap_or_else(crate::run::default_worktree_root),
5862    );
5863    for path in paths {
5864        let probe = if path == repo {
5865            path.as_path()
5866        } else {
5867            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5868        };
5869        let reason = match free_bytes(probe) {
5870            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5871            Err(e) => Some(crate::disk::unmeasured_in(
5872                probe,
5873                &e,
5874                &config.graph.language,
5875            )),
5876        };
5877        if reason.is_some() {
5878            return reason;
5879        }
5880    }
5881    None
5882}
5883
5884/// How long to wait before offering another task when a run lost a seat to a
5885/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5886/// could read, or carried nothing at all. Long enough that a quota outage
5887/// cannot burn through a whole backlog in the few seconds each doomed attempt
5888/// takes to fail; short enough that a quota which clears early is not left
5889/// idle for the fallback's sake.
5890const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5891
5892/// Longest a parsed reset hint may push the wait out to. The hint comes from
5893/// the CLI's own words, not a contract, so a parsing slip that lands a day
5894/// away must not leave the loop asleep for a day.
5895const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5896
5897/// How long [`poll`] should wait before offering the next task, after a run
5898/// lost at least one seat to a rate limit.
5899///
5900/// Pure and separate from the loop so the policy can be exercised without a
5901/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5902/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5903/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5904/// far a parsed hint is trusted to push the wait out.
5905fn quota_wait(
5906    reset_at: Option<Timestamp>,
5907    now: Timestamp,
5908    fallback: Duration,
5909    cap: Duration,
5910) -> Duration {
5911    match reset_at {
5912        Some(at) if at > now => {
5913            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5914            Duration::from_secs(secs).min(cap)
5915        }
5916        _ => fallback,
5917    }
5918}
5919
5920/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5921///
5922/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5923/// explains why parsing it exactly "would be a bug factory" — so this only
5924/// recognises the shapes actually observed in the wild, and returns `None`
5925/// for anything else rather than guess at a format nobody has seen.
5926///
5927/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5928/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5929/// said it, not from whenever this loop happens to read it: anchoring on `now`
5930/// would push the reset later on every read and would read an already-elapsed
5931/// reset as still in the future. (A long hint is still clamped by
5932/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5933fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5934    parse_reset_hint_zoned(text, now)
5935        .or_else(|| parse_reset_hint_dated(text))
5936        .or_else(|| parse_reset_hint_relative(text, recorded))
5937}
5938
5939/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5940/// optional but at least one required, in that order. A bare number or any
5941/// unknown unit is refused.
5942fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5943    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5944    let mut rest = rest.trim();
5945    if rest.is_empty() {
5946        return None;
5947    }
5948    let mut total: i64 = 0;
5949    let mut matched = false;
5950    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5951        if let Some((digits, tail)) = rest.split_once(unit)
5952            && !digits.is_empty()
5953            && digits.bytes().all(|b| b.is_ascii_digit())
5954        {
5955            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5956            rest = tail;
5957            matched = true;
5958        }
5959    }
5960    if !rest.is_empty() || !matched {
5961        return None;
5962    }
5963    recorded
5964        .checked_add(jiff::SignedDuration::from_secs(total))
5965        .ok()
5966}
5967
5968/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5969/// case-insensitive) into a 24-hour hour and minute. Shared by every
5970/// reset-hint shape below.
5971fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5972    let clock = clock.trim().to_lowercase();
5973    let (digits, pm) = clock
5974        .strip_suffix("am")
5975        .map(|d| (d, false))
5976        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5977    let (h, m) = digits.trim().split_once(':')?;
5978    let mut hour: i8 = h.trim().parse().ok()?;
5979    let minute: i8 = m.trim().parse().ok()?;
5980    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5981        return None;
5982    }
5983    if pm && hour != 12 {
5984        hour += 12;
5985    } else if !pm && hour == 12 {
5986        hour = 0;
5987    }
5988    Some((hour, minute))
5989}
5990
5991/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5992/// and a zone, never a date. A clock reading already past today is read as
5993/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5994/// the window rolled over while nothing was watching.
5995fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5996    let open = text.find('(')?;
5997    let close = text.rfind(')')?;
5998    if close <= open {
5999        return None;
6000    }
6001    let zone = text[open + 1..close].trim();
6002    let (hour, minute) = parse_12h_clock(&text[..open])?;
6003    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6004    let candidate = now
6005        .to_zoned(tz)
6006        .with()
6007        .hour(hour)
6008        .minute(minute)
6009        .second(0)
6010        .millisecond(0)
6011        .microsecond(0)
6012        .nanosecond(0)
6013        .build()
6014        .ok()?;
6015    let mut at = candidate.timestamp();
6016    if at <= now {
6017        at += jiff::SignedDuration::from_hours(24);
6018    }
6019    Some(at)
6020}
6021
6022/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6023/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6024/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6025/// "already past today" correction to make: the year already disambiguates
6026/// it. Scanned as a five-word window so it can be pulled out of the middle
6027/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6028/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6029/// any other timestamp with no zone attached.
6030fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6031    let words: Vec<&str> = text.split_whitespace().collect();
6032    if words.len() < 5 {
6033        return None;
6034    }
6035    (0..=words.len() - 5)
6036        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6037}
6038
6039/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6040/// parenthesis right after the window is refused rather than ignored — it
6041/// reads as an explicit zone annotation on a shape that otherwise carries
6042/// none, and guessing UTC anyway would be exactly the silent misread this
6043/// module's parsing otherwise avoids.
6044fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6045    if trailing.is_some_and(|next| next.starts_with('(')) {
6046        return None;
6047    }
6048    let month = month_number(window[0])?;
6049    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6050    let day_digits = ["st", "nd", "rd", "th"]
6051        .iter()
6052        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6053    let day: i8 = day_digits.parse().ok()?;
6054    let year_token = window[2];
6055    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6056        return None;
6057    }
6058    let year: i16 = year_token.parse().ok()?;
6059    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6060    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6061    // reusing the same 12-hour clock reader the bracketed shape uses.
6062    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6063    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6064    let date = jiff::civil::Date::new(year, month, day).ok()?;
6065    let candidate = date
6066        .at(hour, minute, 0, 0)
6067        .to_zoned(jiff::tz::TimeZone::UTC)
6068        .ok()?;
6069    Some(candidate.timestamp())
6070}
6071
6072/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6073/// case-insensitively, into a 1-based month number.
6074fn month_number(name: &str) -> Option<i8> {
6075    const NAMES: [&str; 12] = [
6076        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6077    ];
6078    let lower = name.to_lowercase();
6079    NAMES
6080        .iter()
6081        .position(|n| *n == lower.as_str())
6082        .map(|i| i as i8 + 1)
6083}
6084
6085/// Test probe for the shared resume policy's review-budget exclusion.
6086#[cfg(test)]
6087fn exhausted_review_budget(state: &RunState) -> bool {
6088    // A run whose task-head publication failed has nothing left to review:
6089    // resuming it only retries the publication, so it is never "exhausted".
6090    !crate::handover::can_resume(state)
6091        && state.status == RunStatus::Blocked
6092        && !state.released()
6093        && state.retired_to.is_none()
6094}
6095
6096/// This task's *most recent* run, if resuming it would actually make
6097/// progress. `short` is only for the warning's own message.
6098///
6099/// Only ever `runs.last()` — never a search back through older history.
6100/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6101/// mint, oldest first, and every entry before the last one was already
6102/// superseded at the moment it was minted: the daemon only ever starts a new
6103/// run when the previous one was not worth resuming (unresumable, exhausted,
6104/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6105/// opens a fresh review-only run alongside an older, already-failed
6106/// competition. Searching further back would let an old run that merely
6107/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6108/// behind, say — get resumed instead of the fresh competition
6109/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6110/// nothing asked to revisit.
6111///
6112/// Two runs paid for the "prefer resuming over restarting" half of this
6113/// lesson, which is why this still checks `runs.last()` rather than always
6114/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6115/// task a moment later, duplicating two and a half hours of agent work. Then
6116/// b25f stalled on a judge that timed out and one that answered with no JSON
6117/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6118/// **one second** later, buying three fresh implementations to reach the
6119/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6120/// the second case: a stall is terminal, and its cheap recovery re-asks only
6121/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6122/// that is technically `resumable()` but provably cannot progress must not
6123/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6124/// no-op instead of the fresh competition it promises.
6125///
6126/// A load failure is warned about rather than silently read as "not
6127/// resumable": the alternative is exactly what let a schema mismatch on run
6128/// `eba2` fall through to a full re-competition with nobody told why.
6129/// `crate::conduct` is what actually offers a better answer than
6130/// `Runner::start` here (see `Recovery::Review`), once this task's next
6131/// failure shows it up as `held`/`failed` with the run state unreadable.
6132fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6133    unfinished_run_with(runs, short, RunState::load)
6134}
6135
6136/// [`unfinished_run`] with an injected state reader. Tests provide their
6137/// fixtures directly rather than touching the process-global run home.
6138pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6139where
6140    F: FnMut(&str) -> Result<RunState>,
6141{
6142    let mut id = runs.last()?.clone();
6143    let mut visited = std::collections::BTreeSet::new();
6144    let mut repo = None;
6145    loop {
6146        if !runs.contains(&id) || !visited.insert(id.clone()) {
6147            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6148            return None;
6149        }
6150        let state = match load(&id) {
6151            Ok(state) if state.id == id => state,
6152            Ok(_) => return None,
6153            Err(e) => {
6154                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6155                return None;
6156            }
6157        };
6158        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6159            return None;
6160        }
6161        repo = Some(state.repo.clone());
6162        if let Some(authority) = state.retired_to {
6163            id = authority;
6164            continue;
6165        }
6166        return (crate::handover::can_resume(&state)
6167            && state.liveness(false) != crate::run::Liveness::Live)
6168            .then_some(id);
6169    }
6170}
6171
6172/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6173/// that [`attempt`] will resume it on its own?
6174///
6175/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6176/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6177/// injected reader like its sibling. An unreadable run is not awaiting
6178/// anything: it keeps going to the conductor as before.
6179fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6180where
6181    F: FnOnce(&str) -> Result<RunState>,
6182{
6183    // `Failed` stays: a record an older build wrote for a parked run.
6184    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6185        || task.fresh_start
6186        || task.review_branch.is_some()
6187    {
6188        return false;
6189    }
6190    let Some(id) = task.execution_runs().last() else {
6191        return false;
6192    };
6193    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6194}
6195
6196/// Which of the three ways [`attempt`] can mint or continue a run this task
6197/// should use.
6198#[derive(Debug, Clone, PartialEq, Eq)]
6199enum Starter {
6200    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6201    /// and that still exists.
6202    Review(String),
6203    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6204    Resume(String),
6205    /// `crate::graph::Runner::start`: a fresh competition.
6206    Start,
6207}
6208
6209/// A second bound independent of inputs and the resettable failure counter.
6210/// Count execution and failed-startup recovery records once per run. Startup
6211/// failures can retain unrecorded preparation assets without an execution pass.
6212/// Unknown history is not evidence that a new set of worktrees is affordable.
6213fn retained_attempt_hold(
6214    task: &Task,
6215    starter: &Starter,
6216    limit: usize,
6217    mut load: impl FnMut(&str) -> Result<RunState>,
6218) -> Option<String> {
6219    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6220        return None;
6221    }
6222    let mut retained = 0;
6223    for id in task
6224        .runs
6225        .iter()
6226        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6227        .collect::<std::collections::BTreeSet<_>>()
6228    {
6229        let state = match load(id) {
6230            Ok(state) if state.id == *id => state,
6231            _ => {
6232                return Some(format!(
6233                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6234                ));
6235            }
6236        };
6237        if state.retired_to.is_some() || state.released() {
6238            continue;
6239        }
6240        // Neither a completed status nor an empty candidate array proves that
6241        // all recovery sources (including unrecorded preparation) were retired.
6242        retained += 1;
6243    }
6244    (retained >= limit).then(|| format!(
6245        "[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."
6246    ))
6247}
6248
6249/// A selected public implementation overrides every historical candidate and pin.
6250fn selected_starter(
6251    selected: &crate::pr_recovery::Selection,
6252    previous: Option<&RunState>,
6253    unfinished: Option<&str>,
6254) -> Starter {
6255    if let Some(id) = unfinished
6256        && previous.is_some_and(|r| {
6257            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6258        })
6259    {
6260        Starter::Resume(id.to_owned())
6261    } else {
6262        Starter::Review(selected.branch.clone())
6263    }
6264}
6265
6266/// The owner's answer to this branch's divergence question, consumed from the
6267/// task so a later, different divergence asks again. The runner applies it
6268/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6269fn take_divergence_answer(
6270    branch: &str,
6271    remote: &str,
6272    task: &mut Task,
6273) -> Option<crate::reconcile::Choice> {
6274    let summary = crate::reconcile::summary_for(branch, remote);
6275    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6276        (a.question == summary)
6277            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6278            .flatten()
6279            .map(|c| (i, c))
6280    })?;
6281    task.answers.remove(idx);
6282    Some(choice)
6283}
6284
6285/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6286/// this attempt should use. Pure, and separate from [`attempt`], so the
6287/// routing itself is assertable without spawning a real graph or a git
6288/// process: `attempt`'s own `crate::git::branch_exists` call has already
6289/// happened by the time this is called.
6290///
6291/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6292/// whose branch is gone falls all the way through to [`Starter::Start`], not
6293/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6294/// old (likely `Blocked`) run in the first place, and a branch that vanished
6295/// out from under that choice is not evidence resuming it would fare better.
6296fn choose_starter(
6297    review_branch: Option<&str>,
6298    branch_exists: bool,
6299    unfinished: Option<&str>,
6300) -> Starter {
6301    match review_branch {
6302        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6303        Some(_) => Starter::Start,
6304        None => match unfinished {
6305            Some(id) => Starter::Resume(id.to_owned()),
6306            None => Starter::Start,
6307        },
6308    }
6309}
6310
6311/// Reuse a compatible latest review owner instead of taking its checked-out
6312/// branch into a new run. Different branches and changed criteria still use
6313/// the ordinary review/takeover policy.
6314fn review_retry_starter(
6315    task: &Task,
6316    previous: Option<&RunState>,
6317    branch: Option<&str>,
6318    exists: bool,
6319    unfinished: Option<&str>,
6320) -> Starter {
6321    if let Some(run) = previous
6322        && unfinished == Some(run.id.as_str())
6323        && run.reviewed_commits.is_some()
6324        && branch.is_some_and(|branch| {
6325            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6326        })
6327        && may_resume_run(run, task)
6328    {
6329        return Starter::Resume(run.id.clone());
6330    }
6331    match (branch, unfinished, &task.review_of) {
6332        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6333        _ => choose_starter(branch, exists, unfinished),
6334    }
6335}
6336
6337/// Consume a retained review only while its authored criteria still match.
6338fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
6339    let branch = task.review_branch.take();
6340    let instruction = task.review_instruction.take();
6341    branch.filter(|branch| match &instruction {
6342        Some(authored) => *authored == task.instruction,
6343        // Legacy retained branches must agree with their prior run; only an
6344        // explicitly pinned review can proceed without recoverable provenance.
6345        None => previous.map_or_else(
6346            || task.review_of.as_ref() == Some(branch),
6347            |run| compatible_run_instruction(run, task),
6348        ),
6349    })
6350}
6351
6352/// A current explicit pin can select an otherwise incompatible run. Edits
6353/// and subsequent approvals invalidate pins selected for earlier criteria.
6354fn may_resume_run(run: &RunState, task: &Task) -> bool {
6355    if !task.assignment_accepts(run) {
6356        return false;
6357    }
6358    task.resume_override
6359        .as_ref()
6360        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6361        || compatible_run_instruction(run, task)
6362}
6363
6364/// Review scaffolding is execution context, not evidence of an operator edit.
6365pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6366    if let Some(authored) = &run.task_instruction {
6367        return compatible_instruction(authored, task);
6368    }
6369    if compatible_instruction(&run.instruction, task) {
6370        return true;
6371    }
6372    // Recognize only the existing generated review shapes on legacy runs.
6373    // Ordinary authored text with a similar heading is left intact.
6374    if run.reviewed_commits.is_some() {
6375        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6376            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6377        }
6378        if let Some(branch) = &task.review_of {
6379            let canonical = format!(
6380                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6381            );
6382            let generated = format!(
6383                "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"
6384            );
6385            return task.instruction == canonical && run.instruction.starts_with(&generated);
6386        }
6387    }
6388    false
6389}
6390
6391/// Compare authored instructions, excluding answer blocks appended by the daemon.
6392pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6393    strip_answers_block(old, task) == task.instruction
6394}
6395
6396/// Which repository a task runs in. A task that names none — the normal case
6397/// for one filed from a phone — runs in the daemon's own default.
6398fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6399    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6400        return fallback.to_path_buf();
6401    }
6402    task.repo.clone()
6403}
6404
6405/// The header [`append_answers`] appends operator answers under. Shared with
6406/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6407/// rather than grown a new block on every resume.
6408const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6409
6410/// Render the first `count` answers in the block appended to an instruction.
6411fn answers_block(task: &Task, count: usize) -> String {
6412    let mut s = ANSWERS_HEADER.to_owned();
6413    for a in &task.answers[..count] {
6414        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6415    }
6416    s
6417}
6418
6419/// Render the approval independently of transient task state, so historical
6420/// suffixes remain recognizable after another explicit release.
6421fn resumption_block(r: &crate::queue::Resumption) -> String {
6422    format!(
6423        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6424         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6425        r.generation, r.at, r.instruction, r.answers_through,
6426    )
6427}
6428
6429/// Append audit answers and the latest explicit approval to the instruction.
6430fn append_answers(base: &str, task: &Task) -> String {
6431    let mut s = base.to_owned();
6432    if !task.answers.is_empty() {
6433        s.push_str(&answers_block(task, task.answers.len()));
6434    }
6435    if let Some(r) = &task.resumption {
6436        s.push_str(&resumption_block(r));
6437    }
6438    s
6439}
6440
6441/// Drop the prior answer block only when it is exactly the suffix this task
6442/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6443/// the task author is ordinary instruction text, not a block to remove.
6444fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6445    let mut instruction = instruction;
6446    for approval in task
6447        .resumption
6448        .iter()
6449        .chain(task.resumption_history.iter().rev())
6450    {
6451        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6452            instruction = base;
6453            break;
6454        }
6455    }
6456    for count in (1..=task.answers.len()).rev() {
6457        let block = answers_block(task, count);
6458        if let Some(base) = instruction.strip_suffix(&block) {
6459            return base;
6460        }
6461    }
6462    instruction
6463}
6464
6465/// The instruction handed to `Runner::start`: the task's own text, plus any
6466/// operator answers `crate::conduct` collected for it (see
6467/// [`Task::answers`]), so a decision the operator actually made reaches the
6468/// implementers rather than only clearing the block that was waiting on it.
6469///
6470/// Appended rather than merged into [`Task::instruction`] itself, so the
6471/// task's own record stays exactly what its author wrote.
6472fn instruction_for(task: &Task) -> String {
6473    append_answers(&task.instruction, task)
6474}
6475
6476/// The instruction a resumed run should carry on with: whatever it already
6477/// had, refreshed with the task's *current* operator answers.
6478///
6479/// A resumable run's own `RunState::instruction` predates any answer
6480/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6481/// the behaviour before this function existed — silently drops the very
6482/// decision the operator made to unblock it. Re-stripping any block this
6483/// function appended on an earlier resume before re-appending the current
6484/// list (rather than blindly appending again) is what keeps a task resumed
6485/// three times over three answered questions from carrying the same answer
6486/// three times.
6487fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6488    append_answers(strip_answers_block(old_instruction, task), task)
6489}
6490
6491/// Preserve the producer's verified boundary and target, independent of prose.
6492fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6493    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6494    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6495    if let Some(cause) = task.hold_notice_cause.as_mut() {
6496        cause.target = failure.map(|f| f.target.clone());
6497    }
6498}
6499
6500#[derive(Debug, thiserror::Error)]
6501#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6502struct MissingAttachment {
6503    name: String,
6504    path: PathBuf,
6505}
6506
6507/// The task's attachments as absolute paths, each checked to still exist.
6508fn task_attachments(
6509    queue: &Queue,
6510    task: &Task,
6511) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6512    let paths = queue.attachment_paths(task);
6513    for (name, path) in task.attachments.iter().zip(&paths) {
6514        if !path.is_file() {
6515            return Err(MissingAttachment {
6516                name: name.clone(),
6517                path: path.clone(),
6518            });
6519        }
6520    }
6521    Ok(paths)
6522}
6523
6524/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6525/// answers before handing it to `Runner` — the actual boundary between
6526/// [`choose_starter`]'s routing and the graph, factored out so it is
6527/// assertable without a real repository, git branch, or agent CLI.
6528///
6529/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6530/// instruction from the reviewed branch's own commit log because there is no
6531/// task statement to speak of for hand-written work, and splicing operator
6532/// answers into that text would contradict the very message it sends
6533/// reviewers ("there is no task statement").
6534fn prepare_instruction(
6535    starter: &Starter,
6536    old_instruction: Option<&str>,
6537    task: &Task,
6538) -> Option<String> {
6539    match starter {
6540        Starter::Start => Some(instruction_for(task)),
6541        Starter::Resume(_) => Some(resumed_instruction(
6542            old_instruction.expect("a resumed run always has a prior instruction"),
6543            task,
6544        )),
6545        Starter::Review(_) => None,
6546    }
6547}
6548
6549/// Persist a transition. A queue write failure is logged rather than fatal: the
6550/// run already happened, and taking the daemon down would only add a lost
6551/// backlog to a full disk.
6552fn record(queue: &Queue, task: &mut Task) {
6553    if let Err(e) = queue.put(task) {
6554        tracing::error!("could not record task {}: {e:#}", task.short());
6555        let notice = Notice::error(
6556            "loop:record",
6557            format!(
6558                "Task {} state could not be saved: {}. Check the disk.",
6559                task.id,
6560                e.to_string().lines().next().unwrap_or("unknown save error")
6561            ),
6562        )
6563        .link(Link::Task {
6564            id: task.id.clone(),
6565        });
6566        // The queue lives at `<home>/queue`, so its parent is the home.
6567        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6568            Some(home) => notices::raise_in(home, notice),
6569            None => notices::raise(notice),
6570        }
6571    }
6572}
6573
6574/// Every runnable task, in the order the loop should try them.
6575///
6576/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6577/// tail exists so that a claim somebody else holds costs the loop the next
6578/// candidate rather than a whole poll interval of idleness.
6579fn runnable(queue: &Queue) -> Vec<Task> {
6580    let mut tasks: Vec<Task> = queue
6581        .list()
6582        .into_iter()
6583        .filter(|t| t.status.runnable())
6584        .collect();
6585    tasks.sort_unstable_by(crate::queue::dispatch_order);
6586    tasks
6587}
6588
6589/// Why a run ended where it did, in one line, for [`Task::last_error`].
6590///
6591/// A stalled run names the seats the quota took out: "out of quota" is not
6592/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6593/// agent to replace or which plan to top up.
6594///
6595/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6596/// purpose: unlike `label`'s other callers (an internal log line, an
6597/// already-a-bug fallback message), this string becomes `Task::last_error`
6598/// verbatim, which the phone renders in the same alarm-styled box an
6599/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6600/// `.err` styling. A bare `verified_noop` there would read exactly like the
6601/// failure this whole feature exists to tell apart from one.
6602fn describe(state: &RunState) -> String {
6603    let p = phrases(&state.config.graph.language);
6604    let mut detail = if state.status == RunStatus::Stalled {
6605        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6606        seats.sort_unstable();
6607        seats.dedup();
6608        if seats.is_empty() {
6609            p.quorum_lost.to_owned()
6610        } else {
6611            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6612        }
6613    } else {
6614        format!("{}{}", p.run_ended, state.status.display_label())
6615    };
6616    if let Some(cause) = state.verification_blocking_cause() {
6617        detail.push_str(&format!(" ({cause})"));
6618    } else if let Some(last) = state.events.last() {
6619        // The review loop's "never answered" stop is the one event worth
6620        // translating; it is recognised from structured state, not by
6621        // matching the English event text (which stays as recorded).
6622        let unanswered = state
6623            .reviews
6624            .last()
6625            .filter(|r| {
6626                state.status == RunStatus::Blocked
6627                    && last.node == "review"
6628                    && r.incomplete()
6629                    && r.blocking == 0
6630                    && r.round == state.config.graph.review_rounds
6631                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6632            })
6633            .map(|r| (r.expected - r.answered, r.round));
6634        match unanswered {
6635            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6636                detail.push_str(&format!(
6637                    " ({}: {})",
6638                    last.node,
6639                    (p.reviewers_never_answered)(missing, rounds)
6640                ));
6641            }
6642            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6643        }
6644    }
6645    detail.push_str(&format!(" [run {}]", state.id));
6646    detail
6647}
6648
6649/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6650///
6651/// The task file lives in the backlog indefinitely; a diagnostic is an
6652/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6653/// stay small regardless of how much a gate command or a candidate printed.
6654const DIAGNOSTIC_MAX: usize = 4_000;
6655
6656/// Tail kept from a single failing command's output inside a diagnostic.
6657/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6658/// pointer for a human deciding whether to go read the full artifact by hand,
6659/// not a replacement for reading it.
6660const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6661
6662/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6663/// `magi task show` says more than the one-line reason in [`describe`].
6664///
6665/// The one-liner answers "where did the run stop"; this answers "what would a
6666/// human have found opening `artifacts/` by hand" — the point of the whole
6667/// feature is the case that one-liner actively misleads on: a run held as "no
6668/// candidate produced a change" can mean the implementer actually finished
6669/// the task (opened a PR, merged it, tagged a release) and only left a clean
6670/// local worktree behind, which reads as "nothing happened" unless someone
6671/// goes and reads what the agent actually said. `None` when the run carries
6672/// none of the three shapes this recognises — an ordinary run held for
6673/// something not diagnosable from `RunState` alone still explains itself
6674/// through `Task::last_error`.
6675fn diagnostic(state: &RunState) -> Option<String> {
6676    let mut parts: Vec<String> = Vec::new();
6677
6678    // Gate failure: which check(s), and the tail of what each printed.
6679    for o in state.gate.iter().filter(|o| !o.ok()) {
6680        parts.push(format!(
6681            "gate `{}` failed ({}):\n{}",
6682            o.command,
6683            notices::exit_status(o.code),
6684            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6685        ));
6686    }
6687
6688    // The land loop gave up because the fixer declined while checks were
6689    // still red: the message already names them (see `land::run`).
6690    if let Some(last) = state
6691        .events
6692        .iter()
6693        .rev()
6694        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6695    {
6696        parts.push(last.message.clone());
6697    }
6698
6699    // No viable candidate: every implementer's own final word, sanitized the
6700    // same way a judge would have read it, so a run that actually finished
6701    // the job does not read as an unexplained failure. A verified no-op is
6702    // called out ahead of its own summary and apart from an ordinary
6703    // failure's `why` — this is the one candidate shape whose diagnostic a
6704    // human is expected to actually judge, not just skim.
6705    if state.viable().is_empty() {
6706        for c in &state.candidates {
6707            if let Some(evidence) = &c.verified_noop {
6708                parts.push(format!(
6709                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6710                    c.label
6711                ));
6712            } else if !c.summary.trim().is_empty() {
6713                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6714            } else if let Some(why) = &c.failed {
6715                parts.push(format!("candidate {}: {why}", c.label));
6716            }
6717        }
6718    }
6719
6720    if parts.is_empty() {
6721        return None;
6722    }
6723    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6724    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6725    // back slightly over. Leave it enough room to always land under the
6726    // limit.
6727    Some(crate::run::tail(
6728        &parts.join("\n\n"),
6729        DIAGNOSTIC_MAX.saturating_sub(100),
6730    ))
6731}
6732
6733/// Stable lower-case name for a run status, for an internal log line and the
6734/// "graph stopped without reaching a terminal status" bug message in
6735/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6736/// doc for why that one reads [`RunStatus::display_label`] instead. One
6737/// definition of a status's name, on the type that owns it: this table used
6738/// to live here as a second copy, and a status renamed in one place would
6739/// have gone on reading correctly in the other.
6740fn label(status: RunStatus) -> &'static str {
6741    status.as_str()
6742}
6743
6744/// Parse a merge mode override.
6745pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6746    match mode {
6747        "none" => Ok(MergeMode::None),
6748        "local" => Ok(MergeMode::Local),
6749        "pr" => Ok(MergeMode::Pr),
6750        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6751    }
6752}
6753
6754/// Take the status lock, recovering from a poisoned one.
6755///
6756/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6757/// data, and the worst a poisoned lock can hold is a stale timestamp.
6758fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6759    mutex
6760        .lock()
6761        .unwrap_or_else(std::sync::PoisonError::into_inner)
6762}
6763
6764#[cfg(test)]
6765mod tests {
6766    use super::*;
6767    use crate::queue::{Source, TaskStatus};
6768    use crate::run::{Candidate, CommandOutcome};
6769    use pretty_assertions::assert_eq;
6770
6771    fn task() -> Task {
6772        Task::new(
6773            "add retries".to_owned(),
6774            "add retries".to_owned(),
6775            PathBuf::from("/repo"),
6776            Source::Human,
6777        )
6778    }
6779
6780    #[test]
6781    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
6782        let skips = DispatchSkips::from([
6783            ("a".into(), SkipReason::CoolingDown),
6784            ("b".into(), SkipReason::WaitingOnLanding),
6785            ("c".into(), SkipReason::WaitingOnLanding),
6786            ("d".into(), SkipReason::OrdinaryCapacity),
6787        ]);
6788        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
6789        assert_eq!(wait.runnable, 4);
6790        assert_eq!(
6791            wait.reasons
6792                .iter()
6793                .map(|r| (r.reason.as_str(), r.count))
6794                .collect::<Vec<_>>(),
6795            [
6796                ("waiting_on_landing", 2),
6797                ("cooling_down", 1),
6798                ("ordinary_capacity", 1)
6799            ]
6800        );
6801        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
6802        assert!(
6803            aggregate_dispatch_wait(2, &DispatchSkips::new())
6804                .unwrap()
6805                .reasons
6806                .is_empty()
6807        );
6808    }
6809
6810    #[test]
6811    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
6812        let before = vec!["a".into(), "b".into(), "c".into()];
6813        let allowed = vec![task_with_id("b")];
6814        let skips = interrupt_skips(&before, &allowed);
6815        assert_eq!(
6816            skips,
6817            DispatchSkips::from([
6818                ("a".into(), SkipReason::InterruptGate),
6819                ("c".into(), SkipReason::InterruptGate),
6820            ])
6821        );
6822        let mut previous = DispatchSkips::new();
6823        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
6824        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
6825        assert!(!changed_dispatch_skips(&mut previous, skips));
6826        assert!(changed_dispatch_skips(
6827            &mut previous,
6828            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
6829        ));
6830        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
6831    }
6832
6833    #[test]
6834    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
6835        let mut value = serde_json::to_value(Status::new()).unwrap();
6836        value.as_object_mut().unwrap().remove("dispatch_wait");
6837        assert!(
6838            serde_json::from_value::<Status>(value.clone())
6839                .unwrap()
6840                .dispatch_wait
6841                .is_none()
6842        );
6843        assert!(
6844            serde_json::from_value::<Reading>(value.clone())
6845                .unwrap()
6846                .dispatch_wait
6847                .is_none()
6848        );
6849        value["dispatch_wait"] = serde_json::json!({
6850            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
6851        });
6852        let reading = serde_json::from_value::<Reading>(value).unwrap();
6853        assert_eq!(
6854            reading.dispatch_wait.unwrap().reasons[0].reason,
6855            "future_reason"
6856        );
6857    }
6858
6859    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6860        let job = crate::worker::Job {
6861            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6862            sequence: 1,
6863            kind: "task".into(),
6864            key: format!("task:{}", request.task),
6865            payload: serde_json::to_value(request).unwrap(),
6866            generation: "a".repeat(64),
6867            version: None,
6868            status: crate::worker::Status::Starting,
6869            result: None,
6870            pid: None,
6871            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6872            finished_at: None,
6873        };
6874        let dir = home.join("workers/jobs").join(&job.id);
6875        std::fs::create_dir_all(&dir).unwrap();
6876        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6877        job
6878    }
6879
6880    #[test]
6881    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6882        let home = tempfile::tempdir().unwrap();
6883        let request = TaskWorker {
6884            opts: Opts::default(),
6885            queue: home.path().join("queue"),
6886            task: "startup".into(),
6887            lane: PermitKind::Ordinary,
6888            standalone: false,
6889        };
6890        let job = starting_task_reservation(home.path(), &request);
6891        let error = task_worker_spawn_error(
6892            home.path(),
6893            &request,
6894            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6895        )
6896        .expect_err("our own reservation must not turn a failed spawn into a resync");
6897        let active = crate::worker::active(home.path()).unwrap();
6898        assert_eq!(active.len(), 1);
6899        assert_eq!(active[0].id, job.id);
6900        assert_eq!(active[0].status, crate::worker::Status::Starting);
6901        assert!(
6902            crate::worker::control(home.path(), &job.key)
6903                .unwrap()
6904                .is_none()
6905        );
6906        let notices = notices::Notices::at(home.path().join("notifications")).list();
6907        assert_eq!(notices.len(), 1);
6908        assert_eq!(notices[0].key, "loop:worker-startup");
6909        assert!(!notices[0].message.contains("private-error-detail"));
6910        assert!(notices[0].message.contains(&request.task));
6911        assert!(
6912            notices[0]
6913                .message
6914                .contains("could not be started or acknowledged")
6915        );
6916        assert!(notices[0].message.contains("worker.log"));
6917        assert_eq!(
6918            notices[0].link,
6919            Some(Link::Task {
6920                id: request.task.clone()
6921            })
6922        );
6923        assert!(format!("{error:#}").contains("private-error-detail"));
6924    }
6925
6926    #[test]
6927    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6928        let home = tempfile::tempdir().unwrap();
6929        let mut request = TaskWorker {
6930            opts: Opts::default(),
6931            queue: home.path().join("queue"),
6932            task: "handoff".into(),
6933            lane: PermitKind::Ordinary,
6934            standalone: true,
6935        };
6936        let job = starting_task_reservation(home.path(), &request);
6937        request.standalone = false;
6938        task_worker_spawn_error(
6939            home.path(),
6940            &request,
6941            anyhow::anyhow!("operation key is already reserved for a different request"),
6942        )
6943        .expect("a different standalone request is the handoff race, not our startup failure");
6944        let active = crate::worker::active(home.path()).unwrap();
6945        assert_eq!(active.len(), 1);
6946        assert_eq!(active[0].id, job.id);
6947        assert_eq!(active[0].payload, job.payload);
6948        assert!(
6949            notices::Notices::at(home.path().join("notifications"))
6950                .list()
6951                .is_empty()
6952        );
6953    }
6954
6955    #[test]
6956    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6957        let home = tempfile::tempdir().unwrap();
6958        let queue = Queue::at(home.path().join("queue"));
6959        let mut task = task();
6960        task.runs = vec!["previous".into()];
6961        queue.put(&mut task).unwrap();
6962        let request = TaskWorker {
6963            opts: Opts::default(),
6964            queue: home.path().join("queue"),
6965            task: task.id.clone(),
6966            lane: PermitKind::Ordinary,
6967            standalone: false,
6968        };
6969        let job = starting_task_reservation(home.path(), &request);
6970        let claims = current_work(home.path(), Timestamp::now());
6971        assert_eq!(claims.len(), 1);
6972        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6973        assert_eq!(claims[0].run, "previous");
6974        assert!(other_claims_run(&claims, "previous", None));
6975        // Only after confirming the executing caller may admission ignore
6976        // this exact projection. Cleanup continues to observe it as live.
6977        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6978        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6979    }
6980
6981    #[test]
6982    fn admission_excludes_only_the_callers_exact_reservation() {
6983        let own = Current {
6984            worker: Some("own".into()),
6985            task: "same-task".into(),
6986            run: "previous".into(),
6987        };
6988        assert!(!other_claims_run(
6989            std::slice::from_ref(&own),
6990            "previous",
6991            Some("own")
6992        ));
6993        assert!(other_claims_run(
6994            std::slice::from_ref(&own),
6995            "previous",
6996            None
6997        ));
6998        for worker in [None, Some("other".into())] {
6999            let other = Current {
7000                worker,
7001                ..own.clone()
7002            };
7003            assert!(other_claims_run(
7004                &[own.clone(), other],
7005                "previous",
7006                Some("own")
7007            ));
7008        }
7009        let legacy: Current =
7010            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7011        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7012    }
7013
7014    #[test]
7015    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7016        let mut task = task();
7017        let mut run = run_state(RunStatus::Reviewing);
7018        run.task_instruction = Some(task.instruction.clone());
7019        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7020        let branch = "magi/test/B";
7021        run.candidates.push(crate::run::Candidate {
7022            branch: branch.into(),
7023            ..candidate('B', "preserved work", false, None)
7024        });
7025        task.runs = vec![run.id.clone()];
7026        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7027        assert_eq!(
7028            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7029            Starter::Resume(run.id.clone())
7030        );
7031        assert!(matches!(
7032            review_retry_starter(
7033                &task,
7034                Some(&run),
7035                Some("different"),
7036                true,
7037                unfinished.as_deref()
7038            ),
7039            Starter::Review(_)
7040        ));
7041        assert_eq!(
7042            review_retry_starter(
7043                &task,
7044                Some(&run),
7045                Some(branch),
7046                false,
7047                unfinished.as_deref()
7048            ),
7049            Starter::Start
7050        );
7051        task.instruction.push_str(" changed criteria");
7052        assert!(matches!(
7053            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7054            Starter::Review(_)
7055        ));
7056        assert!(matches!(
7057            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7058            Starter::Review(_)
7059        ));
7060    }
7061
7062    #[test]
7063    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7064        let dir = tempfile::tempdir().unwrap();
7065        let queue = Queue::at(dir.path().join("queue"));
7066        let mut task = task();
7067        task.status = TaskStatus::Running;
7068        task.attempts = 1;
7069        queue.put(&mut task).unwrap();
7070        let live = std::collections::BTreeSet::from([task.id.clone()]);
7071        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7072        drop(queue.claim(&task.id).unwrap());
7073        let saved = queue.get(&task.id).unwrap();
7074        assert_eq!(saved.status, TaskStatus::Running);
7075        assert_eq!(saved.attempts, 1);
7076        assert!(saved.last_error.is_none());
7077    }
7078
7079    #[test]
7080    fn standalone_workers_do_not_consume_scheduler_lanes() {
7081        let request = |task: &str, lane, standalone| TaskWorker {
7082            opts: Opts::default(),
7083            queue: PathBuf::from("/queue"),
7084            task: task.to_owned(),
7085            lane,
7086            standalone,
7087        };
7088        let mut jobs = vec![
7089            request("ordinary", PermitKind::Ordinary, false),
7090            request("standalone-urgent", PermitKind::Urgent, true),
7091            request("standalone-ordinary", PermitKind::Ordinary, true),
7092            request("decision", PermitKind::None, false),
7093        ];
7094        assert_eq!(available_slots(&jobs, 2), (1, 1));
7095        jobs.push(request("urgent", PermitKind::Urgent, false));
7096        assert_eq!(available_slots(&jobs, 2), (1, 0));
7097        assert_eq!(available_slots(&jobs, 0), (0, 0));
7098    }
7099
7100    #[test]
7101    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7102        let now = Timestamp::now();
7103        let mut reading = Reading {
7104            pid: Some(std::process::id()),
7105            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7106            ..Reading::default()
7107        };
7108        assert!(!reading.running(now));
7109        assert!(legacy_scheduler_running(&reading, now, 0));
7110        reading.worker_protocol = Some(1);
7111        assert!(!legacy_scheduler_running(&reading, now, 0));
7112    }
7113
7114    #[test]
7115    fn selected_public_head_overrides_historical_resume_and_pin() {
7116        let mut t = task();
7117        let mut old = run_state(RunStatus::Blocked);
7118        let selection = crate::pr_recovery::Selection {
7119            url: "url".into(),
7120            branch: format!("magi/task-{}", t.id),
7121            head: "a".repeat(40),
7122            source_head: None,
7123            source_run: None,
7124            source_proof: None,
7125            disposition: Some(crate::pr_recovery::Disposition::Review),
7126            instruction: t.instruction.clone(),
7127            approved_at: Timestamp::now(),
7128        };
7129        t.resume_override = Some(crate::queue::OperatorResume {
7130            pinned_run: Some(old.id.clone()),
7131            question_id: "choice".into(),
7132            at: Timestamp::now(),
7133            conductor_rehold: None,
7134            forced: false,
7135        });
7136        assert_eq!(
7137            selected_starter(&selection, Some(&old), Some(&old.id)),
7138            Starter::Review(selection.branch.clone())
7139        );
7140        old.pr_recovery = Some(selection.clone());
7141        assert_eq!(
7142            selected_starter(&selection, Some(&old), Some(&old.id)),
7143            Starter::Review(selection.branch.clone())
7144        );
7145        old.reviewed_commits = Some(vec!["implementation".into()]);
7146        assert_eq!(
7147            selected_starter(&selection, Some(&old), Some(&old.id)),
7148            Starter::Resume(old.id.clone())
7149        );
7150        let mut changed = selection.clone();
7151        changed.head = "b".repeat(40);
7152        assert_eq!(
7153            selected_starter(&changed, Some(&old), Some(&old.id)),
7154            Starter::Review(changed.branch)
7155        );
7156    }
7157
7158    #[test]
7159    fn candidate_transplant_failure_is_one_actionable_hold() {
7160        let dir = tempfile::tempdir().unwrap();
7161        let q = Queue::at(dir.path().join("queue"));
7162        let mut t = task();
7163        let mut state = run_state(RunStatus::Blocked);
7164        state.event("prep", "cannot apply referenced commit: conflict");
7165        state.prep_failure = Some("conflict".into());
7166        t.start(state.id.clone());
7167        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7168        assert_eq!(t.attempts, 1);
7169        assert_eq!(t.status, TaskStatus::Held);
7170        assert!(t.operator_held());
7171        assert!(!t.status.runnable());
7172        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7173        let first = t.chat_notice_key().unwrap();
7174        t.chat_notices.push(first.clone());
7175        t.release_operator("test", None);
7176        state.id = "another-unprepared-run".into();
7177        t.start(state.id.clone());
7178        finish_attempt(
7179            3,
7180            &q,
7181            &mut t,
7182            &state,
7183            &[],
7184            Err(anyhow::anyhow!("still conflicts")),
7185        );
7186        assert_eq!(
7187            t.chat_notice_key().as_ref(),
7188            Some(&first),
7189            "no work happened"
7190        );
7191        t.release_operator("test", None);
7192        state.prep_failure = None;
7193        state.status = RunStatus::Failed;
7194        state.begin_pass();
7195        t.start(state.id.clone());
7196        finish_attempt(
7197            1,
7198            &q,
7199            &mut t,
7200            &state,
7201            &[],
7202            Err(anyhow::anyhow!("new gate failure")),
7203        );
7204        let failure = t.chat_notice_key().unwrap();
7205        assert_ne!(failure, first, "approved recovery reached a real failure");
7206        t.release_operator("test", None);
7207        state.begin_pass();
7208        t.start(state.id.clone());
7209        finish_attempt(
7210            1,
7211            &q,
7212            &mut t,
7213            &state,
7214            &[],
7215            Err(anyhow::anyhow!("new failure on resume")),
7216        );
7217        assert_ne!(
7218            t.chat_notice_key().as_ref(),
7219            Some(&failure),
7220            "a new settled pass"
7221        );
7222    }
7223
7224    #[test]
7225    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7226        for source in ["cli", "web"] {
7227            let mut t = task();
7228            let mut run = run_state(RunStatus::Blocked);
7229            run.instruction = "Run A original criteria".into();
7230            run.task_instruction = Some(run.instruction.clone());
7231            t.start(run.id.clone());
7232            t.release_operator("choice", Some("resume-question"));
7233            t.resume_override = Some(crate::queue::OperatorResume {
7234                question_id: "resume-question".into(),
7235                at: Timestamp::now(),
7236                conductor_rehold: None,
7237                forced: true,
7238                pinned_run: Some(run.id.clone()),
7239            });
7240            t.hold_machine(Some("not enough free space to start a run".into()));
7241            let mut unchanged = t.clone();
7242            unchanged
7243                .edit("title changed".into(), unchanged.instruction.clone())
7244                .unwrap();
7245            unchanged.release_operator(source, None);
7246            assert_eq!(
7247                unchanged
7248                    .resume_override
7249                    .as_ref()
7250                    .unwrap()
7251                    .pinned_run
7252                    .as_deref(),
7253                Some(run.id.as_str())
7254            );
7255            assert!(!compatible_run_instruction(&run, &unchanged));
7256            assert!(may_resume_run(&run, &unchanged));
7257
7258            t.edit(
7259                "approved recovery".into(),
7260                "Reuse measured PR head B; fix Clippy; review".into(),
7261            )
7262            .unwrap();
7263            assert!(t.resume_override.is_none());
7264            t.release_operator(source, None);
7265            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7266            assert!(reloaded.resume_override.is_none());
7267            assert!(!may_resume_run(&run, &reloaded));
7268            let unfinished =
7269                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7270                    .filter(|_| may_resume_run(&run, &reloaded));
7271            assert_eq!(
7272                choose_starter(None, false, unfinished.as_deref()),
7273                Starter::Start
7274            );
7275            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7276            assert_eq!(
7277                reloaded.resumption_history[0].question_id.as_deref(),
7278                Some("resume-question")
7279            );
7280
7281            // A revision already persisted with the old approval/pin is also
7282            // invalidated when the new operator release is recorded.
7283            unchanged.instruction = "Reuse measured PR head B".into();
7284            unchanged.hold_machine(Some("disk hold".into()));
7285            unchanged.release_operator(source, None);
7286            assert!(unchanged.resume_override.is_none());
7287            assert!(!may_resume_run(&run, &unchanged));
7288        }
7289    }
7290
7291    #[test]
7292    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7293        let mut t = task();
7294        let mut run = run_state(RunStatus::Blocked);
7295        t.review_of = Some("approved-head".into());
7296        t.instruction =
7297            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7298                .into();
7299        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();
7300        run.reviewed_commits = Some(vec!["Commit log".into()]);
7301        t.start(run.id.clone());
7302        t.hold_machine(Some("interrupted review".into()));
7303        t.release_operator("cli", None);
7304        assert!(
7305            compatible_run_instruction(&run, &t),
7306            "legacy explicit review remains resumable"
7307        );
7308        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7309            .filter(|_| compatible_run_instruction(&run, &t));
7310        assert_eq!(
7311            choose_starter(None, false, unfinished.as_deref()),
7312            Starter::Resume(run.id.clone())
7313        );
7314        run.task_instruction = Some(t.instruction.clone());
7315        assert!(compatible_run_instruction(&run, &t));
7316        let reloaded: RunState =
7317            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7318        assert!(compatible_run_instruction(&reloaded, &t));
7319        t.edit(
7320            "new approved head".into(),
7321            "Reuse measured PR head B".into(),
7322        )
7323        .unwrap();
7324        assert!(!compatible_run_instruction(&run, &t));
7325
7326        // Legacy recovery reviews retain the task criteria ahead of the log.
7327        t.review_of = None;
7328        t.instruction = "Fix Clippy on approved head".into();
7329        run.task_instruction = None;
7330        run.instruction = format!(
7331            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7332            t.instruction
7333        );
7334        assert!(compatible_run_instruction(&run, &t));
7335        t.instruction.push('\n');
7336        assert!(
7337            compatible_run_instruction(&run, &t),
7338            "legacy generated review trimmed the original criteria"
7339        );
7340        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7341        let mut unchanged = t.clone();
7342        assert_eq!(
7343            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
7344            Some("approved-head")
7345        );
7346        t.edit("new plan".into(), "Reuse measured PR head B".into())
7347            .unwrap();
7348        assert!(take_review_branch(&mut t, Some(&run)).is_none());
7349        assert!(!compatible_run_instruction(&run, &t));
7350        t.review_branch = Some("approved-head".into());
7351        t.review_instruction = None;
7352        assert!(
7353            take_review_branch(&mut t, Some(&run)).is_none(),
7354            "legacy retained candidate cannot replace a revised approved head"
7355        );
7356    }
7357
7358    #[test]
7359    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7360        let home = crate::run::test_home();
7361        crate::run::pin_test_home();
7362        let dir = tempfile::tempdir().unwrap();
7363        let queue = Queue::at(dir.path().join("queue"));
7364        for resume in [true, false] {
7365            let state = run_state(RunStatus::Blocked);
7366            let mut t = task();
7367            t.start(state.id.clone());
7368            let action = if resume {
7369                ask::ChoiceAction::Resume {
7370                    run: state.id.clone(),
7371                }
7372            } else {
7373                ask::ChoiceAction::Requeue
7374            };
7375            let mut q = action_question(&state.id, action);
7376            q.status = ask::QuestionStatus::Open;
7377            q.answer = None;
7378            q.answered_at = None;
7379            t.fail("run stopped with a question", 3);
7380            hold_if_runnable(&queue, &mut t);
7381            assert!(t.operator_decided_at.is_none());
7382            assert!(t.operator_held());
7383            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7384            let expected = if resume {
7385                ActionDecision::Resume(state.id.clone())
7386            } else {
7387                ActionDecision::Requeue
7388            };
7389            assert_eq!(
7390                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7391                expected
7392            );
7393            t.hold_manual(Some("later explicit hold".into()));
7394            assert_eq!(
7395                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7396                ActionDecision::Stale
7397            );
7398        }
7399    }
7400
7401    #[test]
7402    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7403        let mut t = task();
7404        t.answers.push(crate::queue::AnsweredQuestion {
7405            question: "Inspect the remote?".into(),
7406            answer: "Inspect then wait".into(),
7407        });
7408        let old = instruction_for(&t);
7409        assert!(compatible_instruction(&old, &t));
7410        t.instruction = "Reuse approved PR head and review".into();
7411        t.release_operator("cli", None);
7412        assert!(!compatible_instruction(&old, &t));
7413        let approved = instruction_for(&t);
7414        assert!(approved.contains("waiting premises are superseded"));
7415        assert!(compatible_instruction(&approved, &t));
7416        assert_eq!(resumed_instruction(&approved, &t), approved);
7417        t.release_operator("web", None);
7418        assert!(compatible_instruction(&approved, &t));
7419        assert_eq!(t.resumption_history.len(), 1);
7420        t.start("run".into());
7421        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7422    }
7423
7424    /// A run that stopped on an infrastructure wait asked no agent anything:
7425    /// the task is held by the machine under a `[resource]` reason (resumable,
7426    /// re-checked by triage), and the attempt it started is given back.
7427    #[test]
7428    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7429        let mut state = RunState::new(
7430            PathBuf::from("/repo"),
7431            "main".into(),
7432            "base".into(),
7433            "task".into(),
7434            Config::default(),
7435        );
7436        state.status = RunStatus::Landing;
7437        state.parked = true;
7438        state.pr_pushed_head = Some("head".into());
7439        state.land_unrelated = Some(
7440            serde_json::from_value(serde_json::json!({
7441                "head": "head", "question": "ci-question",
7442                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7443            }))
7444            .unwrap(),
7445        );
7446        let mut t = task();
7447        t.start(state.id.clone());
7448        let verdict = Verdict {
7449            status: RunStatus::Landing,
7450            left_pr: true,
7451            quota_hit: false,
7452            parked: true,
7453            no_viable_candidates: false,
7454        };
7455        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7456        assert_eq!(t.attempts, 0);
7457        assert_eq!(t.status, TaskStatus::Held);
7458        assert!(!t.operator_held());
7459        assert!(
7460            t.hold_reason
7461                .as_deref()
7462                .unwrap()
7463                .starts_with("[ci-unrelated]")
7464        );
7465        // A second settlement must not refund an earlier task attempt.
7466        t.attempts = 1;
7467        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7468        assert_eq!(t.attempts, 1);
7469        assert_eq!(t.passes.len(), 1);
7470        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7471        state.pr_pushed_head = Some("new-head".into());
7472        state.parked = false;
7473        state.status = RunStatus::Blocked;
7474        let stale = Verdict {
7475            status: RunStatus::Blocked,
7476            parked: false,
7477            ..verdict
7478        };
7479        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7480        assert_eq!(t.attempts, 1);
7481        // A new execution pass can refund its own newly charged attempt.
7482        state.begin_pass();
7483        state.begin_pass();
7484        state.status = RunStatus::Landing;
7485        state.parked = true;
7486        state.pr_pushed_head = Some("head".into());
7487        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7488        assert_eq!(t.attempts, 0);
7489        assert_eq!(t.passes.len(), 2);
7490    }
7491
7492    #[test]
7493    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7494        let mut state = run_state(RunStatus::Failed);
7495        state
7496            .quota
7497            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7498        state.begin_pass();
7499        let mut t = task();
7500        t.start(state.id.clone());
7501        reclaim(&mut t, Some(state), 2, "en");
7502        assert_eq!(t.attempts, 1);
7503    }
7504
7505    #[test]
7506    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7507        let mut state = run_state(RunStatus::Blocked);
7508        let losses: Vec<_> = ["alpha", "beta"]
7509            .into_iter()
7510            .enumerate()
7511            .map(|(i, agent)| {
7512                QuotaLoss::from_report(
7513                    format!("advisor-{i}"),
7514                    "advise",
7515                    Some(&crate::agent::Quota {
7516                        cause: crate::agent::QuotaCause::Authentication,
7517                        agent: agent.to_owned(),
7518                        reset: None,
7519                    }),
7520                )
7521            })
7522            .collect();
7523        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7524        state.quota = losses;
7525        let mut t = task();
7526        t.start(state.id.clone());
7527        let verdict = Verdict {
7528            status: state.status,
7529            left_pr: false,
7530            quota_hit: true,
7531            parked: false,
7532            no_viable_candidates: true,
7533        };
7534        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7535        assert_eq!(t.attempts, 0);
7536        assert_eq!(t.status, TaskStatus::Held);
7537        assert!(!t.operator_held());
7538        let reason = t.hold_reason.as_deref().unwrap();
7539        assert!(reason.starts_with("[authentication]"));
7540        assert!(
7541            reason.contains("alpha")
7542                && reason.contains("beta")
7543                && reason.contains("re-authenticate")
7544        );
7545        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7546        // Orphan recovery uses the same settlement and cannot spend an attempt.
7547        let mut orphan = task();
7548        orphan.start(state.id.clone());
7549        reclaim(&mut orphan, Some(state), 2, "en");
7550        assert_eq!(orphan.attempts, 0);
7551        assert_eq!(orphan.status, TaskStatus::Held);
7552    }
7553
7554    #[test]
7555    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7556        let mut state = RunState::new(
7557            PathBuf::from("/repo"),
7558            "main".to_owned(),
7559            "abc1234".to_owned(),
7560            "task".to_owned(),
7561            Config::default(),
7562        );
7563        state.status = RunStatus::Blocked;
7564        state.resource_block = Some(crate::run::ResourceBlock {
7565            cause: crate::run::ResourceBlockCause::Other,
7566            node: "graft".to_owned(),
7567            kind: "shared build cache".to_owned(),
7568            detail: "timed out".to_owned(),
7569            at: jiff::Timestamp::now(),
7570        });
7571        let mut t = task();
7572        t.start("20260902-000000-aaaa".to_owned());
7573        assert_eq!(t.attempts, 1);
7574        let verdict = Verdict {
7575            status: RunStatus::Blocked,
7576            left_pr: false,
7577            quota_hit: false,
7578            parked: false,
7579            no_viable_candidates: false,
7580        };
7581        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7582        assert_eq!(t.status, TaskStatus::Held);
7583        assert_eq!(t.attempts, 0, "the attempt is refunded");
7584        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7585        assert!(
7586            !t.operator_held(),
7587            "a machine hold, released without a human"
7588        );
7589
7590        let mut selected = task();
7591        selected.start("20260902-000000-cccc".into());
7592        selected.replacement = Some(crate::merge_decision::Replacement {
7593            question: "fixture".into(),
7594            run: "earlier".into(),
7595            pr: "https://example.invalid/pr/1".into(),
7596            agent: "selected".into(),
7597            context: "fixture".into(),
7598        });
7599        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7600        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7601        assert_eq!(selected.attempts, 0);
7602        assert!(
7603            !selected.operator_held(),
7604            "a selected agent also retains a machine resource hold"
7605        );
7606        assert!(
7607            selected
7608                .hold_reason
7609                .as_deref()
7610                .unwrap()
7611                .starts_with("[resource] ")
7612        );
7613
7614        // A park request outranks it: still the operator's doing.
7615        let mut p = task();
7616        p.start("20260902-000000-bbbb".to_owned());
7617        settle_and_diagnose(
7618            &mut p,
7619            Verdict {
7620                parked: true,
7621                ..verdict
7622            },
7623            "parked",
7624            2,
7625            &state,
7626        );
7627        assert_eq!(p.status, TaskStatus::Parked);
7628        assert_eq!(
7629            p.attempts, 0,
7630            "parking refunds once rather than also settling the resource hold"
7631        );
7632    }
7633
7634    #[test]
7635    fn record_failure_notice_links_the_task() {
7636        let dir = tempfile::tempdir().unwrap();
7637        // A regular file where the queue directory should be makes every
7638        // `put` fail, on every platform and whoever runs the test.
7639        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7640        let queue = Queue::at(dir.path().join("queue"));
7641        let mut t = interrupt_task("rec-fail-1");
7642        record(&queue, &mut t);
7643
7644        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7645        assert_eq!(found.len(), 1);
7646        assert_eq!(found[0].key, "loop:record");
7647        assert_eq!(
7648            found[0].link,
7649            Some(Link::Task {
7650                id: "rec-fail-1".to_owned()
7651            })
7652        );
7653    }
7654
7655    /// A runnable task marked to interrupt, with an id fixed for assertions
7656    /// rather than the random one [`Task::new`] mints.
7657    fn interrupt_task(id: &str) -> Task {
7658        let mut t = task();
7659        t.id = id.to_owned();
7660        t.interrupt = true;
7661        t
7662    }
7663
7664    /// An ordinary runnable task with an id fixed for assertions.
7665    fn task_with_id(id: &str) -> Task {
7666        let mut t = task();
7667        t.id = id.to_owned();
7668        t
7669    }
7670
7671    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7672    fn urgent_task(id: &str) -> Task {
7673        let mut t = task();
7674        t.id = id.to_owned();
7675        t.urgent = true;
7676        t
7677    }
7678
7679    #[test]
7680    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7681        let dir = tempfile::tempdir().unwrap();
7682        let queue = Queue::at(dir.path().join("queue"));
7683        let mut parked = task_with_id("parked");
7684        parked.start("run".into());
7685        parked.park("upgrade");
7686        parked.record_pass_at(
7687            "run",
7688            0,
7689            Some(Timestamp::now()),
7690            1,
7691            Some(crate::run::ParkCause::Upgrade {
7692                from: "old".into(),
7693                to: None,
7694            }),
7695        );
7696        let mut fresh = task_with_id("fresh");
7697        fresh.priority = 100;
7698        let mut urgent_task = urgent_task("urgent");
7699        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7700            queue.put(t).unwrap();
7701        }
7702        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7703        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7704        let candidates = runnable(&queue);
7705        assert_eq!(candidates[0].id, parked.id);
7706        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7707        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
7708        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
7709        drop(first);
7710        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7711        let next = runnable(&queue)
7712            .into_iter()
7713            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
7714            .unwrap();
7715        assert_eq!(next.task.id, fresh.id);
7716        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7717        drop(claimed_elsewhere);
7718        drop(next);
7719        assert!(matches!(
7720            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
7721            Err(SkipReason::CoolingDown)
7722        ));
7723    }
7724
7725    #[test]
7726    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7727        let dir = tempfile::tempdir().unwrap();
7728        let queue = Queue::at(dir.path().join("queue"));
7729        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7730        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7731        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7732        let mut first = task();
7733        queue.put(&mut first).unwrap();
7734        let stale_plain = queue.get(&first.id).unwrap();
7735        first.set_urgent(true).unwrap();
7736        queue.put(&mut first).unwrap();
7737        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7738        let mut second = urgent_task("second");
7739        queue.put(&mut second).unwrap();
7740        assert!(matches!(
7741            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
7742            Err(SkipReason::UrgentCapacity)
7743        ));
7744        drop(queue.claim(&second.id).unwrap());
7745        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7746        drop(dispatched);
7747        let stale_urgent = queue.get(&first.id).unwrap();
7748        first.set_urgent(false).unwrap();
7749        queue.put(&mut first).unwrap();
7750        assert!(matches!(
7751            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
7752            Err(SkipReason::OrdinaryCapacity)
7753        ));
7754        assert_eq!(urgent.available_permits(), 1);
7755        drop(queue.claim(&first.id).unwrap());
7756        drop(occupied);
7757    }
7758
7759    #[test]
7760    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7761        let dir = tempfile::tempdir().unwrap();
7762        let queue = Queue::at(dir.path().join("queue"));
7763        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7764        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7765        let mut t = task();
7766        queue.put(&mut t).unwrap();
7767        for enabled in [true, false] {
7768            let stale = queue.get(&t.id).unwrap();
7769            t.set_urgent(enabled).unwrap();
7770            queue.put(&mut t).unwrap();
7771            assert_ne!(stale.urgent, enabled);
7772            let DispatchClaim {
7773                task: fresh,
7774                claim,
7775                permit,
7776            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7777            assert_eq!(fresh.urgent, enabled);
7778            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7779            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7780            assert!(queue.claim(&t.id).is_err());
7781            assert_eq!(fresh.attempts, stale.attempts);
7782            drop((claim, permit));
7783            assert_eq!(ordinary.available_permits(), 1);
7784            assert_eq!(urgent.available_permits(), 1);
7785        }
7786        t.set_urgent(true).unwrap();
7787        queue.put(&mut t).unwrap();
7788        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7789        assert!(matches!(
7790            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7791            Err(SkipReason::UrgentCapacity)
7792        ));
7793        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7794        drop(queue.claim(&t.id).unwrap());
7795        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7796        drop(occupied);
7797        assert!(matches!(
7798            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
7799            Err(SkipReason::CoolingDown)
7800        ));
7801        drop(queue.claim(&t.id).unwrap());
7802        let held = queue.claim(&t.id).unwrap();
7803        assert!(matches!(
7804            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7805            Err(SkipReason::ClaimUnavailable)
7806        ));
7807        drop(held);
7808        t.status = TaskStatus::Held;
7809        queue.put(&mut t).unwrap();
7810        assert!(matches!(
7811            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7812            Err(SkipReason::NoLongerRunnable)
7813        ));
7814        drop(queue.claim(&t.id).unwrap());
7815        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7816        assert!(matches!(
7817            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7818            Err(SkipReason::RereadFailed)
7819        ));
7820        drop(queue.claim(&t.id).unwrap());
7821        assert_eq!(urgent.available_permits(), 1);
7822    }
7823
7824    /// The land-resume exemption wins outright, whether or not the candidate
7825    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7826    /// queue behind anything" guarantee cannot be weaker just because the
7827    /// same task was also filed with `--urgent`.
7828    #[test]
7829    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7830        assert_eq!(permit_kind(true, false), PermitKind::None);
7831        assert_eq!(permit_kind(true, true), PermitKind::None);
7832    }
7833
7834    /// The one property this whole feature exists for: `--urgent` draws from
7835    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7836    /// ordinary candidate draws from the ordinary pool exactly as before,
7837    /// untouched by the urgent slot's existence.
7838    #[test]
7839    fn permit_kind_separates_urgent_from_ordinary() {
7840        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7841        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7842    }
7843
7844    /// The exact wiring `attempt` runs before minting anything: a config's
7845    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7846    /// Free space is injected rather than asked of the real disk - the point
7847    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7848    /// is deterministic on every machine this test runs on, never dependent
7849    /// on how full the CI runner's own disk happens to be.
7850    #[test]
7851    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7852        let cfg = Config::default();
7853        let repo = Path::new("/any/repo/path");
7854
7855        let reason =
7856            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7857        assert!(reason.contains("1024"), "{reason}");
7858        assert!(
7859            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7860            "{reason}"
7861        );
7862
7863        assert_eq!(
7864            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7865            None,
7866            "exactly at the floor is open"
7867        );
7868        assert_eq!(
7869            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7870            None,
7871            "comfortably above the floor is open"
7872        );
7873    }
7874
7875    #[test]
7876    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
7877        let dir = tempfile::tempdir().unwrap();
7878        let repo = dir.path().join("repo");
7879        let cache = dir.path().join("cache");
7880        let worktrees = dir.path().join("worktrees");
7881        for path in [&repo, &cache, &worktrees] {
7882            std::fs::create_dir(path).unwrap();
7883        }
7884        let mut cfg = Config::default();
7885        cfg.graph.worktree_root = Some(worktrees.clone());
7886        cfg.verify.gate = vec![format!(
7887            "CARGO_TARGET_DIR='{}' cargo build",
7888            cache.display()
7889        )];
7890        for blocked in [&cache, &worktrees] {
7891            for unmeasured in [false, true] {
7892                assert!(
7893                    disk_gate_with(&repo, &cfg, |path| {
7894                        if path == blocked {
7895                            if unmeasured {
7896                                Err(anyhow::anyhow!("measurement failed"))
7897                            } else {
7898                                Ok(0)
7899                            }
7900                        } else {
7901                            Ok(u64::MAX)
7902                        }
7903                    })
7904                    .is_some(),
7905                    "a blocked secondary output volume must close admission"
7906                );
7907            }
7908        }
7909        assert!(disk_gate_with(&repo, &cfg, |_| Ok(u64::MAX)).is_none());
7910    }
7911
7912    #[test]
7913    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7914        let mut cfg = Config::default();
7915        cfg.disk.min_free_bytes = 0;
7916        let repo = Path::new("/any/repo/path");
7917        assert_eq!(
7918            disk_gate_with(repo, &cfg, |_| Ok(0)),
7919            None,
7920            "a zero floor never measures at all"
7921        );
7922    }
7923
7924    #[test]
7925    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7926        let cfg = Config::default();
7927        let repo = Path::new("/any/repo/path");
7928        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7929            .expect("a measurement failure must close the gate, not open it");
7930        assert!(reason.contains("could not measure"), "{reason}");
7931    }
7932
7933    #[test]
7934    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7935        let ordinary = task();
7936        let next = advance_interrupt(
7937            Interrupt::Idle,
7938            std::slice::from_ref(&ordinary.id),
7939            std::slice::from_ref(&ordinary),
7940        );
7941        assert_eq!(next, Interrupt::Idle);
7942    }
7943
7944    #[test]
7945    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7946        // Nothing to interrupt - this is just an ordinary candidate, and the
7947        // loop's normal dispatch will pick it up like any other.
7948        let marked = interrupt_task("marked");
7949        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7950        assert_eq!(next, Interrupt::Idle);
7951    }
7952
7953    #[test]
7954    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7955        let marked = interrupt_task("marked");
7956        let next = advance_interrupt(
7957            Interrupt::Idle,
7958            &["running".to_owned()],
7959            std::slice::from_ref(&marked),
7960        );
7961        assert_eq!(
7962            next,
7963            Interrupt::Parking {
7964                parked: vec!["running".to_owned()],
7965                interrupt_task: "marked".to_owned(),
7966            }
7967        );
7968    }
7969
7970    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7971    /// one run can be in flight when a task becomes runnable and marked.
7972    /// Parking all of them would mean `Resuming` later has more than one id
7973    /// to release back to ordinary dispatch, which cannot be made safe
7974    /// against that same setting's own extra concurrency slots letting two
7975    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7976    /// The simplification the task's own constraints ask for: do not begin
7977    /// a sequence at all until the herd settles back to exactly one.
7978    #[test]
7979    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7980        let marked = interrupt_task("marked");
7981
7982        let two = advance_interrupt(
7983            Interrupt::Idle,
7984            &["a".to_owned(), "b".to_owned()],
7985            std::slice::from_ref(&marked),
7986        );
7987        assert_eq!(two, Interrupt::Idle);
7988
7989        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7990        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7991    }
7992
7993    #[test]
7994    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7995        let state = Interrupt::Parking {
7996            parked: vec!["running".to_owned()],
7997            interrupt_task: "marked".to_owned(),
7998        };
7999        // Still in flight: no change.
8000        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8001        assert_eq!(still_going, state);
8002
8003        // Left flight, but the interrupt task has not been dispatched yet on
8004        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8005        // as long as it is still runnable.
8006        let stopped_but_not_yet_dispatched =
8007            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8008        assert_eq!(stopped_but_not_yet_dispatched, state);
8009
8010        // Left flight, and the interrupt task is now in flight itself.
8011        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8012        assert_eq!(
8013            dispatched,
8014            Interrupt::Running {
8015                parked: vec!["running".to_owned()],
8016                interrupt_task: "marked".to_owned(),
8017            }
8018        );
8019    }
8020
8021    #[test]
8022    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8023        let state = Interrupt::Running {
8024            parked: vec!["running".to_owned()],
8025            interrupt_task: "marked".to_owned(),
8026        };
8027        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8028        assert_eq!(still_running, state);
8029
8030        // Whatever it ended as - merged, failed, held - is not this
8031        // function's concern: leaving flight is the only trigger, driven
8032        // straight off the same in-flight list `poll` already reaps. It does
8033        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8034        // why that would let an unrelated task start ahead of, or alongside,
8035        // the guaranteed resume.
8036        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8037        assert_eq!(
8038            ended,
8039            Interrupt::Resuming {
8040                parked: vec!["running".to_owned()]
8041            }
8042        );
8043    }
8044
8045    #[test]
8046    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8047        let state = Interrupt::Resuming {
8048            parked: vec!["running".to_owned()],
8049        };
8050        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8051        assert_eq!(still_waiting, state);
8052
8053        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8054        assert_eq!(dispatched, Interrupt::Idle);
8055    }
8056
8057    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8058    /// or otherwise moved on by an operator with no claim standing in the
8059    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8060    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8061    /// come. The parked run still gets its resume.
8062    #[test]
8063    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8064    {
8065        let state = Interrupt::Parking {
8066            parked: vec!["running".to_owned()],
8067            interrupt_task: "marked".to_owned(),
8068        };
8069        // `marked` has been held/blocked/deleted since the sequence began:
8070        // it no longer appears in `runnable` at all.
8071        let next = advance_interrupt(state, &[], &[]);
8072        assert_eq!(
8073            next,
8074            Interrupt::Resuming {
8075                parked: vec!["running".to_owned()]
8076            },
8077            "abandoning the interrupt must not abandon the resume it owes"
8078        );
8079    }
8080
8081    /// The same abandonment, one step later: `Resuming` itself must not wait
8082    /// forever for a parked task that has since become unrunnable.
8083    #[test]
8084    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8085        let state = Interrupt::Resuming {
8086            parked: vec!["running".to_owned()],
8087        };
8088        let next = advance_interrupt(state, &[], &[]);
8089        assert_eq!(
8090            next,
8091            Interrupt::Idle,
8092            "nothing is left to wait for; the loop must not stay wedged"
8093        );
8094    }
8095
8096    #[test]
8097    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8098        let marked = interrupt_task("marked");
8099        let next = advance_interrupt_tick(
8100            false,
8101            Interrupt::Idle,
8102            &["running".to_owned()],
8103            std::slice::from_ref(&marked),
8104        );
8105        assert_eq!(
8106            next,
8107            Interrupt::Idle,
8108            "an unmarked, unconfigured daemon must behave exactly as before"
8109        );
8110    }
8111
8112    #[test]
8113    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8114        let state = Interrupt::Parking {
8115            parked: vec!["running".to_owned()],
8116            interrupt_task: "marked".to_owned(),
8117        };
8118        let candidates = vec![interrupt_task("marked"), task()];
8119        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8120        assert!(
8121            allowed.is_empty(),
8122            "nothing may dispatch - not even the interrupt task itself - \
8123             until the parked run has actually stopped"
8124        );
8125    }
8126
8127    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8128    /// grow a special case for it: an urgent candidate that is not the
8129    /// interrupt task withholds exactly like an ordinary one for as long as
8130    /// the parked run it is racing has not actually left flight. A version
8131    /// of this feature once bypassed the gate for urgent candidates, on the
8132    /// theory that a genuinely separate concurrency lane could not collide
8133    /// with 75dd's own; it could, and did - the bypassed task dispatched
8134    /// alongside a run 75dd's own state machine had only *asked* to park,
8135    /// not yet confirmed gone, which is exactly the second run
8136    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8137    /// tick during Parking/Running/Resuming where letting an extra
8138    /// candidate through is safe, urgent or not - the parked run may still
8139    /// be genuinely mid-call.
8140    #[test]
8141    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8142        for state in [
8143            Interrupt::Parking {
8144                parked: vec!["running".to_owned()],
8145                interrupt_task: "marked".to_owned(),
8146            },
8147            Interrupt::Running {
8148                parked: vec!["running".to_owned()],
8149                interrupt_task: "marked".to_owned(),
8150            },
8151            Interrupt::Resuming {
8152                parked: vec!["running".to_owned()],
8153            },
8154        ] {
8155            let candidates = vec![
8156                interrupt_task("marked"),
8157                urgent_task("hot"),
8158                task_with_id("ordinary"),
8159            ];
8160            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8161            assert!(
8162                !allowed.iter().any(|t| t.id == "hot"),
8163                "an urgent candidate must wait out the same gate as anything \
8164                 else while the run it would run alongside has not actually \
8165                 left flight, for state {state:?}: {allowed:?}"
8166            );
8167        }
8168    }
8169
8170    /// The one case where marking a task `--urgent` and `interrupt` at once
8171    /// is not redundant: once the interrupt sequence's own guaranteed
8172    /// resume/dispatch actually admits the task, it is unaffected by also
8173    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8174    /// never on the urgent flag.
8175    #[test]
8176    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8177        let state = Interrupt::Resuming {
8178            parked: vec!["hot".to_owned()],
8179        };
8180        let candidates = vec![urgent_task("hot"), task()];
8181        let allowed = interrupt_gate(&state, &[], candidates);
8182        assert_eq!(
8183            allowed.iter().filter(|t| t.id == "hot").count(),
8184            1,
8185            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8186        );
8187    }
8188
8189    #[test]
8190    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8191        let state = Interrupt::Parking {
8192            parked: vec!["running".to_owned()],
8193            interrupt_task: "marked".to_owned(),
8194        };
8195        let other = task();
8196        let candidates = vec![interrupt_task("marked"), other.clone()];
8197        let allowed = interrupt_gate(&state, &[], candidates);
8198        assert_eq!(allowed.len(), 1);
8199        assert_eq!(allowed[0].id, "marked");
8200    }
8201
8202    #[test]
8203    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8204        let state = Interrupt::Running {
8205            parked: vec!["running".to_owned()],
8206            interrupt_task: "marked".to_owned(),
8207        };
8208        let candidates = vec![task(), task()];
8209        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8210        assert!(allowed.is_empty());
8211    }
8212
8213    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8214    /// sequence began (only reachable above the default
8215    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8216    /// never both in the same tick, which is what "exactly one resume, no
8217    /// simultaneous run" actually requires structurally rather than by
8218    /// coincidence of how many ordinary slots happen to be free.
8219    #[test]
8220    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8221        let state = Interrupt::Resuming {
8222            parked: vec!["a".to_owned(), "c".to_owned()],
8223        };
8224        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8225        let allowed = interrupt_gate(&state, &[], candidates);
8226        assert_eq!(
8227            allowed.len(),
8228            1,
8229            "at most one candidate may be offered while resuming: {allowed:?}"
8230        );
8231        assert_eq!(allowed[0].id, "a");
8232    }
8233
8234    #[test]
8235    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8236        let state = Interrupt::Resuming {
8237            parked: vec!["a".to_owned()],
8238        };
8239        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8240        assert!(allowed.is_empty());
8241    }
8242
8243    /// The invariant the completion criteria ask for by name: across a whole
8244    /// simulated sequence, there is never a tick where the gate would let
8245    /// through both the parked run's resume and the interrupt task, and
8246    /// exactly one candidate resumes the instant the interrupt task's run
8247    /// ends - never zero, never more than one.
8248    #[test]
8249    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8250        let running = task(); // id: whatever `Task::new` minted
8251        let marked = interrupt_task("marked");
8252
8253        let mut state = Interrupt::Idle;
8254        // Tick 1: `running` is in flight, `marked` becomes runnable.
8255        let in_flight = vec![running.id.clone()];
8256        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8257        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8258        assert!(gated.is_empty(), "still waiting on `running` to park");
8259
8260        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8261        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8262        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8263        assert_eq!(
8264            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8265            vec!["marked"],
8266            "only the interrupt task may be offered to the dispatcher now"
8267        );
8268
8269        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8270        state = advance_interrupt_tick(
8271            true,
8272            state,
8273            &["marked".to_owned()],
8274            std::slice::from_ref(&running),
8275        );
8276        let gated = interrupt_gate(
8277            &state,
8278            &["marked".to_owned()],
8279            vec![marked.clone(), running.clone()],
8280        );
8281        assert!(
8282            gated.is_empty(),
8283            "the parked run must not be offered back while the interrupt \
8284             task is still running"
8285        );
8286
8287        // Tick 4: `marked`'s run reached a terminal status and left flight.
8288        // A higher-priority ordinary task `other` is also runnable now - it
8289        // must not be let through instead of, or alongside, `running`.
8290        let other = task_with_id("other");
8291        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8292        assert_eq!(
8293            state,
8294            Interrupt::Resuming {
8295                parked: vec![running.id.clone()]
8296            }
8297        );
8298        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8299        assert_eq!(
8300            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8301            vec![running.id.as_str()],
8302            "exactly the parked run resumes - not the unrelated task, even \
8303             though it was offered first"
8304        );
8305
8306        // Tick 5: `running` is now in flight (dispatched from tick 4's
8307        // gate). Only now does the sequence end and ordinary dispatch fully
8308        // resume.
8309        state = advance_interrupt_tick(
8310            true,
8311            state,
8312            std::slice::from_ref(&running.id),
8313            std::slice::from_ref(&other),
8314        );
8315        assert_eq!(state, Interrupt::Idle);
8316        let gated = interrupt_gate(
8317            &state,
8318            std::slice::from_ref(&running.id),
8319            vec![other.clone()],
8320        );
8321        assert_eq!(
8322            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8323            vec![other.id.as_str()],
8324            "ordinary dispatch is unrestricted again"
8325        );
8326    }
8327
8328    #[test]
8329    fn every_run_status_settles_the_task_it_came_from() {
8330        // run status, resulting task status, attempts still standing after one
8331        let table = [
8332            (RunStatus::Merged, TaskStatus::Done, 1),
8333            (RunStatus::Ready, TaskStatus::Done, 1),
8334            (RunStatus::Stalled, TaskStatus::Failed, 0),
8335            (RunStatus::Blocked, TaskStatus::Failed, 1),
8336            (RunStatus::Failed, TaskStatus::Failed, 1),
8337            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8338            (RunStatus::Prep, TaskStatus::Failed, 1),
8339            (RunStatus::Implementing, TaskStatus::Failed, 1),
8340            (RunStatus::Judging, TaskStatus::Failed, 1),
8341            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8342            (RunStatus::Voting, TaskStatus::Failed, 1),
8343            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8344            (RunStatus::Gating, TaskStatus::Failed, 1),
8345        ];
8346        for (run, want, attempts) in table {
8347            let mut t = task();
8348            t.start("20260902-000000-aaaa".to_owned());
8349            settle(
8350                &mut t,
8351                Verdict {
8352                    status: run,
8353                    left_pr: false,
8354                    parked: false,
8355                    quota_hit: matches!(run, RunStatus::Stalled),
8356                    no_viable_candidates: false,
8357                },
8358                "why",
8359                2,
8360            );
8361            assert_eq!(t.status, want, "task status after {}", label(run));
8362            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8363        }
8364    }
8365
8366    #[test]
8367    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8368        let mut stalled = task();
8369        stalled.start("20260902-000000-aaaa".to_owned());
8370        settle(
8371            &mut stalled,
8372            Verdict {
8373                status: RunStatus::Stalled,
8374                left_pr: false,
8375                parked: false,
8376                quota_hit: true,
8377                no_viable_candidates: false,
8378            },
8379            "quota",
8380            1,
8381        );
8382        assert_eq!(stalled.attempts, 0);
8383        assert!(
8384            stalled.status.runnable(),
8385            "a machine problem must leave the task in line"
8386        );
8387
8388        let mut blocked = task();
8389        blocked.start("20260902-000000-aaaa".to_owned());
8390        settle(
8391            &mut blocked,
8392            Verdict {
8393                status: RunStatus::Blocked,
8394                left_pr: false,
8395                parked: false,
8396                quota_hit: false,
8397                no_viable_candidates: false,
8398            },
8399            "findings open",
8400            1,
8401        );
8402        assert_eq!(blocked.attempts, 1);
8403        assert_eq!(
8404            blocked.status,
8405            TaskStatus::Held,
8406            "the last attempt hands the task to a human"
8407        );
8408    }
8409
8410    #[test]
8411    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8412        // Attempts to spare: without the pull request this task would go
8413        // straight back in line and run the whole competition again.
8414        let mut delivered = task();
8415        delivered.start("20260903-080619-01c2".to_owned());
8416        settle(
8417            &mut delivered,
8418            Verdict {
8419                status: RunStatus::Blocked,
8420                left_pr: true,
8421                parked: false,
8422                quota_hit: false,
8423                no_viable_candidates: false,
8424            },
8425            "no check status",
8426            4,
8427        );
8428        assert_eq!(
8429            delivered.status,
8430            TaskStatus::Held,
8431            "a pull request waiting on CI or a person is not a retryable failure"
8432        );
8433        assert!(
8434            !delivered.status.runnable(),
8435            "the loop must not pick this task up again"
8436        );
8437        assert_eq!(
8438            delivered.last_error.as_deref(),
8439            Some("no check status"),
8440            "the operator needs to be told what the gate was waiting for"
8441        );
8442
8443        // The same status without a pull request is a plain failure, and with
8444        // attempts left it is retried.
8445        let mut empty_handed = task();
8446        empty_handed.start("20260903-080619-01c2".to_owned());
8447        settle(
8448            &mut empty_handed,
8449            Verdict {
8450                status: RunStatus::Blocked,
8451                left_pr: false,
8452                parked: false,
8453                quota_hit: false,
8454                no_viable_candidates: false,
8455            },
8456            "findings open",
8457            4,
8458        );
8459        assert_eq!(empty_handed.status, TaskStatus::Failed);
8460        assert!(empty_handed.status.runnable());
8461    }
8462
8463    #[test]
8464    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8465        // Every candidate agreed, with evidence, that nothing belonged in the
8466        // worktree. That is not a confirmed success to close automatically -
8467        // a human still has to check the claim - and it is not an ordinary
8468        // failure either, so this settles exactly like a pull request nobody
8469        // merged yet: `Held`, same as `Blocked` with a PR.
8470        let mut noop = task();
8471        noop.start("20260912-131304-391f".to_owned());
8472        settle(
8473            &mut noop,
8474            Verdict {
8475                status: RunStatus::VerifiedNoop,
8476                left_pr: false,
8477                parked: false,
8478                quota_hit: false,
8479                no_viable_candidates: true,
8480            },
8481            "candidate A: already fixed by b32cfc4, on main",
8482            4,
8483        );
8484        assert_eq!(
8485            noop.status,
8486            TaskStatus::Held,
8487            "an unverified claim is a request for a human, not a failure"
8488        );
8489        assert!(
8490            !noop.status.runnable(),
8491            "the loop must not requeue this on the same unverified claim"
8492        );
8493        // `Task::release` resets attempts to zero the moment a human looks at
8494        // the evidence and lets it run again, so it does not matter here
8495        // whether the one attempt already spent stays spent - what matters is
8496        // that nothing retries this task unattended in the meantime.
8497        assert_eq!(noop.attempts, 1);
8498    }
8499
8500    #[test]
8501    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8502        // Parking is the operator asking for the process back - to replace the
8503        // binary, most of all. The run's work is intact on disk, so this is
8504        // not a failed attempt, and charging for it would mean a few upgrades
8505        // could exhaust a budget meant for agents that misbehaved.
8506        let mut parked = task();
8507        parked.start("20260903-183634-2d98".to_owned());
8508        settle(
8509            &mut parked,
8510            Verdict {
8511                status: RunStatus::Implementing,
8512                left_pr: false,
8513                quota_hit: false,
8514                parked: true,
8515                no_viable_candidates: false,
8516            },
8517            "parked after `implementing`",
8518            2,
8519        );
8520        assert_eq!(parked.attempts, 0, "a park is refunded");
8521        assert!(
8522            parked.status.runnable(),
8523            "and the task stays in line so the next loop resumes its run"
8524        );
8525        assert_eq!(parked.status, TaskStatus::Parked);
8526        assert_eq!(
8527            parked.park_reason.as_deref(),
8528            Some("parked after `implementing`"),
8529            "the card says where it stopped"
8530        );
8531        assert_eq!(parked.last_error, None, "nothing failed");
8532
8533        // Without the park flag the same non-terminal status is what it always
8534        // was: `execute` returning mid-flight, which is a bug and spends an
8535        // attempt so a task cannot loop on it forever.
8536        let mut broken = task();
8537        broken.start("20260903-183634-2d98".to_owned());
8538        settle(
8539            &mut broken,
8540            Verdict {
8541                status: RunStatus::Implementing,
8542                left_pr: false,
8543                quota_hit: false,
8544                parked: false,
8545                no_viable_candidates: false,
8546            },
8547            "returned mid-flight",
8548            2,
8549        );
8550        assert_eq!(broken.attempts, 1);
8551    }
8552
8553    #[test]
8554    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8555        // Run e633: quorum lost because two judges answered with the wrong
8556        // JSON shape, `quota: []`. Refunding that takes the bound off the
8557        // retry loop, and each retry pays for a fresh hour-long implement
8558        // wave before it can fail the same way.
8559        let mut flaky = task();
8560        flaky.start("20260903-123023-e633".to_owned());
8561        settle(
8562            &mut flaky,
8563            Verdict {
8564                status: RunStatus::Stalled,
8565                left_pr: false,
8566                parked: false,
8567                quota_hit: false,
8568                no_viable_candidates: false,
8569            },
8570            "verdict rests on 1 of 3 judges",
8571            2,
8572        );
8573        assert_eq!(
8574            flaky.attempts, 1,
8575            "flakiness spends an attempt, so `max_attempts` still bounds it"
8576        );
8577        assert!(flaky.status.runnable(), "and it is still worth retrying");
8578
8579        // The same status, lost to a rate limit, is the machine's fault.
8580        let mut limited = task();
8581        limited.start("20260903-123023-e633".to_owned());
8582        settle(
8583            &mut limited,
8584            Verdict {
8585                status: RunStatus::Stalled,
8586                left_pr: false,
8587                parked: false,
8588                quota_hit: true,
8589                no_viable_candidates: false,
8590            },
8591            "judge-2, judge-3 out of quota",
8592            2,
8593        );
8594        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8595        assert!(limited.status.runnable());
8596
8597        // And the bound really binds: a task that keeps stalling on flakiness
8598        // reaches a human instead of running the roster forever.
8599        let mut worn = task();
8600        for _ in 0..2 {
8601            worn.release();
8602        }
8603        worn.start("20260903-123023-e633".to_owned());
8604        worn.attempts = 2;
8605        settle(
8606            &mut worn,
8607            Verdict {
8608                status: RunStatus::Stalled,
8609                left_pr: false,
8610                parked: false,
8611                quota_hit: false,
8612                no_viable_candidates: false,
8613            },
8614            "no quorum again",
8615            2,
8616        );
8617        assert_eq!(worn.status, TaskStatus::Held);
8618        assert!(!worn.status.runnable());
8619    }
8620
8621    #[test]
8622    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8623        // The implement wave loses every seat to the same rate limit and
8624        // `after_implement` bails with nothing viable, which surfaces as
8625        // `Failed` rather than `Stalled`. That is the same machine fact the
8626        // `Stalled`-quota row already refunds, and must be refunded the same
8627        // way, or a quota outage quietly holds every task it touches instead
8628        // of leaving them in line for the reset.
8629        let mut wiped_out = task();
8630        wiped_out.start("20260907-025000-a1b2".to_owned());
8631        settle(
8632            &mut wiped_out,
8633            Verdict {
8634                status: RunStatus::Failed,
8635                left_pr: false,
8636                parked: false,
8637                quota_hit: true,
8638                no_viable_candidates: true,
8639            },
8640            "no candidate produced a change; nothing to judge",
8641            2,
8642        );
8643        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8644        assert!(
8645            wiped_out.status.runnable(),
8646            "a machine problem must leave the task in line"
8647        );
8648
8649        // This is the exemption that must stay narrow: a candidate that did
8650        // produce a change, and then failed for some other reason, still
8651        // spends the attempt even though a seat elsewhere hit its quota.
8652        // Otherwise every ordinary failure that happens to share a run with
8653        // an unrelated rate limit would be refunded for free.
8654        let mut partial_progress = task();
8655        partial_progress.start("20260907-025500-c3d4".to_owned());
8656        settle(
8657            &mut partial_progress,
8658            Verdict {
8659                status: RunStatus::Failed,
8660                left_pr: false,
8661                parked: false,
8662                quota_hit: true,
8663                no_viable_candidates: false,
8664            },
8665            "gate failed on the winning candidate",
8666            2,
8667        );
8668        assert_eq!(
8669            partial_progress.attempts, 1,
8670            "a candidate that actually produced a change spends the attempt \
8671             even though some other seat hit its quota"
8672        );
8673        assert!(partial_progress.status.runnable());
8674    }
8675
8676    #[test]
8677    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8678        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8679        // disk, and that construction must reach the same conclusion as the
8680        // one `attempt` builds from a live run, or a crash at exactly the
8681        // wrong moment gives a recovered task a different policy than one a
8682        // daemon finished settling itself.
8683        let mut t = task();
8684        t.start("20260907-025000-a1b2".to_owned());
8685        let mut state = run_state(RunStatus::Failed);
8686        state.quota.push(QuotaLoss {
8687            cause: crate::agent::QuotaCause::UsageLimit,
8688            agent: String::new(),
8689            seat: "cand-a".to_owned(),
8690            node: "implement".to_owned(),
8691            at: Timestamp::now(),
8692            reset: None,
8693        });
8694        assert!(
8695            state.viable().is_empty(),
8696            "no candidate was added, so nothing is viable"
8697        );
8698        reclaim(&mut t, Some(state), 2, "en");
8699        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8700        assert!(t.status.runnable());
8701    }
8702
8703    #[test]
8704    fn a_held_task_is_never_offered_to_the_loop() {
8705        let dir = tempfile::tempdir().unwrap();
8706        let queue = Queue::at(dir.path().to_path_buf());
8707        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8708            let mut t = task();
8709            t.id = format!("2026090{n}-000000-000{n}");
8710            t.priority = priority;
8711            queue.put(&mut t).unwrap();
8712        }
8713        let mut held = task();
8714        held.id = "20260909-000000-9999".to_owned();
8715        held.priority = 99;
8716        held.hold_machine(None);
8717        queue.put(&mut held).unwrap();
8718
8719        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8720        assert_eq!(order.len(), 3);
8721        assert!(!order.contains(&held.id));
8722        assert_eq!(
8723            order.first().cloned(),
8724            queue.next_runnable().map(|t| t.id),
8725            "the loop's first candidate is exactly what the queue offers"
8726        );
8727        assert_eq!(
8728            order,
8729            vec![
8730                "20260902-000000-0002".to_owned(),
8731                "20260903-000000-0003".to_owned(),
8732                "20260901-000000-0001".to_owned(),
8733            ],
8734            "priority first, then oldest, so nothing starves"
8735        );
8736    }
8737
8738    #[test]
8739    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8740        let dir = tempfile::tempdir().unwrap();
8741        let queue = Queue::at(dir.path().to_path_buf());
8742        let mut old = task();
8743        old.id = "20260101-000000-old0".to_owned();
8744        queue.put(&mut old).unwrap();
8745        let mut fresh = task();
8746        fresh.id = "20260101-000000-new0".to_owned();
8747        queue.put(&mut fresh).unwrap();
8748
8749        // No parseable pid at all, so age is the only signal there is to
8750        // check - unlike a real `Queue::claim`, which always names a real,
8751        // and therefore alive, pid this test cannot fake as dead.
8752        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8753        std::thread::sleep(Duration::from_millis(60));
8754        let live = queue.claim(&fresh.id).unwrap();
8755
8756        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8757        assert_eq!(swept, vec![old.id.clone()]);
8758        assert!(
8759            queue.claim(&old.id).is_ok(),
8760            "an unparseable lock older than the threshold is swept"
8761        );
8762        assert!(
8763            queue.claim(&fresh.id).is_err(),
8764            "a live pid protects its lock regardless of age"
8765        );
8766        drop(live);
8767    }
8768
8769    #[test]
8770    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8771        // A live worker's claim remains authoritative even beyond the sweep's
8772        // age limit. Sweeping it would permit a second competing attempt.
8773        let dir = tempfile::tempdir().unwrap();
8774        let queue = Queue::at(dir.path().to_path_buf());
8775        let mut t = task();
8776        t.id = "20260101-000000-live".to_owned();
8777        queue.put(&mut t).unwrap();
8778
8779        let claim = queue.claim(&t.id).unwrap();
8780        std::thread::sleep(Duration::from_millis(60));
8781
8782        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8783        assert!(
8784            swept.is_empty(),
8785            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8786        );
8787        assert!(
8788            queue.claim(&t.id).is_err(),
8789            "the lock still protects its task"
8790        );
8791        drop(claim);
8792    }
8793
8794    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8795    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8796    fn injected_dead_pid() -> u32 {
8797        std::process::id().checked_add(1).unwrap_or(1)
8798    }
8799
8800    #[test]
8801    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8802        let dir = tempfile::tempdir().unwrap();
8803        let queue = Queue::at(dir.path().to_path_buf());
8804        let mut t = task();
8805        t.id = "20260101-000000-dead".to_owned();
8806        queue.put(&mut t).unwrap();
8807        let dead_pid = injected_dead_pid();
8808
8809        // Written directly rather than through `Queue::claim`, which would
8810        // stamp this test process's own very much alive pid and defeat the
8811        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8812        // like moments after it died, not six hours later.
8813        std::fs::write(
8814            dir.path().join(format!("{}.lock", t.id)),
8815            dead_pid.to_string(),
8816        )
8817        .unwrap();
8818
8819        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8820            pid != dead_pid
8821        });
8822        assert_eq!(
8823            swept,
8824            vec![t.id.clone()],
8825            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8826        );
8827        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8828    }
8829
8830    #[test]
8831    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8832        let dir = tempfile::tempdir().unwrap();
8833        let queue = Queue::at(dir.path().to_path_buf());
8834        let mut t = task();
8835        t.id = "20260101-000000-late".to_owned();
8836        queue.put(&mut t).unwrap();
8837        let dead_pid = injected_dead_pid();
8838
8839        // Tick one, standing in for the sweep `poll` already runs at
8840        // startup: nothing to find yet.
8841        assert!(
8842            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8843            "nothing has claimed the task yet"
8844        );
8845
8846        // A second daemon claims the task and dies before it ever writes
8847        // `running`, well after this loop's own startup sweep already ran.
8848        std::fs::write(
8849            dir.path().join(format!("{}.lock", t.id)),
8850            dead_pid.to_string(),
8851        )
8852        .unwrap();
8853
8854        // Tick two, standing in for a poll long into this daemon's uptime:
8855        // the same function, called again, notices what only just appeared -
8856        // proving the sweep is not a one-shot startup check.
8857        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8858            pid != dead_pid
8859        });
8860        assert_eq!(swept, vec![t.id.clone()]);
8861    }
8862
8863    #[test]
8864    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8865        // `reclaim_orphaned_running` looks up the task's last run, which
8866        // touches `run::home()`; the first call anywhere in this binary wins,
8867        // so this is a no-op if another test already pinned one, and either
8868        // way the run id below is never written under it.
8869        crate::run::pin_test_home();
8870        let dir = tempfile::tempdir().unwrap();
8871        let queue = Queue::at(dir.path().to_path_buf());
8872        let mut t = task();
8873        t.id = "20260101-000000-crsh".to_owned();
8874        t.status = TaskStatus::Running;
8875        t.attempts = 1;
8876        // No `run.json` behind this id: standing in for a run this test does
8877        // not need to make readable, since the point is the lock, not the
8878        // recovery table `reclaim` already has its own tests for.
8879        t.runs.push("20260904-000000-4043".to_owned());
8880        queue.put(&mut t).unwrap();
8881        let dead_pid = injected_dead_pid();
8882
8883        // The crashed daemon's own claim, naming a pid nothing on the
8884        // machine holds anymore.
8885        std::fs::write(
8886            dir.path().join(format!("{}.lock", t.id)),
8887            dead_pid.to_string(),
8888        )
8889        .unwrap();
8890
8891        // Before the lock is swept the task looks claimed, and
8892        // `reclaim_orphaned_running` must leave it alone - this is exactly
8893        // the bug: a `running` task stranded behind a dead daemon's lock,
8894        // invisible to the claim-as-proof check because the lock outlived
8895        // the process that wrote it.
8896        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8897        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8898
8899        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8900            pid != dead_pid
8901        });
8902        assert_eq!(swept, vec![t.id.clone()]);
8903
8904        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8905        assert_eq!(reclaimed, vec![t.id.clone()]);
8906        let after = queue.get(&t.id).unwrap();
8907        assert_eq!(
8908            after.status,
8909            TaskStatus::Held,
8910            "no run.json to recover from, so a human is asked"
8911        );
8912        assert_eq!(
8913            after.runs,
8914            vec!["20260904-000000-4043".to_owned()],
8915            "the crashed run's id is kept as evidence, not discarded"
8916        );
8917    }
8918
8919    #[test]
8920    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8921        let dir = tempfile::tempdir().unwrap();
8922        let queue = Queue::at(dir.path().to_path_buf());
8923        let mut t = task();
8924        t.id = "20260101-000000-unknown".to_owned();
8925        queue.put(&mut t).unwrap();
8926        let dead_pid = injected_dead_pid();
8927        std::fs::write(
8928            dir.path().join(format!("{}.lock", t.id)),
8929            dead_pid.to_string(),
8930        )
8931        .unwrap();
8932
8933        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8934        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8935        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8936    }
8937
8938    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8939        let mut s = run_state(status);
8940        s.config.graph.language = language.to_owned();
8941        s
8942    }
8943
8944    fn unstarted_verdict(status: RunStatus) -> Verdict {
8945        Verdict {
8946            status,
8947            left_pr: false,
8948            quota_hit: false,
8949            parked: false,
8950            no_viable_candidates: false,
8951        }
8952    }
8953
8954    #[test]
8955    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8956        let mut t = task();
8957        t.attempts = 1;
8958        settle_in(
8959            &mut t,
8960            unstarted_verdict(RunStatus::AlreadyInBase),
8961            "already in main",
8962            1,
8963            phrases("en"),
8964        );
8965        assert_eq!(t.status, TaskStatus::Done);
8966        assert_eq!(t.attempts, 0);
8967    }
8968
8969    #[test]
8970    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8971        let reason = |language: &str| {
8972            let mut t = task();
8973            settle_in(
8974                &mut t,
8975                unstarted_verdict(RunStatus::Judging),
8976                "boom",
8977                1,
8978                phrases(language),
8979            );
8980            t.last_error.or(t.hold_reason).unwrap_or_default()
8981        };
8982        assert!(
8983            reason("en").starts_with("the graph stopped at `"),
8984            "{}",
8985            reason("en")
8986        );
8987        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8988        assert!(reason("日本語").contains("boom"));
8989        assert_eq!(reason("fr"), reason("en"));
8990    }
8991
8992    #[test]
8993    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8994        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8995        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8996        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8997        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8998        assert!(ja.contains("[run "), "{ja}");
8999        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9000        assert!(ended.starts_with("run 終了: "), "{ended}");
9001        let mut de = run_state_in(RunStatus::Failed, "de");
9002        let mut en = run_state_in(RunStatus::Failed, "en");
9003        de.id = "same".to_owned();
9004        en.id = "same".to_owned();
9005        assert_eq!(describe(&de), describe(&en));
9006    }
9007
9008    #[test]
9009    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9010        use crate::handover::Refused;
9011        let cases = [
9012            Refused::Foreign {
9013                branch: "b".into(),
9014                path: "/w/x".into(),
9015                why: "made by hand".into(),
9016            },
9017            Refused::Unsafe {
9018                branch: "b".into(),
9019                path: "/w/x".into(),
9020                why: "its worktree has uncommitted changes (a.rs)".into(),
9021            },
9022            Refused::ReleaseFailed {
9023                branch: "b".into(),
9024                path: "/w/x".into(),
9025                run: "ab12".into(),
9026            },
9027        ];
9028        for r in &cases {
9029            let en = (phrases("en").handover_refused)(r);
9030            assert_eq!(en, r.to_string());
9031            let ja = (phrases("ja").handover_refused)(r);
9032            assert!(
9033                !ja.contains("is checked out") && !ja.contains("try again"),
9034                "{ja}"
9035            );
9036            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9037            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9038                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9039            }
9040        }
9041        assert!(phrases("en").handover_hint.contains("release the task"));
9042        assert!(phrases("ja").handover_hint.contains("解放"));
9043    }
9044
9045    #[test]
9046    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9047        let build = |lang: &str| {
9048            let mut s = run_state_in(RunStatus::Blocked, lang);
9049            s.id = "same".to_owned();
9050            s.config.graph.review_rounds = 3;
9051            let mut r = review_round(3);
9052            r.expected = 3;
9053            r.answered = 1;
9054            s.reviews.push(r);
9055            s.event(
9056                "review",
9057                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9058            );
9059            s
9060        };
9061        let en = describe(&build("en"));
9062        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9063        let ja = describe(&build("ja"));
9064        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9065        assert!(!ja.contains("never answered"), "{ja}");
9066        assert!(ja.contains("[run "), "{ja}");
9067
9068        // An incomplete panel whose verification failed is a different stop:
9069        // the real event must survive in ja too.
9070        let mut failed = build("ja");
9071        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9072            command: "cargo test".to_owned(),
9073            code: Some(1),
9074            output_tail: String::new(),
9075            duration_ms: 0,
9076            resource_blocked: false,
9077        });
9078        failed.event("review", "stopped; e2e failed: cargo test");
9079        let ja = describe(&failed);
9080        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9081        assert!(!ja.contains("席のレビュアー"), "{ja}");
9082    }
9083
9084    #[test]
9085    fn refusals_and_recovery_prose_follow_the_language() {
9086        let home = crate::run::test_home();
9087        let t = held_task_with("r1");
9088        let q = action_question(
9089            "r1",
9090            ask::ChoiceAction::Resume {
9091                run: "r1".to_owned(),
9092            },
9093        );
9094        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9095            ActionDecision::Refuse(s) => s,
9096            other => panic!("{other:?}"),
9097        };
9098        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9099        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9100        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9101
9102        let mut held = task();
9103        reclaim(&mut held, None, 2, "ja");
9104        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9105        let mut held = task();
9106        reclaim(&mut held, None, 2, "xx");
9107        assert!(held.hold_reason.unwrap().contains("held for a human"));
9108    }
9109
9110    fn run_state(status: RunStatus) -> RunState {
9111        let mut state = RunState::new(
9112            PathBuf::from("/repo"),
9113            "main".to_owned(),
9114            "abc1234def".to_owned(),
9115            "add retries".to_owned(),
9116            Config::default(),
9117        );
9118        state.status = status;
9119        state
9120    }
9121
9122    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9123        Candidate {
9124            index: 0,
9125            label,
9126            agent: "claude".to_owned(),
9127            branch: format!("magi/x/{label}"),
9128            worktree: PathBuf::from("/repo"),
9129            summary: summary.to_owned(),
9130            stat: String::new(),
9131            files: 0,
9132            commits: usize::from(!empty),
9133            empty,
9134            failed: failed.map(str::to_owned),
9135            verified_noop: None,
9136            duration_ms: 0,
9137            folded: false,
9138        }
9139    }
9140
9141    #[test]
9142    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9143        let mut state = run_state(RunStatus::Blocked);
9144        state.gate = vec![
9145            CommandOutcome {
9146                command: "cargo make check".to_owned(),
9147                code: Some(0),
9148                output_tail: "ok".to_owned(),
9149                duration_ms: 0,
9150                resource_blocked: false,
9151            },
9152            CommandOutcome {
9153                command: "cargo test".to_owned(),
9154                code: Some(101),
9155                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9156                duration_ms: 0,
9157                resource_blocked: false,
9158            },
9159        ];
9160        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9161        assert!(d.contains("cargo test"), "{d}");
9162        assert!(
9163            !d.contains("cargo make check"),
9164            "a passing check is not a diagnostic: {d}"
9165        );
9166        assert!(d.contains("assertion failed"), "{d}");
9167    }
9168
9169    #[test]
9170    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9171        let mut state = run_state(RunStatus::Blocked);
9172        state.event(
9173            "land",
9174            "stopped: the fixer produced no commit while 2 check(s) were failing \
9175             (build, lint); stopping instead of looping on an unchanged tree",
9176        );
9177        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9178        assert!(d.contains("build"), "{d}");
9179        assert!(d.contains("lint"), "{d}");
9180        assert!(d.contains("fixer produced no commit"), "{d}");
9181    }
9182
9183    #[test]
9184    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9185        // `describe`'s output becomes `Task::last_error` verbatim, and the
9186        // phone renders that in the same alarm-styled box an ordinary
9187        // failure gets. A bare `verified_noop` there would read exactly like
9188        // the failure this status exists to be told apart from.
9189        let state = run_state(RunStatus::VerifiedNoop);
9190        let d = describe(&state);
9191        assert!(
9192            d.contains("agent-verified no-op"),
9193            "expected the display label, not the wire spelling: {d}"
9194        );
9195        assert!(!d.contains("verified_noop"), "{d}");
9196    }
9197
9198    #[test]
9199    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9200        let mut state = run_state(RunStatus::Failed);
9201        state.gate.push(crate::run::CommandOutcome {
9202            command: "cargo test".into(),
9203            code: Some(101),
9204            output_tail: format!(
9205                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9206                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9207            ),
9208            duration_ms: 1,
9209            resource_blocked: false,
9210        });
9211        let d = diagnostic(&state).unwrap();
9212        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9213        assert!(d.contains("assertion failed: widget missing"));
9214        assert!(d.contains("widget log"));
9215    }
9216
9217    #[test]
9218    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9219        // The whole point of the feature: a run held as "no candidate produced
9220        // a change" can mean the implementer actually finished the task and
9221        // only left a clean local tree behind - see AGENTS.md on this exact
9222        // failure mode. The diagnostic has to carry what the agent actually
9223        // said, not just the fact that nothing was there to judge.
9224        let mut state = run_state(RunStatus::Failed);
9225        state.candidates = vec![candidate(
9226            'A',
9227            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9228            true,
9229            None,
9230        )];
9231        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9232        assert!(d.contains("candidate A"), "{d}");
9233        assert!(d.contains("tagged v1.2.3"), "{d}");
9234    }
9235
9236    #[test]
9237    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9238        let mut state = run_state(RunStatus::Failed);
9239        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9240        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9241        assert!(d.contains("candidate A"), "{d}");
9242        assert!(d.contains("agent timed out"), "{d}");
9243    }
9244
9245    #[test]
9246    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9247        // A viable candidate existed, the gate never ran, and nothing land
9248        // said matches - `Task::last_error` is left to explain this one alone.
9249        let mut state = run_state(RunStatus::Failed);
9250        state.candidates = vec![candidate('A', "did the work", false, None)];
9251        assert!(diagnostic(&state).is_none());
9252    }
9253
9254    #[test]
9255    fn diagnostic_is_bounded_however_much_a_run_printed() {
9256        let mut state = run_state(RunStatus::Blocked);
9257        state.gate = vec![
9258            CommandOutcome {
9259                command: "cargo test".to_owned(),
9260                code: Some(101),
9261                output_tail: "x".repeat(50_000),
9262                duration_ms: 0,
9263                resource_blocked: false,
9264            },
9265            CommandOutcome {
9266                command: "cargo clippy".to_owned(),
9267                code: Some(1),
9268                output_tail: "y".repeat(50_000),
9269                duration_ms: 0,
9270                resource_blocked: false,
9271            },
9272        ];
9273        state.candidates = vec![
9274            candidate('A', &"z".repeat(50_000), true, None),
9275            candidate('B', &"w".repeat(50_000), true, None),
9276        ];
9277        let d = diagnostic(&state).expect("plenty here to diagnose");
9278        assert!(
9279            d.len() <= DIAGNOSTIC_MAX,
9280            "diagnostic grew to {} bytes, unbounded",
9281            d.len()
9282        );
9283    }
9284
9285    #[test]
9286    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9287        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9288            let mut t = task();
9289            let mut state = run_state(status);
9290            t.pr_recovery = Some(crate::pr_recovery::Selection {
9291                url: "url".into(),
9292                branch: format!("magi/task-{}", t.id),
9293                head: "a".repeat(40),
9294                source_head: None,
9295                source_run: None,
9296                source_proof: None,
9297                disposition: Some(crate::pr_recovery::Disposition::Land),
9298                instruction: t.instruction.clone(),
9299                approved_at: Timestamp::now(),
9300            });
9301            state.pr_recovery = t.pr_recovery.clone();
9302            t.start(state.id.clone());
9303            settle_and_diagnose(
9304                &mut t,
9305                Verdict {
9306                    status,
9307                    left_pr: false,
9308                    quota_hit: false,
9309                    parked: false,
9310                    no_viable_candidates: false,
9311                },
9312                "delivery stopped",
9313                5,
9314                &state,
9315            );
9316            assert_eq!(t.status, TaskStatus::Held);
9317            let reason = t.hold_reason.as_deref().unwrap();
9318            if status == RunStatus::Ready {
9319                assert!(reason.contains("Selected PR delivery is incomplete"));
9320                assert!(t.recovery_budget.is_none());
9321            } else {
9322                assert!(reason.contains("Selected recovery stopped"));
9323                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9324            }
9325            assert!(t.pr_recovery.is_some());
9326        }
9327    }
9328
9329    #[test]
9330    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9331        let mut state = run_state(RunStatus::Voting);
9332        state.base_sync = Some(crate::run::BaseSync {
9333            tip: "base-tip".into(),
9334            behind: 3,
9335            attempts: 4,
9336            conflict: Some("base stopped".into()),
9337            already_in: None,
9338        });
9339        state.record_base_sync_stop("candidate-head");
9340        let mut t = task();
9341        t.start(state.id.clone());
9342        let verdict = Verdict {
9343            status: RunStatus::Blocked,
9344            left_pr: false,
9345            quota_hit: false,
9346            parked: false,
9347            no_viable_candidates: false,
9348        };
9349        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9350        assert_eq!(
9351            t.status,
9352            TaskStatus::Held,
9353            "unspent task attempts cannot start another competition"
9354        );
9355        let at = t.held_at;
9356        let cause = t.hold_notice_cause.clone();
9357        state.begin_pass();
9358        t.release_operator("test-resume", None);
9359        t.start(state.id.clone());
9360        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9361        assert_eq!(t.status, TaskStatus::Held);
9362        assert_eq!(t.held_at, at);
9363        assert_eq!(t.hold_notice_cause, cause);
9364    }
9365
9366    #[test]
9367    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9368        let mut state = run_state(RunStatus::Blocked);
9369        state.gate = vec![CommandOutcome {
9370            command: "cargo test".to_owned(),
9371            code: Some(101),
9372            output_tail: "assertion failed".to_owned(),
9373            duration_ms: 0,
9374            resource_blocked: false,
9375        }];
9376        let verdict = Verdict {
9377            status: RunStatus::Blocked,
9378            left_pr: false,
9379            quota_hit: false,
9380            parked: false,
9381            no_viable_candidates: false,
9382        };
9383
9384        // Attempt one of two still has a retry coming: no diagnostic yet, the
9385        // task is going to run again and this run's evidence would go stale.
9386        let mut t = task();
9387        t.start("run-1".to_owned());
9388        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9389        assert_eq!(t.status, TaskStatus::Failed);
9390        assert!(t.diagnostic.is_none());
9391
9392        // Attempt two exhausts the budget: now it is held, and the
9393        // diagnostic is what `magi task show` has to say more than one line.
9394        t.start("run-2".to_owned());
9395        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9396        assert_eq!(t.status, TaskStatus::Held);
9397        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9398        assert!(d.contains("cargo test"), "{d}");
9399    }
9400
9401    #[test]
9402    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9403        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9404        // `magi ask` question settled Held with `hold_reason: null`, so the
9405        // notification said nothing actionable. `note_open_question` should
9406        // append the question id to whatever `handed_off` already wrote.
9407        crate::run::pin_test_home();
9408        let home = crate::run::home();
9409        let state = run_state(RunStatus::VerifiedNoop);
9410        let mut q = ask::Question::new(
9411            state.id.clone(),
9412            "implement".to_owned(),
9413            "impl-A".to_owned(),
9414            "is this really a no-op?".to_owned(),
9415            String::new(),
9416            Vec::new(),
9417        );
9418        Questions::at(home.join("questions")).put(&mut q).unwrap();
9419
9420        let verdict = Verdict {
9421            status: RunStatus::VerifiedNoop,
9422            left_pr: false,
9423            quota_hit: false,
9424            parked: false,
9425            no_viable_candidates: false,
9426        };
9427        let mut t = task();
9428        t.start(state.id.clone());
9429        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9430
9431        assert_eq!(t.status, TaskStatus::Held);
9432        let reason = t.hold_reason.expect("a held task must record why");
9433        assert!(
9434            reason.starts_with("run ended agent-verified no-op"),
9435            "the original settle reason must survive unchanged: {reason}"
9436        );
9437        assert!(
9438            reason.contains(q.short()),
9439            "the open question's id must be named so the notice is actionable: {reason}"
9440        );
9441    }
9442
9443    #[test]
9444    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9445        crate::run::pin_test_home();
9446        let state = run_state(RunStatus::VerifiedNoop);
9447
9448        let verdict = Verdict {
9449            status: RunStatus::VerifiedNoop,
9450            left_pr: false,
9451            quota_hit: false,
9452            parked: false,
9453            no_viable_candidates: false,
9454        };
9455        let mut t = task();
9456        t.start(state.id.clone());
9457        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9458
9459        assert_eq!(t.status, TaskStatus::Held);
9460        assert_eq!(
9461            t.hold_reason.as_deref(),
9462            Some("run ended agent-verified no-op"),
9463            "nothing to append when the question was already answered or never asked"
9464        );
9465    }
9466
9467    #[test]
9468    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9469        crate::run::pin_test_home();
9470        let mut first = run_state(RunStatus::Blocked);
9471        first.id = "20260101-000000-sup1".to_owned();
9472        first.save().unwrap();
9473        let mut second = run_state(RunStatus::Merged);
9474        second.id = "20260101-000000-sup2".to_owned();
9475        second.save().unwrap();
9476
9477        let mut t = task();
9478        t.runs = vec![first.id.clone(), second.id.clone()];
9479        t.status = TaskStatus::Done;
9480
9481        supersede_prior_runs(&t, &crate::run::home());
9482
9483        assert_eq!(
9484            RunState::load(&first.id).unwrap().status,
9485            RunStatus::Superseded,
9486            "the first attempt's Blocked no longer needs anyone's attention"
9487        );
9488        assert_eq!(
9489            RunState::load(&second.id).unwrap().status,
9490            RunStatus::Merged,
9491            "the run that actually succeeded is left exactly as it was"
9492        );
9493    }
9494
9495    #[test]
9496    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9497        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9498        // --resume` invoked by hand outside the daemon never touches
9499        // `daemon.json` at all, so it would look identical to a genuinely
9500        // idle run without also consulting `RunState::liveness`, which reads
9501        // this run's own recorded `driver_pid` instead.
9502        crate::run::pin_test_home();
9503        let mut first = run_state(RunStatus::Blocked);
9504        first.id = "20260101-000000-sup9".to_owned();
9505        // This test process's own pid: guaranteed alive without needing a
9506        // real second process or daemon.
9507        first.driver_pid = Some(std::process::id());
9508        first.driver_started_at = Some(
9509            crate::proc::process_started_at(std::process::id())
9510                .expect("this test process's own start time must be queryable"),
9511        );
9512        first.save().unwrap();
9513        let mut second = run_state(RunStatus::Merged);
9514        second.id = "20260101-000000-supa".to_owned();
9515        second.save().unwrap();
9516
9517        let mut t = task();
9518        t.runs = vec![first.id.clone(), second.id.clone()];
9519        t.status = TaskStatus::Done;
9520
9521        supersede_prior_runs(&t, &crate::run::home());
9522
9523        assert_eq!(
9524            RunState::load(&first.id).unwrap().status,
9525            RunStatus::Blocked,
9526            "a live driver_pid means something is still actually working this run, \
9527             even though no daemon claims it - rewriting under it would just be \
9528             undone the next time that process saves"
9529        );
9530    }
9531
9532    #[test]
9533    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9534        // The first resweep must skip a still-live attempt exactly like
9535        // `supersede_prior_runs` itself does; a later resweep, once that
9536        // process is no longer actually driving it, is what closes the gap
9537        // `supersede_prior_runs` alone leaves - a task only ever reaches
9538        // `Done` once, so nothing else would ever look at this run again.
9539        let dir = tempfile::tempdir().unwrap();
9540        let home = dir.path().to_path_buf();
9541        let queue = Queue::at(dir.path().join("queue"));
9542
9543        let mut first = run_state(RunStatus::Blocked);
9544        first.id = "20260101-000000-supd".to_owned();
9545        first.driver_pid = Some(std::process::id());
9546        first.driver_started_at = Some(
9547            crate::proc::process_started_at(std::process::id())
9548                .expect("this test process's own start time must be queryable"),
9549        );
9550        first.save_under(&home).unwrap();
9551        let mut second = run_state(RunStatus::Merged);
9552        second.id = "20260101-000000-supe".to_owned();
9553        second.save_under(&home).unwrap();
9554
9555        let mut t = task();
9556        t.runs = vec![first.id.clone(), second.id.clone()];
9557        t.status = TaskStatus::Done;
9558        queue.put(&mut t).unwrap();
9559
9560        resweep_superseded_attempts(&queue, &home);
9561        assert_eq!(
9562            RunState::load_under(&first.id, &home).unwrap().status,
9563            RunStatus::Blocked,
9564            "still live on the first pass, so still untouched"
9565        );
9566
9567        // Stand in for the manual process no longer being the one driving
9568        // this run: same pid (this test process really is still alive), but
9569        // an identity marker that no longer matches it - see
9570        // `RunState::liveness`'s own doc for why a mismatched
9571        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9572        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9573        stale.driver_started_at = Some("1".to_owned());
9574        stale.save_under(&home).unwrap();
9575
9576        resweep_superseded_attempts(&queue, &home);
9577        assert_eq!(
9578            RunState::load_under(&first.id, &home).unwrap().status,
9579            RunStatus::Superseded,
9580            "the second pass catches up what the first one correctly skipped"
9581        );
9582    }
9583
9584    #[test]
9585    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9586        crate::run::pin_test_home();
9587        let mut first = run_state(RunStatus::Blocked);
9588        first.id = "20260101-000000-sup3".to_owned();
9589        first.save().unwrap();
9590        let mut second = run_state(RunStatus::Blocked);
9591        second.id = "20260101-000000-sup4".to_owned();
9592        second.save().unwrap();
9593
9594        let mut t = task();
9595        t.runs = vec![first.id.clone(), second.id.clone()];
9596        // Still retrying: nothing about this task's story is settled yet, so
9597        // neither Blocked run may be relabelled, even though a later attempt
9598        // already exists.
9599        t.status = TaskStatus::Failed;
9600
9601        supersede_prior_runs(&t, &crate::run::home());
9602
9603        assert_eq!(
9604            RunState::load(&first.id).unwrap().status,
9605            RunStatus::Blocked
9606        );
9607        assert_eq!(
9608            RunState::load(&second.id).unwrap().status,
9609            RunStatus::Blocked
9610        );
9611    }
9612
9613    #[test]
9614    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9615        // `magi task done` (or the API's equivalent) can close a task with no
9616        // run of its own ever having succeeded - there is nothing here that
9617        // counts as "the attempt that finished it", so nothing is rewritten.
9618        crate::run::pin_test_home();
9619        let mut first = run_state(RunStatus::Blocked);
9620        first.id = "20260101-000000-sup5".to_owned();
9621        first.save().unwrap();
9622
9623        let mut t = task();
9624        t.runs = vec![first.id.clone()];
9625        t.status = TaskStatus::Done;
9626
9627        supersede_prior_runs(&t, &crate::run::home());
9628
9629        assert_eq!(
9630            RunState::load(&first.id).unwrap().status,
9631            RunStatus::Blocked,
9632            "a single-attempt task has no earlier run to supersede"
9633        );
9634    }
9635
9636    #[test]
9637    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9638        // `magi task done` (or the web/conductor equivalents) can close a
9639        // task in any status, including one whose *last* recorded attempt is
9640        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9641        // never watched, say. `runs.last()` being `Done`-adjacent is not
9642        // proof it actually succeeded, so nothing earlier may be relabelled
9643        // on its say-so alone.
9644        crate::run::pin_test_home();
9645        let mut first = run_state(RunStatus::Blocked);
9646        first.id = "20260101-000000-supb".to_owned();
9647        first.save().unwrap();
9648        let mut second = run_state(RunStatus::Failed);
9649        second.id = "20260101-000000-supc".to_owned();
9650        second.save().unwrap();
9651
9652        let mut t = task();
9653        t.runs = vec![first.id.clone(), second.id.clone()];
9654        t.status = TaskStatus::Done;
9655
9656        supersede_prior_runs(&t, &crate::run::home());
9657
9658        assert_eq!(
9659            RunState::load(&first.id).unwrap().status,
9660            RunStatus::Blocked,
9661            "the task's last attempt never landed, so there is nothing here \
9662             actually superseding it"
9663        );
9664    }
9665
9666    #[test]
9667    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9668        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9669        // to look" - `Failed` and `VerifiedNoop` are already their own
9670        // terminal answers and must not be relabelled into a third one.
9671        crate::run::pin_test_home();
9672        let mut failed = run_state(RunStatus::Failed);
9673        failed.id = "20260101-000000-sup6".to_owned();
9674        failed.save().unwrap();
9675        let mut noop = run_state(RunStatus::VerifiedNoop);
9676        noop.id = "20260101-000000-sup7".to_owned();
9677        noop.save().unwrap();
9678        let mut winner = run_state(RunStatus::Ready);
9679        winner.id = "20260101-000000-sup8".to_owned();
9680        winner.save().unwrap();
9681
9682        let mut t = task();
9683        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9684        t.status = TaskStatus::Done;
9685
9686        supersede_prior_runs(&t, &crate::run::home());
9687
9688        assert_eq!(
9689            RunState::load(&failed.id).unwrap().status,
9690            RunStatus::Failed
9691        );
9692        assert_eq!(
9693            RunState::load(&noop.id).unwrap().status,
9694            RunStatus::VerifiedNoop
9695        );
9696    }
9697
9698    fn approval_question(run: &str) -> ask::Question {
9699        ask::Question::new(
9700            run.to_owned(),
9701            land::APPROVAL_NODE.to_owned(),
9702            "land".to_owned(),
9703            "merge?".to_owned(),
9704            String::new(),
9705            vec!["merge".to_owned(), "hold".to_owned()],
9706        )
9707    }
9708
9709    #[test]
9710    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9711        crate::run::pin_test_home();
9712        let mut state = run_state(RunStatus::Landing);
9713        state.id = "20260101-000000-fre1".to_owned();
9714        state.parked = true;
9715        state.save().unwrap();
9716        ask::Questions::open()
9717            .put(&mut approval_question(&state.id))
9718            .unwrap();
9719
9720        let mut t = task();
9721        t.runs.push(state.id.clone());
9722        assert_eq!(
9723            land_resume_state(&t),
9724            LandResume::StillWaiting,
9725            "nobody has answered and the timeout has not passed"
9726        );
9727    }
9728
9729    #[test]
9730    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9731        crate::run::pin_test_home();
9732        let mut state = run_state(RunStatus::Gating);
9733        state.id = "20260101-000000-gt01".to_owned();
9734        state.parked = true;
9735        state.config.graph.answer_timeout = 60;
9736        state.github_text = Some(crate::run::GithubTextAsk {
9737            rewrite: None,
9738            fingerprint: "f".into(),
9739            title: true,
9740            body: false,
9741            categories: vec!["title-language".into()],
9742            question: None,
9743            asks: 1,
9744            resolved: false,
9745            chosen_title: None,
9746            choice: None,
9747            publication: None,
9748        });
9749        state.save().unwrap();
9750        let store = ask::Questions::open();
9751        let mut q = ask::Question::new(
9752            state.id.clone(),
9753            crate::github_text::ASK_NODE.to_owned(),
9754            crate::github_text::ASK_SEAT.to_owned(),
9755            "s".into(),
9756            String::new(),
9757            vec!["use fallback".into()],
9758        );
9759        store.put(&mut q).unwrap();
9760        let mut t = task();
9761        t.runs.push(state.id.clone());
9762        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9763        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9764        store.put(&mut q).unwrap();
9765        assert_eq!(land_resume_state(&t), LandResume::Ready);
9766        assert!(!store.get(&q.id).unwrap().status.open());
9767        // Once decided, a parked run is an ordinary candidate again.
9768        state.github_text.as_mut().unwrap().resolved = true;
9769        state.save().unwrap();
9770        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9771    }
9772
9773    #[test]
9774    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9775        // `ask::ask_and_wait`'s own deadline used to retire a question
9776        // nobody answered; land's approval bypasses that wait (see
9777        // `land::approval_gate`), so this is now the only place
9778        // `graph.answer_timeout` is enforced for a land approval at all.
9779        crate::run::pin_test_home();
9780        let mut state = run_state(RunStatus::Landing);
9781        state.id = "20260101-000000-exp1".to_owned();
9782        state.parked = true;
9783        state.config.graph.answer_timeout = 60;
9784        state.save().unwrap();
9785
9786        let store = ask::Questions::open();
9787        let mut q = approval_question(&state.id);
9788        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9789        store.put(&mut q).unwrap();
9790
9791        let mut t = task();
9792        t.runs.push(state.id.clone());
9793        assert_eq!(
9794            land_resume_state(&t),
9795            LandResume::Ready,
9796            "an expired question must not be waited on forever"
9797        );
9798
9799        let after = store.get(&q.id).unwrap();
9800        assert!(
9801            !after.status.open(),
9802            "the question is abandoned, not silently ignored"
9803        );
9804        assert!(
9805            after.resolution().is_none(),
9806            "an abandoned question is not read as a decision"
9807        );
9808    }
9809
9810    #[test]
9811    fn reclaim_settles_a_running_task_against_its_last_run() {
9812        let mut t = task();
9813        t.start("20260904-000000-4043".to_owned());
9814        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9815        assert_eq!(
9816            t.status,
9817            TaskStatus::Done,
9818            "a run that actually finished must not stay `running` forever"
9819        );
9820    }
9821
9822    #[test]
9823    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
9824        let dir = tempfile::tempdir().unwrap();
9825        let queue = Queue::at(dir.path().join("queue"));
9826        let mut task = task();
9827        let mut run = run_state(RunStatus::Blocked);
9828        run.reserve_under(dir.path()).unwrap();
9829        run.driver_exited = true;
9830        run.save_under(dir.path()).unwrap();
9831        queue.put(&mut task).unwrap();
9832        let stale = task.clone();
9833        task.resume_override = Some(crate::queue::OperatorResume {
9834            question_id: "pending-resume".into(),
9835            at: Timestamp::now(),
9836            conductor_rehold: None,
9837            forced: true,
9838            pinned_run: Some(run.id.clone()),
9839        });
9840        task.start(run.id.clone());
9841        queue.put(&mut task).unwrap();
9842        // Discard every in-memory handoff, as a worker death before execute does.
9843        let mut recovered = queue.get(&task.id).unwrap();
9844        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
9845        reclaim(&mut recovered, Some(disk), 2, "en");
9846        queue.put(&mut recovered).unwrap();
9847        assert!(recovered.resume_override.is_none());
9848        assert_eq!(
9849            recovered.dispatched_resumes.get("pending-resume"),
9850            Some(&run.id)
9851        );
9852        let mut stale = stale;
9853        queue.put(&mut stale).unwrap();
9854        assert_eq!(
9855            stale.dispatched_resumes, recovered.dispatched_resumes,
9856            "a stale task writer cannot erase dispatch ownership"
9857        );
9858        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
9859        assert!(resumed.decision_starts.is_empty());
9860        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
9861        assert!(
9862            resumed.decision_starts.is_empty(),
9863            "handoff is not execution proof"
9864        );
9865        resumed.begin_pass();
9866        resumed.save_under(dir.path()).unwrap();
9867        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
9868        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
9869        disk.carry_dispatched_resumes(&recovered);
9870        disk.begin_pass();
9871        assert_eq!(
9872            disk.decision_starts.get("pending-resume"),
9873            Some(&0),
9874            "later execution must preserve the original pass receipt"
9875        );
9876    }
9877
9878    #[test]
9879    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9880        let mut t = task();
9881        t.start("20260904-000000-4043".to_owned());
9882        t.last_error = Some("earlier trouble".to_owned());
9883        let mut state = run_state(RunStatus::Judging);
9884        state.parked = true;
9885        reclaim(&mut t, Some(state), 1, "en");
9886        assert_eq!(t.status, TaskStatus::Parked);
9887        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9888        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9889        assert!(t.park_reason.is_some());
9890        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9891        assert!(!t.fresh_start);
9892        assert!(t.status.runnable());
9893    }
9894
9895    #[test]
9896    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9897        let mut t = task();
9898        t.start("20260904-000000-4043".to_owned());
9899        t.last_error = Some("earlier trouble".to_owned());
9900        settle(
9901            &mut t,
9902            Verdict {
9903                status: RunStatus::Judging,
9904                left_pr: false,
9905                quota_hit: false,
9906                parked: true,
9907                no_viable_candidates: false,
9908            },
9909            "parked after `judging`",
9910            1,
9911        );
9912        assert_eq!(t.status, TaskStatus::Parked);
9913        assert_eq!(t.attempts, 0);
9914        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9915        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9916        assert_eq!(t.schema, crate::queue::SCHEMA);
9917        assert!(
9918            crate::notices::task_held(&t).is_none(),
9919            "a park is not news"
9920        );
9921        t.start("20260904-000000-4043".to_owned());
9922        assert_eq!(t.park_reason, None);
9923    }
9924
9925    #[test]
9926    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9927        // A blocked run with attempts left goes back to `Failed`, exactly as
9928        // it would from `attempt` itself - `reclaim` must not invent a second
9929        // policy for a task a daemon merely stopped without reporting.
9930        let mut t = task();
9931        t.start("20260904-000000-4043".to_owned());
9932        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9933        assert_eq!(t.status, TaskStatus::Failed);
9934        assert!(t.status.runnable());
9935    }
9936
9937    #[test]
9938    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9939        let mut t = task();
9940        t.start("20260904-000000-4043".to_owned());
9941        assert_eq!(t.attempts, 1);
9942        let mut run = run_state(RunStatus::Implementing);
9943        run.id = "20260904-000000-4043".to_owned();
9944        run.begin_pass();
9945        let cause = crate::run::ParkCause::Upgrade {
9946            from: "0.121.0".to_owned(),
9947            to: Some("0.121.1".to_owned()),
9948        };
9949        run.end_pass_parked(cause.clone());
9950        run.parked = true;
9951        let verdict = Verdict {
9952            status: run.status,
9953            left_pr: false,
9954            quota_hit: false,
9955            parked: true,
9956            no_viable_candidates: false,
9957        };
9958        // A crash after the checkpoint but before queue settlement must
9959        // recover exactly the same scheduling evidence and refund.
9960        let mut orphan = t.clone();
9961        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9962        assert_eq!(orphan.status, TaskStatus::Parked);
9963        assert_eq!(orphan.attempts, 0);
9964        assert_eq!(
9965            orphan.upgrade_resume_key(),
9966            Some((run.passes[0].started_at, orphan.id.as_str()))
9967        );
9968        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9969        assert_eq!(t.attempts, 0);
9970        assert_eq!(t.passes.len(), 1);
9971        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9972        assert_eq!(t.passes[0].parked, Some(cause));
9973        assert_eq!(t.passes[0].pass_index, 0);
9974        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9975        assert!(t.upgrade_resume_key().is_some());
9976
9977        // A resumed pass that then fails spends its attempt, and the earlier
9978        // pass's entry is untouched.
9979        t.start("20260904-000000-4043".to_owned());
9980        run.begin_pass();
9981        run.status = RunStatus::Failed;
9982        let verdict = Verdict {
9983            status: RunStatus::Failed,
9984            left_pr: false,
9985            quota_hit: false,
9986            parked: false,
9987            no_viable_candidates: false,
9988        };
9989        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9990        assert_eq!(t.passes.len(), 2);
9991        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9992        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9993        assert_eq!(t.passes[1].pass_index, 1);
9994        assert_eq!(t.attempts, 1);
9995    }
9996
9997    #[test]
9998    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9999        let mut t = task();
10000        t.start("20260904-000000-4043".to_owned());
10001        reclaim(&mut t, None, 2, "en");
10002        assert_eq!(t.status, TaskStatus::Held);
10003        assert!(
10004            t.last_error
10005                .as_deref()
10006                .is_some_and(|e| e.contains("running")),
10007            "the operator needs to know why this task was held"
10008        );
10009    }
10010
10011    #[test]
10012    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10013        let dir = tempfile::tempdir().unwrap();
10014        let queue = Queue::at(dir.path().to_path_buf());
10015
10016        // No run recorded, so this never has to touch `RunState::load`.
10017        let mut orphaned = task();
10018        orphaned.id = "20260904-000000-orph".to_owned();
10019        orphaned.status = TaskStatus::Running;
10020        orphaned.attempts = 1;
10021        queue.put(&mut orphaned).unwrap();
10022
10023        let mut alive = task();
10024        alive.id = "20260904-000000-live".to_owned();
10025        alive.status = TaskStatus::Running;
10026        alive.attempts = 1;
10027        queue.put(&mut alive).unwrap();
10028        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10029
10030        let mut queued = task();
10031        queued.id = "20260904-000000-wait".to_owned();
10032        queue.put(&mut queued).unwrap();
10033
10034        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10035        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10036
10037        assert_eq!(
10038            queue.get(&orphaned.id).unwrap().status,
10039            TaskStatus::Held,
10040            "nothing was driving it and there was no run to recover"
10041        );
10042        assert_eq!(
10043            queue.get(&alive.id).unwrap().status,
10044            TaskStatus::Running,
10045            "a live claim must protect the task it belongs to"
10046        );
10047        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10048    }
10049
10050    /// Read a run.json back from an explicit `home`, the same way
10051    /// `reclaim_abandoned_runs` itself does - never through the
10052    /// process-global `RunState::load`, which this test's own `home` (an
10053    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10054    /// use at all.
10055    fn read_run_under(home: &Path, id: &str) -> RunState {
10056        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10057        serde_json::from_str(&body).unwrap()
10058    }
10059
10060    #[test]
10061    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10062        let dir = tempfile::tempdir().unwrap();
10063        let home = dir.path().to_path_buf();
10064        let now = Timestamp::now();
10065        let overrun_seat = || crate::run::ActiveSeat {
10066            node: "implement".to_owned(),
10067            started_at: now - jiff::SignedDuration::new(21_000, 0),
10068            timeout_secs: 3_600,
10069            attempt: 0,
10070            task: None,
10071            command: None,
10072            index: None,
10073            total: None,
10074        };
10075
10076        let mut dead = run_state(RunStatus::Implementing);
10077        dead.id = "20260101-000000-dead".to_owned();
10078        dead.active.insert("impl-A".to_owned(), overrun_seat());
10079        // A `driver_pid` the injected query below confirms gone outright —
10080        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10081        dead.driver_pid = Some(4242);
10082        dead.save_under(&home).unwrap();
10083
10084        // Same shape, but a live daemon's heartbeat names it: must be left
10085        // exactly alone, however far past its own timeout the seat sits.
10086        let mut alive = run_state(RunStatus::Implementing);
10087        alive.id = "20260101-000000-aliv".to_owned();
10088        alive.active.insert("impl-A".to_owned(), overrun_seat());
10089        alive.save_under(&home).unwrap();
10090        let mut status = Status::new();
10091        status.current = vec![Current {
10092            worker: None,
10093            task: "20260101-000000-task".to_owned(),
10094            run: alive.id.clone(),
10095        }];
10096        write_status_to(&home.join("daemon.json"), &status).unwrap();
10097
10098        // The abandoned seat left an open question behind: nobody is left to
10099        // read an answer once the run is failed, and this must not wait for
10100        // some later daemon startup's own sweep to notice that.
10101        let questions = Questions::at(home.join("questions"));
10102        let mut q = ask::Question::new(
10103            dead.id.clone(),
10104            "implement".to_owned(),
10105            "impl-A".to_owned(),
10106            "Which storage backend?".to_owned(),
10107            String::new(),
10108            vec!["SQLite".to_owned(), "Redis".to_owned()],
10109        );
10110        questions.put(&mut q).unwrap();
10111
10112        let abandoned = reclaim_abandoned_runs_with(
10113            &home,
10114            now,
10115            |pid| if pid == 4242 { Some(false) } else { None },
10116            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10117        );
10118        assert_eq!(abandoned, vec![dead.id.clone()]);
10119
10120        let reloaded = read_run_under(&home, &dead.id);
10121        assert_eq!(reloaded.status, RunStatus::Failed);
10122        assert!(reloaded.active.is_empty());
10123        assert!(
10124            !questions.get(&q.id).unwrap().status.open(),
10125            "the failed run's own open question must be settled in the same pass"
10126        );
10127
10128        let still_alive = read_run_under(&home, &alive.id);
10129        assert_eq!(
10130            still_alive.status,
10131            RunStatus::Implementing,
10132            "a live daemon's claim protects it"
10133        );
10134        assert!(!still_alive.active.is_empty());
10135    }
10136
10137    /// The exact shape a review round flagged as broken: `magi serve` running
10138    /// in this same `home` scans *every* run on disk, including a manual
10139    /// `magi review` / `magi run` this daemon never started and that
10140    /// therefore claims no heartbeat of its own. Before this scan asked
10141    /// `liveness` rather than just `is_working_on`, a manual run whose active
10142    /// seat merely ran a little past its own timeout — the CLI finishing up,
10143    /// its result still being collected — got wiped and failed by a daemon
10144    /// that had nothing to do with it, out from under a process that was
10145    /// still very much running.
10146    #[test]
10147    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10148        let dir = tempfile::tempdir().unwrap();
10149        let home = dir.path().to_path_buf();
10150        let now = Timestamp::now();
10151
10152        let mut manual = run_state(RunStatus::Reviewing);
10153        manual.id = "20260101-000000-manl".to_owned();
10154        manual.active.insert(
10155            "review-1".to_owned(),
10156            crate::run::ActiveSeat {
10157                node: "review".to_owned(),
10158                started_at: now - jiff::SignedDuration::new(21_000, 0),
10159                timeout_secs: 3_600,
10160                attempt: 0,
10161                task: None,
10162                command: None,
10163                index: None,
10164                total: None,
10165            },
10166        );
10167        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10168        // but a real, still-running process: `liveness` must corroborate this
10169        // as `Live`, not read the missing daemon claim as death.
10170        manual.driver_pid = Some(4242);
10171        manual.driver_started_at = Some("1790000000".to_owned());
10172        manual.save_under(&home).unwrap();
10173
10174        let abandoned = reclaim_abandoned_runs_with(
10175            &home,
10176            now,
10177            |pid| if pid == 4242 { Some(true) } else { None },
10178            |pid| {
10179                if pid == 4242 {
10180                    Some("1790000000".to_owned())
10181                } else {
10182                    None
10183                }
10184            },
10185        );
10186        assert!(
10187            abandoned.is_empty(),
10188            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10189        );
10190
10191        let reloaded = read_run_under(&home, &manual.id);
10192        assert_eq!(reloaded.status, RunStatus::Reviewing);
10193        assert!(!reloaded.active.is_empty());
10194    }
10195
10196    #[test]
10197    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10198        let dir = tempfile::tempdir().unwrap();
10199        let queue = Queue::at(dir.path().to_path_buf());
10200        let mut only = task();
10201        queue.put(&mut only).unwrap();
10202
10203        let _elsewhere = queue.claim(&only.id).unwrap();
10204        let candidates = runnable(&queue);
10205        assert_eq!(candidates.len(), 1, "the task is still runnable");
10206        assert!(
10207            queue.claim(&candidates[0].id).is_err(),
10208            "the loop cannot take a claim somebody else holds"
10209        );
10210
10211        let after = queue.get(&only.id).unwrap();
10212        assert_eq!(after.status, TaskStatus::Queued);
10213        assert_eq!(
10214            after.attempts, 0,
10215            "losing the race is not an attempt at the task"
10216        );
10217        assert_eq!(after.last_error, None);
10218    }
10219
10220    #[test]
10221    fn the_status_file_round_trips_and_its_heartbeat_advances() {
10222        let dir = tempfile::tempdir().unwrap();
10223        let path = dir.path().join("daemon.json");
10224
10225        let mut status = Status::new();
10226        status.idle = false;
10227        status.completed = 7;
10228        status.current = vec![Current {
10229            worker: None,
10230            task: "20260902-000000-t111".to_owned(),
10231            run: "20260902-000001-r111".to_owned(),
10232        }];
10233        write_status_to(&path, &status).unwrap();
10234        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10235        assert_eq!(first.schema, SCHEMA);
10236        assert_eq!(first.pid, std::process::id());
10237        assert!(!first.idle);
10238        assert_eq!(first.completed, 7);
10239        assert_eq!(first.current, status.current);
10240        assert!(
10241            !path.with_extension("json.tmp").exists(),
10242            "the temp file is renamed, not left behind"
10243        );
10244
10245        std::thread::sleep(Duration::from_millis(5));
10246        status.updated_at = Timestamp::now();
10247        status.polls = 3;
10248        write_status_to(&path, &status).unwrap();
10249        let second: Status =
10250            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10251        assert!(
10252            second.updated_at > first.updated_at,
10253            "a reader can only detect staleness if the heartbeat moves"
10254        );
10255        assert_eq!(
10256            second.started_at, first.started_at,
10257            "the start time is not a heartbeat"
10258        );
10259        assert_eq!(second.polls, 3);
10260    }
10261
10262    #[test]
10263    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10264        let dir = tempfile::tempdir().unwrap();
10265
10266        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10267
10268        let mut status = Status::new();
10269        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10270        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10271        let stale = read_status(dir.path()).unwrap();
10272        assert!(
10273            !stale.running(Timestamp::now()),
10274            "a minute without a heartbeat is a dead daemon, not a busy one"
10275        );
10276        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10277
10278        status.updated_at = Timestamp::now();
10279        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10280        let fresh = read_status(dir.path()).unwrap();
10281        assert!(fresh.running(Timestamp::now()));
10282    }
10283
10284    #[test]
10285    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10286        let dir = tempfile::tempdir().unwrap();
10287        let now = Timestamp::now();
10288        let mine = "20260903-080619-01c2";
10289
10290        assert!(
10291            !is_working_on(dir.path(), mine, now),
10292            "no status file means nobody is working on anything"
10293        );
10294
10295        let mut status = Status::new();
10296        status.current = vec![Current {
10297            worker: None,
10298            task: "20260903-080340-0167".to_owned(),
10299            run: mine.to_owned(),
10300        }];
10301        status.updated_at = now;
10302        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10303        assert!(is_working_on(dir.path(), mine, now));
10304        assert!(
10305            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10306            "a daemon busy with one run is not working on another"
10307        );
10308
10309        // A killed daemon stops writing heartbeats but leaves the file behind
10310        // naming the run it died in. That run must not be undeletable forever.
10311        status.updated_at = now - jiff::SignedDuration::from_secs(600);
10312        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10313        assert!(
10314            !is_working_on(dir.path(), mine, now),
10315            "a stale heartbeat is a dead daemon, so its run is a leftover"
10316        );
10317    }
10318
10319    #[test]
10320    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10321        let dir = tempfile::tempdir().unwrap();
10322        let now = Timestamp::now();
10323
10324        assert!(
10325            !is_working_on_short(dir.path(), "01c2", now),
10326            "no status file means nobody is working on anything"
10327        );
10328
10329        let mut status = Status::new();
10330        status.current = vec![Current {
10331            worker: None,
10332            task: "20260903-080340-0167".to_owned(),
10333            run: "20260903-080619-01c2".to_owned(),
10334        }];
10335        status.updated_at = now;
10336        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10337        assert!(
10338            is_working_on_short(dir.path(), "01c2", now),
10339            "the run's short id is the last block of its full id"
10340        );
10341        assert!(
10342            !is_working_on_short(dir.path(), "3cbf", now),
10343            "a daemon busy with one worktree bay is not working on another"
10344        );
10345    }
10346
10347    #[test]
10348    fn a_newer_status_file_still_yields_a_reading() {
10349        let dir = tempfile::tempdir().unwrap();
10350        // A field this build has never heard of must not turn the reading into
10351        // nothing at all; that is the whole reason the reader is permissive.
10352        std::fs::write(
10353            dir.path().join("daemon.json"),
10354            serde_json::json!({
10355                "schema": 2,
10356                "updated_at": Timestamp::now().to_string(),
10357                "idle": true,
10358                "surprise": { "nested": [1, 2, 3] },
10359            })
10360            .to_string(),
10361        )
10362        .unwrap();
10363
10364        let reading = read_status(dir.path()).expect("a forward-compatible read");
10365        assert!(reading.running(Timestamp::now()));
10366        assert!(reading.idle);
10367        assert!(reading.current.is_empty());
10368    }
10369
10370    #[test]
10371    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10372        // A daemon started before `current` became a list keeps writing this
10373        // shape on every heartbeat until it is restarted. A rolling upgrade
10374        // - a newer `magi web` or `magi doctor` reading an older `magi
10375        // serve`'s heartbeat - must still see the run it is on, not "no
10376        // daemon" from a type mismatch failing the whole struct.
10377        let dir = tempfile::tempdir().unwrap();
10378        std::fs::write(
10379            dir.path().join("daemon.json"),
10380            serde_json::json!({
10381                "schema": 1,
10382                "pid": 4242,
10383                "updated_at": Timestamp::now().to_string(),
10384                "idle": false,
10385                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10386                "completed": 3,
10387                "polls": 9,
10388            })
10389            .to_string(),
10390        )
10391        .unwrap();
10392
10393        let reading = read_status(dir.path()).expect("an older shape must still parse");
10394        assert!(reading.running(Timestamp::now()));
10395        assert_eq!(
10396            reading.current,
10397            vec![Current {
10398                worker: None,
10399                task: "20260902-140501-aaaa".to_owned(),
10400                run: "20260902-140502-bbbb".to_owned(),
10401            }]
10402        );
10403    }
10404
10405    #[test]
10406    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10407        let dir = tempfile::tempdir().unwrap();
10408        std::fs::write(
10409            dir.path().join("daemon.json"),
10410            serde_json::json!({
10411                "schema": 1,
10412                "updated_at": Timestamp::now().to_string(),
10413                "idle": true,
10414                "current": null,
10415            })
10416            .to_string(),
10417        )
10418        .unwrap();
10419        let with_null = read_status(dir.path()).expect("null must still parse");
10420        assert!(with_null.current.is_empty());
10421
10422        std::fs::write(
10423            dir.path().join("daemon.json"),
10424            serde_json::json!({
10425                "schema": 1,
10426                "updated_at": Timestamp::now().to_string(),
10427                "idle": true,
10428            })
10429            .to_string(),
10430        )
10431        .unwrap();
10432        let absent = read_status(dir.path()).expect("a missing field must still parse");
10433        assert!(absent.current.is_empty());
10434    }
10435
10436    #[test]
10437    fn a_task_without_a_repository_runs_in_the_daemons_default() {
10438        let fallback = Path::new("/default");
10439        let mut blank = task();
10440        blank.repo = PathBuf::new();
10441        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10442        let mut dot = task();
10443        dot.repo = PathBuf::from(".");
10444        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10445        assert_eq!(
10446            repo_for(&task(), fallback),
10447            PathBuf::from("/repo"),
10448            "a task that names a repository keeps it"
10449        );
10450    }
10451
10452    #[test]
10453    fn task_implementers_edit_inherits_daemon_config_and_merge() {
10454        let dir = tempfile::tempdir().unwrap();
10455        let path = dir.path().join("explicit.toml");
10456        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10457        let opts = Opts {
10458            config: Some(path),
10459            merge: Some("none".into()),
10460            ..Default::default()
10461        };
10462        let mut t = task();
10463        t.set_implementers(
10464            2,
10465            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10466                .unwrap(),
10467        )
10468        .unwrap();
10469        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10470        assert_eq!(cfg.graph.implementers, 2);
10471        assert_eq!(cfg.graph.judges, 1);
10472        assert_eq!(cfg.merge.mode, MergeMode::None);
10473        t.set_implementers(1, &cfg).unwrap();
10474        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10475        apply_task_implementers(&mut cfg, &t);
10476        assert_eq!(cfg.graph.implementers, 1);
10477        assert_eq!(cfg.graph.judges, 1);
10478        assert_eq!(cfg.merge.mode, MergeMode::None);
10479    }
10480
10481    #[test]
10482    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10483        let dir = tempfile::tempdir().unwrap();
10484        let repo = dir.path().join("repo");
10485        std::fs::create_dir(&repo).unwrap();
10486        std::fs::write(
10487            repo.join("magi.toml"),
10488            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10489        )
10490        .unwrap();
10491        let daemon_config = dir.path().join("daemon.toml");
10492        std::fs::write(
10493            &daemon_config,
10494            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10495        )
10496        .unwrap();
10497        let opts = Opts {
10498            config: Some(daemon_config),
10499            merge: Some("pr".into()),
10500            ..Default::default()
10501        };
10502        let q = Queue::at(dir.path().join("queue"));
10503        let validation: Config =
10504            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10505                .unwrap();
10506        // No provenance field on legacy direct tasks: both shapes stay isolated.
10507        for record in ["{}", r#"{"candidates":2}"#] {
10508            let overrides = serde_json::from_str(record).unwrap();
10509            let filing = crate::direct::Filing {
10510                instruction: "work".into(),
10511                title: "direct".into(),
10512                repo: repo.clone(),
10513                source: crate::queue::Source::Human,
10514                solo: false,
10515                overrides,
10516                review_of: None,
10517                sources: Default::default(),
10518            };
10519            let filed =
10520                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
10521            let crate::direct::Filed::Standalone {
10522                mut task,
10523                claim: _claim,
10524            } = filed
10525            else {
10526                panic!("local filing")
10527            };
10528            let before = prepare_for(&repo, &opts, &task).unwrap();
10529            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
10530            assert_eq!(
10531                before.merge.mode,
10532                MergeMode::None,
10533                "daemon --merge must not leak"
10534            );
10535            for n in [2, 1, 2] {
10536                task.set_implementers(n, &validation).unwrap();
10537                q.put(&mut task).unwrap();
10538                task = q.get(&task.id).unwrap();
10539                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
10540                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
10541                apply_task_implementers(&mut cfg, &task);
10542                assert_eq!(cfg.graph.implementers, usize::from(n));
10543                assert_eq!(cfg.graph.judges, 2);
10544                assert_eq!(cfg.merge.mode, MergeMode::None);
10545            }
10546        }
10547    }
10548
10549    #[test]
10550    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
10551        let cfg: Config =
10552            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10553                .unwrap();
10554        let mut t = task();
10555        t.review_of = Some("review-target".into());
10556        t.hold_manual(Some("retry".into()));
10557        let mut previous = RunState::new(
10558            PathBuf::from("/repo"),
10559            "main".into(),
10560            "abc1234".into(),
10561            "review".into(),
10562            cfg.clone(),
10563        );
10564        previous.config.graph.implementers = 2;
10565        for count in [1, 3] {
10566            t.set_implementers(count, &cfg).unwrap();
10567            t.release();
10568            assert_eq!(t.review_of.as_deref(), Some("review-target"));
10569            for proposed in [
10570                Starter::Resume(previous.id.clone()),
10571                Starter::Review("recovery-target".into()),
10572            ] {
10573                assert_eq!(
10574                    starter_with_implementers(&t, Some(&previous), proposed),
10575                    Starter::Review("review-target".into())
10576                );
10577            }
10578            let mut configured = cfg.clone();
10579            apply_task_implementers(&mut configured, &t);
10580            assert_eq!(configured.graph.implementers, usize::from(count));
10581            assert_eq!(previous.config.graph.implementers, 2);
10582        }
10583    }
10584
10585    #[test]
10586    fn task_implementers_dispatch_and_resume_agree() {
10587        let mut t = task();
10588        let cfg: crate::config::Config =
10589            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10590                .unwrap();
10591        let mut run = RunState::new(
10592            PathBuf::from("/repo"),
10593            "main".into(),
10594            "abc1234".into(),
10595            "work".into(),
10596            cfg.clone(),
10597        );
10598        run.config.graph.implementers = 2;
10599        for n in [2, 1, 3, 2] {
10600            t.set_implementers(n, &cfg).unwrap();
10601            let mut dispatched = cfg.clone();
10602            apply_task_implementers(&mut dispatched, &t);
10603            assert_eq!(dispatched.graph.implementers, usize::from(n));
10604            assert_eq!(implementers_match(&t, &run), n == 2);
10605            for proposed in [
10606                Starter::Resume(run.id.clone()),
10607                Starter::Review("old-branch".into()),
10608            ] {
10609                let expected = if n == 2 {
10610                    proposed.clone()
10611                } else {
10612                    Starter::Start
10613                };
10614                assert_eq!(
10615                    starter_with_implementers(&t, Some(&run), proposed),
10616                    expected
10617                );
10618            }
10619            assert_eq!(
10620                run.config.graph.implementers, 2,
10621                "history must not be rewritten"
10622            );
10623        }
10624        t.solo = false;
10625        t.overrides = None;
10626        assert!(implementers_match(&t, &run));
10627    }
10628
10629    #[test]
10630    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10631        // Three seats said out loud. What `solo` promises is one candidate
10632        // *whatever the config asks for*, so the contrast has to be a number
10633        // this test owns - it used to be `Config::default()`'s, which became
10634        // 1 when one implementation became the default and left the two
10635        // halves of this test asserting the same thing.
10636        let mut solo_cfg = Config::default();
10637        solo_cfg.graph.implementers = 3;
10638        let mut solo_task = task();
10639        solo_task.solo = true;
10640        apply_task_implementers(&mut solo_cfg, &solo_task);
10641        assert_eq!(solo_cfg.graph.implementers, 1);
10642
10643        let mut plain_cfg = Config::default();
10644        plain_cfg.graph.implementers = 3;
10645        let plain_task = task();
10646        assert!(!plain_task.solo);
10647        apply_task_implementers(&mut plain_cfg, &plain_task);
10648        assert_eq!(
10649            plain_cfg.graph.implementers, 3,
10650            "a task that did not ask to run alone keeps the config's candidates"
10651        );
10652    }
10653
10654    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10655        QuotaLoss {
10656            cause: crate::agent::QuotaCause::UsageLimit,
10657            agent: String::new(),
10658            seat: seat.into(),
10659            node: "judge".into(),
10660            at: at.parse().unwrap(),
10661            reset: reset.map(str::to_string),
10662        }
10663    }
10664
10665    #[test]
10666    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10667        let now = Timestamp::now();
10668        for reset in [None, Some("in 1h")] {
10669            let auth = crate::agent::Quota {
10670                cause: crate::agent::QuotaCause::Authentication,
10671                agent: "alpha".into(),
10672                reset: reset.map(str::to_owned),
10673            };
10674            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10675            assert_eq!(cooldown_until(&[loss], now), None);
10676        }
10677    }
10678
10679    #[test]
10680    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10681        let old: Vec<QuotaLoss> = (1..=4)
10682            .map(|i| {
10683                loss(
10684                    &format!("judge-{i}"),
10685                    "2026-09-23T05:23:00Z",
10686                    Some("2:40pm (Asia/Tokyo)"),
10687                )
10688            })
10689            .collect();
10690        let fresh = losses_this_attempt(&old, &old);
10691        assert!(fresh.is_empty());
10692        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10693        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10694    }
10695
10696    #[test]
10697    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10698        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10699        let now = Timestamp::now();
10700        let mut after = old.clone();
10701        after.push(loss("judge-2", &now.to_string(), None));
10702        let fresh = losses_this_attempt(&old, &after);
10703        assert_eq!(fresh, vec![after[1].clone()]);
10704        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10705        assert_eq!(
10706            until,
10707            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10708        );
10709    }
10710
10711    #[test]
10712    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10713        // `recover_stall` removes judge-1's loss and the retry then hits quota
10714        // again: the vector is the same length, so an index diff sees nothing.
10715        let before = vec![
10716            loss("judge-1", "2026-09-23T05:23:00Z", None),
10717            loss("judge-2", "2026-09-23T05:24:00Z", None),
10718        ];
10719        let after = vec![
10720            loss("judge-2", "2026-09-23T05:24:00Z", None),
10721            loss("judge-1", "2026-09-24T01:00:00Z", None),
10722        ];
10723        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10724    }
10725
10726    #[test]
10727    fn merge_overrides_are_parsed_or_refused() {
10728        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10729        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10730        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10731        assert!(merge_mode("squash").is_err());
10732    }
10733
10734    #[test]
10735    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10736        let now = Timestamp::now();
10737        let fallback = Duration::from_secs(300);
10738        let cap = Duration::from_secs(1800);
10739
10740        // No reset hint at all: the fallback.
10741        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10742
10743        // A reset ten minutes out, well inside the cap: waited for exactly.
10744        let soon = now + jiff::SignedDuration::from_secs(600);
10745        assert_eq!(
10746            quota_wait(Some(soon), now, fallback, cap),
10747            Duration::from_secs(600)
10748        );
10749
10750        // A reset already in the past is not trusted: the fallback, not a
10751        // zero or negative wait that would spin the loop right back around.
10752        let past = now - jiff::SignedDuration::from_secs(60);
10753        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10754
10755        // A reset further out than the cap is trusted for direction but not
10756        // for magnitude: a parsing slip must not sleep the loop for a day.
10757        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10758        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10759    }
10760
10761    #[test]
10762    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10763        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10764
10765        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10766        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10767
10768        // Same clock reading, but it has already gone by today: read as
10769        // tomorrow's, since the CLI would not still be reporting a limit past
10770        // its own stated reset.
10771        let already_past =
10772            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10773        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10774
10775        assert!(
10776            parse_reset_hint("session limit reached", now, now).is_none(),
10777            "free text with no recognised shape is not guessed at"
10778        );
10779        assert!(
10780            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10781            "an unresolvable zone name is not guessed at either"
10782        );
10783    }
10784
10785    #[test]
10786    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10787        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10788
10789        let at = parse_reset_hint(
10790            "You've hit your usage limit. Visit \
10791             https://chatgpt.com/codex/settings/usage to purchase more \
10792             credits or try again at Sep 19th, 2026 5:10 PM.",
10793            now,
10794            now,
10795        )
10796        .expect("the codex reset wording is a recognised shape");
10797        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10798
10799        // The month is explicit, so a date already earlier in the same
10800        // sentence-implied year than `now` is trusted as written rather than
10801        // rolled forward a year the way the bracketed shape rolls a
10802        // same-day clock reading to tomorrow.
10803        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10804            .expect("an explicit year needs no rollover");
10805        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10806
10807        assert!(
10808            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10809            "a two-digit year is not the documented shape and is not guessed at"
10810        );
10811        assert!(
10812            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10813            "a four-letter month name is not the documented three-letter abbreviation"
10814        );
10815        assert!(
10816            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10817            "an explicit zone on the dated shape is a format nobody has \
10818             documented, and is refused rather than guessed at as UTC"
10819        );
10820    }
10821
10822    #[test]
10823    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10824        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10825        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10826
10827        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10828        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10829
10830        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10831        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10832
10833        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10834            assert!(
10835                parse_reset_hint(bad, now, recorded).is_none(),
10836                "{bad:?} must not be guessed at"
10837            );
10838        }
10839    }
10840
10841    /// A loop whose queue lives in a temp tree and whose poll interval is far
10842    /// longer than the test's patience, so anything that waits out a poll
10843    /// instead of noticing the stop fails rather than merely being slow.
10844    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10845        let config = dir.join("magi.toml");
10846        std::fs::write(
10847            &config,
10848            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10849        )
10850        .unwrap();
10851        let opts = Opts {
10852            poll: Duration::from_secs(30),
10853            config: Some(config),
10854            // The explicit fixture config keeps startup cleanup from reading
10855            // machine configuration. This fictional repository likewise
10856            // keeps any best-effort git cleanup away from this checkout.
10857            repo: dir.join("repo"),
10858            ..Opts::default()
10859        };
10860        // The status file goes in a directory that does not exist yet, so its
10861        // creation is itself evidence the loop published one. `worktrees`
10862        // must be just as fictional: the janitor reclaims worktrees under it
10863        // for real, and a test that let it fall through to
10864        // `crate::run::default_worktree_root()` would have it reclaim
10865        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10866        // which is exactly what happened before this function took the
10867        // parameter at all.
10868        let home = dir.join("home");
10869        // These control-only fixtures do not launch native workers. Give the
10870        // independently tested maintenance services a fresh cadence receipt.
10871        let stamps = home.join("service-ticks");
10872        std::fs::create_dir_all(&stamps).unwrap();
10873        for service in ["waiter", "deputies", "release-watch"] {
10874            std::fs::write(
10875                stamps.join(service),
10876                Timestamp::now().as_second().to_string(),
10877            )
10878            .unwrap();
10879        }
10880        for operation in [
10881            "conductor",
10882            "maintenance",
10883            "housekeeping",
10884            "disk-pressure",
10885            "cache",
10886            "fetch",
10887        ] {
10888            std::fs::write(
10889                stamps.join(format!("daemon-{operation}")),
10890                serde_json::to_vec(&Timestamp::now()).unwrap(),
10891            )
10892            .unwrap();
10893        }
10894        let worktrees = dir.join("wt");
10895        (
10896            opts,
10897            Queue::at(dir.join("queue")),
10898            home.join("daemon.json"),
10899            home,
10900            worktrees,
10901        )
10902    }
10903
10904    #[tokio::test]
10905    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
10906        let dir = tempfile::tempdir().unwrap();
10907        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10908        let mut waiting = task();
10909        waiting.repo = opts.repo.clone();
10910        waiting.hold_machine(crate::disk::gate(1, 100));
10911        waiting.mark_disk_capacity();
10912        waiting.attempts = 2;
10913        queue.put(&mut waiting).unwrap();
10914        let mut busy = task();
10915        busy.status = TaskStatus::Running;
10916        queue.put(&mut busy).unwrap();
10917        let payload = serde_json::to_value(ServiceWorker {
10918            opts,
10919            queue: queue.root().to_owned(),
10920            worktrees_root: worktrees,
10921            operation: "maintenance".into(),
10922        })
10923        .unwrap();
10924        run_service_worker(&home, payload.clone()).await.unwrap();
10925        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
10926        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
10927        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
10928        run_service_worker(&home, payload).await.unwrap();
10929        assert!(
10930            crate::worker::active(&home).unwrap().is_empty(),
10931            "monitoring only queues; normal dispatch owns launches"
10932        );
10933        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
10934    }
10935
10936    #[tokio::test]
10937    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
10938        let dir = tempfile::tempdir().unwrap();
10939        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10940        let cfg = Config::default();
10941        start_service(
10942            &home,
10943            &opts,
10944            &queue,
10945            &worktrees,
10946            "housekeeping",
10947            Some(&cfg),
10948            true,
10949        )
10950        .await
10951        .unwrap();
10952        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
10953        let read = |path: &Path| -> serde_json::Value {
10954            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
10955        };
10956        assert_eq!(read(&receipt)["detail"], "cadence not due");
10957        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
10958        start_service(
10959            &home,
10960            &opts,
10961            &queue,
10962            &worktrees,
10963            "housekeeping",
10964            Some(&cfg),
10965            true,
10966        )
10967        .await
10968        .unwrap();
10969        assert_eq!(
10970            read(&receipt)["detail"],
10971            "active work or runnable task queue"
10972        );
10973        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
10974        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
10975        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
10976        start_service(
10977            &home,
10978            &opts,
10979            &queue,
10980            &worktrees,
10981            "disk-pressure",
10982            Some(&cfg),
10983            false,
10984        )
10985        .await
10986        .unwrap();
10987        assert_eq!(
10988            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
10989            "no active work; idle housekeeping owns scan"
10990        );
10991        assert!(crate::worker::active(&home).unwrap().is_empty());
10992    }
10993
10994    #[test]
10995    fn a_stop_is_idempotent_and_once_set_stays_set() {
10996        let stop = Stop::new();
10997        assert!(!stop.stopped());
10998
10999        stop.stop();
11000        assert!(stop.stopped());
11001        stop.stop();
11002        assert!(stop.stopped(), "a second stop is not a toggle");
11003
11004        let shared = stop.clone();
11005        assert!(
11006            shared.stopped(),
11007            "a clone is the same stop; that is how the loop and its caller share one"
11008        );
11009    }
11010
11011    #[tokio::test]
11012    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11013        for operation in ["conductor", "maintenance", "housekeeping"] {
11014            let dir = tempfile::tempdir().unwrap();
11015            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11016            opts.once = true;
11017            opts.poll = Duration::from_millis(1);
11018            let mut task = task();
11019            task.runs.push("fixture-run".into());
11020            queue.put(&mut task).unwrap();
11021            let claim = queue.claim(&task.id).unwrap();
11022
11023            // Model a live service holding the task's claim across the
11024            // scheduler's dispatch scan. No real subprocess or timed race.
11025            let directory = home.join("workers/jobs/abcdef");
11026            std::fs::create_dir_all(&directory).unwrap();
11027            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11028            crate::pr_head::try_lock_file(&lease).unwrap();
11029            let mut job = crate::worker::Job {
11030                id: "abcdef".into(),
11031                sequence: 1,
11032                kind: "daemon-service".into(),
11033                key: format!("service:daemon-{operation}"),
11034                payload: serde_json::Value::Null,
11035                generation: "fixture".into(),
11036                version: None,
11037                status: crate::worker::Status::Running,
11038                result: None,
11039                pid: Some(std::process::id()),
11040                created_at: Timestamp::now().as_second() as u64,
11041                finished_at: None,
11042            };
11043            let record = directory.join("job.json");
11044            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11045
11046            let status = Arc::new(Mutex::new(Status::new()));
11047            let stop = Stop::new();
11048            let mut drain = Box::pin(poll(
11049                &opts,
11050                &queue,
11051                &status,
11052                &home,
11053                &worktrees,
11054                &stop,
11055                DispatchLimits {
11056                    max_concurrent: 1,
11057                    pause_for_interrupts: false,
11058                    recovery_cfg: None,
11059                },
11060            ));
11061            std::future::poll_fn(|cx| {
11062                use std::future::Future;
11063                assert!(
11064                    drain.as_mut().poll(cx).is_pending(),
11065                    "--once must wait for {operation} to release its queue claim"
11066                );
11067                std::task::Poll::Ready(())
11068            })
11069            .await;
11070            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11071
11072            // An answer arrives while the service still owns the claim. A
11073            // fresh scheduling pass must apply it before declaring idle.
11074            let questions = Questions::at(home.join("questions"));
11075            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
11076            questions.put(&mut q).unwrap();
11077            drop(claim);
11078            // Model services that took longer than their cadence, without a
11079            // wall-clock sleep. The final scans must not respawn them even
11080            // though their receipts now permit another periodic invocation.
11081            let expired =
11082                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11083            for service in [operation, "housekeeping"] {
11084                std::fs::write(
11085                    home.join("service-ticks").join(format!("daemon-{service}")),
11086                    &expired,
11087                )
11088                .unwrap();
11089            }
11090            job.status = crate::worker::Status::Finished;
11091            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11092            drop(lease);
11093            tokio::time::timeout(Duration::from_secs(2), drain)
11094                .await
11095                .expect("the settled service must allow the drain to finish")
11096                .unwrap();
11097            let after = queue.get(&task.id).unwrap();
11098            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11099            assert!(after.action_applied(&q.id));
11100            for service in [operation, "housekeeping"] {
11101                assert_eq!(
11102                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11103                        .unwrap(),
11104                    expired,
11105                    "the final once rescan must not restart {service}"
11106                );
11107            }
11108        }
11109    }
11110
11111    #[test]
11112    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11113        let stop = Stop::new();
11114        stop.busy.store(1, Ordering::SeqCst);
11115        assert!(
11116            !stop.finishing(),
11117            "a busy loop nobody has asked to stop is just running"
11118        );
11119
11120        stop.stop();
11121        assert!(
11122            stop.finishing(),
11123            "a stop asked for mid-run has not landed until the run is settled"
11124        );
11125
11126        stop.busy.store(0, Ordering::SeqCst);
11127        assert!(
11128            !stop.finishing(),
11129            "once the run is settled the stop has landed and there is nothing to finish"
11130        );
11131    }
11132
11133    #[test]
11134    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11135        let stop = Stop::new();
11136        stop.busy.store(2, Ordering::SeqCst);
11137        stop.stop();
11138        assert!(stop.finishing(), "two runs still in flight");
11139
11140        stop.busy.store(1, Ordering::SeqCst);
11141        assert!(
11142            stop.finishing(),
11143            "one run finished, but a sibling is still working"
11144        );
11145
11146        stop.busy.store(0, Ordering::SeqCst);
11147        assert!(
11148            !stop.finishing(),
11149            "the last run out is what actually lands the stop"
11150        );
11151    }
11152
11153    #[tokio::test]
11154    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11155        let dir = tempfile::tempdir().unwrap();
11156        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11157        let stop = Stop::new();
11158        stop.stop();
11159
11160        let began = std::time::Instant::now();
11161        tokio::time::timeout(
11162            Duration::from_secs(2),
11163            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11164        )
11165        .await
11166        .expect("a stopped loop must return, not sit out its poll interval")
11167        .expect("the loop's own setup and teardown must not fail");
11168        assert!(
11169            began.elapsed() < opts.poll,
11170            "returned only after {:?}, which is a poll interval, not a stop",
11171            began.elapsed()
11172        );
11173    }
11174
11175    #[tokio::test]
11176    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11177        let dir = tempfile::tempdir().unwrap();
11178        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11179        let stop = Stop::new();
11180
11181        // Asked for after the loop is already parked on its empty queue, which
11182        // is the case an operator tapping stop on a phone actually hits.
11183        let asker = {
11184            let stop = stop.clone();
11185            tokio::spawn(async move {
11186                tokio::time::sleep(Duration::from_millis(20)).await;
11187                stop.stop();
11188            })
11189        };
11190
11191        let began = std::time::Instant::now();
11192        tokio::time::timeout(
11193            Duration::from_secs(2),
11194            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11195        )
11196        .await
11197        .expect("a stop asked for while idle must wake the wait")
11198        .expect("the loop's own setup and teardown must not fail");
11199        asker.await.unwrap();
11200        assert!(
11201            began.elapsed() < opts.poll,
11202            "returned only after {:?}, so the stop waited on the sleep",
11203            began.elapsed()
11204        );
11205    }
11206
11207    #[tokio::test]
11208    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11209        let dir = tempfile::tempdir().unwrap();
11210        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11211        let stop = Stop::new();
11212        stop.stop();
11213
11214        tokio::time::timeout(
11215            Duration::from_secs(2),
11216            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11217        )
11218        .await
11219        .expect("a stopped loop must return")
11220        .expect("the loop's own setup and teardown must not fail");
11221
11222        assert!(
11223            home.is_dir(),
11224            "the loop did publish a status file, so its removal is the teardown and not an absence"
11225        );
11226        assert!(
11227            !status_file.exists(),
11228            "a stopped loop clears its status file"
11229        );
11230        assert!(
11231            read_status(&home).is_none(),
11232            "a reader must see no daemon at all, not a heartbeat that merely stopped"
11233        );
11234    }
11235
11236    #[tokio::test]
11237    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
11238        let dir = tempfile::tempdir().unwrap();
11239        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11240
11241        let mut settled = RunState::new(
11242            dir.path().join("repo"),
11243            "main".to_owned(),
11244            "abc1234".to_owned(),
11245            "fixture".to_owned(),
11246            Config::default(),
11247        );
11248        settled.status = RunStatus::Ready;
11249        let run_dir = home.join("runs").join(&settled.id);
11250        std::fs::create_dir_all(&run_dir).unwrap();
11251        std::fs::write(
11252            run_dir.join("run.json"),
11253            serde_json::to_string_pretty(&settled).unwrap(),
11254        )
11255        .unwrap();
11256        let questions = Questions::at(home.join("questions"));
11257        let mut question = ask::Question::new(
11258            settled.id.clone(),
11259            "review".to_owned(),
11260            "reviewer-1".to_owned(),
11261            "Continue?".to_owned(),
11262            String::new(),
11263            Vec::new(),
11264        );
11265        questions.put(&mut question).unwrap();
11266
11267        run_service_worker(
11268            &home,
11269            serde_json::to_value(ServiceWorker {
11270                opts,
11271                queue: queue.root().to_path_buf(),
11272                worktrees_root: worktrees,
11273                operation: "housekeeping".to_owned(),
11274            })
11275            .unwrap(),
11276        )
11277        .await
11278        .unwrap();
11279
11280        assert_eq!(
11281            questions.get(&question.id).unwrap().status,
11282            ask::QuestionStatus::Abandoned,
11283            "the independent housekeeping worker settles ended-run questions"
11284        );
11285    }
11286
11287    #[test]
11288    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11289        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11290
11291        assert!(
11292            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11293            "never checked before: due at once"
11294        );
11295
11296        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11297        assert!(
11298            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11299            "well inside the interval: not due yet"
11300        );
11301
11302        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11303        assert!(
11304            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11305            "exactly at the edge: not yet due, same convention as `clean::due`"
11306        );
11307
11308        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11309        assert!(
11310            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11311            "past the interval: due again"
11312        );
11313    }
11314
11315    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
11316    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
11317    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
11318    /// and the congestion test below both need, and must not drift apart.
11319    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11320        let config = dir.join("magi.toml");
11321        // A literal (single-quoted) TOML string, not a basic one: the cache
11322        // path is a Windows path full of backslashes, and a basic string
11323        // would have TOML try to interpret `\U` (from `\Users\...`) as a
11324        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
11325        // `{{ vars.cache }}` rendering documents.
11326        std::fs::write(
11327            &config,
11328            format!(
11329                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
11330                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
11331                cache_dir.display()
11332            ),
11333        )
11334        .unwrap();
11335        Opts {
11336            config: Some(config),
11337            repo: dir.join("repo"),
11338            ..Opts::default()
11339        }
11340    }
11341
11342    #[tokio::test]
11343    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
11344        let dir = tempfile::tempdir().unwrap();
11345        let home = dir.path().join("home");
11346        let cache_dir = dir.path().join("cache");
11347        std::fs::create_dir_all(&cache_dir).unwrap();
11348        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11349        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11350
11351        // Nobody has asked this daemon to stop, which is the ordinary case;
11352        // the skip that a stop buys is asserted by its own test below.
11353        let running = Stop::new();
11354        let mut last_checked = None;
11355        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11356        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
11357            .await;
11358        assert_eq!(
11359            crate::disk::dir_size(&cache_dir),
11360            0,
11361            "over the cap on the first check ever: pruned at once, no idle queue required"
11362        );
11363        assert_eq!(last_checked, Some(t0));
11364
11365        // A fresh oversized file lands, but the next check is not due yet.
11366        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11367        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11368        maybe_prune_cache_between_runs(
11369            &opts.repo,
11370            &opts,
11371            &home,
11372            &running,
11373            &mut last_checked,
11374            too_soon,
11375        )
11376        .await;
11377        assert_eq!(
11378            crate::disk::dir_size(&cache_dir),
11379            10,
11380            "too soon since the last check: left alone rather than rescanned every call"
11381        );
11382        assert_eq!(
11383            last_checked,
11384            Some(t0),
11385            "an idle check does not reset the clock"
11386        );
11387
11388        // Once the interval elapses, the same oversized cache is caught again.
11389        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11390        maybe_prune_cache_between_runs(
11391            &opts.repo,
11392            &opts,
11393            &home,
11394            &running,
11395            &mut last_checked,
11396            due_again,
11397        )
11398        .await;
11399        assert_eq!(
11400            crate::disk::dir_size(&cache_dir),
11401            0,
11402            "due again: pruned back under the cap"
11403        );
11404    }
11405
11406    /// A stop must not queue behind housekeeping. The prune below is a
11407    /// synchronous walk of the whole cache with no await point in it, so a
11408    /// loop that entered it could not get back to its own `stopped()` test
11409    /// until the walk finished - and because no run is in flight at this
11410    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
11411    /// the stop had already landed. The idle branch has always made this same
11412    /// check before reaching `janitor`; the between-runs path makes it too.
11413    #[tokio::test]
11414    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
11415        let dir = tempfile::tempdir().unwrap();
11416        let home = dir.path().join("home");
11417        let cache_dir = dir.path().join("cache");
11418        std::fs::create_dir_all(&cache_dir).unwrap();
11419        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11420        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11421
11422        let stop = Stop::new();
11423        stop.stop();
11424        assert!(
11425            !stop.finishing(),
11426            "no run is in flight at a between-runs boundary, so nothing else \
11427             would tell the operator this stop had not taken effect yet"
11428        );
11429
11430        let mut last_checked = None;
11431        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11432        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
11433            .await;
11434        assert_eq!(
11435            crate::disk::dir_size(&cache_dir),
11436            10,
11437            "over its cap, and due for the first check ever, but a stop outranks \
11438             it: the cap is a standing policy the next start measures again"
11439        );
11440        assert_eq!(
11441            last_checked, None,
11442            "a check that never happened must not claim the interval"
11443        );
11444    }
11445
11446    /// A backlog must not starve cache pruning. The finite cache worker runs
11447    /// independently of queue drain and must not consume any task attempts.
11448    #[tokio::test]
11449    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
11450        let dir = tempfile::tempdir().unwrap();
11451        let cache_dir = dir.path().join("cache");
11452        std::fs::create_dir_all(&cache_dir).unwrap();
11453        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
11454
11455        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
11456        opts.poll = Duration::from_millis(20);
11457        opts.max_attempts = 1_000;
11458
11459        let queue = Queue::at(dir.path().join("queue"));
11460        for i in 0..128 {
11461            let mut task = Task::new(
11462                format!("queued work {i}"),
11463                format!("queued work {i}"),
11464                opts.repo.clone(),
11465                Source::Human,
11466            );
11467            queue.put(&mut task).unwrap();
11468        }
11469
11470        let home = dir.path().join("home");
11471        let worktrees = dir.path().join("wt");
11472        run_service_worker(
11473            &home,
11474            serde_json::to_value(ServiceWorker {
11475                opts,
11476                queue: queue.root().to_path_buf(),
11477                worktrees_root: worktrees,
11478                operation: "cache".to_owned(),
11479            })
11480            .unwrap(),
11481        )
11482        .await
11483        .unwrap();
11484        let after = queue.list();
11485        assert_eq!(after.len(), 128);
11486        assert!(
11487            after
11488                .iter()
11489                .all(|task| task.status.runnable() && task.attempts == 0)
11490        );
11491
11492        assert_eq!(
11493            crate::disk::dir_size(&cache_dir),
11494            0,
11495            "an oversized cache must not be left to grow unboundedly just because the \
11496             queue kept the loop busy the whole time"
11497        );
11498    }
11499
11500    #[test]
11501    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
11502        let dir = tempfile::tempdir().unwrap();
11503        let queue = Queue::at(dir.path().join("queue"));
11504        let questions = Questions::at(dir.path().join("questions"));
11505        let mut task = task();
11506        queue.put(&mut task).unwrap();
11507
11508        let mut task_question = ask::Question::new(
11509            task.id.clone(),
11510            crate::conduct::NODE.to_owned(),
11511            "conduct".to_owned(),
11512            "Which backend?".to_owned(),
11513            String::new(),
11514            Vec::new(),
11515        );
11516        questions.put(&mut task_question).unwrap();
11517        task.block(vec![task_question.id.clone()], None);
11518        queue.put(&mut task).unwrap();
11519
11520        let mut run_question = ask::Question::new(
11521            "20260101-000000-run1".to_owned(),
11522            "review".to_owned(),
11523            "reviewer-1".to_owned(),
11524            "Run question".to_owned(),
11525            String::new(),
11526            Vec::new(),
11527        );
11528        questions.put(&mut run_question).unwrap();
11529
11530        // A question from another node whose `run` happens to equal this
11531        // task's id — the same field, filled in for an unrelated reason. Only
11532        // `crate::conduct::NODE` questions use `run` as a task id; this one
11533        // must never be touched by this reconciliation, even after release.
11534        let mut coincidental = ask::Question::new(
11535            task.id.clone(),
11536            "review".to_owned(),
11537            "reviewer-1".to_owned(),
11538            "Unrelated review question".to_owned(),
11539            String::new(),
11540            Vec::new(),
11541        );
11542        questions.put(&mut coincidental).unwrap();
11543
11544        reconcile_task_questions(&queue, &questions);
11545        assert!(questions.get(&task_question.id).unwrap().status.open());
11546        assert!(questions.get(&run_question.id).unwrap().status.open());
11547        assert!(questions.get(&coincidental.id).unwrap().status.open());
11548
11549        task.release();
11550        queue.put(&mut task).unwrap();
11551        reconcile_task_questions(&queue, &questions);
11552        assert_eq!(
11553            questions.get(&task_question.id).unwrap().status,
11554            ask::QuestionStatus::Abandoned
11555        );
11556        assert!(
11557            questions.get(&run_question.id).unwrap().status.open(),
11558            "run questions remain the run janitor's responsibility"
11559        );
11560        assert!(
11561            questions.get(&coincidental.id).unwrap().status.open(),
11562            "a non-conductor question must not be abandoned just because its \
11563             run id coincides with a task id"
11564        );
11565    }
11566
11567    #[test]
11568    fn a_freshly_started_running_task_is_never_stalled() {
11569        let dir = tempfile::tempdir().unwrap();
11570        let mut t = task();
11571        t.start("run-1".to_owned());
11572        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
11573        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
11574        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
11575    }
11576
11577    #[test]
11578    fn a_long_running_task_with_no_live_daemon_is_stalled() {
11579        let dir = tempfile::tempdir().unwrap();
11580        let mut t = task();
11581        t.start("run-1".to_owned());
11582        t.updated_at = Timestamp::now()
11583            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11584        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
11585        assert_eq!(
11586            stalled_tasks(
11587                &Queue::at(dir.path().join("q")),
11588                dir.path(),
11589                Timestamp::now()
11590            )
11591            .len(),
11592            0,
11593            "the task was never written to this queue"
11594        );
11595    }
11596
11597    #[test]
11598    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
11599        let dir = tempfile::tempdir().unwrap();
11600        let mut t = task();
11601        t.id = "20260903-080340-0167".to_owned();
11602        t.start("20260903-080619-01c2".to_owned());
11603        t.updated_at = Timestamp::now()
11604            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11605
11606        let mut status = Status::new();
11607        status.current = vec![Current {
11608            worker: None,
11609            task: t.id.clone(),
11610            run: "20260903-080619-01c2".to_owned(),
11611        }];
11612        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11613
11614        assert!(
11615            !is_stalled(&t, dir.path(), Timestamp::now()),
11616            "a live daemon's own heartbeat rules out stalled, however long the task has run"
11617        );
11618    }
11619
11620    /// Rewrite a task's `updated_at` on disk directly, bypassing
11621    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
11622    /// a fixture look like it has genuinely been `running` for a while.
11623    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
11624        let path = queue.path_of(id);
11625        let body = std::fs::read_to_string(&path).unwrap();
11626        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
11627        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
11628        v["updated_at"] = serde_json::Value::String(old.to_string());
11629        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
11630    }
11631
11632    #[test]
11633    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
11634        // The realistic `poll()` ordering, not `is_stalled` in isolation:
11635        // `reclaim_orphaned_running` runs first, on every poll, and settles
11636        // any `running` task whose claim it can actually take. For most
11637        // crashes that is immediate - a dead pid is proof enough for
11638        // `sweep_stale_claims` to drop the lock the same tick, and the very
11639        // next claim attempt succeeds. But a lock whose pid cannot be parsed
11640        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
11641        // `sweep_stale_claims`'s own doc), so the lock - and the claim
11642        // failure behind it - can legitimately outlive many polls. This is
11643        // exactly the gap `stalled_tasks` exists to surface well before that
11644        // six-hour sweep would: reclaim leaves the task `running`, and it
11645        // must still reach the conductor as stalled.
11646        let dir = tempfile::tempdir().unwrap();
11647        let queue = Queue::at(dir.path().join("queue"));
11648        let home = dir.path().join("home");
11649
11650        let mut t = task();
11651        t.id = "20260101-000001-lock".to_owned();
11652        t.start("run-1".to_owned());
11653        queue.put(&mut t).unwrap();
11654        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11655        std::fs::write(
11656            dir.path().join("queue").join(format!("{}.lock", t.id)),
11657            "not a pid",
11658        )
11659        .unwrap();
11660
11661        let now = Timestamp::now();
11662        assert!(
11663            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
11664            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
11665             and reclaim must leave the task alone"
11666        );
11667        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11668
11669        let stalled = stalled_tasks(&queue, &home, now);
11670        assert_eq!(
11671            stalled.len(),
11672            1,
11673            "reclaim's inability to claim it yet must not hide it from the conductor"
11674        );
11675        assert_eq!(stalled[0].id, t.id);
11676    }
11677
11678    #[test]
11679    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
11680        let dir = tempfile::tempdir().unwrap();
11681        crate::run::set_home(dir.path().join("run-home"));
11682        let queue = Queue::at(dir.path().join("queue"));
11683        let home = dir.path().join("home");
11684        let questions = Questions::at(dir.path().join("questions"));
11685
11686        let mut t = task();
11687        t.id = "20260101-000003-dead".to_owned();
11688        t.start("missing-run".to_owned());
11689        queue.put(&mut t).unwrap();
11690        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11691
11692        // This is the real poll ordering: retain the deterministic stalled
11693        // input before a claim proves the owner is gone and reclaims it.
11694        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11695        assert_eq!(
11696            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
11697            [&t.id]
11698        );
11699        assert_eq!(
11700            reclaim_orphaned_running(&queue, 2, &Default::default()),
11701            [t.id.clone()]
11702        );
11703        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11704
11705        // Reclaim drops its guard before conductor decisions are applied, so
11706        // the decision for the captured stalled input has a real write path.
11707        crate::conduct::apply(
11708            &queue,
11709            &questions,
11710            &crate::conduct::Verdict {
11711                decisions: vec![crate::conduct::Decision {
11712                    id: t.id.clone(),
11713                    recovery: Some(crate::conduct::Recovery::Requeue),
11714                    ..crate::conduct::Decision::default()
11715                }],
11716            },
11717        )
11718        .unwrap();
11719        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11720    }
11721
11722    #[test]
11723    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
11724        let dir = tempfile::tempdir().unwrap();
11725        let queue = Queue::at(dir.path().join("queue"));
11726        let home = dir.path().join("home");
11727
11728        let mut fresh = task();
11729        fresh.id = "20260101-000001-aaaa".to_owned();
11730        fresh.start("run-1".to_owned());
11731        queue.put(&mut fresh).unwrap();
11732
11733        let mut old = task();
11734        old.id = "20260101-000002-bbbb".to_owned();
11735        old.start("run-2".to_owned());
11736        queue.put(&mut old).unwrap();
11737        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
11738
11739        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11740        assert_eq!(stalled.len(), 1);
11741        assert_eq!(stalled[0].id, old.id);
11742    }
11743
11744    #[test]
11745    fn queued_and_finished_task_views_partition_by_status() {
11746        let dir = tempfile::tempdir().unwrap();
11747        let queue = Queue::at(dir.path().join("queue"));
11748
11749        let mut queued = task();
11750        queued.id = "20260101-000001-aaaa".to_owned();
11751        queue.put(&mut queued).unwrap();
11752
11753        let mut failed = task();
11754        failed.id = "20260101-000002-bbbb".to_owned();
11755        failed.start("run-1".to_owned());
11756        failed.fail("gate red", 5);
11757        queue.put(&mut failed).unwrap();
11758
11759        let mut held = task();
11760        held.id = "20260101-000003-cccc".to_owned();
11761        held.hold_machine(None);
11762        queue.put(&mut held).unwrap();
11763
11764        let mut running = task();
11765        running.id = "20260101-000004-dddd".to_owned();
11766        running.start("run-2".to_owned());
11767        queue.put(&mut running).unwrap();
11768
11769        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11770        assert_eq!(queued_ids, [queued.id.clone()]);
11771
11772        let mut finished_ids: Vec<String> =
11773            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11774        finished_ids.sort_unstable();
11775        let mut want = vec![failed.id.clone(), held.id.clone()];
11776        want.sort_unstable();
11777        assert_eq!(finished_ids, want);
11778    }
11779
11780    #[test]
11781    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11782        for short in [false, true] {
11783            let dir = tempfile::tempdir().unwrap();
11784            let queue = Queue::at(dir.path().join("queue"));
11785            let questions = ask::Questions::at(dir.path().join("questions"));
11786            let mut running = task();
11787            running.id = "20261013-192213-feb2".into();
11788            running.start("existing-run".into());
11789            queue.put(&mut running).unwrap();
11790            let mut middle = task();
11791            middle.id = "20261013-193611-ca5b".into();
11792            middle.block(
11793                vec![if short {
11794                    "feb2".into()
11795                } else {
11796                    running.id.clone()
11797                }],
11798                None,
11799            );
11800            queue.put(&mut middle).unwrap();
11801            let mut waiting = task();
11802            waiting.id = "20261013-202849-ee37".into();
11803            waiting.block(
11804                vec![if short {
11805                    "ca5b".into()
11806                } else {
11807                    middle.id.clone()
11808                }],
11809                Some("wait for implementation".into()),
11810            );
11811            queue.put(&mut waiting).unwrap();
11812            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11813            let inv = crate::blockers::Inventory::load(&queue, &questions);
11814            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11815            assert!(inv.stuck().is_empty());
11816            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11817            assert!(report.quarantined.is_empty());
11818            assert!(report.asked.is_empty());
11819            resolve_blockers(&queue, &questions);
11820            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11821            assert!(questions.list().is_empty());
11822            // Finishing the transitive prerequisite alone does not satisfy
11823            // the task's direct dependency.
11824            running.succeed();
11825            queue.put(&mut running).unwrap();
11826            resolve_blockers(&queue, &questions);
11827            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11828            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11829            middle = queue.get(&middle.id).unwrap();
11830            middle.succeed();
11831            queue.put(&mut middle).unwrap();
11832            resolve_blockers(&queue, &questions);
11833            let after = queue.get(&waiting.id).unwrap();
11834            assert_eq!(after.status, TaskStatus::Queued);
11835            assert!(after.blocked_by.is_empty());
11836            assert_eq!(after.instruction, waiting.instruction);
11837        }
11838    }
11839
11840    #[test]
11841    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11842        for future_schema in [false, true] {
11843            let name = "20261013-193611-ca5b";
11844            let mut future = task();
11845            future.id = name.into();
11846            future.schema = crate::queue::SCHEMA + 1;
11847            let contents = if future_schema {
11848                serde_json::to_string(&future).unwrap()
11849            } else {
11850                "corrupt".into()
11851            };
11852            let dir = tempfile::tempdir().unwrap();
11853            let queue = Queue::at(dir.path().join("queue"));
11854            let questions = ask::Questions::at(dir.path().join("questions"));
11855            let mut waiting = task();
11856            waiting.id = "20261013-202849-ee37".into();
11857            waiting.block(vec!["ca5b".into()], None);
11858            queue.put(&mut waiting).unwrap();
11859            std::fs::write(queue.path_of(name), contents).unwrap();
11860            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11861            assert!(
11862                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11863            );
11864            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11865            assert!(report.asked.is_empty());
11866            resolve_blockers(&queue, &questions);
11867            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11868            assert!(questions.list().is_empty());
11869        }
11870        let dir = tempfile::tempdir().unwrap();
11871        let queue = Queue::at(dir.path().join("queue"));
11872        let questions = ask::Questions::at(dir.path().join("questions"));
11873        let mut waiting = task();
11874        waiting.id = "20261013-202849-ee37".into();
11875        waiting.block(vec!["ca5b".into()], None);
11876        queue.put(&mut waiting).unwrap();
11877        let mut done = task();
11878        done.id = "20261013-193611-ca5b".into();
11879        done.succeed();
11880        queue.put(&mut done).unwrap();
11881        // An unreadable second match must not disappear from uniqueness
11882        // checks just because Queue::list skips it.
11883        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11884        assert!(queue.get("ca5b").is_err());
11885        assert_eq!(
11886            crate::queue::dependency(&queue, &questions, "ca5b"),
11887            crate::queue::Dependency::Ambiguous
11888        );
11889        resolve_blockers(&queue, &questions);
11890        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11891        assert!(report.asked.is_empty());
11892        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11893        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11894    }
11895
11896    #[test]
11897    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11898        for held in [false, true] {
11899            for question in [false, true] {
11900                for reference in ["ca5b", "20261013-193611-ca5b"] {
11901                    let dir = tempfile::tempdir().unwrap();
11902                    let queue = Queue::at(dir.path().join("queue"));
11903                    let questions = ask::Questions::at(dir.path().join("questions"));
11904                    let mut prerequisite = task();
11905                    prerequisite.id = "20261013-193611-ca5b".into();
11906                    prerequisite.start("existing-run".into());
11907                    queue.put(&mut prerequisite).unwrap();
11908                    let mut waiting = task();
11909                    waiting.id = "20261013-202849-ee37".into();
11910                    if held {
11911                        waiting.hold_machine(Some("waiting for separate consent".into()));
11912                    }
11913                    queue.put(&mut waiting).unwrap();
11914                    let reason = "Deleting saved data requires separate owner consent";
11915                    crate::conduct::apply(
11916                        &queue,
11917                        &questions,
11918                        &crate::conduct::Verdict {
11919                            decisions: vec![crate::conduct::Decision {
11920                                id: waiting.id.clone(),
11921                                blocked_by: vec![reference.into()],
11922                                question: question.then(|| "May the saved data be deleted?".into()),
11923                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11924                                reason: Some(reason.into()),
11925                                ..crate::conduct::Decision::default()
11926                            }],
11927                        },
11928                    )
11929                    .unwrap();
11930                    let before = queue.get(&waiting.id).unwrap();
11931                    if question {
11932                        assert_eq!(before.status, TaskStatus::Blocked);
11933                        let q = questions.get(&before.blocked_by[0]).unwrap();
11934                        assert_eq!(q.summary, "May the saved data be deleted?");
11935                        assert!(q.status.open());
11936                    } else {
11937                        assert_eq!(before.status, TaskStatus::Held);
11938                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11939                        assert!(recorded_reason.starts_with(reason));
11940                        if held {
11941                            assert!(recorded_reason.contains("waiting for separate consent"));
11942                        }
11943                    }
11944                    prerequisite.succeed();
11945                    queue.put(&mut prerequisite).unwrap();
11946                    resolve_blockers(&queue, &questions);
11947                    let after = queue.get(&waiting.id).unwrap();
11948                    assert_eq!(after.status, before.status);
11949                    assert_eq!(after.blocked_by, before.blocked_by);
11950                    assert_eq!(after.hold_reason, before.hold_reason);
11951                    assert_eq!(after.instruction, waiting.instruction);
11952                    if question {
11953                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11954                    }
11955                    assert!(
11956                        queue.next_runnable().is_none(),
11957                        "dependency completion is not consent"
11958                    );
11959                }
11960            }
11961        }
11962    }
11963
11964    #[test]
11965    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11966        let dir = tempfile::tempdir().unwrap();
11967        let queue = Queue::at(dir.path().join("queue"));
11968        let questions = ask::Questions::at(dir.path().join("questions"));
11969
11970        let mut dep = task();
11971        dep.id = "20260101-000001-dep0".to_owned();
11972        dep.succeed();
11973        queue.put(&mut dep).unwrap();
11974
11975        let mut still_going = task();
11976        still_going.id = "20260101-000002-dep1".to_owned();
11977        queue.put(&mut still_going).unwrap();
11978
11979        let mut blocked = task();
11980        blocked.id = "20260101-000003-main".to_owned();
11981        blocked.block(
11982            vec![dep.id.clone(), still_going.id.clone()],
11983            Some("waits on both".to_owned()),
11984        );
11985        queue.put(&mut blocked).unwrap();
11986
11987        resolve_blockers(&queue, &questions);
11988
11989        let after = queue.get(&blocked.id).unwrap();
11990        assert_eq!(
11991            after.status,
11992            TaskStatus::Blocked,
11993            "one dependency is still outstanding"
11994        );
11995        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11996    }
11997
11998    #[test]
11999    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12000        let dir = tempfile::tempdir().unwrap();
12001        let queue = Queue::at(dir.path().join("queue"));
12002        let questions = ask::Questions::at(dir.path().join("questions"));
12003
12004        let mut q = crate::ask::Question::new(
12005            "20260101-000001-main".to_owned(),
12006            crate::conduct::NODE.to_owned(),
12007            "conduct".to_owned(),
12008            "Which backend?".to_owned(),
12009            String::new(),
12010            Vec::new(),
12011        );
12012        questions.put(&mut q).unwrap();
12013        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12014            .unwrap();
12015        questions.put(&mut q).unwrap();
12016
12017        let mut blocked = task();
12018        blocked.id = "20260101-000001-main".to_owned();
12019        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12020        queue.put(&mut blocked).unwrap();
12021
12022        resolve_blockers(&queue, &questions);
12023
12024        let after = queue.get(&blocked.id).unwrap();
12025        assert_eq!(
12026            after.status,
12027            TaskStatus::Queued,
12028            "the only blocker resolved"
12029        );
12030        assert_eq!(after.answers.len(), 1);
12031        assert_eq!(after.answers[0].question, "Which backend?");
12032        assert_eq!(after.answers[0].answer, "SQLite");
12033
12034        // And the run this task starts next is told about it.
12035        let instruction = instruction_for(&after);
12036        assert!(instruction.contains("Which backend?"));
12037        assert!(instruction.contains("SQLite"));
12038    }
12039
12040    #[test]
12041    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12042        let dir = tempfile::tempdir().unwrap();
12043        let queue = Queue::at(dir.path().join("queue"));
12044        let questions = ask::Questions::at(dir.path().join("questions"));
12045
12046        let mut q = crate::ask::Question::new(
12047            "20260101-000001-main".to_owned(),
12048            crate::conduct::NODE.to_owned(),
12049            "conduct".to_owned(),
12050            "Is the setup done?".to_owned(),
12051            String::new(),
12052            Vec::new(),
12053        );
12054        q.abandon("no answer within 60s of asking");
12055        questions.put(&mut q).unwrap();
12056
12057        let mut blocked = task();
12058        blocked.id = "20260101-000001-main".to_owned();
12059        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12060        queue.put(&mut blocked).unwrap();
12061
12062        resolve_blockers(&queue, &questions);
12063
12064        let after = queue.get(&blocked.id).unwrap();
12065        assert_eq!(
12066            after.status,
12067            TaskStatus::Held,
12068            "never left blocked on nothing"
12069        );
12070        assert!(!after.operator_held(), "a machine hold, for triage");
12071        assert!(
12072            after
12073                .hold_reason
12074                .as_deref()
12075                .unwrap_or_default()
12076                .contains("went unanswered")
12077        );
12078    }
12079
12080    #[test]
12081    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12082        // Reproduces the reported bug (task 3958): a task held out of
12083        // attempts, blocked on a `crate::conduct` follow-up question, must
12084        // come back `held` once that question is answered - never `queued`,
12085        // whatever the answer said - or it silently re-enters the
12086        // competition queue with its attempts already exhausted.
12087        let dir = tempfile::tempdir().unwrap();
12088        let queue = Queue::at(dir.path().join("queue"));
12089        let questions = ask::Questions::at(dir.path().join("questions"));
12090
12091        let mut q = crate::ask::Question::new(
12092            "20260101-000001-main".to_owned(),
12093            crate::conduct::NODE.to_owned(),
12094            "conduct".to_owned(),
12095            "How should this be handled?".to_owned(),
12096            String::new(),
12097            Vec::new(),
12098        );
12099        questions.put(&mut q).unwrap();
12100        q.answer(crate::ask::Answer::Text(
12101            "leave it held, a human will look at it later".to_owned(),
12102        ))
12103        .unwrap();
12104        questions.put(&mut q).unwrap();
12105
12106        let mut held = task();
12107        held.id = "20260101-000001-main".to_owned();
12108        held.hold_machine(Some("out of attempts".to_owned()));
12109        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12110        queue.put(&mut held).unwrap();
12111
12112        resolve_blockers(&queue, &questions);
12113
12114        let after = queue.get(&held.id).unwrap();
12115        assert_eq!(after.status, TaskStatus::Held);
12116        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12117        assert_eq!(
12118            after.answers[0].answer,
12119            "leave it held, a human will look at it later"
12120        );
12121    }
12122
12123    #[test]
12124    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
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        let mut dep = task();
12129        dep.id = "20260101-000001-gone".to_owned();
12130        queue.put(&mut dep).unwrap();
12131        let mut blocked = task();
12132        blocked.id = "20260101-000003-main".to_owned();
12133        blocked.block(vec![dep.id.clone()], None);
12134        queue.put(&mut blocked).unwrap();
12135
12136        // Claimed, so `remove` cannot rewrite it and the resolver must.
12137        let claim = queue.claim(&blocked.id).unwrap();
12138        queue.remove(&dep.id, false, &questions).unwrap();
12139        drop(claim);
12140        resolve_blockers(&queue, &questions);
12141
12142        let after = queue.get(&blocked.id).unwrap();
12143        assert_eq!(after.status, TaskStatus::Queued);
12144        assert!(after.blocked_by.is_empty());
12145    }
12146
12147    #[test]
12148    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12149        // Reproduces the reported bug: a task blocked on a task id that was
12150        // removed (`magi task rm`, or deleted by hand) can never see that id
12151        // reach `Done`, so the ordinary per-id loop has nothing to notice and
12152        // would otherwise leave the task `blocked` forever with no way for an
12153        // operator to find out why.
12154        let dir = tempfile::tempdir().unwrap();
12155        let queue = Queue::at(dir.path().join("queue"));
12156        let questions = ask::Questions::at(dir.path().join("questions"));
12157
12158        let mut still_going = task();
12159        still_going.id = "20260101-000002-dep1".to_owned();
12160        queue.put(&mut still_going).unwrap();
12161
12162        let mut blocked = task();
12163        blocked.id = "20260101-000003-main".to_owned();
12164        blocked.block(
12165            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12166            Some("waits on both".to_owned()),
12167        );
12168        queue.put(&mut blocked).unwrap();
12169
12170        resolve_blockers(&queue, &questions);
12171
12172        let after = queue.get(&blocked.id).unwrap();
12173        assert_eq!(
12174            after.status,
12175            TaskStatus::Held,
12176            "a missing dependency must not leave the task blocked forever"
12177        );
12178        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12179        assert!(after.blocked_by.is_empty());
12180        let reason = after.hold_reason.as_deref().unwrap_or_default();
12181        assert!(
12182            reason.contains("20260101-000001-gone"),
12183            "the missing id must be named so an operator can tell what happened: {reason}"
12184        );
12185        assert!(
12186            reason.contains(&still_going.id),
12187            "the still-valid dependency must not silently vanish from the record: {reason}"
12188        );
12189    }
12190
12191    #[test]
12192    fn instruction_for_is_unchanged_without_any_answers() {
12193        let t = task();
12194        assert_eq!(instruction_for(&t), t.instruction);
12195    }
12196
12197    #[test]
12198    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12199        let dir = tempfile::tempdir().unwrap();
12200        let q = Queue::at(dir.path().join("queue"));
12201        let src = dir.path().join("shot.png");
12202        std::fs::write(&src, "x").unwrap();
12203        let mut t = task();
12204        q.attach(&mut t, &[src]).unwrap();
12205        let paths = task_attachments(&q, &t).unwrap();
12206        assert_eq!(paths.len(), 1);
12207        assert!(paths[0].is_absolute() && paths[0].is_file());
12208        std::fs::remove_file(&paths[0]).unwrap();
12209        let err = task_attachments(&q, &t).unwrap_err().to_string();
12210        assert!(err.contains("shot.png"), "{err}");
12211    }
12212
12213    #[tokio::test]
12214    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
12215        let dir = tempfile::tempdir().unwrap();
12216        let queue_path = dir.path().join("queue");
12217        let queue = Queue::at(queue_path.clone());
12218        let mut t = task();
12219        t.source = Source::Agent {
12220            run: "originating-chat".into(),
12221            node: crate::queue::CHAT_NODE.into(),
12222        };
12223        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
12224            stage: "config-fetch",
12225            target: "origin/main".into(),
12226        });
12227        record_config_failure(&mut t, &fetch);
12228        t.hold_machine(Some(format!("{fetch:#}")));
12229        let fetch_key = t.chat_notice_due().unwrap();
12230        t.chat_notices.push(fetch_key.clone());
12231        queue.put(&mut t).unwrap();
12232
12233        let queue = Queue::at(queue_path);
12234        let mut t = queue.get(&t.id).unwrap();
12235        let a = dir.path().join("a.toml");
12236        let b = dir.path().join("b.toml");
12237        for (path, text, new_cause) in [
12238            (&a, "[graph", true),
12239            (&a, "[verify", false),
12240            (&a, "[graph]\nimplementers = 'invalid-type'", true),
12241            (&b, "[graph]\nimplementers = 'invalid-type'", true),
12242        ] {
12243            t.release_operator("test", None);
12244            std::fs::write(path, text).unwrap();
12245            let error = Config::discover_fetched(dir.path(), Some(path))
12246                .await
12247                .unwrap_err();
12248            record_config_failure(&mut t, &error);
12249            t.hold_machine(Some(format!("{error:#}")));
12250            let due = t.chat_notice_due();
12251            assert_eq!(due.is_some(), new_cause, "{error:#}");
12252            if let Some(key) = due {
12253                assert_ne!(key, fetch_key);
12254                t.chat_notices.push(key);
12255            }
12256        }
12257        t.succeed();
12258        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
12259    }
12260
12261    #[test]
12262    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12263        let dir = tempfile::tempdir().unwrap();
12264        let queue_path = dir.path().join("queue");
12265        let queue = Queue::at(queue_path.clone());
12266        let mut t = task();
12267        t.source = crate::queue::Source::Agent {
12268            run: "originating-chat".into(),
12269            node: crate::queue::CHAT_NODE.into(),
12270        };
12271        let a = dir.path().join("a.png");
12272        let b = dir.path().join("b.png");
12273        std::fs::write(&a, "a").unwrap();
12274        std::fs::write(&b, "b").unwrap();
12275        queue.attach(&mut t, &[a, b]).unwrap();
12276        let paths = task_attachments(&queue, &t).unwrap();
12277        for path in &paths {
12278            std::fs::remove_file(path).unwrap();
12279        }
12280        let missing = task_attachments(&queue, &t).unwrap_err();
12281        t.attempts += 1;
12282        let reason = missing.to_string();
12283        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12284        let first = t.chat_notice_due().expect("first attachment notice");
12285        t.chat_notices.push(first.clone());
12286        queue.put(&mut t).unwrap();
12287
12288        let queue = Queue::at(queue_path.clone());
12289        let mut t = queue.get(&t.id).unwrap();
12290        assert!(t.chat_notice_due().is_none(), "restart does not replay");
12291        t.release_operator("test", None);
12292        t.attempts += 1;
12293        let missing = task_attachments(&queue, &t).unwrap_err();
12294        t.fail_startup_target(
12295            "startup-attachments",
12296            missing.name,
12297            "same missing attachment with regenerated wording",
12298            1,
12299        );
12300        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
12301
12302        std::fs::write(&paths[0], "restored").unwrap();
12303        t.release_operator("test", None);
12304        t.attempts += 1;
12305        let missing = task_attachments(&queue, &t).unwrap_err();
12306        let reason = missing.to_string();
12307        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12308        let second = t
12309            .chat_notice_due()
12310            .expect("different attachment must notify");
12311        assert_ne!(first, second);
12312        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
12313    }
12314
12315    #[test]
12316    fn resumed_instruction_is_unchanged_without_any_answers() {
12317        let t = task();
12318        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
12319    }
12320
12321    #[test]
12322    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
12323        let mut t = task();
12324        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12325        // The run's own instruction on disk predates the answer: it is the
12326        // plain original text `Runner::start` saved before the operator was
12327        // ever asked anything.
12328        let old = t.instruction.clone();
12329
12330        let refreshed = resumed_instruction(&old, &t);
12331        assert!(refreshed.starts_with(&old), "the original text is kept");
12332        assert!(refreshed.contains("Which backend?"));
12333        assert!(refreshed.contains("SQLite"));
12334    }
12335
12336    #[test]
12337    fn resumed_instruction_keeps_an_original_answers_heading() {
12338        let mut t = task();
12339        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
12340        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12341
12342        let refreshed = resumed_instruction(&t.instruction, &t);
12343
12344        assert!(
12345            refreshed.starts_with(&t.instruction),
12346            "an answers heading in the original instruction is not the appended block"
12347        );
12348        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
12349        assert!(refreshed.contains("Which backend?"));
12350        assert!(refreshed.contains("SQLite"));
12351
12352        let repeated = resumed_instruction(&refreshed, &t);
12353        assert_eq!(
12354            repeated, refreshed,
12355            "only the final appended block is refreshed"
12356        );
12357    }
12358
12359    #[test]
12360    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
12361        let mut t = task();
12362        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12363
12364        // A first resume appends the block; a second resume of the same run,
12365        // with no new answer in between, must reproduce exactly the same
12366        // text rather than appending the block a second time.
12367        let once = resumed_instruction(&t.instruction, &t);
12368        let twice = resumed_instruction(&once, &t);
12369        assert_eq!(once, twice);
12370        assert_eq!(once.matches("Which backend?").count(), 1);
12371
12372        // A later answer replaces the block wholesale rather than growing it.
12373        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
12374        let refreshed = resumed_instruction(&once, &t);
12375        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
12376        assert!(refreshed.contains("Which backend?"));
12377        assert!(refreshed.contains("Which cache?"));
12378    }
12379
12380    #[test]
12381    fn prepare_instruction_covers_all_three_starters() {
12382        let mut t = task();
12383        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12384
12385        // Start: a fresh run gets the task text plus every answer so far —
12386        // exactly `instruction_for`.
12387        assert_eq!(
12388            prepare_instruction(&Starter::Start, None, &t),
12389            Some(instruction_for(&t))
12390        );
12391
12392        // Resume: the run's prior instruction is refreshed with the answer,
12393        // not discarded and not left stale.
12394        let old = t.instruction.clone();
12395        assert_eq!(
12396            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
12397            Some(resumed_instruction(&old, &t))
12398        );
12399
12400        // Review: a review-only pass builds its own instruction from the
12401        // branch's history in `crate::graph`, with no task statement at all -
12402        // this boundary must leave it alone.
12403        assert_eq!(
12404            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
12405            None
12406        );
12407    }
12408
12409    #[test]
12410    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
12411        assert_eq!(
12412            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
12413            Starter::Review("magi/eba2/A".to_owned())
12414        );
12415    }
12416
12417    #[test]
12418    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
12419        assert_eq!(
12420            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
12421            Starter::Start,
12422            "a vanished review branch must not fall back to resuming the old run either"
12423        );
12424    }
12425
12426    #[test]
12427    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
12428        let mut t = task();
12429        t.start("old-run".to_owned());
12430        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
12431        t.release();
12432        let branch = t.review_branch.take();
12433        assert_eq!(
12434            choose_starter(branch.as_deref(), true, Some("old-run")),
12435            Starter::Review("magi/eba2/A".to_owned()),
12436            "a review wins over resuming the old run"
12437        );
12438    }
12439
12440    #[test]
12441    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
12442        assert_eq!(
12443            choose_starter(None, false, Some("some-run")),
12444            Starter::Resume("some-run".to_owned())
12445        );
12446        assert_eq!(choose_starter(None, false, None), Starter::Start);
12447    }
12448
12449    #[test]
12450    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
12451        let mut released = task();
12452        released.start("stalled-run".to_owned());
12453        released.requeue();
12454        let unfinished = (!released.fresh_start)
12455            .then(|| Some("stalled-run".to_owned()))
12456            .flatten();
12457        assert_eq!(
12458            choose_starter(None, false, unfinished.as_deref()),
12459            Starter::Start,
12460            "release keeps run history but must not resume it"
12461        );
12462        assert_eq!(released.runs, ["stalled-run"]);
12463    }
12464
12465    #[test]
12466    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
12467        let dir = tempfile::tempdir().unwrap();
12468        let queue = Queue::at(dir.path().join("queue"));
12469        let mut state = run_state(RunStatus::Blocked);
12470        state.merge_decision = Some(crate::merge_decision::Decision {
12471            question: "hold-inquiry".into(),
12472            target: crate::merge_decision::Target {
12473                pr: "https://example.test/pull/1".into(),
12474                head: "reviewed-head".into(),
12475                language: "en".into(),
12476            },
12477            choice: land::HOLD.into(),
12478            closed: false,
12479            replacement_run: None,
12480            replacement_pr: None,
12481        });
12482        let mut t = task();
12483        t.start(state.id.clone());
12484        settle_and_diagnose(
12485            &mut t,
12486            Verdict {
12487                status: RunStatus::Blocked,
12488                left_pr: true,
12489                quota_hit: false,
12490                parked: false,
12491                no_viable_candidates: false,
12492            },
12493            "held",
12494            2,
12495            &state,
12496        );
12497        queue.put(&mut t).unwrap();
12498        t.release_operator("chat", None);
12499        t.edit("revised".into(), "revised instruction".into())
12500            .unwrap();
12501        queue.put(&mut t).unwrap();
12502        drop(state);
12503        assert_eq!(
12504            queue
12505                .get(&t.id)
12506                .unwrap()
12507                .decision_effects
12508                .get("hold-inquiry"),
12509            Some(&format!("decision: {}", land::HOLD))
12510        );
12511    }
12512
12513    fn stopped_public_run(status: RunStatus) -> RunState {
12514        let mut state = run_state(status);
12515        state.driver_exited = true;
12516        state.config.graph.land = true;
12517        state.config.graph.review_rounds = 1;
12518        state.reviews = vec![review_round(1)];
12519        state.merge = Some(crate::run::MergeOutcome {
12520            mode: MergeMode::Pr,
12521            ok: false,
12522            detail: "landing stopped".into(),
12523            empty: false,
12524        });
12525        state.pr = Some(crate::run::PrRecord {
12526            url: "https://example.test/pull/1".into(),
12527            number: 1,
12528            state: "open".into(),
12529            checks: "red".into(),
12530            round: 1,
12531            rounds: 1,
12532            red_at_merge: Vec::new(),
12533        });
12534        state
12535    }
12536
12537    #[test]
12538    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
12539        for status in [RunStatus::Blocked, RunStatus::Gating] {
12540            let home = tempfile::tempdir().unwrap();
12541            let mut state = stopped_public_run(status);
12542            state.save_under(home.path()).unwrap();
12543            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
12544            assert!(!exhausted_review_budget(&state));
12545            let mut task = held_task_with(&state.id);
12546            task.release();
12547            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12548            assert_eq!(
12549                choose_starter(None, false, unfinished.as_deref()),
12550                Starter::Resume(state.id.clone())
12551            );
12552            let question = action_question(&state.id, resume_action(&state.id));
12553            assert_eq!(
12554                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12555                    state.clone()
12556                )),
12557                ActionDecision::Resume(state.id.clone())
12558            );
12559            // The control-plane command uses this same preflight before pinning.
12560            assert_eq!(
12561                crate::resume::validate(home.path(), &state.id).unwrap().id,
12562                state.id
12563            );
12564            let queue = Queue::at(home.path().join("queue"));
12565            let mut controlled = Task::new(
12566                "resume land".into(),
12567                state.instruction.clone(),
12568                state.repo.clone(),
12569                Source::Agent {
12570                    run: "talk".into(),
12571                    node: crate::queue::CHAT_NODE.into(),
12572                },
12573            );
12574            controlled.runs.push(state.id.clone());
12575            controlled.hold_machine(Some("land stopped".into()));
12576            queue.put(&mut controlled).unwrap();
12577            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12578            assert_eq!(resumed.status, TaskStatus::Queued);
12579            assert_eq!(
12580                resumed.resume_override.unwrap().pinned_run,
12581                Some(state.id.clone())
12582            );
12583            assert_eq!(resumed.attempts, 0);
12584        }
12585    }
12586
12587    #[test]
12588    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
12589        for review_rounds in [0, 1] {
12590            let home = tempfile::tempdir().unwrap();
12591            let mut state = run_state(RunStatus::Blocked);
12592            state.config.graph.review_rounds = review_rounds;
12593            if review_rounds > 0 {
12594                let mut review = review_round(1);
12595                review.clean = true;
12596                state.reviews = vec![review];
12597            }
12598            state.gate_ran = true;
12599            state.gate = vec![crate::run::CommandOutcome {
12600                command: "verify".into(),
12601                code: Some(1),
12602                output_tail: "gate failed after repair budget exhausted".into(),
12603                duration_ms: 0,
12604                resource_blocked: false,
12605            }];
12606            state.save_under(home.path()).unwrap();
12607            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12608            assert!(exhausted_review_budget(&state));
12609            let mut task = held_task_with(&state.id);
12610            task.release();
12611            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
12612            let question = action_question(&state.id, resume_action(&state.id));
12613            assert_ne!(
12614                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12615                    state.clone()
12616                )),
12617                ActionDecision::Resume(state.id.clone())
12618            );
12619            let error = crate::resume::validate(home.path(), &state.id)
12620                .unwrap_err()
12621                .to_string();
12622            assert!(!error.contains("review budget exhausted"), "{error}");
12623            assert!(
12624                error.contains(if review_rounds == 0 {
12625                    "review is disabled"
12626                } else {
12627                    "gate already ran"
12628                }),
12629                "{error}"
12630            );
12631
12632            // An unexecuted gate still has work to do with or without reviews.
12633            state.gate_ran = false;
12634            state.gate.clear();
12635            assert!(!exhausted_review_budget(&state));
12636            assert_eq!(
12637                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
12638                Some(state.id)
12639            );
12640        }
12641    }
12642
12643    #[test]
12644    fn resource_blocked_verification_resumes_the_same_run() {
12645        for (kind, stage) in [
12646            ("cache", "clean"),
12647            ("coordination", "clean"),
12648            ("cache", "review-e2e"),
12649            ("coordination", "no-reviews"),
12650            ("coordination", "handoff"),
12651        ] {
12652            let home = tempfile::tempdir().unwrap();
12653            let mut state = run_state(RunStatus::Blocked);
12654            state.config.graph.review_rounds = 1;
12655            let mut review = review_round(1);
12656            review.clean = true;
12657            state.reviews = vec![review];
12658            if stage == "review-e2e" {
12659                let review = &mut state.reviews[0];
12660                review.clean = false;
12661                review.blocking = 1;
12662                review.e2e = vec![crate::run::CommandOutcome {
12663                    command: "verify".into(),
12664                    code: None,
12665                    output_tail: "resource wait expired".into(),
12666                    duration_ms: 0,
12667                    resource_blocked: true,
12668                }];
12669            } else if stage == "no-reviews" {
12670                state.config.graph.review_rounds = 0;
12671                state.reviews.clear();
12672            } else if stage == "handoff" {
12673                // A completed final verification can hand off to the gate
12674                // even when the review still carries contested findings.
12675                let review = &mut state.reviews[0];
12676                review.clean = false;
12677                review.blocking = 1;
12678                review.e2e = vec![crate::run::CommandOutcome {
12679                    command: "verify".into(),
12680                    code: Some(0),
12681                    output_tail: String::new(),
12682                    duration_ms: 0,
12683                    resource_blocked: false,
12684                }];
12685            }
12686            state.gate_ran = false;
12687            state.resource_block = Some(crate::run::ResourceBlock {
12688                cause: crate::run::ResourceBlockCause::Other,
12689                node: if stage == "review-e2e" {
12690                    "review"
12691                } else {
12692                    "gate"
12693                }
12694                .into(),
12695                kind: kind.into(),
12696                detail: "resource wait expired".into(),
12697                at: jiff::Timestamp::now(),
12698            });
12699            state.save_under(home.path()).unwrap();
12700            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12701            assert!(!exhausted_review_budget(&state));
12702            let mut task = held_task_with(&state.id);
12703            task.release();
12704            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12705            assert_eq!(
12706                choose_starter(None, false, unfinished.as_deref()),
12707                Starter::Resume(state.id.clone())
12708            );
12709            let question = action_question(&state.id, resume_action(&state.id));
12710            assert_eq!(
12711                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12712                    state.clone()
12713                )),
12714                ActionDecision::Resume(state.id.clone())
12715            );
12716            assert_eq!(
12717                crate::resume::validate(home.path(), &state.id).unwrap().id,
12718                state.id
12719            );
12720            let queue = Queue::at(home.path().join("queue"));
12721            let mut controlled = Task::new(
12722                "resume verification".into(),
12723                state.instruction.clone(),
12724                state.repo.clone(),
12725                Source::Agent {
12726                    run: "talk".into(),
12727                    node: crate::queue::CHAT_NODE.into(),
12728                },
12729            );
12730            controlled.runs.push(state.id.clone());
12731            controlled.hold_machine(Some("verification resource unavailable".into()));
12732            queue.put(&mut controlled).unwrap();
12733            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12734            assert_eq!(resumed.status, TaskStatus::Queued);
12735            assert_eq!(
12736                resumed.resume_override.unwrap().pinned_run,
12737                Some(state.id.clone())
12738            );
12739            assert_eq!(resumed.attempts, 0);
12740
12741            // A genuinely unresolved final review still exhausts the budget.
12742            state.config.graph.review_rounds = 1;
12743            let mut unresolved = review_round(1);
12744            unresolved.blocking = 1;
12745            state.reviews = vec![unresolved];
12746            state.resource_block = None;
12747            state.save_under(home.path()).unwrap();
12748            assert!(exhausted_review_budget(&state));
12749            assert!(crate::resume::validate(home.path(), &state.id).is_err());
12750        }
12751    }
12752
12753    #[tokio::test]
12754    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
12755        if !crate::standalone_test(
12756            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
12757        ) {
12758            return;
12759        }
12760        let home = tempfile::tempdir().unwrap();
12761        let mut owner = stopped_public_run(RunStatus::Blocked);
12762        owner.save_under(home.path()).unwrap();
12763        let history = vec![owner.id.clone()];
12764        let repo = owner.repo.clone();
12765        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
12766        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
12767        let initial =
12768            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
12769        assert!(
12770            initial.is_pending(),
12771            "a busy record must not hold or resume the task"
12772        );
12773        owner.retired_to = Some("20260101-000001-bbbb".into());
12774        owner.save_under(home.path()).unwrap();
12775        drop(lock);
12776        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
12777            .await
12778            .expect("ownership lock released")
12779            .expect("read settled owner");
12780        assert!(
12781            result.is_none(),
12782            "the retired owner must not be resumed from a stale read"
12783        );
12784    }
12785
12786    #[tokio::test]
12787    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
12788        if !crate::standalone_test(
12789            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
12790        ) {
12791            return;
12792        }
12793        let home = tempfile::tempdir().unwrap();
12794        let mut owner = stopped_public_run(RunStatus::Blocked);
12795        let repo = tempfile::tempdir().unwrap();
12796        crate::git::git(repo.path(), &["init"]).await.unwrap();
12797        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12798        owner.id = "20260101-000000-aaaa".into();
12799        owner.save_under(home.path()).unwrap();
12800        let mut successor = run_state(RunStatus::Blocked);
12801        successor.id = "20260101-000001-bbbb".into();
12802        successor.save_under(home.path()).unwrap();
12803        let runs = vec![owner.id.clone(), successor.id.clone()];
12804        assert_eq!(
12805            public_resume_owner(home.path(), &runs, &owner.repo)
12806                .await
12807                .unwrap()
12808                .unwrap()
12809                .id,
12810            owner.id
12811        );
12812        let subdir = owner.repo.join("nested");
12813        std::fs::create_dir(&subdir).unwrap();
12814        assert_eq!(
12815            public_resume_owner(home.path(), &runs, &subdir)
12816                .await
12817                .unwrap()
12818                .unwrap()
12819                .id,
12820            owner.id
12821        );
12822        #[cfg(unix)]
12823        {
12824            let alias = home.path().join("repo-alias");
12825            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12826            assert_eq!(
12827                public_resume_owner(home.path(), &runs, &alias.join("nested"))
12828                    .await
12829                    .unwrap()
12830                    .unwrap()
12831                    .id,
12832                owner.id
12833            );
12834        }
12835        let different = tempfile::tempdir().unwrap();
12836        crate::git::git(different.path(), &["init"]).await.unwrap();
12837        assert!(
12838            public_resume_owner(home.path(), &runs, different.path())
12839                .await
12840                .is_err()
12841        );
12842        std::fs::remove_file(
12843            home.path()
12844                .join("runs")
12845                .join(&successor.id)
12846                .join("run.json"),
12847        )
12848        .unwrap();
12849        assert!(
12850            public_resume_owner(home.path(), &runs, &owner.repo)
12851                .await
12852                .is_err()
12853        );
12854    }
12855
12856    #[test]
12857    fn an_ordinary_release_keeps_a_resumable_run_available() {
12858        let mut released = task();
12859        released.start("stalled-run".to_owned());
12860        released.release();
12861        let unfinished = (!released.fresh_start)
12862            .then(|| Some("stalled-run".to_owned()))
12863            .flatten();
12864        assert_eq!(
12865            choose_starter(None, false, unfinished.as_deref()),
12866            Starter::Resume("stalled-run".to_owned()),
12867            "manual release must preserve the normal resume path"
12868        );
12869    }
12870
12871    #[test]
12872    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12873        use crate::handover::{ResumeRefusal, resume_refusal_under};
12874        let home = tempfile::tempdir().unwrap();
12875        let mut exhausted = run_state(RunStatus::Blocked);
12876        exhausted.driver_exited = true;
12877        exhausted.config.graph.review_rounds = 3;
12878        exhausted.reviews = (1..=3).map(review_round).collect();
12879        for refusal in [
12880            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12881            ResumeRefusal::Status(RunStatus::Ready),
12882            ResumeRefusal::Released("20261022-000000-aaaa".into()),
12883            ResumeRefusal::Retired("retirement-successor".into()),
12884            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12885        ] {
12886            let mut state = exhausted.clone();
12887            let expected = match refusal {
12888                ResumeRefusal::Status(_) => {
12889                    state.status = RunStatus::Ready;
12890                    "status `ready`"
12891                }
12892                ResumeRefusal::Released(ref target) => {
12893                    state.released_to = Some(target.clone());
12894                    "execution was released"
12895                }
12896                ResumeRefusal::Retired(ref target) => {
12897                    state.retired_to = Some(target.clone());
12898                    "execution was retired"
12899                }
12900                ResumeRefusal::OwnershipTransferred(ref target) => {
12901                    state.pr_taken_over_by = Some(target.clone());
12902                    "PR ownership was transferred"
12903                }
12904                _ => "review budget exhausted (3/3 rounds used)",
12905            };
12906            assert_eq!(
12907                resume_refusal_under(&state, Some(home.path())),
12908                Some(refusal.clone())
12909            );
12910            assert_eq!(
12911                refusal.successor(),
12912                state
12913                    .released_to
12914                    .as_deref()
12915                    .or(state.retired_to.as_deref())
12916                    .or(state.pr_taken_over_by.as_deref())
12917            );
12918            state.save_under(home.path()).unwrap();
12919            let queue = Queue::at(home.path().join("queue"));
12920            let mut task = Task::new(
12921                "retained implementation".into(),
12922                state.instruction.clone(),
12923                state.repo.clone(),
12924                Source::Agent {
12925                    run: "talk".into(),
12926                    node: crate::queue::CHAT_NODE.into(),
12927                },
12928            );
12929            task.runs.push(state.id.clone());
12930            task.hold_machine(Some("stopped".into()));
12931            queue.put(&mut task).unwrap();
12932            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12933            let before_run = serde_json::to_value(&state).unwrap();
12934            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12935                .unwrap_err()
12936                .to_string();
12937            assert!(error.contains(expected), "{error}");
12938            assert!(!error.contains("only a stalled or blocked"), "{error}");
12939            if matches!(refusal, ResumeRefusal::Status(_)) {
12940                assert!(
12941                    error.contains("is final; there is nothing left to resume"),
12942                    "{error}"
12943                );
12944            }
12945            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12946                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12947                assert!(error.contains("review-only successor with a new review budget"));
12948                assert!(error.contains("does not resume this run"));
12949            }
12950            for target in [
12951                &state.released_to,
12952                &state.retired_to,
12953                &state.pr_taken_over_by,
12954            ]
12955            .into_iter()
12956            .flatten()
12957            {
12958                let short = if state.retired_to.as_ref() == Some(target) {
12959                    target.as_str()
12960                } else {
12961                    crate::run::short_of(target)
12962                };
12963                assert!(
12964                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12965                    "{error}"
12966                );
12967                if short != target {
12968                    assert!(!error.contains(target), "full successor id leaked: {error}");
12969                }
12970            }
12971            assert_eq!(
12972                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12973                before_task
12974            );
12975            assert_eq!(
12976                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12977                    .unwrap(),
12978                before_run
12979            );
12980            let question = action_question(&state.id, resume_action(&state.id));
12981            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12982                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12983                    RunState::load_under(id, home.path())
12984                });
12985                let ActionDecision::Refuse(detail) = decision else {
12986                    panic!(
12987                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12988                        state.id,
12989                        home.path().display()
12990                    );
12991                };
12992                assert!(detail.contains(expected), "{detail}");
12993            }
12994        }
12995        // Preserve predicate ordering, while keeping every recorded destination visible.
12996        exhausted.status = RunStatus::Ready;
12997        exhausted.released_to = Some("released".into());
12998        exhausted.retired_to = Some("retired".into());
12999        exhausted.pr_taken_over_by = Some("owner".into());
13000        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13001        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13002        let detail = reason.diagnostic(&exhausted);
13003        for target in ["released", "retired", "owner"] {
13004            assert!(detail.contains(&format!("magi show {target}")));
13005        }
13006    }
13007
13008    #[test]
13009    fn resume_action_ignores_question_checkpoints_in_another_home() {
13010        crate::run::pin_test_home();
13011        let home = tempfile::tempdir().unwrap();
13012        let mut state = run_state(RunStatus::Blocked);
13013        // The private directory reserves this fixture's identity even while
13014        // other tests write questions into the process-wide store.
13015        state.id = format!(
13016            "resume-context-{}",
13017            home.path().file_name().unwrap().to_str().unwrap()
13018        );
13019        state.driver_exited = true;
13020        state.config.graph.review_rounds = 1;
13021        state.reviews = vec![review_round(1)];
13022        state.save_under(home.path()).unwrap();
13023        let task = held_task_with(&state.id);
13024        let answer = action_question(&state.id, resume_action(&state.id));
13025        let mut checkpoint = approval_question(&state.id);
13026        let foreign = Questions::open();
13027        foreign.put(&mut checkpoint).unwrap();
13028        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13029        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13030            RunState::load_under(id, home.path())
13031        });
13032        let matching: Vec<_> = foreign
13033            .list()
13034            .into_iter()
13035            .filter(|q| q.run == state.id && q.status.open())
13036            .collect();
13037        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13038        assert!(
13039            matches!(decision, ActionDecision::Refuse(_)),
13040            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13041            state.id,
13042            home.path().display(),
13043            crate::run::test_home().display()
13044        );
13045        assert_eq!(
13046            refusal,
13047            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13048        );
13049        let local = Questions::at(home.path().join("questions"));
13050        for status in [
13051            ask::QuestionStatus::Open,
13052            ask::QuestionStatus::Answered,
13053            ask::QuestionStatus::Abandoned,
13054        ] {
13055            let mut question = checkpoint.clone();
13056            match status {
13057                ask::QuestionStatus::Open => {}
13058                ask::QuestionStatus::Answered => {
13059                    question
13060                        .answer(ask::Answer::Choice(question.choices[0].clone()))
13061                        .unwrap();
13062                }
13063                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13064            }
13065            local.put(&mut question).unwrap();
13066            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13067                RunState::load_under(id, home.path())
13068            });
13069            if status.open() {
13070                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13071            } else {
13072                assert!(
13073                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13074                    "status={status:?}, decision={decision:?}"
13075                );
13076            }
13077        }
13078    }
13079
13080    #[test]
13081    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13082        let home = tempfile::tempdir().unwrap();
13083        let mut state = run_state(RunStatus::Stalled);
13084        state.id = format!(
13085            "resume-driver-{}",
13086            home.path().file_name().unwrap().to_str().unwrap()
13087        );
13088        state.driver_claimed = Some(false);
13089        state.save_under(home.path()).unwrap();
13090        let task = held_task_with(&state.id);
13091        let question = action_question(&state.id, resume_action(&state.id));
13092        let decide = || {
13093            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13094                RunState::load_under(id, home.path())
13095            })
13096        };
13097        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13098        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13099        assert_eq!(
13100            decide(),
13101            ActionDecision::Refuse("run already has a live driver".into())
13102        );
13103        drop(lease);
13104        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13105    }
13106
13107    #[test]
13108    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13109        let home = tempfile::tempdir().unwrap();
13110        let mut state = run_state(RunStatus::Blocked);
13111        state.driver_exited = true;
13112        state.config.graph.review_rounds = 1;
13113        state.reviews = vec![review_round(1)];
13114        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13115        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13116            let mut saved = state.clone();
13117            match checkpoint {
13118                "publication" => saved.pr_publication_pending = true,
13119                "approval" => {
13120                    saved.land_approval = Some(crate::run::LandApproval {
13121                        question: "approval".into(),
13122                        head: "head".into(),
13123                    })
13124                }
13125                "armed" => saved.land_armed_head = Some("head".into()),
13126                "landing" => saved.status = RunStatus::Landing,
13127                _ => {
13128                    let mut question = ask::Question::new(
13129                        saved.id.clone(),
13130                        "review".into(),
13131                        "review-1".into(),
13132                        "continue?".into(),
13133                        String::new(),
13134                        vec!["continue".into()],
13135                    );
13136                    ask::Questions::at(home.path().join("questions"))
13137                        .put(&mut question)
13138                        .unwrap();
13139                }
13140            }
13141            saved.save_under(home.path()).unwrap();
13142            assert!(
13143                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13144                "{checkpoint}"
13145            );
13146            assert!(
13147                crate::resume::validate(home.path(), &saved.id).is_ok(),
13148                "{checkpoint}"
13149            );
13150        }
13151    }
13152
13153    #[test]
13154    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
13155        let mut state = run_state(RunStatus::Blocked);
13156        state.config.graph.review_rounds = 3;
13157        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
13158        assert!(exhausted_review_budget(&state));
13159
13160        // One round still unused: resuming can still ask a reviewer something.
13161        state.reviews.pop();
13162        assert!(!exhausted_review_budget(&state));
13163
13164        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
13165        // count: only a `Blocked` run re-enters the review loop on resume.
13166        let mut stalled = run_state(RunStatus::Stalled);
13167        stalled.config.graph.review_rounds = 1;
13168        stalled.reviews = vec![review_round(1)];
13169        assert!(!exhausted_review_budget(&stalled));
13170    }
13171
13172    fn review_round(round: usize) -> crate::run::ReviewRound {
13173        crate::run::ReviewRound {
13174            round,
13175            head: "deadbeef".to_owned(),
13176            verified_head: None,
13177            verified_at: None,
13178            reviews: Vec::new(),
13179            e2e: Vec::new(),
13180            verify_retried: false,
13181            e2e_deferred: false,
13182            e2e_defer_reason: None,
13183            fix: None,
13184            blocking: 0,
13185            answered: 1,
13186            expected: 1,
13187            clean: false,
13188            progressed: true,
13189            vote_split: false,
13190            reconsideration: Vec::new(),
13191            verdict: None,
13192        }
13193    }
13194
13195    #[test]
13196    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
13197        let mut run = RunState::new(
13198            PathBuf::from("/repo"),
13199            "main".to_owned(),
13200            "abc1234def".to_owned(),
13201            "add retries".to_owned(),
13202            Config::default(),
13203        );
13204        run.status = RunStatus::Judging;
13205        run.parked = true;
13206        let mut task = Task::new(
13207            "add retries".to_owned(),
13208            "add retries".to_owned(),
13209            PathBuf::from("/repo"),
13210            crate::queue::Source::Human,
13211        );
13212        task.status = TaskStatus::Failed;
13213        task.runs = vec![run.id.clone()];
13214        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
13215        assert!(with(&task, &run), "parked after judging is the case");
13216        let mut parked_task = task.clone();
13217        parked_task.status = TaskStatus::Parked;
13218        assert!(with(&parked_task, &run), "the Parked status is the case");
13219
13220        let mut not_parked = run.clone();
13221        not_parked.parked = false;
13222        not_parked.status = RunStatus::Stalled;
13223        assert!(!with(&task, &not_parked), "a stall is the conductor's");
13224
13225        let mut fresh = task.clone();
13226        fresh.fresh_start = true;
13227        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
13228
13229        let mut review = task.clone();
13230        review.review_branch = Some("magi/x/A".to_owned());
13231        assert!(!with(&review, &run), "review is ranked before resume");
13232
13233        let mut held = task.clone();
13234        held.status = TaskStatus::Held;
13235        assert!(!with(&held, &run), "a hold stays visible to the conductor");
13236
13237        let mut released = run.clone();
13238        released.released_to = Some("20260901-000000-new1".to_owned());
13239        assert!(!with(&task, &released), "nothing left to resume into");
13240
13241        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13242            "unreadable"
13243        )));
13244    }
13245
13246    #[test]
13247    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13248        let mut released = RunState::new(
13249            PathBuf::from("/repo"),
13250            "main".to_owned(),
13251            "abc1234def".to_owned(),
13252            "add retries".to_owned(),
13253            Config::default(),
13254        );
13255        released.status = RunStatus::Blocked;
13256        assert_eq!(
13257            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13258            Some(released.id.clone())
13259        );
13260        released.released_to = Some("20260901-000000-new1".to_owned());
13261        assert_eq!(
13262            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13263            None,
13264            "there is nothing left to resume it into"
13265        );
13266    }
13267
13268    #[test]
13269    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13270        // Mirrors the failure this exists to close: a task's last run ended
13271        // `Blocked` with the review budget spent, `crate::conduct` chose
13272        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
13273        // evidence), and without this check `attempt` would go on treating
13274        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
13275        // review loop iterates zero times over an already-spent budget, so
13276        // the resumed run settles right back to `Blocked` having asked nobody
13277        // anything, and `Requeue`'s promised fresh competition never happens.
13278        let mut exhausted = RunState::new(
13279            PathBuf::from("/repo"),
13280            "main".to_owned(),
13281            "abc1234def".to_owned(),
13282            "add retries".to_owned(),
13283            Config::default(),
13284        );
13285        exhausted.status = RunStatus::Blocked;
13286        exhausted.config.graph.review_rounds = 1;
13287        exhausted.reviews = vec![review_round(1)];
13288
13289        assert_eq!(
13290            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
13291            None,
13292            "an exhausted `Blocked` run must not be offered as resumable"
13293        );
13294
13295        // A `Blocked` run with rounds still unused is genuinely worth
13296        // resuming, and must still be found.
13297        let mut has_budget_left = RunState::new(
13298            PathBuf::from("/repo"),
13299            "main".to_owned(),
13300            "abc1234def".to_owned(),
13301            "add retries".to_owned(),
13302            Config::default(),
13303        );
13304        has_budget_left.status = RunStatus::Blocked;
13305        has_budget_left.config.graph.review_rounds = 3;
13306        has_budget_left.reviews = vec![review_round(1)];
13307
13308        assert_eq!(
13309            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
13310                Ok(has_budget_left.clone())
13311            }),
13312            Some(has_budget_left.id.clone())
13313        );
13314    }
13315
13316    #[test]
13317    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
13318        let mut run = RunState::new(
13319            PathBuf::from("/repo"),
13320            "main".to_owned(),
13321            "abc1234def".to_owned(),
13322            "add retries".to_owned(),
13323            Config::default(),
13324        );
13325        run.status = RunStatus::Blocked;
13326        run.config.graph.review_rounds = 1;
13327        run.reviews = vec![review_round(1)];
13328        run.pr_publication_pending = true;
13329        assert_eq!(
13330            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
13331            Some(run.id.clone()),
13332            "a spent review budget must not turn a failed publication into a re-competition"
13333        );
13334    }
13335
13336    #[test]
13337    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
13338        let mut task = Task::new(
13339            "recover work".into(),
13340            "recover work".into(),
13341            PathBuf::from("/repo"),
13342            crate::queue::Source::Human,
13343        );
13344        let mut history = std::collections::BTreeMap::new();
13345        for index in 0..8 {
13346            let mut run = run_state(RunStatus::Blocked);
13347            run.id = format!("20260101-000000-{index:04}");
13348            run.base_commit = format!("upstream-{index}");
13349            // Seven empty newer attempts must not erase the old recovery owner.
13350            if index > 0 {
13351                run.candidates.clear();
13352            }
13353            task.runs.extend([run.id.clone(), run.id.clone()]);
13354            history.insert(run.id.clone(), run);
13355            task.requeue();
13356        }
13357        let check = |task: &Task, starter: &Starter, limit| {
13358            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
13359        };
13360        assert!(
13361            check(&task, &Starter::Start, 8)
13362                .unwrap()
13363                .contains("8 unretired")
13364        );
13365        assert!(check(&task, &Starter::Start, 9).is_none());
13366        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13367        task.release_operator("owner", None);
13368        assert_eq!(task.attempts, 0);
13369        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13370        assert!(check(&restored, &Starter::Start, 8).is_some());
13371        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
13372        assert!(check(&restored, &Starter::Start, 0).is_none());
13373    }
13374
13375    #[test]
13376    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
13377        let tmp = tempfile::tempdir().unwrap();
13378        let mut task = Task::new(
13379            "recover selected PR".into(),
13380            "preserve implementation".into(),
13381            tmp.path().join("repo"),
13382            crate::queue::Source::Human,
13383        );
13384        let mut failed = run_state(RunStatus::Failed);
13385        failed.id = "20260101-000000-fail".into();
13386        failed.candidates.clear();
13387        failed.prep_complete = Some(false);
13388        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
13389        failed.startup = Some(crate::run::Startup {
13390            kind: "pr-recovery".into(),
13391            branch: Some("selected-public-head".into()),
13392            stage: "worktree-setup".into(),
13393            complete: false,
13394            failure: Some("setup modified a tracked file and failed".into()),
13395        });
13396        // Setup may fail before a candidate is recorded; its dirty worktree
13397        // still needs protection and consumes the independent retained bound.
13398        let worktree = failed.worktree_root().join("under-review");
13399        std::fs::create_dir_all(&worktree).unwrap();
13400        let retained_edit = worktree.join("implementation");
13401        std::fs::write(&retained_edit, "retained setup edit").unwrap();
13402        task.record_startup_failure(crate::run::StartupFailure {
13403            run: failed.id.clone(),
13404            stage: "worktree-setup".into(),
13405        });
13406        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13407        assert!(task.runs.is_empty() && task.passes.is_empty());
13408        assert_eq!(task.attempts, 0);
13409        let starter = Starter::Review("selected-public-head".into());
13410        assert!(
13411            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
13412                .unwrap()
13413                .contains("1 unretired")
13414        );
13415        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
13416        assert!(
13417            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
13418                .unwrap()
13419                .contains("Cannot verify")
13420        );
13421        // Older or mixed writers can link the same reservation in both lists.
13422        let mut mixed = task.clone();
13423        mixed.runs.push(failed.id.clone());
13424        mixed
13425            .startup_failures
13426            .push(task.startup_failures[0].clone());
13427        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
13428        failed.retired_to = Some("verified-recovery-owner".into());
13429        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
13430        assert!(
13431            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
13432                panic!("resuming the existing owner must not allocate a new attempt")
13433            })
13434            .is_none()
13435        );
13436        assert_eq!(
13437            std::fs::read_to_string(retained_edit).unwrap(),
13438            "retained setup edit"
13439        );
13440        assert!(task.runs.is_empty() && task.passes.is_empty());
13441        assert_eq!(task.attempts, 0);
13442    }
13443
13444    #[test]
13445    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
13446        let mut task = Task::new(
13447            "recover work".into(),
13448            "recover work".into(),
13449            PathBuf::from("/repo"),
13450            crate::queue::Source::Human,
13451        );
13452        let mut run = run_state(RunStatus::Superseded);
13453        run.candidates.clear();
13454        task.runs.push(run.id.clone());
13455        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
13456        run.retired_to = Some("authority".into());
13457        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13458        run.retired_to = None;
13459        run.released_to = Some("authority".into());
13460        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13461        assert!(
13462            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
13463                .unwrap()
13464                .contains("Cannot verify")
13465        );
13466        // Resuming an existing owner needs no new inventory or worktree budget.
13467        assert!(
13468            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
13469                panic!("resume must not load historical attempts")
13470            })
13471            .is_none()
13472        );
13473    }
13474
13475    #[test]
13476    fn retired_resume_requires_a_valid_same_repository_authority() {
13477        let mut source = run_state(RunStatus::Blocked);
13478        let mut empty = run_state(RunStatus::Blocked);
13479        empty.retired_to = Some(source.id.clone());
13480        let runs = vec![source.id.clone(), empty.id.clone()];
13481        let resolve = |source: &RunState, empty: &RunState| {
13482            unfinished_run_with(&runs, "fixture", |id| {
13483                if id == source.id {
13484                    Ok(source.clone())
13485                } else if id == empty.id {
13486                    Ok(empty.clone())
13487                } else {
13488                    bail!("unreadable authority")
13489                }
13490            })
13491        };
13492        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
13493        assert_eq!(
13494            choose_starter(None, false, resolve(&source, &empty).as_deref()),
13495            Starter::Resume(source.id.clone())
13496        );
13497        source.retired_to = Some(empty.id.clone());
13498        assert!(
13499            resolve(&source, &empty).is_none(),
13500            "cycles do not revive obsolete runs"
13501        );
13502        source.retired_to = None;
13503        source.repo = PathBuf::from("/another-repository");
13504        assert!(resolve(&source, &empty).is_none());
13505        source.repo = empty.repo.clone();
13506        source.released_to = Some("later".into());
13507        assert!(resolve(&source, &empty).is_none());
13508        empty.retired_to = Some("unlisted-run".into());
13509        assert!(resolve(&source, &empty).is_none());
13510    }
13511
13512    #[test]
13513    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
13514        // A task whose history holds an *older* run that still looks
13515        // resumable (say, a competition `Runner::review` was started
13516        // alongside after that older run went `Stalled`) and a *newest* run
13517        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
13518        // on this task must mean a fresh competition — falling back to the
13519        // stale, superseded `Stalled` run instead would resurrect history
13520        // nothing asked to revisit and silently defeat the requeue.
13521        let mut older_stalled = RunState::new(
13522            PathBuf::from("/repo"),
13523            "main".to_owned(),
13524            "abc1234def".to_owned(),
13525            "add retries".to_owned(),
13526            Config::default(),
13527        );
13528        older_stalled.status = RunStatus::Stalled;
13529
13530        let mut newest_exhausted = RunState::new(
13531            PathBuf::from("/repo"),
13532            "main".to_owned(),
13533            "abc1234def".to_owned(),
13534            "add retries".to_owned(),
13535            Config::default(),
13536        );
13537        newest_exhausted.status = RunStatus::Blocked;
13538        newest_exhausted.config.graph.review_rounds = 1;
13539        newest_exhausted.reviews = vec![review_round(1)];
13540
13541        assert_eq!(
13542            unfinished_run_with(
13543                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
13544                "t",
13545                |_| Ok(newest_exhausted.clone())
13546            ),
13547            None,
13548            "the newest run is exhausted, so nothing here is worth resuming - \
13549             least of all the older, already-superseded run"
13550        );
13551    }
13552
13553    #[test]
13554    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
13555        assert_eq!(
13556            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
13557                Err(anyhow::anyhow!("fixture is absent"))
13558            }),
13559            None
13560        );
13561    }
13562
13563    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
13564        let mut q = ask::Question::new(
13565            run.to_owned(),
13566            "implement".to_owned(),
13567            "impl-A".to_owned(),
13568            "continue?".to_owned(),
13569            String::new(),
13570            vec!["resume で続行する".to_owned(), "other".to_owned()],
13571        );
13572        q.actions.insert("resume で続行する".to_owned(), action);
13573        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
13574            .unwrap();
13575        q
13576    }
13577
13578    fn held_task_with(run: &str) -> Task {
13579        let mut t = task();
13580        t.runs = vec![run.to_owned()];
13581        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
13582        t
13583    }
13584
13585    fn resume_action(run: &str) -> ask::ChoiceAction {
13586        ask::ChoiceAction::Resume { run: run.into() }
13587    }
13588
13589    #[test]
13590    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
13591        let home = crate::run::test_home();
13592        for parked in [false, true] {
13593            let mut t = task();
13594            t.start("A".into());
13595            t.start("B".into());
13596            assert_eq!(t.runs, vec!["A", "B"]);
13597            t.start("A".into());
13598            let mut resumed = run_state(RunStatus::Blocked);
13599            resumed.id = "A".into();
13600            resumed.parked = parked;
13601            resumed.driver_exited = true;
13602            t.hold_machine(Some("resumed run stopped".into()));
13603            let q = action_question("A", resume_action("A"));
13604            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13605            assert_eq!(
13606                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
13607                    assert_eq!(id, "A");
13608                    Ok(resumed.clone())
13609                }),
13610                ActionDecision::Resume("A".into())
13611            );
13612            assert_eq!(
13613                action_standing(&t, &action_question("B", resume_action("B"))),
13614                ActionStanding::Stale
13615            );
13616            t.release_operator("cli", None);
13617            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
13618                assert_eq!(id, "A");
13619                Ok(resumed.clone())
13620            });
13621            assert_eq!(
13622                choose_starter(None, false, unfinished.as_deref()),
13623                Starter::Resume("A".into())
13624            );
13625            assert_eq!(t.runs, vec!["B", "A"]);
13626        }
13627    }
13628
13629    #[test]
13630    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
13631        let home = crate::run::test_home();
13632        let mut state = crate::land::tests::repair_state(true, true);
13633        state.status = RunStatus::Landing;
13634        state.parked = true;
13635        state.driver_exited = true;
13636        let mut q = ask::Question::new(
13637            state.id.clone(),
13638            land::APPROVAL_NODE.into(),
13639            "land".into(),
13640            "Merge?".into(),
13641            String::new(),
13642            vec![land::APPROVE.into(), land::HOLD.into()],
13643        );
13644        q.id = state.id.clone();
13645        state.land_approval = Some(crate::run::LandApproval {
13646            question: q.id.clone(),
13647            head: "current-head".into(),
13648        });
13649        assert!(land::upgrade_repair_choice(&mut q, &state));
13650        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13651        let mut task = held_task_with(&state.id);
13652        task.status = TaskStatus::Parked;
13653        assert_eq!(
13654            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13655            ActionDecision::Resume(state.id.clone())
13656        );
13657        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13658        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
13659        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
13660        assert_eq!(
13661            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13662            ActionDecision::Resume(state.id.clone()),
13663            "a repair answer newer than the manual hold resumes the existing owner"
13664        );
13665        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13666        for answered_at in [q.answered_at, None] {
13667            let mut older = q.clone();
13668            older.answered_at = answered_at;
13669            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
13670                panic!("a later manual hold must prevent dispatch")
13671            });
13672            let ActionDecision::Refuse(reason) = refused else {
13673                panic!("expected an actionable refusal, got {refused:?}");
13674            };
13675            assert!(reason.contains("later operator decision"));
13676            assert!(reason.contains(&format!("magi task release {}", task.id)));
13677        }
13678        task.operator_decided_at = None;
13679        let mut superseded = state.clone();
13680        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
13681        assert_eq!(
13682            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
13683            ActionDecision::Stale
13684        );
13685        for case in 1..4 {
13686            let mut changed = state.clone();
13687            match case {
13688                1 => changed.status = RunStatus::Blocked,
13689                2 => changed.released_to = Some("new-owner".into()),
13690                _ => changed.land_approval.as_mut().unwrap().head.clear(),
13691            }
13692            assert!(matches!(
13693                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
13694                ActionDecision::Refuse(_)
13695            ));
13696        }
13697        assert!(matches!(
13698            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
13699                "missing owner"
13700            )),
13701            ActionDecision::Refuse(_)
13702        ));
13703        task.runs.push("replacement".into());
13704        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13705        assert_eq!(
13706            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
13707                "old owner must not load"
13708            )),
13709            ActionDecision::Stale
13710        );
13711    }
13712
13713    #[test]
13714    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
13715        let mut state = crate::land::tests::repair_state(true, true);
13716        state.status = RunStatus::Landing;
13717        state.parked = true;
13718        state.driver_exited = true;
13719        let mut q = ask::Question::new(
13720            state.id.clone(),
13721            land::APPROVAL_NODE.into(),
13722            "land".into(),
13723            "Merge?".into(),
13724            String::new(),
13725            vec![land::APPROVE.into(), land::HOLD.into()],
13726        );
13727        q.id = state.id.clone();
13728        state.land_approval = Some(crate::run::LandApproval {
13729            question: q.id.clone(),
13730            head: "current-head".into(),
13731        });
13732        state.save().unwrap();
13733        land::upgrade_repair_choice(&mut q, &state);
13734        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13735        Questions::open().put(&mut q).unwrap();
13736        let tmp = tempfile::tempdir().unwrap();
13737        let queue = Queue::at(tmp.path().join("queue"));
13738        let mut task = held_task_with(&state.id);
13739        task.status = TaskStatus::Parked;
13740        queue.put(&mut task).unwrap();
13741        let empty = Arc::new(tokio::sync::Semaphore::new(0));
13742        let free = Arc::new(tokio::sync::Semaphore::new(1));
13743        assert!(matches!(
13744            claim_dispatch(&queue, &task, false, &empty, &free),
13745            Err(SkipReason::OrdinaryCapacity)
13746        ));
13747        assert!(matches!(
13748            claim_dispatch(&queue, &task, true, &free, &free),
13749            Err(SkipReason::CoolingDown)
13750        ));
13751        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
13752        assert!(claim.permit.is_some());
13753        assert!(matches!(
13754            claim_dispatch(&queue, &task, false, &free, &free),
13755            Err(SkipReason::ClaimUnavailable)
13756        ));
13757        drop(claim);
13758        Questions::open()
13759            .update(&q.id, |q| {
13760                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
13761                Ok(())
13762            })
13763            .unwrap();
13764        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
13765        assert!(claim.permit.is_none());
13766        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
13767    }
13768
13769    #[test]
13770    fn decide_action_resumes_only_the_latest_resumable_run() {
13771        let home = crate::run::test_home();
13772        let t = held_task_with("r1");
13773        let q = action_question("r1", resume_action("r1"));
13774        let load = |s: RunState| move |_: &str| Ok(s);
13775        assert_eq!(
13776            decide_action(
13777                &home,
13778                &t,
13779                &q,
13780                &PHRASES_EN,
13781                load(run_state(RunStatus::Blocked))
13782            ),
13783            ActionDecision::Resume("r1".into())
13784        );
13785        // Not the latest run of the task.
13786        let q_other = action_question("r1", resume_action("r0"));
13787        assert!(matches!(
13788            decide_action(
13789                &home,
13790                &t,
13791                &q_other,
13792                &PHRASES_EN,
13793                load(run_state(RunStatus::Blocked))
13794            ),
13795            ActionDecision::Refuse(_)
13796        ));
13797        // A finished run cannot make progress.
13798        assert!(matches!(
13799            decide_action(
13800                &home,
13801                &t,
13802                &q,
13803                &PHRASES_EN,
13804                load(run_state(RunStatus::Ready))
13805            ),
13806            ActionDecision::Refuse(_)
13807        ));
13808        // A released one either.
13809        let mut released = run_state(RunStatus::Blocked);
13810        released.released_to = Some("elsewhere".into());
13811        assert!(matches!(
13812            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13813            ActionDecision::Refuse(_)
13814        ));
13815        // Unreadable state is a refusal, never a fresh competition.
13816        assert!(matches!(
13817            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13818            ActionDecision::Refuse(_)
13819        ));
13820    }
13821
13822    #[test]
13823    fn decide_action_ignores_a_question_about_an_earlier_run() {
13824        let home = crate::run::test_home();
13825        let mut t = held_task_with("r1");
13826        t.runs.push("r2".to_owned());
13827        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13828        assert_eq!(
13829            decide_action(
13830                &home,
13831                &t,
13832                &action_question("r1", ask::ChoiceAction::Done),
13833                &PHRASES_EN,
13834                never
13835            ),
13836            ActionDecision::Stale
13837        );
13838    }
13839
13840    #[test]
13841    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13842        let home = crate::run::test_home();
13843        let mut t = held_task_with("r1");
13844        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13845        assert_eq!(
13846            decide_action(
13847                &home,
13848                &t,
13849                &action_question("r1", ask::ChoiceAction::Requeue),
13850                &PHRASES_EN,
13851                never
13852            ),
13853            ActionDecision::Requeue
13854        );
13855        let done_q = action_question("r1", ask::ChoiceAction::Done);
13856        assert_eq!(
13857            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13858            ActionDecision::Done
13859        );
13860        t.mark_action_applied(&done_q.id);
13861        assert_eq!(
13862            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13863            ActionDecision::Skip
13864        );
13865
13866        // A plain answer (no action for that label) does nothing.
13867        let mut plain = action_question("r1", ask::ChoiceAction::Done);
13868        plain.actions.clear();
13869        assert_eq!(
13870            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13871            ActionDecision::Skip
13872        );
13873        // A running task is left alone.
13874        let mut running = held_task_with("r1");
13875        running.status = TaskStatus::Running;
13876        assert_eq!(
13877            decide_action(
13878                &home,
13879                &running,
13880                &action_question("r1", ask::ChoiceAction::Done),
13881                &PHRASES_EN,
13882                never
13883            ),
13884            ActionDecision::Skip
13885        );
13886    }
13887
13888    #[test]
13889    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13890        crate::run::pin_test_home();
13891        for legacy in [false, true] {
13892            let dir = tempfile::tempdir().unwrap();
13893            let queue = Queue::at(dir.path().join("queue"));
13894            let questions = Questions::at(dir.path().join("questions"));
13895            let run = "20260101-000000-hold";
13896            let mut task = held_task_with(run);
13897            task.status = TaskStatus::Parked;
13898            let mut q = ask::Question::new(
13899                run.into(),
13900                land::APPROVAL_NODE.into(),
13901                "land".into(),
13902                "Repair?".into(),
13903                String::new(),
13904                vec![land::REPAIR.into()],
13905            );
13906            q.actions.insert(land::REPAIR.into(), resume_action(run));
13907            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13908            // Deterministically order the answer before the actual manual hold.
13909            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13910            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13911            questions.put(&mut q).unwrap();
13912            task.hold_manual(Some("Keep this PR paused".into()));
13913            if legacy {
13914                task.hold_source = None;
13915            }
13916            queue.put(&mut task).unwrap();
13917
13918            apply_task_choice_actions(&queue, &questions, dir.path());
13919            let after = queue.get(&task.id).unwrap();
13920            assert!(after.operator_held());
13921            assert_eq!(after.hold_source, task.hold_source);
13922            assert_eq!(after.operator_decided_at, task.operator_decided_at);
13923            assert_eq!(after.runs, task.runs);
13924            assert_eq!(after.instruction, task.instruction);
13925            assert!(after.resume_override.is_none());
13926            assert!(after.action_applied(&q.id));
13927            let reason = after.hold_reason.as_deref().unwrap();
13928            assert!(reason.starts_with("Keep this PR paused"));
13929            assert!(reason.contains("later operator decision"));
13930            assert!(reason.contains(&format!("magi task release {}", task.id)));
13931
13932            for recovery in [
13933                crate::conduct::Recovery::Review,
13934                crate::conduct::Recovery::Requeue,
13935            ] {
13936                crate::conduct::apply(
13937                    &queue,
13938                    &questions,
13939                    &crate::conduct::Verdict {
13940                        decisions: vec![crate::conduct::Decision {
13941                            id: task.id.clone(),
13942                            recovery: Some(recovery),
13943                            ..Default::default()
13944                        }],
13945                    },
13946                )
13947                .unwrap();
13948            }
13949            // Reconciliation is idempotent, and automatic recovery cannot
13950            // reopen this owner after it observes the rejected repair answer.
13951            apply_task_choice_actions(&queue, &questions, dir.path());
13952            let still_held = queue.get(&task.id).unwrap();
13953            assert!(still_held.operator_held());
13954            assert_eq!(still_held.hold_reason, after.hold_reason);
13955            assert_eq!(still_held.runs, task.runs);
13956            assert!(still_held.review_branch.is_none());
13957            assert!(!still_held.fresh_start);
13958            assert!(queue.next_runnable().is_none());
13959        }
13960    }
13961
13962    #[test]
13963    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13964        for held in [false, true] {
13965            for retry in [false, true] {
13966                let dir = tempfile::tempdir().unwrap();
13967                let queue = Queue::at(dir.path().join("queue"));
13968                let questions = Questions::at(dir.path().join("questions"));
13969                let home = dir.path().join("home");
13970                let mut t = task();
13971                if held {
13972                    t.hold_machine(Some("driver state unknown".into()));
13973                }
13974                queue.put(&mut t).unwrap();
13975                let verdict = serde_json::from_value(serde_json::json!({
13976                    "decisions": [{
13977                        "id": t.id,
13978                        "question": "Driver state unknown; retry the checks or hold?",
13979                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13980                        "actions": {
13981                            "daemon: recheck and retry": {"do": "requeue"},
13982                            "daemon: hold the task": {"do": "hold"}
13983                        }
13984                    }]
13985                }))
13986                .unwrap();
13987                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13988                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13989                let mut q = questions.list().pop().unwrap();
13990                let choice = if retry {
13991                    "daemon: recheck and retry"
13992                } else {
13993                    "daemon: hold the task"
13994                };
13995                assert_eq!(q.actions.len(), 2);
13996                q.answer(ask::Answer::Choice(choice.into())).unwrap();
13997                questions.put(&mut q).unwrap();
13998
13999                // A Web answer does not remove the deputy's fresh lease.
14000                questions.beat(&q.id, ask::WaiterKind::Deputy);
14001                for _ in 0..2 {
14002                    resolve_blockers(&queue, &questions);
14003                    apply_task_choice_actions(&queue, &questions, &home);
14004                    let waiting = queue.get(&t.id).unwrap();
14005                    assert_eq!(waiting.status, TaskStatus::Blocked);
14006                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
14007                    assert!(waiting.answers.is_empty());
14008                    assert!(!waiting.action_applied(&q.id));
14009                    assert!(runnable(&queue).is_empty());
14010                    let free = Arc::new(tokio::sync::Semaphore::new(1));
14011                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14012                }
14013                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14014
14015                // Releasing the blocker and applying the operation share one save.
14016                resolve_blockers(&queue, &questions);
14017                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14018                apply_task_choice_actions(&queue, &questions, &home);
14019                let after = queue.get(&t.id).unwrap();
14020                assert_eq!(
14021                    after.status,
14022                    if retry {
14023                        TaskStatus::Queued
14024                    } else {
14025                        TaskStatus::Held
14026                    }
14027                );
14028                assert!(after.action_applied(&q.id));
14029                assert_eq!(after.operator_held(), !retry);
14030                assert_eq!(after.answers.len(), 1);
14031
14032                // A later operator decision must not replay this answer.
14033                let mut changed = after;
14034                if retry {
14035                    changed.hold_manual(Some("later hold".into()));
14036                } else {
14037                    changed.release_operator("test", None);
14038                }
14039                let expected = changed.status;
14040                queue.put(&mut changed).unwrap();
14041                apply_task_choice_actions(&queue, &questions, &home);
14042                assert_eq!(queue.get(&t.id).unwrap().status, expected);
14043            }
14044        }
14045    }
14046
14047    #[test]
14048    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14049        let dir = tempfile::tempdir().unwrap();
14050        let queue = Queue::at(dir.path().join("queue"));
14051        let questions = Questions::at(dir.path().join("questions"));
14052        let home = dir.path().join("home");
14053        let mut state = run_state(RunStatus::Blocked);
14054        state.id = "20260101-000000-act1".to_owned();
14055        state.save_under(&home).unwrap();
14056
14057        let mut t = held_task_with(&state.id);
14058        queue.put(&mut t).unwrap();
14059        let mut q = action_question(&state.id, resume_action(&state.id));
14060        questions.put(&mut q).unwrap();
14061
14062        apply_task_choice_actions(&queue, &questions, &home);
14063        let after = queue.get(&t.id).unwrap();
14064        assert_eq!(after.status, TaskStatus::Queued);
14065        assert!(!after.fresh_start);
14066        assert!(after.action_applied(&q.id));
14067        let pin = after.resume_override.clone().unwrap();
14068        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14069        assert!(pin.forced);
14070
14071        // Held again later: the same answer does not release it a second time.
14072        let mut again = queue.get(&t.id).unwrap();
14073        again.hold_machine(Some("later".into()));
14074        queue.put(&mut again).unwrap();
14075        apply_task_choice_actions(&queue, &questions, &home);
14076        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14077    }
14078
14079    #[test]
14080    fn a_delivered_answer_is_still_acted_on_exactly_once() {
14081        let dir = tempfile::tempdir().unwrap();
14082        let queue = Queue::at(dir.path().join("queue"));
14083        let questions = Questions::at(dir.path().join("questions"));
14084        let home = dir.path().join("home");
14085        let mut state = run_state(RunStatus::Blocked);
14086        state.id = "20260101-000000-act2".to_owned();
14087        state.save_under(&home).unwrap();
14088
14089        let mut t = held_task_with(&state.id);
14090        queue.put(&mut t).unwrap();
14091        let mut q = action_question(&state.id, resume_action(&state.id));
14092        q.answer_delivered = true;
14093        questions.put(&mut q).unwrap();
14094
14095        // Delivered, and the agent then died: the task is still held, so the
14096        // chosen action applies.
14097        apply_task_choice_actions(&queue, &questions, &home);
14098        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14099        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14100
14101        // Held again: the same answer does nothing a second time.
14102        let mut again = queue.get(&t.id).unwrap();
14103        again.hold_machine(Some("later".into()));
14104        queue.put(&mut again).unwrap();
14105        apply_task_choice_actions(&queue, &questions, &home);
14106        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14107    }
14108
14109    #[test]
14110    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14111        let dir = tempfile::tempdir().unwrap();
14112        let queue = Queue::at(dir.path().join("queue"));
14113        let questions = Questions::at(dir.path().join("questions"));
14114        let home = dir.path().join("home");
14115        let mut state = run_state(RunStatus::Blocked);
14116        state.id = "20260101-000000-act3".to_owned();
14117        state.save_under(&home).unwrap();
14118        let mut t = held_task_with(&state.id);
14119        queue.put(&mut t).unwrap();
14120        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
14121        questions.put(&mut q).unwrap();
14122
14123        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
14124        apply_task_choice_actions(&queue, &questions, &home);
14125        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14126
14127        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14128        apply_task_choice_actions(&queue, &questions, &home);
14129        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14130    }
14131
14132    #[test]
14133    fn action_standing_tells_the_reasons_apart() {
14134        let mut t = held_task_with("r1");
14135        let q = action_question("r1", ask::ChoiceAction::Requeue);
14136        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14137        let mut plain = q.clone();
14138        plain.actions.clear();
14139        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
14140
14141        // Applied wins over everything, even a running task.
14142        t.mark_action_applied(&q.id);
14143        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
14144
14145        // A newer attempt running: the old question is Stale, not Busy.
14146        let mut t = held_task_with("r1");
14147        t.start("r2".to_owned());
14148        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
14149        // The same question about the latest run just waits.
14150        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
14151        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14152        t.status = TaskStatus::Blocked;
14153        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14154
14155        // A conductor question is keyed by the task, never stale.
14156        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
14157        c.node = crate::conduct::NODE.to_owned();
14158        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
14159        assert!(!ActionStanding::Busy.daemon_owns());
14160    }
14161
14162    #[test]
14163    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
14164        let dir = tempfile::tempdir().unwrap();
14165        let queue = Queue::at(dir.path().join("queue"));
14166        let questions = Questions::at(dir.path().join("questions"));
14167        let home = dir.path().join("home");
14168        let mut state = run_state(RunStatus::Blocked);
14169        state.id = "20260101-000000-act4".to_owned();
14170        state.save_under(&home).unwrap();
14171        let mut t = held_task_with(&state.id);
14172        t.status = TaskStatus::Running;
14173        queue.put(&mut t).unwrap();
14174        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
14175        q.cwd = Some(dir.path().display().to_string());
14176        questions.put(&mut q).unwrap();
14177
14178        // While the task runs the daemon will not act, so the waiter still
14179        // delivers the word to the dead asker's seat ...
14180        let running = queue.get(&t.id).unwrap();
14181        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
14182        assert!(matches!(
14183            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
14184            crate::waiter::Action::Deliver(_)
14185        ));
14186        // ... and the daemon waits while the task runs, then applies once.
14187        apply_task_choice_actions(&queue, &questions, &home);
14188        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14189        let mut back = queue.get(&t.id).unwrap();
14190        back.hold_machine(Some("later".into()));
14191        queue.put(&mut back).unwrap();
14192        apply_task_choice_actions(&queue, &questions, &home);
14193        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
14194        let mut again = queue.get(&t.id).unwrap();
14195        again.hold_machine(Some("again".into()));
14196        queue.put(&mut again).unwrap();
14197        apply_task_choice_actions(&queue, &questions, &home);
14198        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14199    }
14200}